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::isFPImmLegal(const APFloat &Imm, EVT VT, 1235 bool ForCodeSize) const { 1236 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1237 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1238 return false; 1239 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1240 return false; 1241 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1242 return false; 1243 return Imm.isZero(); 1244 } 1245 1246 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1247 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1248 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1249 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1250 } 1251 1252 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1253 CallingConv::ID CC, 1254 EVT VT) const { 1255 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1256 // We might still end up using a GPR but that will be decided based on ABI. 1257 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1258 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1259 return MVT::f32; 1260 1261 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1262 } 1263 1264 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1265 CallingConv::ID CC, 1266 EVT VT) const { 1267 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1268 // We might still end up using a GPR but that will be decided based on ABI. 1269 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1270 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1271 return 1; 1272 1273 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1274 } 1275 1276 // Changes the condition code and swaps operands if necessary, so the SetCC 1277 // operation matches one of the comparisons supported directly by branches 1278 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1279 // with 1/-1. 1280 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1281 ISD::CondCode &CC, SelectionDAG &DAG) { 1282 // Convert X > -1 to X >= 0. 1283 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1284 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1285 CC = ISD::SETGE; 1286 return; 1287 } 1288 // Convert X < 1 to 0 >= X. 1289 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1290 RHS = LHS; 1291 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1292 CC = ISD::SETGE; 1293 return; 1294 } 1295 1296 switch (CC) { 1297 default: 1298 break; 1299 case ISD::SETGT: 1300 case ISD::SETLE: 1301 case ISD::SETUGT: 1302 case ISD::SETULE: 1303 CC = ISD::getSetCCSwappedOperands(CC); 1304 std::swap(LHS, RHS); 1305 break; 1306 } 1307 } 1308 1309 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1310 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1311 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1312 if (VT.getVectorElementType() == MVT::i1) 1313 KnownSize *= 8; 1314 1315 switch (KnownSize) { 1316 default: 1317 llvm_unreachable("Invalid LMUL."); 1318 case 8: 1319 return RISCVII::VLMUL::LMUL_F8; 1320 case 16: 1321 return RISCVII::VLMUL::LMUL_F4; 1322 case 32: 1323 return RISCVII::VLMUL::LMUL_F2; 1324 case 64: 1325 return RISCVII::VLMUL::LMUL_1; 1326 case 128: 1327 return RISCVII::VLMUL::LMUL_2; 1328 case 256: 1329 return RISCVII::VLMUL::LMUL_4; 1330 case 512: 1331 return RISCVII::VLMUL::LMUL_8; 1332 } 1333 } 1334 1335 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1336 switch (LMul) { 1337 default: 1338 llvm_unreachable("Invalid LMUL."); 1339 case RISCVII::VLMUL::LMUL_F8: 1340 case RISCVII::VLMUL::LMUL_F4: 1341 case RISCVII::VLMUL::LMUL_F2: 1342 case RISCVII::VLMUL::LMUL_1: 1343 return RISCV::VRRegClassID; 1344 case RISCVII::VLMUL::LMUL_2: 1345 return RISCV::VRM2RegClassID; 1346 case RISCVII::VLMUL::LMUL_4: 1347 return RISCV::VRM4RegClassID; 1348 case RISCVII::VLMUL::LMUL_8: 1349 return RISCV::VRM8RegClassID; 1350 } 1351 } 1352 1353 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1354 RISCVII::VLMUL LMUL = getLMUL(VT); 1355 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1356 LMUL == RISCVII::VLMUL::LMUL_F4 || 1357 LMUL == RISCVII::VLMUL::LMUL_F2 || 1358 LMUL == RISCVII::VLMUL::LMUL_1) { 1359 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1360 "Unexpected subreg numbering"); 1361 return RISCV::sub_vrm1_0 + Index; 1362 } 1363 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1364 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1365 "Unexpected subreg numbering"); 1366 return RISCV::sub_vrm2_0 + Index; 1367 } 1368 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1369 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1370 "Unexpected subreg numbering"); 1371 return RISCV::sub_vrm4_0 + Index; 1372 } 1373 llvm_unreachable("Invalid vector type."); 1374 } 1375 1376 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1377 if (VT.getVectorElementType() == MVT::i1) 1378 return RISCV::VRRegClassID; 1379 return getRegClassIDForLMUL(getLMUL(VT)); 1380 } 1381 1382 // Attempt to decompose a subvector insert/extract between VecVT and 1383 // SubVecVT via subregister indices. Returns the subregister index that 1384 // can perform the subvector insert/extract with the given element index, as 1385 // well as the index corresponding to any leftover subvectors that must be 1386 // further inserted/extracted within the register class for SubVecVT. 1387 std::pair<unsigned, unsigned> 1388 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1389 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1390 const RISCVRegisterInfo *TRI) { 1391 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1392 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1393 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1394 "Register classes not ordered"); 1395 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1396 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1397 // Try to compose a subregister index that takes us from the incoming 1398 // LMUL>1 register class down to the outgoing one. At each step we half 1399 // the LMUL: 1400 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1401 // Note that this is not guaranteed to find a subregister index, such as 1402 // when we are extracting from one VR type to another. 1403 unsigned SubRegIdx = RISCV::NoSubRegister; 1404 for (const unsigned RCID : 1405 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1406 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1407 VecVT = VecVT.getHalfNumVectorElementsVT(); 1408 bool IsHi = 1409 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1410 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1411 getSubregIndexByMVT(VecVT, IsHi)); 1412 if (IsHi) 1413 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1414 } 1415 return {SubRegIdx, InsertExtractIdx}; 1416 } 1417 1418 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1419 // stores for those types. 1420 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1421 return !Subtarget.useRVVForFixedLengthVectors() || 1422 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1423 } 1424 1425 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1426 if (ScalarTy->isPointerTy()) 1427 return true; 1428 1429 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1430 ScalarTy->isIntegerTy(32)) 1431 return true; 1432 1433 if (ScalarTy->isIntegerTy(64)) 1434 return Subtarget.hasVInstructionsI64(); 1435 1436 if (ScalarTy->isHalfTy()) 1437 return Subtarget.hasVInstructionsF16(); 1438 if (ScalarTy->isFloatTy()) 1439 return Subtarget.hasVInstructionsF32(); 1440 if (ScalarTy->isDoubleTy()) 1441 return Subtarget.hasVInstructionsF64(); 1442 1443 return false; 1444 } 1445 1446 static SDValue getVLOperand(SDValue Op) { 1447 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1448 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1449 "Unexpected opcode"); 1450 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1451 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1452 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1453 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1454 if (!II) 1455 return SDValue(); 1456 return Op.getOperand(II->VLOperand + 1 + HasChain); 1457 } 1458 1459 static bool useRVVForFixedLengthVectorVT(MVT VT, 1460 const RISCVSubtarget &Subtarget) { 1461 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1462 if (!Subtarget.useRVVForFixedLengthVectors()) 1463 return false; 1464 1465 // We only support a set of vector types with a consistent maximum fixed size 1466 // across all supported vector element types to avoid legalization issues. 1467 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1468 // fixed-length vector type we support is 1024 bytes. 1469 if (VT.getFixedSizeInBits() > 1024 * 8) 1470 return false; 1471 1472 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1473 1474 MVT EltVT = VT.getVectorElementType(); 1475 1476 // Don't use RVV for vectors we cannot scalarize if required. 1477 switch (EltVT.SimpleTy) { 1478 // i1 is supported but has different rules. 1479 default: 1480 return false; 1481 case MVT::i1: 1482 // Masks can only use a single register. 1483 if (VT.getVectorNumElements() > MinVLen) 1484 return false; 1485 MinVLen /= 8; 1486 break; 1487 case MVT::i8: 1488 case MVT::i16: 1489 case MVT::i32: 1490 break; 1491 case MVT::i64: 1492 if (!Subtarget.hasVInstructionsI64()) 1493 return false; 1494 break; 1495 case MVT::f16: 1496 if (!Subtarget.hasVInstructionsF16()) 1497 return false; 1498 break; 1499 case MVT::f32: 1500 if (!Subtarget.hasVInstructionsF32()) 1501 return false; 1502 break; 1503 case MVT::f64: 1504 if (!Subtarget.hasVInstructionsF64()) 1505 return false; 1506 break; 1507 } 1508 1509 // Reject elements larger than ELEN. 1510 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1511 return false; 1512 1513 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1514 // Don't use RVV for types that don't fit. 1515 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1516 return false; 1517 1518 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1519 // the base fixed length RVV support in place. 1520 if (!VT.isPow2VectorType()) 1521 return false; 1522 1523 return true; 1524 } 1525 1526 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1527 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1528 } 1529 1530 // Return the largest legal scalable vector type that matches VT's element type. 1531 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1532 const RISCVSubtarget &Subtarget) { 1533 // This may be called before legal types are setup. 1534 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1535 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1536 "Expected legal fixed length vector!"); 1537 1538 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1539 unsigned MaxELen = Subtarget.getELEN(); 1540 1541 MVT EltVT = VT.getVectorElementType(); 1542 switch (EltVT.SimpleTy) { 1543 default: 1544 llvm_unreachable("unexpected element type for RVV container"); 1545 case MVT::i1: 1546 case MVT::i8: 1547 case MVT::i16: 1548 case MVT::i32: 1549 case MVT::i64: 1550 case MVT::f16: 1551 case MVT::f32: 1552 case MVT::f64: { 1553 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1554 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1555 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1556 unsigned NumElts = 1557 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1558 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1559 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1560 return MVT::getScalableVectorVT(EltVT, NumElts); 1561 } 1562 } 1563 } 1564 1565 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1566 const RISCVSubtarget &Subtarget) { 1567 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1568 Subtarget); 1569 } 1570 1571 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1572 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1573 } 1574 1575 // Grow V to consume an entire RVV register. 1576 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1577 const RISCVSubtarget &Subtarget) { 1578 assert(VT.isScalableVector() && 1579 "Expected to convert into a scalable vector!"); 1580 assert(V.getValueType().isFixedLengthVector() && 1581 "Expected a fixed length vector operand!"); 1582 SDLoc DL(V); 1583 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1584 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1585 } 1586 1587 // Shrink V so it's just big enough to maintain a VT's worth of data. 1588 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1589 const RISCVSubtarget &Subtarget) { 1590 assert(VT.isFixedLengthVector() && 1591 "Expected to convert into a fixed length vector!"); 1592 assert(V.getValueType().isScalableVector() && 1593 "Expected a scalable vector operand!"); 1594 SDLoc DL(V); 1595 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1596 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1597 } 1598 1599 /// Return the type of the mask type suitable for masking the provided 1600 /// vector type. This is simply an i1 element type vector of the same 1601 /// (possibly scalable) length. 1602 static MVT getMaskTypeFor(EVT VecVT) { 1603 assert(VecVT.isVector()); 1604 ElementCount EC = VecVT.getVectorElementCount(); 1605 return MVT::getVectorVT(MVT::i1, EC); 1606 } 1607 1608 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1609 /// vector length VL. . 1610 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1611 SelectionDAG &DAG) { 1612 MVT MaskVT = getMaskTypeFor(VecVT); 1613 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1614 } 1615 1616 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1617 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1618 // the vector type that it is contained in. 1619 static std::pair<SDValue, SDValue> 1620 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1621 const RISCVSubtarget &Subtarget) { 1622 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1623 MVT XLenVT = Subtarget.getXLenVT(); 1624 SDValue VL = VecVT.isFixedLengthVector() 1625 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1626 : DAG.getRegister(RISCV::X0, XLenVT); 1627 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1628 return {Mask, VL}; 1629 } 1630 1631 // As above but assuming the given type is a scalable vector type. 1632 static std::pair<SDValue, SDValue> 1633 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1634 const RISCVSubtarget &Subtarget) { 1635 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1636 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1637 } 1638 1639 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1640 // of either is (currently) supported. This can get us into an infinite loop 1641 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1642 // as a ..., etc. 1643 // Until either (or both) of these can reliably lower any node, reporting that 1644 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1645 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1646 // which is not desirable. 1647 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1648 EVT VT, unsigned DefinedValues) const { 1649 return false; 1650 } 1651 1652 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1653 const RISCVSubtarget &Subtarget) { 1654 // RISCV FP-to-int conversions saturate to the destination register size, but 1655 // don't produce 0 for nan. We can use a conversion instruction and fix the 1656 // nan case with a compare and a select. 1657 SDValue Src = Op.getOperand(0); 1658 1659 EVT DstVT = Op.getValueType(); 1660 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1661 1662 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1663 unsigned Opc; 1664 if (SatVT == DstVT) 1665 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1666 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1667 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1668 else 1669 return SDValue(); 1670 // FIXME: Support other SatVTs by clamping before or after the conversion. 1671 1672 SDLoc DL(Op); 1673 SDValue FpToInt = DAG.getNode( 1674 Opc, DL, DstVT, Src, 1675 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1676 1677 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1678 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1679 } 1680 1681 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1682 // and back. Taking care to avoid converting values that are nan or already 1683 // correct. 1684 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1685 // have FRM dependencies modeled yet. 1686 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1687 MVT VT = Op.getSimpleValueType(); 1688 assert(VT.isVector() && "Unexpected type"); 1689 1690 SDLoc DL(Op); 1691 1692 // Freeze the source since we are increasing the number of uses. 1693 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1694 1695 // Truncate to integer and convert back to FP. 1696 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1697 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1698 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1699 1700 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1701 1702 if (Op.getOpcode() == ISD::FCEIL) { 1703 // If the truncated value is the greater than or equal to the original 1704 // value, we've computed the ceil. Otherwise, we went the wrong way and 1705 // need to increase by 1. 1706 // FIXME: This should use a masked operation. Handle here or in isel? 1707 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1708 DAG.getConstantFP(1.0, DL, VT)); 1709 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1710 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1711 } else if (Op.getOpcode() == ISD::FFLOOR) { 1712 // If the truncated value is the less than or equal to the original value, 1713 // we've computed the floor. Otherwise, we went the wrong way and need to 1714 // decrease by 1. 1715 // FIXME: This should use a masked operation. Handle here or in isel? 1716 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1717 DAG.getConstantFP(1.0, DL, VT)); 1718 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1719 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1720 } 1721 1722 // Restore the original sign so that -0.0 is preserved. 1723 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1724 1725 // Determine the largest integer that can be represented exactly. This and 1726 // values larger than it don't have any fractional bits so don't need to 1727 // be converted. 1728 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1729 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1730 APFloat MaxVal = APFloat(FltSem); 1731 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1732 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1733 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1734 1735 // If abs(Src) was larger than MaxVal or nan, keep it. 1736 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1737 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1738 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1739 } 1740 1741 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1742 // This mode isn't supported in vector hardware on RISCV. But as long as we 1743 // aren't compiling with trapping math, we can emulate this with 1744 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1745 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1746 // dependencies modeled yet. 1747 // FIXME: Use masked operations to avoid final merge. 1748 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1749 MVT VT = Op.getSimpleValueType(); 1750 assert(VT.isVector() && "Unexpected type"); 1751 1752 SDLoc DL(Op); 1753 1754 // Freeze the source since we are increasing the number of uses. 1755 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1756 1757 // We do the conversion on the absolute value and fix the sign at the end. 1758 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1759 1760 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1761 bool Ignored; 1762 APFloat Point5Pred = APFloat(0.5f); 1763 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1764 Point5Pred.next(/*nextDown*/ true); 1765 1766 // Add the adjustment. 1767 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1768 DAG.getConstantFP(Point5Pred, DL, VT)); 1769 1770 // Truncate to integer and convert back to fp. 1771 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1772 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1773 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1774 1775 // Restore the original sign. 1776 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1777 1778 // Determine the largest integer that can be represented exactly. This and 1779 // values larger than it don't have any fractional bits so don't need to 1780 // be converted. 1781 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1782 APFloat MaxVal = APFloat(FltSem); 1783 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1784 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1785 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1786 1787 // If abs(Src) was larger than MaxVal or nan, keep it. 1788 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1789 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1790 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1791 } 1792 1793 struct VIDSequence { 1794 int64_t StepNumerator; 1795 unsigned StepDenominator; 1796 int64_t Addend; 1797 }; 1798 1799 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1800 // to the (non-zero) step S and start value X. This can be then lowered as the 1801 // RVV sequence (VID * S) + X, for example. 1802 // The step S is represented as an integer numerator divided by a positive 1803 // denominator. Note that the implementation currently only identifies 1804 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1805 // cannot detect 2/3, for example. 1806 // Note that this method will also match potentially unappealing index 1807 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1808 // determine whether this is worth generating code for. 1809 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1810 unsigned NumElts = Op.getNumOperands(); 1811 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1812 if (!Op.getValueType().isInteger()) 1813 return None; 1814 1815 Optional<unsigned> SeqStepDenom; 1816 Optional<int64_t> SeqStepNum, SeqAddend; 1817 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1818 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1819 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1820 // Assume undef elements match the sequence; we just have to be careful 1821 // when interpolating across them. 1822 if (Op.getOperand(Idx).isUndef()) 1823 continue; 1824 // The BUILD_VECTOR must be all constants. 1825 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1826 return None; 1827 1828 uint64_t Val = Op.getConstantOperandVal(Idx) & 1829 maskTrailingOnes<uint64_t>(EltSizeInBits); 1830 1831 if (PrevElt) { 1832 // Calculate the step since the last non-undef element, and ensure 1833 // it's consistent across the entire sequence. 1834 unsigned IdxDiff = Idx - PrevElt->second; 1835 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1836 1837 // A zero-value value difference means that we're somewhere in the middle 1838 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1839 // step change before evaluating the sequence. 1840 if (ValDiff == 0) 1841 continue; 1842 1843 int64_t Remainder = ValDiff % IdxDiff; 1844 // Normalize the step if it's greater than 1. 1845 if (Remainder != ValDiff) { 1846 // The difference must cleanly divide the element span. 1847 if (Remainder != 0) 1848 return None; 1849 ValDiff /= IdxDiff; 1850 IdxDiff = 1; 1851 } 1852 1853 if (!SeqStepNum) 1854 SeqStepNum = ValDiff; 1855 else if (ValDiff != SeqStepNum) 1856 return None; 1857 1858 if (!SeqStepDenom) 1859 SeqStepDenom = IdxDiff; 1860 else if (IdxDiff != *SeqStepDenom) 1861 return None; 1862 } 1863 1864 // Record this non-undef element for later. 1865 if (!PrevElt || PrevElt->first != Val) 1866 PrevElt = std::make_pair(Val, Idx); 1867 } 1868 1869 // We need to have logged a step for this to count as a legal index sequence. 1870 if (!SeqStepNum || !SeqStepDenom) 1871 return None; 1872 1873 // Loop back through the sequence and validate elements we might have skipped 1874 // while waiting for a valid step. While doing this, log any sequence addend. 1875 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1876 if (Op.getOperand(Idx).isUndef()) 1877 continue; 1878 uint64_t Val = Op.getConstantOperandVal(Idx) & 1879 maskTrailingOnes<uint64_t>(EltSizeInBits); 1880 uint64_t ExpectedVal = 1881 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1882 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1883 if (!SeqAddend) 1884 SeqAddend = Addend; 1885 else if (Addend != SeqAddend) 1886 return None; 1887 } 1888 1889 assert(SeqAddend && "Must have an addend if we have a step"); 1890 1891 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1892 } 1893 1894 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1895 // and lower it as a VRGATHER_VX_VL from the source vector. 1896 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1897 SelectionDAG &DAG, 1898 const RISCVSubtarget &Subtarget) { 1899 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1900 return SDValue(); 1901 SDValue Vec = SplatVal.getOperand(0); 1902 // Only perform this optimization on vectors of the same size for simplicity. 1903 if (Vec.getValueType() != VT) 1904 return SDValue(); 1905 SDValue Idx = SplatVal.getOperand(1); 1906 // The index must be a legal type. 1907 if (Idx.getValueType() != Subtarget.getXLenVT()) 1908 return SDValue(); 1909 1910 MVT ContainerVT = VT; 1911 if (VT.isFixedLengthVector()) { 1912 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1913 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1914 } 1915 1916 SDValue Mask, VL; 1917 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1918 1919 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 1920 Idx, Mask, VL); 1921 1922 if (!VT.isFixedLengthVector()) 1923 return Gather; 1924 1925 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 1926 } 1927 1928 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1929 const RISCVSubtarget &Subtarget) { 1930 MVT VT = Op.getSimpleValueType(); 1931 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1932 1933 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1934 1935 SDLoc DL(Op); 1936 SDValue Mask, VL; 1937 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1938 1939 MVT XLenVT = Subtarget.getXLenVT(); 1940 unsigned NumElts = Op.getNumOperands(); 1941 1942 if (VT.getVectorElementType() == MVT::i1) { 1943 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1944 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1945 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1946 } 1947 1948 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1949 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1950 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1951 } 1952 1953 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1954 // scalar integer chunks whose bit-width depends on the number of mask 1955 // bits and XLEN. 1956 // First, determine the most appropriate scalar integer type to use. This 1957 // is at most XLenVT, but may be shrunk to a smaller vector element type 1958 // according to the size of the final vector - use i8 chunks rather than 1959 // XLenVT if we're producing a v8i1. This results in more consistent 1960 // codegen across RV32 and RV64. 1961 unsigned NumViaIntegerBits = 1962 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1963 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 1964 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1965 // If we have to use more than one INSERT_VECTOR_ELT then this 1966 // optimization is likely to increase code size; avoid peforming it in 1967 // such a case. We can use a load from a constant pool in this case. 1968 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1969 return SDValue(); 1970 // Now we can create our integer vector type. Note that it may be larger 1971 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1972 MVT IntegerViaVecVT = 1973 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1974 divideCeil(NumElts, NumViaIntegerBits)); 1975 1976 uint64_t Bits = 0; 1977 unsigned BitPos = 0, IntegerEltIdx = 0; 1978 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1979 1980 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1981 // Once we accumulate enough bits to fill our scalar type, insert into 1982 // our vector and clear our accumulated data. 1983 if (I != 0 && I % NumViaIntegerBits == 0) { 1984 if (NumViaIntegerBits <= 32) 1985 Bits = SignExtend64(Bits, 32); 1986 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1987 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1988 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1989 Bits = 0; 1990 BitPos = 0; 1991 IntegerEltIdx++; 1992 } 1993 SDValue V = Op.getOperand(I); 1994 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1995 Bits |= ((uint64_t)BitValue << BitPos); 1996 } 1997 1998 // Insert the (remaining) scalar value into position in our integer 1999 // vector type. 2000 if (NumViaIntegerBits <= 32) 2001 Bits = SignExtend64(Bits, 32); 2002 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2003 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2004 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2005 2006 if (NumElts < NumViaIntegerBits) { 2007 // If we're producing a smaller vector than our minimum legal integer 2008 // type, bitcast to the equivalent (known-legal) mask type, and extract 2009 // our final mask. 2010 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2011 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2012 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2013 DAG.getConstant(0, DL, XLenVT)); 2014 } else { 2015 // Else we must have produced an integer type with the same size as the 2016 // mask type; bitcast for the final result. 2017 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2018 Vec = DAG.getBitcast(VT, Vec); 2019 } 2020 2021 return Vec; 2022 } 2023 2024 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2025 // vector type, we have a legal equivalently-sized i8 type, so we can use 2026 // that. 2027 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2028 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2029 2030 SDValue WideVec; 2031 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2032 // For a splat, perform a scalar truncate before creating the wider 2033 // vector. 2034 assert(Splat.getValueType() == XLenVT && 2035 "Unexpected type for i1 splat value"); 2036 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2037 DAG.getConstant(1, DL, XLenVT)); 2038 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2039 } else { 2040 SmallVector<SDValue, 8> Ops(Op->op_values()); 2041 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2042 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2043 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2044 } 2045 2046 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2047 } 2048 2049 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2050 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2051 return Gather; 2052 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2053 : RISCVISD::VMV_V_X_VL; 2054 Splat = 2055 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2056 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2057 } 2058 2059 // Try and match index sequences, which we can lower to the vid instruction 2060 // with optional modifications. An all-undef vector is matched by 2061 // getSplatValue, above. 2062 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2063 int64_t StepNumerator = SimpleVID->StepNumerator; 2064 unsigned StepDenominator = SimpleVID->StepDenominator; 2065 int64_t Addend = SimpleVID->Addend; 2066 2067 assert(StepNumerator != 0 && "Invalid step"); 2068 bool Negate = false; 2069 int64_t SplatStepVal = StepNumerator; 2070 unsigned StepOpcode = ISD::MUL; 2071 if (StepNumerator != 1) { 2072 if (isPowerOf2_64(std::abs(StepNumerator))) { 2073 Negate = StepNumerator < 0; 2074 StepOpcode = ISD::SHL; 2075 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2076 } 2077 } 2078 2079 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2080 // threshold since it's the immediate value many RVV instructions accept. 2081 // There is no vmul.vi instruction so ensure multiply constant can fit in 2082 // a single addi instruction. 2083 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2084 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2085 isPowerOf2_32(StepDenominator) && 2086 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2087 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2088 // Convert right out of the scalable type so we can use standard ISD 2089 // nodes for the rest of the computation. If we used scalable types with 2090 // these, we'd lose the fixed-length vector info and generate worse 2091 // vsetvli code. 2092 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2093 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2094 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2095 SDValue SplatStep = DAG.getSplatBuildVector( 2096 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2097 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2098 } 2099 if (StepDenominator != 1) { 2100 SDValue SplatStep = DAG.getSplatBuildVector( 2101 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2102 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2103 } 2104 if (Addend != 0 || Negate) { 2105 SDValue SplatAddend = DAG.getSplatBuildVector( 2106 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2107 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2108 } 2109 return VID; 2110 } 2111 } 2112 2113 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2114 // when re-interpreted as a vector with a larger element type. For example, 2115 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2116 // could be instead splat as 2117 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2118 // TODO: This optimization could also work on non-constant splats, but it 2119 // would require bit-manipulation instructions to construct the splat value. 2120 SmallVector<SDValue> Sequence; 2121 unsigned EltBitSize = VT.getScalarSizeInBits(); 2122 const auto *BV = cast<BuildVectorSDNode>(Op); 2123 if (VT.isInteger() && EltBitSize < 64 && 2124 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2125 BV->getRepeatedSequence(Sequence) && 2126 (Sequence.size() * EltBitSize) <= 64) { 2127 unsigned SeqLen = Sequence.size(); 2128 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2129 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2130 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2131 ViaIntVT == MVT::i64) && 2132 "Unexpected sequence type"); 2133 2134 unsigned EltIdx = 0; 2135 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2136 uint64_t SplatValue = 0; 2137 // Construct the amalgamated value which can be splatted as this larger 2138 // vector type. 2139 for (const auto &SeqV : Sequence) { 2140 if (!SeqV.isUndef()) 2141 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2142 << (EltIdx * EltBitSize)); 2143 EltIdx++; 2144 } 2145 2146 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2147 // achieve better constant materializion. 2148 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2149 SplatValue = SignExtend64(SplatValue, 32); 2150 2151 // Since we can't introduce illegal i64 types at this stage, we can only 2152 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2153 // way we can use RVV instructions to splat. 2154 assert((ViaIntVT.bitsLE(XLenVT) || 2155 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2156 "Unexpected bitcast sequence"); 2157 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2158 SDValue ViaVL = 2159 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2160 MVT ViaContainerVT = 2161 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2162 SDValue Splat = 2163 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2164 DAG.getUNDEF(ViaContainerVT), 2165 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2166 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2167 return DAG.getBitcast(VT, Splat); 2168 } 2169 } 2170 2171 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2172 // which constitute a large proportion of the elements. In such cases we can 2173 // splat a vector with the dominant element and make up the shortfall with 2174 // INSERT_VECTOR_ELTs. 2175 // Note that this includes vectors of 2 elements by association. The 2176 // upper-most element is the "dominant" one, allowing us to use a splat to 2177 // "insert" the upper element, and an insert of the lower element at position 2178 // 0, which improves codegen. 2179 SDValue DominantValue; 2180 unsigned MostCommonCount = 0; 2181 DenseMap<SDValue, unsigned> ValueCounts; 2182 unsigned NumUndefElts = 2183 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2184 2185 // Track the number of scalar loads we know we'd be inserting, estimated as 2186 // any non-zero floating-point constant. Other kinds of element are either 2187 // already in registers or are materialized on demand. The threshold at which 2188 // a vector load is more desirable than several scalar materializion and 2189 // vector-insertion instructions is not known. 2190 unsigned NumScalarLoads = 0; 2191 2192 for (SDValue V : Op->op_values()) { 2193 if (V.isUndef()) 2194 continue; 2195 2196 ValueCounts.insert(std::make_pair(V, 0)); 2197 unsigned &Count = ValueCounts[V]; 2198 2199 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2200 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2201 2202 // Is this value dominant? In case of a tie, prefer the highest element as 2203 // it's cheaper to insert near the beginning of a vector than it is at the 2204 // end. 2205 if (++Count >= MostCommonCount) { 2206 DominantValue = V; 2207 MostCommonCount = Count; 2208 } 2209 } 2210 2211 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2212 unsigned NumDefElts = NumElts - NumUndefElts; 2213 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2214 2215 // Don't perform this optimization when optimizing for size, since 2216 // materializing elements and inserting them tends to cause code bloat. 2217 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2218 ((MostCommonCount > DominantValueCountThreshold) || 2219 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2220 // Start by splatting the most common element. 2221 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2222 2223 DenseSet<SDValue> Processed{DominantValue}; 2224 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2225 for (const auto &OpIdx : enumerate(Op->ops())) { 2226 const SDValue &V = OpIdx.value(); 2227 if (V.isUndef() || !Processed.insert(V).second) 2228 continue; 2229 if (ValueCounts[V] == 1) { 2230 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2231 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2232 } else { 2233 // Blend in all instances of this value using a VSELECT, using a 2234 // mask where each bit signals whether that element is the one 2235 // we're after. 2236 SmallVector<SDValue> Ops; 2237 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2238 return DAG.getConstant(V == V1, DL, XLenVT); 2239 }); 2240 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2241 DAG.getBuildVector(SelMaskTy, DL, Ops), 2242 DAG.getSplatBuildVector(VT, DL, V), Vec); 2243 } 2244 } 2245 2246 return Vec; 2247 } 2248 2249 return SDValue(); 2250 } 2251 2252 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2253 SDValue Lo, SDValue Hi, SDValue VL, 2254 SelectionDAG &DAG) { 2255 if (!Passthru) 2256 Passthru = DAG.getUNDEF(VT); 2257 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2258 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2259 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2260 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2261 // node in order to try and match RVV vector/scalar instructions. 2262 if ((LoC >> 31) == HiC) 2263 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2264 2265 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2266 // vmv.v.x whose EEW = 32 to lower it. 2267 auto *Const = dyn_cast<ConstantSDNode>(VL); 2268 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2269 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2270 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2271 // access the subtarget here now. 2272 auto InterVec = DAG.getNode( 2273 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2274 DAG.getRegister(RISCV::X0, MVT::i32)); 2275 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2276 } 2277 } 2278 2279 // Fall back to a stack store and stride x0 vector load. 2280 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2281 Hi, VL); 2282 } 2283 2284 // Called by type legalization to handle splat of i64 on RV32. 2285 // FIXME: We can optimize this when the type has sign or zero bits in one 2286 // of the halves. 2287 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2288 SDValue Scalar, SDValue VL, 2289 SelectionDAG &DAG) { 2290 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2291 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2292 DAG.getConstant(0, DL, MVT::i32)); 2293 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2294 DAG.getConstant(1, DL, MVT::i32)); 2295 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2296 } 2297 2298 // This function lowers a splat of a scalar operand Splat with the vector 2299 // length VL. It ensures the final sequence is type legal, which is useful when 2300 // lowering a splat after type legalization. 2301 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2302 MVT VT, SDLoc DL, SelectionDAG &DAG, 2303 const RISCVSubtarget &Subtarget) { 2304 bool HasPassthru = Passthru && !Passthru.isUndef(); 2305 if (!HasPassthru && !Passthru) 2306 Passthru = DAG.getUNDEF(VT); 2307 if (VT.isFloatingPoint()) { 2308 // If VL is 1, we could use vfmv.s.f. 2309 if (isOneConstant(VL)) 2310 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2311 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2312 } 2313 2314 MVT XLenVT = Subtarget.getXLenVT(); 2315 2316 // Simplest case is that the operand needs to be promoted to XLenVT. 2317 if (Scalar.getValueType().bitsLE(XLenVT)) { 2318 // If the operand is a constant, sign extend to increase our chances 2319 // of being able to use a .vi instruction. ANY_EXTEND would become a 2320 // a zero extend and the simm5 check in isel would fail. 2321 // FIXME: Should we ignore the upper bits in isel instead? 2322 unsigned ExtOpc = 2323 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2324 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2325 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2326 // If VL is 1 and the scalar value won't benefit from immediate, we could 2327 // use vmv.s.x. 2328 if (isOneConstant(VL) && 2329 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2330 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2331 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2332 } 2333 2334 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2335 "Unexpected scalar for splat lowering!"); 2336 2337 if (isOneConstant(VL) && isNullConstant(Scalar)) 2338 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2339 DAG.getConstant(0, DL, XLenVT), VL); 2340 2341 // Otherwise use the more complicated splatting algorithm. 2342 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2343 } 2344 2345 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2346 const RISCVSubtarget &Subtarget) { 2347 // We need to be able to widen elements to the next larger integer type. 2348 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2349 return false; 2350 2351 int Size = Mask.size(); 2352 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2353 2354 int Srcs[] = {-1, -1}; 2355 for (int i = 0; i != Size; ++i) { 2356 // Ignore undef elements. 2357 if (Mask[i] < 0) 2358 continue; 2359 2360 // Is this an even or odd element. 2361 int Pol = i % 2; 2362 2363 // Ensure we consistently use the same source for this element polarity. 2364 int Src = Mask[i] / Size; 2365 if (Srcs[Pol] < 0) 2366 Srcs[Pol] = Src; 2367 if (Srcs[Pol] != Src) 2368 return false; 2369 2370 // Make sure the element within the source is appropriate for this element 2371 // in the destination. 2372 int Elt = Mask[i] % Size; 2373 if (Elt != i / 2) 2374 return false; 2375 } 2376 2377 // We need to find a source for each polarity and they can't be the same. 2378 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2379 return false; 2380 2381 // Swap the sources if the second source was in the even polarity. 2382 SwapSources = Srcs[0] > Srcs[1]; 2383 2384 return true; 2385 } 2386 2387 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2388 /// and then extract the original number of elements from the rotated result. 2389 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2390 /// returned rotation amount is for a rotate right, where elements move from 2391 /// higher elements to lower elements. \p LoSrc indicates the first source 2392 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2393 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2394 /// 0 or 1 if a rotation is found. 2395 /// 2396 /// NOTE: We talk about rotate to the right which matches how bit shift and 2397 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2398 /// and the table below write vectors with the lowest elements on the left. 2399 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2400 int Size = Mask.size(); 2401 2402 // We need to detect various ways of spelling a rotation: 2403 // [11, 12, 13, 14, 15, 0, 1, 2] 2404 // [-1, 12, 13, 14, -1, -1, 1, -1] 2405 // [-1, -1, -1, -1, -1, -1, 1, 2] 2406 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2407 // [-1, 4, 5, 6, -1, -1, 9, -1] 2408 // [-1, 4, 5, 6, -1, -1, -1, -1] 2409 int Rotation = 0; 2410 LoSrc = -1; 2411 HiSrc = -1; 2412 for (int i = 0; i != Size; ++i) { 2413 int M = Mask[i]; 2414 if (M < 0) 2415 continue; 2416 2417 // Determine where a rotate vector would have started. 2418 int StartIdx = i - (M % Size); 2419 // The identity rotation isn't interesting, stop. 2420 if (StartIdx == 0) 2421 return -1; 2422 2423 // If we found the tail of a vector the rotation must be the missing 2424 // front. If we found the head of a vector, it must be how much of the 2425 // head. 2426 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2427 2428 if (Rotation == 0) 2429 Rotation = CandidateRotation; 2430 else if (Rotation != CandidateRotation) 2431 // The rotations don't match, so we can't match this mask. 2432 return -1; 2433 2434 // Compute which value this mask is pointing at. 2435 int MaskSrc = M < Size ? 0 : 1; 2436 2437 // Compute which of the two target values this index should be assigned to. 2438 // This reflects whether the high elements are remaining or the low elemnts 2439 // are remaining. 2440 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2441 2442 // Either set up this value if we've not encountered it before, or check 2443 // that it remains consistent. 2444 if (TargetSrc < 0) 2445 TargetSrc = MaskSrc; 2446 else if (TargetSrc != MaskSrc) 2447 // This may be a rotation, but it pulls from the inputs in some 2448 // unsupported interleaving. 2449 return -1; 2450 } 2451 2452 // Check that we successfully analyzed the mask, and normalize the results. 2453 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2454 assert((LoSrc >= 0 || HiSrc >= 0) && 2455 "Failed to find a rotated input vector!"); 2456 2457 return Rotation; 2458 } 2459 2460 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2461 const RISCVSubtarget &Subtarget) { 2462 SDValue V1 = Op.getOperand(0); 2463 SDValue V2 = Op.getOperand(1); 2464 SDLoc DL(Op); 2465 MVT XLenVT = Subtarget.getXLenVT(); 2466 MVT VT = Op.getSimpleValueType(); 2467 unsigned NumElts = VT.getVectorNumElements(); 2468 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2469 2470 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2471 2472 SDValue TrueMask, VL; 2473 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2474 2475 if (SVN->isSplat()) { 2476 const int Lane = SVN->getSplatIndex(); 2477 if (Lane >= 0) { 2478 MVT SVT = VT.getVectorElementType(); 2479 2480 // Turn splatted vector load into a strided load with an X0 stride. 2481 SDValue V = V1; 2482 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2483 // with undef. 2484 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2485 int Offset = Lane; 2486 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2487 int OpElements = 2488 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2489 V = V.getOperand(Offset / OpElements); 2490 Offset %= OpElements; 2491 } 2492 2493 // We need to ensure the load isn't atomic or volatile. 2494 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2495 auto *Ld = cast<LoadSDNode>(V); 2496 Offset *= SVT.getStoreSize(); 2497 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2498 TypeSize::Fixed(Offset), DL); 2499 2500 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2501 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2502 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2503 SDValue IntID = 2504 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2505 SDValue Ops[] = {Ld->getChain(), 2506 IntID, 2507 DAG.getUNDEF(ContainerVT), 2508 NewAddr, 2509 DAG.getRegister(RISCV::X0, XLenVT), 2510 VL}; 2511 SDValue NewLoad = DAG.getMemIntrinsicNode( 2512 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2513 DAG.getMachineFunction().getMachineMemOperand( 2514 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2515 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2516 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2517 } 2518 2519 // Otherwise use a scalar load and splat. This will give the best 2520 // opportunity to fold a splat into the operation. ISel can turn it into 2521 // the x0 strided load if we aren't able to fold away the select. 2522 if (SVT.isFloatingPoint()) 2523 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2524 Ld->getPointerInfo().getWithOffset(Offset), 2525 Ld->getOriginalAlign(), 2526 Ld->getMemOperand()->getFlags()); 2527 else 2528 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2529 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2530 Ld->getOriginalAlign(), 2531 Ld->getMemOperand()->getFlags()); 2532 DAG.makeEquivalentMemoryOrdering(Ld, V); 2533 2534 unsigned Opc = 2535 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2536 SDValue Splat = 2537 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2538 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2539 } 2540 2541 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2542 assert(Lane < (int)NumElts && "Unexpected lane!"); 2543 SDValue Gather = 2544 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2545 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2546 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2547 } 2548 } 2549 2550 ArrayRef<int> Mask = SVN->getMask(); 2551 2552 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2553 // be undef which can be handled with a single SLIDEDOWN/UP. 2554 int LoSrc, HiSrc; 2555 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2556 if (Rotation > 0) { 2557 SDValue LoV, HiV; 2558 if (LoSrc >= 0) { 2559 LoV = LoSrc == 0 ? V1 : V2; 2560 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2561 } 2562 if (HiSrc >= 0) { 2563 HiV = HiSrc == 0 ? V1 : V2; 2564 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2565 } 2566 2567 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2568 // to slide LoV up by (NumElts - Rotation). 2569 unsigned InvRotate = NumElts - Rotation; 2570 2571 SDValue Res = DAG.getUNDEF(ContainerVT); 2572 if (HiV) { 2573 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2574 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2575 // causes multiple vsetvlis in some test cases such as lowering 2576 // reduce.mul 2577 SDValue DownVL = VL; 2578 if (LoV) 2579 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2580 Res = 2581 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2582 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2583 } 2584 if (LoV) 2585 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2586 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2587 2588 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2589 } 2590 2591 // Detect an interleave shuffle and lower to 2592 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2593 bool SwapSources; 2594 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2595 // Swap sources if needed. 2596 if (SwapSources) 2597 std::swap(V1, V2); 2598 2599 // Extract the lower half of the vectors. 2600 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2601 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2602 DAG.getConstant(0, DL, XLenVT)); 2603 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2604 DAG.getConstant(0, DL, XLenVT)); 2605 2606 // Double the element width and halve the number of elements in an int type. 2607 unsigned EltBits = VT.getScalarSizeInBits(); 2608 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2609 MVT WideIntVT = 2610 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2611 // Convert this to a scalable vector. We need to base this on the 2612 // destination size to ensure there's always a type with a smaller LMUL. 2613 MVT WideIntContainerVT = 2614 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2615 2616 // Convert sources to scalable vectors with the same element count as the 2617 // larger type. 2618 MVT HalfContainerVT = MVT::getVectorVT( 2619 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2620 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2621 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2622 2623 // Cast sources to integer. 2624 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2625 MVT IntHalfVT = 2626 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2627 V1 = DAG.getBitcast(IntHalfVT, V1); 2628 V2 = DAG.getBitcast(IntHalfVT, V2); 2629 2630 // Freeze V2 since we use it twice and we need to be sure that the add and 2631 // multiply see the same value. 2632 V2 = DAG.getFreeze(V2); 2633 2634 // Recreate TrueMask using the widened type's element count. 2635 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2636 2637 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2638 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2639 V2, TrueMask, VL); 2640 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2641 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2642 DAG.getUNDEF(IntHalfVT), 2643 DAG.getAllOnesConstant(DL, XLenVT)); 2644 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2645 V2, Multiplier, TrueMask, VL); 2646 // Add the new copies to our previous addition giving us 2^eltbits copies of 2647 // V2. This is equivalent to shifting V2 left by eltbits. This should 2648 // combine with the vwmulu.vv above to form vwmaccu.vv. 2649 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2650 TrueMask, VL); 2651 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2652 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2653 // vector VT. 2654 ContainerVT = 2655 MVT::getVectorVT(VT.getVectorElementType(), 2656 WideIntContainerVT.getVectorElementCount() * 2); 2657 Add = DAG.getBitcast(ContainerVT, Add); 2658 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2659 } 2660 2661 // Detect shuffles which can be re-expressed as vector selects; these are 2662 // shuffles in which each element in the destination is taken from an element 2663 // at the corresponding index in either source vectors. 2664 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2665 int MaskIndex = MaskIdx.value(); 2666 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2667 }); 2668 2669 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2670 2671 SmallVector<SDValue> MaskVals; 2672 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2673 // merged with a second vrgather. 2674 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2675 2676 // By default we preserve the original operand order, and use a mask to 2677 // select LHS as true and RHS as false. However, since RVV vector selects may 2678 // feature splats but only on the LHS, we may choose to invert our mask and 2679 // instead select between RHS and LHS. 2680 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2681 bool InvertMask = IsSelect == SwapOps; 2682 2683 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2684 // half. 2685 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2686 2687 // Now construct the mask that will be used by the vselect or blended 2688 // vrgather operation. For vrgathers, construct the appropriate indices into 2689 // each vector. 2690 for (int MaskIndex : Mask) { 2691 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2692 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2693 if (!IsSelect) { 2694 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2695 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2696 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2697 : DAG.getUNDEF(XLenVT)); 2698 GatherIndicesRHS.push_back( 2699 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2700 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2701 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2702 ++LHSIndexCounts[MaskIndex]; 2703 if (!IsLHSOrUndefIndex) 2704 ++RHSIndexCounts[MaskIndex - NumElts]; 2705 } 2706 } 2707 2708 if (SwapOps) { 2709 std::swap(V1, V2); 2710 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2711 } 2712 2713 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2714 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2715 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2716 2717 if (IsSelect) 2718 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2719 2720 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2721 // On such a large vector we're unable to use i8 as the index type. 2722 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2723 // may involve vector splitting if we're already at LMUL=8, or our 2724 // user-supplied maximum fixed-length LMUL. 2725 return SDValue(); 2726 } 2727 2728 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2729 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2730 MVT IndexVT = VT.changeTypeToInteger(); 2731 // Since we can't introduce illegal index types at this stage, use i16 and 2732 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2733 // than XLenVT. 2734 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2735 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2736 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2737 } 2738 2739 MVT IndexContainerVT = 2740 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2741 2742 SDValue Gather; 2743 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2744 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2745 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2746 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2747 Subtarget); 2748 } else { 2749 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2750 // If only one index is used, we can use a "splat" vrgather. 2751 // TODO: We can splat the most-common index and fix-up any stragglers, if 2752 // that's beneficial. 2753 if (LHSIndexCounts.size() == 1) { 2754 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2755 Gather = 2756 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2757 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2758 } else { 2759 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2760 LHSIndices = 2761 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2762 2763 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2764 TrueMask, VL); 2765 } 2766 } 2767 2768 // If a second vector operand is used by this shuffle, blend it in with an 2769 // additional vrgather. 2770 if (!V2.isUndef()) { 2771 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2772 // If only one index is used, we can use a "splat" vrgather. 2773 // TODO: We can splat the most-common index and fix-up any stragglers, if 2774 // that's beneficial. 2775 if (RHSIndexCounts.size() == 1) { 2776 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2777 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2778 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2779 } else { 2780 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2781 RHSIndices = 2782 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2783 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2784 VL); 2785 } 2786 2787 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2788 SelectMask = 2789 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2790 2791 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2792 Gather, VL); 2793 } 2794 2795 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2796 } 2797 2798 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2799 // Support splats for any type. These should type legalize well. 2800 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2801 return true; 2802 2803 // Only support legal VTs for other shuffles for now. 2804 if (!isTypeLegal(VT)) 2805 return false; 2806 2807 MVT SVT = VT.getSimpleVT(); 2808 2809 bool SwapSources; 2810 int LoSrc, HiSrc; 2811 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2812 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2813 } 2814 2815 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2816 // the exponent. 2817 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2818 MVT VT = Op.getSimpleValueType(); 2819 unsigned EltSize = VT.getScalarSizeInBits(); 2820 SDValue Src = Op.getOperand(0); 2821 SDLoc DL(Op); 2822 2823 // We need a FP type that can represent the value. 2824 // TODO: Use f16 for i8 when possible? 2825 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2826 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2827 2828 // Legal types should have been checked in the RISCVTargetLowering 2829 // constructor. 2830 // TODO: Splitting may make sense in some cases. 2831 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2832 "Expected legal float type!"); 2833 2834 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2835 // The trailing zero count is equal to log2 of this single bit value. 2836 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2837 SDValue Neg = 2838 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2839 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2840 } 2841 2842 // We have a legal FP type, convert to it. 2843 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2844 // Bitcast to integer and shift the exponent to the LSB. 2845 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2846 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2847 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2848 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2849 DAG.getConstant(ShiftAmt, DL, IntVT)); 2850 // Truncate back to original type to allow vnsrl. 2851 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2852 // The exponent contains log2 of the value in biased form. 2853 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2854 2855 // For trailing zeros, we just need to subtract the bias. 2856 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2857 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2858 DAG.getConstant(ExponentBias, DL, VT)); 2859 2860 // For leading zeros, we need to remove the bias and convert from log2 to 2861 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2862 unsigned Adjust = ExponentBias + (EltSize - 1); 2863 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2864 } 2865 2866 // While RVV has alignment restrictions, we should always be able to load as a 2867 // legal equivalently-sized byte-typed vector instead. This method is 2868 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2869 // the load is already correctly-aligned, it returns SDValue(). 2870 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2871 SelectionDAG &DAG) const { 2872 auto *Load = cast<LoadSDNode>(Op); 2873 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2874 2875 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2876 Load->getMemoryVT(), 2877 *Load->getMemOperand())) 2878 return SDValue(); 2879 2880 SDLoc DL(Op); 2881 MVT VT = Op.getSimpleValueType(); 2882 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2883 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2884 "Unexpected unaligned RVV load type"); 2885 MVT NewVT = 2886 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2887 assert(NewVT.isValid() && 2888 "Expecting equally-sized RVV vector types to be legal"); 2889 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2890 Load->getPointerInfo(), Load->getOriginalAlign(), 2891 Load->getMemOperand()->getFlags()); 2892 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2893 } 2894 2895 // While RVV has alignment restrictions, we should always be able to store as a 2896 // legal equivalently-sized byte-typed vector instead. This method is 2897 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2898 // returns SDValue() if the store is already correctly aligned. 2899 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2900 SelectionDAG &DAG) const { 2901 auto *Store = cast<StoreSDNode>(Op); 2902 assert(Store && Store->getValue().getValueType().isVector() && 2903 "Expected vector store"); 2904 2905 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2906 Store->getMemoryVT(), 2907 *Store->getMemOperand())) 2908 return SDValue(); 2909 2910 SDLoc DL(Op); 2911 SDValue StoredVal = Store->getValue(); 2912 MVT VT = StoredVal.getSimpleValueType(); 2913 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2914 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2915 "Unexpected unaligned RVV store type"); 2916 MVT NewVT = 2917 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2918 assert(NewVT.isValid() && 2919 "Expecting equally-sized RVV vector types to be legal"); 2920 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2921 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2922 Store->getPointerInfo(), Store->getOriginalAlign(), 2923 Store->getMemOperand()->getFlags()); 2924 } 2925 2926 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2927 SelectionDAG &DAG) const { 2928 switch (Op.getOpcode()) { 2929 default: 2930 report_fatal_error("unimplemented operand"); 2931 case ISD::GlobalAddress: 2932 return lowerGlobalAddress(Op, DAG); 2933 case ISD::BlockAddress: 2934 return lowerBlockAddress(Op, DAG); 2935 case ISD::ConstantPool: 2936 return lowerConstantPool(Op, DAG); 2937 case ISD::JumpTable: 2938 return lowerJumpTable(Op, DAG); 2939 case ISD::GlobalTLSAddress: 2940 return lowerGlobalTLSAddress(Op, DAG); 2941 case ISD::SELECT: 2942 return lowerSELECT(Op, DAG); 2943 case ISD::BRCOND: 2944 return lowerBRCOND(Op, DAG); 2945 case ISD::VASTART: 2946 return lowerVASTART(Op, DAG); 2947 case ISD::FRAMEADDR: 2948 return lowerFRAMEADDR(Op, DAG); 2949 case ISD::RETURNADDR: 2950 return lowerRETURNADDR(Op, DAG); 2951 case ISD::SHL_PARTS: 2952 return lowerShiftLeftParts(Op, DAG); 2953 case ISD::SRA_PARTS: 2954 return lowerShiftRightParts(Op, DAG, true); 2955 case ISD::SRL_PARTS: 2956 return lowerShiftRightParts(Op, DAG, false); 2957 case ISD::BITCAST: { 2958 SDLoc DL(Op); 2959 EVT VT = Op.getValueType(); 2960 SDValue Op0 = Op.getOperand(0); 2961 EVT Op0VT = Op0.getValueType(); 2962 MVT XLenVT = Subtarget.getXLenVT(); 2963 if (VT.isFixedLengthVector()) { 2964 // We can handle fixed length vector bitcasts with a simple replacement 2965 // in isel. 2966 if (Op0VT.isFixedLengthVector()) 2967 return Op; 2968 // When bitcasting from scalar to fixed-length vector, insert the scalar 2969 // into a one-element vector of the result type, and perform a vector 2970 // bitcast. 2971 if (!Op0VT.isVector()) { 2972 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2973 if (!isTypeLegal(BVT)) 2974 return SDValue(); 2975 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2976 DAG.getUNDEF(BVT), Op0, 2977 DAG.getConstant(0, DL, XLenVT))); 2978 } 2979 return SDValue(); 2980 } 2981 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2982 // thus: bitcast the vector to a one-element vector type whose element type 2983 // is the same as the result type, and extract the first element. 2984 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2985 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2986 if (!isTypeLegal(BVT)) 2987 return SDValue(); 2988 SDValue BVec = DAG.getBitcast(BVT, Op0); 2989 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2990 DAG.getConstant(0, DL, XLenVT)); 2991 } 2992 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2993 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2994 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2995 return FPConv; 2996 } 2997 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2998 Subtarget.hasStdExtF()) { 2999 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3000 SDValue FPConv = 3001 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3002 return FPConv; 3003 } 3004 return SDValue(); 3005 } 3006 case ISD::INTRINSIC_WO_CHAIN: 3007 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3008 case ISD::INTRINSIC_W_CHAIN: 3009 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3010 case ISD::INTRINSIC_VOID: 3011 return LowerINTRINSIC_VOID(Op, DAG); 3012 case ISD::BSWAP: 3013 case ISD::BITREVERSE: { 3014 MVT VT = Op.getSimpleValueType(); 3015 SDLoc DL(Op); 3016 if (Subtarget.hasStdExtZbp()) { 3017 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3018 // Start with the maximum immediate value which is the bitwidth - 1. 3019 unsigned Imm = VT.getSizeInBits() - 1; 3020 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3021 if (Op.getOpcode() == ISD::BSWAP) 3022 Imm &= ~0x7U; 3023 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3024 DAG.getConstant(Imm, DL, VT)); 3025 } 3026 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3027 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3028 // Expand bitreverse to a bswap(rev8) followed by brev8. 3029 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3030 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3031 // as brev8 by an isel pattern. 3032 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3033 DAG.getConstant(7, DL, VT)); 3034 } 3035 case ISD::FSHL: 3036 case ISD::FSHR: { 3037 MVT VT = Op.getSimpleValueType(); 3038 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3039 SDLoc DL(Op); 3040 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3041 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3042 // accidentally setting the extra bit. 3043 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3044 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3045 DAG.getConstant(ShAmtWidth, DL, VT)); 3046 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3047 // instruction use different orders. fshl will return its first operand for 3048 // shift of zero, fshr will return its second operand. fsl and fsr both 3049 // return rs1 so the ISD nodes need to have different operand orders. 3050 // Shift amount is in rs2. 3051 SDValue Op0 = Op.getOperand(0); 3052 SDValue Op1 = Op.getOperand(1); 3053 unsigned Opc = RISCVISD::FSL; 3054 if (Op.getOpcode() == ISD::FSHR) { 3055 std::swap(Op0, Op1); 3056 Opc = RISCVISD::FSR; 3057 } 3058 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3059 } 3060 case ISD::TRUNCATE: 3061 // Only custom-lower vector truncates 3062 if (!Op.getSimpleValueType().isVector()) 3063 return Op; 3064 return lowerVectorTruncLike(Op, DAG); 3065 case ISD::ANY_EXTEND: 3066 case ISD::ZERO_EXTEND: 3067 if (Op.getOperand(0).getValueType().isVector() && 3068 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3069 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3070 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3071 case ISD::SIGN_EXTEND: 3072 if (Op.getOperand(0).getValueType().isVector() && 3073 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3074 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3075 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3076 case ISD::SPLAT_VECTOR_PARTS: 3077 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3078 case ISD::INSERT_VECTOR_ELT: 3079 return lowerINSERT_VECTOR_ELT(Op, DAG); 3080 case ISD::EXTRACT_VECTOR_ELT: 3081 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3082 case ISD::VSCALE: { 3083 MVT VT = Op.getSimpleValueType(); 3084 SDLoc DL(Op); 3085 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3086 // We define our scalable vector types for lmul=1 to use a 64 bit known 3087 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3088 // vscale as VLENB / 8. 3089 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3090 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3091 report_fatal_error("Support for VLEN==32 is incomplete."); 3092 // We assume VLENB is a multiple of 8. We manually choose the best shift 3093 // here because SimplifyDemandedBits isn't always able to simplify it. 3094 uint64_t Val = Op.getConstantOperandVal(0); 3095 if (isPowerOf2_64(Val)) { 3096 uint64_t Log2 = Log2_64(Val); 3097 if (Log2 < 3) 3098 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3099 DAG.getConstant(3 - Log2, DL, VT)); 3100 if (Log2 > 3) 3101 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3102 DAG.getConstant(Log2 - 3, DL, VT)); 3103 return VLENB; 3104 } 3105 // If the multiplier is a multiple of 8, scale it down to avoid needing 3106 // to shift the VLENB value. 3107 if ((Val % 8) == 0) 3108 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3109 DAG.getConstant(Val / 8, DL, VT)); 3110 3111 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3112 DAG.getConstant(3, DL, VT)); 3113 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3114 } 3115 case ISD::FPOWI: { 3116 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3117 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3118 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3119 Op.getOperand(1).getValueType() == MVT::i32) { 3120 SDLoc DL(Op); 3121 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3122 SDValue Powi = 3123 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3124 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3125 DAG.getIntPtrConstant(0, DL)); 3126 } 3127 return SDValue(); 3128 } 3129 case ISD::FP_EXTEND: 3130 case ISD::FP_ROUND: 3131 if (!Op.getValueType().isVector()) 3132 return Op; 3133 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3134 case ISD::FP_TO_SINT: 3135 case ISD::FP_TO_UINT: 3136 case ISD::SINT_TO_FP: 3137 case ISD::UINT_TO_FP: { 3138 // RVV can only do fp<->int conversions to types half/double the size as 3139 // the source. We custom-lower any conversions that do two hops into 3140 // sequences. 3141 MVT VT = Op.getSimpleValueType(); 3142 if (!VT.isVector()) 3143 return Op; 3144 SDLoc DL(Op); 3145 SDValue Src = Op.getOperand(0); 3146 MVT EltVT = VT.getVectorElementType(); 3147 MVT SrcVT = Src.getSimpleValueType(); 3148 MVT SrcEltVT = SrcVT.getVectorElementType(); 3149 unsigned EltSize = EltVT.getSizeInBits(); 3150 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3151 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3152 "Unexpected vector element types"); 3153 3154 bool IsInt2FP = SrcEltVT.isInteger(); 3155 // Widening conversions 3156 if (EltSize > (2 * SrcEltSize)) { 3157 if (IsInt2FP) { 3158 // Do a regular integer sign/zero extension then convert to float. 3159 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3160 VT.getVectorElementCount()); 3161 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3162 ? ISD::ZERO_EXTEND 3163 : ISD::SIGN_EXTEND; 3164 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3165 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3166 } 3167 // FP2Int 3168 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3169 // Do one doubling fp_extend then complete the operation by converting 3170 // to int. 3171 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3172 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3173 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3174 } 3175 3176 // Narrowing conversions 3177 if (SrcEltSize > (2 * EltSize)) { 3178 if (IsInt2FP) { 3179 // One narrowing int_to_fp, then an fp_round. 3180 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3181 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3182 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3183 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3184 } 3185 // FP2Int 3186 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3187 // representable by the integer, the result is poison. 3188 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3189 VT.getVectorElementCount()); 3190 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3191 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3192 } 3193 3194 // Scalable vectors can exit here. Patterns will handle equally-sized 3195 // conversions halving/doubling ones. 3196 if (!VT.isFixedLengthVector()) 3197 return Op; 3198 3199 // For fixed-length vectors we lower to a custom "VL" node. 3200 unsigned RVVOpc = 0; 3201 switch (Op.getOpcode()) { 3202 default: 3203 llvm_unreachable("Impossible opcode"); 3204 case ISD::FP_TO_SINT: 3205 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3206 break; 3207 case ISD::FP_TO_UINT: 3208 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3209 break; 3210 case ISD::SINT_TO_FP: 3211 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3212 break; 3213 case ISD::UINT_TO_FP: 3214 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3215 break; 3216 } 3217 3218 MVT ContainerVT, SrcContainerVT; 3219 // Derive the reference container type from the larger vector type. 3220 if (SrcEltSize > EltSize) { 3221 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3222 ContainerVT = 3223 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3224 } else { 3225 ContainerVT = getContainerForFixedLengthVector(VT); 3226 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3227 } 3228 3229 SDValue Mask, VL; 3230 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3231 3232 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3233 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3234 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3235 } 3236 case ISD::FP_TO_SINT_SAT: 3237 case ISD::FP_TO_UINT_SAT: 3238 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3239 case ISD::FTRUNC: 3240 case ISD::FCEIL: 3241 case ISD::FFLOOR: 3242 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3243 case ISD::FROUND: 3244 return lowerFROUND(Op, DAG); 3245 case ISD::VECREDUCE_ADD: 3246 case ISD::VECREDUCE_UMAX: 3247 case ISD::VECREDUCE_SMAX: 3248 case ISD::VECREDUCE_UMIN: 3249 case ISD::VECREDUCE_SMIN: 3250 return lowerVECREDUCE(Op, DAG); 3251 case ISD::VECREDUCE_AND: 3252 case ISD::VECREDUCE_OR: 3253 case ISD::VECREDUCE_XOR: 3254 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3255 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3256 return lowerVECREDUCE(Op, DAG); 3257 case ISD::VECREDUCE_FADD: 3258 case ISD::VECREDUCE_SEQ_FADD: 3259 case ISD::VECREDUCE_FMIN: 3260 case ISD::VECREDUCE_FMAX: 3261 return lowerFPVECREDUCE(Op, DAG); 3262 case ISD::VP_REDUCE_ADD: 3263 case ISD::VP_REDUCE_UMAX: 3264 case ISD::VP_REDUCE_SMAX: 3265 case ISD::VP_REDUCE_UMIN: 3266 case ISD::VP_REDUCE_SMIN: 3267 case ISD::VP_REDUCE_FADD: 3268 case ISD::VP_REDUCE_SEQ_FADD: 3269 case ISD::VP_REDUCE_FMIN: 3270 case ISD::VP_REDUCE_FMAX: 3271 return lowerVPREDUCE(Op, DAG); 3272 case ISD::VP_REDUCE_AND: 3273 case ISD::VP_REDUCE_OR: 3274 case ISD::VP_REDUCE_XOR: 3275 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3276 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3277 return lowerVPREDUCE(Op, DAG); 3278 case ISD::INSERT_SUBVECTOR: 3279 return lowerINSERT_SUBVECTOR(Op, DAG); 3280 case ISD::EXTRACT_SUBVECTOR: 3281 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3282 case ISD::STEP_VECTOR: 3283 return lowerSTEP_VECTOR(Op, DAG); 3284 case ISD::VECTOR_REVERSE: 3285 return lowerVECTOR_REVERSE(Op, DAG); 3286 case ISD::VECTOR_SPLICE: 3287 return lowerVECTOR_SPLICE(Op, DAG); 3288 case ISD::BUILD_VECTOR: 3289 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3290 case ISD::SPLAT_VECTOR: 3291 if (Op.getValueType().getVectorElementType() == MVT::i1) 3292 return lowerVectorMaskSplat(Op, DAG); 3293 return SDValue(); 3294 case ISD::VECTOR_SHUFFLE: 3295 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3296 case ISD::CONCAT_VECTORS: { 3297 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3298 // better than going through the stack, as the default expansion does. 3299 SDLoc DL(Op); 3300 MVT VT = Op.getSimpleValueType(); 3301 unsigned NumOpElts = 3302 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3303 SDValue Vec = DAG.getUNDEF(VT); 3304 for (const auto &OpIdx : enumerate(Op->ops())) { 3305 SDValue SubVec = OpIdx.value(); 3306 // Don't insert undef subvectors. 3307 if (SubVec.isUndef()) 3308 continue; 3309 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3310 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3311 } 3312 return Vec; 3313 } 3314 case ISD::LOAD: 3315 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3316 return V; 3317 if (Op.getValueType().isFixedLengthVector()) 3318 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3319 return Op; 3320 case ISD::STORE: 3321 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3322 return V; 3323 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3324 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3325 return Op; 3326 case ISD::MLOAD: 3327 case ISD::VP_LOAD: 3328 return lowerMaskedLoad(Op, DAG); 3329 case ISD::MSTORE: 3330 case ISD::VP_STORE: 3331 return lowerMaskedStore(Op, DAG); 3332 case ISD::SETCC: 3333 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3334 case ISD::ADD: 3335 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3336 case ISD::SUB: 3337 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3338 case ISD::MUL: 3339 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3340 case ISD::MULHS: 3341 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3342 case ISD::MULHU: 3343 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3344 case ISD::AND: 3345 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3346 RISCVISD::AND_VL); 3347 case ISD::OR: 3348 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3349 RISCVISD::OR_VL); 3350 case ISD::XOR: 3351 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3352 RISCVISD::XOR_VL); 3353 case ISD::SDIV: 3354 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3355 case ISD::SREM: 3356 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3357 case ISD::UDIV: 3358 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3359 case ISD::UREM: 3360 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3361 case ISD::SHL: 3362 case ISD::SRA: 3363 case ISD::SRL: 3364 if (Op.getSimpleValueType().isFixedLengthVector()) 3365 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3366 // This can be called for an i32 shift amount that needs to be promoted. 3367 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3368 "Unexpected custom legalisation"); 3369 return SDValue(); 3370 case ISD::SADDSAT: 3371 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3372 case ISD::UADDSAT: 3373 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3374 case ISD::SSUBSAT: 3375 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3376 case ISD::USUBSAT: 3377 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3378 case ISD::FADD: 3379 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3380 case ISD::FSUB: 3381 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3382 case ISD::FMUL: 3383 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3384 case ISD::FDIV: 3385 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3386 case ISD::FNEG: 3387 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3388 case ISD::FABS: 3389 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3390 case ISD::FSQRT: 3391 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3392 case ISD::FMA: 3393 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3394 case ISD::SMIN: 3395 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3396 case ISD::SMAX: 3397 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3398 case ISD::UMIN: 3399 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3400 case ISD::UMAX: 3401 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3402 case ISD::FMINNUM: 3403 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3404 case ISD::FMAXNUM: 3405 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3406 case ISD::ABS: 3407 return lowerABS(Op, DAG); 3408 case ISD::CTLZ_ZERO_UNDEF: 3409 case ISD::CTTZ_ZERO_UNDEF: 3410 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3411 case ISD::VSELECT: 3412 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3413 case ISD::FCOPYSIGN: 3414 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3415 case ISD::MGATHER: 3416 case ISD::VP_GATHER: 3417 return lowerMaskedGather(Op, DAG); 3418 case ISD::MSCATTER: 3419 case ISD::VP_SCATTER: 3420 return lowerMaskedScatter(Op, DAG); 3421 case ISD::FLT_ROUNDS_: 3422 return lowerGET_ROUNDING(Op, DAG); 3423 case ISD::SET_ROUNDING: 3424 return lowerSET_ROUNDING(Op, DAG); 3425 case ISD::VP_SELECT: 3426 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3427 case ISD::VP_MERGE: 3428 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3429 case ISD::VP_ADD: 3430 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3431 case ISD::VP_SUB: 3432 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3433 case ISD::VP_MUL: 3434 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3435 case ISD::VP_SDIV: 3436 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3437 case ISD::VP_UDIV: 3438 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3439 case ISD::VP_SREM: 3440 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3441 case ISD::VP_UREM: 3442 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3443 case ISD::VP_AND: 3444 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3445 case ISD::VP_OR: 3446 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3447 case ISD::VP_XOR: 3448 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3449 case ISD::VP_ASHR: 3450 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3451 case ISD::VP_LSHR: 3452 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3453 case ISD::VP_SHL: 3454 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3455 case ISD::VP_FADD: 3456 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3457 case ISD::VP_FSUB: 3458 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3459 case ISD::VP_FMUL: 3460 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3461 case ISD::VP_FDIV: 3462 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3463 case ISD::VP_FNEG: 3464 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3465 case ISD::VP_FMA: 3466 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3467 case ISD::VP_SIGN_EXTEND: 3468 case ISD::VP_ZERO_EXTEND: 3469 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3470 return lowerVPExtMaskOp(Op, DAG); 3471 return lowerVPOp(Op, DAG, 3472 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3473 ? RISCVISD::VSEXT_VL 3474 : RISCVISD::VZEXT_VL); 3475 case ISD::VP_TRUNCATE: 3476 return lowerVectorTruncLike(Op, DAG); 3477 case ISD::VP_FP_EXTEND: 3478 case ISD::VP_FP_ROUND: 3479 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3480 case ISD::VP_FPTOSI: 3481 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3482 case ISD::VP_FPTOUI: 3483 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3484 case ISD::VP_SITOFP: 3485 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3486 case ISD::VP_UITOFP: 3487 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3488 case ISD::VP_SETCC: 3489 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3490 return lowerVPSetCCMaskOp(Op, DAG); 3491 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3492 } 3493 } 3494 3495 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3496 SelectionDAG &DAG, unsigned Flags) { 3497 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3498 } 3499 3500 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3501 SelectionDAG &DAG, unsigned Flags) { 3502 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3503 Flags); 3504 } 3505 3506 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3507 SelectionDAG &DAG, unsigned Flags) { 3508 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3509 N->getOffset(), Flags); 3510 } 3511 3512 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3513 SelectionDAG &DAG, unsigned Flags) { 3514 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3515 } 3516 3517 template <class NodeTy> 3518 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3519 bool IsLocal) const { 3520 SDLoc DL(N); 3521 EVT Ty = getPointerTy(DAG.getDataLayout()); 3522 3523 if (isPositionIndependent()) { 3524 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3525 if (IsLocal) 3526 // Use PC-relative addressing to access the symbol. This generates the 3527 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3528 // %pcrel_lo(auipc)). 3529 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3530 3531 // Use PC-relative addressing to access the GOT for this symbol, then load 3532 // the address from the GOT. This generates the pattern (PseudoLA sym), 3533 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3534 SDValue Load = 3535 SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3536 MachineFunction &MF = DAG.getMachineFunction(); 3537 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3538 MachinePointerInfo::getGOT(MF), 3539 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3540 MachineMemOperand::MOInvariant, 3541 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3542 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3543 return Load; 3544 } 3545 3546 switch (getTargetMachine().getCodeModel()) { 3547 default: 3548 report_fatal_error("Unsupported code model for lowering"); 3549 case CodeModel::Small: { 3550 // Generate a sequence for accessing addresses within the first 2 GiB of 3551 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3552 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3553 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3554 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3555 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3556 } 3557 case CodeModel::Medium: { 3558 // Generate a sequence for accessing addresses within any 2GiB range within 3559 // the address space. This generates the pattern (PseudoLLA sym), which 3560 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3561 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3562 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3563 } 3564 } 3565 } 3566 3567 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>( 3568 GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3569 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>( 3570 BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3571 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>( 3572 ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3573 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>( 3574 JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3575 3576 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3577 SelectionDAG &DAG) const { 3578 SDLoc DL(Op); 3579 EVT Ty = Op.getValueType(); 3580 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3581 int64_t Offset = N->getOffset(); 3582 MVT XLenVT = Subtarget.getXLenVT(); 3583 3584 const GlobalValue *GV = N->getGlobal(); 3585 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3586 SDValue Addr = getAddr(N, DAG, IsLocal); 3587 3588 // In order to maximise the opportunity for common subexpression elimination, 3589 // emit a separate ADD node for the global address offset instead of folding 3590 // it in the global address node. Later peephole optimisations may choose to 3591 // fold it back in when profitable. 3592 if (Offset != 0) 3593 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3594 DAG.getConstant(Offset, DL, XLenVT)); 3595 return Addr; 3596 } 3597 3598 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3599 SelectionDAG &DAG) const { 3600 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3601 3602 return getAddr(N, DAG); 3603 } 3604 3605 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3606 SelectionDAG &DAG) const { 3607 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3608 3609 return getAddr(N, DAG); 3610 } 3611 3612 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3613 SelectionDAG &DAG) const { 3614 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3615 3616 return getAddr(N, DAG); 3617 } 3618 3619 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3620 SelectionDAG &DAG, 3621 bool UseGOT) const { 3622 SDLoc DL(N); 3623 EVT Ty = getPointerTy(DAG.getDataLayout()); 3624 const GlobalValue *GV = N->getGlobal(); 3625 MVT XLenVT = Subtarget.getXLenVT(); 3626 3627 if (UseGOT) { 3628 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3629 // load the address from the GOT and add the thread pointer. This generates 3630 // the pattern (PseudoLA_TLS_IE sym), which expands to 3631 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3632 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3633 SDValue Load = 3634 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3635 MachineFunction &MF = DAG.getMachineFunction(); 3636 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3637 MachinePointerInfo::getGOT(MF), 3638 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3639 MachineMemOperand::MOInvariant, 3640 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3641 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3642 3643 // Add the thread pointer. 3644 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3645 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3646 } 3647 3648 // Generate a sequence for accessing the address relative to the thread 3649 // pointer, with the appropriate adjustment for the thread pointer offset. 3650 // This generates the pattern 3651 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3652 SDValue AddrHi = 3653 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3654 SDValue AddrAdd = 3655 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3656 SDValue AddrLo = 3657 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3658 3659 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3660 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3661 SDValue MNAdd = SDValue( 3662 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3663 0); 3664 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3665 } 3666 3667 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3668 SelectionDAG &DAG) const { 3669 SDLoc DL(N); 3670 EVT Ty = getPointerTy(DAG.getDataLayout()); 3671 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3672 const GlobalValue *GV = N->getGlobal(); 3673 3674 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3675 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3676 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3677 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3678 SDValue Load = 3679 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3680 3681 // Prepare argument list to generate call. 3682 ArgListTy Args; 3683 ArgListEntry Entry; 3684 Entry.Node = Load; 3685 Entry.Ty = CallTy; 3686 Args.push_back(Entry); 3687 3688 // Setup call to __tls_get_addr. 3689 TargetLowering::CallLoweringInfo CLI(DAG); 3690 CLI.setDebugLoc(DL) 3691 .setChain(DAG.getEntryNode()) 3692 .setLibCallee(CallingConv::C, CallTy, 3693 DAG.getExternalSymbol("__tls_get_addr", Ty), 3694 std::move(Args)); 3695 3696 return LowerCallTo(CLI).first; 3697 } 3698 3699 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3700 SelectionDAG &DAG) const { 3701 SDLoc DL(Op); 3702 EVT Ty = Op.getValueType(); 3703 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3704 int64_t Offset = N->getOffset(); 3705 MVT XLenVT = Subtarget.getXLenVT(); 3706 3707 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3708 3709 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3710 CallingConv::GHC) 3711 report_fatal_error("In GHC calling convention TLS is not supported"); 3712 3713 SDValue Addr; 3714 switch (Model) { 3715 case TLSModel::LocalExec: 3716 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3717 break; 3718 case TLSModel::InitialExec: 3719 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3720 break; 3721 case TLSModel::LocalDynamic: 3722 case TLSModel::GeneralDynamic: 3723 Addr = getDynamicTLSAddr(N, DAG); 3724 break; 3725 } 3726 3727 // In order to maximise the opportunity for common subexpression elimination, 3728 // emit a separate ADD node for the global address offset instead of folding 3729 // it in the global address node. Later peephole optimisations may choose to 3730 // fold it back in when profitable. 3731 if (Offset != 0) 3732 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3733 DAG.getConstant(Offset, DL, XLenVT)); 3734 return Addr; 3735 } 3736 3737 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3738 SDValue CondV = Op.getOperand(0); 3739 SDValue TrueV = Op.getOperand(1); 3740 SDValue FalseV = Op.getOperand(2); 3741 SDLoc DL(Op); 3742 MVT VT = Op.getSimpleValueType(); 3743 MVT XLenVT = Subtarget.getXLenVT(); 3744 3745 // Lower vector SELECTs to VSELECTs by splatting the condition. 3746 if (VT.isVector()) { 3747 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3748 SDValue CondSplat = VT.isScalableVector() 3749 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3750 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3751 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3752 } 3753 3754 // If the result type is XLenVT and CondV is the output of a SETCC node 3755 // which also operated on XLenVT inputs, then merge the SETCC node into the 3756 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3757 // compare+branch instructions. i.e.: 3758 // (select (setcc lhs, rhs, cc), truev, falsev) 3759 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3760 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3761 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3762 SDValue LHS = CondV.getOperand(0); 3763 SDValue RHS = CondV.getOperand(1); 3764 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3765 ISD::CondCode CCVal = CC->get(); 3766 3767 // Special case for a select of 2 constants that have a diffence of 1. 3768 // Normally this is done by DAGCombine, but if the select is introduced by 3769 // type legalization or op legalization, we miss it. Restricting to SETLT 3770 // case for now because that is what signed saturating add/sub need. 3771 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3772 // but we would probably want to swap the true/false values if the condition 3773 // is SETGE/SETLE to avoid an XORI. 3774 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3775 CCVal == ISD::SETLT) { 3776 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3777 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3778 if (TrueVal - 1 == FalseVal) 3779 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3780 if (TrueVal + 1 == FalseVal) 3781 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3782 } 3783 3784 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3785 3786 SDValue TargetCC = DAG.getCondCode(CCVal); 3787 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3788 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3789 } 3790 3791 // Otherwise: 3792 // (select condv, truev, falsev) 3793 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3794 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3795 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3796 3797 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3798 3799 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3800 } 3801 3802 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3803 SDValue CondV = Op.getOperand(1); 3804 SDLoc DL(Op); 3805 MVT XLenVT = Subtarget.getXLenVT(); 3806 3807 if (CondV.getOpcode() == ISD::SETCC && 3808 CondV.getOperand(0).getValueType() == XLenVT) { 3809 SDValue LHS = CondV.getOperand(0); 3810 SDValue RHS = CondV.getOperand(1); 3811 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3812 3813 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3814 3815 SDValue TargetCC = DAG.getCondCode(CCVal); 3816 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3817 LHS, RHS, TargetCC, Op.getOperand(2)); 3818 } 3819 3820 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3821 CondV, DAG.getConstant(0, DL, XLenVT), 3822 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3823 } 3824 3825 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3826 MachineFunction &MF = DAG.getMachineFunction(); 3827 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3828 3829 SDLoc DL(Op); 3830 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3831 getPointerTy(MF.getDataLayout())); 3832 3833 // vastart just stores the address of the VarArgsFrameIndex slot into the 3834 // memory location argument. 3835 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3836 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3837 MachinePointerInfo(SV)); 3838 } 3839 3840 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3841 SelectionDAG &DAG) const { 3842 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3843 MachineFunction &MF = DAG.getMachineFunction(); 3844 MachineFrameInfo &MFI = MF.getFrameInfo(); 3845 MFI.setFrameAddressIsTaken(true); 3846 Register FrameReg = RI.getFrameRegister(MF); 3847 int XLenInBytes = Subtarget.getXLen() / 8; 3848 3849 EVT VT = Op.getValueType(); 3850 SDLoc DL(Op); 3851 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3852 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3853 while (Depth--) { 3854 int Offset = -(XLenInBytes * 2); 3855 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3856 DAG.getIntPtrConstant(Offset, DL)); 3857 FrameAddr = 3858 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3859 } 3860 return FrameAddr; 3861 } 3862 3863 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3864 SelectionDAG &DAG) const { 3865 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3866 MachineFunction &MF = DAG.getMachineFunction(); 3867 MachineFrameInfo &MFI = MF.getFrameInfo(); 3868 MFI.setReturnAddressIsTaken(true); 3869 MVT XLenVT = Subtarget.getXLenVT(); 3870 int XLenInBytes = Subtarget.getXLen() / 8; 3871 3872 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3873 return SDValue(); 3874 3875 EVT VT = Op.getValueType(); 3876 SDLoc DL(Op); 3877 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3878 if (Depth) { 3879 int Off = -XLenInBytes; 3880 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3881 SDValue Offset = DAG.getConstant(Off, DL, VT); 3882 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3883 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3884 MachinePointerInfo()); 3885 } 3886 3887 // Return the value of the return address register, marking it an implicit 3888 // live-in. 3889 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3890 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3891 } 3892 3893 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3894 SelectionDAG &DAG) const { 3895 SDLoc DL(Op); 3896 SDValue Lo = Op.getOperand(0); 3897 SDValue Hi = Op.getOperand(1); 3898 SDValue Shamt = Op.getOperand(2); 3899 EVT VT = Lo.getValueType(); 3900 3901 // if Shamt-XLEN < 0: // Shamt < XLEN 3902 // Lo = Lo << Shamt 3903 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 3904 // else: 3905 // Lo = 0 3906 // Hi = Lo << (Shamt-XLEN) 3907 3908 SDValue Zero = DAG.getConstant(0, DL, VT); 3909 SDValue One = DAG.getConstant(1, DL, VT); 3910 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3911 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3912 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3913 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3914 3915 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3916 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3917 SDValue ShiftRightLo = 3918 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3919 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3920 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3921 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3922 3923 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3924 3925 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3926 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3927 3928 SDValue Parts[2] = {Lo, Hi}; 3929 return DAG.getMergeValues(Parts, DL); 3930 } 3931 3932 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3933 bool IsSRA) const { 3934 SDLoc DL(Op); 3935 SDValue Lo = Op.getOperand(0); 3936 SDValue Hi = Op.getOperand(1); 3937 SDValue Shamt = Op.getOperand(2); 3938 EVT VT = Lo.getValueType(); 3939 3940 // SRA expansion: 3941 // if Shamt-XLEN < 0: // Shamt < XLEN 3942 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3943 // Hi = Hi >>s Shamt 3944 // else: 3945 // Lo = Hi >>s (Shamt-XLEN); 3946 // Hi = Hi >>s (XLEN-1) 3947 // 3948 // SRL expansion: 3949 // if Shamt-XLEN < 0: // Shamt < XLEN 3950 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3951 // Hi = Hi >>u Shamt 3952 // else: 3953 // Lo = Hi >>u (Shamt-XLEN); 3954 // Hi = 0; 3955 3956 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3957 3958 SDValue Zero = DAG.getConstant(0, DL, VT); 3959 SDValue One = DAG.getConstant(1, DL, VT); 3960 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3961 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3962 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3963 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3964 3965 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3966 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3967 SDValue ShiftLeftHi = 3968 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3969 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3970 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3971 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3972 SDValue HiFalse = 3973 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3974 3975 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3976 3977 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3978 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3979 3980 SDValue Parts[2] = {Lo, Hi}; 3981 return DAG.getMergeValues(Parts, DL); 3982 } 3983 3984 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3985 // legal equivalently-sized i8 type, so we can use that as a go-between. 3986 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3987 SelectionDAG &DAG) const { 3988 SDLoc DL(Op); 3989 MVT VT = Op.getSimpleValueType(); 3990 SDValue SplatVal = Op.getOperand(0); 3991 // All-zeros or all-ones splats are handled specially. 3992 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3993 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3994 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3995 } 3996 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3997 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3998 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3999 } 4000 MVT XLenVT = Subtarget.getXLenVT(); 4001 assert(SplatVal.getValueType() == XLenVT && 4002 "Unexpected type for i1 splat value"); 4003 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4004 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4005 DAG.getConstant(1, DL, XLenVT)); 4006 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4007 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4008 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4009 } 4010 4011 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4012 // illegal (currently only vXi64 RV32). 4013 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4014 // them to VMV_V_X_VL. 4015 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4016 SelectionDAG &DAG) const { 4017 SDLoc DL(Op); 4018 MVT VecVT = Op.getSimpleValueType(); 4019 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4020 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4021 4022 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4023 SDValue Lo = Op.getOperand(0); 4024 SDValue Hi = Op.getOperand(1); 4025 4026 if (VecVT.isFixedLengthVector()) { 4027 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4028 SDLoc DL(Op); 4029 SDValue Mask, VL; 4030 std::tie(Mask, VL) = 4031 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4032 4033 SDValue Res = 4034 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4035 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4036 } 4037 4038 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4039 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4040 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4041 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4042 // node in order to try and match RVV vector/scalar instructions. 4043 if ((LoC >> 31) == HiC) 4044 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4045 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4046 } 4047 4048 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4049 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4050 isa<ConstantSDNode>(Hi.getOperand(1)) && 4051 Hi.getConstantOperandVal(1) == 31) 4052 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4053 DAG.getRegister(RISCV::X0, MVT::i32)); 4054 4055 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4056 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4057 DAG.getUNDEF(VecVT), Lo, Hi, 4058 DAG.getRegister(RISCV::X0, MVT::i32)); 4059 } 4060 4061 // Custom-lower extensions from mask vectors by using a vselect either with 1 4062 // for zero/any-extension or -1 for sign-extension: 4063 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4064 // Note that any-extension is lowered identically to zero-extension. 4065 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4066 int64_t ExtTrueVal) const { 4067 SDLoc DL(Op); 4068 MVT VecVT = Op.getSimpleValueType(); 4069 SDValue Src = Op.getOperand(0); 4070 // Only custom-lower extensions from mask types 4071 assert(Src.getValueType().isVector() && 4072 Src.getValueType().getVectorElementType() == MVT::i1); 4073 4074 if (VecVT.isScalableVector()) { 4075 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4076 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4077 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4078 } 4079 4080 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4081 MVT I1ContainerVT = 4082 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4083 4084 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4085 4086 SDValue Mask, VL; 4087 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4088 4089 MVT XLenVT = Subtarget.getXLenVT(); 4090 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4091 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4092 4093 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4094 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4095 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4096 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4097 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4098 SplatTrueVal, SplatZero, VL); 4099 4100 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4101 } 4102 4103 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4104 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4105 MVT ExtVT = Op.getSimpleValueType(); 4106 // Only custom-lower extensions from fixed-length vector types. 4107 if (!ExtVT.isFixedLengthVector()) 4108 return Op; 4109 MVT VT = Op.getOperand(0).getSimpleValueType(); 4110 // Grab the canonical container type for the extended type. Infer the smaller 4111 // type from that to ensure the same number of vector elements, as we know 4112 // the LMUL will be sufficient to hold the smaller type. 4113 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4114 // Get the extended container type manually to ensure the same number of 4115 // vector elements between source and dest. 4116 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4117 ContainerExtVT.getVectorElementCount()); 4118 4119 SDValue Op1 = 4120 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4121 4122 SDLoc DL(Op); 4123 SDValue Mask, VL; 4124 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4125 4126 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4127 4128 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4129 } 4130 4131 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4132 // setcc operation: 4133 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4134 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4135 SelectionDAG &DAG) const { 4136 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4137 SDLoc DL(Op); 4138 EVT MaskVT = Op.getValueType(); 4139 // Only expect to custom-lower truncations to mask types 4140 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4141 "Unexpected type for vector mask lowering"); 4142 SDValue Src = Op.getOperand(0); 4143 MVT VecVT = Src.getSimpleValueType(); 4144 SDValue Mask, VL; 4145 if (IsVPTrunc) { 4146 Mask = Op.getOperand(1); 4147 VL = Op.getOperand(2); 4148 } 4149 // If this is a fixed vector, we need to convert it to a scalable vector. 4150 MVT ContainerVT = VecVT; 4151 4152 if (VecVT.isFixedLengthVector()) { 4153 ContainerVT = getContainerForFixedLengthVector(VecVT); 4154 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4155 if (IsVPTrunc) { 4156 MVT MaskContainerVT = 4157 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4158 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4159 } 4160 } 4161 4162 if (!IsVPTrunc) { 4163 std::tie(Mask, VL) = 4164 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4165 } 4166 4167 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4168 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4169 4170 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4171 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4172 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4173 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4174 4175 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4176 SDValue Trunc = 4177 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4178 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4179 DAG.getCondCode(ISD::SETNE), Mask, VL); 4180 if (MaskVT.isFixedLengthVector()) 4181 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4182 return Trunc; 4183 } 4184 4185 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4186 SelectionDAG &DAG) const { 4187 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4188 SDLoc DL(Op); 4189 4190 MVT VT = Op.getSimpleValueType(); 4191 // Only custom-lower vector truncates 4192 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4193 4194 // Truncates to mask types are handled differently 4195 if (VT.getVectorElementType() == MVT::i1) 4196 return lowerVectorMaskTruncLike(Op, DAG); 4197 4198 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4199 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4200 // truncate by one power of two at a time. 4201 MVT DstEltVT = VT.getVectorElementType(); 4202 4203 SDValue Src = Op.getOperand(0); 4204 MVT SrcVT = Src.getSimpleValueType(); 4205 MVT SrcEltVT = SrcVT.getVectorElementType(); 4206 4207 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4208 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4209 "Unexpected vector truncate lowering"); 4210 4211 MVT ContainerVT = SrcVT; 4212 SDValue Mask, VL; 4213 if (IsVPTrunc) { 4214 Mask = Op.getOperand(1); 4215 VL = Op.getOperand(2); 4216 } 4217 if (SrcVT.isFixedLengthVector()) { 4218 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4219 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4220 if (IsVPTrunc) { 4221 MVT MaskVT = getMaskTypeFor(ContainerVT); 4222 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4223 } 4224 } 4225 4226 SDValue Result = Src; 4227 if (!IsVPTrunc) { 4228 std::tie(Mask, VL) = 4229 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4230 } 4231 4232 LLVMContext &Context = *DAG.getContext(); 4233 const ElementCount Count = ContainerVT.getVectorElementCount(); 4234 do { 4235 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4236 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4237 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4238 Mask, VL); 4239 } while (SrcEltVT != DstEltVT); 4240 4241 if (SrcVT.isFixedLengthVector()) 4242 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4243 4244 return Result; 4245 } 4246 4247 SDValue 4248 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4249 SelectionDAG &DAG) const { 4250 bool IsVP = 4251 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4252 bool IsExtend = 4253 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4254 // RVV can only do truncate fp to types half the size as the source. We 4255 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4256 // conversion instruction. 4257 SDLoc DL(Op); 4258 MVT VT = Op.getSimpleValueType(); 4259 4260 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4261 4262 SDValue Src = Op.getOperand(0); 4263 MVT SrcVT = Src.getSimpleValueType(); 4264 4265 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4266 SrcVT.getVectorElementType() != MVT::f16); 4267 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4268 SrcVT.getVectorElementType() != MVT::f64); 4269 4270 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4271 4272 // Prepare any fixed-length vector operands. 4273 MVT ContainerVT = VT; 4274 SDValue Mask, VL; 4275 if (IsVP) { 4276 Mask = Op.getOperand(1); 4277 VL = Op.getOperand(2); 4278 } 4279 if (VT.isFixedLengthVector()) { 4280 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4281 ContainerVT = 4282 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4283 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4284 if (IsVP) { 4285 MVT MaskVT = getMaskTypeFor(ContainerVT); 4286 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4287 } 4288 } 4289 4290 if (!IsVP) 4291 std::tie(Mask, VL) = 4292 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4293 4294 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4295 4296 if (IsDirectConv) { 4297 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4298 if (VT.isFixedLengthVector()) 4299 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4300 return Src; 4301 } 4302 4303 unsigned InterConvOpc = 4304 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4305 4306 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4307 SDValue IntermediateConv = 4308 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4309 SDValue Result = 4310 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4311 if (VT.isFixedLengthVector()) 4312 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4313 return Result; 4314 } 4315 4316 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4317 // first position of a vector, and that vector is slid up to the insert index. 4318 // By limiting the active vector length to index+1 and merging with the 4319 // original vector (with an undisturbed tail policy for elements >= VL), we 4320 // achieve the desired result of leaving all elements untouched except the one 4321 // at VL-1, which is replaced with the desired value. 4322 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4323 SelectionDAG &DAG) const { 4324 SDLoc DL(Op); 4325 MVT VecVT = Op.getSimpleValueType(); 4326 SDValue Vec = Op.getOperand(0); 4327 SDValue Val = Op.getOperand(1); 4328 SDValue Idx = Op.getOperand(2); 4329 4330 if (VecVT.getVectorElementType() == MVT::i1) { 4331 // FIXME: For now we just promote to an i8 vector and insert into that, 4332 // but this is probably not optimal. 4333 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4334 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4335 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4336 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4337 } 4338 4339 MVT ContainerVT = VecVT; 4340 // If the operand is a fixed-length vector, convert to a scalable one. 4341 if (VecVT.isFixedLengthVector()) { 4342 ContainerVT = getContainerForFixedLengthVector(VecVT); 4343 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4344 } 4345 4346 MVT XLenVT = Subtarget.getXLenVT(); 4347 4348 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4349 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4350 // Even i64-element vectors on RV32 can be lowered without scalar 4351 // legalization if the most-significant 32 bits of the value are not affected 4352 // by the sign-extension of the lower 32 bits. 4353 // TODO: We could also catch sign extensions of a 32-bit value. 4354 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4355 const auto *CVal = cast<ConstantSDNode>(Val); 4356 if (isInt<32>(CVal->getSExtValue())) { 4357 IsLegalInsert = true; 4358 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4359 } 4360 } 4361 4362 SDValue Mask, VL; 4363 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4364 4365 SDValue ValInVec; 4366 4367 if (IsLegalInsert) { 4368 unsigned Opc = 4369 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4370 if (isNullConstant(Idx)) { 4371 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4372 if (!VecVT.isFixedLengthVector()) 4373 return Vec; 4374 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4375 } 4376 ValInVec = 4377 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4378 } else { 4379 // On RV32, i64-element vectors must be specially handled to place the 4380 // value at element 0, by using two vslide1up instructions in sequence on 4381 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4382 // this. 4383 SDValue One = DAG.getConstant(1, DL, XLenVT); 4384 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4385 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4386 MVT I32ContainerVT = 4387 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4388 SDValue I32Mask = 4389 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4390 // Limit the active VL to two. 4391 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4392 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4393 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4394 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4395 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4396 // First slide in the hi value, then the lo in underneath it. 4397 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4398 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4399 I32Mask, InsertI64VL); 4400 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4401 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4402 I32Mask, InsertI64VL); 4403 // Bitcast back to the right container type. 4404 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4405 } 4406 4407 // Now that the value is in a vector, slide it into position. 4408 SDValue InsertVL = 4409 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4410 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4411 ValInVec, Idx, Mask, InsertVL); 4412 if (!VecVT.isFixedLengthVector()) 4413 return Slideup; 4414 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4415 } 4416 4417 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4418 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4419 // types this is done using VMV_X_S to allow us to glean information about the 4420 // sign bits of the result. 4421 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4422 SelectionDAG &DAG) const { 4423 SDLoc DL(Op); 4424 SDValue Idx = Op.getOperand(1); 4425 SDValue Vec = Op.getOperand(0); 4426 EVT EltVT = Op.getValueType(); 4427 MVT VecVT = Vec.getSimpleValueType(); 4428 MVT XLenVT = Subtarget.getXLenVT(); 4429 4430 if (VecVT.getVectorElementType() == MVT::i1) { 4431 if (VecVT.isFixedLengthVector()) { 4432 unsigned NumElts = VecVT.getVectorNumElements(); 4433 if (NumElts >= 8) { 4434 MVT WideEltVT; 4435 unsigned WidenVecLen; 4436 SDValue ExtractElementIdx; 4437 SDValue ExtractBitIdx; 4438 unsigned MaxEEW = Subtarget.getELEN(); 4439 MVT LargestEltVT = MVT::getIntegerVT( 4440 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4441 if (NumElts <= LargestEltVT.getSizeInBits()) { 4442 assert(isPowerOf2_32(NumElts) && 4443 "the number of elements should be power of 2"); 4444 WideEltVT = MVT::getIntegerVT(NumElts); 4445 WidenVecLen = 1; 4446 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4447 ExtractBitIdx = Idx; 4448 } else { 4449 WideEltVT = LargestEltVT; 4450 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4451 // extract element index = index / element width 4452 ExtractElementIdx = DAG.getNode( 4453 ISD::SRL, DL, XLenVT, Idx, 4454 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4455 // mask bit index = index % element width 4456 ExtractBitIdx = DAG.getNode( 4457 ISD::AND, DL, XLenVT, Idx, 4458 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4459 } 4460 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4461 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4462 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4463 Vec, ExtractElementIdx); 4464 // Extract the bit from GPR. 4465 SDValue ShiftRight = 4466 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4467 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4468 DAG.getConstant(1, DL, XLenVT)); 4469 } 4470 } 4471 // Otherwise, promote to an i8 vector and extract from that. 4472 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4473 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4474 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4475 } 4476 4477 // If this is a fixed vector, we need to convert it to a scalable vector. 4478 MVT ContainerVT = VecVT; 4479 if (VecVT.isFixedLengthVector()) { 4480 ContainerVT = getContainerForFixedLengthVector(VecVT); 4481 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4482 } 4483 4484 // If the index is 0, the vector is already in the right position. 4485 if (!isNullConstant(Idx)) { 4486 // Use a VL of 1 to avoid processing more elements than we need. 4487 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4488 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4489 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4490 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4491 } 4492 4493 if (!EltVT.isInteger()) { 4494 // Floating-point extracts are handled in TableGen. 4495 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4496 DAG.getConstant(0, DL, XLenVT)); 4497 } 4498 4499 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4500 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4501 } 4502 4503 // Some RVV intrinsics may claim that they want an integer operand to be 4504 // promoted or expanded. 4505 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4506 const RISCVSubtarget &Subtarget) { 4507 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4508 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4509 "Unexpected opcode"); 4510 4511 if (!Subtarget.hasVInstructions()) 4512 return SDValue(); 4513 4514 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4515 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4516 SDLoc DL(Op); 4517 4518 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4519 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4520 if (!II || !II->hasScalarOperand()) 4521 return SDValue(); 4522 4523 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4524 assert(SplatOp < Op.getNumOperands()); 4525 4526 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4527 SDValue &ScalarOp = Operands[SplatOp]; 4528 MVT OpVT = ScalarOp.getSimpleValueType(); 4529 MVT XLenVT = Subtarget.getXLenVT(); 4530 4531 // If this isn't a scalar, or its type is XLenVT we're done. 4532 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4533 return SDValue(); 4534 4535 // Simplest case is that the operand needs to be promoted to XLenVT. 4536 if (OpVT.bitsLT(XLenVT)) { 4537 // If the operand is a constant, sign extend to increase our chances 4538 // of being able to use a .vi instruction. ANY_EXTEND would become a 4539 // a zero extend and the simm5 check in isel would fail. 4540 // FIXME: Should we ignore the upper bits in isel instead? 4541 unsigned ExtOpc = 4542 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4543 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4544 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4545 } 4546 4547 // Use the previous operand to get the vXi64 VT. The result might be a mask 4548 // VT for compares. Using the previous operand assumes that the previous 4549 // operand will never have a smaller element size than a scalar operand and 4550 // that a widening operation never uses SEW=64. 4551 // NOTE: If this fails the below assert, we can probably just find the 4552 // element count from any operand or result and use it to construct the VT. 4553 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4554 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4555 4556 // The more complex case is when the scalar is larger than XLenVT. 4557 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4558 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4559 4560 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4561 // instruction to sign-extend since SEW>XLEN. 4562 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4563 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4564 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4565 } 4566 4567 switch (IntNo) { 4568 case Intrinsic::riscv_vslide1up: 4569 case Intrinsic::riscv_vslide1down: 4570 case Intrinsic::riscv_vslide1up_mask: 4571 case Intrinsic::riscv_vslide1down_mask: { 4572 // We need to special case these when the scalar is larger than XLen. 4573 unsigned NumOps = Op.getNumOperands(); 4574 bool IsMasked = NumOps == 7; 4575 4576 // Convert the vector source to the equivalent nxvXi32 vector. 4577 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4578 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4579 4580 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4581 DAG.getConstant(0, DL, XLenVT)); 4582 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4583 DAG.getConstant(1, DL, XLenVT)); 4584 4585 // Double the VL since we halved SEW. 4586 SDValue AVL = getVLOperand(Op); 4587 SDValue I32VL; 4588 4589 // Optimize for constant AVL 4590 if (isa<ConstantSDNode>(AVL)) { 4591 unsigned EltSize = VT.getScalarSizeInBits(); 4592 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4593 4594 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4595 unsigned MaxVLMAX = 4596 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4597 4598 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4599 unsigned MinVLMAX = 4600 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4601 4602 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4603 if (AVLInt <= MinVLMAX) { 4604 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4605 } else if (AVLInt >= 2 * MaxVLMAX) { 4606 // Just set vl to VLMAX in this situation 4607 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4608 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4609 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4610 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4611 SDValue SETVLMAX = DAG.getTargetConstant( 4612 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4613 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4614 LMUL); 4615 } else { 4616 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4617 // is related to the hardware implementation. 4618 // So let the following code handle 4619 } 4620 } 4621 if (!I32VL) { 4622 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4623 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4624 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4625 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4626 SDValue SETVL = 4627 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4628 // Using vsetvli instruction to get actually used length which related to 4629 // the hardware implementation 4630 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4631 SEW, LMUL); 4632 I32VL = 4633 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4634 } 4635 4636 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4637 4638 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4639 // instructions. 4640 SDValue Passthru; 4641 if (IsMasked) 4642 Passthru = DAG.getUNDEF(I32VT); 4643 else 4644 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4645 4646 if (IntNo == Intrinsic::riscv_vslide1up || 4647 IntNo == Intrinsic::riscv_vslide1up_mask) { 4648 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4649 ScalarHi, I32Mask, I32VL); 4650 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4651 ScalarLo, I32Mask, I32VL); 4652 } else { 4653 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4654 ScalarLo, I32Mask, I32VL); 4655 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4656 ScalarHi, I32Mask, I32VL); 4657 } 4658 4659 // Convert back to nxvXi64. 4660 Vec = DAG.getBitcast(VT, Vec); 4661 4662 if (!IsMasked) 4663 return Vec; 4664 // Apply mask after the operation. 4665 SDValue Mask = Operands[NumOps - 3]; 4666 SDValue MaskedOff = Operands[1]; 4667 // Assume Policy operand is the last operand. 4668 uint64_t Policy = 4669 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4670 // We don't need to select maskedoff if it's undef. 4671 if (MaskedOff.isUndef()) 4672 return Vec; 4673 // TAMU 4674 if (Policy == RISCVII::TAIL_AGNOSTIC) 4675 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4676 AVL); 4677 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4678 // It's fine because vmerge does not care mask policy. 4679 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4680 AVL); 4681 } 4682 } 4683 4684 // We need to convert the scalar to a splat vector. 4685 SDValue VL = getVLOperand(Op); 4686 assert(VL.getValueType() == XLenVT); 4687 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4688 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4689 } 4690 4691 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4692 SelectionDAG &DAG) const { 4693 unsigned IntNo = Op.getConstantOperandVal(0); 4694 SDLoc DL(Op); 4695 MVT XLenVT = Subtarget.getXLenVT(); 4696 4697 switch (IntNo) { 4698 default: 4699 break; // Don't custom lower most intrinsics. 4700 case Intrinsic::thread_pointer: { 4701 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4702 return DAG.getRegister(RISCV::X4, PtrVT); 4703 } 4704 case Intrinsic::riscv_orc_b: 4705 case Intrinsic::riscv_brev8: { 4706 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4707 unsigned Opc = 4708 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4709 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4710 DAG.getConstant(7, DL, XLenVT)); 4711 } 4712 case Intrinsic::riscv_grev: 4713 case Intrinsic::riscv_gorc: { 4714 unsigned Opc = 4715 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4716 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4717 } 4718 case Intrinsic::riscv_zip: 4719 case Intrinsic::riscv_unzip: { 4720 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4721 // For i32 the immediate is 15. For i64 the immediate is 31. 4722 unsigned Opc = 4723 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4724 unsigned BitWidth = Op.getValueSizeInBits(); 4725 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4726 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4727 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4728 } 4729 case Intrinsic::riscv_shfl: 4730 case Intrinsic::riscv_unshfl: { 4731 unsigned Opc = 4732 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4733 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4734 } 4735 case Intrinsic::riscv_bcompress: 4736 case Intrinsic::riscv_bdecompress: { 4737 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4738 : RISCVISD::BDECOMPRESS; 4739 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4740 } 4741 case Intrinsic::riscv_bfp: 4742 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4743 Op.getOperand(2)); 4744 case Intrinsic::riscv_fsl: 4745 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4746 Op.getOperand(2), Op.getOperand(3)); 4747 case Intrinsic::riscv_fsr: 4748 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4749 Op.getOperand(2), Op.getOperand(3)); 4750 case Intrinsic::riscv_vmv_x_s: 4751 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4752 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4753 Op.getOperand(1)); 4754 case Intrinsic::riscv_vmv_v_x: 4755 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4756 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4757 Subtarget); 4758 case Intrinsic::riscv_vfmv_v_f: 4759 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4760 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4761 case Intrinsic::riscv_vmv_s_x: { 4762 SDValue Scalar = Op.getOperand(2); 4763 4764 if (Scalar.getValueType().bitsLE(XLenVT)) { 4765 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4766 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4767 Op.getOperand(1), Scalar, Op.getOperand(3)); 4768 } 4769 4770 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4771 4772 // This is an i64 value that lives in two scalar registers. We have to 4773 // insert this in a convoluted way. First we build vXi64 splat containing 4774 // the two values that we assemble using some bit math. Next we'll use 4775 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4776 // to merge element 0 from our splat into the source vector. 4777 // FIXME: This is probably not the best way to do this, but it is 4778 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4779 // point. 4780 // sw lo, (a0) 4781 // sw hi, 4(a0) 4782 // vlse vX, (a0) 4783 // 4784 // vid.v vVid 4785 // vmseq.vx mMask, vVid, 0 4786 // vmerge.vvm vDest, vSrc, vVal, mMask 4787 MVT VT = Op.getSimpleValueType(); 4788 SDValue Vec = Op.getOperand(1); 4789 SDValue VL = getVLOperand(Op); 4790 4791 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4792 if (Op.getOperand(1).isUndef()) 4793 return SplattedVal; 4794 SDValue SplattedIdx = 4795 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4796 DAG.getConstant(0, DL, MVT::i32), VL); 4797 4798 MVT MaskVT = getMaskTypeFor(VT); 4799 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4800 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4801 SDValue SelectCond = 4802 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4803 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4804 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4805 Vec, VL); 4806 } 4807 } 4808 4809 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4810 } 4811 4812 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4813 SelectionDAG &DAG) const { 4814 unsigned IntNo = Op.getConstantOperandVal(1); 4815 switch (IntNo) { 4816 default: 4817 break; 4818 case Intrinsic::riscv_masked_strided_load: { 4819 SDLoc DL(Op); 4820 MVT XLenVT = Subtarget.getXLenVT(); 4821 4822 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4823 // the selection of the masked intrinsics doesn't do this for us. 4824 SDValue Mask = Op.getOperand(5); 4825 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4826 4827 MVT VT = Op->getSimpleValueType(0); 4828 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4829 4830 SDValue PassThru = Op.getOperand(2); 4831 if (!IsUnmasked) { 4832 MVT MaskVT = getMaskTypeFor(ContainerVT); 4833 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4834 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4835 } 4836 4837 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4838 4839 SDValue IntID = DAG.getTargetConstant( 4840 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4841 XLenVT); 4842 4843 auto *Load = cast<MemIntrinsicSDNode>(Op); 4844 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4845 if (IsUnmasked) 4846 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4847 else 4848 Ops.push_back(PassThru); 4849 Ops.push_back(Op.getOperand(3)); // Ptr 4850 Ops.push_back(Op.getOperand(4)); // Stride 4851 if (!IsUnmasked) 4852 Ops.push_back(Mask); 4853 Ops.push_back(VL); 4854 if (!IsUnmasked) { 4855 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4856 Ops.push_back(Policy); 4857 } 4858 4859 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4860 SDValue Result = 4861 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4862 Load->getMemoryVT(), Load->getMemOperand()); 4863 SDValue Chain = Result.getValue(1); 4864 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4865 return DAG.getMergeValues({Result, Chain}, DL); 4866 } 4867 case Intrinsic::riscv_seg2_load: 4868 case Intrinsic::riscv_seg3_load: 4869 case Intrinsic::riscv_seg4_load: 4870 case Intrinsic::riscv_seg5_load: 4871 case Intrinsic::riscv_seg6_load: 4872 case Intrinsic::riscv_seg7_load: 4873 case Intrinsic::riscv_seg8_load: { 4874 SDLoc DL(Op); 4875 static const Intrinsic::ID VlsegInts[7] = { 4876 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4877 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4878 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4879 Intrinsic::riscv_vlseg8}; 4880 unsigned NF = Op->getNumValues() - 1; 4881 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4882 MVT XLenVT = Subtarget.getXLenVT(); 4883 MVT VT = Op->getSimpleValueType(0); 4884 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4885 4886 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4887 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4888 auto *Load = cast<MemIntrinsicSDNode>(Op); 4889 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4890 ContainerVTs.push_back(MVT::Other); 4891 SDVTList VTs = DAG.getVTList(ContainerVTs); 4892 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 4893 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 4894 Ops.push_back(Op.getOperand(2)); 4895 Ops.push_back(VL); 4896 SDValue Result = 4897 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4898 Load->getMemoryVT(), Load->getMemOperand()); 4899 SmallVector<SDValue, 9> Results; 4900 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4901 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4902 DAG, Subtarget)); 4903 Results.push_back(Result.getValue(NF)); 4904 return DAG.getMergeValues(Results, DL); 4905 } 4906 } 4907 4908 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4909 } 4910 4911 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4912 SelectionDAG &DAG) const { 4913 unsigned IntNo = Op.getConstantOperandVal(1); 4914 switch (IntNo) { 4915 default: 4916 break; 4917 case Intrinsic::riscv_masked_strided_store: { 4918 SDLoc DL(Op); 4919 MVT XLenVT = Subtarget.getXLenVT(); 4920 4921 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4922 // the selection of the masked intrinsics doesn't do this for us. 4923 SDValue Mask = Op.getOperand(5); 4924 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4925 4926 SDValue Val = Op.getOperand(2); 4927 MVT VT = Val.getSimpleValueType(); 4928 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4929 4930 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4931 if (!IsUnmasked) { 4932 MVT MaskVT = getMaskTypeFor(ContainerVT); 4933 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4934 } 4935 4936 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4937 4938 SDValue IntID = DAG.getTargetConstant( 4939 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4940 XLenVT); 4941 4942 auto *Store = cast<MemIntrinsicSDNode>(Op); 4943 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4944 Ops.push_back(Val); 4945 Ops.push_back(Op.getOperand(3)); // Ptr 4946 Ops.push_back(Op.getOperand(4)); // Stride 4947 if (!IsUnmasked) 4948 Ops.push_back(Mask); 4949 Ops.push_back(VL); 4950 4951 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4952 Ops, Store->getMemoryVT(), 4953 Store->getMemOperand()); 4954 } 4955 } 4956 4957 return SDValue(); 4958 } 4959 4960 static MVT getLMUL1VT(MVT VT) { 4961 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4962 "Unexpected vector MVT"); 4963 return MVT::getScalableVectorVT( 4964 VT.getVectorElementType(), 4965 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4966 } 4967 4968 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4969 switch (ISDOpcode) { 4970 default: 4971 llvm_unreachable("Unhandled reduction"); 4972 case ISD::VECREDUCE_ADD: 4973 return RISCVISD::VECREDUCE_ADD_VL; 4974 case ISD::VECREDUCE_UMAX: 4975 return RISCVISD::VECREDUCE_UMAX_VL; 4976 case ISD::VECREDUCE_SMAX: 4977 return RISCVISD::VECREDUCE_SMAX_VL; 4978 case ISD::VECREDUCE_UMIN: 4979 return RISCVISD::VECREDUCE_UMIN_VL; 4980 case ISD::VECREDUCE_SMIN: 4981 return RISCVISD::VECREDUCE_SMIN_VL; 4982 case ISD::VECREDUCE_AND: 4983 return RISCVISD::VECREDUCE_AND_VL; 4984 case ISD::VECREDUCE_OR: 4985 return RISCVISD::VECREDUCE_OR_VL; 4986 case ISD::VECREDUCE_XOR: 4987 return RISCVISD::VECREDUCE_XOR_VL; 4988 } 4989 } 4990 4991 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4992 SelectionDAG &DAG, 4993 bool IsVP) const { 4994 SDLoc DL(Op); 4995 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4996 MVT VecVT = Vec.getSimpleValueType(); 4997 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4998 Op.getOpcode() == ISD::VECREDUCE_OR || 4999 Op.getOpcode() == ISD::VECREDUCE_XOR || 5000 Op.getOpcode() == ISD::VP_REDUCE_AND || 5001 Op.getOpcode() == ISD::VP_REDUCE_OR || 5002 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5003 "Unexpected reduction lowering"); 5004 5005 MVT XLenVT = Subtarget.getXLenVT(); 5006 assert(Op.getValueType() == XLenVT && 5007 "Expected reduction output to be legalized to XLenVT"); 5008 5009 MVT ContainerVT = VecVT; 5010 if (VecVT.isFixedLengthVector()) { 5011 ContainerVT = getContainerForFixedLengthVector(VecVT); 5012 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5013 } 5014 5015 SDValue Mask, VL; 5016 if (IsVP) { 5017 Mask = Op.getOperand(2); 5018 VL = Op.getOperand(3); 5019 } else { 5020 std::tie(Mask, VL) = 5021 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5022 } 5023 5024 unsigned BaseOpc; 5025 ISD::CondCode CC; 5026 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5027 5028 switch (Op.getOpcode()) { 5029 default: 5030 llvm_unreachable("Unhandled reduction"); 5031 case ISD::VECREDUCE_AND: 5032 case ISD::VP_REDUCE_AND: { 5033 // vcpop ~x == 0 5034 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5035 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5036 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5037 CC = ISD::SETEQ; 5038 BaseOpc = ISD::AND; 5039 break; 5040 } 5041 case ISD::VECREDUCE_OR: 5042 case ISD::VP_REDUCE_OR: 5043 // vcpop x != 0 5044 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5045 CC = ISD::SETNE; 5046 BaseOpc = ISD::OR; 5047 break; 5048 case ISD::VECREDUCE_XOR: 5049 case ISD::VP_REDUCE_XOR: { 5050 // ((vcpop x) & 1) != 0 5051 SDValue One = DAG.getConstant(1, DL, XLenVT); 5052 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5053 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5054 CC = ISD::SETNE; 5055 BaseOpc = ISD::XOR; 5056 break; 5057 } 5058 } 5059 5060 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5061 5062 if (!IsVP) 5063 return SetCC; 5064 5065 // Now include the start value in the operation. 5066 // Note that we must return the start value when no elements are operated 5067 // upon. The vcpop instructions we've emitted in each case above will return 5068 // 0 for an inactive vector, and so we've already received the neutral value: 5069 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5070 // can simply include the start value. 5071 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5072 } 5073 5074 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5075 SelectionDAG &DAG) const { 5076 SDLoc DL(Op); 5077 SDValue Vec = Op.getOperand(0); 5078 EVT VecEVT = Vec.getValueType(); 5079 5080 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5081 5082 // Due to ordering in legalize types we may have a vector type that needs to 5083 // be split. Do that manually so we can get down to a legal type. 5084 while (getTypeAction(*DAG.getContext(), VecEVT) == 5085 TargetLowering::TypeSplitVector) { 5086 SDValue Lo, Hi; 5087 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5088 VecEVT = Lo.getValueType(); 5089 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5090 } 5091 5092 // TODO: The type may need to be widened rather than split. Or widened before 5093 // it can be split. 5094 if (!isTypeLegal(VecEVT)) 5095 return SDValue(); 5096 5097 MVT VecVT = VecEVT.getSimpleVT(); 5098 MVT VecEltVT = VecVT.getVectorElementType(); 5099 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5100 5101 MVT ContainerVT = VecVT; 5102 if (VecVT.isFixedLengthVector()) { 5103 ContainerVT = getContainerForFixedLengthVector(VecVT); 5104 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5105 } 5106 5107 MVT M1VT = getLMUL1VT(ContainerVT); 5108 MVT XLenVT = Subtarget.getXLenVT(); 5109 5110 SDValue Mask, VL; 5111 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5112 5113 SDValue NeutralElem = 5114 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5115 SDValue IdentitySplat = 5116 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5117 M1VT, DL, DAG, Subtarget); 5118 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5119 IdentitySplat, Mask, VL); 5120 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5121 DAG.getConstant(0, DL, XLenVT)); 5122 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5123 } 5124 5125 // Given a reduction op, this function returns the matching reduction opcode, 5126 // the vector SDValue and the scalar SDValue required to lower this to a 5127 // RISCVISD node. 5128 static std::tuple<unsigned, SDValue, SDValue> 5129 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5130 SDLoc DL(Op); 5131 auto Flags = Op->getFlags(); 5132 unsigned Opcode = Op.getOpcode(); 5133 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5134 switch (Opcode) { 5135 default: 5136 llvm_unreachable("Unhandled reduction"); 5137 case ISD::VECREDUCE_FADD: { 5138 // Use positive zero if we can. It is cheaper to materialize. 5139 SDValue Zero = 5140 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5141 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5142 } 5143 case ISD::VECREDUCE_SEQ_FADD: 5144 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5145 Op.getOperand(0)); 5146 case ISD::VECREDUCE_FMIN: 5147 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5148 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5149 case ISD::VECREDUCE_FMAX: 5150 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5151 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5152 } 5153 } 5154 5155 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5156 SelectionDAG &DAG) const { 5157 SDLoc DL(Op); 5158 MVT VecEltVT = Op.getSimpleValueType(); 5159 5160 unsigned RVVOpcode; 5161 SDValue VectorVal, ScalarVal; 5162 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5163 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5164 MVT VecVT = VectorVal.getSimpleValueType(); 5165 5166 MVT ContainerVT = VecVT; 5167 if (VecVT.isFixedLengthVector()) { 5168 ContainerVT = getContainerForFixedLengthVector(VecVT); 5169 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5170 } 5171 5172 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5173 MVT XLenVT = Subtarget.getXLenVT(); 5174 5175 SDValue Mask, VL; 5176 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5177 5178 SDValue ScalarSplat = 5179 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5180 M1VT, DL, DAG, Subtarget); 5181 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5182 VectorVal, ScalarSplat, Mask, VL); 5183 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5184 DAG.getConstant(0, DL, XLenVT)); 5185 } 5186 5187 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5188 switch (ISDOpcode) { 5189 default: 5190 llvm_unreachable("Unhandled reduction"); 5191 case ISD::VP_REDUCE_ADD: 5192 return RISCVISD::VECREDUCE_ADD_VL; 5193 case ISD::VP_REDUCE_UMAX: 5194 return RISCVISD::VECREDUCE_UMAX_VL; 5195 case ISD::VP_REDUCE_SMAX: 5196 return RISCVISD::VECREDUCE_SMAX_VL; 5197 case ISD::VP_REDUCE_UMIN: 5198 return RISCVISD::VECREDUCE_UMIN_VL; 5199 case ISD::VP_REDUCE_SMIN: 5200 return RISCVISD::VECREDUCE_SMIN_VL; 5201 case ISD::VP_REDUCE_AND: 5202 return RISCVISD::VECREDUCE_AND_VL; 5203 case ISD::VP_REDUCE_OR: 5204 return RISCVISD::VECREDUCE_OR_VL; 5205 case ISD::VP_REDUCE_XOR: 5206 return RISCVISD::VECREDUCE_XOR_VL; 5207 case ISD::VP_REDUCE_FADD: 5208 return RISCVISD::VECREDUCE_FADD_VL; 5209 case ISD::VP_REDUCE_SEQ_FADD: 5210 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5211 case ISD::VP_REDUCE_FMAX: 5212 return RISCVISD::VECREDUCE_FMAX_VL; 5213 case ISD::VP_REDUCE_FMIN: 5214 return RISCVISD::VECREDUCE_FMIN_VL; 5215 } 5216 } 5217 5218 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5219 SelectionDAG &DAG) const { 5220 SDLoc DL(Op); 5221 SDValue Vec = Op.getOperand(1); 5222 EVT VecEVT = Vec.getValueType(); 5223 5224 // TODO: The type may need to be widened rather than split. Or widened before 5225 // it can be split. 5226 if (!isTypeLegal(VecEVT)) 5227 return SDValue(); 5228 5229 MVT VecVT = VecEVT.getSimpleVT(); 5230 MVT VecEltVT = VecVT.getVectorElementType(); 5231 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5232 5233 MVT ContainerVT = VecVT; 5234 if (VecVT.isFixedLengthVector()) { 5235 ContainerVT = getContainerForFixedLengthVector(VecVT); 5236 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5237 } 5238 5239 SDValue VL = Op.getOperand(3); 5240 SDValue Mask = Op.getOperand(2); 5241 5242 MVT M1VT = getLMUL1VT(ContainerVT); 5243 MVT XLenVT = Subtarget.getXLenVT(); 5244 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5245 5246 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5247 DAG.getConstant(1, DL, XLenVT), M1VT, 5248 DL, DAG, Subtarget); 5249 SDValue Reduction = 5250 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5251 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5252 DAG.getConstant(0, DL, XLenVT)); 5253 if (!VecVT.isInteger()) 5254 return Elt0; 5255 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5256 } 5257 5258 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5259 SelectionDAG &DAG) const { 5260 SDValue Vec = Op.getOperand(0); 5261 SDValue SubVec = Op.getOperand(1); 5262 MVT VecVT = Vec.getSimpleValueType(); 5263 MVT SubVecVT = SubVec.getSimpleValueType(); 5264 5265 SDLoc DL(Op); 5266 MVT XLenVT = Subtarget.getXLenVT(); 5267 unsigned OrigIdx = Op.getConstantOperandVal(2); 5268 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5269 5270 // We don't have the ability to slide mask vectors up indexed by their i1 5271 // elements; the smallest we can do is i8. Often we are able to bitcast to 5272 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5273 // into a scalable one, we might not necessarily have enough scalable 5274 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5275 if (SubVecVT.getVectorElementType() == MVT::i1 && 5276 (OrigIdx != 0 || !Vec.isUndef())) { 5277 if (VecVT.getVectorMinNumElements() >= 8 && 5278 SubVecVT.getVectorMinNumElements() >= 8) { 5279 assert(OrigIdx % 8 == 0 && "Invalid index"); 5280 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5281 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5282 "Unexpected mask vector lowering"); 5283 OrigIdx /= 8; 5284 SubVecVT = 5285 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5286 SubVecVT.isScalableVector()); 5287 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5288 VecVT.isScalableVector()); 5289 Vec = DAG.getBitcast(VecVT, Vec); 5290 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5291 } else { 5292 // We can't slide this mask vector up indexed by its i1 elements. 5293 // This poses a problem when we wish to insert a scalable vector which 5294 // can't be re-expressed as a larger type. Just choose the slow path and 5295 // extend to a larger type, then truncate back down. 5296 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5297 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5298 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5299 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5300 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5301 Op.getOperand(2)); 5302 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5303 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5304 } 5305 } 5306 5307 // If the subvector vector is a fixed-length type, we cannot use subregister 5308 // manipulation to simplify the codegen; we don't know which register of a 5309 // LMUL group contains the specific subvector as we only know the minimum 5310 // register size. Therefore we must slide the vector group up the full 5311 // amount. 5312 if (SubVecVT.isFixedLengthVector()) { 5313 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5314 return Op; 5315 MVT ContainerVT = VecVT; 5316 if (VecVT.isFixedLengthVector()) { 5317 ContainerVT = getContainerForFixedLengthVector(VecVT); 5318 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5319 } 5320 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5321 DAG.getUNDEF(ContainerVT), SubVec, 5322 DAG.getConstant(0, DL, XLenVT)); 5323 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5324 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5325 return DAG.getBitcast(Op.getValueType(), SubVec); 5326 } 5327 SDValue Mask = 5328 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5329 // Set the vector length to only the number of elements we care about. Note 5330 // that for slideup this includes the offset. 5331 SDValue VL = 5332 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5333 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5334 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5335 SubVec, SlideupAmt, Mask, VL); 5336 if (VecVT.isFixedLengthVector()) 5337 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5338 return DAG.getBitcast(Op.getValueType(), Slideup); 5339 } 5340 5341 unsigned SubRegIdx, RemIdx; 5342 std::tie(SubRegIdx, RemIdx) = 5343 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5344 VecVT, SubVecVT, OrigIdx, TRI); 5345 5346 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5347 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5348 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5349 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5350 5351 // 1. If the Idx has been completely eliminated and this subvector's size is 5352 // a vector register or a multiple thereof, or the surrounding elements are 5353 // undef, then this is a subvector insert which naturally aligns to a vector 5354 // register. These can easily be handled using subregister manipulation. 5355 // 2. If the subvector is smaller than a vector register, then the insertion 5356 // must preserve the undisturbed elements of the register. We do this by 5357 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5358 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5359 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5360 // LMUL=1 type back into the larger vector (resolving to another subregister 5361 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5362 // to avoid allocating a large register group to hold our subvector. 5363 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5364 return Op; 5365 5366 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5367 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5368 // (in our case undisturbed). This means we can set up a subvector insertion 5369 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5370 // size of the subvector. 5371 MVT InterSubVT = VecVT; 5372 SDValue AlignedExtract = Vec; 5373 unsigned AlignedIdx = OrigIdx - RemIdx; 5374 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5375 InterSubVT = getLMUL1VT(VecVT); 5376 // Extract a subvector equal to the nearest full vector register type. This 5377 // should resolve to a EXTRACT_SUBREG instruction. 5378 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5379 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5380 } 5381 5382 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5383 // For scalable vectors this must be further multiplied by vscale. 5384 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5385 5386 SDValue Mask, VL; 5387 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5388 5389 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5390 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5391 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5392 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5393 5394 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5395 DAG.getUNDEF(InterSubVT), SubVec, 5396 DAG.getConstant(0, DL, XLenVT)); 5397 5398 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5399 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5400 5401 // If required, insert this subvector back into the correct vector register. 5402 // This should resolve to an INSERT_SUBREG instruction. 5403 if (VecVT.bitsGT(InterSubVT)) 5404 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5405 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5406 5407 // We might have bitcast from a mask type: cast back to the original type if 5408 // required. 5409 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5410 } 5411 5412 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5413 SelectionDAG &DAG) const { 5414 SDValue Vec = Op.getOperand(0); 5415 MVT SubVecVT = Op.getSimpleValueType(); 5416 MVT VecVT = Vec.getSimpleValueType(); 5417 5418 SDLoc DL(Op); 5419 MVT XLenVT = Subtarget.getXLenVT(); 5420 unsigned OrigIdx = Op.getConstantOperandVal(1); 5421 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5422 5423 // We don't have the ability to slide mask vectors down indexed by their i1 5424 // elements; the smallest we can do is i8. Often we are able to bitcast to 5425 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5426 // from a scalable one, we might not necessarily have enough scalable 5427 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5428 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5429 if (VecVT.getVectorMinNumElements() >= 8 && 5430 SubVecVT.getVectorMinNumElements() >= 8) { 5431 assert(OrigIdx % 8 == 0 && "Invalid index"); 5432 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5433 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5434 "Unexpected mask vector lowering"); 5435 OrigIdx /= 8; 5436 SubVecVT = 5437 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5438 SubVecVT.isScalableVector()); 5439 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5440 VecVT.isScalableVector()); 5441 Vec = DAG.getBitcast(VecVT, Vec); 5442 } else { 5443 // We can't slide this mask vector down, indexed by its i1 elements. 5444 // This poses a problem when we wish to extract a scalable vector which 5445 // can't be re-expressed as a larger type. Just choose the slow path and 5446 // extend to a larger type, then truncate back down. 5447 // TODO: We could probably improve this when extracting certain fixed 5448 // from fixed, where we can extract as i8 and shift the correct element 5449 // right to reach the desired subvector? 5450 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5451 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5452 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5453 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5454 Op.getOperand(1)); 5455 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5456 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5457 } 5458 } 5459 5460 // If the subvector vector is a fixed-length type, we cannot use subregister 5461 // manipulation to simplify the codegen; we don't know which register of a 5462 // LMUL group contains the specific subvector as we only know the minimum 5463 // register size. Therefore we must slide the vector group down the full 5464 // amount. 5465 if (SubVecVT.isFixedLengthVector()) { 5466 // With an index of 0 this is a cast-like subvector, which can be performed 5467 // with subregister operations. 5468 if (OrigIdx == 0) 5469 return Op; 5470 MVT ContainerVT = VecVT; 5471 if (VecVT.isFixedLengthVector()) { 5472 ContainerVT = getContainerForFixedLengthVector(VecVT); 5473 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5474 } 5475 SDValue Mask = 5476 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5477 // Set the vector length to only the number of elements we care about. This 5478 // avoids sliding down elements we're going to discard straight away. 5479 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5480 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5481 SDValue Slidedown = 5482 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5483 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5484 // Now we can use a cast-like subvector extract to get the result. 5485 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5486 DAG.getConstant(0, DL, XLenVT)); 5487 return DAG.getBitcast(Op.getValueType(), Slidedown); 5488 } 5489 5490 unsigned SubRegIdx, RemIdx; 5491 std::tie(SubRegIdx, RemIdx) = 5492 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5493 VecVT, SubVecVT, OrigIdx, TRI); 5494 5495 // If the Idx has been completely eliminated then this is a subvector extract 5496 // which naturally aligns to a vector register. These can easily be handled 5497 // using subregister manipulation. 5498 if (RemIdx == 0) 5499 return Op; 5500 5501 // Else we must shift our vector register directly to extract the subvector. 5502 // Do this using VSLIDEDOWN. 5503 5504 // If the vector type is an LMUL-group type, extract a subvector equal to the 5505 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5506 // instruction. 5507 MVT InterSubVT = VecVT; 5508 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5509 InterSubVT = getLMUL1VT(VecVT); 5510 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5511 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5512 } 5513 5514 // Slide this vector register down by the desired number of elements in order 5515 // to place the desired subvector starting at element 0. 5516 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5517 // For scalable vectors this must be further multiplied by vscale. 5518 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5519 5520 SDValue Mask, VL; 5521 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5522 SDValue Slidedown = 5523 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5524 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5525 5526 // Now the vector is in the right position, extract our final subvector. This 5527 // should resolve to a COPY. 5528 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5529 DAG.getConstant(0, DL, XLenVT)); 5530 5531 // We might have bitcast from a mask type: cast back to the original type if 5532 // required. 5533 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5534 } 5535 5536 // Lower step_vector to the vid instruction. Any non-identity step value must 5537 // be accounted for my manual expansion. 5538 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5539 SelectionDAG &DAG) const { 5540 SDLoc DL(Op); 5541 MVT VT = Op.getSimpleValueType(); 5542 MVT XLenVT = Subtarget.getXLenVT(); 5543 SDValue Mask, VL; 5544 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5545 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5546 uint64_t StepValImm = Op.getConstantOperandVal(0); 5547 if (StepValImm != 1) { 5548 if (isPowerOf2_64(StepValImm)) { 5549 SDValue StepVal = 5550 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5551 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5552 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5553 } else { 5554 SDValue StepVal = lowerScalarSplat( 5555 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5556 VL, VT, DL, DAG, Subtarget); 5557 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5558 } 5559 } 5560 return StepVec; 5561 } 5562 5563 // Implement vector_reverse using vrgather.vv with indices determined by 5564 // subtracting the id of each element from (VLMAX-1). This will convert 5565 // the indices like so: 5566 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5567 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5568 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5569 SelectionDAG &DAG) const { 5570 SDLoc DL(Op); 5571 MVT VecVT = Op.getSimpleValueType(); 5572 unsigned EltSize = VecVT.getScalarSizeInBits(); 5573 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5574 5575 unsigned MaxVLMAX = 0; 5576 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5577 if (VectorBitsMax != 0) 5578 MaxVLMAX = 5579 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5580 5581 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5582 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5583 5584 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5585 // to use vrgatherei16.vv. 5586 // TODO: It's also possible to use vrgatherei16.vv for other types to 5587 // decrease register width for the index calculation. 5588 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5589 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5590 // Reverse each half, then reassemble them in reverse order. 5591 // NOTE: It's also possible that after splitting that VLMAX no longer 5592 // requires vrgatherei16.vv. 5593 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5594 SDValue Lo, Hi; 5595 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5596 EVT LoVT, HiVT; 5597 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5598 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5599 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5600 // Reassemble the low and high pieces reversed. 5601 // FIXME: This is a CONCAT_VECTORS. 5602 SDValue Res = 5603 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5604 DAG.getIntPtrConstant(0, DL)); 5605 return DAG.getNode( 5606 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5607 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5608 } 5609 5610 // Just promote the int type to i16 which will double the LMUL. 5611 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5612 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5613 } 5614 5615 MVT XLenVT = Subtarget.getXLenVT(); 5616 SDValue Mask, VL; 5617 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5618 5619 // Calculate VLMAX-1 for the desired SEW. 5620 unsigned MinElts = VecVT.getVectorMinNumElements(); 5621 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5622 DAG.getConstant(MinElts, DL, XLenVT)); 5623 SDValue VLMinus1 = 5624 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5625 5626 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5627 bool IsRV32E64 = 5628 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5629 SDValue SplatVL; 5630 if (!IsRV32E64) 5631 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5632 else 5633 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5634 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5635 5636 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5637 SDValue Indices = 5638 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5639 5640 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5641 } 5642 5643 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5644 SelectionDAG &DAG) const { 5645 SDLoc DL(Op); 5646 SDValue V1 = Op.getOperand(0); 5647 SDValue V2 = Op.getOperand(1); 5648 MVT XLenVT = Subtarget.getXLenVT(); 5649 MVT VecVT = Op.getSimpleValueType(); 5650 5651 unsigned MinElts = VecVT.getVectorMinNumElements(); 5652 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5653 DAG.getConstant(MinElts, DL, XLenVT)); 5654 5655 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5656 SDValue DownOffset, UpOffset; 5657 if (ImmValue >= 0) { 5658 // The operand is a TargetConstant, we need to rebuild it as a regular 5659 // constant. 5660 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5661 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5662 } else { 5663 // The operand is a TargetConstant, we need to rebuild it as a regular 5664 // constant rather than negating the original operand. 5665 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5666 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5667 } 5668 5669 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5670 5671 SDValue SlideDown = 5672 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5673 DownOffset, TrueMask, UpOffset); 5674 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5675 TrueMask, 5676 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5677 } 5678 5679 SDValue 5680 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5681 SelectionDAG &DAG) const { 5682 SDLoc DL(Op); 5683 auto *Load = cast<LoadSDNode>(Op); 5684 5685 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5686 Load->getMemoryVT(), 5687 *Load->getMemOperand()) && 5688 "Expecting a correctly-aligned load"); 5689 5690 MVT VT = Op.getSimpleValueType(); 5691 MVT XLenVT = Subtarget.getXLenVT(); 5692 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5693 5694 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5695 5696 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5697 SDValue IntID = DAG.getTargetConstant( 5698 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5699 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5700 if (!IsMaskOp) 5701 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5702 Ops.push_back(Load->getBasePtr()); 5703 Ops.push_back(VL); 5704 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5705 SDValue NewLoad = 5706 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5707 Load->getMemoryVT(), Load->getMemOperand()); 5708 5709 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5710 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5711 } 5712 5713 SDValue 5714 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5715 SelectionDAG &DAG) const { 5716 SDLoc DL(Op); 5717 auto *Store = cast<StoreSDNode>(Op); 5718 5719 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5720 Store->getMemoryVT(), 5721 *Store->getMemOperand()) && 5722 "Expecting a correctly-aligned store"); 5723 5724 SDValue StoreVal = Store->getValue(); 5725 MVT VT = StoreVal.getSimpleValueType(); 5726 MVT XLenVT = Subtarget.getXLenVT(); 5727 5728 // If the size less than a byte, we need to pad with zeros to make a byte. 5729 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5730 VT = MVT::v8i1; 5731 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5732 DAG.getConstant(0, DL, VT), StoreVal, 5733 DAG.getIntPtrConstant(0, DL)); 5734 } 5735 5736 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5737 5738 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5739 5740 SDValue NewValue = 5741 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5742 5743 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5744 SDValue IntID = DAG.getTargetConstant( 5745 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5746 return DAG.getMemIntrinsicNode( 5747 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5748 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5749 Store->getMemoryVT(), Store->getMemOperand()); 5750 } 5751 5752 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5753 SelectionDAG &DAG) const { 5754 SDLoc DL(Op); 5755 MVT VT = Op.getSimpleValueType(); 5756 5757 const auto *MemSD = cast<MemSDNode>(Op); 5758 EVT MemVT = MemSD->getMemoryVT(); 5759 MachineMemOperand *MMO = MemSD->getMemOperand(); 5760 SDValue Chain = MemSD->getChain(); 5761 SDValue BasePtr = MemSD->getBasePtr(); 5762 5763 SDValue Mask, PassThru, VL; 5764 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5765 Mask = VPLoad->getMask(); 5766 PassThru = DAG.getUNDEF(VT); 5767 VL = VPLoad->getVectorLength(); 5768 } else { 5769 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5770 Mask = MLoad->getMask(); 5771 PassThru = MLoad->getPassThru(); 5772 } 5773 5774 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5775 5776 MVT XLenVT = Subtarget.getXLenVT(); 5777 5778 MVT ContainerVT = VT; 5779 if (VT.isFixedLengthVector()) { 5780 ContainerVT = getContainerForFixedLengthVector(VT); 5781 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5782 if (!IsUnmasked) { 5783 MVT MaskVT = getMaskTypeFor(ContainerVT); 5784 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5785 } 5786 } 5787 5788 if (!VL) 5789 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5790 5791 unsigned IntID = 5792 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5793 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5794 if (IsUnmasked) 5795 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5796 else 5797 Ops.push_back(PassThru); 5798 Ops.push_back(BasePtr); 5799 if (!IsUnmasked) 5800 Ops.push_back(Mask); 5801 Ops.push_back(VL); 5802 if (!IsUnmasked) 5803 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5804 5805 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5806 5807 SDValue Result = 5808 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5809 Chain = Result.getValue(1); 5810 5811 if (VT.isFixedLengthVector()) 5812 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5813 5814 return DAG.getMergeValues({Result, Chain}, DL); 5815 } 5816 5817 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5818 SelectionDAG &DAG) const { 5819 SDLoc DL(Op); 5820 5821 const auto *MemSD = cast<MemSDNode>(Op); 5822 EVT MemVT = MemSD->getMemoryVT(); 5823 MachineMemOperand *MMO = MemSD->getMemOperand(); 5824 SDValue Chain = MemSD->getChain(); 5825 SDValue BasePtr = MemSD->getBasePtr(); 5826 SDValue Val, Mask, VL; 5827 5828 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5829 Val = VPStore->getValue(); 5830 Mask = VPStore->getMask(); 5831 VL = VPStore->getVectorLength(); 5832 } else { 5833 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5834 Val = MStore->getValue(); 5835 Mask = MStore->getMask(); 5836 } 5837 5838 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5839 5840 MVT VT = Val.getSimpleValueType(); 5841 MVT XLenVT = Subtarget.getXLenVT(); 5842 5843 MVT ContainerVT = VT; 5844 if (VT.isFixedLengthVector()) { 5845 ContainerVT = getContainerForFixedLengthVector(VT); 5846 5847 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5848 if (!IsUnmasked) { 5849 MVT MaskVT = getMaskTypeFor(ContainerVT); 5850 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5851 } 5852 } 5853 5854 if (!VL) 5855 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5856 5857 unsigned IntID = 5858 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5859 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5860 Ops.push_back(Val); 5861 Ops.push_back(BasePtr); 5862 if (!IsUnmasked) 5863 Ops.push_back(Mask); 5864 Ops.push_back(VL); 5865 5866 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5867 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5868 } 5869 5870 SDValue 5871 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5872 SelectionDAG &DAG) const { 5873 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5874 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5875 5876 MVT VT = Op.getSimpleValueType(); 5877 5878 SDValue Op1 = 5879 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5880 SDValue Op2 = 5881 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5882 5883 SDLoc DL(Op); 5884 SDValue VL = 5885 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5886 5887 MVT MaskVT = getMaskTypeFor(ContainerVT); 5888 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 5889 5890 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5891 Op.getOperand(2), Mask, VL); 5892 5893 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5894 } 5895 5896 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5897 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5898 MVT VT = Op.getSimpleValueType(); 5899 5900 if (VT.getVectorElementType() == MVT::i1) 5901 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5902 5903 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5904 } 5905 5906 SDValue 5907 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5908 SelectionDAG &DAG) const { 5909 unsigned Opc; 5910 switch (Op.getOpcode()) { 5911 default: llvm_unreachable("Unexpected opcode!"); 5912 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5913 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5914 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5915 } 5916 5917 return lowerToScalableOp(Op, DAG, Opc); 5918 } 5919 5920 // Lower vector ABS to smax(X, sub(0, X)). 5921 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5922 SDLoc DL(Op); 5923 MVT VT = Op.getSimpleValueType(); 5924 SDValue X = Op.getOperand(0); 5925 5926 assert(VT.isFixedLengthVector() && "Unexpected type"); 5927 5928 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5929 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5930 5931 SDValue Mask, VL; 5932 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5933 5934 SDValue SplatZero = DAG.getNode( 5935 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5936 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5937 SDValue NegX = 5938 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5939 SDValue Max = 5940 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5941 5942 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5943 } 5944 5945 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5946 SDValue Op, SelectionDAG &DAG) const { 5947 SDLoc DL(Op); 5948 MVT VT = Op.getSimpleValueType(); 5949 SDValue Mag = Op.getOperand(0); 5950 SDValue Sign = Op.getOperand(1); 5951 assert(Mag.getValueType() == Sign.getValueType() && 5952 "Can only handle COPYSIGN with matching types."); 5953 5954 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5955 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5956 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5957 5958 SDValue Mask, VL; 5959 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5960 5961 SDValue CopySign = 5962 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5963 5964 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5965 } 5966 5967 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5968 SDValue Op, SelectionDAG &DAG) const { 5969 MVT VT = Op.getSimpleValueType(); 5970 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5971 5972 MVT I1ContainerVT = 5973 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5974 5975 SDValue CC = 5976 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5977 SDValue Op1 = 5978 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5979 SDValue Op2 = 5980 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5981 5982 SDLoc DL(Op); 5983 SDValue Mask, VL; 5984 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5985 5986 SDValue Select = 5987 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5988 5989 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5990 } 5991 5992 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5993 unsigned NewOpc, 5994 bool HasMask) const { 5995 MVT VT = Op.getSimpleValueType(); 5996 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5997 5998 // Create list of operands by converting existing ones to scalable types. 5999 SmallVector<SDValue, 6> Ops; 6000 for (const SDValue &V : Op->op_values()) { 6001 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6002 6003 // Pass through non-vector operands. 6004 if (!V.getValueType().isVector()) { 6005 Ops.push_back(V); 6006 continue; 6007 } 6008 6009 // "cast" fixed length vector to a scalable vector. 6010 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6011 "Only fixed length vectors are supported!"); 6012 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6013 } 6014 6015 SDLoc DL(Op); 6016 SDValue Mask, VL; 6017 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6018 if (HasMask) 6019 Ops.push_back(Mask); 6020 Ops.push_back(VL); 6021 6022 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6023 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6024 } 6025 6026 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6027 // * Operands of each node are assumed to be in the same order. 6028 // * The EVL operand is promoted from i32 to i64 on RV64. 6029 // * Fixed-length vectors are converted to their scalable-vector container 6030 // types. 6031 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6032 unsigned RISCVISDOpc) const { 6033 SDLoc DL(Op); 6034 MVT VT = Op.getSimpleValueType(); 6035 SmallVector<SDValue, 4> Ops; 6036 6037 for (const auto &OpIdx : enumerate(Op->ops())) { 6038 SDValue V = OpIdx.value(); 6039 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6040 // Pass through operands which aren't fixed-length vectors. 6041 if (!V.getValueType().isFixedLengthVector()) { 6042 Ops.push_back(V); 6043 continue; 6044 } 6045 // "cast" fixed length vector to a scalable vector. 6046 MVT OpVT = V.getSimpleValueType(); 6047 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6048 assert(useRVVForFixedLengthVectorVT(OpVT) && 6049 "Only fixed length vectors are supported!"); 6050 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6051 } 6052 6053 if (!VT.isFixedLengthVector()) 6054 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags()); 6055 6056 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6057 6058 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags()); 6059 6060 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6061 } 6062 6063 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6064 SelectionDAG &DAG) const { 6065 SDLoc DL(Op); 6066 MVT VT = Op.getSimpleValueType(); 6067 6068 SDValue Src = Op.getOperand(0); 6069 // NOTE: Mask is dropped. 6070 SDValue VL = Op.getOperand(2); 6071 6072 MVT ContainerVT = VT; 6073 if (VT.isFixedLengthVector()) { 6074 ContainerVT = getContainerForFixedLengthVector(VT); 6075 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6076 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6077 } 6078 6079 MVT XLenVT = Subtarget.getXLenVT(); 6080 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6081 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6082 DAG.getUNDEF(ContainerVT), Zero, VL); 6083 6084 SDValue SplatValue = DAG.getConstant( 6085 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6086 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6087 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6088 6089 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6090 Splat, ZeroSplat, VL); 6091 if (!VT.isFixedLengthVector()) 6092 return Result; 6093 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6094 } 6095 6096 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6097 SelectionDAG &DAG) const { 6098 SDLoc DL(Op); 6099 MVT VT = Op.getSimpleValueType(); 6100 6101 SDValue Op1 = Op.getOperand(0); 6102 SDValue Op2 = Op.getOperand(1); 6103 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6104 // NOTE: Mask is dropped. 6105 SDValue VL = Op.getOperand(4); 6106 6107 MVT ContainerVT = VT; 6108 if (VT.isFixedLengthVector()) { 6109 ContainerVT = getContainerForFixedLengthVector(VT); 6110 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6111 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6112 } 6113 6114 SDValue Result; 6115 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6116 6117 switch (Condition) { 6118 default: 6119 break; 6120 // X != Y --> (X^Y) 6121 case ISD::SETNE: 6122 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6123 break; 6124 // X == Y --> ~(X^Y) 6125 case ISD::SETEQ: { 6126 SDValue Temp = 6127 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6128 Result = 6129 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6130 break; 6131 } 6132 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6133 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6134 case ISD::SETGT: 6135 case ISD::SETULT: { 6136 SDValue Temp = 6137 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6138 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6139 break; 6140 } 6141 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6142 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6143 case ISD::SETLT: 6144 case ISD::SETUGT: { 6145 SDValue Temp = 6146 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6147 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6148 break; 6149 } 6150 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6151 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6152 case ISD::SETGE: 6153 case ISD::SETULE: { 6154 SDValue Temp = 6155 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6156 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6157 break; 6158 } 6159 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6160 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6161 case ISD::SETLE: 6162 case ISD::SETUGE: { 6163 SDValue Temp = 6164 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6165 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6166 break; 6167 } 6168 } 6169 6170 if (!VT.isFixedLengthVector()) 6171 return Result; 6172 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6173 } 6174 6175 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6176 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6177 unsigned RISCVISDOpc) const { 6178 SDLoc DL(Op); 6179 6180 SDValue Src = Op.getOperand(0); 6181 SDValue Mask = Op.getOperand(1); 6182 SDValue VL = Op.getOperand(2); 6183 6184 MVT DstVT = Op.getSimpleValueType(); 6185 MVT SrcVT = Src.getSimpleValueType(); 6186 if (DstVT.isFixedLengthVector()) { 6187 DstVT = getContainerForFixedLengthVector(DstVT); 6188 SrcVT = getContainerForFixedLengthVector(SrcVT); 6189 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6190 MVT MaskVT = getMaskTypeFor(DstVT); 6191 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6192 } 6193 6194 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6195 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6196 ? RISCVISD::VSEXT_VL 6197 : RISCVISD::VZEXT_VL; 6198 6199 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6200 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6201 6202 SDValue Result; 6203 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6204 if (SrcVT.isInteger()) { 6205 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6206 6207 // Do we need to do any pre-widening before converting? 6208 if (SrcEltSize == 1) { 6209 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6210 MVT XLenVT = Subtarget.getXLenVT(); 6211 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6212 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6213 DAG.getUNDEF(IntVT), Zero, VL); 6214 SDValue One = DAG.getConstant( 6215 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6216 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6217 DAG.getUNDEF(IntVT), One, VL); 6218 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6219 ZeroSplat, VL); 6220 } else if (DstEltSize > (2 * SrcEltSize)) { 6221 // Widen before converting. 6222 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6223 DstVT.getVectorElementCount()); 6224 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6225 } 6226 6227 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6228 } else { 6229 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6230 "Wrong input/output vector types"); 6231 6232 // Convert f16 to f32 then convert f32 to i64. 6233 if (DstEltSize > (2 * SrcEltSize)) { 6234 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6235 MVT InterimFVT = 6236 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6237 Src = 6238 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6239 } 6240 6241 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6242 } 6243 } else { // Narrowing + Conversion 6244 if (SrcVT.isInteger()) { 6245 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6246 // First do a narrowing convert to an FP type half the size, then round 6247 // the FP type to a small FP type if needed. 6248 6249 MVT InterimFVT = DstVT; 6250 if (SrcEltSize > (2 * DstEltSize)) { 6251 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6252 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6253 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6254 } 6255 6256 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6257 6258 if (InterimFVT != DstVT) { 6259 Src = Result; 6260 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6261 } 6262 } else { 6263 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6264 "Wrong input/output vector types"); 6265 // First do a narrowing conversion to an integer half the size, then 6266 // truncate if needed. 6267 6268 if (DstEltSize == 1) { 6269 // First convert to the same size integer, then convert to mask using 6270 // setcc. 6271 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6272 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6273 DstVT.getVectorElementCount()); 6274 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6275 6276 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6277 // otherwise the conversion was undefined. 6278 MVT XLenVT = Subtarget.getXLenVT(); 6279 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6280 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6281 DAG.getUNDEF(InterimIVT), SplatZero); 6282 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6283 DAG.getCondCode(ISD::SETNE), Mask, VL); 6284 } else { 6285 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6286 DstVT.getVectorElementCount()); 6287 6288 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6289 6290 while (InterimIVT != DstVT) { 6291 SrcEltSize /= 2; 6292 Src = Result; 6293 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6294 DstVT.getVectorElementCount()); 6295 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6296 Src, Mask, VL); 6297 } 6298 } 6299 } 6300 } 6301 6302 MVT VT = Op.getSimpleValueType(); 6303 if (!VT.isFixedLengthVector()) 6304 return Result; 6305 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6306 } 6307 6308 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6309 unsigned MaskOpc, 6310 unsigned VecOpc) const { 6311 MVT VT = Op.getSimpleValueType(); 6312 if (VT.getVectorElementType() != MVT::i1) 6313 return lowerVPOp(Op, DAG, VecOpc); 6314 6315 // It is safe to drop mask parameter as masked-off elements are undef. 6316 SDValue Op1 = Op->getOperand(0); 6317 SDValue Op2 = Op->getOperand(1); 6318 SDValue VL = Op->getOperand(3); 6319 6320 MVT ContainerVT = VT; 6321 const bool IsFixed = VT.isFixedLengthVector(); 6322 if (IsFixed) { 6323 ContainerVT = getContainerForFixedLengthVector(VT); 6324 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6325 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6326 } 6327 6328 SDLoc DL(Op); 6329 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6330 if (!IsFixed) 6331 return Val; 6332 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6333 } 6334 6335 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6336 // matched to a RVV indexed load. The RVV indexed load instructions only 6337 // support the "unsigned unscaled" addressing mode; indices are implicitly 6338 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6339 // signed or scaled indexing is extended to the XLEN value type and scaled 6340 // accordingly. 6341 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6342 SelectionDAG &DAG) const { 6343 SDLoc DL(Op); 6344 MVT VT = Op.getSimpleValueType(); 6345 6346 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6347 EVT MemVT = MemSD->getMemoryVT(); 6348 MachineMemOperand *MMO = MemSD->getMemOperand(); 6349 SDValue Chain = MemSD->getChain(); 6350 SDValue BasePtr = MemSD->getBasePtr(); 6351 6352 ISD::LoadExtType LoadExtType; 6353 SDValue Index, Mask, PassThru, VL; 6354 6355 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6356 Index = VPGN->getIndex(); 6357 Mask = VPGN->getMask(); 6358 PassThru = DAG.getUNDEF(VT); 6359 VL = VPGN->getVectorLength(); 6360 // VP doesn't support extending loads. 6361 LoadExtType = ISD::NON_EXTLOAD; 6362 } else { 6363 // Else it must be a MGATHER. 6364 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6365 Index = MGN->getIndex(); 6366 Mask = MGN->getMask(); 6367 PassThru = MGN->getPassThru(); 6368 LoadExtType = MGN->getExtensionType(); 6369 } 6370 6371 MVT IndexVT = Index.getSimpleValueType(); 6372 MVT XLenVT = Subtarget.getXLenVT(); 6373 6374 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6375 "Unexpected VTs!"); 6376 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6377 // Targets have to explicitly opt-in for extending vector loads. 6378 assert(LoadExtType == ISD::NON_EXTLOAD && 6379 "Unexpected extending MGATHER/VP_GATHER"); 6380 (void)LoadExtType; 6381 6382 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6383 // the selection of the masked intrinsics doesn't do this for us. 6384 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6385 6386 MVT ContainerVT = VT; 6387 if (VT.isFixedLengthVector()) { 6388 // We need to use the larger of the result and index type to determine the 6389 // scalable type to use so we don't increase LMUL for any operand/result. 6390 if (VT.bitsGE(IndexVT)) { 6391 ContainerVT = getContainerForFixedLengthVector(VT); 6392 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6393 ContainerVT.getVectorElementCount()); 6394 } else { 6395 IndexVT = getContainerForFixedLengthVector(IndexVT); 6396 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6397 IndexVT.getVectorElementCount()); 6398 } 6399 6400 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6401 6402 if (!IsUnmasked) { 6403 MVT MaskVT = getMaskTypeFor(ContainerVT); 6404 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6405 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6406 } 6407 } 6408 6409 if (!VL) 6410 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6411 6412 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6413 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6414 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6415 VL); 6416 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6417 TrueMask, VL); 6418 } 6419 6420 unsigned IntID = 6421 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6422 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6423 if (IsUnmasked) 6424 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6425 else 6426 Ops.push_back(PassThru); 6427 Ops.push_back(BasePtr); 6428 Ops.push_back(Index); 6429 if (!IsUnmasked) 6430 Ops.push_back(Mask); 6431 Ops.push_back(VL); 6432 if (!IsUnmasked) 6433 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6434 6435 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6436 SDValue Result = 6437 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6438 Chain = Result.getValue(1); 6439 6440 if (VT.isFixedLengthVector()) 6441 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6442 6443 return DAG.getMergeValues({Result, Chain}, DL); 6444 } 6445 6446 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6447 // matched to a RVV indexed store. The RVV indexed store instructions only 6448 // support the "unsigned unscaled" addressing mode; indices are implicitly 6449 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6450 // signed or scaled indexing is extended to the XLEN value type and scaled 6451 // accordingly. 6452 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6453 SelectionDAG &DAG) const { 6454 SDLoc DL(Op); 6455 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6456 EVT MemVT = MemSD->getMemoryVT(); 6457 MachineMemOperand *MMO = MemSD->getMemOperand(); 6458 SDValue Chain = MemSD->getChain(); 6459 SDValue BasePtr = MemSD->getBasePtr(); 6460 6461 bool IsTruncatingStore = false; 6462 SDValue Index, Mask, Val, VL; 6463 6464 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6465 Index = VPSN->getIndex(); 6466 Mask = VPSN->getMask(); 6467 Val = VPSN->getValue(); 6468 VL = VPSN->getVectorLength(); 6469 // VP doesn't support truncating stores. 6470 IsTruncatingStore = false; 6471 } else { 6472 // Else it must be a MSCATTER. 6473 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6474 Index = MSN->getIndex(); 6475 Mask = MSN->getMask(); 6476 Val = MSN->getValue(); 6477 IsTruncatingStore = MSN->isTruncatingStore(); 6478 } 6479 6480 MVT VT = Val.getSimpleValueType(); 6481 MVT IndexVT = Index.getSimpleValueType(); 6482 MVT XLenVT = Subtarget.getXLenVT(); 6483 6484 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6485 "Unexpected VTs!"); 6486 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6487 // Targets have to explicitly opt-in for extending vector loads and 6488 // truncating vector stores. 6489 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6490 (void)IsTruncatingStore; 6491 6492 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6493 // the selection of the masked intrinsics doesn't do this for us. 6494 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6495 6496 MVT ContainerVT = VT; 6497 if (VT.isFixedLengthVector()) { 6498 // We need to use the larger of the value and index type to determine the 6499 // scalable type to use so we don't increase LMUL for any operand/result. 6500 if (VT.bitsGE(IndexVT)) { 6501 ContainerVT = getContainerForFixedLengthVector(VT); 6502 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6503 ContainerVT.getVectorElementCount()); 6504 } else { 6505 IndexVT = getContainerForFixedLengthVector(IndexVT); 6506 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6507 IndexVT.getVectorElementCount()); 6508 } 6509 6510 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6511 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6512 6513 if (!IsUnmasked) { 6514 MVT MaskVT = getMaskTypeFor(ContainerVT); 6515 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6516 } 6517 } 6518 6519 if (!VL) 6520 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6521 6522 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6523 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6524 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6525 VL); 6526 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6527 TrueMask, VL); 6528 } 6529 6530 unsigned IntID = 6531 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6532 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6533 Ops.push_back(Val); 6534 Ops.push_back(BasePtr); 6535 Ops.push_back(Index); 6536 if (!IsUnmasked) 6537 Ops.push_back(Mask); 6538 Ops.push_back(VL); 6539 6540 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6541 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6542 } 6543 6544 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6545 SelectionDAG &DAG) const { 6546 const MVT XLenVT = Subtarget.getXLenVT(); 6547 SDLoc DL(Op); 6548 SDValue Chain = Op->getOperand(0); 6549 SDValue SysRegNo = DAG.getTargetConstant( 6550 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6551 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6552 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6553 6554 // Encoding used for rounding mode in RISCV differs from that used in 6555 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6556 // table, which consists of a sequence of 4-bit fields, each representing 6557 // corresponding FLT_ROUNDS mode. 6558 static const int Table = 6559 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6560 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6561 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6562 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6563 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6564 6565 SDValue Shift = 6566 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6567 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6568 DAG.getConstant(Table, DL, XLenVT), Shift); 6569 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6570 DAG.getConstant(7, DL, XLenVT)); 6571 6572 return DAG.getMergeValues({Masked, Chain}, DL); 6573 } 6574 6575 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6576 SelectionDAG &DAG) const { 6577 const MVT XLenVT = Subtarget.getXLenVT(); 6578 SDLoc DL(Op); 6579 SDValue Chain = Op->getOperand(0); 6580 SDValue RMValue = Op->getOperand(1); 6581 SDValue SysRegNo = DAG.getTargetConstant( 6582 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6583 6584 // Encoding used for rounding mode in RISCV differs from that used in 6585 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6586 // a table, which consists of a sequence of 4-bit fields, each representing 6587 // corresponding RISCV mode. 6588 static const unsigned Table = 6589 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6590 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6591 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6592 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6593 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6594 6595 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6596 DAG.getConstant(2, DL, XLenVT)); 6597 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6598 DAG.getConstant(Table, DL, XLenVT), Shift); 6599 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6600 DAG.getConstant(0x7, DL, XLenVT)); 6601 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6602 RMValue); 6603 } 6604 6605 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6606 switch (IntNo) { 6607 default: 6608 llvm_unreachable("Unexpected Intrinsic"); 6609 case Intrinsic::riscv_bcompress: 6610 return RISCVISD::BCOMPRESSW; 6611 case Intrinsic::riscv_bdecompress: 6612 return RISCVISD::BDECOMPRESSW; 6613 case Intrinsic::riscv_bfp: 6614 return RISCVISD::BFPW; 6615 case Intrinsic::riscv_fsl: 6616 return RISCVISD::FSLW; 6617 case Intrinsic::riscv_fsr: 6618 return RISCVISD::FSRW; 6619 } 6620 } 6621 6622 // Converts the given intrinsic to a i64 operation with any extension. 6623 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6624 unsigned IntNo) { 6625 SDLoc DL(N); 6626 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6627 // Deal with the Instruction Operands 6628 SmallVector<SDValue, 3> NewOps; 6629 for (SDValue Op : drop_begin(N->ops())) 6630 // Promote the operand to i64 type 6631 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6632 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6633 // ReplaceNodeResults requires we maintain the same type for the return value. 6634 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6635 } 6636 6637 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6638 // form of the given Opcode. 6639 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6640 switch (Opcode) { 6641 default: 6642 llvm_unreachable("Unexpected opcode"); 6643 case ISD::SHL: 6644 return RISCVISD::SLLW; 6645 case ISD::SRA: 6646 return RISCVISD::SRAW; 6647 case ISD::SRL: 6648 return RISCVISD::SRLW; 6649 case ISD::SDIV: 6650 return RISCVISD::DIVW; 6651 case ISD::UDIV: 6652 return RISCVISD::DIVUW; 6653 case ISD::UREM: 6654 return RISCVISD::REMUW; 6655 case ISD::ROTL: 6656 return RISCVISD::ROLW; 6657 case ISD::ROTR: 6658 return RISCVISD::RORW; 6659 } 6660 } 6661 6662 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6663 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6664 // otherwise be promoted to i64, making it difficult to select the 6665 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6666 // type i8/i16/i32 is lost. 6667 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6668 unsigned ExtOpc = ISD::ANY_EXTEND) { 6669 SDLoc DL(N); 6670 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6671 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6672 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6673 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6674 // ReplaceNodeResults requires we maintain the same type for the return value. 6675 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6676 } 6677 6678 // Converts the given 32-bit operation to a i64 operation with signed extension 6679 // semantic to reduce the signed extension instructions. 6680 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6681 SDLoc DL(N); 6682 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6683 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6684 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6685 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6686 DAG.getValueType(MVT::i32)); 6687 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6688 } 6689 6690 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6691 SmallVectorImpl<SDValue> &Results, 6692 SelectionDAG &DAG) const { 6693 SDLoc DL(N); 6694 switch (N->getOpcode()) { 6695 default: 6696 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6697 case ISD::STRICT_FP_TO_SINT: 6698 case ISD::STRICT_FP_TO_UINT: 6699 case ISD::FP_TO_SINT: 6700 case ISD::FP_TO_UINT: { 6701 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6702 "Unexpected custom legalisation"); 6703 bool IsStrict = N->isStrictFPOpcode(); 6704 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6705 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6706 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6707 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6708 TargetLowering::TypeSoftenFloat) { 6709 if (!isTypeLegal(Op0.getValueType())) 6710 return; 6711 if (IsStrict) { 6712 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6713 : RISCVISD::STRICT_FCVT_WU_RV64; 6714 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6715 SDValue Res = DAG.getNode( 6716 Opc, DL, VTs, N->getOperand(0), Op0, 6717 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6718 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6719 Results.push_back(Res.getValue(1)); 6720 return; 6721 } 6722 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6723 SDValue Res = 6724 DAG.getNode(Opc, DL, MVT::i64, Op0, 6725 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6726 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6727 return; 6728 } 6729 // If the FP type needs to be softened, emit a library call using the 'si' 6730 // version. If we left it to default legalization we'd end up with 'di'. If 6731 // the FP type doesn't need to be softened just let generic type 6732 // legalization promote the result type. 6733 RTLIB::Libcall LC; 6734 if (IsSigned) 6735 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6736 else 6737 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6738 MakeLibCallOptions CallOptions; 6739 EVT OpVT = Op0.getValueType(); 6740 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6741 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6742 SDValue Result; 6743 std::tie(Result, Chain) = 6744 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6745 Results.push_back(Result); 6746 if (IsStrict) 6747 Results.push_back(Chain); 6748 break; 6749 } 6750 case ISD::READCYCLECOUNTER: { 6751 assert(!Subtarget.is64Bit() && 6752 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6753 6754 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6755 SDValue RCW = 6756 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6757 6758 Results.push_back( 6759 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6760 Results.push_back(RCW.getValue(2)); 6761 break; 6762 } 6763 case ISD::MUL: { 6764 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6765 unsigned XLen = Subtarget.getXLen(); 6766 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6767 if (Size > XLen) { 6768 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6769 SDValue LHS = N->getOperand(0); 6770 SDValue RHS = N->getOperand(1); 6771 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6772 6773 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6774 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6775 // We need exactly one side to be unsigned. 6776 if (LHSIsU == RHSIsU) 6777 return; 6778 6779 auto MakeMULPair = [&](SDValue S, SDValue U) { 6780 MVT XLenVT = Subtarget.getXLenVT(); 6781 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6782 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6783 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6784 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6785 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6786 }; 6787 6788 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6789 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6790 6791 // The other operand should be signed, but still prefer MULH when 6792 // possible. 6793 if (RHSIsU && LHSIsS && !RHSIsS) 6794 Results.push_back(MakeMULPair(LHS, RHS)); 6795 else if (LHSIsU && RHSIsS && !LHSIsS) 6796 Results.push_back(MakeMULPair(RHS, LHS)); 6797 6798 return; 6799 } 6800 LLVM_FALLTHROUGH; 6801 } 6802 case ISD::ADD: 6803 case ISD::SUB: 6804 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6805 "Unexpected custom legalisation"); 6806 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6807 break; 6808 case ISD::SHL: 6809 case ISD::SRA: 6810 case ISD::SRL: 6811 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6812 "Unexpected custom legalisation"); 6813 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6814 // If we can use a BSET instruction, allow default promotion to apply. 6815 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6816 isOneConstant(N->getOperand(0))) 6817 break; 6818 Results.push_back(customLegalizeToWOp(N, DAG)); 6819 break; 6820 } 6821 6822 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6823 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6824 // shift amount. 6825 if (N->getOpcode() == ISD::SHL) { 6826 SDLoc DL(N); 6827 SDValue NewOp0 = 6828 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6829 SDValue NewOp1 = 6830 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6831 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6832 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6833 DAG.getValueType(MVT::i32)); 6834 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6835 } 6836 6837 break; 6838 case ISD::ROTL: 6839 case ISD::ROTR: 6840 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6841 "Unexpected custom legalisation"); 6842 Results.push_back(customLegalizeToWOp(N, DAG)); 6843 break; 6844 case ISD::CTTZ: 6845 case ISD::CTTZ_ZERO_UNDEF: 6846 case ISD::CTLZ: 6847 case ISD::CTLZ_ZERO_UNDEF: { 6848 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6849 "Unexpected custom legalisation"); 6850 6851 SDValue NewOp0 = 6852 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6853 bool IsCTZ = 6854 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6855 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6856 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6857 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6858 return; 6859 } 6860 case ISD::SDIV: 6861 case ISD::UDIV: 6862 case ISD::UREM: { 6863 MVT VT = N->getSimpleValueType(0); 6864 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6865 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6866 "Unexpected custom legalisation"); 6867 // Don't promote division/remainder by constant since we should expand those 6868 // to multiply by magic constant. 6869 // FIXME: What if the expansion is disabled for minsize. 6870 if (N->getOperand(1).getOpcode() == ISD::Constant) 6871 return; 6872 6873 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6874 // the upper 32 bits. For other types we need to sign or zero extend 6875 // based on the opcode. 6876 unsigned ExtOpc = ISD::ANY_EXTEND; 6877 if (VT != MVT::i32) 6878 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6879 : ISD::ZERO_EXTEND; 6880 6881 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6882 break; 6883 } 6884 case ISD::UADDO: 6885 case ISD::USUBO: { 6886 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6887 "Unexpected custom legalisation"); 6888 bool IsAdd = N->getOpcode() == ISD::UADDO; 6889 // Create an ADDW or SUBW. 6890 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6891 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6892 SDValue Res = 6893 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6894 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6895 DAG.getValueType(MVT::i32)); 6896 6897 SDValue Overflow; 6898 if (IsAdd && isOneConstant(RHS)) { 6899 // Special case uaddo X, 1 overflowed if the addition result is 0. 6900 // The general case (X + C) < C is not necessarily beneficial. Although we 6901 // reduce the live range of X, we may introduce the materialization of 6902 // constant C, especially when the setcc result is used by branch. We have 6903 // no compare with constant and branch instructions. 6904 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6905 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6906 } else { 6907 // Sign extend the LHS and perform an unsigned compare with the ADDW 6908 // result. Since the inputs are sign extended from i32, this is equivalent 6909 // to comparing the lower 32 bits. 6910 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6911 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6912 IsAdd ? ISD::SETULT : ISD::SETUGT); 6913 } 6914 6915 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6916 Results.push_back(Overflow); 6917 return; 6918 } 6919 case ISD::UADDSAT: 6920 case ISD::USUBSAT: { 6921 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6922 "Unexpected custom legalisation"); 6923 if (Subtarget.hasStdExtZbb()) { 6924 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6925 // sign extend allows overflow of the lower 32 bits to be detected on 6926 // the promoted size. 6927 SDValue LHS = 6928 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6929 SDValue RHS = 6930 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6931 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6932 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6933 return; 6934 } 6935 6936 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6937 // promotion for UADDO/USUBO. 6938 Results.push_back(expandAddSubSat(N, DAG)); 6939 return; 6940 } 6941 case ISD::ABS: { 6942 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6943 "Unexpected custom legalisation"); 6944 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6945 6946 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6947 6948 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6949 6950 // Freeze the source so we can increase it's use count. 6951 Src = DAG.getFreeze(Src); 6952 6953 // Copy sign bit to all bits using the sraiw pattern. 6954 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6955 DAG.getValueType(MVT::i32)); 6956 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6957 DAG.getConstant(31, DL, MVT::i64)); 6958 6959 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6960 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6961 6962 // NOTE: The result is only required to be anyextended, but sext is 6963 // consistent with type legalization of sub. 6964 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6965 DAG.getValueType(MVT::i32)); 6966 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6967 return; 6968 } 6969 case ISD::BITCAST: { 6970 EVT VT = N->getValueType(0); 6971 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6972 SDValue Op0 = N->getOperand(0); 6973 EVT Op0VT = Op0.getValueType(); 6974 MVT XLenVT = Subtarget.getXLenVT(); 6975 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6976 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6977 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6978 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6979 Subtarget.hasStdExtF()) { 6980 SDValue FPConv = 6981 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6982 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6983 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6984 isTypeLegal(Op0VT)) { 6985 // Custom-legalize bitcasts from fixed-length vector types to illegal 6986 // scalar types in order to improve codegen. Bitcast the vector to a 6987 // one-element vector type whose element type is the same as the result 6988 // type, and extract the first element. 6989 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6990 if (isTypeLegal(BVT)) { 6991 SDValue BVec = DAG.getBitcast(BVT, Op0); 6992 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6993 DAG.getConstant(0, DL, XLenVT))); 6994 } 6995 } 6996 break; 6997 } 6998 case RISCVISD::GREV: 6999 case RISCVISD::GORC: 7000 case RISCVISD::SHFL: { 7001 MVT VT = N->getSimpleValueType(0); 7002 MVT XLenVT = Subtarget.getXLenVT(); 7003 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7004 "Unexpected custom legalisation"); 7005 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7006 assert((Subtarget.hasStdExtZbp() || 7007 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7008 N->getConstantOperandVal(1) == 7)) && 7009 "Unexpected extension"); 7010 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7011 SDValue NewOp1 = 7012 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7013 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7014 // ReplaceNodeResults requires we maintain the same type for the return 7015 // value. 7016 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7017 break; 7018 } 7019 case ISD::BSWAP: 7020 case ISD::BITREVERSE: { 7021 MVT VT = N->getSimpleValueType(0); 7022 MVT XLenVT = Subtarget.getXLenVT(); 7023 assert((VT == MVT::i8 || VT == MVT::i16 || 7024 (VT == MVT::i32 && Subtarget.is64Bit())) && 7025 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7026 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7027 unsigned Imm = VT.getSizeInBits() - 1; 7028 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7029 if (N->getOpcode() == ISD::BSWAP) 7030 Imm &= ~0x7U; 7031 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7032 DAG.getConstant(Imm, DL, XLenVT)); 7033 // ReplaceNodeResults requires we maintain the same type for the return 7034 // value. 7035 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7036 break; 7037 } 7038 case ISD::FSHL: 7039 case ISD::FSHR: { 7040 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7041 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7042 SDValue NewOp0 = 7043 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7044 SDValue NewOp1 = 7045 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7046 SDValue NewShAmt = 7047 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7048 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7049 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7050 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7051 DAG.getConstant(0x1f, DL, MVT::i64)); 7052 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7053 // instruction use different orders. fshl will return its first operand for 7054 // shift of zero, fshr will return its second operand. fsl and fsr both 7055 // return rs1 so the ISD nodes need to have different operand orders. 7056 // Shift amount is in rs2. 7057 unsigned Opc = RISCVISD::FSLW; 7058 if (N->getOpcode() == ISD::FSHR) { 7059 std::swap(NewOp0, NewOp1); 7060 Opc = RISCVISD::FSRW; 7061 } 7062 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7063 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7064 break; 7065 } 7066 case ISD::EXTRACT_VECTOR_ELT: { 7067 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7068 // type is illegal (currently only vXi64 RV32). 7069 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7070 // transferred to the destination register. We issue two of these from the 7071 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7072 // first element. 7073 SDValue Vec = N->getOperand(0); 7074 SDValue Idx = N->getOperand(1); 7075 7076 // The vector type hasn't been legalized yet so we can't issue target 7077 // specific nodes if it needs legalization. 7078 // FIXME: We would manually legalize if it's important. 7079 if (!isTypeLegal(Vec.getValueType())) 7080 return; 7081 7082 MVT VecVT = Vec.getSimpleValueType(); 7083 7084 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7085 VecVT.getVectorElementType() == MVT::i64 && 7086 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7087 7088 // If this is a fixed vector, we need to convert it to a scalable vector. 7089 MVT ContainerVT = VecVT; 7090 if (VecVT.isFixedLengthVector()) { 7091 ContainerVT = getContainerForFixedLengthVector(VecVT); 7092 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7093 } 7094 7095 MVT XLenVT = Subtarget.getXLenVT(); 7096 7097 // Use a VL of 1 to avoid processing more elements than we need. 7098 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7099 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7100 7101 // Unless the index is known to be 0, we must slide the vector down to get 7102 // the desired element into index 0. 7103 if (!isNullConstant(Idx)) { 7104 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7105 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7106 } 7107 7108 // Extract the lower XLEN bits of the correct vector element. 7109 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7110 7111 // To extract the upper XLEN bits of the vector element, shift the first 7112 // element right by 32 bits and re-extract the lower XLEN bits. 7113 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7114 DAG.getUNDEF(ContainerVT), 7115 DAG.getConstant(32, DL, XLenVT), VL); 7116 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7117 ThirtyTwoV, Mask, VL); 7118 7119 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7120 7121 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7122 break; 7123 } 7124 case ISD::INTRINSIC_WO_CHAIN: { 7125 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7126 switch (IntNo) { 7127 default: 7128 llvm_unreachable( 7129 "Don't know how to custom type legalize this intrinsic!"); 7130 case Intrinsic::riscv_grev: 7131 case Intrinsic::riscv_gorc: { 7132 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7133 "Unexpected custom legalisation"); 7134 SDValue NewOp1 = 7135 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7136 SDValue NewOp2 = 7137 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7138 unsigned Opc = 7139 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7140 // If the control is a constant, promote the node by clearing any extra 7141 // bits bits in the control. isel will form greviw/gorciw if the result is 7142 // sign extended. 7143 if (isa<ConstantSDNode>(NewOp2)) { 7144 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7145 DAG.getConstant(0x1f, DL, MVT::i64)); 7146 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7147 } 7148 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7149 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7150 break; 7151 } 7152 case Intrinsic::riscv_bcompress: 7153 case Intrinsic::riscv_bdecompress: 7154 case Intrinsic::riscv_bfp: 7155 case Intrinsic::riscv_fsl: 7156 case Intrinsic::riscv_fsr: { 7157 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7158 "Unexpected custom legalisation"); 7159 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7160 break; 7161 } 7162 case Intrinsic::riscv_orc_b: { 7163 // Lower to the GORCI encoding for orc.b with the operand extended. 7164 SDValue NewOp = 7165 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7166 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7167 DAG.getConstant(7, DL, MVT::i64)); 7168 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7169 return; 7170 } 7171 case Intrinsic::riscv_shfl: 7172 case Intrinsic::riscv_unshfl: { 7173 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7174 "Unexpected custom legalisation"); 7175 SDValue NewOp1 = 7176 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7177 SDValue NewOp2 = 7178 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7179 unsigned Opc = 7180 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7181 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7182 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7183 // will be shuffled the same way as the lower 32 bit half, but the two 7184 // halves won't cross. 7185 if (isa<ConstantSDNode>(NewOp2)) { 7186 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7187 DAG.getConstant(0xf, DL, MVT::i64)); 7188 Opc = 7189 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7190 } 7191 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7192 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7193 break; 7194 } 7195 case Intrinsic::riscv_vmv_x_s: { 7196 EVT VT = N->getValueType(0); 7197 MVT XLenVT = Subtarget.getXLenVT(); 7198 if (VT.bitsLT(XLenVT)) { 7199 // Simple case just extract using vmv.x.s and truncate. 7200 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7201 Subtarget.getXLenVT(), N->getOperand(1)); 7202 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7203 return; 7204 } 7205 7206 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7207 "Unexpected custom legalization"); 7208 7209 // We need to do the move in two steps. 7210 SDValue Vec = N->getOperand(1); 7211 MVT VecVT = Vec.getSimpleValueType(); 7212 7213 // First extract the lower XLEN bits of the element. 7214 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7215 7216 // To extract the upper XLEN bits of the vector element, shift the first 7217 // element right by 32 bits and re-extract the lower XLEN bits. 7218 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7219 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7220 7221 SDValue ThirtyTwoV = 7222 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7223 DAG.getConstant(32, DL, XLenVT), VL); 7224 SDValue LShr32 = 7225 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7226 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7227 7228 Results.push_back( 7229 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7230 break; 7231 } 7232 } 7233 break; 7234 } 7235 case ISD::VECREDUCE_ADD: 7236 case ISD::VECREDUCE_AND: 7237 case ISD::VECREDUCE_OR: 7238 case ISD::VECREDUCE_XOR: 7239 case ISD::VECREDUCE_SMAX: 7240 case ISD::VECREDUCE_UMAX: 7241 case ISD::VECREDUCE_SMIN: 7242 case ISD::VECREDUCE_UMIN: 7243 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7244 Results.push_back(V); 7245 break; 7246 case ISD::VP_REDUCE_ADD: 7247 case ISD::VP_REDUCE_AND: 7248 case ISD::VP_REDUCE_OR: 7249 case ISD::VP_REDUCE_XOR: 7250 case ISD::VP_REDUCE_SMAX: 7251 case ISD::VP_REDUCE_UMAX: 7252 case ISD::VP_REDUCE_SMIN: 7253 case ISD::VP_REDUCE_UMIN: 7254 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7255 Results.push_back(V); 7256 break; 7257 case ISD::FLT_ROUNDS_: { 7258 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7259 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7260 Results.push_back(Res.getValue(0)); 7261 Results.push_back(Res.getValue(1)); 7262 break; 7263 } 7264 } 7265 } 7266 7267 // A structure to hold one of the bit-manipulation patterns below. Together, a 7268 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7269 // (or (and (shl x, 1), 0xAAAAAAAA), 7270 // (and (srl x, 1), 0x55555555)) 7271 struct RISCVBitmanipPat { 7272 SDValue Op; 7273 unsigned ShAmt; 7274 bool IsSHL; 7275 7276 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7277 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7278 } 7279 }; 7280 7281 // Matches patterns of the form 7282 // (and (shl x, C2), (C1 << C2)) 7283 // (and (srl x, C2), C1) 7284 // (shl (and x, C1), C2) 7285 // (srl (and x, (C1 << C2)), C2) 7286 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7287 // The expected masks for each shift amount are specified in BitmanipMasks where 7288 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7289 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7290 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7291 // XLen is 64. 7292 static Optional<RISCVBitmanipPat> 7293 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7294 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7295 "Unexpected number of masks"); 7296 Optional<uint64_t> Mask; 7297 // Optionally consume a mask around the shift operation. 7298 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7299 Mask = Op.getConstantOperandVal(1); 7300 Op = Op.getOperand(0); 7301 } 7302 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7303 return None; 7304 bool IsSHL = Op.getOpcode() == ISD::SHL; 7305 7306 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7307 return None; 7308 uint64_t ShAmt = Op.getConstantOperandVal(1); 7309 7310 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7311 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7312 return None; 7313 // If we don't have enough masks for 64 bit, then we must be trying to 7314 // match SHFL so we're only allowed to shift 1/4 of the width. 7315 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7316 return None; 7317 7318 SDValue Src = Op.getOperand(0); 7319 7320 // The expected mask is shifted left when the AND is found around SHL 7321 // patterns. 7322 // ((x >> 1) & 0x55555555) 7323 // ((x << 1) & 0xAAAAAAAA) 7324 bool SHLExpMask = IsSHL; 7325 7326 if (!Mask) { 7327 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7328 // the mask is all ones: consume that now. 7329 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7330 Mask = Src.getConstantOperandVal(1); 7331 Src = Src.getOperand(0); 7332 // The expected mask is now in fact shifted left for SRL, so reverse the 7333 // decision. 7334 // ((x & 0xAAAAAAAA) >> 1) 7335 // ((x & 0x55555555) << 1) 7336 SHLExpMask = !SHLExpMask; 7337 } else { 7338 // Use a default shifted mask of all-ones if there's no AND, truncated 7339 // down to the expected width. This simplifies the logic later on. 7340 Mask = maskTrailingOnes<uint64_t>(Width); 7341 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7342 } 7343 } 7344 7345 unsigned MaskIdx = Log2_32(ShAmt); 7346 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7347 7348 if (SHLExpMask) 7349 ExpMask <<= ShAmt; 7350 7351 if (Mask != ExpMask) 7352 return None; 7353 7354 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7355 } 7356 7357 // Matches any of the following bit-manipulation patterns: 7358 // (and (shl x, 1), (0x55555555 << 1)) 7359 // (and (srl x, 1), 0x55555555) 7360 // (shl (and x, 0x55555555), 1) 7361 // (srl (and x, (0x55555555 << 1)), 1) 7362 // where the shift amount and mask may vary thus: 7363 // [1] = 0x55555555 / 0xAAAAAAAA 7364 // [2] = 0x33333333 / 0xCCCCCCCC 7365 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7366 // [8] = 0x00FF00FF / 0xFF00FF00 7367 // [16] = 0x0000FFFF / 0xFFFFFFFF 7368 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7369 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7370 // These are the unshifted masks which we use to match bit-manipulation 7371 // patterns. They may be shifted left in certain circumstances. 7372 static const uint64_t BitmanipMasks[] = { 7373 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7374 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7375 7376 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7377 } 7378 7379 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7380 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7381 auto BinOpToRVVReduce = [](unsigned Opc) { 7382 switch (Opc) { 7383 default: 7384 llvm_unreachable("Unhandled binary to transfrom reduction"); 7385 case ISD::ADD: 7386 return RISCVISD::VECREDUCE_ADD_VL; 7387 case ISD::UMAX: 7388 return RISCVISD::VECREDUCE_UMAX_VL; 7389 case ISD::SMAX: 7390 return RISCVISD::VECREDUCE_SMAX_VL; 7391 case ISD::UMIN: 7392 return RISCVISD::VECREDUCE_UMIN_VL; 7393 case ISD::SMIN: 7394 return RISCVISD::VECREDUCE_SMIN_VL; 7395 case ISD::AND: 7396 return RISCVISD::VECREDUCE_AND_VL; 7397 case ISD::OR: 7398 return RISCVISD::VECREDUCE_OR_VL; 7399 case ISD::XOR: 7400 return RISCVISD::VECREDUCE_XOR_VL; 7401 case ISD::FADD: 7402 return RISCVISD::VECREDUCE_FADD_VL; 7403 case ISD::FMAXNUM: 7404 return RISCVISD::VECREDUCE_FMAX_VL; 7405 case ISD::FMINNUM: 7406 return RISCVISD::VECREDUCE_FMIN_VL; 7407 } 7408 }; 7409 7410 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7411 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7412 isNullConstant(V.getOperand(1)) && 7413 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7414 }; 7415 7416 unsigned Opc = N->getOpcode(); 7417 unsigned ReduceIdx; 7418 if (IsReduction(N->getOperand(0), Opc)) 7419 ReduceIdx = 0; 7420 else if (IsReduction(N->getOperand(1), Opc)) 7421 ReduceIdx = 1; 7422 else 7423 return SDValue(); 7424 7425 // Skip if FADD disallows reassociation but the combiner needs. 7426 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7427 return SDValue(); 7428 7429 SDValue Extract = N->getOperand(ReduceIdx); 7430 SDValue Reduce = Extract.getOperand(0); 7431 if (!Reduce.hasOneUse()) 7432 return SDValue(); 7433 7434 SDValue ScalarV = Reduce.getOperand(2); 7435 7436 // Make sure that ScalarV is a splat with VL=1. 7437 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7438 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7439 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7440 return SDValue(); 7441 7442 if (!isOneConstant(ScalarV.getOperand(2))) 7443 return SDValue(); 7444 7445 // TODO: Deal with value other than neutral element. 7446 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7447 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7448 isNullFPConstant(V)) 7449 return true; 7450 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7451 N->getFlags()) == V; 7452 }; 7453 7454 // Check the scalar of ScalarV is neutral element 7455 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7456 return SDValue(); 7457 7458 if (!ScalarV.hasOneUse()) 7459 return SDValue(); 7460 7461 EVT SplatVT = ScalarV.getValueType(); 7462 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7463 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7464 if (SplatVT.isInteger()) { 7465 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7466 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7467 SplatOpc = RISCVISD::VMV_S_X_VL; 7468 else 7469 SplatOpc = RISCVISD::VMV_V_X_VL; 7470 } 7471 7472 SDValue NewScalarV = 7473 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7474 ScalarV.getOperand(2)); 7475 SDValue NewReduce = 7476 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7477 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7478 Reduce.getOperand(3), Reduce.getOperand(4)); 7479 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7480 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7481 } 7482 7483 // Match the following pattern as a GREVI(W) operation 7484 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7485 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7486 const RISCVSubtarget &Subtarget) { 7487 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7488 EVT VT = Op.getValueType(); 7489 7490 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7491 auto LHS = matchGREVIPat(Op.getOperand(0)); 7492 auto RHS = matchGREVIPat(Op.getOperand(1)); 7493 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7494 SDLoc DL(Op); 7495 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7496 DAG.getConstant(LHS->ShAmt, DL, VT)); 7497 } 7498 } 7499 return SDValue(); 7500 } 7501 7502 // Matches any the following pattern as a GORCI(W) operation 7503 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7504 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7505 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7506 // Note that with the variant of 3., 7507 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7508 // the inner pattern will first be matched as GREVI and then the outer 7509 // pattern will be matched to GORC via the first rule above. 7510 // 4. (or (rotl/rotr x, bitwidth/2), x) 7511 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7512 const RISCVSubtarget &Subtarget) { 7513 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7514 EVT VT = Op.getValueType(); 7515 7516 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7517 SDLoc DL(Op); 7518 SDValue Op0 = Op.getOperand(0); 7519 SDValue Op1 = Op.getOperand(1); 7520 7521 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7522 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7523 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7524 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7525 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7526 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7527 if ((Reverse.getOpcode() == ISD::ROTL || 7528 Reverse.getOpcode() == ISD::ROTR) && 7529 Reverse.getOperand(0) == X && 7530 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7531 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7532 if (RotAmt == (VT.getSizeInBits() / 2)) 7533 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7534 DAG.getConstant(RotAmt, DL, VT)); 7535 } 7536 return SDValue(); 7537 }; 7538 7539 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7540 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7541 return V; 7542 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7543 return V; 7544 7545 // OR is commutable so canonicalize its OR operand to the left 7546 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7547 std::swap(Op0, Op1); 7548 if (Op0.getOpcode() != ISD::OR) 7549 return SDValue(); 7550 SDValue OrOp0 = Op0.getOperand(0); 7551 SDValue OrOp1 = Op0.getOperand(1); 7552 auto LHS = matchGREVIPat(OrOp0); 7553 // OR is commutable so swap the operands and try again: x might have been 7554 // on the left 7555 if (!LHS) { 7556 std::swap(OrOp0, OrOp1); 7557 LHS = matchGREVIPat(OrOp0); 7558 } 7559 auto RHS = matchGREVIPat(Op1); 7560 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7561 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7562 DAG.getConstant(LHS->ShAmt, DL, VT)); 7563 } 7564 } 7565 return SDValue(); 7566 } 7567 7568 // Matches any of the following bit-manipulation patterns: 7569 // (and (shl x, 1), (0x22222222 << 1)) 7570 // (and (srl x, 1), 0x22222222) 7571 // (shl (and x, 0x22222222), 1) 7572 // (srl (and x, (0x22222222 << 1)), 1) 7573 // where the shift amount and mask may vary thus: 7574 // [1] = 0x22222222 / 0x44444444 7575 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7576 // [4] = 0x00F000F0 / 0x0F000F00 7577 // [8] = 0x0000FF00 / 0x00FF0000 7578 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7579 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7580 // These are the unshifted masks which we use to match bit-manipulation 7581 // patterns. They may be shifted left in certain circumstances. 7582 static const uint64_t BitmanipMasks[] = { 7583 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7584 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7585 7586 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7587 } 7588 7589 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7590 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7591 const RISCVSubtarget &Subtarget) { 7592 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7593 EVT VT = Op.getValueType(); 7594 7595 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7596 return SDValue(); 7597 7598 SDValue Op0 = Op.getOperand(0); 7599 SDValue Op1 = Op.getOperand(1); 7600 7601 // Or is commutable so canonicalize the second OR to the LHS. 7602 if (Op0.getOpcode() != ISD::OR) 7603 std::swap(Op0, Op1); 7604 if (Op0.getOpcode() != ISD::OR) 7605 return SDValue(); 7606 7607 // We found an inner OR, so our operands are the operands of the inner OR 7608 // and the other operand of the outer OR. 7609 SDValue A = Op0.getOperand(0); 7610 SDValue B = Op0.getOperand(1); 7611 SDValue C = Op1; 7612 7613 auto Match1 = matchSHFLPat(A); 7614 auto Match2 = matchSHFLPat(B); 7615 7616 // If neither matched, we failed. 7617 if (!Match1 && !Match2) 7618 return SDValue(); 7619 7620 // We had at least one match. if one failed, try the remaining C operand. 7621 if (!Match1) { 7622 std::swap(A, C); 7623 Match1 = matchSHFLPat(A); 7624 if (!Match1) 7625 return SDValue(); 7626 } else if (!Match2) { 7627 std::swap(B, C); 7628 Match2 = matchSHFLPat(B); 7629 if (!Match2) 7630 return SDValue(); 7631 } 7632 assert(Match1 && Match2); 7633 7634 // Make sure our matches pair up. 7635 if (!Match1->formsPairWith(*Match2)) 7636 return SDValue(); 7637 7638 // All the remains is to make sure C is an AND with the same input, that masks 7639 // out the bits that are being shuffled. 7640 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7641 C.getOperand(0) != Match1->Op) 7642 return SDValue(); 7643 7644 uint64_t Mask = C.getConstantOperandVal(1); 7645 7646 static const uint64_t BitmanipMasks[] = { 7647 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7648 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7649 }; 7650 7651 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7652 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7653 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7654 7655 if (Mask != ExpMask) 7656 return SDValue(); 7657 7658 SDLoc DL(Op); 7659 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7660 DAG.getConstant(Match1->ShAmt, DL, VT)); 7661 } 7662 7663 // Optimize (add (shl x, c0), (shl y, c1)) -> 7664 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7665 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7666 const RISCVSubtarget &Subtarget) { 7667 // Perform this optimization only in the zba extension. 7668 if (!Subtarget.hasStdExtZba()) 7669 return SDValue(); 7670 7671 // Skip for vector types and larger types. 7672 EVT VT = N->getValueType(0); 7673 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7674 return SDValue(); 7675 7676 // The two operand nodes must be SHL and have no other use. 7677 SDValue N0 = N->getOperand(0); 7678 SDValue N1 = N->getOperand(1); 7679 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7680 !N0->hasOneUse() || !N1->hasOneUse()) 7681 return SDValue(); 7682 7683 // Check c0 and c1. 7684 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7685 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7686 if (!N0C || !N1C) 7687 return SDValue(); 7688 int64_t C0 = N0C->getSExtValue(); 7689 int64_t C1 = N1C->getSExtValue(); 7690 if (C0 <= 0 || C1 <= 0) 7691 return SDValue(); 7692 7693 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7694 int64_t Bits = std::min(C0, C1); 7695 int64_t Diff = std::abs(C0 - C1); 7696 if (Diff != 1 && Diff != 2 && Diff != 3) 7697 return SDValue(); 7698 7699 // Build nodes. 7700 SDLoc DL(N); 7701 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7702 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7703 SDValue NA0 = 7704 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7705 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7706 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7707 } 7708 7709 // Combine 7710 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7711 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7712 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7713 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7714 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7715 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7716 // The grev patterns represents BSWAP. 7717 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7718 // off the grev. 7719 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7720 const RISCVSubtarget &Subtarget) { 7721 bool IsWInstruction = 7722 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7723 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7724 IsWInstruction) && 7725 "Unexpected opcode!"); 7726 SDValue Src = N->getOperand(0); 7727 EVT VT = N->getValueType(0); 7728 SDLoc DL(N); 7729 7730 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7731 return SDValue(); 7732 7733 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7734 !isa<ConstantSDNode>(Src.getOperand(1))) 7735 return SDValue(); 7736 7737 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7738 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7739 7740 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7741 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7742 unsigned ShAmt1 = N->getConstantOperandVal(1); 7743 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7744 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7745 return SDValue(); 7746 7747 Src = Src.getOperand(0); 7748 7749 // Toggle bit the MSB of the shift. 7750 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7751 if (CombinedShAmt == 0) 7752 return Src; 7753 7754 SDValue Res = DAG.getNode( 7755 RISCVISD::GREV, DL, VT, Src, 7756 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7757 if (!IsWInstruction) 7758 return Res; 7759 7760 // Sign extend the result to match the behavior of the rotate. This will be 7761 // selected to GREVIW in isel. 7762 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7763 DAG.getValueType(MVT::i32)); 7764 } 7765 7766 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7767 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7768 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7769 // not undo itself, but they are redundant. 7770 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7771 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7772 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7773 SDValue Src = N->getOperand(0); 7774 7775 if (Src.getOpcode() != N->getOpcode()) 7776 return SDValue(); 7777 7778 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7779 !isa<ConstantSDNode>(Src.getOperand(1))) 7780 return SDValue(); 7781 7782 unsigned ShAmt1 = N->getConstantOperandVal(1); 7783 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7784 Src = Src.getOperand(0); 7785 7786 unsigned CombinedShAmt; 7787 if (IsGORC) 7788 CombinedShAmt = ShAmt1 | ShAmt2; 7789 else 7790 CombinedShAmt = ShAmt1 ^ ShAmt2; 7791 7792 if (CombinedShAmt == 0) 7793 return Src; 7794 7795 SDLoc DL(N); 7796 return DAG.getNode( 7797 N->getOpcode(), DL, N->getValueType(0), Src, 7798 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7799 } 7800 7801 // Combine a constant select operand into its use: 7802 // 7803 // (and (select cond, -1, c), x) 7804 // -> (select cond, x, (and x, c)) [AllOnes=1] 7805 // (or (select cond, 0, c), x) 7806 // -> (select cond, x, (or x, c)) [AllOnes=0] 7807 // (xor (select cond, 0, c), x) 7808 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7809 // (add (select cond, 0, c), x) 7810 // -> (select cond, x, (add x, c)) [AllOnes=0] 7811 // (sub x, (select cond, 0, c)) 7812 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7813 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7814 SelectionDAG &DAG, bool AllOnes) { 7815 EVT VT = N->getValueType(0); 7816 7817 // Skip vectors. 7818 if (VT.isVector()) 7819 return SDValue(); 7820 7821 if ((Slct.getOpcode() != ISD::SELECT && 7822 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7823 !Slct.hasOneUse()) 7824 return SDValue(); 7825 7826 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7827 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7828 }; 7829 7830 bool SwapSelectOps; 7831 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7832 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7833 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7834 SDValue NonConstantVal; 7835 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7836 SwapSelectOps = false; 7837 NonConstantVal = FalseVal; 7838 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7839 SwapSelectOps = true; 7840 NonConstantVal = TrueVal; 7841 } else 7842 return SDValue(); 7843 7844 // Slct is now know to be the desired identity constant when CC is true. 7845 TrueVal = OtherOp; 7846 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7847 // Unless SwapSelectOps says the condition should be false. 7848 if (SwapSelectOps) 7849 std::swap(TrueVal, FalseVal); 7850 7851 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7852 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7853 {Slct.getOperand(0), Slct.getOperand(1), 7854 Slct.getOperand(2), TrueVal, FalseVal}); 7855 7856 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7857 {Slct.getOperand(0), TrueVal, FalseVal}); 7858 } 7859 7860 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7861 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7862 bool AllOnes) { 7863 SDValue N0 = N->getOperand(0); 7864 SDValue N1 = N->getOperand(1); 7865 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7866 return Result; 7867 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7868 return Result; 7869 return SDValue(); 7870 } 7871 7872 // Transform (add (mul x, c0), c1) -> 7873 // (add (mul (add x, c1/c0), c0), c1%c0). 7874 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7875 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7876 // to an infinite loop in DAGCombine if transformed. 7877 // Or transform (add (mul x, c0), c1) -> 7878 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7879 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7880 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7881 // lead to an infinite loop in DAGCombine if transformed. 7882 // Or transform (add (mul x, c0), c1) -> 7883 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7884 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7885 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7886 // lead to an infinite loop in DAGCombine if transformed. 7887 // Or transform (add (mul x, c0), c1) -> 7888 // (mul (add x, c1/c0), c0). 7889 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7890 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7891 const RISCVSubtarget &Subtarget) { 7892 // Skip for vector types and larger types. 7893 EVT VT = N->getValueType(0); 7894 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7895 return SDValue(); 7896 // The first operand node must be a MUL and has no other use. 7897 SDValue N0 = N->getOperand(0); 7898 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7899 return SDValue(); 7900 // Check if c0 and c1 match above conditions. 7901 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7902 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7903 if (!N0C || !N1C) 7904 return SDValue(); 7905 // If N0C has multiple uses it's possible one of the cases in 7906 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7907 // in an infinite loop. 7908 if (!N0C->hasOneUse()) 7909 return SDValue(); 7910 int64_t C0 = N0C->getSExtValue(); 7911 int64_t C1 = N1C->getSExtValue(); 7912 int64_t CA, CB; 7913 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7914 return SDValue(); 7915 // Search for proper CA (non-zero) and CB that both are simm12. 7916 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7917 !isInt<12>(C0 * (C1 / C0))) { 7918 CA = C1 / C0; 7919 CB = C1 % C0; 7920 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7921 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7922 CA = C1 / C0 + 1; 7923 CB = C1 % C0 - C0; 7924 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7925 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7926 CA = C1 / C0 - 1; 7927 CB = C1 % C0 + C0; 7928 } else 7929 return SDValue(); 7930 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7931 SDLoc DL(N); 7932 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7933 DAG.getConstant(CA, DL, VT)); 7934 SDValue New1 = 7935 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7936 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7937 } 7938 7939 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7940 const RISCVSubtarget &Subtarget) { 7941 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7942 return V; 7943 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7944 return V; 7945 if (SDValue V = combineBinOpToReduce(N, DAG)) 7946 return V; 7947 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7948 // (select lhs, rhs, cc, x, (add x, y)) 7949 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7950 } 7951 7952 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7953 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7954 // (select lhs, rhs, cc, x, (sub x, y)) 7955 SDValue N0 = N->getOperand(0); 7956 SDValue N1 = N->getOperand(1); 7957 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7958 } 7959 7960 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 7961 const RISCVSubtarget &Subtarget) { 7962 SDValue N0 = N->getOperand(0); 7963 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 7964 // extending X. This is safe since we only need the LSB after the shift and 7965 // shift amounts larger than 31 would produce poison. If we wait until 7966 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 7967 // to use a BEXT instruction. 7968 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 7969 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 7970 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 7971 N0.hasOneUse()) { 7972 SDLoc DL(N); 7973 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 7974 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 7975 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 7976 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 7977 DAG.getConstant(1, DL, MVT::i64)); 7978 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 7979 } 7980 7981 if (SDValue V = combineBinOpToReduce(N, DAG)) 7982 return V; 7983 7984 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7985 // (select lhs, rhs, cc, x, (and x, y)) 7986 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7987 } 7988 7989 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7990 const RISCVSubtarget &Subtarget) { 7991 if (Subtarget.hasStdExtZbp()) { 7992 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7993 return GREV; 7994 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7995 return GORC; 7996 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7997 return SHFL; 7998 } 7999 8000 if (SDValue V = combineBinOpToReduce(N, DAG)) 8001 return V; 8002 // fold (or (select cond, 0, y), x) -> 8003 // (select cond, x, (or x, y)) 8004 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8005 } 8006 8007 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 8008 SDValue N0 = N->getOperand(0); 8009 SDValue N1 = N->getOperand(1); 8010 8011 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8012 // NOTE: Assumes ROL being legal means ROLW is legal. 8013 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8014 if (N0.getOpcode() == RISCVISD::SLLW && 8015 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8016 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8017 SDLoc DL(N); 8018 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8019 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8020 } 8021 8022 if (SDValue V = combineBinOpToReduce(N, DAG)) 8023 return V; 8024 // fold (xor (select cond, 0, y), x) -> 8025 // (select cond, x, (xor x, y)) 8026 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8027 } 8028 8029 static SDValue 8030 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8031 const RISCVSubtarget &Subtarget) { 8032 SDValue Src = N->getOperand(0); 8033 EVT VT = N->getValueType(0); 8034 8035 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8036 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8037 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8038 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8039 Src.getOperand(0)); 8040 8041 // Fold (i64 (sext_inreg (abs X), i32)) -> 8042 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8043 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8044 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8045 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8046 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8047 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8048 // may get combined into an earlier operation so we need to use 8049 // ComputeNumSignBits. 8050 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8051 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8052 // we can't assume that X has 33 sign bits. We must check. 8053 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8054 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8055 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8056 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8057 SDLoc DL(N); 8058 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8059 SDValue Neg = 8060 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8061 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8062 DAG.getValueType(MVT::i32)); 8063 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8064 } 8065 8066 return SDValue(); 8067 } 8068 8069 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8070 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8071 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8072 bool Commute = false) { 8073 assert((N->getOpcode() == RISCVISD::ADD_VL || 8074 N->getOpcode() == RISCVISD::SUB_VL) && 8075 "Unexpected opcode"); 8076 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8077 SDValue Op0 = N->getOperand(0); 8078 SDValue Op1 = N->getOperand(1); 8079 if (Commute) 8080 std::swap(Op0, Op1); 8081 8082 MVT VT = N->getSimpleValueType(0); 8083 8084 // Determine the narrow size for a widening add/sub. 8085 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8086 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8087 VT.getVectorElementCount()); 8088 8089 SDValue Mask = N->getOperand(2); 8090 SDValue VL = N->getOperand(3); 8091 8092 SDLoc DL(N); 8093 8094 // If the RHS is a sext or zext, we can form a widening op. 8095 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8096 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8097 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8098 unsigned ExtOpc = Op1.getOpcode(); 8099 Op1 = Op1.getOperand(0); 8100 // Re-introduce narrower extends if needed. 8101 if (Op1.getValueType() != NarrowVT) 8102 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8103 8104 unsigned WOpc; 8105 if (ExtOpc == RISCVISD::VSEXT_VL) 8106 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8107 else 8108 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8109 8110 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8111 } 8112 8113 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8114 // sext/zext? 8115 8116 return SDValue(); 8117 } 8118 8119 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8120 // vwsub(u).vv/vx. 8121 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8122 SDValue Op0 = N->getOperand(0); 8123 SDValue Op1 = N->getOperand(1); 8124 SDValue Mask = N->getOperand(2); 8125 SDValue VL = N->getOperand(3); 8126 8127 MVT VT = N->getSimpleValueType(0); 8128 MVT NarrowVT = Op1.getSimpleValueType(); 8129 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8130 8131 unsigned VOpc; 8132 switch (N->getOpcode()) { 8133 default: llvm_unreachable("Unexpected opcode"); 8134 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8135 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8136 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8137 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8138 } 8139 8140 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8141 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8142 8143 SDLoc DL(N); 8144 8145 // If the LHS is a sext or zext, we can narrow this op to the same size as 8146 // the RHS. 8147 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8148 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8149 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8150 unsigned ExtOpc = Op0.getOpcode(); 8151 Op0 = Op0.getOperand(0); 8152 // Re-introduce narrower extends if needed. 8153 if (Op0.getValueType() != NarrowVT) 8154 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8155 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8156 } 8157 8158 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8159 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8160 8161 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8162 // to commute and use a vwadd(u).vx instead. 8163 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8164 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8165 Op0 = Op0.getOperand(1); 8166 8167 // See if have enough sign bits or zero bits in the scalar to use a 8168 // widening add/sub by splatting to smaller element size. 8169 unsigned EltBits = VT.getScalarSizeInBits(); 8170 unsigned ScalarBits = Op0.getValueSizeInBits(); 8171 // Make sure we're getting all element bits from the scalar register. 8172 // FIXME: Support implicit sign extension of vmv.v.x? 8173 if (ScalarBits < EltBits) 8174 return SDValue(); 8175 8176 if (IsSigned) { 8177 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8178 return SDValue(); 8179 } else { 8180 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8181 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8182 return SDValue(); 8183 } 8184 8185 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8186 DAG.getUNDEF(NarrowVT), Op0, VL); 8187 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8188 } 8189 8190 return SDValue(); 8191 } 8192 8193 // Try to form VWMUL, VWMULU or VWMULSU. 8194 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8195 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8196 bool Commute) { 8197 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8198 SDValue Op0 = N->getOperand(0); 8199 SDValue Op1 = N->getOperand(1); 8200 if (Commute) 8201 std::swap(Op0, Op1); 8202 8203 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8204 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8205 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8206 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8207 return SDValue(); 8208 8209 SDValue Mask = N->getOperand(2); 8210 SDValue VL = N->getOperand(3); 8211 8212 // Make sure the mask and VL match. 8213 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8214 return SDValue(); 8215 8216 MVT VT = N->getSimpleValueType(0); 8217 8218 // Determine the narrow size for a widening multiply. 8219 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8220 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8221 VT.getVectorElementCount()); 8222 8223 SDLoc DL(N); 8224 8225 // See if the other operand is the same opcode. 8226 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8227 if (!Op1.hasOneUse()) 8228 return SDValue(); 8229 8230 // Make sure the mask and VL match. 8231 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8232 return SDValue(); 8233 8234 Op1 = Op1.getOperand(0); 8235 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8236 // The operand is a splat of a scalar. 8237 8238 // The pasthru must be undef for tail agnostic 8239 if (!Op1.getOperand(0).isUndef()) 8240 return SDValue(); 8241 // The VL must be the same. 8242 if (Op1.getOperand(2) != VL) 8243 return SDValue(); 8244 8245 // Get the scalar value. 8246 Op1 = Op1.getOperand(1); 8247 8248 // See if have enough sign bits or zero bits in the scalar to use a 8249 // widening multiply by splatting to smaller element size. 8250 unsigned EltBits = VT.getScalarSizeInBits(); 8251 unsigned ScalarBits = Op1.getValueSizeInBits(); 8252 // Make sure we're getting all element bits from the scalar register. 8253 // FIXME: Support implicit sign extension of vmv.v.x? 8254 if (ScalarBits < EltBits) 8255 return SDValue(); 8256 8257 // If the LHS is a sign extend, try to use vwmul. 8258 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8259 // Can use vwmul. 8260 } else { 8261 // Otherwise try to use vwmulu or vwmulsu. 8262 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8263 if (DAG.MaskedValueIsZero(Op1, Mask)) 8264 IsVWMULSU = IsSignExt; 8265 else 8266 return SDValue(); 8267 } 8268 8269 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8270 DAG.getUNDEF(NarrowVT), Op1, VL); 8271 } else 8272 return SDValue(); 8273 8274 Op0 = Op0.getOperand(0); 8275 8276 // Re-introduce narrower extends if needed. 8277 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8278 if (Op0.getValueType() != NarrowVT) 8279 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8280 // vwmulsu requires second operand to be zero extended. 8281 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8282 if (Op1.getValueType() != NarrowVT) 8283 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8284 8285 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8286 if (!IsVWMULSU) 8287 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8288 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8289 } 8290 8291 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8292 switch (Op.getOpcode()) { 8293 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8294 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8295 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8296 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8297 case ISD::FROUND: return RISCVFPRndMode::RMM; 8298 } 8299 8300 return RISCVFPRndMode::Invalid; 8301 } 8302 8303 // Fold 8304 // (fp_to_int (froundeven X)) -> fcvt X, rne 8305 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8306 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8307 // (fp_to_int (fceil X)) -> fcvt X, rup 8308 // (fp_to_int (fround X)) -> fcvt X, rmm 8309 static SDValue performFP_TO_INTCombine(SDNode *N, 8310 TargetLowering::DAGCombinerInfo &DCI, 8311 const RISCVSubtarget &Subtarget) { 8312 SelectionDAG &DAG = DCI.DAG; 8313 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8314 MVT XLenVT = Subtarget.getXLenVT(); 8315 8316 // Only handle XLen or i32 types. Other types narrower than XLen will 8317 // eventually be legalized to XLenVT. 8318 EVT VT = N->getValueType(0); 8319 if (VT != MVT::i32 && VT != XLenVT) 8320 return SDValue(); 8321 8322 SDValue Src = N->getOperand(0); 8323 8324 // Ensure the FP type is also legal. 8325 if (!TLI.isTypeLegal(Src.getValueType())) 8326 return SDValue(); 8327 8328 // Don't do this for f16 with Zfhmin and not Zfh. 8329 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8330 return SDValue(); 8331 8332 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8333 if (FRM == RISCVFPRndMode::Invalid) 8334 return SDValue(); 8335 8336 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8337 8338 unsigned Opc; 8339 if (VT == XLenVT) 8340 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8341 else 8342 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8343 8344 SDLoc DL(N); 8345 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8346 DAG.getTargetConstant(FRM, DL, XLenVT)); 8347 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8348 } 8349 8350 // Fold 8351 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8352 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8353 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8354 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8355 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8356 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8357 TargetLowering::DAGCombinerInfo &DCI, 8358 const RISCVSubtarget &Subtarget) { 8359 SelectionDAG &DAG = DCI.DAG; 8360 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8361 MVT XLenVT = Subtarget.getXLenVT(); 8362 8363 // Only handle XLen types. Other types narrower than XLen will eventually be 8364 // legalized to XLenVT. 8365 EVT DstVT = N->getValueType(0); 8366 if (DstVT != XLenVT) 8367 return SDValue(); 8368 8369 SDValue Src = N->getOperand(0); 8370 8371 // Ensure the FP type is also legal. 8372 if (!TLI.isTypeLegal(Src.getValueType())) 8373 return SDValue(); 8374 8375 // Don't do this for f16 with Zfhmin and not Zfh. 8376 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8377 return SDValue(); 8378 8379 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8380 8381 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8382 if (FRM == RISCVFPRndMode::Invalid) 8383 return SDValue(); 8384 8385 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8386 8387 unsigned Opc; 8388 if (SatVT == DstVT) 8389 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8390 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8391 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8392 else 8393 return SDValue(); 8394 // FIXME: Support other SatVTs by clamping before or after the conversion. 8395 8396 Src = Src.getOperand(0); 8397 8398 SDLoc DL(N); 8399 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8400 DAG.getTargetConstant(FRM, DL, XLenVT)); 8401 8402 // RISCV FP-to-int conversions saturate to the destination register size, but 8403 // don't produce 0 for nan. 8404 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8405 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8406 } 8407 8408 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8409 // smaller than XLenVT. 8410 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8411 const RISCVSubtarget &Subtarget) { 8412 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8413 8414 SDValue Src = N->getOperand(0); 8415 if (Src.getOpcode() != ISD::BSWAP) 8416 return SDValue(); 8417 8418 EVT VT = N->getValueType(0); 8419 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8420 !isPowerOf2_32(VT.getSizeInBits())) 8421 return SDValue(); 8422 8423 SDLoc DL(N); 8424 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8425 DAG.getConstant(7, DL, VT)); 8426 } 8427 8428 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8429 DAGCombinerInfo &DCI) const { 8430 SelectionDAG &DAG = DCI.DAG; 8431 8432 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8433 // bits are demanded. N will be added to the Worklist if it was not deleted. 8434 // Caller should return SDValue(N, 0) if this returns true. 8435 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8436 SDValue Op = N->getOperand(OpNo); 8437 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8438 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8439 return false; 8440 8441 if (N->getOpcode() != ISD::DELETED_NODE) 8442 DCI.AddToWorklist(N); 8443 return true; 8444 }; 8445 8446 switch (N->getOpcode()) { 8447 default: 8448 break; 8449 case RISCVISD::SplitF64: { 8450 SDValue Op0 = N->getOperand(0); 8451 // If the input to SplitF64 is just BuildPairF64 then the operation is 8452 // redundant. Instead, use BuildPairF64's operands directly. 8453 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8454 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8455 8456 if (Op0->isUndef()) { 8457 SDValue Lo = DAG.getUNDEF(MVT::i32); 8458 SDValue Hi = DAG.getUNDEF(MVT::i32); 8459 return DCI.CombineTo(N, Lo, Hi); 8460 } 8461 8462 SDLoc DL(N); 8463 8464 // It's cheaper to materialise two 32-bit integers than to load a double 8465 // from the constant pool and transfer it to integer registers through the 8466 // stack. 8467 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8468 APInt V = C->getValueAPF().bitcastToAPInt(); 8469 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8470 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8471 return DCI.CombineTo(N, Lo, Hi); 8472 } 8473 8474 // This is a target-specific version of a DAGCombine performed in 8475 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8476 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8477 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8478 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8479 !Op0.getNode()->hasOneUse()) 8480 break; 8481 SDValue NewSplitF64 = 8482 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8483 Op0.getOperand(0)); 8484 SDValue Lo = NewSplitF64.getValue(0); 8485 SDValue Hi = NewSplitF64.getValue(1); 8486 APInt SignBit = APInt::getSignMask(32); 8487 if (Op0.getOpcode() == ISD::FNEG) { 8488 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8489 DAG.getConstant(SignBit, DL, MVT::i32)); 8490 return DCI.CombineTo(N, Lo, NewHi); 8491 } 8492 assert(Op0.getOpcode() == ISD::FABS); 8493 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8494 DAG.getConstant(~SignBit, DL, MVT::i32)); 8495 return DCI.CombineTo(N, Lo, NewHi); 8496 } 8497 case RISCVISD::SLLW: 8498 case RISCVISD::SRAW: 8499 case RISCVISD::SRLW: { 8500 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8501 if (SimplifyDemandedLowBitsHelper(0, 32) || 8502 SimplifyDemandedLowBitsHelper(1, 5)) 8503 return SDValue(N, 0); 8504 8505 break; 8506 } 8507 case ISD::ROTR: 8508 case ISD::ROTL: 8509 case RISCVISD::RORW: 8510 case RISCVISD::ROLW: { 8511 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8512 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8513 if (SimplifyDemandedLowBitsHelper(0, 32) || 8514 SimplifyDemandedLowBitsHelper(1, 5)) 8515 return SDValue(N, 0); 8516 } 8517 8518 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8519 } 8520 case RISCVISD::CLZW: 8521 case RISCVISD::CTZW: { 8522 // Only the lower 32 bits of the first operand are read 8523 if (SimplifyDemandedLowBitsHelper(0, 32)) 8524 return SDValue(N, 0); 8525 break; 8526 } 8527 case RISCVISD::GREV: 8528 case RISCVISD::GORC: { 8529 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8530 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8531 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8532 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8533 return SDValue(N, 0); 8534 8535 return combineGREVI_GORCI(N, DAG); 8536 } 8537 case RISCVISD::GREVW: 8538 case RISCVISD::GORCW: { 8539 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8540 if (SimplifyDemandedLowBitsHelper(0, 32) || 8541 SimplifyDemandedLowBitsHelper(1, 5)) 8542 return SDValue(N, 0); 8543 8544 break; 8545 } 8546 case RISCVISD::SHFL: 8547 case RISCVISD::UNSHFL: { 8548 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8549 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8550 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8551 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8552 return SDValue(N, 0); 8553 8554 break; 8555 } 8556 case RISCVISD::SHFLW: 8557 case RISCVISD::UNSHFLW: { 8558 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8559 if (SimplifyDemandedLowBitsHelper(0, 32) || 8560 SimplifyDemandedLowBitsHelper(1, 4)) 8561 return SDValue(N, 0); 8562 8563 break; 8564 } 8565 case RISCVISD::BCOMPRESSW: 8566 case RISCVISD::BDECOMPRESSW: { 8567 // Only the lower 32 bits of LHS and RHS are read. 8568 if (SimplifyDemandedLowBitsHelper(0, 32) || 8569 SimplifyDemandedLowBitsHelper(1, 32)) 8570 return SDValue(N, 0); 8571 8572 break; 8573 } 8574 case RISCVISD::FSR: 8575 case RISCVISD::FSL: 8576 case RISCVISD::FSRW: 8577 case RISCVISD::FSLW: { 8578 bool IsWInstruction = 8579 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8580 unsigned BitWidth = 8581 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8582 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8583 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8584 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8585 return SDValue(N, 0); 8586 8587 break; 8588 } 8589 case RISCVISD::FMV_X_ANYEXTH: 8590 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8591 SDLoc DL(N); 8592 SDValue Op0 = N->getOperand(0); 8593 MVT VT = N->getSimpleValueType(0); 8594 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8595 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8596 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8597 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8598 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8599 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8600 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8601 assert(Op0.getOperand(0).getValueType() == VT && 8602 "Unexpected value type!"); 8603 return Op0.getOperand(0); 8604 } 8605 8606 // This is a target-specific version of a DAGCombine performed in 8607 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8608 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8609 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8610 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8611 !Op0.getNode()->hasOneUse()) 8612 break; 8613 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8614 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8615 APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits()); 8616 if (Op0.getOpcode() == ISD::FNEG) 8617 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8618 DAG.getConstant(SignBit, DL, VT)); 8619 8620 assert(Op0.getOpcode() == ISD::FABS); 8621 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8622 DAG.getConstant(~SignBit, DL, VT)); 8623 } 8624 case ISD::ADD: 8625 return performADDCombine(N, DAG, Subtarget); 8626 case ISD::SUB: 8627 return performSUBCombine(N, DAG); 8628 case ISD::AND: 8629 return performANDCombine(N, DAG, Subtarget); 8630 case ISD::OR: 8631 return performORCombine(N, DAG, Subtarget); 8632 case ISD::XOR: 8633 return performXORCombine(N, DAG); 8634 case ISD::FADD: 8635 case ISD::UMAX: 8636 case ISD::UMIN: 8637 case ISD::SMAX: 8638 case ISD::SMIN: 8639 case ISD::FMAXNUM: 8640 case ISD::FMINNUM: 8641 return combineBinOpToReduce(N, DAG); 8642 case ISD::SIGN_EXTEND_INREG: 8643 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8644 case ISD::ZERO_EXTEND: 8645 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8646 // type legalization. This is safe because fp_to_uint produces poison if 8647 // it overflows. 8648 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8649 SDValue Src = N->getOperand(0); 8650 if (Src.getOpcode() == ISD::FP_TO_UINT && 8651 isTypeLegal(Src.getOperand(0).getValueType())) 8652 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8653 Src.getOperand(0)); 8654 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8655 isTypeLegal(Src.getOperand(1).getValueType())) { 8656 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8657 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8658 Src.getOperand(0), Src.getOperand(1)); 8659 DCI.CombineTo(N, Res); 8660 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8661 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8662 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8663 } 8664 } 8665 return SDValue(); 8666 case RISCVISD::SELECT_CC: { 8667 // Transform 8668 SDValue LHS = N->getOperand(0); 8669 SDValue RHS = N->getOperand(1); 8670 SDValue TrueV = N->getOperand(3); 8671 SDValue FalseV = N->getOperand(4); 8672 8673 // If the True and False values are the same, we don't need a select_cc. 8674 if (TrueV == FalseV) 8675 return TrueV; 8676 8677 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8678 if (!ISD::isIntEqualitySetCC(CCVal)) 8679 break; 8680 8681 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8682 // (select_cc X, Y, lt, trueV, falseV) 8683 // Sometimes the setcc is introduced after select_cc has been formed. 8684 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8685 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8686 // If we're looking for eq 0 instead of ne 0, we need to invert the 8687 // condition. 8688 bool Invert = CCVal == ISD::SETEQ; 8689 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8690 if (Invert) 8691 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8692 8693 SDLoc DL(N); 8694 RHS = LHS.getOperand(1); 8695 LHS = LHS.getOperand(0); 8696 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8697 8698 SDValue TargetCC = DAG.getCondCode(CCVal); 8699 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8700 {LHS, RHS, TargetCC, TrueV, FalseV}); 8701 } 8702 8703 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8704 // (select_cc X, Y, eq/ne, trueV, falseV) 8705 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8706 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8707 {LHS.getOperand(0), LHS.getOperand(1), 8708 N->getOperand(2), TrueV, FalseV}); 8709 // (select_cc X, 1, setne, trueV, falseV) -> 8710 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8711 // This can occur when legalizing some floating point comparisons. 8712 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8713 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8714 SDLoc DL(N); 8715 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8716 SDValue TargetCC = DAG.getCondCode(CCVal); 8717 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8718 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8719 {LHS, RHS, TargetCC, TrueV, FalseV}); 8720 } 8721 8722 break; 8723 } 8724 case RISCVISD::BR_CC: { 8725 SDValue LHS = N->getOperand(1); 8726 SDValue RHS = N->getOperand(2); 8727 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8728 if (!ISD::isIntEqualitySetCC(CCVal)) 8729 break; 8730 8731 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8732 // (br_cc X, Y, lt, dest) 8733 // Sometimes the setcc is introduced after br_cc has been formed. 8734 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8735 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8736 // If we're looking for eq 0 instead of ne 0, we need to invert the 8737 // condition. 8738 bool Invert = CCVal == ISD::SETEQ; 8739 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8740 if (Invert) 8741 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8742 8743 SDLoc DL(N); 8744 RHS = LHS.getOperand(1); 8745 LHS = LHS.getOperand(0); 8746 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8747 8748 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8749 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8750 N->getOperand(4)); 8751 } 8752 8753 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8754 // (br_cc X, Y, eq/ne, trueV, falseV) 8755 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8756 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8757 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8758 N->getOperand(3), N->getOperand(4)); 8759 8760 // (br_cc X, 1, setne, br_cc) -> 8761 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8762 // This can occur when legalizing some floating point comparisons. 8763 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8764 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8765 SDLoc DL(N); 8766 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8767 SDValue TargetCC = DAG.getCondCode(CCVal); 8768 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8769 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8770 N->getOperand(0), LHS, RHS, TargetCC, 8771 N->getOperand(4)); 8772 } 8773 break; 8774 } 8775 case ISD::BITREVERSE: 8776 return performBITREVERSECombine(N, DAG, Subtarget); 8777 case ISD::FP_TO_SINT: 8778 case ISD::FP_TO_UINT: 8779 return performFP_TO_INTCombine(N, DCI, Subtarget); 8780 case ISD::FP_TO_SINT_SAT: 8781 case ISD::FP_TO_UINT_SAT: 8782 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8783 case ISD::FCOPYSIGN: { 8784 EVT VT = N->getValueType(0); 8785 if (!VT.isVector()) 8786 break; 8787 // There is a form of VFSGNJ which injects the negated sign of its second 8788 // operand. Try and bubble any FNEG up after the extend/round to produce 8789 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8790 // TRUNC=1. 8791 SDValue In2 = N->getOperand(1); 8792 // Avoid cases where the extend/round has multiple uses, as duplicating 8793 // those is typically more expensive than removing a fneg. 8794 if (!In2.hasOneUse()) 8795 break; 8796 if (In2.getOpcode() != ISD::FP_EXTEND && 8797 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8798 break; 8799 In2 = In2.getOperand(0); 8800 if (In2.getOpcode() != ISD::FNEG) 8801 break; 8802 SDLoc DL(N); 8803 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8804 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8805 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8806 } 8807 case ISD::MGATHER: 8808 case ISD::MSCATTER: 8809 case ISD::VP_GATHER: 8810 case ISD::VP_SCATTER: { 8811 if (!DCI.isBeforeLegalize()) 8812 break; 8813 SDValue Index, ScaleOp; 8814 bool IsIndexScaled = false; 8815 bool IsIndexSigned = false; 8816 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8817 Index = VPGSN->getIndex(); 8818 ScaleOp = VPGSN->getScale(); 8819 IsIndexScaled = VPGSN->isIndexScaled(); 8820 IsIndexSigned = VPGSN->isIndexSigned(); 8821 } else { 8822 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8823 Index = MGSN->getIndex(); 8824 ScaleOp = MGSN->getScale(); 8825 IsIndexScaled = MGSN->isIndexScaled(); 8826 IsIndexSigned = MGSN->isIndexSigned(); 8827 } 8828 EVT IndexVT = Index.getValueType(); 8829 MVT XLenVT = Subtarget.getXLenVT(); 8830 // RISCV indexed loads only support the "unsigned unscaled" addressing 8831 // mode, so anything else must be manually legalized. 8832 bool NeedsIdxLegalization = 8833 IsIndexScaled || 8834 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8835 if (!NeedsIdxLegalization) 8836 break; 8837 8838 SDLoc DL(N); 8839 8840 // Any index legalization should first promote to XLenVT, so we don't lose 8841 // bits when scaling. This may create an illegal index type so we let 8842 // LLVM's legalization take care of the splitting. 8843 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8844 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8845 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8846 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8847 DL, IndexVT, Index); 8848 } 8849 8850 if (IsIndexScaled) { 8851 // Manually scale the indices. 8852 // TODO: Sanitize the scale operand here? 8853 // TODO: For VP nodes, should we use VP_SHL here? 8854 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8855 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8856 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8857 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8858 ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType()); 8859 } 8860 8861 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED; 8862 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8863 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8864 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8865 ScaleOp, VPGN->getMask(), 8866 VPGN->getVectorLength()}, 8867 VPGN->getMemOperand(), NewIndexTy); 8868 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8869 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8870 {VPSN->getChain(), VPSN->getValue(), 8871 VPSN->getBasePtr(), Index, ScaleOp, 8872 VPSN->getMask(), VPSN->getVectorLength()}, 8873 VPSN->getMemOperand(), NewIndexTy); 8874 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8875 return DAG.getMaskedGather( 8876 N->getVTList(), MGN->getMemoryVT(), DL, 8877 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8878 MGN->getBasePtr(), Index, ScaleOp}, 8879 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8880 const auto *MSN = cast<MaskedScatterSDNode>(N); 8881 return DAG.getMaskedScatter( 8882 N->getVTList(), MSN->getMemoryVT(), DL, 8883 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8884 Index, ScaleOp}, 8885 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8886 } 8887 case RISCVISD::SRA_VL: 8888 case RISCVISD::SRL_VL: 8889 case RISCVISD::SHL_VL: { 8890 SDValue ShAmt = N->getOperand(1); 8891 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8892 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8893 SDLoc DL(N); 8894 SDValue VL = N->getOperand(3); 8895 EVT VT = N->getValueType(0); 8896 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8897 ShAmt.getOperand(1), VL); 8898 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8899 N->getOperand(2), N->getOperand(3)); 8900 } 8901 break; 8902 } 8903 case ISD::SRA: 8904 case ISD::SRL: 8905 case ISD::SHL: { 8906 SDValue ShAmt = N->getOperand(1); 8907 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8908 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8909 SDLoc DL(N); 8910 EVT VT = N->getValueType(0); 8911 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8912 ShAmt.getOperand(1), 8913 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8914 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8915 } 8916 break; 8917 } 8918 case RISCVISD::ADD_VL: 8919 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8920 return V; 8921 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8922 case RISCVISD::SUB_VL: 8923 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8924 case RISCVISD::VWADD_W_VL: 8925 case RISCVISD::VWADDU_W_VL: 8926 case RISCVISD::VWSUB_W_VL: 8927 case RISCVISD::VWSUBU_W_VL: 8928 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8929 case RISCVISD::MUL_VL: 8930 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8931 return V; 8932 // Mul is commutative. 8933 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8934 case ISD::STORE: { 8935 auto *Store = cast<StoreSDNode>(N); 8936 SDValue Val = Store->getValue(); 8937 // Combine store of vmv.x.s to vse with VL of 1. 8938 // FIXME: Support FP. 8939 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8940 SDValue Src = Val.getOperand(0); 8941 EVT VecVT = Src.getValueType(); 8942 EVT MemVT = Store->getMemoryVT(); 8943 // The memory VT and the element type must match. 8944 if (VecVT.getVectorElementType() == MemVT) { 8945 SDLoc DL(N); 8946 MVT MaskVT = getMaskTypeFor(VecVT); 8947 return DAG.getStoreVP( 8948 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8949 DAG.getConstant(1, DL, MaskVT), 8950 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8951 Store->getMemOperand(), Store->getAddressingMode(), 8952 Store->isTruncatingStore(), /*IsCompress*/ false); 8953 } 8954 } 8955 8956 break; 8957 } 8958 case ISD::SPLAT_VECTOR: { 8959 EVT VT = N->getValueType(0); 8960 // Only perform this combine on legal MVT types. 8961 if (!isTypeLegal(VT)) 8962 break; 8963 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8964 DAG, Subtarget)) 8965 return Gather; 8966 break; 8967 } 8968 case RISCVISD::VMV_V_X_VL: { 8969 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8970 // scalar input. 8971 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8972 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8973 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8974 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8975 return SDValue(N, 0); 8976 8977 break; 8978 } 8979 case ISD::INTRINSIC_WO_CHAIN: { 8980 unsigned IntNo = N->getConstantOperandVal(0); 8981 switch (IntNo) { 8982 // By default we do not combine any intrinsic. 8983 default: 8984 return SDValue(); 8985 case Intrinsic::riscv_vcpop: 8986 case Intrinsic::riscv_vcpop_mask: 8987 case Intrinsic::riscv_vfirst: 8988 case Intrinsic::riscv_vfirst_mask: { 8989 SDValue VL = N->getOperand(2); 8990 if (IntNo == Intrinsic::riscv_vcpop_mask || 8991 IntNo == Intrinsic::riscv_vfirst_mask) 8992 VL = N->getOperand(3); 8993 if (!isNullConstant(VL)) 8994 return SDValue(); 8995 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8996 SDLoc DL(N); 8997 EVT VT = N->getValueType(0); 8998 if (IntNo == Intrinsic::riscv_vfirst || 8999 IntNo == Intrinsic::riscv_vfirst_mask) 9000 return DAG.getConstant(-1, DL, VT); 9001 return DAG.getConstant(0, DL, VT); 9002 } 9003 } 9004 } 9005 } 9006 9007 return SDValue(); 9008 } 9009 9010 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 9011 const SDNode *N, CombineLevel Level) const { 9012 // The following folds are only desirable if `(OP _, c1 << c2)` can be 9013 // materialised in fewer instructions than `(OP _, c1)`: 9014 // 9015 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9016 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9017 SDValue N0 = N->getOperand(0); 9018 EVT Ty = N0.getValueType(); 9019 if (Ty.isScalarInteger() && 9020 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9021 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9022 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9023 if (C1 && C2) { 9024 const APInt &C1Int = C1->getAPIntValue(); 9025 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9026 9027 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9028 // and the combine should happen, to potentially allow further combines 9029 // later. 9030 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9031 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9032 return true; 9033 9034 // We can materialise `c1` in an add immediate, so it's "free", and the 9035 // combine should be prevented. 9036 if (C1Int.getMinSignedBits() <= 64 && 9037 isLegalAddImmediate(C1Int.getSExtValue())) 9038 return false; 9039 9040 // Neither constant will fit into an immediate, so find materialisation 9041 // costs. 9042 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9043 Subtarget.getFeatureBits(), 9044 /*CompressionCost*/true); 9045 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9046 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9047 /*CompressionCost*/true); 9048 9049 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9050 // combine should be prevented. 9051 if (C1Cost < ShiftedC1Cost) 9052 return false; 9053 } 9054 } 9055 return true; 9056 } 9057 9058 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9059 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9060 TargetLoweringOpt &TLO) const { 9061 // Delay this optimization as late as possible. 9062 if (!TLO.LegalOps) 9063 return false; 9064 9065 EVT VT = Op.getValueType(); 9066 if (VT.isVector()) 9067 return false; 9068 9069 // Only handle AND for now. 9070 if (Op.getOpcode() != ISD::AND) 9071 return false; 9072 9073 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9074 if (!C) 9075 return false; 9076 9077 const APInt &Mask = C->getAPIntValue(); 9078 9079 // Clear all non-demanded bits initially. 9080 APInt ShrunkMask = Mask & DemandedBits; 9081 9082 // Try to make a smaller immediate by setting undemanded bits. 9083 9084 APInt ExpandedMask = Mask | ~DemandedBits; 9085 9086 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9087 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9088 }; 9089 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 9090 if (NewMask == Mask) 9091 return true; 9092 SDLoc DL(Op); 9093 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 9094 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 9095 return TLO.CombineTo(Op, NewOp); 9096 }; 9097 9098 // If the shrunk mask fits in sign extended 12 bits, let the target 9099 // independent code apply it. 9100 if (ShrunkMask.isSignedIntN(12)) 9101 return false; 9102 9103 // Preserve (and X, 0xffff) when zext.h is supported. 9104 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9105 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9106 if (IsLegalMask(NewMask)) 9107 return UseMask(NewMask); 9108 } 9109 9110 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9111 if (VT == MVT::i64) { 9112 APInt NewMask = APInt(64, 0xffffffff); 9113 if (IsLegalMask(NewMask)) 9114 return UseMask(NewMask); 9115 } 9116 9117 // For the remaining optimizations, we need to be able to make a negative 9118 // number through a combination of mask and undemanded bits. 9119 if (!ExpandedMask.isNegative()) 9120 return false; 9121 9122 // What is the fewest number of bits we need to represent the negative number. 9123 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9124 9125 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9126 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9127 APInt NewMask = ShrunkMask; 9128 if (MinSignedBits <= 12) 9129 NewMask.setBitsFrom(11); 9130 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9131 NewMask.setBitsFrom(31); 9132 else 9133 return false; 9134 9135 // Check that our new mask is a subset of the demanded mask. 9136 assert(IsLegalMask(NewMask)); 9137 return UseMask(NewMask); 9138 } 9139 9140 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9141 static const uint64_t GREVMasks[] = { 9142 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9143 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9144 9145 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9146 unsigned Shift = 1 << Stage; 9147 if (ShAmt & Shift) { 9148 uint64_t Mask = GREVMasks[Stage]; 9149 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9150 if (IsGORC) 9151 Res |= x; 9152 x = Res; 9153 } 9154 } 9155 9156 return x; 9157 } 9158 9159 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9160 KnownBits &Known, 9161 const APInt &DemandedElts, 9162 const SelectionDAG &DAG, 9163 unsigned Depth) const { 9164 unsigned BitWidth = Known.getBitWidth(); 9165 unsigned Opc = Op.getOpcode(); 9166 assert((Opc >= ISD::BUILTIN_OP_END || 9167 Opc == ISD::INTRINSIC_WO_CHAIN || 9168 Opc == ISD::INTRINSIC_W_CHAIN || 9169 Opc == ISD::INTRINSIC_VOID) && 9170 "Should use MaskedValueIsZero if you don't know whether Op" 9171 " is a target node!"); 9172 9173 Known.resetAll(); 9174 switch (Opc) { 9175 default: break; 9176 case RISCVISD::SELECT_CC: { 9177 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9178 // If we don't know any bits, early out. 9179 if (Known.isUnknown()) 9180 break; 9181 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9182 9183 // Only known if known in both the LHS and RHS. 9184 Known = KnownBits::commonBits(Known, Known2); 9185 break; 9186 } 9187 case RISCVISD::REMUW: { 9188 KnownBits Known2; 9189 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9190 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9191 // We only care about the lower 32 bits. 9192 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9193 // Restore the original width by sign extending. 9194 Known = Known.sext(BitWidth); 9195 break; 9196 } 9197 case RISCVISD::DIVUW: { 9198 KnownBits Known2; 9199 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9200 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9201 // We only care about the lower 32 bits. 9202 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9203 // Restore the original width by sign extending. 9204 Known = Known.sext(BitWidth); 9205 break; 9206 } 9207 case RISCVISD::CTZW: { 9208 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9209 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9210 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9211 Known.Zero.setBitsFrom(LowBits); 9212 break; 9213 } 9214 case RISCVISD::CLZW: { 9215 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9216 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9217 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9218 Known.Zero.setBitsFrom(LowBits); 9219 break; 9220 } 9221 case RISCVISD::GREV: 9222 case RISCVISD::GORC: { 9223 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9224 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9225 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9226 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9227 // To compute zeros, we need to invert the value and invert it back after. 9228 Known.Zero = 9229 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9230 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9231 } 9232 break; 9233 } 9234 case RISCVISD::READ_VLENB: { 9235 // If we know the minimum VLen from Zvl extensions, we can use that to 9236 // determine the trailing zeros of VLENB. 9237 // FIXME: Limit to 128 bit vectors until we have more testing. 9238 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 9239 if (MinVLenB > 0) 9240 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9241 // We assume VLENB is no more than 65536 / 8 bytes. 9242 Known.Zero.setBitsFrom(14); 9243 break; 9244 } 9245 case ISD::INTRINSIC_W_CHAIN: 9246 case ISD::INTRINSIC_WO_CHAIN: { 9247 unsigned IntNo = 9248 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9249 switch (IntNo) { 9250 default: 9251 // We can't do anything for most intrinsics. 9252 break; 9253 case Intrinsic::riscv_vsetvli: 9254 case Intrinsic::riscv_vsetvlimax: 9255 case Intrinsic::riscv_vsetvli_opt: 9256 case Intrinsic::riscv_vsetvlimax_opt: 9257 // Assume that VL output is positive and would fit in an int32_t. 9258 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9259 if (BitWidth >= 32) 9260 Known.Zero.setBitsFrom(31); 9261 break; 9262 } 9263 break; 9264 } 9265 } 9266 } 9267 9268 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9269 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9270 unsigned Depth) const { 9271 switch (Op.getOpcode()) { 9272 default: 9273 break; 9274 case RISCVISD::SELECT_CC: { 9275 unsigned Tmp = 9276 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9277 if (Tmp == 1) return 1; // Early out. 9278 unsigned Tmp2 = 9279 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9280 return std::min(Tmp, Tmp2); 9281 } 9282 case RISCVISD::SLLW: 9283 case RISCVISD::SRAW: 9284 case RISCVISD::SRLW: 9285 case RISCVISD::DIVW: 9286 case RISCVISD::DIVUW: 9287 case RISCVISD::REMUW: 9288 case RISCVISD::ROLW: 9289 case RISCVISD::RORW: 9290 case RISCVISD::GREVW: 9291 case RISCVISD::GORCW: 9292 case RISCVISD::FSLW: 9293 case RISCVISD::FSRW: 9294 case RISCVISD::SHFLW: 9295 case RISCVISD::UNSHFLW: 9296 case RISCVISD::BCOMPRESSW: 9297 case RISCVISD::BDECOMPRESSW: 9298 case RISCVISD::BFPW: 9299 case RISCVISD::FCVT_W_RV64: 9300 case RISCVISD::FCVT_WU_RV64: 9301 case RISCVISD::STRICT_FCVT_W_RV64: 9302 case RISCVISD::STRICT_FCVT_WU_RV64: 9303 // TODO: As the result is sign-extended, this is conservatively correct. A 9304 // more precise answer could be calculated for SRAW depending on known 9305 // bits in the shift amount. 9306 return 33; 9307 case RISCVISD::SHFL: 9308 case RISCVISD::UNSHFL: { 9309 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9310 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9311 // will stay within the upper 32 bits. If there were more than 32 sign bits 9312 // before there will be at least 33 sign bits after. 9313 if (Op.getValueType() == MVT::i64 && 9314 isa<ConstantSDNode>(Op.getOperand(1)) && 9315 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9316 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9317 if (Tmp > 32) 9318 return 33; 9319 } 9320 break; 9321 } 9322 case RISCVISD::VMV_X_S: { 9323 // The number of sign bits of the scalar result is computed by obtaining the 9324 // element type of the input vector operand, subtracting its width from the 9325 // XLEN, and then adding one (sign bit within the element type). If the 9326 // element type is wider than XLen, the least-significant XLEN bits are 9327 // taken. 9328 unsigned XLen = Subtarget.getXLen(); 9329 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9330 if (EltBits <= XLen) 9331 return XLen - EltBits + 1; 9332 break; 9333 } 9334 } 9335 9336 return 1; 9337 } 9338 9339 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9340 MachineBasicBlock *BB) { 9341 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9342 9343 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9344 // Should the count have wrapped while it was being read, we need to try 9345 // again. 9346 // ... 9347 // read: 9348 // rdcycleh x3 # load high word of cycle 9349 // rdcycle x2 # load low word of cycle 9350 // rdcycleh x4 # load high word of cycle 9351 // bne x3, x4, read # check if high word reads match, otherwise try again 9352 // ... 9353 9354 MachineFunction &MF = *BB->getParent(); 9355 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9356 MachineFunction::iterator It = ++BB->getIterator(); 9357 9358 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9359 MF.insert(It, LoopMBB); 9360 9361 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9362 MF.insert(It, DoneMBB); 9363 9364 // Transfer the remainder of BB and its successor edges to DoneMBB. 9365 DoneMBB->splice(DoneMBB->begin(), BB, 9366 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9367 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9368 9369 BB->addSuccessor(LoopMBB); 9370 9371 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9372 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9373 Register LoReg = MI.getOperand(0).getReg(); 9374 Register HiReg = MI.getOperand(1).getReg(); 9375 DebugLoc DL = MI.getDebugLoc(); 9376 9377 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9378 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9379 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9380 .addReg(RISCV::X0); 9381 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9382 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9383 .addReg(RISCV::X0); 9384 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9385 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9386 .addReg(RISCV::X0); 9387 9388 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9389 .addReg(HiReg) 9390 .addReg(ReadAgainReg) 9391 .addMBB(LoopMBB); 9392 9393 LoopMBB->addSuccessor(LoopMBB); 9394 LoopMBB->addSuccessor(DoneMBB); 9395 9396 MI.eraseFromParent(); 9397 9398 return DoneMBB; 9399 } 9400 9401 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9402 MachineBasicBlock *BB) { 9403 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9404 9405 MachineFunction &MF = *BB->getParent(); 9406 DebugLoc DL = MI.getDebugLoc(); 9407 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9408 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9409 Register LoReg = MI.getOperand(0).getReg(); 9410 Register HiReg = MI.getOperand(1).getReg(); 9411 Register SrcReg = MI.getOperand(2).getReg(); 9412 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9413 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9414 9415 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9416 RI); 9417 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9418 MachineMemOperand *MMOLo = 9419 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9420 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9421 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9422 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9423 .addFrameIndex(FI) 9424 .addImm(0) 9425 .addMemOperand(MMOLo); 9426 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9427 .addFrameIndex(FI) 9428 .addImm(4) 9429 .addMemOperand(MMOHi); 9430 MI.eraseFromParent(); // The pseudo instruction is gone now. 9431 return BB; 9432 } 9433 9434 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9435 MachineBasicBlock *BB) { 9436 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9437 "Unexpected instruction"); 9438 9439 MachineFunction &MF = *BB->getParent(); 9440 DebugLoc DL = MI.getDebugLoc(); 9441 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9442 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9443 Register DstReg = MI.getOperand(0).getReg(); 9444 Register LoReg = MI.getOperand(1).getReg(); 9445 Register HiReg = MI.getOperand(2).getReg(); 9446 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9447 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9448 9449 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9450 MachineMemOperand *MMOLo = 9451 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9452 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9453 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9454 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9455 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9456 .addFrameIndex(FI) 9457 .addImm(0) 9458 .addMemOperand(MMOLo); 9459 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9460 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9461 .addFrameIndex(FI) 9462 .addImm(4) 9463 .addMemOperand(MMOHi); 9464 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9465 MI.eraseFromParent(); // The pseudo instruction is gone now. 9466 return BB; 9467 } 9468 9469 static bool isSelectPseudo(MachineInstr &MI) { 9470 switch (MI.getOpcode()) { 9471 default: 9472 return false; 9473 case RISCV::Select_GPR_Using_CC_GPR: 9474 case RISCV::Select_FPR16_Using_CC_GPR: 9475 case RISCV::Select_FPR32_Using_CC_GPR: 9476 case RISCV::Select_FPR64_Using_CC_GPR: 9477 return true; 9478 } 9479 } 9480 9481 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9482 unsigned RelOpcode, unsigned EqOpcode, 9483 const RISCVSubtarget &Subtarget) { 9484 DebugLoc DL = MI.getDebugLoc(); 9485 Register DstReg = MI.getOperand(0).getReg(); 9486 Register Src1Reg = MI.getOperand(1).getReg(); 9487 Register Src2Reg = MI.getOperand(2).getReg(); 9488 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9489 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9490 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9491 9492 // Save the current FFLAGS. 9493 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9494 9495 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9496 .addReg(Src1Reg) 9497 .addReg(Src2Reg); 9498 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9499 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9500 9501 // Restore the FFLAGS. 9502 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9503 .addReg(SavedFFlags, RegState::Kill); 9504 9505 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9506 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9507 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9508 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9509 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9510 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9511 9512 // Erase the pseudoinstruction. 9513 MI.eraseFromParent(); 9514 return BB; 9515 } 9516 9517 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9518 MachineBasicBlock *BB, 9519 const RISCVSubtarget &Subtarget) { 9520 // To "insert" Select_* instructions, we actually have to insert the triangle 9521 // control-flow pattern. The incoming instructions know the destination vreg 9522 // to set, the condition code register to branch on, the true/false values to 9523 // select between, and the condcode to use to select the appropriate branch. 9524 // 9525 // We produce the following control flow: 9526 // HeadMBB 9527 // | \ 9528 // | IfFalseMBB 9529 // | / 9530 // TailMBB 9531 // 9532 // When we find a sequence of selects we attempt to optimize their emission 9533 // by sharing the control flow. Currently we only handle cases where we have 9534 // multiple selects with the exact same condition (same LHS, RHS and CC). 9535 // The selects may be interleaved with other instructions if the other 9536 // instructions meet some requirements we deem safe: 9537 // - They are debug instructions. Otherwise, 9538 // - They do not have side-effects, do not access memory and their inputs do 9539 // not depend on the results of the select pseudo-instructions. 9540 // The TrueV/FalseV operands of the selects cannot depend on the result of 9541 // previous selects in the sequence. 9542 // These conditions could be further relaxed. See the X86 target for a 9543 // related approach and more information. 9544 Register LHS = MI.getOperand(1).getReg(); 9545 Register RHS = MI.getOperand(2).getReg(); 9546 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9547 9548 SmallVector<MachineInstr *, 4> SelectDebugValues; 9549 SmallSet<Register, 4> SelectDests; 9550 SelectDests.insert(MI.getOperand(0).getReg()); 9551 9552 MachineInstr *LastSelectPseudo = &MI; 9553 9554 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9555 SequenceMBBI != E; ++SequenceMBBI) { 9556 if (SequenceMBBI->isDebugInstr()) 9557 continue; 9558 if (isSelectPseudo(*SequenceMBBI)) { 9559 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9560 SequenceMBBI->getOperand(2).getReg() != RHS || 9561 SequenceMBBI->getOperand(3).getImm() != CC || 9562 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9563 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9564 break; 9565 LastSelectPseudo = &*SequenceMBBI; 9566 SequenceMBBI->collectDebugValues(SelectDebugValues); 9567 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9568 } else { 9569 if (SequenceMBBI->hasUnmodeledSideEffects() || 9570 SequenceMBBI->mayLoadOrStore()) 9571 break; 9572 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9573 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9574 })) 9575 break; 9576 } 9577 } 9578 9579 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9580 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9581 DebugLoc DL = MI.getDebugLoc(); 9582 MachineFunction::iterator I = ++BB->getIterator(); 9583 9584 MachineBasicBlock *HeadMBB = BB; 9585 MachineFunction *F = BB->getParent(); 9586 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9587 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9588 9589 F->insert(I, IfFalseMBB); 9590 F->insert(I, TailMBB); 9591 9592 // Transfer debug instructions associated with the selects to TailMBB. 9593 for (MachineInstr *DebugInstr : SelectDebugValues) { 9594 TailMBB->push_back(DebugInstr->removeFromParent()); 9595 } 9596 9597 // Move all instructions after the sequence to TailMBB. 9598 TailMBB->splice(TailMBB->end(), HeadMBB, 9599 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9600 // Update machine-CFG edges by transferring all successors of the current 9601 // block to the new block which will contain the Phi nodes for the selects. 9602 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9603 // Set the successors for HeadMBB. 9604 HeadMBB->addSuccessor(IfFalseMBB); 9605 HeadMBB->addSuccessor(TailMBB); 9606 9607 // Insert appropriate branch. 9608 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9609 .addReg(LHS) 9610 .addReg(RHS) 9611 .addMBB(TailMBB); 9612 9613 // IfFalseMBB just falls through to TailMBB. 9614 IfFalseMBB->addSuccessor(TailMBB); 9615 9616 // Create PHIs for all of the select pseudo-instructions. 9617 auto SelectMBBI = MI.getIterator(); 9618 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9619 auto InsertionPoint = TailMBB->begin(); 9620 while (SelectMBBI != SelectEnd) { 9621 auto Next = std::next(SelectMBBI); 9622 if (isSelectPseudo(*SelectMBBI)) { 9623 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9624 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9625 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9626 .addReg(SelectMBBI->getOperand(4).getReg()) 9627 .addMBB(HeadMBB) 9628 .addReg(SelectMBBI->getOperand(5).getReg()) 9629 .addMBB(IfFalseMBB); 9630 SelectMBBI->eraseFromParent(); 9631 } 9632 SelectMBBI = Next; 9633 } 9634 9635 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9636 return TailMBB; 9637 } 9638 9639 MachineBasicBlock * 9640 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9641 MachineBasicBlock *BB) const { 9642 switch (MI.getOpcode()) { 9643 default: 9644 llvm_unreachable("Unexpected instr type to insert"); 9645 case RISCV::ReadCycleWide: 9646 assert(!Subtarget.is64Bit() && 9647 "ReadCycleWrite is only to be used on riscv32"); 9648 return emitReadCycleWidePseudo(MI, BB); 9649 case RISCV::Select_GPR_Using_CC_GPR: 9650 case RISCV::Select_FPR16_Using_CC_GPR: 9651 case RISCV::Select_FPR32_Using_CC_GPR: 9652 case RISCV::Select_FPR64_Using_CC_GPR: 9653 return emitSelectPseudo(MI, BB, Subtarget); 9654 case RISCV::BuildPairF64Pseudo: 9655 return emitBuildPairF64Pseudo(MI, BB); 9656 case RISCV::SplitF64Pseudo: 9657 return emitSplitF64Pseudo(MI, BB); 9658 case RISCV::PseudoQuietFLE_H: 9659 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9660 case RISCV::PseudoQuietFLT_H: 9661 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9662 case RISCV::PseudoQuietFLE_S: 9663 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9664 case RISCV::PseudoQuietFLT_S: 9665 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9666 case RISCV::PseudoQuietFLE_D: 9667 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9668 case RISCV::PseudoQuietFLT_D: 9669 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9670 } 9671 } 9672 9673 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9674 SDNode *Node) const { 9675 // Add FRM dependency to any instructions with dynamic rounding mode. 9676 unsigned Opc = MI.getOpcode(); 9677 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9678 if (Idx < 0) 9679 return; 9680 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9681 return; 9682 // If the instruction already reads FRM, don't add another read. 9683 if (MI.readsRegister(RISCV::FRM)) 9684 return; 9685 MI.addOperand( 9686 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9687 } 9688 9689 // Calling Convention Implementation. 9690 // The expectations for frontend ABI lowering vary from target to target. 9691 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9692 // details, but this is a longer term goal. For now, we simply try to keep the 9693 // role of the frontend as simple and well-defined as possible. The rules can 9694 // be summarised as: 9695 // * Never split up large scalar arguments. We handle them here. 9696 // * If a hardfloat calling convention is being used, and the struct may be 9697 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9698 // available, then pass as two separate arguments. If either the GPRs or FPRs 9699 // are exhausted, then pass according to the rule below. 9700 // * If a struct could never be passed in registers or directly in a stack 9701 // slot (as it is larger than 2*XLEN and the floating point rules don't 9702 // apply), then pass it using a pointer with the byval attribute. 9703 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9704 // word-sized array or a 2*XLEN scalar (depending on alignment). 9705 // * The frontend can determine whether a struct is returned by reference or 9706 // not based on its size and fields. If it will be returned by reference, the 9707 // frontend must modify the prototype so a pointer with the sret annotation is 9708 // passed as the first argument. This is not necessary for large scalar 9709 // returns. 9710 // * Struct return values and varargs should be coerced to structs containing 9711 // register-size fields in the same situations they would be for fixed 9712 // arguments. 9713 9714 static const MCPhysReg ArgGPRs[] = { 9715 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9716 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9717 }; 9718 static const MCPhysReg ArgFPR16s[] = { 9719 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9720 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9721 }; 9722 static const MCPhysReg ArgFPR32s[] = { 9723 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9724 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9725 }; 9726 static const MCPhysReg ArgFPR64s[] = { 9727 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9728 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9729 }; 9730 // This is an interim calling convention and it may be changed in the future. 9731 static const MCPhysReg ArgVRs[] = { 9732 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9733 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9734 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9735 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9736 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9737 RISCV::V20M2, RISCV::V22M2}; 9738 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9739 RISCV::V20M4}; 9740 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9741 9742 // Pass a 2*XLEN argument that has been split into two XLEN values through 9743 // registers or the stack as necessary. 9744 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9745 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9746 MVT ValVT2, MVT LocVT2, 9747 ISD::ArgFlagsTy ArgFlags2) { 9748 unsigned XLenInBytes = XLen / 8; 9749 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9750 // At least one half can be passed via register. 9751 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9752 VA1.getLocVT(), CCValAssign::Full)); 9753 } else { 9754 // Both halves must be passed on the stack, with proper alignment. 9755 Align StackAlign = 9756 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9757 State.addLoc( 9758 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9759 State.AllocateStack(XLenInBytes, StackAlign), 9760 VA1.getLocVT(), CCValAssign::Full)); 9761 State.addLoc(CCValAssign::getMem( 9762 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9763 LocVT2, CCValAssign::Full)); 9764 return false; 9765 } 9766 9767 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9768 // The second half can also be passed via register. 9769 State.addLoc( 9770 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9771 } else { 9772 // The second half is passed via the stack, without additional alignment. 9773 State.addLoc(CCValAssign::getMem( 9774 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9775 LocVT2, CCValAssign::Full)); 9776 } 9777 9778 return false; 9779 } 9780 9781 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9782 Optional<unsigned> FirstMaskArgument, 9783 CCState &State, const RISCVTargetLowering &TLI) { 9784 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9785 if (RC == &RISCV::VRRegClass) { 9786 // Assign the first mask argument to V0. 9787 // This is an interim calling convention and it may be changed in the 9788 // future. 9789 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9790 return State.AllocateReg(RISCV::V0); 9791 return State.AllocateReg(ArgVRs); 9792 } 9793 if (RC == &RISCV::VRM2RegClass) 9794 return State.AllocateReg(ArgVRM2s); 9795 if (RC == &RISCV::VRM4RegClass) 9796 return State.AllocateReg(ArgVRM4s); 9797 if (RC == &RISCV::VRM8RegClass) 9798 return State.AllocateReg(ArgVRM8s); 9799 llvm_unreachable("Unhandled register class for ValueType"); 9800 } 9801 9802 // Implements the RISC-V calling convention. Returns true upon failure. 9803 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9804 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9805 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9806 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9807 Optional<unsigned> FirstMaskArgument) { 9808 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9809 assert(XLen == 32 || XLen == 64); 9810 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9811 9812 // Any return value split in to more than two values can't be returned 9813 // directly. Vectors are returned via the available vector registers. 9814 if (!LocVT.isVector() && IsRet && ValNo > 1) 9815 return true; 9816 9817 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9818 // variadic argument, or if no F16/F32 argument registers are available. 9819 bool UseGPRForF16_F32 = true; 9820 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9821 // variadic argument, or if no F64 argument registers are available. 9822 bool UseGPRForF64 = true; 9823 9824 switch (ABI) { 9825 default: 9826 llvm_unreachable("Unexpected ABI"); 9827 case RISCVABI::ABI_ILP32: 9828 case RISCVABI::ABI_LP64: 9829 break; 9830 case RISCVABI::ABI_ILP32F: 9831 case RISCVABI::ABI_LP64F: 9832 UseGPRForF16_F32 = !IsFixed; 9833 break; 9834 case RISCVABI::ABI_ILP32D: 9835 case RISCVABI::ABI_LP64D: 9836 UseGPRForF16_F32 = !IsFixed; 9837 UseGPRForF64 = !IsFixed; 9838 break; 9839 } 9840 9841 // FPR16, FPR32, and FPR64 alias each other. 9842 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9843 UseGPRForF16_F32 = true; 9844 UseGPRForF64 = true; 9845 } 9846 9847 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9848 // similar local variables rather than directly checking against the target 9849 // ABI. 9850 9851 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9852 LocVT = XLenVT; 9853 LocInfo = CCValAssign::BCvt; 9854 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9855 LocVT = MVT::i64; 9856 LocInfo = CCValAssign::BCvt; 9857 } 9858 9859 // If this is a variadic argument, the RISC-V calling convention requires 9860 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9861 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9862 // be used regardless of whether the original argument was split during 9863 // legalisation or not. The argument will not be passed by registers if the 9864 // original type is larger than 2*XLEN, so the register alignment rule does 9865 // not apply. 9866 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9867 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9868 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9869 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9870 // Skip 'odd' register if necessary. 9871 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9872 State.AllocateReg(ArgGPRs); 9873 } 9874 9875 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9876 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9877 State.getPendingArgFlags(); 9878 9879 assert(PendingLocs.size() == PendingArgFlags.size() && 9880 "PendingLocs and PendingArgFlags out of sync"); 9881 9882 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9883 // registers are exhausted. 9884 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9885 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9886 "Can't lower f64 if it is split"); 9887 // Depending on available argument GPRS, f64 may be passed in a pair of 9888 // GPRs, split between a GPR and the stack, or passed completely on the 9889 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9890 // cases. 9891 Register Reg = State.AllocateReg(ArgGPRs); 9892 LocVT = MVT::i32; 9893 if (!Reg) { 9894 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9895 State.addLoc( 9896 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9897 return false; 9898 } 9899 if (!State.AllocateReg(ArgGPRs)) 9900 State.AllocateStack(4, Align(4)); 9901 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9902 return false; 9903 } 9904 9905 // Fixed-length vectors are located in the corresponding scalable-vector 9906 // container types. 9907 if (ValVT.isFixedLengthVector()) 9908 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9909 9910 // Split arguments might be passed indirectly, so keep track of the pending 9911 // values. Split vectors are passed via a mix of registers and indirectly, so 9912 // treat them as we would any other argument. 9913 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9914 LocVT = XLenVT; 9915 LocInfo = CCValAssign::Indirect; 9916 PendingLocs.push_back( 9917 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9918 PendingArgFlags.push_back(ArgFlags); 9919 if (!ArgFlags.isSplitEnd()) { 9920 return false; 9921 } 9922 } 9923 9924 // If the split argument only had two elements, it should be passed directly 9925 // in registers or on the stack. 9926 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9927 PendingLocs.size() <= 2) { 9928 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9929 // Apply the normal calling convention rules to the first half of the 9930 // split argument. 9931 CCValAssign VA = PendingLocs[0]; 9932 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9933 PendingLocs.clear(); 9934 PendingArgFlags.clear(); 9935 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9936 ArgFlags); 9937 } 9938 9939 // Allocate to a register if possible, or else a stack slot. 9940 Register Reg; 9941 unsigned StoreSizeBytes = XLen / 8; 9942 Align StackAlign = Align(XLen / 8); 9943 9944 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9945 Reg = State.AllocateReg(ArgFPR16s); 9946 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9947 Reg = State.AllocateReg(ArgFPR32s); 9948 else if (ValVT == MVT::f64 && !UseGPRForF64) 9949 Reg = State.AllocateReg(ArgFPR64s); 9950 else if (ValVT.isVector()) { 9951 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9952 if (!Reg) { 9953 // For return values, the vector must be passed fully via registers or 9954 // via the stack. 9955 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9956 // but we're using all of them. 9957 if (IsRet) 9958 return true; 9959 // Try using a GPR to pass the address 9960 if ((Reg = State.AllocateReg(ArgGPRs))) { 9961 LocVT = XLenVT; 9962 LocInfo = CCValAssign::Indirect; 9963 } else if (ValVT.isScalableVector()) { 9964 LocVT = XLenVT; 9965 LocInfo = CCValAssign::Indirect; 9966 } else { 9967 // Pass fixed-length vectors on the stack. 9968 LocVT = ValVT; 9969 StoreSizeBytes = ValVT.getStoreSize(); 9970 // Align vectors to their element sizes, being careful for vXi1 9971 // vectors. 9972 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9973 } 9974 } 9975 } else { 9976 Reg = State.AllocateReg(ArgGPRs); 9977 } 9978 9979 unsigned StackOffset = 9980 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9981 9982 // If we reach this point and PendingLocs is non-empty, we must be at the 9983 // end of a split argument that must be passed indirectly. 9984 if (!PendingLocs.empty()) { 9985 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9986 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9987 9988 for (auto &It : PendingLocs) { 9989 if (Reg) 9990 It.convertToReg(Reg); 9991 else 9992 It.convertToMem(StackOffset); 9993 State.addLoc(It); 9994 } 9995 PendingLocs.clear(); 9996 PendingArgFlags.clear(); 9997 return false; 9998 } 9999 10000 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 10001 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 10002 "Expected an XLenVT or vector types at this stage"); 10003 10004 if (Reg) { 10005 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10006 return false; 10007 } 10008 10009 // When a floating-point value is passed on the stack, no bit-conversion is 10010 // needed. 10011 if (ValVT.isFloatingPoint()) { 10012 LocVT = ValVT; 10013 LocInfo = CCValAssign::Full; 10014 } 10015 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10016 return false; 10017 } 10018 10019 template <typename ArgTy> 10020 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10021 for (const auto &ArgIdx : enumerate(Args)) { 10022 MVT ArgVT = ArgIdx.value().VT; 10023 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10024 return ArgIdx.index(); 10025 } 10026 return None; 10027 } 10028 10029 void RISCVTargetLowering::analyzeInputArgs( 10030 MachineFunction &MF, CCState &CCInfo, 10031 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10032 RISCVCCAssignFn Fn) const { 10033 unsigned NumArgs = Ins.size(); 10034 FunctionType *FType = MF.getFunction().getFunctionType(); 10035 10036 Optional<unsigned> FirstMaskArgument; 10037 if (Subtarget.hasVInstructions()) 10038 FirstMaskArgument = preAssignMask(Ins); 10039 10040 for (unsigned i = 0; i != NumArgs; ++i) { 10041 MVT ArgVT = Ins[i].VT; 10042 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10043 10044 Type *ArgTy = nullptr; 10045 if (IsRet) 10046 ArgTy = FType->getReturnType(); 10047 else if (Ins[i].isOrigArg()) 10048 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10049 10050 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10051 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10052 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10053 FirstMaskArgument)) { 10054 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10055 << EVT(ArgVT).getEVTString() << '\n'); 10056 llvm_unreachable(nullptr); 10057 } 10058 } 10059 } 10060 10061 void RISCVTargetLowering::analyzeOutputArgs( 10062 MachineFunction &MF, CCState &CCInfo, 10063 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10064 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10065 unsigned NumArgs = Outs.size(); 10066 10067 Optional<unsigned> FirstMaskArgument; 10068 if (Subtarget.hasVInstructions()) 10069 FirstMaskArgument = preAssignMask(Outs); 10070 10071 for (unsigned i = 0; i != NumArgs; i++) { 10072 MVT ArgVT = Outs[i].VT; 10073 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10074 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10075 10076 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10077 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10078 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10079 FirstMaskArgument)) { 10080 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10081 << EVT(ArgVT).getEVTString() << "\n"); 10082 llvm_unreachable(nullptr); 10083 } 10084 } 10085 } 10086 10087 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10088 // values. 10089 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10090 const CCValAssign &VA, const SDLoc &DL, 10091 const RISCVSubtarget &Subtarget) { 10092 switch (VA.getLocInfo()) { 10093 default: 10094 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10095 case CCValAssign::Full: 10096 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10097 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10098 break; 10099 case CCValAssign::BCvt: 10100 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10101 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10102 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10103 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10104 else 10105 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10106 break; 10107 } 10108 return Val; 10109 } 10110 10111 // The caller is responsible for loading the full value if the argument is 10112 // passed with CCValAssign::Indirect. 10113 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10114 const CCValAssign &VA, const SDLoc &DL, 10115 const RISCVTargetLowering &TLI) { 10116 MachineFunction &MF = DAG.getMachineFunction(); 10117 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10118 EVT LocVT = VA.getLocVT(); 10119 SDValue Val; 10120 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10121 Register VReg = RegInfo.createVirtualRegister(RC); 10122 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10123 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10124 10125 if (VA.getLocInfo() == CCValAssign::Indirect) 10126 return Val; 10127 10128 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10129 } 10130 10131 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10132 const CCValAssign &VA, const SDLoc &DL, 10133 const RISCVSubtarget &Subtarget) { 10134 EVT LocVT = VA.getLocVT(); 10135 10136 switch (VA.getLocInfo()) { 10137 default: 10138 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10139 case CCValAssign::Full: 10140 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10141 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10142 break; 10143 case CCValAssign::BCvt: 10144 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10145 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10146 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10147 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10148 else 10149 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10150 break; 10151 } 10152 return Val; 10153 } 10154 10155 // The caller is responsible for loading the full value if the argument is 10156 // passed with CCValAssign::Indirect. 10157 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10158 const CCValAssign &VA, const SDLoc &DL) { 10159 MachineFunction &MF = DAG.getMachineFunction(); 10160 MachineFrameInfo &MFI = MF.getFrameInfo(); 10161 EVT LocVT = VA.getLocVT(); 10162 EVT ValVT = VA.getValVT(); 10163 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10164 if (ValVT.isScalableVector()) { 10165 // When the value is a scalable vector, we save the pointer which points to 10166 // the scalable vector value in the stack. The ValVT will be the pointer 10167 // type, instead of the scalable vector type. 10168 ValVT = LocVT; 10169 } 10170 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10171 /*IsImmutable=*/true); 10172 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10173 SDValue Val; 10174 10175 ISD::LoadExtType ExtType; 10176 switch (VA.getLocInfo()) { 10177 default: 10178 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10179 case CCValAssign::Full: 10180 case CCValAssign::Indirect: 10181 case CCValAssign::BCvt: 10182 ExtType = ISD::NON_EXTLOAD; 10183 break; 10184 } 10185 Val = DAG.getExtLoad( 10186 ExtType, DL, LocVT, Chain, FIN, 10187 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10188 return Val; 10189 } 10190 10191 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10192 const CCValAssign &VA, const SDLoc &DL) { 10193 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10194 "Unexpected VA"); 10195 MachineFunction &MF = DAG.getMachineFunction(); 10196 MachineFrameInfo &MFI = MF.getFrameInfo(); 10197 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10198 10199 if (VA.isMemLoc()) { 10200 // f64 is passed on the stack. 10201 int FI = 10202 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10203 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10204 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10205 MachinePointerInfo::getFixedStack(MF, FI)); 10206 } 10207 10208 assert(VA.isRegLoc() && "Expected register VA assignment"); 10209 10210 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10211 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10212 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10213 SDValue Hi; 10214 if (VA.getLocReg() == RISCV::X17) { 10215 // Second half of f64 is passed on the stack. 10216 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10217 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10218 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10219 MachinePointerInfo::getFixedStack(MF, FI)); 10220 } else { 10221 // Second half of f64 is passed in another GPR. 10222 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10223 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10224 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10225 } 10226 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10227 } 10228 10229 // FastCC has less than 1% performance improvement for some particular 10230 // benchmark. But theoretically, it may has benenfit for some cases. 10231 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10232 unsigned ValNo, MVT ValVT, MVT LocVT, 10233 CCValAssign::LocInfo LocInfo, 10234 ISD::ArgFlagsTy ArgFlags, CCState &State, 10235 bool IsFixed, bool IsRet, Type *OrigTy, 10236 const RISCVTargetLowering &TLI, 10237 Optional<unsigned> FirstMaskArgument) { 10238 10239 // X5 and X6 might be used for save-restore libcall. 10240 static const MCPhysReg GPRList[] = { 10241 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10242 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10243 RISCV::X29, RISCV::X30, RISCV::X31}; 10244 10245 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10246 if (unsigned Reg = State.AllocateReg(GPRList)) { 10247 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10248 return false; 10249 } 10250 } 10251 10252 if (LocVT == MVT::f16) { 10253 static const MCPhysReg FPR16List[] = { 10254 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10255 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10256 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10257 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10258 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10259 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10260 return false; 10261 } 10262 } 10263 10264 if (LocVT == MVT::f32) { 10265 static const MCPhysReg FPR32List[] = { 10266 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10267 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10268 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10269 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10270 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10271 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10272 return false; 10273 } 10274 } 10275 10276 if (LocVT == MVT::f64) { 10277 static const MCPhysReg FPR64List[] = { 10278 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10279 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10280 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10281 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10282 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10283 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10284 return false; 10285 } 10286 } 10287 10288 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10289 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10290 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10291 return false; 10292 } 10293 10294 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10295 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10296 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10297 return false; 10298 } 10299 10300 if (LocVT.isVector()) { 10301 if (unsigned Reg = 10302 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10303 // Fixed-length vectors are located in the corresponding scalable-vector 10304 // container types. 10305 if (ValVT.isFixedLengthVector()) 10306 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10307 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10308 } else { 10309 // Try and pass the address via a "fast" GPR. 10310 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10311 LocInfo = CCValAssign::Indirect; 10312 LocVT = TLI.getSubtarget().getXLenVT(); 10313 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10314 } else if (ValVT.isFixedLengthVector()) { 10315 auto StackAlign = 10316 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10317 unsigned StackOffset = 10318 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10319 State.addLoc( 10320 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10321 } else { 10322 // Can't pass scalable vectors on the stack. 10323 return true; 10324 } 10325 } 10326 10327 return false; 10328 } 10329 10330 return true; // CC didn't match. 10331 } 10332 10333 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10334 CCValAssign::LocInfo LocInfo, 10335 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10336 10337 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10338 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10339 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10340 static const MCPhysReg GPRList[] = { 10341 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10342 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10343 if (unsigned Reg = State.AllocateReg(GPRList)) { 10344 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10345 return false; 10346 } 10347 } 10348 10349 if (LocVT == MVT::f32) { 10350 // Pass in STG registers: F1, ..., F6 10351 // fs0 ... fs5 10352 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10353 RISCV::F18_F, RISCV::F19_F, 10354 RISCV::F20_F, RISCV::F21_F}; 10355 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10356 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10357 return false; 10358 } 10359 } 10360 10361 if (LocVT == MVT::f64) { 10362 // Pass in STG registers: D1, ..., D6 10363 // fs6 ... fs11 10364 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10365 RISCV::F24_D, RISCV::F25_D, 10366 RISCV::F26_D, RISCV::F27_D}; 10367 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10368 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10369 return false; 10370 } 10371 } 10372 10373 report_fatal_error("No registers left in GHC calling convention"); 10374 return true; 10375 } 10376 10377 // Transform physical registers into virtual registers. 10378 SDValue RISCVTargetLowering::LowerFormalArguments( 10379 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10380 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10381 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10382 10383 MachineFunction &MF = DAG.getMachineFunction(); 10384 10385 switch (CallConv) { 10386 default: 10387 report_fatal_error("Unsupported calling convention"); 10388 case CallingConv::C: 10389 case CallingConv::Fast: 10390 break; 10391 case CallingConv::GHC: 10392 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10393 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10394 report_fatal_error( 10395 "GHC calling convention requires the F and D instruction set extensions"); 10396 } 10397 10398 const Function &Func = MF.getFunction(); 10399 if (Func.hasFnAttribute("interrupt")) { 10400 if (!Func.arg_empty()) 10401 report_fatal_error( 10402 "Functions with the interrupt attribute cannot have arguments!"); 10403 10404 StringRef Kind = 10405 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10406 10407 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10408 report_fatal_error( 10409 "Function interrupt attribute argument not supported!"); 10410 } 10411 10412 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10413 MVT XLenVT = Subtarget.getXLenVT(); 10414 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10415 // Used with vargs to acumulate store chains. 10416 std::vector<SDValue> OutChains; 10417 10418 // Assign locations to all of the incoming arguments. 10419 SmallVector<CCValAssign, 16> ArgLocs; 10420 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10421 10422 if (CallConv == CallingConv::GHC) 10423 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10424 else 10425 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10426 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10427 : CC_RISCV); 10428 10429 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10430 CCValAssign &VA = ArgLocs[i]; 10431 SDValue ArgValue; 10432 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10433 // case. 10434 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10435 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10436 else if (VA.isRegLoc()) 10437 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10438 else 10439 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10440 10441 if (VA.getLocInfo() == CCValAssign::Indirect) { 10442 // If the original argument was split and passed by reference (e.g. i128 10443 // on RV32), we need to load all parts of it here (using the same 10444 // address). Vectors may be partly split to registers and partly to the 10445 // stack, in which case the base address is partly offset and subsequent 10446 // stores are relative to that. 10447 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10448 MachinePointerInfo())); 10449 unsigned ArgIndex = Ins[i].OrigArgIndex; 10450 unsigned ArgPartOffset = Ins[i].PartOffset; 10451 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10452 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10453 CCValAssign &PartVA = ArgLocs[i + 1]; 10454 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10455 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10456 if (PartVA.getValVT().isScalableVector()) 10457 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10458 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10459 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10460 MachinePointerInfo())); 10461 ++i; 10462 } 10463 continue; 10464 } 10465 InVals.push_back(ArgValue); 10466 } 10467 10468 if (IsVarArg) { 10469 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10470 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10471 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10472 MachineFrameInfo &MFI = MF.getFrameInfo(); 10473 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10474 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10475 10476 // Offset of the first variable argument from stack pointer, and size of 10477 // the vararg save area. For now, the varargs save area is either zero or 10478 // large enough to hold a0-a7. 10479 int VaArgOffset, VarArgsSaveSize; 10480 10481 // If all registers are allocated, then all varargs must be passed on the 10482 // stack and we don't need to save any argregs. 10483 if (ArgRegs.size() == Idx) { 10484 VaArgOffset = CCInfo.getNextStackOffset(); 10485 VarArgsSaveSize = 0; 10486 } else { 10487 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10488 VaArgOffset = -VarArgsSaveSize; 10489 } 10490 10491 // Record the frame index of the first variable argument 10492 // which is a value necessary to VASTART. 10493 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10494 RVFI->setVarArgsFrameIndex(FI); 10495 10496 // If saving an odd number of registers then create an extra stack slot to 10497 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10498 // offsets to even-numbered registered remain 2*XLEN-aligned. 10499 if (Idx % 2) { 10500 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10501 VarArgsSaveSize += XLenInBytes; 10502 } 10503 10504 // Copy the integer registers that may have been used for passing varargs 10505 // to the vararg save area. 10506 for (unsigned I = Idx; I < ArgRegs.size(); 10507 ++I, VaArgOffset += XLenInBytes) { 10508 const Register Reg = RegInfo.createVirtualRegister(RC); 10509 RegInfo.addLiveIn(ArgRegs[I], Reg); 10510 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10511 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10512 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10513 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10514 MachinePointerInfo::getFixedStack(MF, FI)); 10515 cast<StoreSDNode>(Store.getNode()) 10516 ->getMemOperand() 10517 ->setValue((Value *)nullptr); 10518 OutChains.push_back(Store); 10519 } 10520 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10521 } 10522 10523 // All stores are grouped in one node to allow the matching between 10524 // the size of Ins and InVals. This only happens for vararg functions. 10525 if (!OutChains.empty()) { 10526 OutChains.push_back(Chain); 10527 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10528 } 10529 10530 return Chain; 10531 } 10532 10533 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10534 /// for tail call optimization. 10535 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10536 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10537 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10538 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10539 10540 auto &Callee = CLI.Callee; 10541 auto CalleeCC = CLI.CallConv; 10542 auto &Outs = CLI.Outs; 10543 auto &Caller = MF.getFunction(); 10544 auto CallerCC = Caller.getCallingConv(); 10545 10546 // Exception-handling functions need a special set of instructions to 10547 // indicate a return to the hardware. Tail-calling another function would 10548 // probably break this. 10549 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10550 // should be expanded as new function attributes are introduced. 10551 if (Caller.hasFnAttribute("interrupt")) 10552 return false; 10553 10554 // Do not tail call opt if the stack is used to pass parameters. 10555 if (CCInfo.getNextStackOffset() != 0) 10556 return false; 10557 10558 // Do not tail call opt if any parameters need to be passed indirectly. 10559 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10560 // passed indirectly. So the address of the value will be passed in a 10561 // register, or if not available, then the address is put on the stack. In 10562 // order to pass indirectly, space on the stack often needs to be allocated 10563 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10564 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10565 // are passed CCValAssign::Indirect. 10566 for (auto &VA : ArgLocs) 10567 if (VA.getLocInfo() == CCValAssign::Indirect) 10568 return false; 10569 10570 // Do not tail call opt if either caller or callee uses struct return 10571 // semantics. 10572 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10573 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10574 if (IsCallerStructRet || IsCalleeStructRet) 10575 return false; 10576 10577 // Externally-defined functions with weak linkage should not be 10578 // tail-called. The behaviour of branch instructions in this situation (as 10579 // used for tail calls) is implementation-defined, so we cannot rely on the 10580 // linker replacing the tail call with a return. 10581 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10582 const GlobalValue *GV = G->getGlobal(); 10583 if (GV->hasExternalWeakLinkage()) 10584 return false; 10585 } 10586 10587 // The callee has to preserve all registers the caller needs to preserve. 10588 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10589 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10590 if (CalleeCC != CallerCC) { 10591 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10592 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10593 return false; 10594 } 10595 10596 // Byval parameters hand the function a pointer directly into the stack area 10597 // we want to reuse during a tail call. Working around this *is* possible 10598 // but less efficient and uglier in LowerCall. 10599 for (auto &Arg : Outs) 10600 if (Arg.Flags.isByVal()) 10601 return false; 10602 10603 return true; 10604 } 10605 10606 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10607 return DAG.getDataLayout().getPrefTypeAlign( 10608 VT.getTypeForEVT(*DAG.getContext())); 10609 } 10610 10611 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10612 // and output parameter nodes. 10613 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10614 SmallVectorImpl<SDValue> &InVals) const { 10615 SelectionDAG &DAG = CLI.DAG; 10616 SDLoc &DL = CLI.DL; 10617 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10618 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10619 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10620 SDValue Chain = CLI.Chain; 10621 SDValue Callee = CLI.Callee; 10622 bool &IsTailCall = CLI.IsTailCall; 10623 CallingConv::ID CallConv = CLI.CallConv; 10624 bool IsVarArg = CLI.IsVarArg; 10625 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10626 MVT XLenVT = Subtarget.getXLenVT(); 10627 10628 MachineFunction &MF = DAG.getMachineFunction(); 10629 10630 // Analyze the operands of the call, assigning locations to each operand. 10631 SmallVector<CCValAssign, 16> ArgLocs; 10632 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10633 10634 if (CallConv == CallingConv::GHC) 10635 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10636 else 10637 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10638 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10639 : CC_RISCV); 10640 10641 // Check if it's really possible to do a tail call. 10642 if (IsTailCall) 10643 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10644 10645 if (IsTailCall) 10646 ++NumTailCalls; 10647 else if (CLI.CB && CLI.CB->isMustTailCall()) 10648 report_fatal_error("failed to perform tail call elimination on a call " 10649 "site marked musttail"); 10650 10651 // Get a count of how many bytes are to be pushed on the stack. 10652 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10653 10654 // Create local copies for byval args 10655 SmallVector<SDValue, 8> ByValArgs; 10656 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10657 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10658 if (!Flags.isByVal()) 10659 continue; 10660 10661 SDValue Arg = OutVals[i]; 10662 unsigned Size = Flags.getByValSize(); 10663 Align Alignment = Flags.getNonZeroByValAlign(); 10664 10665 int FI = 10666 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10667 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10668 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10669 10670 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10671 /*IsVolatile=*/false, 10672 /*AlwaysInline=*/false, IsTailCall, 10673 MachinePointerInfo(), MachinePointerInfo()); 10674 ByValArgs.push_back(FIPtr); 10675 } 10676 10677 if (!IsTailCall) 10678 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10679 10680 // Copy argument values to their designated locations. 10681 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10682 SmallVector<SDValue, 8> MemOpChains; 10683 SDValue StackPtr; 10684 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10685 CCValAssign &VA = ArgLocs[i]; 10686 SDValue ArgValue = OutVals[i]; 10687 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10688 10689 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10690 bool IsF64OnRV32DSoftABI = 10691 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10692 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10693 SDValue SplitF64 = DAG.getNode( 10694 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10695 SDValue Lo = SplitF64.getValue(0); 10696 SDValue Hi = SplitF64.getValue(1); 10697 10698 Register RegLo = VA.getLocReg(); 10699 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10700 10701 if (RegLo == RISCV::X17) { 10702 // Second half of f64 is passed on the stack. 10703 // Work out the address of the stack slot. 10704 if (!StackPtr.getNode()) 10705 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10706 // Emit the store. 10707 MemOpChains.push_back( 10708 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10709 } else { 10710 // Second half of f64 is passed in another GPR. 10711 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10712 Register RegHigh = RegLo + 1; 10713 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10714 } 10715 continue; 10716 } 10717 10718 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10719 // as any other MemLoc. 10720 10721 // Promote the value if needed. 10722 // For now, only handle fully promoted and indirect arguments. 10723 if (VA.getLocInfo() == CCValAssign::Indirect) { 10724 // Store the argument in a stack slot and pass its address. 10725 Align StackAlign = 10726 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10727 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10728 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10729 // If the original argument was split (e.g. i128), we need 10730 // to store the required parts of it here (and pass just one address). 10731 // Vectors may be partly split to registers and partly to the stack, in 10732 // which case the base address is partly offset and subsequent stores are 10733 // relative to that. 10734 unsigned ArgIndex = Outs[i].OrigArgIndex; 10735 unsigned ArgPartOffset = Outs[i].PartOffset; 10736 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10737 // Calculate the total size to store. We don't have access to what we're 10738 // actually storing other than performing the loop and collecting the 10739 // info. 10740 SmallVector<std::pair<SDValue, SDValue>> Parts; 10741 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10742 SDValue PartValue = OutVals[i + 1]; 10743 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10744 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10745 EVT PartVT = PartValue.getValueType(); 10746 if (PartVT.isScalableVector()) 10747 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10748 StoredSize += PartVT.getStoreSize(); 10749 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10750 Parts.push_back(std::make_pair(PartValue, Offset)); 10751 ++i; 10752 } 10753 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10754 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10755 MemOpChains.push_back( 10756 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10757 MachinePointerInfo::getFixedStack(MF, FI))); 10758 for (const auto &Part : Parts) { 10759 SDValue PartValue = Part.first; 10760 SDValue PartOffset = Part.second; 10761 SDValue Address = 10762 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10763 MemOpChains.push_back( 10764 DAG.getStore(Chain, DL, PartValue, Address, 10765 MachinePointerInfo::getFixedStack(MF, FI))); 10766 } 10767 ArgValue = SpillSlot; 10768 } else { 10769 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10770 } 10771 10772 // Use local copy if it is a byval arg. 10773 if (Flags.isByVal()) 10774 ArgValue = ByValArgs[j++]; 10775 10776 if (VA.isRegLoc()) { 10777 // Queue up the argument copies and emit them at the end. 10778 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10779 } else { 10780 assert(VA.isMemLoc() && "Argument not register or memory"); 10781 assert(!IsTailCall && "Tail call not allowed if stack is used " 10782 "for passing parameters"); 10783 10784 // Work out the address of the stack slot. 10785 if (!StackPtr.getNode()) 10786 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10787 SDValue Address = 10788 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10789 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10790 10791 // Emit the store. 10792 MemOpChains.push_back( 10793 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10794 } 10795 } 10796 10797 // Join the stores, which are independent of one another. 10798 if (!MemOpChains.empty()) 10799 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10800 10801 SDValue Glue; 10802 10803 // Build a sequence of copy-to-reg nodes, chained and glued together. 10804 for (auto &Reg : RegsToPass) { 10805 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10806 Glue = Chain.getValue(1); 10807 } 10808 10809 // Validate that none of the argument registers have been marked as 10810 // reserved, if so report an error. Do the same for the return address if this 10811 // is not a tailcall. 10812 validateCCReservedRegs(RegsToPass, MF); 10813 if (!IsTailCall && 10814 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10815 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10816 MF.getFunction(), 10817 "Return address register required, but has been reserved."}); 10818 10819 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10820 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10821 // split it and then direct call can be matched by PseudoCALL. 10822 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10823 const GlobalValue *GV = S->getGlobal(); 10824 10825 unsigned OpFlags = RISCVII::MO_CALL; 10826 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10827 OpFlags = RISCVII::MO_PLT; 10828 10829 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10830 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10831 unsigned OpFlags = RISCVII::MO_CALL; 10832 10833 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10834 nullptr)) 10835 OpFlags = RISCVII::MO_PLT; 10836 10837 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10838 } 10839 10840 // The first call operand is the chain and the second is the target address. 10841 SmallVector<SDValue, 8> Ops; 10842 Ops.push_back(Chain); 10843 Ops.push_back(Callee); 10844 10845 // Add argument registers to the end of the list so that they are 10846 // known live into the call. 10847 for (auto &Reg : RegsToPass) 10848 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10849 10850 if (!IsTailCall) { 10851 // Add a register mask operand representing the call-preserved registers. 10852 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10853 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10854 assert(Mask && "Missing call preserved mask for calling convention"); 10855 Ops.push_back(DAG.getRegisterMask(Mask)); 10856 } 10857 10858 // Glue the call to the argument copies, if any. 10859 if (Glue.getNode()) 10860 Ops.push_back(Glue); 10861 10862 // Emit the call. 10863 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10864 10865 if (IsTailCall) { 10866 MF.getFrameInfo().setHasTailCall(); 10867 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10868 } 10869 10870 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10871 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10872 Glue = Chain.getValue(1); 10873 10874 // Mark the end of the call, which is glued to the call itself. 10875 Chain = DAG.getCALLSEQ_END(Chain, 10876 DAG.getConstant(NumBytes, DL, PtrVT, true), 10877 DAG.getConstant(0, DL, PtrVT, true), 10878 Glue, DL); 10879 Glue = Chain.getValue(1); 10880 10881 // Assign locations to each value returned by this call. 10882 SmallVector<CCValAssign, 16> RVLocs; 10883 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10884 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10885 10886 // Copy all of the result registers out of their specified physreg. 10887 for (auto &VA : RVLocs) { 10888 // Copy the value out 10889 SDValue RetValue = 10890 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10891 // Glue the RetValue to the end of the call sequence 10892 Chain = RetValue.getValue(1); 10893 Glue = RetValue.getValue(2); 10894 10895 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10896 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10897 SDValue RetValue2 = 10898 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10899 Chain = RetValue2.getValue(1); 10900 Glue = RetValue2.getValue(2); 10901 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10902 RetValue2); 10903 } 10904 10905 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10906 10907 InVals.push_back(RetValue); 10908 } 10909 10910 return Chain; 10911 } 10912 10913 bool RISCVTargetLowering::CanLowerReturn( 10914 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10915 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10916 SmallVector<CCValAssign, 16> RVLocs; 10917 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10918 10919 Optional<unsigned> FirstMaskArgument; 10920 if (Subtarget.hasVInstructions()) 10921 FirstMaskArgument = preAssignMask(Outs); 10922 10923 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10924 MVT VT = Outs[i].VT; 10925 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10926 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10927 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10928 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10929 *this, FirstMaskArgument)) 10930 return false; 10931 } 10932 return true; 10933 } 10934 10935 SDValue 10936 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10937 bool IsVarArg, 10938 const SmallVectorImpl<ISD::OutputArg> &Outs, 10939 const SmallVectorImpl<SDValue> &OutVals, 10940 const SDLoc &DL, SelectionDAG &DAG) const { 10941 const MachineFunction &MF = DAG.getMachineFunction(); 10942 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10943 10944 // Stores the assignment of the return value to a location. 10945 SmallVector<CCValAssign, 16> RVLocs; 10946 10947 // Info about the registers and stack slot. 10948 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10949 *DAG.getContext()); 10950 10951 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10952 nullptr, CC_RISCV); 10953 10954 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10955 report_fatal_error("GHC functions return void only"); 10956 10957 SDValue Glue; 10958 SmallVector<SDValue, 4> RetOps(1, Chain); 10959 10960 // Copy the result values into the output registers. 10961 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10962 SDValue Val = OutVals[i]; 10963 CCValAssign &VA = RVLocs[i]; 10964 assert(VA.isRegLoc() && "Can only return in registers!"); 10965 10966 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10967 // Handle returning f64 on RV32D with a soft float ABI. 10968 assert(VA.isRegLoc() && "Expected return via registers"); 10969 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10970 DAG.getVTList(MVT::i32, MVT::i32), Val); 10971 SDValue Lo = SplitF64.getValue(0); 10972 SDValue Hi = SplitF64.getValue(1); 10973 Register RegLo = VA.getLocReg(); 10974 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10975 Register RegHi = RegLo + 1; 10976 10977 if (STI.isRegisterReservedByUser(RegLo) || 10978 STI.isRegisterReservedByUser(RegHi)) 10979 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10980 MF.getFunction(), 10981 "Return value register required, but has been reserved."}); 10982 10983 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10984 Glue = Chain.getValue(1); 10985 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10986 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10987 Glue = Chain.getValue(1); 10988 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10989 } else { 10990 // Handle a 'normal' return. 10991 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10992 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10993 10994 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10995 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10996 MF.getFunction(), 10997 "Return value register required, but has been reserved."}); 10998 10999 // Guarantee that all emitted copies are stuck together. 11000 Glue = Chain.getValue(1); 11001 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 11002 } 11003 } 11004 11005 RetOps[0] = Chain; // Update chain. 11006 11007 // Add the glue node if we have it. 11008 if (Glue.getNode()) { 11009 RetOps.push_back(Glue); 11010 } 11011 11012 unsigned RetOpc = RISCVISD::RET_FLAG; 11013 // Interrupt service routines use different return instructions. 11014 const Function &Func = DAG.getMachineFunction().getFunction(); 11015 if (Func.hasFnAttribute("interrupt")) { 11016 if (!Func.getReturnType()->isVoidTy()) 11017 report_fatal_error( 11018 "Functions with the interrupt attribute must have void return type!"); 11019 11020 MachineFunction &MF = DAG.getMachineFunction(); 11021 StringRef Kind = 11022 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11023 11024 if (Kind == "user") 11025 RetOpc = RISCVISD::URET_FLAG; 11026 else if (Kind == "supervisor") 11027 RetOpc = RISCVISD::SRET_FLAG; 11028 else 11029 RetOpc = RISCVISD::MRET_FLAG; 11030 } 11031 11032 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11033 } 11034 11035 void RISCVTargetLowering::validateCCReservedRegs( 11036 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11037 MachineFunction &MF) const { 11038 const Function &F = MF.getFunction(); 11039 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11040 11041 if (llvm::any_of(Regs, [&STI](auto Reg) { 11042 return STI.isRegisterReservedByUser(Reg.first); 11043 })) 11044 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11045 F, "Argument register required, but has been reserved."}); 11046 } 11047 11048 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11049 return CI->isTailCall(); 11050 } 11051 11052 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11053 #define NODE_NAME_CASE(NODE) \ 11054 case RISCVISD::NODE: \ 11055 return "RISCVISD::" #NODE; 11056 // clang-format off 11057 switch ((RISCVISD::NodeType)Opcode) { 11058 case RISCVISD::FIRST_NUMBER: 11059 break; 11060 NODE_NAME_CASE(RET_FLAG) 11061 NODE_NAME_CASE(URET_FLAG) 11062 NODE_NAME_CASE(SRET_FLAG) 11063 NODE_NAME_CASE(MRET_FLAG) 11064 NODE_NAME_CASE(CALL) 11065 NODE_NAME_CASE(SELECT_CC) 11066 NODE_NAME_CASE(BR_CC) 11067 NODE_NAME_CASE(BuildPairF64) 11068 NODE_NAME_CASE(SplitF64) 11069 NODE_NAME_CASE(TAIL) 11070 NODE_NAME_CASE(MULHSU) 11071 NODE_NAME_CASE(SLLW) 11072 NODE_NAME_CASE(SRAW) 11073 NODE_NAME_CASE(SRLW) 11074 NODE_NAME_CASE(DIVW) 11075 NODE_NAME_CASE(DIVUW) 11076 NODE_NAME_CASE(REMUW) 11077 NODE_NAME_CASE(ROLW) 11078 NODE_NAME_CASE(RORW) 11079 NODE_NAME_CASE(CLZW) 11080 NODE_NAME_CASE(CTZW) 11081 NODE_NAME_CASE(FSLW) 11082 NODE_NAME_CASE(FSRW) 11083 NODE_NAME_CASE(FSL) 11084 NODE_NAME_CASE(FSR) 11085 NODE_NAME_CASE(FMV_H_X) 11086 NODE_NAME_CASE(FMV_X_ANYEXTH) 11087 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11088 NODE_NAME_CASE(FMV_W_X_RV64) 11089 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11090 NODE_NAME_CASE(FCVT_X) 11091 NODE_NAME_CASE(FCVT_XU) 11092 NODE_NAME_CASE(FCVT_W_RV64) 11093 NODE_NAME_CASE(FCVT_WU_RV64) 11094 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11095 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11096 NODE_NAME_CASE(READ_CYCLE_WIDE) 11097 NODE_NAME_CASE(GREV) 11098 NODE_NAME_CASE(GREVW) 11099 NODE_NAME_CASE(GORC) 11100 NODE_NAME_CASE(GORCW) 11101 NODE_NAME_CASE(SHFL) 11102 NODE_NAME_CASE(SHFLW) 11103 NODE_NAME_CASE(UNSHFL) 11104 NODE_NAME_CASE(UNSHFLW) 11105 NODE_NAME_CASE(BFP) 11106 NODE_NAME_CASE(BFPW) 11107 NODE_NAME_CASE(BCOMPRESS) 11108 NODE_NAME_CASE(BCOMPRESSW) 11109 NODE_NAME_CASE(BDECOMPRESS) 11110 NODE_NAME_CASE(BDECOMPRESSW) 11111 NODE_NAME_CASE(VMV_V_X_VL) 11112 NODE_NAME_CASE(VFMV_V_F_VL) 11113 NODE_NAME_CASE(VMV_X_S) 11114 NODE_NAME_CASE(VMV_S_X_VL) 11115 NODE_NAME_CASE(VFMV_S_F_VL) 11116 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11117 NODE_NAME_CASE(READ_VLENB) 11118 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11119 NODE_NAME_CASE(VSLIDEUP_VL) 11120 NODE_NAME_CASE(VSLIDE1UP_VL) 11121 NODE_NAME_CASE(VSLIDEDOWN_VL) 11122 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11123 NODE_NAME_CASE(VID_VL) 11124 NODE_NAME_CASE(VFNCVT_ROD_VL) 11125 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11126 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11127 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11128 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11129 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11130 NODE_NAME_CASE(VECREDUCE_AND_VL) 11131 NODE_NAME_CASE(VECREDUCE_OR_VL) 11132 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11133 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11134 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11135 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11136 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11137 NODE_NAME_CASE(ADD_VL) 11138 NODE_NAME_CASE(AND_VL) 11139 NODE_NAME_CASE(MUL_VL) 11140 NODE_NAME_CASE(OR_VL) 11141 NODE_NAME_CASE(SDIV_VL) 11142 NODE_NAME_CASE(SHL_VL) 11143 NODE_NAME_CASE(SREM_VL) 11144 NODE_NAME_CASE(SRA_VL) 11145 NODE_NAME_CASE(SRL_VL) 11146 NODE_NAME_CASE(SUB_VL) 11147 NODE_NAME_CASE(UDIV_VL) 11148 NODE_NAME_CASE(UREM_VL) 11149 NODE_NAME_CASE(XOR_VL) 11150 NODE_NAME_CASE(SADDSAT_VL) 11151 NODE_NAME_CASE(UADDSAT_VL) 11152 NODE_NAME_CASE(SSUBSAT_VL) 11153 NODE_NAME_CASE(USUBSAT_VL) 11154 NODE_NAME_CASE(FADD_VL) 11155 NODE_NAME_CASE(FSUB_VL) 11156 NODE_NAME_CASE(FMUL_VL) 11157 NODE_NAME_CASE(FDIV_VL) 11158 NODE_NAME_CASE(FNEG_VL) 11159 NODE_NAME_CASE(FABS_VL) 11160 NODE_NAME_CASE(FSQRT_VL) 11161 NODE_NAME_CASE(FMA_VL) 11162 NODE_NAME_CASE(FCOPYSIGN_VL) 11163 NODE_NAME_CASE(SMIN_VL) 11164 NODE_NAME_CASE(SMAX_VL) 11165 NODE_NAME_CASE(UMIN_VL) 11166 NODE_NAME_CASE(UMAX_VL) 11167 NODE_NAME_CASE(FMINNUM_VL) 11168 NODE_NAME_CASE(FMAXNUM_VL) 11169 NODE_NAME_CASE(MULHS_VL) 11170 NODE_NAME_CASE(MULHU_VL) 11171 NODE_NAME_CASE(FP_TO_SINT_VL) 11172 NODE_NAME_CASE(FP_TO_UINT_VL) 11173 NODE_NAME_CASE(SINT_TO_FP_VL) 11174 NODE_NAME_CASE(UINT_TO_FP_VL) 11175 NODE_NAME_CASE(FP_EXTEND_VL) 11176 NODE_NAME_CASE(FP_ROUND_VL) 11177 NODE_NAME_CASE(VWMUL_VL) 11178 NODE_NAME_CASE(VWMULU_VL) 11179 NODE_NAME_CASE(VWMULSU_VL) 11180 NODE_NAME_CASE(VWADD_VL) 11181 NODE_NAME_CASE(VWADDU_VL) 11182 NODE_NAME_CASE(VWSUB_VL) 11183 NODE_NAME_CASE(VWSUBU_VL) 11184 NODE_NAME_CASE(VWADD_W_VL) 11185 NODE_NAME_CASE(VWADDU_W_VL) 11186 NODE_NAME_CASE(VWSUB_W_VL) 11187 NODE_NAME_CASE(VWSUBU_W_VL) 11188 NODE_NAME_CASE(SETCC_VL) 11189 NODE_NAME_CASE(VSELECT_VL) 11190 NODE_NAME_CASE(VP_MERGE_VL) 11191 NODE_NAME_CASE(VMAND_VL) 11192 NODE_NAME_CASE(VMOR_VL) 11193 NODE_NAME_CASE(VMXOR_VL) 11194 NODE_NAME_CASE(VMCLR_VL) 11195 NODE_NAME_CASE(VMSET_VL) 11196 NODE_NAME_CASE(VRGATHER_VX_VL) 11197 NODE_NAME_CASE(VRGATHER_VV_VL) 11198 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11199 NODE_NAME_CASE(VSEXT_VL) 11200 NODE_NAME_CASE(VZEXT_VL) 11201 NODE_NAME_CASE(VCPOP_VL) 11202 NODE_NAME_CASE(READ_CSR) 11203 NODE_NAME_CASE(WRITE_CSR) 11204 NODE_NAME_CASE(SWAP_CSR) 11205 } 11206 // clang-format on 11207 return nullptr; 11208 #undef NODE_NAME_CASE 11209 } 11210 11211 /// getConstraintType - Given a constraint letter, return the type of 11212 /// constraint it is for this target. 11213 RISCVTargetLowering::ConstraintType 11214 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11215 if (Constraint.size() == 1) { 11216 switch (Constraint[0]) { 11217 default: 11218 break; 11219 case 'f': 11220 return C_RegisterClass; 11221 case 'I': 11222 case 'J': 11223 case 'K': 11224 return C_Immediate; 11225 case 'A': 11226 return C_Memory; 11227 case 'S': // A symbolic address 11228 return C_Other; 11229 } 11230 } else { 11231 if (Constraint == "vr" || Constraint == "vm") 11232 return C_RegisterClass; 11233 } 11234 return TargetLowering::getConstraintType(Constraint); 11235 } 11236 11237 std::pair<unsigned, const TargetRegisterClass *> 11238 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11239 StringRef Constraint, 11240 MVT VT) const { 11241 // First, see if this is a constraint that directly corresponds to a 11242 // RISCV register class. 11243 if (Constraint.size() == 1) { 11244 switch (Constraint[0]) { 11245 case 'r': 11246 // TODO: Support fixed vectors up to XLen for P extension? 11247 if (VT.isVector()) 11248 break; 11249 return std::make_pair(0U, &RISCV::GPRRegClass); 11250 case 'f': 11251 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11252 return std::make_pair(0U, &RISCV::FPR16RegClass); 11253 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11254 return std::make_pair(0U, &RISCV::FPR32RegClass); 11255 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11256 return std::make_pair(0U, &RISCV::FPR64RegClass); 11257 break; 11258 default: 11259 break; 11260 } 11261 } else if (Constraint == "vr") { 11262 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11263 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11264 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11265 return std::make_pair(0U, RC); 11266 } 11267 } else if (Constraint == "vm") { 11268 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11269 return std::make_pair(0U, &RISCV::VMV0RegClass); 11270 } 11271 11272 // Clang will correctly decode the usage of register name aliases into their 11273 // official names. However, other frontends like `rustc` do not. This allows 11274 // users of these frontends to use the ABI names for registers in LLVM-style 11275 // register constraints. 11276 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11277 .Case("{zero}", RISCV::X0) 11278 .Case("{ra}", RISCV::X1) 11279 .Case("{sp}", RISCV::X2) 11280 .Case("{gp}", RISCV::X3) 11281 .Case("{tp}", RISCV::X4) 11282 .Case("{t0}", RISCV::X5) 11283 .Case("{t1}", RISCV::X6) 11284 .Case("{t2}", RISCV::X7) 11285 .Cases("{s0}", "{fp}", RISCV::X8) 11286 .Case("{s1}", RISCV::X9) 11287 .Case("{a0}", RISCV::X10) 11288 .Case("{a1}", RISCV::X11) 11289 .Case("{a2}", RISCV::X12) 11290 .Case("{a3}", RISCV::X13) 11291 .Case("{a4}", RISCV::X14) 11292 .Case("{a5}", RISCV::X15) 11293 .Case("{a6}", RISCV::X16) 11294 .Case("{a7}", RISCV::X17) 11295 .Case("{s2}", RISCV::X18) 11296 .Case("{s3}", RISCV::X19) 11297 .Case("{s4}", RISCV::X20) 11298 .Case("{s5}", RISCV::X21) 11299 .Case("{s6}", RISCV::X22) 11300 .Case("{s7}", RISCV::X23) 11301 .Case("{s8}", RISCV::X24) 11302 .Case("{s9}", RISCV::X25) 11303 .Case("{s10}", RISCV::X26) 11304 .Case("{s11}", RISCV::X27) 11305 .Case("{t3}", RISCV::X28) 11306 .Case("{t4}", RISCV::X29) 11307 .Case("{t5}", RISCV::X30) 11308 .Case("{t6}", RISCV::X31) 11309 .Default(RISCV::NoRegister); 11310 if (XRegFromAlias != RISCV::NoRegister) 11311 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11312 11313 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11314 // TableGen record rather than the AsmName to choose registers for InlineAsm 11315 // constraints, plus we want to match those names to the widest floating point 11316 // register type available, manually select floating point registers here. 11317 // 11318 // The second case is the ABI name of the register, so that frontends can also 11319 // use the ABI names in register constraint lists. 11320 if (Subtarget.hasStdExtF()) { 11321 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11322 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11323 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11324 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11325 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11326 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11327 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11328 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11329 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11330 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11331 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11332 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11333 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11334 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11335 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11336 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11337 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11338 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11339 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11340 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11341 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11342 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11343 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11344 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11345 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11346 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11347 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11348 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11349 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11350 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11351 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11352 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11353 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11354 .Default(RISCV::NoRegister); 11355 if (FReg != RISCV::NoRegister) { 11356 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11357 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11358 unsigned RegNo = FReg - RISCV::F0_F; 11359 unsigned DReg = RISCV::F0_D + RegNo; 11360 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11361 } 11362 if (VT == MVT::f32 || VT == MVT::Other) 11363 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11364 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11365 unsigned RegNo = FReg - RISCV::F0_F; 11366 unsigned HReg = RISCV::F0_H + RegNo; 11367 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11368 } 11369 } 11370 } 11371 11372 if (Subtarget.hasVInstructions()) { 11373 Register VReg = StringSwitch<Register>(Constraint.lower()) 11374 .Case("{v0}", RISCV::V0) 11375 .Case("{v1}", RISCV::V1) 11376 .Case("{v2}", RISCV::V2) 11377 .Case("{v3}", RISCV::V3) 11378 .Case("{v4}", RISCV::V4) 11379 .Case("{v5}", RISCV::V5) 11380 .Case("{v6}", RISCV::V6) 11381 .Case("{v7}", RISCV::V7) 11382 .Case("{v8}", RISCV::V8) 11383 .Case("{v9}", RISCV::V9) 11384 .Case("{v10}", RISCV::V10) 11385 .Case("{v11}", RISCV::V11) 11386 .Case("{v12}", RISCV::V12) 11387 .Case("{v13}", RISCV::V13) 11388 .Case("{v14}", RISCV::V14) 11389 .Case("{v15}", RISCV::V15) 11390 .Case("{v16}", RISCV::V16) 11391 .Case("{v17}", RISCV::V17) 11392 .Case("{v18}", RISCV::V18) 11393 .Case("{v19}", RISCV::V19) 11394 .Case("{v20}", RISCV::V20) 11395 .Case("{v21}", RISCV::V21) 11396 .Case("{v22}", RISCV::V22) 11397 .Case("{v23}", RISCV::V23) 11398 .Case("{v24}", RISCV::V24) 11399 .Case("{v25}", RISCV::V25) 11400 .Case("{v26}", RISCV::V26) 11401 .Case("{v27}", RISCV::V27) 11402 .Case("{v28}", RISCV::V28) 11403 .Case("{v29}", RISCV::V29) 11404 .Case("{v30}", RISCV::V30) 11405 .Case("{v31}", RISCV::V31) 11406 .Default(RISCV::NoRegister); 11407 if (VReg != RISCV::NoRegister) { 11408 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11409 return std::make_pair(VReg, &RISCV::VMRegClass); 11410 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11411 return std::make_pair(VReg, &RISCV::VRRegClass); 11412 for (const auto *RC : 11413 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11414 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11415 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11416 return std::make_pair(VReg, RC); 11417 } 11418 } 11419 } 11420 } 11421 11422 std::pair<Register, const TargetRegisterClass *> Res = 11423 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11424 11425 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11426 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11427 // Subtarget into account. 11428 if (Res.second == &RISCV::GPRF16RegClass || 11429 Res.second == &RISCV::GPRF32RegClass || 11430 Res.second == &RISCV::GPRF64RegClass) 11431 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11432 11433 return Res; 11434 } 11435 11436 unsigned 11437 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11438 // Currently only support length 1 constraints. 11439 if (ConstraintCode.size() == 1) { 11440 switch (ConstraintCode[0]) { 11441 case 'A': 11442 return InlineAsm::Constraint_A; 11443 default: 11444 break; 11445 } 11446 } 11447 11448 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11449 } 11450 11451 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11452 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11453 SelectionDAG &DAG) const { 11454 // Currently only support length 1 constraints. 11455 if (Constraint.length() == 1) { 11456 switch (Constraint[0]) { 11457 case 'I': 11458 // Validate & create a 12-bit signed immediate operand. 11459 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11460 uint64_t CVal = C->getSExtValue(); 11461 if (isInt<12>(CVal)) 11462 Ops.push_back( 11463 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11464 } 11465 return; 11466 case 'J': 11467 // Validate & create an integer zero operand. 11468 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11469 if (C->getZExtValue() == 0) 11470 Ops.push_back( 11471 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11472 return; 11473 case 'K': 11474 // Validate & create a 5-bit unsigned immediate operand. 11475 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11476 uint64_t CVal = C->getZExtValue(); 11477 if (isUInt<5>(CVal)) 11478 Ops.push_back( 11479 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11480 } 11481 return; 11482 case 'S': 11483 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11484 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11485 GA->getValueType(0))); 11486 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11487 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11488 BA->getValueType(0))); 11489 } 11490 return; 11491 default: 11492 break; 11493 } 11494 } 11495 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11496 } 11497 11498 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11499 Instruction *Inst, 11500 AtomicOrdering Ord) const { 11501 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11502 return Builder.CreateFence(Ord); 11503 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11504 return Builder.CreateFence(AtomicOrdering::Release); 11505 return nullptr; 11506 } 11507 11508 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11509 Instruction *Inst, 11510 AtomicOrdering Ord) const { 11511 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11512 return Builder.CreateFence(AtomicOrdering::Acquire); 11513 return nullptr; 11514 } 11515 11516 TargetLowering::AtomicExpansionKind 11517 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11518 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11519 // point operations can't be used in an lr/sc sequence without breaking the 11520 // forward-progress guarantee. 11521 if (AI->isFloatingPointOperation()) 11522 return AtomicExpansionKind::CmpXChg; 11523 11524 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11525 if (Size == 8 || Size == 16) 11526 return AtomicExpansionKind::MaskedIntrinsic; 11527 return AtomicExpansionKind::None; 11528 } 11529 11530 static Intrinsic::ID 11531 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11532 if (XLen == 32) { 11533 switch (BinOp) { 11534 default: 11535 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11536 case AtomicRMWInst::Xchg: 11537 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11538 case AtomicRMWInst::Add: 11539 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11540 case AtomicRMWInst::Sub: 11541 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11542 case AtomicRMWInst::Nand: 11543 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11544 case AtomicRMWInst::Max: 11545 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11546 case AtomicRMWInst::Min: 11547 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11548 case AtomicRMWInst::UMax: 11549 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11550 case AtomicRMWInst::UMin: 11551 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11552 } 11553 } 11554 11555 if (XLen == 64) { 11556 switch (BinOp) { 11557 default: 11558 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11559 case AtomicRMWInst::Xchg: 11560 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11561 case AtomicRMWInst::Add: 11562 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11563 case AtomicRMWInst::Sub: 11564 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11565 case AtomicRMWInst::Nand: 11566 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11567 case AtomicRMWInst::Max: 11568 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11569 case AtomicRMWInst::Min: 11570 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11571 case AtomicRMWInst::UMax: 11572 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11573 case AtomicRMWInst::UMin: 11574 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11575 } 11576 } 11577 11578 llvm_unreachable("Unexpected XLen\n"); 11579 } 11580 11581 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11582 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11583 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11584 unsigned XLen = Subtarget.getXLen(); 11585 Value *Ordering = 11586 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11587 Type *Tys[] = {AlignedAddr->getType()}; 11588 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11589 AI->getModule(), 11590 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11591 11592 if (XLen == 64) { 11593 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11594 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11595 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11596 } 11597 11598 Value *Result; 11599 11600 // Must pass the shift amount needed to sign extend the loaded value prior 11601 // to performing a signed comparison for min/max. ShiftAmt is the number of 11602 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11603 // is the number of bits to left+right shift the value in order to 11604 // sign-extend. 11605 if (AI->getOperation() == AtomicRMWInst::Min || 11606 AI->getOperation() == AtomicRMWInst::Max) { 11607 const DataLayout &DL = AI->getModule()->getDataLayout(); 11608 unsigned ValWidth = 11609 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11610 Value *SextShamt = 11611 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11612 Result = Builder.CreateCall(LrwOpScwLoop, 11613 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11614 } else { 11615 Result = 11616 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11617 } 11618 11619 if (XLen == 64) 11620 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11621 return Result; 11622 } 11623 11624 TargetLowering::AtomicExpansionKind 11625 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11626 AtomicCmpXchgInst *CI) const { 11627 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11628 if (Size == 8 || Size == 16) 11629 return AtomicExpansionKind::MaskedIntrinsic; 11630 return AtomicExpansionKind::None; 11631 } 11632 11633 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11634 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11635 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11636 unsigned XLen = Subtarget.getXLen(); 11637 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11638 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11639 if (XLen == 64) { 11640 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11641 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11642 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11643 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11644 } 11645 Type *Tys[] = {AlignedAddr->getType()}; 11646 Function *MaskedCmpXchg = 11647 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11648 Value *Result = Builder.CreateCall( 11649 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11650 if (XLen == 64) 11651 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11652 return Result; 11653 } 11654 11655 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT, 11656 EVT DataVT) const { 11657 return false; 11658 } 11659 11660 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11661 EVT VT) const { 11662 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11663 return false; 11664 11665 switch (FPVT.getSimpleVT().SimpleTy) { 11666 case MVT::f16: 11667 return Subtarget.hasStdExtZfh(); 11668 case MVT::f32: 11669 return Subtarget.hasStdExtF(); 11670 case MVT::f64: 11671 return Subtarget.hasStdExtD(); 11672 default: 11673 return false; 11674 } 11675 } 11676 11677 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11678 // If we are using the small code model, we can reduce size of jump table 11679 // entry to 4 bytes. 11680 if (Subtarget.is64Bit() && !isPositionIndependent() && 11681 getTargetMachine().getCodeModel() == CodeModel::Small) { 11682 return MachineJumpTableInfo::EK_Custom32; 11683 } 11684 return TargetLowering::getJumpTableEncoding(); 11685 } 11686 11687 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11688 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11689 unsigned uid, MCContext &Ctx) const { 11690 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11691 getTargetMachine().getCodeModel() == CodeModel::Small); 11692 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11693 } 11694 11695 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11696 EVT VT) const { 11697 VT = VT.getScalarType(); 11698 11699 if (!VT.isSimple()) 11700 return false; 11701 11702 switch (VT.getSimpleVT().SimpleTy) { 11703 case MVT::f16: 11704 return Subtarget.hasStdExtZfh(); 11705 case MVT::f32: 11706 return Subtarget.hasStdExtF(); 11707 case MVT::f64: 11708 return Subtarget.hasStdExtD(); 11709 default: 11710 break; 11711 } 11712 11713 return false; 11714 } 11715 11716 Register RISCVTargetLowering::getExceptionPointerRegister( 11717 const Constant *PersonalityFn) const { 11718 return RISCV::X10; 11719 } 11720 11721 Register RISCVTargetLowering::getExceptionSelectorRegister( 11722 const Constant *PersonalityFn) const { 11723 return RISCV::X11; 11724 } 11725 11726 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11727 // Return false to suppress the unnecessary extensions if the LibCall 11728 // arguments or return value is f32 type for LP64 ABI. 11729 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11730 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11731 return false; 11732 11733 return true; 11734 } 11735 11736 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11737 if (Subtarget.is64Bit() && Type == MVT::i32) 11738 return true; 11739 11740 return IsSigned; 11741 } 11742 11743 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11744 SDValue C) const { 11745 // Check integral scalar types. 11746 if (VT.isScalarInteger()) { 11747 // Omit the optimization if the sub target has the M extension and the data 11748 // size exceeds XLen. 11749 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11750 return false; 11751 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11752 // Break the MUL to a SLLI and an ADD/SUB. 11753 const APInt &Imm = ConstNode->getAPIntValue(); 11754 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11755 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11756 return true; 11757 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11758 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11759 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11760 (Imm - 8).isPowerOf2())) 11761 return true; 11762 // Omit the following optimization if the sub target has the M extension 11763 // and the data size >= XLen. 11764 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11765 return false; 11766 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11767 // a pair of LUI/ADDI. 11768 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11769 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11770 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11771 (1 - ImmS).isPowerOf2()) 11772 return true; 11773 } 11774 } 11775 } 11776 11777 return false; 11778 } 11779 11780 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11781 SDValue ConstNode) const { 11782 // Let the DAGCombiner decide for vectors. 11783 EVT VT = AddNode.getValueType(); 11784 if (VT.isVector()) 11785 return true; 11786 11787 // Let the DAGCombiner decide for larger types. 11788 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11789 return true; 11790 11791 // It is worse if c1 is simm12 while c1*c2 is not. 11792 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11793 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11794 const APInt &C1 = C1Node->getAPIntValue(); 11795 const APInt &C2 = C2Node->getAPIntValue(); 11796 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11797 return false; 11798 11799 // Default to true and let the DAGCombiner decide. 11800 return true; 11801 } 11802 11803 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11804 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11805 bool *Fast) const { 11806 if (!VT.isVector()) 11807 return false; 11808 11809 EVT ElemVT = VT.getVectorElementType(); 11810 if (Alignment >= ElemVT.getStoreSize()) { 11811 if (Fast) 11812 *Fast = true; 11813 return true; 11814 } 11815 11816 return false; 11817 } 11818 11819 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11820 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11821 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11822 bool IsABIRegCopy = CC.hasValue(); 11823 EVT ValueVT = Val.getValueType(); 11824 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11825 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11826 // and cast to f32. 11827 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11828 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11829 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11830 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11831 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11832 Parts[0] = Val; 11833 return true; 11834 } 11835 11836 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11837 LLVMContext &Context = *DAG.getContext(); 11838 EVT ValueEltVT = ValueVT.getVectorElementType(); 11839 EVT PartEltVT = PartVT.getVectorElementType(); 11840 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11841 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11842 if (PartVTBitSize % ValueVTBitSize == 0) { 11843 assert(PartVTBitSize >= ValueVTBitSize); 11844 // If the element types are different, bitcast to the same element type of 11845 // PartVT first. 11846 // Give an example here, we want copy a <vscale x 1 x i8> value to 11847 // <vscale x 4 x i16>. 11848 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11849 // subvector, then we can bitcast to <vscale x 4 x i16>. 11850 if (ValueEltVT != PartEltVT) { 11851 if (PartVTBitSize > ValueVTBitSize) { 11852 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11853 assert(Count != 0 && "The number of element should not be zero."); 11854 EVT SameEltTypeVT = 11855 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11856 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11857 DAG.getUNDEF(SameEltTypeVT), Val, 11858 DAG.getVectorIdxConstant(0, DL)); 11859 } 11860 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11861 } else { 11862 Val = 11863 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11864 Val, DAG.getVectorIdxConstant(0, DL)); 11865 } 11866 Parts[0] = Val; 11867 return true; 11868 } 11869 } 11870 return false; 11871 } 11872 11873 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11874 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11875 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11876 bool IsABIRegCopy = CC.hasValue(); 11877 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11878 SDValue Val = Parts[0]; 11879 11880 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11881 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11882 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11883 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11884 return Val; 11885 } 11886 11887 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11888 LLVMContext &Context = *DAG.getContext(); 11889 SDValue Val = Parts[0]; 11890 EVT ValueEltVT = ValueVT.getVectorElementType(); 11891 EVT PartEltVT = PartVT.getVectorElementType(); 11892 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11893 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11894 if (PartVTBitSize % ValueVTBitSize == 0) { 11895 assert(PartVTBitSize >= ValueVTBitSize); 11896 EVT SameEltTypeVT = ValueVT; 11897 // If the element types are different, convert it to the same element type 11898 // of PartVT. 11899 // Give an example here, we want copy a <vscale x 1 x i8> value from 11900 // <vscale x 4 x i16>. 11901 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11902 // then we can extract <vscale x 1 x i8>. 11903 if (ValueEltVT != PartEltVT) { 11904 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11905 assert(Count != 0 && "The number of element should not be zero."); 11906 SameEltTypeVT = 11907 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11908 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11909 } 11910 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11911 DAG.getVectorIdxConstant(0, DL)); 11912 return Val; 11913 } 11914 } 11915 return SDValue(); 11916 } 11917 11918 SDValue 11919 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11920 SelectionDAG &DAG, 11921 SmallVectorImpl<SDNode *> &Created) const { 11922 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11923 if (isIntDivCheap(N->getValueType(0), Attr)) 11924 return SDValue(N, 0); // Lower SDIV as SDIV 11925 11926 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11927 "Unexpected divisor!"); 11928 11929 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11930 if (!Subtarget.hasStdExtZbt()) 11931 return SDValue(); 11932 11933 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11934 // Besides, more critical path instructions will be generated when dividing 11935 // by 2. So we keep using the original DAGs for these cases. 11936 unsigned Lg2 = Divisor.countTrailingZeros(); 11937 if (Lg2 == 1 || Lg2 >= 12) 11938 return SDValue(); 11939 11940 // fold (sdiv X, pow2) 11941 EVT VT = N->getValueType(0); 11942 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11943 return SDValue(); 11944 11945 SDLoc DL(N); 11946 SDValue N0 = N->getOperand(0); 11947 SDValue Zero = DAG.getConstant(0, DL, VT); 11948 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11949 11950 // Add (N0 < 0) ? Pow2 - 1 : 0; 11951 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11952 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11953 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11954 11955 Created.push_back(Cmp.getNode()); 11956 Created.push_back(Add.getNode()); 11957 Created.push_back(Sel.getNode()); 11958 11959 // Divide by pow2. 11960 SDValue SRA = 11961 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11962 11963 // If we're dividing by a positive value, we're done. Otherwise, we must 11964 // negate the result. 11965 if (Divisor.isNonNegative()) 11966 return SRA; 11967 11968 Created.push_back(SRA.getNode()); 11969 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11970 } 11971 11972 #define GET_REGISTER_MATCHER 11973 #include "RISCVGenAsmMatcher.inc" 11974 11975 Register 11976 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11977 const MachineFunction &MF) const { 11978 Register Reg = MatchRegisterAltName(RegName); 11979 if (Reg == RISCV::NoRegister) 11980 Reg = MatchRegisterName(RegName); 11981 if (Reg == RISCV::NoRegister) 11982 report_fatal_error( 11983 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11984 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11985 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11986 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11987 StringRef(RegName) + "\".")); 11988 return Reg; 11989 } 11990 11991 namespace llvm { 11992 namespace RISCVVIntrinsicsTable { 11993 11994 #define GET_RISCVVIntrinsicsTable_IMPL 11995 #include "RISCVGenSearchableTables.inc" 11996 11997 } // namespace RISCVVIntrinsicsTable 11998 11999 } // namespace llvm 12000