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/CommandLine.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/KnownBits.h" 40 #include "llvm/Support/MathExtras.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include <optional> 43 44 using namespace llvm; 45 46 #define DEBUG_TYPE "riscv-lower" 47 48 STATISTIC(NumTailCalls, "Number of tail calls"); 49 50 static cl::opt<unsigned> ExtensionMaxWebSize( 51 DEBUG_TYPE "-ext-max-web-size", cl::Hidden, 52 cl::desc("Give the maximum size (in number of nodes) of the web of " 53 "instructions that we will consider for VW expansion"), 54 cl::init(18)); 55 56 static cl::opt<bool> 57 AllowSplatInVW_W(DEBUG_TYPE "-form-vw-w-with-splat", cl::Hidden, 58 cl::desc("Allow the formation of VW_W operations (e.g., " 59 "VWADD_W) with splat constants"), 60 cl::init(false)); 61 62 static cl::opt<unsigned> NumRepeatedDivisors( 63 DEBUG_TYPE "-fp-repeated-divisors", cl::Hidden, 64 cl::desc("Set the minimum number of repetitions of a divisor to allow " 65 "transformation to multiplications by the reciprocal"), 66 cl::init(2)); 67 68 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 69 const RISCVSubtarget &STI) 70 : TargetLowering(TM), Subtarget(STI) { 71 72 if (Subtarget.isRV32E()) 73 report_fatal_error("Codegen not yet implemented for RV32E"); 74 75 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 76 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 77 78 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 79 !Subtarget.hasStdExtF()) { 80 errs() << "Hard-float 'f' ABI can't be used for a target that " 81 "doesn't support the F instruction set extension (ignoring " 82 "target-abi)\n"; 83 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 84 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 85 !Subtarget.hasStdExtD()) { 86 errs() << "Hard-float 'd' ABI can't be used for a target that " 87 "doesn't support the D instruction set extension (ignoring " 88 "target-abi)\n"; 89 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 90 } 91 92 switch (ABI) { 93 default: 94 report_fatal_error("Don't know how to lower this ABI"); 95 case RISCVABI::ABI_ILP32: 96 case RISCVABI::ABI_ILP32F: 97 case RISCVABI::ABI_ILP32D: 98 case RISCVABI::ABI_LP64: 99 case RISCVABI::ABI_LP64F: 100 case RISCVABI::ABI_LP64D: 101 break; 102 } 103 104 MVT XLenVT = Subtarget.getXLenVT(); 105 106 // Set up the register classes. 107 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 108 109 if (Subtarget.hasStdExtZfhOrZfhmin()) 110 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 111 if (Subtarget.hasStdExtF()) 112 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 113 if (Subtarget.hasStdExtD()) 114 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 115 116 static const MVT::SimpleValueType BoolVecVTs[] = { 117 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 118 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 119 static const MVT::SimpleValueType IntVecVTs[] = { 120 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 121 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 122 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 123 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 124 MVT::nxv4i64, MVT::nxv8i64}; 125 static const MVT::SimpleValueType F16VecVTs[] = { 126 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 127 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 128 static const MVT::SimpleValueType F32VecVTs[] = { 129 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 130 static const MVT::SimpleValueType F64VecVTs[] = { 131 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 132 133 if (Subtarget.hasVInstructions()) { 134 auto addRegClassForRVV = [this](MVT VT) { 135 // Disable the smallest fractional LMUL types if ELEN is less than 136 // RVVBitsPerBlock. 137 unsigned MinElts = RISCV::RVVBitsPerBlock / Subtarget.getELEN(); 138 if (VT.getVectorMinNumElements() < MinElts) 139 return; 140 141 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 142 const TargetRegisterClass *RC; 143 if (Size <= RISCV::RVVBitsPerBlock) 144 RC = &RISCV::VRRegClass; 145 else if (Size == 2 * RISCV::RVVBitsPerBlock) 146 RC = &RISCV::VRM2RegClass; 147 else if (Size == 4 * RISCV::RVVBitsPerBlock) 148 RC = &RISCV::VRM4RegClass; 149 else if (Size == 8 * RISCV::RVVBitsPerBlock) 150 RC = &RISCV::VRM8RegClass; 151 else 152 llvm_unreachable("Unexpected size"); 153 154 addRegisterClass(VT, RC); 155 }; 156 157 for (MVT VT : BoolVecVTs) 158 addRegClassForRVV(VT); 159 for (MVT VT : IntVecVTs) { 160 if (VT.getVectorElementType() == MVT::i64 && 161 !Subtarget.hasVInstructionsI64()) 162 continue; 163 addRegClassForRVV(VT); 164 } 165 166 if (Subtarget.hasVInstructionsF16()) 167 for (MVT VT : F16VecVTs) 168 addRegClassForRVV(VT); 169 170 if (Subtarget.hasVInstructionsF32()) 171 for (MVT VT : F32VecVTs) 172 addRegClassForRVV(VT); 173 174 if (Subtarget.hasVInstructionsF64()) 175 for (MVT VT : F64VecVTs) 176 addRegClassForRVV(VT); 177 178 if (Subtarget.useRVVForFixedLengthVectors()) { 179 auto addRegClassForFixedVectors = [this](MVT VT) { 180 MVT ContainerVT = getContainerForFixedLengthVector(VT); 181 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 182 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 183 addRegisterClass(VT, TRI.getRegClass(RCID)); 184 }; 185 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 186 if (useRVVForFixedLengthVectorVT(VT)) 187 addRegClassForFixedVectors(VT); 188 189 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 190 if (useRVVForFixedLengthVectorVT(VT)) 191 addRegClassForFixedVectors(VT); 192 } 193 } 194 195 // Compute derived properties from the register classes. 196 computeRegisterProperties(STI.getRegisterInfo()); 197 198 setStackPointerRegisterToSaveRestore(RISCV::X2); 199 200 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT, 201 MVT::i1, Promote); 202 // DAGCombiner can call isLoadExtLegal for types that aren't legal. 203 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, MVT::i32, 204 MVT::i1, Promote); 205 206 // TODO: add all necessary setOperationAction calls. 207 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 208 209 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 210 setOperationAction(ISD::BR_CC, XLenVT, Expand); 211 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 212 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 213 214 setCondCodeAction(ISD::SETLE, XLenVT, Expand); 215 setCondCodeAction(ISD::SETGT, XLenVT, Custom); 216 setCondCodeAction(ISD::SETGE, XLenVT, Expand); 217 setCondCodeAction(ISD::SETULE, XLenVT, Expand); 218 setCondCodeAction(ISD::SETUGT, XLenVT, Custom); 219 setCondCodeAction(ISD::SETUGE, XLenVT, Expand); 220 221 setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand); 222 223 setOperationAction(ISD::VASTART, MVT::Other, Custom); 224 setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand); 225 226 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 227 228 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 229 230 if (!Subtarget.hasStdExtZbb()) 231 setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand); 232 233 if (Subtarget.is64Bit()) { 234 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 235 236 setOperationAction(ISD::LOAD, MVT::i32, Custom); 237 238 setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL}, 239 MVT::i32, Custom); 240 241 setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT}, 242 MVT::i32, Custom); 243 } else { 244 setLibcallName( 245 {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128}, 246 nullptr); 247 setLibcallName(RTLIB::MULO_I64, nullptr); 248 } 249 250 if (!Subtarget.hasStdExtM() && !Subtarget.hasStdExtZmmul()) { 251 setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU}, XLenVT, Expand); 252 } else { 253 if (Subtarget.is64Bit()) { 254 setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom); 255 } else { 256 setOperationAction(ISD::MUL, MVT::i64, Custom); 257 } 258 } 259 260 if (!Subtarget.hasStdExtM()) { 261 setOperationAction({ISD::SDIV, ISD::UDIV, ISD::SREM, ISD::UREM}, 262 XLenVT, Expand); 263 } else { 264 if (Subtarget.is64Bit()) { 265 setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM}, 266 {MVT::i8, MVT::i16, MVT::i32}, Custom); 267 } 268 } 269 270 setOperationAction( 271 {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT, 272 Expand); 273 274 setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT, 275 Custom); 276 277 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) { 278 if (Subtarget.is64Bit()) 279 setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom); 280 } else { 281 setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand); 282 } 283 284 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 285 // pattern match it directly in isel. 286 setOperationAction(ISD::BSWAP, XLenVT, 287 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 288 ? Legal 289 : Expand); 290 // Zbkb can use rev8+brev8 to implement bitreverse. 291 setOperationAction(ISD::BITREVERSE, XLenVT, 292 Subtarget.hasStdExtZbkb() ? Custom : Expand); 293 294 if (Subtarget.hasStdExtZbb()) { 295 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT, 296 Legal); 297 298 if (Subtarget.is64Bit()) 299 setOperationAction( 300 {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, 301 MVT::i32, Custom); 302 } else { 303 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand); 304 } 305 306 if (Subtarget.is64Bit()) 307 setOperationAction(ISD::ABS, MVT::i32, Custom); 308 309 if (!Subtarget.hasVendorXVentanaCondOps()) 310 setOperationAction(ISD::SELECT, XLenVT, Custom); 311 312 static const unsigned FPLegalNodeTypes[] = { 313 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 314 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 315 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 316 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 317 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 318 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 319 320 static const ISD::CondCode FPCCToExpand[] = { 321 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 322 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 323 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 324 325 static const unsigned FPOpToExpand[] = { 326 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 327 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 328 329 static const unsigned FPRndMode[] = { 330 ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FRINT, ISD::FROUND, 331 ISD::FROUNDEVEN}; 332 333 if (Subtarget.hasStdExtZfhOrZfhmin()) 334 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 335 336 if (Subtarget.hasStdExtZfhOrZfhmin()) { 337 if (Subtarget.hasStdExtZfh()) { 338 setOperationAction(FPLegalNodeTypes, MVT::f16, Legal); 339 setOperationAction(FPRndMode, MVT::f16, Custom); 340 setOperationAction(ISD::SELECT, MVT::f16, Custom); 341 } else { 342 static const unsigned ZfhminPromoteOps[] = { 343 ISD::FMINNUM, ISD::FMAXNUM, ISD::FADD, 344 ISD::FSUB, ISD::FMUL, ISD::FMA, 345 ISD::FDIV, ISD::FSQRT, ISD::FABS, 346 ISD::FNEG, ISD::STRICT_FMA, ISD::STRICT_FADD, 347 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 348 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS, 349 ISD::SETCC, ISD::FCEIL, ISD::FFLOOR, 350 ISD::FTRUNC, ISD::FRINT, ISD::FROUND, 351 ISD::FROUNDEVEN, ISD::SELECT}; 352 353 setOperationAction(ZfhminPromoteOps, MVT::f16, Promote); 354 setOperationAction({ISD::STRICT_LRINT, ISD::STRICT_LLRINT, 355 ISD::STRICT_LROUND, ISD::STRICT_LLROUND}, 356 MVT::f16, Legal); 357 // FIXME: Need to promote f16 FCOPYSIGN to f32, but the 358 // DAGCombiner::visitFP_ROUND probably needs improvements first. 359 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand); 360 } 361 362 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 363 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 364 setCondCodeAction(FPCCToExpand, MVT::f16, Expand); 365 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 366 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 367 368 setOperationAction({ISD::FREM, ISD::FNEARBYINT, ISD::FPOW, ISD::FPOWI, 369 ISD::FCOS, ISD::FSIN, ISD::FSINCOS, ISD::FEXP, 370 ISD::FEXP2, ISD::FLOG, ISD::FLOG2, ISD::FLOG10}, 371 MVT::f16, Promote); 372 373 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 374 // complete support for all operations in LegalizeDAG. 375 setOperationAction({ISD::STRICT_FCEIL, ISD::STRICT_FFLOOR, 376 ISD::STRICT_FNEARBYINT, ISD::STRICT_FRINT, 377 ISD::STRICT_FROUND, ISD::STRICT_FROUNDEVEN, 378 ISD::STRICT_FTRUNC}, 379 MVT::f16, Promote); 380 381 // We need to custom promote this. 382 if (Subtarget.is64Bit()) 383 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 384 } 385 386 if (Subtarget.hasStdExtF()) { 387 setOperationAction(FPLegalNodeTypes, MVT::f32, Legal); 388 setOperationAction(FPRndMode, MVT::f32, Custom); 389 setCondCodeAction(FPCCToExpand, MVT::f32, Expand); 390 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 391 setOperationAction(ISD::SELECT, MVT::f32, Custom); 392 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 393 setOperationAction(FPOpToExpand, MVT::f32, Expand); 394 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 395 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 396 } 397 398 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 399 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 400 401 if (Subtarget.hasStdExtD()) { 402 setOperationAction(FPLegalNodeTypes, MVT::f64, Legal); 403 if (Subtarget.is64Bit()) { 404 setOperationAction(FPRndMode, MVT::f64, Custom); 405 } 406 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 407 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 408 setCondCodeAction(FPCCToExpand, MVT::f64, Expand); 409 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 410 setOperationAction(ISD::SELECT, MVT::f64, Custom); 411 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 412 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 413 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 414 setOperationAction(FPOpToExpand, MVT::f64, Expand); 415 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 416 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 417 } 418 419 if (Subtarget.is64Bit()) 420 setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT, 421 ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT}, 422 MVT::i32, Custom); 423 424 if (Subtarget.hasStdExtF()) { 425 setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT, 426 Custom); 427 428 setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT, 429 ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP}, 430 XLenVT, Legal); 431 432 setOperationAction(ISD::GET_ROUNDING, XLenVT, Custom); 433 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 434 } 435 436 setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool, 437 ISD::JumpTable}, 438 XLenVT, Custom); 439 440 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 441 442 if (Subtarget.is64Bit()) 443 setOperationAction(ISD::Constant, MVT::i64, Custom); 444 445 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 446 // Unfortunately this can't be determined just from the ISA naming string. 447 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 448 Subtarget.is64Bit() ? Legal : Custom); 449 450 setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal); 451 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 452 if (Subtarget.is64Bit()) 453 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 454 455 if (Subtarget.hasStdExtA()) { 456 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 457 setMinCmpXchgSizeInBits(32); 458 } else if (Subtarget.hasForcedAtomics()) { 459 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 460 } else { 461 setMaxAtomicSizeInBitsSupported(0); 462 } 463 464 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 465 466 setBooleanContents(ZeroOrOneBooleanContent); 467 468 if (Subtarget.hasVInstructions()) { 469 setBooleanVectorContents(ZeroOrOneBooleanContent); 470 471 setOperationAction(ISD::VSCALE, XLenVT, Custom); 472 473 // RVV intrinsics may have illegal operands. 474 // We also need to custom legalize vmv.x.s. 475 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 476 {MVT::i8, MVT::i16}, Custom); 477 if (Subtarget.is64Bit()) 478 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 479 else 480 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 481 MVT::i64, Custom); 482 483 setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID}, 484 MVT::Other, Custom); 485 486 static const unsigned IntegerVPOps[] = { 487 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 488 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 489 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 490 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 491 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 492 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 493 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 494 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FP_TO_SINT, 495 ISD::VP_FP_TO_UINT, ISD::VP_SETCC, ISD::VP_SIGN_EXTEND, 496 ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE, ISD::VP_SMIN, 497 ISD::VP_SMAX, ISD::VP_UMIN, ISD::VP_UMAX, 498 ISD::VP_ABS}; 499 500 static const unsigned FloatingPointVPOps[] = { 501 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 502 ISD::VP_FDIV, ISD::VP_FNEG, ISD::VP_FABS, 503 ISD::VP_FMA, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 504 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, 505 ISD::VP_SELECT, ISD::VP_SINT_TO_FP, ISD::VP_UINT_TO_FP, 506 ISD::VP_SETCC, ISD::VP_FP_ROUND, ISD::VP_FP_EXTEND, 507 ISD::VP_SQRT, ISD::VP_FMINNUM, ISD::VP_FMAXNUM, 508 ISD::VP_FCEIL, ISD::VP_FFLOOR, ISD::VP_FROUND, 509 ISD::VP_FROUNDEVEN, ISD::VP_FCOPYSIGN, ISD::VP_FROUNDTOZERO, 510 ISD::VP_FRINT, ISD::VP_FNEARBYINT}; 511 512 static const unsigned IntegerVecReduceOps[] = { 513 ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, 514 ISD::VECREDUCE_XOR, ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 515 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}; 516 517 static const unsigned FloatingPointVecReduceOps[] = { 518 ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, ISD::VECREDUCE_FMIN, 519 ISD::VECREDUCE_FMAX}; 520 521 if (!Subtarget.is64Bit()) { 522 // We must custom-lower certain vXi64 operations on RV32 due to the vector 523 // element type being illegal. 524 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 525 MVT::i64, Custom); 526 527 setOperationAction(IntegerVecReduceOps, MVT::i64, Custom); 528 529 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 530 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, 531 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN, 532 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}, 533 MVT::i64, Custom); 534 } 535 536 for (MVT VT : BoolVecVTs) { 537 if (!isTypeLegal(VT)) 538 continue; 539 540 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 541 542 // Mask VTs are custom-expanded into a series of standard nodes 543 setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS, 544 ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 545 VT, Custom); 546 547 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 548 Custom); 549 550 setOperationAction(ISD::SELECT, VT, Custom); 551 setOperationAction( 552 {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT, 553 Expand); 554 555 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom); 556 557 setOperationAction( 558 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 559 Custom); 560 561 setOperationAction( 562 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 563 Custom); 564 565 // RVV has native int->float & float->int conversions where the 566 // element type sizes are within one power-of-two of each other. Any 567 // wider distances between type sizes have to be lowered as sequences 568 // which progressively narrow the gap in stages. 569 setOperationAction( 570 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 571 VT, Custom); 572 setOperationAction({ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}, VT, 573 Custom); 574 575 // Expand all extending loads to types larger than this, and truncating 576 // stores from types larger than this. 577 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 578 setTruncStoreAction(OtherVT, VT, Expand); 579 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 580 VT, Expand); 581 } 582 583 setOperationAction({ISD::VP_FP_TO_SINT, ISD::VP_FP_TO_UINT, 584 ISD::VP_TRUNCATE, ISD::VP_SETCC}, 585 VT, Custom); 586 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 587 588 setOperationPromotedToType( 589 ISD::VECTOR_SPLICE, VT, 590 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount())); 591 } 592 593 for (MVT VT : IntVecVTs) { 594 if (!isTypeLegal(VT)) 595 continue; 596 597 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 598 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 599 600 // Vectors implement MULHS/MULHU. 601 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 602 603 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 604 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 605 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 606 607 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 608 Legal); 609 610 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 611 612 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, VT, Expand); 613 614 setOperationAction(ISD::BSWAP, VT, Expand); 615 setOperationAction({ISD::VP_BSWAP, ISD::VP_BITREVERSE}, VT, Expand); 616 setOperationAction({ISD::VP_FSHL, ISD::VP_FSHR}, VT, Expand); 617 setOperationAction({ISD::VP_CTLZ, ISD::VP_CTLZ_ZERO_UNDEF, ISD::VP_CTTZ, 618 ISD::VP_CTTZ_ZERO_UNDEF, ISD::VP_CTPOP}, 619 VT, Expand); 620 621 // Custom-lower extensions and truncations from/to mask types. 622 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 623 VT, Custom); 624 625 // RVV has native int->float & float->int conversions where the 626 // element type sizes are within one power-of-two of each other. Any 627 // wider distances between type sizes have to be lowered as sequences 628 // which progressively narrow the gap in stages. 629 setOperationAction( 630 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 631 VT, Custom); 632 setOperationAction({ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}, VT, 633 Custom); 634 635 setOperationAction( 636 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 637 638 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 639 // nodes which truncate by one power of two at a time. 640 setOperationAction(ISD::TRUNCATE, VT, Custom); 641 642 // Custom-lower insert/extract operations to simplify patterns. 643 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 644 Custom); 645 646 // Custom-lower reduction operations to set up the corresponding custom 647 // nodes' operands. 648 setOperationAction(IntegerVecReduceOps, VT, Custom); 649 650 setOperationAction(IntegerVPOps, VT, Custom); 651 652 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 653 654 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 655 VT, Custom); 656 657 setOperationAction( 658 {ISD::VP_LOAD, ISD::VP_STORE, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, 659 ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, 660 VT, Custom); 661 662 setOperationAction( 663 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 664 VT, Custom); 665 666 setOperationAction(ISD::SELECT, VT, Custom); 667 setOperationAction(ISD::SELECT_CC, VT, Expand); 668 669 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 670 671 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 672 setTruncStoreAction(VT, OtherVT, Expand); 673 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 674 VT, Expand); 675 } 676 677 // Splice 678 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 679 680 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if element of VT in the range 681 // of f32. 682 EVT FloatVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 683 if (isTypeLegal(FloatVT)) { 684 setOperationAction( 685 {ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 686 Custom); 687 } 688 } 689 690 // Expand various CCs to best match the RVV ISA, which natively supports UNE 691 // but no other unordered comparisons, and supports all ordered comparisons 692 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 693 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 694 // and we pattern-match those back to the "original", swapping operands once 695 // more. This way we catch both operations and both "vf" and "fv" forms with 696 // fewer patterns. 697 static const ISD::CondCode VFPCCToExpand[] = { 698 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 699 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 700 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 701 }; 702 703 // Sets common operation actions on RVV floating-point vector types. 704 const auto SetCommonVFPActions = [&](MVT VT) { 705 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 706 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 707 // sizes are within one power-of-two of each other. Therefore conversions 708 // between vXf16 and vXf64 must be lowered as sequences which convert via 709 // vXf32. 710 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 711 // Custom-lower insert/extract operations to simplify patterns. 712 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 713 Custom); 714 // Expand various condition codes (explained above). 715 setCondCodeAction(VFPCCToExpand, VT, Expand); 716 717 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 718 719 setOperationAction( 720 {ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND, ISD::FROUNDEVEN}, 721 VT, Custom); 722 723 setOperationAction(FloatingPointVecReduceOps, VT, Custom); 724 725 // Expand FP operations that need libcalls. 726 setOperationAction(ISD::FREM, VT, Expand); 727 setOperationAction(ISD::FPOW, VT, Expand); 728 setOperationAction(ISD::FCOS, VT, Expand); 729 setOperationAction(ISD::FSIN, VT, Expand); 730 setOperationAction(ISD::FSINCOS, VT, Expand); 731 setOperationAction(ISD::FEXP, VT, Expand); 732 setOperationAction(ISD::FEXP2, VT, Expand); 733 setOperationAction(ISD::FLOG, VT, Expand); 734 setOperationAction(ISD::FLOG2, VT, Expand); 735 setOperationAction(ISD::FLOG10, VT, Expand); 736 setOperationAction(ISD::FRINT, VT, Expand); 737 setOperationAction(ISD::FNEARBYINT, VT, Expand); 738 739 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 740 741 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 742 743 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 744 VT, Custom); 745 746 setOperationAction( 747 {ISD::VP_LOAD, ISD::VP_STORE, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, 748 ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, 749 VT, Custom); 750 751 setOperationAction(ISD::SELECT, VT, Custom); 752 setOperationAction(ISD::SELECT_CC, VT, Expand); 753 754 setOperationAction( 755 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 756 VT, Custom); 757 758 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 759 760 setOperationAction(FloatingPointVPOps, VT, Custom); 761 }; 762 763 // Sets common extload/truncstore actions on RVV floating-point vector 764 // types. 765 const auto SetCommonVFPExtLoadTruncStoreActions = 766 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 767 for (auto SmallVT : SmallerVTs) { 768 setTruncStoreAction(VT, SmallVT, Expand); 769 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 770 } 771 }; 772 773 if (Subtarget.hasVInstructionsF16()) { 774 for (MVT VT : F16VecVTs) { 775 if (!isTypeLegal(VT)) 776 continue; 777 SetCommonVFPActions(VT); 778 } 779 } 780 781 if (Subtarget.hasVInstructionsF32()) { 782 for (MVT VT : F32VecVTs) { 783 if (!isTypeLegal(VT)) 784 continue; 785 SetCommonVFPActions(VT); 786 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 787 } 788 } 789 790 if (Subtarget.hasVInstructionsF64()) { 791 for (MVT VT : F64VecVTs) { 792 if (!isTypeLegal(VT)) 793 continue; 794 SetCommonVFPActions(VT); 795 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 796 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 797 } 798 } 799 800 if (Subtarget.useRVVForFixedLengthVectors()) { 801 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 802 if (!useRVVForFixedLengthVectorVT(VT)) 803 continue; 804 805 // By default everything must be expanded. 806 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 807 setOperationAction(Op, VT, Expand); 808 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 809 setTruncStoreAction(VT, OtherVT, Expand); 810 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, 811 OtherVT, VT, Expand); 812 } 813 814 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 815 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 816 Custom); 817 818 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT, 819 Custom); 820 821 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 822 VT, Custom); 823 824 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 825 826 setOperationAction(ISD::SETCC, VT, Custom); 827 828 setOperationAction(ISD::SELECT, VT, Custom); 829 830 setOperationAction(ISD::TRUNCATE, VT, Custom); 831 832 setOperationAction(ISD::BITCAST, VT, Custom); 833 834 setOperationAction( 835 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 836 Custom); 837 838 setOperationAction( 839 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 840 Custom); 841 842 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, 843 ISD::FP_TO_UINT}, 844 VT, Custom); 845 setOperationAction({ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}, VT, 846 Custom); 847 848 // Operations below are different for between masks and other vectors. 849 if (VT.getVectorElementType() == MVT::i1) { 850 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND, 851 ISD::OR, ISD::XOR}, 852 VT, Custom); 853 854 setOperationAction({ISD::VP_FP_TO_SINT, ISD::VP_FP_TO_UINT, 855 ISD::VP_SETCC, ISD::VP_TRUNCATE}, 856 VT, Custom); 857 continue; 858 } 859 860 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 861 // it before type legalization for i64 vectors on RV32. It will then be 862 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 863 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 864 // improvements first. 865 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 866 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 867 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 868 } 869 870 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 871 872 setOperationAction( 873 {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom); 874 875 setOperationAction({ISD::VP_LOAD, ISD::VP_STORE, 876 ISD::EXPERIMENTAL_VP_STRIDED_LOAD, 877 ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER, 878 ISD::VP_SCATTER}, 879 VT, Custom); 880 881 setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR, 882 ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV, 883 ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL}, 884 VT, Custom); 885 886 setOperationAction( 887 {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom); 888 889 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 890 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) 891 setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom); 892 893 setOperationAction( 894 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, 895 Custom); 896 897 setOperationAction(ISD::VSELECT, VT, Custom); 898 setOperationAction(ISD::SELECT_CC, VT, Expand); 899 900 setOperationAction( 901 {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom); 902 903 // Custom-lower reduction operations to set up the corresponding custom 904 // nodes' operands. 905 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX, 906 ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX, 907 ISD::VECREDUCE_UMIN}, 908 VT, Custom); 909 910 setOperationAction(IntegerVPOps, VT, Custom); 911 912 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if element of VT in the 913 // range of f32. 914 EVT FloatVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 915 if (isTypeLegal(FloatVT)) 916 setOperationAction( 917 {ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 918 Custom); 919 } 920 921 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 922 if (!useRVVForFixedLengthVectorVT(VT)) 923 continue; 924 925 // By default everything must be expanded. 926 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 927 setOperationAction(Op, VT, Expand); 928 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 929 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 930 setTruncStoreAction(VT, OtherVT, Expand); 931 } 932 933 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 934 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 935 Custom); 936 937 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 938 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 939 ISD::EXTRACT_VECTOR_ELT}, 940 VT, Custom); 941 942 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 943 ISD::MGATHER, ISD::MSCATTER}, 944 VT, Custom); 945 946 setOperationAction({ISD::VP_LOAD, ISD::VP_STORE, 947 ISD::EXPERIMENTAL_VP_STRIDED_LOAD, 948 ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER, 949 ISD::VP_SCATTER}, 950 VT, Custom); 951 952 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 953 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 954 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 955 VT, Custom); 956 957 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 958 959 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND, 960 ISD::FROUNDEVEN}, 961 VT, Custom); 962 963 setCondCodeAction(VFPCCToExpand, VT, Expand); 964 965 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 966 setOperationAction(ISD::SELECT_CC, VT, Expand); 967 968 setOperationAction(ISD::BITCAST, VT, Custom); 969 970 setOperationAction(FloatingPointVecReduceOps, VT, Custom); 971 972 setOperationAction(FloatingPointVPOps, VT, Custom); 973 } 974 975 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 976 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 977 Custom); 978 if (Subtarget.hasStdExtZfhOrZfhmin()) 979 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 980 if (Subtarget.hasStdExtF()) 981 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 982 if (Subtarget.hasStdExtD()) 983 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 984 } 985 } 986 987 if (Subtarget.hasForcedAtomics()) { 988 // Set atomic rmw/cas operations to expand to force __sync libcalls. 989 setOperationAction( 990 {ISD::ATOMIC_CMP_SWAP, ISD::ATOMIC_SWAP, ISD::ATOMIC_LOAD_ADD, 991 ISD::ATOMIC_LOAD_SUB, ISD::ATOMIC_LOAD_AND, ISD::ATOMIC_LOAD_OR, 992 ISD::ATOMIC_LOAD_XOR, ISD::ATOMIC_LOAD_NAND, ISD::ATOMIC_LOAD_MIN, 993 ISD::ATOMIC_LOAD_MAX, ISD::ATOMIC_LOAD_UMIN, ISD::ATOMIC_LOAD_UMAX}, 994 XLenVT, Expand); 995 } 996 997 // Function alignments. 998 const Align FunctionAlignment(Subtarget.hasStdExtCOrZca() ? 2 : 4); 999 setMinFunctionAlignment(FunctionAlignment); 1000 setPrefFunctionAlignment(FunctionAlignment); 1001 1002 setMinimumJumpTableEntries(5); 1003 1004 // Jumps are expensive, compared to logic 1005 setJumpIsExpensive(); 1006 1007 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 1008 ISD::OR, ISD::XOR, ISD::SETCC, ISD::SELECT}); 1009 if (Subtarget.is64Bit()) 1010 setTargetDAGCombine(ISD::SRA); 1011 1012 if (Subtarget.hasStdExtF()) 1013 setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM}); 1014 1015 if (Subtarget.hasStdExtZbb()) 1016 setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN}); 1017 1018 if (Subtarget.hasStdExtZbs() && Subtarget.is64Bit()) 1019 setTargetDAGCombine(ISD::TRUNCATE); 1020 1021 if (Subtarget.hasStdExtZbkb()) 1022 setTargetDAGCombine(ISD::BITREVERSE); 1023 if (Subtarget.hasStdExtZfhOrZfhmin()) 1024 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 1025 if (Subtarget.hasStdExtF()) 1026 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 1027 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 1028 if (Subtarget.hasVInstructions()) 1029 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 1030 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 1031 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 1032 if (Subtarget.useRVVForFixedLengthVectors()) 1033 setTargetDAGCombine(ISD::BITCAST); 1034 1035 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1036 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1037 } 1038 1039 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1040 LLVMContext &Context, 1041 EVT VT) const { 1042 if (!VT.isVector()) 1043 return getPointerTy(DL); 1044 if (Subtarget.hasVInstructions() && 1045 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1046 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1047 return VT.changeVectorElementTypeToInteger(); 1048 } 1049 1050 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1051 return Subtarget.getXLenVT(); 1052 } 1053 1054 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1055 const CallInst &I, 1056 MachineFunction &MF, 1057 unsigned Intrinsic) const { 1058 auto &DL = I.getModule()->getDataLayout(); 1059 switch (Intrinsic) { 1060 default: 1061 return false; 1062 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1063 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1064 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1065 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1066 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1067 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1068 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1069 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1070 case Intrinsic::riscv_masked_cmpxchg_i32: 1071 Info.opc = ISD::INTRINSIC_W_CHAIN; 1072 Info.memVT = MVT::i32; 1073 Info.ptrVal = I.getArgOperand(0); 1074 Info.offset = 0; 1075 Info.align = Align(4); 1076 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1077 MachineMemOperand::MOVolatile; 1078 return true; 1079 case Intrinsic::riscv_masked_strided_load: 1080 Info.opc = ISD::INTRINSIC_W_CHAIN; 1081 Info.ptrVal = I.getArgOperand(1); 1082 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1083 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1084 Info.size = MemoryLocation::UnknownSize; 1085 Info.flags |= MachineMemOperand::MOLoad; 1086 return true; 1087 case Intrinsic::riscv_masked_strided_store: 1088 Info.opc = ISD::INTRINSIC_VOID; 1089 Info.ptrVal = I.getArgOperand(1); 1090 Info.memVT = 1091 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1092 Info.align = Align( 1093 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1094 8); 1095 Info.size = MemoryLocation::UnknownSize; 1096 Info.flags |= MachineMemOperand::MOStore; 1097 return true; 1098 case Intrinsic::riscv_seg2_load: 1099 case Intrinsic::riscv_seg3_load: 1100 case Intrinsic::riscv_seg4_load: 1101 case Intrinsic::riscv_seg5_load: 1102 case Intrinsic::riscv_seg6_load: 1103 case Intrinsic::riscv_seg7_load: 1104 case Intrinsic::riscv_seg8_load: 1105 Info.opc = ISD::INTRINSIC_W_CHAIN; 1106 Info.ptrVal = I.getArgOperand(0); 1107 Info.memVT = 1108 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1109 Info.align = 1110 Align(DL.getTypeSizeInBits( 1111 I.getType()->getStructElementType(0)->getScalarType()) / 1112 8); 1113 Info.size = MemoryLocation::UnknownSize; 1114 Info.flags |= MachineMemOperand::MOLoad; 1115 return true; 1116 } 1117 } 1118 1119 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1120 const AddrMode &AM, Type *Ty, 1121 unsigned AS, 1122 Instruction *I) const { 1123 // No global is ever allowed as a base. 1124 if (AM.BaseGV) 1125 return false; 1126 1127 // RVV instructions only support register addressing. 1128 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty)) 1129 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs; 1130 1131 // Require a 12-bit signed offset. 1132 if (!isInt<12>(AM.BaseOffs)) 1133 return false; 1134 1135 switch (AM.Scale) { 1136 case 0: // "r+i" or just "i", depending on HasBaseReg. 1137 break; 1138 case 1: 1139 if (!AM.HasBaseReg) // allow "r+i". 1140 break; 1141 return false; // disallow "r+r" or "r+r+i". 1142 default: 1143 return false; 1144 } 1145 1146 return true; 1147 } 1148 1149 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1150 return isInt<12>(Imm); 1151 } 1152 1153 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1154 return isInt<12>(Imm); 1155 } 1156 1157 // On RV32, 64-bit integers are split into their high and low parts and held 1158 // in two different registers, so the trunc is free since the low register can 1159 // just be used. 1160 // FIXME: Should we consider i64->i32 free on RV64 to match the EVT version of 1161 // isTruncateFree? 1162 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1163 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1164 return false; 1165 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1166 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1167 return (SrcBits == 64 && DestBits == 32); 1168 } 1169 1170 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1171 // We consider i64->i32 free on RV64 since we have good selection of W 1172 // instructions that make promoting operations back to i64 free in many cases. 1173 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 1174 !DstVT.isInteger()) 1175 return false; 1176 unsigned SrcBits = SrcVT.getSizeInBits(); 1177 unsigned DestBits = DstVT.getSizeInBits(); 1178 return (SrcBits == 64 && DestBits == 32); 1179 } 1180 1181 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1182 // Zexts are free if they can be combined with a load. 1183 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1184 // poorly with type legalization of compares preferring sext. 1185 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1186 EVT MemVT = LD->getMemoryVT(); 1187 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1188 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1189 LD->getExtensionType() == ISD::ZEXTLOAD)) 1190 return true; 1191 } 1192 1193 return TargetLowering::isZExtFree(Val, VT2); 1194 } 1195 1196 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1197 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1198 } 1199 1200 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1201 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1202 } 1203 1204 bool RISCVTargetLowering::isCheapToSpeculateCttz(Type *Ty) const { 1205 return Subtarget.hasStdExtZbb(); 1206 } 1207 1208 bool RISCVTargetLowering::isCheapToSpeculateCtlz(Type *Ty) const { 1209 return Subtarget.hasStdExtZbb(); 1210 } 1211 1212 bool RISCVTargetLowering::isMaskAndCmp0FoldingBeneficial( 1213 const Instruction &AndI) const { 1214 // We expect to be able to match a bit extraction instruction if the Zbs 1215 // extension is supported and the mask is a power of two. However, we 1216 // conservatively return false if the mask would fit in an ANDI instruction, 1217 // on the basis that it's possible the sinking+duplication of the AND in 1218 // CodeGenPrepare triggered by this hook wouldn't decrease the instruction 1219 // count and would increase code size (e.g. ANDI+BNEZ => BEXTI+BNEZ). 1220 if (!Subtarget.hasStdExtZbs()) 1221 return false; 1222 ConstantInt *Mask = dyn_cast<ConstantInt>(AndI.getOperand(1)); 1223 if (!Mask) 1224 return false; 1225 return !Mask->getValue().isSignedIntN(12) && Mask->getValue().isPowerOf2(); 1226 } 1227 1228 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1229 EVT VT = Y.getValueType(); 1230 1231 // FIXME: Support vectors once we have tests. 1232 if (VT.isVector()) 1233 return false; 1234 1235 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) && 1236 !isa<ConstantSDNode>(Y); 1237 } 1238 1239 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1240 // Zbs provides BEXT[_I], which can be used with SEQZ/SNEZ as a bit test. 1241 if (Subtarget.hasStdExtZbs()) 1242 return X.getValueType().isScalarInteger(); 1243 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1244 auto *C = dyn_cast<ConstantSDNode>(Y); 1245 return C && C->getAPIntValue().ule(10); 1246 } 1247 1248 bool RISCVTargetLowering::shouldFoldSelectWithIdentityConstant(unsigned Opcode, 1249 EVT VT) const { 1250 // Only enable for rvv. 1251 if (!VT.isVector() || !Subtarget.hasVInstructions()) 1252 return false; 1253 1254 if (VT.isFixedLengthVector() && !isTypeLegal(VT)) 1255 return false; 1256 1257 return true; 1258 } 1259 1260 bool RISCVTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1261 Type *Ty) const { 1262 assert(Ty->isIntegerTy()); 1263 1264 unsigned BitSize = Ty->getIntegerBitWidth(); 1265 if (BitSize > Subtarget.getXLen()) 1266 return false; 1267 1268 // Fast path, assume 32-bit immediates are cheap. 1269 int64_t Val = Imm.getSExtValue(); 1270 if (isInt<32>(Val)) 1271 return true; 1272 1273 // A constant pool entry may be more aligned thant he load we're trying to 1274 // replace. If we don't support unaligned scalar mem, prefer the constant 1275 // pool. 1276 // TODO: Can the caller pass down the alignment? 1277 if (!Subtarget.enableUnalignedScalarMem()) 1278 return true; 1279 1280 // Prefer to keep the load if it would require many instructions. 1281 // This uses the same threshold we use for constant pools but doesn't 1282 // check useConstantPoolForLargeInts. 1283 // TODO: Should we keep the load only when we're definitely going to emit a 1284 // constant pool? 1285 1286 RISCVMatInt::InstSeq Seq = 1287 RISCVMatInt::generateInstSeq(Val, Subtarget.getFeatureBits()); 1288 return Seq.size() <= Subtarget.getMaxBuildIntsCost(); 1289 } 1290 1291 bool RISCVTargetLowering:: 1292 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 1293 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 1294 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 1295 SelectionDAG &DAG) const { 1296 // One interesting pattern that we'd want to form is 'bit extract': 1297 // ((1 >> Y) & 1) ==/!= 0 1298 // But we also need to be careful not to try to reverse that fold. 1299 1300 // Is this '((1 >> Y) & 1)'? 1301 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne()) 1302 return false; // Keep the 'bit extract' pattern. 1303 1304 // Will this be '((1 >> Y) & 1)' after the transform? 1305 if (NewShiftOpcode == ISD::SRL && CC->isOne()) 1306 return true; // Do form the 'bit extract' pattern. 1307 1308 // If 'X' is a constant, and we transform, then we will immediately 1309 // try to undo the fold, thus causing endless combine loop. 1310 // So only do the transform if X is not a constant. This matches the default 1311 // implementation of this function. 1312 return !XC; 1313 } 1314 1315 bool RISCVTargetLowering::canSplatOperand(unsigned Opcode, int Operand) const { 1316 switch (Opcode) { 1317 case Instruction::Add: 1318 case Instruction::Sub: 1319 case Instruction::Mul: 1320 case Instruction::And: 1321 case Instruction::Or: 1322 case Instruction::Xor: 1323 case Instruction::FAdd: 1324 case Instruction::FSub: 1325 case Instruction::FMul: 1326 case Instruction::FDiv: 1327 case Instruction::ICmp: 1328 case Instruction::FCmp: 1329 return true; 1330 case Instruction::Shl: 1331 case Instruction::LShr: 1332 case Instruction::AShr: 1333 case Instruction::UDiv: 1334 case Instruction::SDiv: 1335 case Instruction::URem: 1336 case Instruction::SRem: 1337 return Operand == 1; 1338 default: 1339 return false; 1340 } 1341 } 1342 1343 1344 bool RISCVTargetLowering::canSplatOperand(Instruction *I, int Operand) const { 1345 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1346 return false; 1347 1348 if (canSplatOperand(I->getOpcode(), Operand)) 1349 return true; 1350 1351 auto *II = dyn_cast<IntrinsicInst>(I); 1352 if (!II) 1353 return false; 1354 1355 switch (II->getIntrinsicID()) { 1356 case Intrinsic::fma: 1357 case Intrinsic::vp_fma: 1358 return Operand == 0 || Operand == 1; 1359 case Intrinsic::vp_shl: 1360 case Intrinsic::vp_lshr: 1361 case Intrinsic::vp_ashr: 1362 case Intrinsic::vp_udiv: 1363 case Intrinsic::vp_sdiv: 1364 case Intrinsic::vp_urem: 1365 case Intrinsic::vp_srem: 1366 return Operand == 1; 1367 // These intrinsics are commutative. 1368 case Intrinsic::vp_add: 1369 case Intrinsic::vp_mul: 1370 case Intrinsic::vp_and: 1371 case Intrinsic::vp_or: 1372 case Intrinsic::vp_xor: 1373 case Intrinsic::vp_fadd: 1374 case Intrinsic::vp_fmul: 1375 // These intrinsics have 'vr' versions. 1376 case Intrinsic::vp_sub: 1377 case Intrinsic::vp_fsub: 1378 case Intrinsic::vp_fdiv: 1379 return Operand == 0 || Operand == 1; 1380 default: 1381 return false; 1382 } 1383 } 1384 1385 /// Check if sinking \p I's operands to I's basic block is profitable, because 1386 /// the operands can be folded into a target instruction, e.g. 1387 /// splats of scalars can fold into vector instructions. 1388 bool RISCVTargetLowering::shouldSinkOperands( 1389 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1390 using namespace llvm::PatternMatch; 1391 1392 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1393 return false; 1394 1395 for (auto OpIdx : enumerate(I->operands())) { 1396 if (!canSplatOperand(I, OpIdx.index())) 1397 continue; 1398 1399 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1400 // Make sure we are not already sinking this operand 1401 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1402 continue; 1403 1404 // We are looking for a splat that can be sunk. 1405 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1406 m_Undef(), m_ZeroMask()))) 1407 continue; 1408 1409 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1410 // and vector registers 1411 for (Use &U : Op->uses()) { 1412 Instruction *Insn = cast<Instruction>(U.getUser()); 1413 if (!canSplatOperand(Insn, U.getOperandNo())) 1414 return false; 1415 } 1416 1417 Ops.push_back(&Op->getOperandUse(0)); 1418 Ops.push_back(&OpIdx.value()); 1419 } 1420 return true; 1421 } 1422 1423 bool RISCVTargetLowering::shouldScalarizeBinop(SDValue VecOp) const { 1424 unsigned Opc = VecOp.getOpcode(); 1425 1426 // Assume target opcodes can't be scalarized. 1427 // TODO - do we have any exceptions? 1428 if (Opc >= ISD::BUILTIN_OP_END) 1429 return false; 1430 1431 // If the vector op is not supported, try to convert to scalar. 1432 EVT VecVT = VecOp.getValueType(); 1433 if (!isOperationLegalOrCustomOrPromote(Opc, VecVT)) 1434 return true; 1435 1436 // If the vector op is supported, but the scalar op is not, the transform may 1437 // not be worthwhile. 1438 EVT ScalarVT = VecVT.getScalarType(); 1439 return isOperationLegalOrCustomOrPromote(Opc, ScalarVT); 1440 } 1441 1442 bool RISCVTargetLowering::isOffsetFoldingLegal( 1443 const GlobalAddressSDNode *GA) const { 1444 // In order to maximise the opportunity for common subexpression elimination, 1445 // keep a separate ADD node for the global address offset instead of folding 1446 // it in the global address node. Later peephole optimisations may choose to 1447 // fold it back in when profitable. 1448 return false; 1449 } 1450 1451 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1452 bool ForCodeSize) const { 1453 if (VT == MVT::f16 && !Subtarget.hasStdExtZfhOrZfhmin()) 1454 return false; 1455 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1456 return false; 1457 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1458 return false; 1459 return Imm.isZero(); 1460 } 1461 1462 // TODO: This is very conservative. 1463 bool RISCVTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 1464 unsigned Index) const { 1465 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 1466 return false; 1467 1468 // Only support extracting a fixed from a fixed vector for now. 1469 if (ResVT.isScalableVector() || SrcVT.isScalableVector()) 1470 return false; 1471 1472 unsigned ResElts = ResVT.getVectorNumElements(); 1473 unsigned SrcElts = SrcVT.getVectorNumElements(); 1474 1475 // Convervatively only handle extracting half of a vector. 1476 // TODO: Relax this. 1477 if ((ResElts * 2) != SrcElts) 1478 return false; 1479 1480 // The smallest type we can slide is i8. 1481 // TODO: We can extract index 0 from a mask vector without a slide. 1482 if (ResVT.getVectorElementType() == MVT::i1) 1483 return false; 1484 1485 // Slide can support arbitrary index, but we only treat vslidedown.vi as 1486 // cheap. 1487 if (Index >= 32) 1488 return false; 1489 1490 // TODO: We can do arbitrary slidedowns, but for now only support extracting 1491 // the upper half of a vector until we have more test coverage. 1492 return Index == 0 || Index == ResElts; 1493 } 1494 1495 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1496 return (VT == MVT::f16 && Subtarget.hasStdExtZfhOrZfhmin()) || 1497 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1498 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1499 } 1500 1501 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1502 CallingConv::ID CC, 1503 EVT VT) const { 1504 // Use f32 to pass f16 if it is legal and Zfh/Zfhmin is not enabled. 1505 // We might still end up using a GPR but that will be decided based on ABI. 1506 if (VT == MVT::f16 && Subtarget.hasStdExtF() && 1507 !Subtarget.hasStdExtZfhOrZfhmin()) 1508 return MVT::f32; 1509 1510 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1511 } 1512 1513 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1514 CallingConv::ID CC, 1515 EVT VT) const { 1516 // Use f32 to pass f16 if it is legal and Zfh/Zfhmin is not enabled. 1517 // We might still end up using a GPR but that will be decided based on ABI. 1518 if (VT == MVT::f16 && Subtarget.hasStdExtF() && 1519 !Subtarget.hasStdExtZfhOrZfhmin()) 1520 return 1; 1521 1522 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1523 } 1524 1525 // Changes the condition code and swaps operands if necessary, so the SetCC 1526 // operation matches one of the comparisons supported directly by branches 1527 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1528 // with 1/-1. 1529 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1530 ISD::CondCode &CC, SelectionDAG &DAG) { 1531 // If this is a single bit test that can't be handled by ANDI, shift the 1532 // bit to be tested to the MSB and perform a signed compare with 0. 1533 if (isIntEqualitySetCC(CC) && isNullConstant(RHS) && 1534 LHS.getOpcode() == ISD::AND && LHS.hasOneUse() && 1535 isa<ConstantSDNode>(LHS.getOperand(1))) { 1536 uint64_t Mask = LHS.getConstantOperandVal(1); 1537 if ((isPowerOf2_64(Mask) || isMask_64(Mask)) && !isInt<12>(Mask)) { 1538 unsigned ShAmt = 0; 1539 if (isPowerOf2_64(Mask)) { 1540 CC = CC == ISD::SETEQ ? ISD::SETGE : ISD::SETLT; 1541 ShAmt = LHS.getValueSizeInBits() - 1 - Log2_64(Mask); 1542 } else { 1543 ShAmt = LHS.getValueSizeInBits() - llvm::bit_width(Mask); 1544 } 1545 1546 LHS = LHS.getOperand(0); 1547 if (ShAmt != 0) 1548 LHS = DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS, 1549 DAG.getConstant(ShAmt, DL, LHS.getValueType())); 1550 return; 1551 } 1552 } 1553 1554 if (auto *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 1555 int64_t C = RHSC->getSExtValue(); 1556 switch (CC) { 1557 default: break; 1558 case ISD::SETGT: 1559 // Convert X > -1 to X >= 0. 1560 if (C == -1) { 1561 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1562 CC = ISD::SETGE; 1563 return; 1564 } 1565 break; 1566 case ISD::SETLT: 1567 // Convert X < 1 to 0 <= X. 1568 if (C == 1) { 1569 RHS = LHS; 1570 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1571 CC = ISD::SETGE; 1572 return; 1573 } 1574 break; 1575 } 1576 } 1577 1578 switch (CC) { 1579 default: 1580 break; 1581 case ISD::SETGT: 1582 case ISD::SETLE: 1583 case ISD::SETUGT: 1584 case ISD::SETULE: 1585 CC = ISD::getSetCCSwappedOperands(CC); 1586 std::swap(LHS, RHS); 1587 break; 1588 } 1589 } 1590 1591 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1592 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1593 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1594 if (VT.getVectorElementType() == MVT::i1) 1595 KnownSize *= 8; 1596 1597 switch (KnownSize) { 1598 default: 1599 llvm_unreachable("Invalid LMUL."); 1600 case 8: 1601 return RISCVII::VLMUL::LMUL_F8; 1602 case 16: 1603 return RISCVII::VLMUL::LMUL_F4; 1604 case 32: 1605 return RISCVII::VLMUL::LMUL_F2; 1606 case 64: 1607 return RISCVII::VLMUL::LMUL_1; 1608 case 128: 1609 return RISCVII::VLMUL::LMUL_2; 1610 case 256: 1611 return RISCVII::VLMUL::LMUL_4; 1612 case 512: 1613 return RISCVII::VLMUL::LMUL_8; 1614 } 1615 } 1616 1617 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1618 switch (LMul) { 1619 default: 1620 llvm_unreachable("Invalid LMUL."); 1621 case RISCVII::VLMUL::LMUL_F8: 1622 case RISCVII::VLMUL::LMUL_F4: 1623 case RISCVII::VLMUL::LMUL_F2: 1624 case RISCVII::VLMUL::LMUL_1: 1625 return RISCV::VRRegClassID; 1626 case RISCVII::VLMUL::LMUL_2: 1627 return RISCV::VRM2RegClassID; 1628 case RISCVII::VLMUL::LMUL_4: 1629 return RISCV::VRM4RegClassID; 1630 case RISCVII::VLMUL::LMUL_8: 1631 return RISCV::VRM8RegClassID; 1632 } 1633 } 1634 1635 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1636 RISCVII::VLMUL LMUL = getLMUL(VT); 1637 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1638 LMUL == RISCVII::VLMUL::LMUL_F4 || 1639 LMUL == RISCVII::VLMUL::LMUL_F2 || 1640 LMUL == RISCVII::VLMUL::LMUL_1) { 1641 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1642 "Unexpected subreg numbering"); 1643 return RISCV::sub_vrm1_0 + Index; 1644 } 1645 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1646 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1647 "Unexpected subreg numbering"); 1648 return RISCV::sub_vrm2_0 + Index; 1649 } 1650 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1651 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1652 "Unexpected subreg numbering"); 1653 return RISCV::sub_vrm4_0 + Index; 1654 } 1655 llvm_unreachable("Invalid vector type."); 1656 } 1657 1658 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1659 if (VT.getVectorElementType() == MVT::i1) 1660 return RISCV::VRRegClassID; 1661 return getRegClassIDForLMUL(getLMUL(VT)); 1662 } 1663 1664 // Attempt to decompose a subvector insert/extract between VecVT and 1665 // SubVecVT via subregister indices. Returns the subregister index that 1666 // can perform the subvector insert/extract with the given element index, as 1667 // well as the index corresponding to any leftover subvectors that must be 1668 // further inserted/extracted within the register class for SubVecVT. 1669 std::pair<unsigned, unsigned> 1670 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1671 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1672 const RISCVRegisterInfo *TRI) { 1673 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1674 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1675 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1676 "Register classes not ordered"); 1677 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1678 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1679 // Try to compose a subregister index that takes us from the incoming 1680 // LMUL>1 register class down to the outgoing one. At each step we half 1681 // the LMUL: 1682 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1683 // Note that this is not guaranteed to find a subregister index, such as 1684 // when we are extracting from one VR type to another. 1685 unsigned SubRegIdx = RISCV::NoSubRegister; 1686 for (const unsigned RCID : 1687 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1688 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1689 VecVT = VecVT.getHalfNumVectorElementsVT(); 1690 bool IsHi = 1691 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1692 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1693 getSubregIndexByMVT(VecVT, IsHi)); 1694 if (IsHi) 1695 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1696 } 1697 return {SubRegIdx, InsertExtractIdx}; 1698 } 1699 1700 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1701 // stores for those types. 1702 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1703 return !Subtarget.useRVVForFixedLengthVectors() || 1704 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1705 } 1706 1707 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1708 if (ScalarTy->isPointerTy()) 1709 return true; 1710 1711 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1712 ScalarTy->isIntegerTy(32)) 1713 return true; 1714 1715 if (ScalarTy->isIntegerTy(64)) 1716 return Subtarget.hasVInstructionsI64(); 1717 1718 if (ScalarTy->isHalfTy()) 1719 return Subtarget.hasVInstructionsF16(); 1720 if (ScalarTy->isFloatTy()) 1721 return Subtarget.hasVInstructionsF32(); 1722 if (ScalarTy->isDoubleTy()) 1723 return Subtarget.hasVInstructionsF64(); 1724 1725 return false; 1726 } 1727 1728 unsigned RISCVTargetLowering::combineRepeatedFPDivisors() const { 1729 return NumRepeatedDivisors; 1730 } 1731 1732 static SDValue getVLOperand(SDValue Op) { 1733 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1734 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1735 "Unexpected opcode"); 1736 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1737 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1738 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1739 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1740 if (!II) 1741 return SDValue(); 1742 return Op.getOperand(II->VLOperand + 1 + HasChain); 1743 } 1744 1745 static bool useRVVForFixedLengthVectorVT(MVT VT, 1746 const RISCVSubtarget &Subtarget) { 1747 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1748 if (!Subtarget.useRVVForFixedLengthVectors()) 1749 return false; 1750 1751 // We only support a set of vector types with a consistent maximum fixed size 1752 // across all supported vector element types to avoid legalization issues. 1753 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1754 // fixed-length vector type we support is 1024 bytes. 1755 if (VT.getFixedSizeInBits() > 1024 * 8) 1756 return false; 1757 1758 unsigned MinVLen = Subtarget.getRealMinVLen(); 1759 1760 MVT EltVT = VT.getVectorElementType(); 1761 1762 // Don't use RVV for vectors we cannot scalarize if required. 1763 switch (EltVT.SimpleTy) { 1764 // i1 is supported but has different rules. 1765 default: 1766 return false; 1767 case MVT::i1: 1768 // Masks can only use a single register. 1769 if (VT.getVectorNumElements() > MinVLen) 1770 return false; 1771 MinVLen /= 8; 1772 break; 1773 case MVT::i8: 1774 case MVT::i16: 1775 case MVT::i32: 1776 break; 1777 case MVT::i64: 1778 if (!Subtarget.hasVInstructionsI64()) 1779 return false; 1780 break; 1781 case MVT::f16: 1782 if (!Subtarget.hasVInstructionsF16()) 1783 return false; 1784 break; 1785 case MVT::f32: 1786 if (!Subtarget.hasVInstructionsF32()) 1787 return false; 1788 break; 1789 case MVT::f64: 1790 if (!Subtarget.hasVInstructionsF64()) 1791 return false; 1792 break; 1793 } 1794 1795 // Reject elements larger than ELEN. 1796 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1797 return false; 1798 1799 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1800 // Don't use RVV for types that don't fit. 1801 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1802 return false; 1803 1804 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1805 // the base fixed length RVV support in place. 1806 if (!VT.isPow2VectorType()) 1807 return false; 1808 1809 return true; 1810 } 1811 1812 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1813 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1814 } 1815 1816 // Return the largest legal scalable vector type that matches VT's element type. 1817 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1818 const RISCVSubtarget &Subtarget) { 1819 // This may be called before legal types are setup. 1820 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1821 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1822 "Expected legal fixed length vector!"); 1823 1824 unsigned MinVLen = Subtarget.getRealMinVLen(); 1825 unsigned MaxELen = Subtarget.getELEN(); 1826 1827 MVT EltVT = VT.getVectorElementType(); 1828 switch (EltVT.SimpleTy) { 1829 default: 1830 llvm_unreachable("unexpected element type for RVV container"); 1831 case MVT::i1: 1832 case MVT::i8: 1833 case MVT::i16: 1834 case MVT::i32: 1835 case MVT::i64: 1836 case MVT::f16: 1837 case MVT::f32: 1838 case MVT::f64: { 1839 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1840 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1841 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1842 unsigned NumElts = 1843 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1844 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1845 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1846 return MVT::getScalableVectorVT(EltVT, NumElts); 1847 } 1848 } 1849 } 1850 1851 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1852 const RISCVSubtarget &Subtarget) { 1853 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1854 Subtarget); 1855 } 1856 1857 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1858 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1859 } 1860 1861 // Grow V to consume an entire RVV register. 1862 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1863 const RISCVSubtarget &Subtarget) { 1864 assert(VT.isScalableVector() && 1865 "Expected to convert into a scalable vector!"); 1866 assert(V.getValueType().isFixedLengthVector() && 1867 "Expected a fixed length vector operand!"); 1868 SDLoc DL(V); 1869 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1870 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1871 } 1872 1873 // Shrink V so it's just big enough to maintain a VT's worth of data. 1874 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1875 const RISCVSubtarget &Subtarget) { 1876 assert(VT.isFixedLengthVector() && 1877 "Expected to convert into a fixed length vector!"); 1878 assert(V.getValueType().isScalableVector() && 1879 "Expected a scalable vector operand!"); 1880 SDLoc DL(V); 1881 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1882 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1883 } 1884 1885 /// Return the type of the mask type suitable for masking the provided 1886 /// vector type. This is simply an i1 element type vector of the same 1887 /// (possibly scalable) length. 1888 static MVT getMaskTypeFor(MVT VecVT) { 1889 assert(VecVT.isVector()); 1890 ElementCount EC = VecVT.getVectorElementCount(); 1891 return MVT::getVectorVT(MVT::i1, EC); 1892 } 1893 1894 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1895 /// vector length VL. . 1896 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1897 SelectionDAG &DAG) { 1898 MVT MaskVT = getMaskTypeFor(VecVT); 1899 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1900 } 1901 1902 static SDValue getVLOp(uint64_t NumElts, SDLoc DL, SelectionDAG &DAG, 1903 const RISCVSubtarget &Subtarget) { 1904 return DAG.getConstant(NumElts, DL, Subtarget.getXLenVT()); 1905 } 1906 1907 static std::pair<SDValue, SDValue> 1908 getDefaultVLOps(uint64_t NumElts, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1909 const RISCVSubtarget &Subtarget) { 1910 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1911 SDValue VL = getVLOp(NumElts, DL, DAG, Subtarget); 1912 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1913 return {Mask, VL}; 1914 } 1915 1916 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1917 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1918 // the vector type that the fixed-length vector is contained in. Otherwise if 1919 // VecVT is scalable, then ContainerVT should be the same as VecVT. 1920 static std::pair<SDValue, SDValue> 1921 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1922 const RISCVSubtarget &Subtarget) { 1923 if (VecVT.isFixedLengthVector()) 1924 return getDefaultVLOps(VecVT.getVectorNumElements(), ContainerVT, DL, DAG, 1925 Subtarget); 1926 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1927 MVT XLenVT = Subtarget.getXLenVT(); 1928 SDValue VL = DAG.getRegister(RISCV::X0, XLenVT); 1929 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1930 return {Mask, VL}; 1931 } 1932 1933 // As above but assuming the given type is a scalable vector type. 1934 static std::pair<SDValue, SDValue> 1935 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1936 const RISCVSubtarget &Subtarget) { 1937 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1938 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1939 } 1940 1941 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1942 // of either is (currently) supported. This can get us into an infinite loop 1943 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1944 // as a ..., etc. 1945 // Until either (or both) of these can reliably lower any node, reporting that 1946 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1947 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1948 // which is not desirable. 1949 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1950 EVT VT, unsigned DefinedValues) const { 1951 return false; 1952 } 1953 1954 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1955 const RISCVSubtarget &Subtarget) { 1956 // RISCV FP-to-int conversions saturate to the destination register size, but 1957 // don't produce 0 for nan. We can use a conversion instruction and fix the 1958 // nan case with a compare and a select. 1959 SDValue Src = Op.getOperand(0); 1960 1961 MVT DstVT = Op.getSimpleValueType(); 1962 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1963 1964 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1965 1966 if (!DstVT.isVector()) { 1967 // In absense of Zfh, promote f16 to f32, then saturate the result. 1968 if (Src.getSimpleValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) { 1969 Src = DAG.getNode(ISD::FP_EXTEND, SDLoc(Op), MVT::f32, Src); 1970 } 1971 1972 unsigned Opc; 1973 if (SatVT == DstVT) 1974 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1975 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1976 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1977 else 1978 return SDValue(); 1979 // FIXME: Support other SatVTs by clamping before or after the conversion. 1980 1981 SDLoc DL(Op); 1982 SDValue FpToInt = DAG.getNode( 1983 Opc, DL, DstVT, Src, 1984 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1985 1986 if (Opc == RISCVISD::FCVT_WU_RV64) 1987 FpToInt = DAG.getZeroExtendInReg(FpToInt, DL, MVT::i32); 1988 1989 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1990 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, 1991 ISD::CondCode::SETUO); 1992 } 1993 1994 // Vectors. 1995 1996 MVT DstEltVT = DstVT.getVectorElementType(); 1997 MVT SrcVT = Src.getSimpleValueType(); 1998 MVT SrcEltVT = SrcVT.getVectorElementType(); 1999 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 2000 unsigned DstEltSize = DstEltVT.getSizeInBits(); 2001 2002 // Only handle saturating to the destination type. 2003 if (SatVT != DstEltVT) 2004 return SDValue(); 2005 2006 // FIXME: Don't support narrowing by more than 1 steps for now. 2007 if (SrcEltSize > (2 * DstEltSize)) 2008 return SDValue(); 2009 2010 MVT DstContainerVT = DstVT; 2011 MVT SrcContainerVT = SrcVT; 2012 if (DstVT.isFixedLengthVector()) { 2013 DstContainerVT = getContainerForFixedLengthVector(DAG, DstVT, Subtarget); 2014 SrcContainerVT = getContainerForFixedLengthVector(DAG, SrcVT, Subtarget); 2015 assert(DstContainerVT.getVectorElementCount() == 2016 SrcContainerVT.getVectorElementCount() && 2017 "Expected same element count"); 2018 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2019 } 2020 2021 SDLoc DL(Op); 2022 2023 auto [Mask, VL] = getDefaultVLOps(DstVT, DstContainerVT, DL, DAG, Subtarget); 2024 2025 SDValue IsNan = DAG.getNode(RISCVISD::SETCC_VL, DL, Mask.getValueType(), 2026 {Src, Src, DAG.getCondCode(ISD::SETNE), 2027 DAG.getUNDEF(Mask.getValueType()), Mask, VL}); 2028 2029 // Need to widen by more than 1 step, promote the FP type, then do a widening 2030 // convert. 2031 if (DstEltSize > (2 * SrcEltSize)) { 2032 assert(SrcContainerVT.getVectorElementType() == MVT::f16 && "Unexpected VT!"); 2033 MVT InterVT = SrcContainerVT.changeVectorElementType(MVT::f32); 2034 Src = DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterVT, Src, Mask, VL); 2035 } 2036 2037 unsigned RVVOpc = 2038 IsSigned ? RISCVISD::VFCVT_RTZ_X_F_VL : RISCVISD::VFCVT_RTZ_XU_F_VL; 2039 SDValue Res = DAG.getNode(RVVOpc, DL, DstContainerVT, Src, Mask, VL); 2040 2041 SDValue SplatZero = DAG.getNode( 2042 RISCVISD::VMV_V_X_VL, DL, DstContainerVT, DAG.getUNDEF(DstContainerVT), 2043 DAG.getConstant(0, DL, Subtarget.getXLenVT()), VL); 2044 Res = DAG.getNode(RISCVISD::VSELECT_VL, DL, DstContainerVT, IsNan, SplatZero, 2045 Res, VL); 2046 2047 if (DstVT.isFixedLengthVector()) 2048 Res = convertFromScalableVector(DstVT, Res, DAG, Subtarget); 2049 2050 return Res; 2051 } 2052 2053 static RISCVFPRndMode::RoundingMode matchRoundingOp(unsigned Opc) { 2054 switch (Opc) { 2055 case ISD::FROUNDEVEN: 2056 case ISD::VP_FROUNDEVEN: 2057 return RISCVFPRndMode::RNE; 2058 case ISD::FTRUNC: 2059 case ISD::VP_FROUNDTOZERO: 2060 return RISCVFPRndMode::RTZ; 2061 case ISD::FFLOOR: 2062 case ISD::VP_FFLOOR: 2063 return RISCVFPRndMode::RDN; 2064 case ISD::FCEIL: 2065 case ISD::VP_FCEIL: 2066 return RISCVFPRndMode::RUP; 2067 case ISD::FROUND: 2068 case ISD::VP_FROUND: 2069 return RISCVFPRndMode::RMM; 2070 case ISD::FRINT: 2071 return RISCVFPRndMode::DYN; 2072 } 2073 2074 return RISCVFPRndMode::Invalid; 2075 } 2076 2077 // Expand vector FTRUNC, FCEIL, FFLOOR, FROUND, VP_FCEIL, VP_FFLOOR, VP_FROUND 2078 // VP_FROUNDEVEN, VP_FROUNDTOZERO, VP_FRINT and VP_FNEARBYINT by converting to 2079 // the integer domain and back. Taking care to avoid converting values that are 2080 // nan or already correct. 2081 static SDValue 2082 lowerVectorFTRUNC_FCEIL_FFLOOR_FROUND(SDValue Op, SelectionDAG &DAG, 2083 const RISCVSubtarget &Subtarget) { 2084 MVT VT = Op.getSimpleValueType(); 2085 assert(VT.isVector() && "Unexpected type"); 2086 2087 SDLoc DL(Op); 2088 2089 SDValue Src = Op.getOperand(0); 2090 2091 MVT ContainerVT = VT; 2092 if (VT.isFixedLengthVector()) { 2093 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2094 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 2095 } 2096 2097 SDValue Mask, VL; 2098 if (Op->isVPOpcode()) { 2099 Mask = Op.getOperand(1); 2100 VL = Op.getOperand(2); 2101 } else { 2102 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2103 } 2104 2105 // Freeze the source since we are increasing the number of uses. 2106 Src = DAG.getFreeze(Src); 2107 2108 // We do the conversion on the absolute value and fix the sign at the end. 2109 SDValue Abs = DAG.getNode(RISCVISD::FABS_VL, DL, ContainerVT, Src, Mask, VL); 2110 2111 // Determine the largest integer that can be represented exactly. This and 2112 // values larger than it don't have any fractional bits so don't need to 2113 // be converted. 2114 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(ContainerVT); 2115 unsigned Precision = APFloat::semanticsPrecision(FltSem); 2116 APFloat MaxVal = APFloat(FltSem); 2117 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 2118 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 2119 SDValue MaxValNode = 2120 DAG.getConstantFP(MaxVal, DL, ContainerVT.getVectorElementType()); 2121 SDValue MaxValSplat = DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, ContainerVT, 2122 DAG.getUNDEF(ContainerVT), MaxValNode, VL); 2123 2124 // If abs(Src) was larger than MaxVal or nan, keep it. 2125 MVT SetccVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 2126 Mask = 2127 DAG.getNode(RISCVISD::SETCC_VL, DL, SetccVT, 2128 {Abs, MaxValSplat, DAG.getCondCode(ISD::SETOLT), 2129 Mask, Mask, VL}); 2130 2131 // Truncate to integer and convert back to FP. 2132 MVT IntVT = ContainerVT.changeVectorElementTypeToInteger(); 2133 MVT XLenVT = Subtarget.getXLenVT(); 2134 SDValue Truncated; 2135 2136 switch (Op.getOpcode()) { 2137 default: 2138 llvm_unreachable("Unexpected opcode"); 2139 case ISD::FCEIL: 2140 case ISD::VP_FCEIL: 2141 case ISD::FFLOOR: 2142 case ISD::VP_FFLOOR: 2143 case ISD::FROUND: 2144 case ISD::FROUNDEVEN: 2145 case ISD::VP_FROUND: 2146 case ISD::VP_FROUNDEVEN: 2147 case ISD::VP_FROUNDTOZERO: { 2148 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Op.getOpcode()); 2149 assert(FRM != RISCVFPRndMode::Invalid); 2150 Truncated = DAG.getNode(RISCVISD::VFCVT_RM_X_F_VL, DL, IntVT, Src, Mask, 2151 DAG.getTargetConstant(FRM, DL, XLenVT), VL); 2152 break; 2153 } 2154 case ISD::FTRUNC: 2155 Truncated = DAG.getNode(RISCVISD::VFCVT_RTZ_X_F_VL, DL, IntVT, Src, 2156 Mask, VL); 2157 break; 2158 case ISD::VP_FRINT: 2159 Truncated = DAG.getNode(RISCVISD::VFCVT_X_F_VL, DL, IntVT, Src, Mask, VL); 2160 break; 2161 case ISD::VP_FNEARBYINT: 2162 Truncated = DAG.getNode(RISCVISD::VFROUND_NOEXCEPT_VL, DL, ContainerVT, Src, 2163 Mask, VL); 2164 break; 2165 } 2166 2167 // VFROUND_NOEXCEPT_VL includes SINT_TO_FP_VL. 2168 if (Op.getOpcode() != ISD::VP_FNEARBYINT) 2169 Truncated = DAG.getNode(RISCVISD::SINT_TO_FP_VL, DL, ContainerVT, Truncated, 2170 Mask, VL); 2171 2172 // Restore the original sign so that -0.0 is preserved. 2173 Truncated = DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Truncated, 2174 Src, Src, Mask, VL); 2175 2176 if (!VT.isFixedLengthVector()) 2177 return Truncated; 2178 2179 return convertFromScalableVector(VT, Truncated, DAG, Subtarget); 2180 } 2181 2182 static SDValue 2183 lowerFTRUNC_FCEIL_FFLOOR_FROUND(SDValue Op, SelectionDAG &DAG, 2184 const RISCVSubtarget &Subtarget) { 2185 MVT VT = Op.getSimpleValueType(); 2186 if (VT.isVector()) 2187 return lowerVectorFTRUNC_FCEIL_FFLOOR_FROUND(Op, DAG, Subtarget); 2188 2189 if (DAG.shouldOptForSize()) 2190 return SDValue(); 2191 2192 SDLoc DL(Op); 2193 SDValue Src = Op.getOperand(0); 2194 2195 // Create an integer the size of the mantissa with the MSB set. This and all 2196 // values larger than it don't have any fractional bits so don't need to be 2197 // converted. 2198 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 2199 unsigned Precision = APFloat::semanticsPrecision(FltSem); 2200 APFloat MaxVal = APFloat(FltSem); 2201 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 2202 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 2203 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 2204 2205 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Op.getOpcode()); 2206 return DAG.getNode(RISCVISD::FROUND, DL, VT, Src, MaxValNode, 2207 DAG.getTargetConstant(FRM, DL, Subtarget.getXLenVT())); 2208 } 2209 2210 struct VIDSequence { 2211 int64_t StepNumerator; 2212 unsigned StepDenominator; 2213 int64_t Addend; 2214 }; 2215 2216 static std::optional<uint64_t> getExactInteger(const APFloat &APF, 2217 uint32_t BitWidth) { 2218 APSInt ValInt(BitWidth, !APF.isNegative()); 2219 // We use an arbitrary rounding mode here. If a floating-point is an exact 2220 // integer (e.g., 1.0), the rounding mode does not affect the output value. If 2221 // the rounding mode changes the output value, then it is not an exact 2222 // integer. 2223 RoundingMode ArbitraryRM = RoundingMode::TowardZero; 2224 bool IsExact; 2225 // If it is out of signed integer range, it will return an invalid operation. 2226 // If it is not an exact integer, IsExact is false. 2227 if ((APF.convertToInteger(ValInt, ArbitraryRM, &IsExact) == 2228 APFloatBase::opInvalidOp) || 2229 !IsExact) 2230 return std::nullopt; 2231 return ValInt.extractBitsAsZExtValue(BitWidth, 0); 2232 } 2233 2234 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 2235 // to the (non-zero) step S and start value X. This can be then lowered as the 2236 // RVV sequence (VID * S) + X, for example. 2237 // The step S is represented as an integer numerator divided by a positive 2238 // denominator. Note that the implementation currently only identifies 2239 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 2240 // cannot detect 2/3, for example. 2241 // Note that this method will also match potentially unappealing index 2242 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 2243 // determine whether this is worth generating code for. 2244 static std::optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 2245 unsigned NumElts = Op.getNumOperands(); 2246 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 2247 bool IsInteger = Op.getValueType().isInteger(); 2248 2249 std::optional<unsigned> SeqStepDenom; 2250 std::optional<int64_t> SeqStepNum, SeqAddend; 2251 std::optional<std::pair<uint64_t, unsigned>> PrevElt; 2252 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 2253 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 2254 // Assume undef elements match the sequence; we just have to be careful 2255 // when interpolating across them. 2256 if (Op.getOperand(Idx).isUndef()) 2257 continue; 2258 2259 uint64_t Val; 2260 if (IsInteger) { 2261 // The BUILD_VECTOR must be all constants. 2262 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 2263 return std::nullopt; 2264 Val = Op.getConstantOperandVal(Idx) & 2265 maskTrailingOnes<uint64_t>(EltSizeInBits); 2266 } else { 2267 // The BUILD_VECTOR must be all constants. 2268 if (!isa<ConstantFPSDNode>(Op.getOperand(Idx))) 2269 return std::nullopt; 2270 if (auto ExactInteger = getExactInteger( 2271 cast<ConstantFPSDNode>(Op.getOperand(Idx))->getValueAPF(), 2272 EltSizeInBits)) 2273 Val = *ExactInteger; 2274 else 2275 return std::nullopt; 2276 } 2277 2278 if (PrevElt) { 2279 // Calculate the step since the last non-undef element, and ensure 2280 // it's consistent across the entire sequence. 2281 unsigned IdxDiff = Idx - PrevElt->second; 2282 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 2283 2284 // A zero-value value difference means that we're somewhere in the middle 2285 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 2286 // step change before evaluating the sequence. 2287 if (ValDiff == 0) 2288 continue; 2289 2290 int64_t Remainder = ValDiff % IdxDiff; 2291 // Normalize the step if it's greater than 1. 2292 if (Remainder != ValDiff) { 2293 // The difference must cleanly divide the element span. 2294 if (Remainder != 0) 2295 return std::nullopt; 2296 ValDiff /= IdxDiff; 2297 IdxDiff = 1; 2298 } 2299 2300 if (!SeqStepNum) 2301 SeqStepNum = ValDiff; 2302 else if (ValDiff != SeqStepNum) 2303 return std::nullopt; 2304 2305 if (!SeqStepDenom) 2306 SeqStepDenom = IdxDiff; 2307 else if (IdxDiff != *SeqStepDenom) 2308 return std::nullopt; 2309 } 2310 2311 // Record this non-undef element for later. 2312 if (!PrevElt || PrevElt->first != Val) 2313 PrevElt = std::make_pair(Val, Idx); 2314 } 2315 2316 // We need to have logged a step for this to count as a legal index sequence. 2317 if (!SeqStepNum || !SeqStepDenom) 2318 return std::nullopt; 2319 2320 // Loop back through the sequence and validate elements we might have skipped 2321 // while waiting for a valid step. While doing this, log any sequence addend. 2322 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 2323 if (Op.getOperand(Idx).isUndef()) 2324 continue; 2325 uint64_t Val; 2326 if (IsInteger) { 2327 Val = Op.getConstantOperandVal(Idx) & 2328 maskTrailingOnes<uint64_t>(EltSizeInBits); 2329 } else { 2330 Val = *getExactInteger( 2331 cast<ConstantFPSDNode>(Op.getOperand(Idx))->getValueAPF(), 2332 EltSizeInBits); 2333 } 2334 uint64_t ExpectedVal = 2335 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 2336 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 2337 if (!SeqAddend) 2338 SeqAddend = Addend; 2339 else if (Addend != SeqAddend) 2340 return std::nullopt; 2341 } 2342 2343 assert(SeqAddend && "Must have an addend if we have a step"); 2344 2345 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 2346 } 2347 2348 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 2349 // and lower it as a VRGATHER_VX_VL from the source vector. 2350 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 2351 SelectionDAG &DAG, 2352 const RISCVSubtarget &Subtarget) { 2353 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 2354 return SDValue(); 2355 SDValue Vec = SplatVal.getOperand(0); 2356 // Only perform this optimization on vectors of the same size for simplicity. 2357 // Don't perform this optimization for i1 vectors. 2358 // FIXME: Support i1 vectors, maybe by promoting to i8? 2359 if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1) 2360 return SDValue(); 2361 SDValue Idx = SplatVal.getOperand(1); 2362 // The index must be a legal type. 2363 if (Idx.getValueType() != Subtarget.getXLenVT()) 2364 return SDValue(); 2365 2366 MVT ContainerVT = VT; 2367 if (VT.isFixedLengthVector()) { 2368 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2369 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2370 } 2371 2372 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2373 2374 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2375 Idx, DAG.getUNDEF(ContainerVT), Mask, VL); 2376 2377 if (!VT.isFixedLengthVector()) 2378 return Gather; 2379 2380 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2381 } 2382 2383 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2384 const RISCVSubtarget &Subtarget) { 2385 MVT VT = Op.getSimpleValueType(); 2386 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2387 2388 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2389 2390 SDLoc DL(Op); 2391 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2392 2393 MVT XLenVT = Subtarget.getXLenVT(); 2394 unsigned NumElts = Op.getNumOperands(); 2395 2396 if (VT.getVectorElementType() == MVT::i1) { 2397 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2398 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2399 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2400 } 2401 2402 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2403 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2404 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2405 } 2406 2407 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2408 // scalar integer chunks whose bit-width depends on the number of mask 2409 // bits and XLEN. 2410 // First, determine the most appropriate scalar integer type to use. This 2411 // is at most XLenVT, but may be shrunk to a smaller vector element type 2412 // according to the size of the final vector - use i8 chunks rather than 2413 // XLenVT if we're producing a v8i1. This results in more consistent 2414 // codegen across RV32 and RV64. 2415 unsigned NumViaIntegerBits = 2416 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2417 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 2418 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2419 // If we have to use more than one INSERT_VECTOR_ELT then this 2420 // optimization is likely to increase code size; avoid peforming it in 2421 // such a case. We can use a load from a constant pool in this case. 2422 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2423 return SDValue(); 2424 // Now we can create our integer vector type. Note that it may be larger 2425 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2426 MVT IntegerViaVecVT = 2427 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2428 divideCeil(NumElts, NumViaIntegerBits)); 2429 2430 uint64_t Bits = 0; 2431 unsigned BitPos = 0, IntegerEltIdx = 0; 2432 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2433 2434 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2435 // Once we accumulate enough bits to fill our scalar type, insert into 2436 // our vector and clear our accumulated data. 2437 if (I != 0 && I % NumViaIntegerBits == 0) { 2438 if (NumViaIntegerBits <= 32) 2439 Bits = SignExtend64<32>(Bits); 2440 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2441 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2442 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2443 Bits = 0; 2444 BitPos = 0; 2445 IntegerEltIdx++; 2446 } 2447 SDValue V = Op.getOperand(I); 2448 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2449 Bits |= ((uint64_t)BitValue << BitPos); 2450 } 2451 2452 // Insert the (remaining) scalar value into position in our integer 2453 // vector type. 2454 if (NumViaIntegerBits <= 32) 2455 Bits = SignExtend64<32>(Bits); 2456 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2457 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2458 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2459 2460 if (NumElts < NumViaIntegerBits) { 2461 // If we're producing a smaller vector than our minimum legal integer 2462 // type, bitcast to the equivalent (known-legal) mask type, and extract 2463 // our final mask. 2464 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2465 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2466 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2467 DAG.getConstant(0, DL, XLenVT)); 2468 } else { 2469 // Else we must have produced an integer type with the same size as the 2470 // mask type; bitcast for the final result. 2471 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2472 Vec = DAG.getBitcast(VT, Vec); 2473 } 2474 2475 return Vec; 2476 } 2477 2478 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2479 // vector type, we have a legal equivalently-sized i8 type, so we can use 2480 // that. 2481 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2482 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2483 2484 SDValue WideVec; 2485 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2486 // For a splat, perform a scalar truncate before creating the wider 2487 // vector. 2488 assert(Splat.getValueType() == XLenVT && 2489 "Unexpected type for i1 splat value"); 2490 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2491 DAG.getConstant(1, DL, XLenVT)); 2492 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2493 } else { 2494 SmallVector<SDValue, 8> Ops(Op->op_values()); 2495 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2496 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2497 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2498 } 2499 2500 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2501 } 2502 2503 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2504 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2505 return Gather; 2506 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2507 : RISCVISD::VMV_V_X_VL; 2508 Splat = 2509 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2510 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2511 } 2512 2513 // Try and match index sequences, which we can lower to the vid instruction 2514 // with optional modifications. An all-undef vector is matched by 2515 // getSplatValue, above. 2516 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2517 int64_t StepNumerator = SimpleVID->StepNumerator; 2518 unsigned StepDenominator = SimpleVID->StepDenominator; 2519 int64_t Addend = SimpleVID->Addend; 2520 2521 assert(StepNumerator != 0 && "Invalid step"); 2522 bool Negate = false; 2523 int64_t SplatStepVal = StepNumerator; 2524 unsigned StepOpcode = ISD::MUL; 2525 if (StepNumerator != 1) { 2526 if (isPowerOf2_64(std::abs(StepNumerator))) { 2527 Negate = StepNumerator < 0; 2528 StepOpcode = ISD::SHL; 2529 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2530 } 2531 } 2532 2533 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2534 // threshold since it's the immediate value many RVV instructions accept. 2535 // There is no vmul.vi instruction so ensure multiply constant can fit in 2536 // a single addi instruction. 2537 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2538 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2539 isPowerOf2_32(StepDenominator) && 2540 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2541 MVT VIDVT = 2542 VT.isFloatingPoint() ? VT.changeVectorElementTypeToInteger() : VT; 2543 MVT VIDContainerVT = 2544 getContainerForFixedLengthVector(DAG, VIDVT, Subtarget); 2545 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VIDContainerVT, Mask, VL); 2546 // Convert right out of the scalable type so we can use standard ISD 2547 // nodes for the rest of the computation. If we used scalable types with 2548 // these, we'd lose the fixed-length vector info and generate worse 2549 // vsetvli code. 2550 VID = convertFromScalableVector(VIDVT, VID, DAG, Subtarget); 2551 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2552 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2553 SDValue SplatStep = DAG.getSplatBuildVector( 2554 VIDVT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2555 VID = DAG.getNode(StepOpcode, DL, VIDVT, VID, SplatStep); 2556 } 2557 if (StepDenominator != 1) { 2558 SDValue SplatStep = DAG.getSplatBuildVector( 2559 VIDVT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2560 VID = DAG.getNode(ISD::SRL, DL, VIDVT, VID, SplatStep); 2561 } 2562 if (Addend != 0 || Negate) { 2563 SDValue SplatAddend = DAG.getSplatBuildVector( 2564 VIDVT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2565 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VIDVT, SplatAddend, 2566 VID); 2567 } 2568 if (VT.isFloatingPoint()) { 2569 // TODO: Use vfwcvt to reduce register pressure. 2570 VID = DAG.getNode(ISD::SINT_TO_FP, DL, VT, VID); 2571 } 2572 return VID; 2573 } 2574 } 2575 2576 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2577 // when re-interpreted as a vector with a larger element type. For example, 2578 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2579 // could be instead splat as 2580 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2581 // TODO: This optimization could also work on non-constant splats, but it 2582 // would require bit-manipulation instructions to construct the splat value. 2583 SmallVector<SDValue> Sequence; 2584 unsigned EltBitSize = VT.getScalarSizeInBits(); 2585 const auto *BV = cast<BuildVectorSDNode>(Op); 2586 if (VT.isInteger() && EltBitSize < 64 && 2587 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2588 BV->getRepeatedSequence(Sequence) && 2589 (Sequence.size() * EltBitSize) <= 64) { 2590 unsigned SeqLen = Sequence.size(); 2591 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2592 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2593 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2594 ViaIntVT == MVT::i64) && 2595 "Unexpected sequence type"); 2596 2597 unsigned EltIdx = 0; 2598 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2599 uint64_t SplatValue = 0; 2600 // Construct the amalgamated value which can be splatted as this larger 2601 // vector type. 2602 for (const auto &SeqV : Sequence) { 2603 if (!SeqV.isUndef()) 2604 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2605 << (EltIdx * EltBitSize)); 2606 EltIdx++; 2607 } 2608 2609 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2610 // achieve better constant materializion. 2611 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2612 SplatValue = SignExtend64<32>(SplatValue); 2613 2614 // Since we can't introduce illegal i64 types at this stage, we can only 2615 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2616 // way we can use RVV instructions to splat. 2617 assert((ViaIntVT.bitsLE(XLenVT) || 2618 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2619 "Unexpected bitcast sequence"); 2620 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2621 SDValue ViaVL = 2622 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2623 MVT ViaContainerVT = 2624 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2625 SDValue Splat = 2626 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2627 DAG.getUNDEF(ViaContainerVT), 2628 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2629 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2630 return DAG.getBitcast(VT, Splat); 2631 } 2632 } 2633 2634 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2635 // which constitute a large proportion of the elements. In such cases we can 2636 // splat a vector with the dominant element and make up the shortfall with 2637 // INSERT_VECTOR_ELTs. 2638 // Note that this includes vectors of 2 elements by association. The 2639 // upper-most element is the "dominant" one, allowing us to use a splat to 2640 // "insert" the upper element, and an insert of the lower element at position 2641 // 0, which improves codegen. 2642 SDValue DominantValue; 2643 unsigned MostCommonCount = 0; 2644 DenseMap<SDValue, unsigned> ValueCounts; 2645 unsigned NumUndefElts = 2646 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2647 2648 // Track the number of scalar loads we know we'd be inserting, estimated as 2649 // any non-zero floating-point constant. Other kinds of element are either 2650 // already in registers or are materialized on demand. The threshold at which 2651 // a vector load is more desirable than several scalar materializion and 2652 // vector-insertion instructions is not known. 2653 unsigned NumScalarLoads = 0; 2654 2655 for (SDValue V : Op->op_values()) { 2656 if (V.isUndef()) 2657 continue; 2658 2659 ValueCounts.insert(std::make_pair(V, 0)); 2660 unsigned &Count = ValueCounts[V]; 2661 2662 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2663 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2664 2665 // Is this value dominant? In case of a tie, prefer the highest element as 2666 // it's cheaper to insert near the beginning of a vector than it is at the 2667 // end. 2668 if (++Count >= MostCommonCount) { 2669 DominantValue = V; 2670 MostCommonCount = Count; 2671 } 2672 } 2673 2674 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2675 unsigned NumDefElts = NumElts - NumUndefElts; 2676 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2677 2678 // Don't perform this optimization when optimizing for size, since 2679 // materializing elements and inserting them tends to cause code bloat. 2680 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2681 ((MostCommonCount > DominantValueCountThreshold) || 2682 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2683 // Start by splatting the most common element. 2684 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2685 2686 DenseSet<SDValue> Processed{DominantValue}; 2687 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2688 for (const auto &OpIdx : enumerate(Op->ops())) { 2689 const SDValue &V = OpIdx.value(); 2690 if (V.isUndef() || !Processed.insert(V).second) 2691 continue; 2692 if (ValueCounts[V] == 1) { 2693 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2694 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2695 } else { 2696 // Blend in all instances of this value using a VSELECT, using a 2697 // mask where each bit signals whether that element is the one 2698 // we're after. 2699 SmallVector<SDValue> Ops; 2700 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2701 return DAG.getConstant(V == V1, DL, XLenVT); 2702 }); 2703 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2704 DAG.getBuildVector(SelMaskTy, DL, Ops), 2705 DAG.getSplatBuildVector(VT, DL, V), Vec); 2706 } 2707 } 2708 2709 return Vec; 2710 } 2711 2712 return SDValue(); 2713 } 2714 2715 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2716 SDValue Lo, SDValue Hi, SDValue VL, 2717 SelectionDAG &DAG) { 2718 if (!Passthru) 2719 Passthru = DAG.getUNDEF(VT); 2720 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2721 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2722 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2723 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2724 // node in order to try and match RVV vector/scalar instructions. 2725 if ((LoC >> 31) == HiC) 2726 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2727 2728 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2729 // vmv.v.x whose EEW = 32 to lower it. 2730 auto *Const = dyn_cast<ConstantSDNode>(VL); 2731 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2732 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2733 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2734 // access the subtarget here now. 2735 auto InterVec = DAG.getNode( 2736 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2737 DAG.getRegister(RISCV::X0, MVT::i32)); 2738 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2739 } 2740 } 2741 2742 // Fall back to a stack store and stride x0 vector load. 2743 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2744 Hi, VL); 2745 } 2746 2747 // Called by type legalization to handle splat of i64 on RV32. 2748 // FIXME: We can optimize this when the type has sign or zero bits in one 2749 // of the halves. 2750 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2751 SDValue Scalar, SDValue VL, 2752 SelectionDAG &DAG) { 2753 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2754 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2755 DAG.getConstant(0, DL, MVT::i32)); 2756 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2757 DAG.getConstant(1, DL, MVT::i32)); 2758 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2759 } 2760 2761 // This function lowers a splat of a scalar operand Splat with the vector 2762 // length VL. It ensures the final sequence is type legal, which is useful when 2763 // lowering a splat after type legalization. 2764 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2765 MVT VT, SDLoc DL, SelectionDAG &DAG, 2766 const RISCVSubtarget &Subtarget) { 2767 bool HasPassthru = Passthru && !Passthru.isUndef(); 2768 if (!HasPassthru && !Passthru) 2769 Passthru = DAG.getUNDEF(VT); 2770 if (VT.isFloatingPoint()) { 2771 // If VL is 1, we could use vfmv.s.f. 2772 if (isOneConstant(VL)) 2773 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2774 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2775 } 2776 2777 MVT XLenVT = Subtarget.getXLenVT(); 2778 2779 // Simplest case is that the operand needs to be promoted to XLenVT. 2780 if (Scalar.getValueType().bitsLE(XLenVT)) { 2781 // If the operand is a constant, sign extend to increase our chances 2782 // of being able to use a .vi instruction. ANY_EXTEND would become a 2783 // a zero extend and the simm5 check in isel would fail. 2784 // FIXME: Should we ignore the upper bits in isel instead? 2785 unsigned ExtOpc = 2786 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2787 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2788 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2789 // If VL is 1 and the scalar value won't benefit from immediate, we could 2790 // use vmv.s.x. 2791 if (isOneConstant(VL) && 2792 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2793 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2794 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2795 } 2796 2797 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2798 "Unexpected scalar for splat lowering!"); 2799 2800 if (isOneConstant(VL) && isNullConstant(Scalar)) 2801 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2802 DAG.getConstant(0, DL, XLenVT), VL); 2803 2804 // Otherwise use the more complicated splatting algorithm. 2805 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2806 } 2807 2808 static MVT getLMUL1VT(MVT VT) { 2809 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 2810 "Unexpected vector MVT"); 2811 return MVT::getScalableVectorVT( 2812 VT.getVectorElementType(), 2813 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 2814 } 2815 2816 // This function lowers an insert of a scalar operand Scalar into lane 2817 // 0 of the vector regardless of the value of VL. The contents of the 2818 // remaining lanes of the result vector are unspecified. VL is assumed 2819 // to be non-zero. 2820 static SDValue lowerScalarInsert(SDValue Scalar, SDValue VL, 2821 MVT VT, SDLoc DL, SelectionDAG &DAG, 2822 const RISCVSubtarget &Subtarget) { 2823 const MVT XLenVT = Subtarget.getXLenVT(); 2824 2825 SDValue Passthru = DAG.getUNDEF(VT); 2826 if (VT.isFloatingPoint()) { 2827 // TODO: Use vmv.v.i for appropriate constants 2828 // Use M1 or smaller to avoid over constraining register allocation 2829 const MVT M1VT = getLMUL1VT(VT); 2830 auto InnerVT = VT.bitsLE(M1VT) ? VT : M1VT; 2831 SDValue Result = DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, InnerVT, 2832 DAG.getUNDEF(InnerVT), Scalar, VL); 2833 if (VT != InnerVT) 2834 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 2835 DAG.getUNDEF(VT), 2836 Result, DAG.getConstant(0, DL, XLenVT)); 2837 return Result; 2838 } 2839 2840 2841 // Avoid the tricky legalization cases by falling back to using the 2842 // splat code which already handles it gracefully. 2843 if (!Scalar.getValueType().bitsLE(XLenVT)) 2844 return lowerScalarSplat(DAG.getUNDEF(VT), Scalar, 2845 DAG.getConstant(1, DL, XLenVT), 2846 VT, DL, DAG, Subtarget); 2847 2848 // If the operand is a constant, sign extend to increase our chances 2849 // of being able to use a .vi instruction. ANY_EXTEND would become a 2850 // a zero extend and the simm5 check in isel would fail. 2851 // FIXME: Should we ignore the upper bits in isel instead? 2852 unsigned ExtOpc = 2853 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2854 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2855 // We use a vmv.v.i if possible. We limit this to LMUL1. LMUL2 or 2856 // higher would involve overly constraining the register allocator for 2857 // no purpose. 2858 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar)) { 2859 if (!isNullConstant(Scalar) && isInt<5>(Const->getSExtValue()) && 2860 VT.bitsLE(getLMUL1VT(VT))) 2861 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2862 } 2863 // Use M1 or smaller to avoid over constraining register allocation 2864 const MVT M1VT = getLMUL1VT(VT); 2865 auto InnerVT = VT.bitsLE(M1VT) ? VT : M1VT; 2866 SDValue Result = DAG.getNode(RISCVISD::VMV_S_X_VL, DL, InnerVT, 2867 DAG.getUNDEF(InnerVT), Scalar, VL); 2868 if (VT != InnerVT) 2869 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 2870 DAG.getUNDEF(VT), 2871 Result, DAG.getConstant(0, DL, XLenVT)); 2872 return Result; 2873 2874 } 2875 2876 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2877 const RISCVSubtarget &Subtarget) { 2878 // We need to be able to widen elements to the next larger integer type. 2879 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2880 return false; 2881 2882 int Size = Mask.size(); 2883 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2884 2885 int Srcs[] = {-1, -1}; 2886 for (int i = 0; i != Size; ++i) { 2887 // Ignore undef elements. 2888 if (Mask[i] < 0) 2889 continue; 2890 2891 // Is this an even or odd element. 2892 int Pol = i % 2; 2893 2894 // Ensure we consistently use the same source for this element polarity. 2895 int Src = Mask[i] / Size; 2896 if (Srcs[Pol] < 0) 2897 Srcs[Pol] = Src; 2898 if (Srcs[Pol] != Src) 2899 return false; 2900 2901 // Make sure the element within the source is appropriate for this element 2902 // in the destination. 2903 int Elt = Mask[i] % Size; 2904 if (Elt != i / 2) 2905 return false; 2906 } 2907 2908 // We need to find a source for each polarity and they can't be the same. 2909 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2910 return false; 2911 2912 // Swap the sources if the second source was in the even polarity. 2913 SwapSources = Srcs[0] > Srcs[1]; 2914 2915 return true; 2916 } 2917 2918 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2919 /// and then extract the original number of elements from the rotated result. 2920 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2921 /// returned rotation amount is for a rotate right, where elements move from 2922 /// higher elements to lower elements. \p LoSrc indicates the first source 2923 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2924 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2925 /// 0 or 1 if a rotation is found. 2926 /// 2927 /// NOTE: We talk about rotate to the right which matches how bit shift and 2928 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2929 /// and the table below write vectors with the lowest elements on the left. 2930 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2931 int Size = Mask.size(); 2932 2933 // We need to detect various ways of spelling a rotation: 2934 // [11, 12, 13, 14, 15, 0, 1, 2] 2935 // [-1, 12, 13, 14, -1, -1, 1, -1] 2936 // [-1, -1, -1, -1, -1, -1, 1, 2] 2937 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2938 // [-1, 4, 5, 6, -1, -1, 9, -1] 2939 // [-1, 4, 5, 6, -1, -1, -1, -1] 2940 int Rotation = 0; 2941 LoSrc = -1; 2942 HiSrc = -1; 2943 for (int i = 0; i != Size; ++i) { 2944 int M = Mask[i]; 2945 if (M < 0) 2946 continue; 2947 2948 // Determine where a rotate vector would have started. 2949 int StartIdx = i - (M % Size); 2950 // The identity rotation isn't interesting, stop. 2951 if (StartIdx == 0) 2952 return -1; 2953 2954 // If we found the tail of a vector the rotation must be the missing 2955 // front. If we found the head of a vector, it must be how much of the 2956 // head. 2957 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2958 2959 if (Rotation == 0) 2960 Rotation = CandidateRotation; 2961 else if (Rotation != CandidateRotation) 2962 // The rotations don't match, so we can't match this mask. 2963 return -1; 2964 2965 // Compute which value this mask is pointing at. 2966 int MaskSrc = M < Size ? 0 : 1; 2967 2968 // Compute which of the two target values this index should be assigned to. 2969 // This reflects whether the high elements are remaining or the low elemnts 2970 // are remaining. 2971 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2972 2973 // Either set up this value if we've not encountered it before, or check 2974 // that it remains consistent. 2975 if (TargetSrc < 0) 2976 TargetSrc = MaskSrc; 2977 else if (TargetSrc != MaskSrc) 2978 // This may be a rotation, but it pulls from the inputs in some 2979 // unsupported interleaving. 2980 return -1; 2981 } 2982 2983 // Check that we successfully analyzed the mask, and normalize the results. 2984 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2985 assert((LoSrc >= 0 || HiSrc >= 0) && 2986 "Failed to find a rotated input vector!"); 2987 2988 return Rotation; 2989 } 2990 2991 // Lower the following shuffles to vnsrl. 2992 // t34: v8i8 = extract_subvector t11, Constant:i64<0> 2993 // t33: v8i8 = extract_subvector t11, Constant:i64<8> 2994 // a) t35: v8i8 = vector_shuffle<0,2,4,6,8,10,12,14> t34, t33 2995 // b) t35: v8i8 = vector_shuffle<1,3,5,7,9,11,13,15> t34, t33 2996 static SDValue lowerVECTOR_SHUFFLEAsVNSRL(const SDLoc &DL, MVT VT, 2997 MVT ContainerVT, SDValue V1, 2998 SDValue V2, SDValue TrueMask, 2999 SDValue VL, ArrayRef<int> Mask, 3000 const RISCVSubtarget &Subtarget, 3001 SelectionDAG &DAG) { 3002 // Need to be able to widen the vector. 3003 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 3004 return SDValue(); 3005 3006 // Both input must be extracts. 3007 if (V1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 3008 V2.getOpcode() != ISD::EXTRACT_SUBVECTOR) 3009 return SDValue(); 3010 3011 // Extracting from the same source. 3012 SDValue Src = V1.getOperand(0); 3013 if (Src != V2.getOperand(0)) 3014 return SDValue(); 3015 3016 // Src needs to have twice the number of elements. 3017 if (Src.getValueType().getVectorNumElements() != (Mask.size() * 2)) 3018 return SDValue(); 3019 3020 // The extracts must extract the two halves of the source. 3021 if (V1.getConstantOperandVal(1) != 0 || 3022 V2.getConstantOperandVal(1) != Mask.size()) 3023 return SDValue(); 3024 3025 // First index must be the first even or odd element from V1. 3026 if (Mask[0] != 0 && Mask[0] != 1) 3027 return SDValue(); 3028 3029 // The others must increase by 2 each time. 3030 // TODO: Support undef elements? 3031 for (unsigned i = 1; i != Mask.size(); ++i) 3032 if (Mask[i] != Mask[i - 1] + 2) 3033 return SDValue(); 3034 3035 // Convert the source using a container type with twice the elements. Since 3036 // source VT is legal and twice this VT, we know VT isn't LMUL=8 so it is 3037 // safe to double. 3038 MVT DoubleContainerVT = 3039 MVT::getVectorVT(ContainerVT.getVectorElementType(), 3040 ContainerVT.getVectorElementCount() * 2); 3041 Src = convertToScalableVector(DoubleContainerVT, Src, DAG, Subtarget); 3042 3043 // Convert the vector to a wider integer type with the original element 3044 // count. This also converts FP to int. 3045 unsigned EltBits = ContainerVT.getScalarSizeInBits(); 3046 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 3047 MVT WideIntContainerVT = 3048 MVT::getVectorVT(WideIntEltVT, ContainerVT.getVectorElementCount()); 3049 Src = DAG.getBitcast(WideIntContainerVT, Src); 3050 3051 // Convert to the integer version of the container type. 3052 MVT IntEltVT = MVT::getIntegerVT(EltBits); 3053 MVT IntContainerVT = 3054 MVT::getVectorVT(IntEltVT, ContainerVT.getVectorElementCount()); 3055 3056 // If we want even elements, then the shift amount is 0. Otherwise, shift by 3057 // the original element size. 3058 unsigned Shift = Mask[0] == 0 ? 0 : EltBits; 3059 SDValue SplatShift = DAG.getNode( 3060 RISCVISD::VMV_V_X_VL, DL, IntContainerVT, DAG.getUNDEF(ContainerVT), 3061 DAG.getConstant(Shift, DL, Subtarget.getXLenVT()), VL); 3062 SDValue Res = 3063 DAG.getNode(RISCVISD::VNSRL_VL, DL, IntContainerVT, Src, SplatShift, 3064 DAG.getUNDEF(IntContainerVT), TrueMask, VL); 3065 // Cast back to FP if needed. 3066 Res = DAG.getBitcast(ContainerVT, Res); 3067 3068 return convertFromScalableVector(VT, Res, DAG, Subtarget); 3069 } 3070 3071 static SDValue 3072 getVSlidedown(SelectionDAG &DAG, const RISCVSubtarget &Subtarget, SDLoc DL, 3073 EVT VT, SDValue Merge, SDValue Op, SDValue Offset, SDValue Mask, 3074 SDValue VL, 3075 unsigned Policy = RISCVII::TAIL_UNDISTURBED_MASK_UNDISTURBED) { 3076 if (Merge.isUndef()) 3077 Policy = RISCVII::TAIL_AGNOSTIC | RISCVII::MASK_AGNOSTIC; 3078 SDValue PolicyOp = DAG.getTargetConstant(Policy, DL, Subtarget.getXLenVT()); 3079 SDValue Ops[] = {Merge, Op, Offset, Mask, VL, PolicyOp}; 3080 return DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VT, Ops); 3081 } 3082 3083 static SDValue 3084 getVSlideup(SelectionDAG &DAG, const RISCVSubtarget &Subtarget, SDLoc DL, 3085 EVT VT, SDValue Merge, SDValue Op, SDValue Offset, SDValue Mask, 3086 SDValue VL, 3087 unsigned Policy = RISCVII::TAIL_UNDISTURBED_MASK_UNDISTURBED) { 3088 if (Merge.isUndef()) 3089 Policy = RISCVII::TAIL_AGNOSTIC | RISCVII::MASK_AGNOSTIC; 3090 SDValue PolicyOp = DAG.getTargetConstant(Policy, DL, Subtarget.getXLenVT()); 3091 SDValue Ops[] = {Merge, Op, Offset, Mask, VL, PolicyOp}; 3092 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VT, Ops); 3093 } 3094 3095 // Lower the following shuffle to vslidedown. 3096 // a) 3097 // t49: v8i8 = extract_subvector t13, Constant:i64<0> 3098 // t109: v8i8 = extract_subvector t13, Constant:i64<8> 3099 // t108: v8i8 = vector_shuffle<1,2,3,4,5,6,7,8> t49, t106 3100 // b) 3101 // t69: v16i16 = extract_subvector t68, Constant:i64<0> 3102 // t23: v8i16 = extract_subvector t69, Constant:i64<0> 3103 // t29: v4i16 = extract_subvector t23, Constant:i64<4> 3104 // t26: v8i16 = extract_subvector t69, Constant:i64<8> 3105 // t30: v4i16 = extract_subvector t26, Constant:i64<0> 3106 // t54: v4i16 = vector_shuffle<1,2,3,4> t29, t30 3107 static SDValue lowerVECTOR_SHUFFLEAsVSlidedown(const SDLoc &DL, MVT VT, 3108 SDValue V1, SDValue V2, 3109 ArrayRef<int> Mask, 3110 const RISCVSubtarget &Subtarget, 3111 SelectionDAG &DAG) { 3112 auto findNonEXTRACT_SUBVECTORParent = 3113 [](SDValue Parent) -> std::pair<SDValue, uint64_t> { 3114 uint64_t Offset = 0; 3115 while (Parent.getOpcode() == ISD::EXTRACT_SUBVECTOR && 3116 // EXTRACT_SUBVECTOR can be used to extract a fixed-width vector from 3117 // a scalable vector. But we don't want to match the case. 3118 Parent.getOperand(0).getSimpleValueType().isFixedLengthVector()) { 3119 Offset += Parent.getConstantOperandVal(1); 3120 Parent = Parent.getOperand(0); 3121 } 3122 return std::make_pair(Parent, Offset); 3123 }; 3124 3125 auto [V1Src, V1IndexOffset] = findNonEXTRACT_SUBVECTORParent(V1); 3126 auto [V2Src, V2IndexOffset] = findNonEXTRACT_SUBVECTORParent(V2); 3127 3128 // Extracting from the same source. 3129 SDValue Src = V1Src; 3130 if (Src != V2Src) 3131 return SDValue(); 3132 3133 // Rebuild mask because Src may be from multiple EXTRACT_SUBVECTORs. 3134 SmallVector<int, 16> NewMask(Mask); 3135 for (size_t i = 0; i != NewMask.size(); ++i) { 3136 if (NewMask[i] == -1) 3137 continue; 3138 3139 if (static_cast<size_t>(NewMask[i]) < NewMask.size()) { 3140 NewMask[i] = NewMask[i] + V1IndexOffset; 3141 } else { 3142 // Minus NewMask.size() is needed. Otherwise, the b case would be 3143 // <5,6,7,12> instead of <5,6,7,8>. 3144 NewMask[i] = NewMask[i] - NewMask.size() + V2IndexOffset; 3145 } 3146 } 3147 3148 // First index must be known and non-zero. It will be used as the slidedown 3149 // amount. 3150 if (NewMask[0] <= 0) 3151 return SDValue(); 3152 3153 // NewMask is also continuous. 3154 for (unsigned i = 1; i != NewMask.size(); ++i) 3155 if (NewMask[i - 1] + 1 != NewMask[i]) 3156 return SDValue(); 3157 3158 MVT XLenVT = Subtarget.getXLenVT(); 3159 MVT SrcVT = Src.getSimpleValueType(); 3160 MVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT, Subtarget); 3161 auto [TrueMask, VL] = getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3162 SDValue Slidedown = 3163 getVSlidedown(DAG, Subtarget, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 3164 convertToScalableVector(ContainerVT, Src, DAG, Subtarget), 3165 DAG.getConstant(NewMask[0], DL, XLenVT), TrueMask, VL); 3166 return DAG.getNode( 3167 ISD::EXTRACT_SUBVECTOR, DL, VT, 3168 convertFromScalableVector(SrcVT, Slidedown, DAG, Subtarget), 3169 DAG.getConstant(0, DL, XLenVT)); 3170 } 3171 3172 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 3173 const RISCVSubtarget &Subtarget) { 3174 SDValue V1 = Op.getOperand(0); 3175 SDValue V2 = Op.getOperand(1); 3176 SDLoc DL(Op); 3177 MVT XLenVT = Subtarget.getXLenVT(); 3178 MVT VT = Op.getSimpleValueType(); 3179 unsigned NumElts = VT.getVectorNumElements(); 3180 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 3181 3182 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 3183 3184 auto [TrueMask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3185 3186 if (SVN->isSplat()) { 3187 const int Lane = SVN->getSplatIndex(); 3188 if (Lane >= 0) { 3189 MVT SVT = VT.getVectorElementType(); 3190 3191 // Turn splatted vector load into a strided load with an X0 stride. 3192 SDValue V = V1; 3193 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 3194 // with undef. 3195 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 3196 int Offset = Lane; 3197 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 3198 int OpElements = 3199 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 3200 V = V.getOperand(Offset / OpElements); 3201 Offset %= OpElements; 3202 } 3203 3204 // We need to ensure the load isn't atomic or volatile. 3205 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 3206 auto *Ld = cast<LoadSDNode>(V); 3207 Offset *= SVT.getStoreSize(); 3208 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 3209 TypeSize::Fixed(Offset), DL); 3210 3211 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 3212 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 3213 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 3214 SDValue IntID = 3215 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 3216 SDValue Ops[] = {Ld->getChain(), 3217 IntID, 3218 DAG.getUNDEF(ContainerVT), 3219 NewAddr, 3220 DAG.getRegister(RISCV::X0, XLenVT), 3221 VL}; 3222 SDValue NewLoad = DAG.getMemIntrinsicNode( 3223 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 3224 DAG.getMachineFunction().getMachineMemOperand( 3225 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 3226 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 3227 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 3228 } 3229 3230 // Otherwise use a scalar load and splat. This will give the best 3231 // opportunity to fold a splat into the operation. ISel can turn it into 3232 // the x0 strided load if we aren't able to fold away the select. 3233 if (SVT.isFloatingPoint()) 3234 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 3235 Ld->getPointerInfo().getWithOffset(Offset), 3236 Ld->getOriginalAlign(), 3237 Ld->getMemOperand()->getFlags()); 3238 else 3239 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 3240 Ld->getPointerInfo().getWithOffset(Offset), SVT, 3241 Ld->getOriginalAlign(), 3242 Ld->getMemOperand()->getFlags()); 3243 DAG.makeEquivalentMemoryOrdering(Ld, V); 3244 3245 unsigned Opc = 3246 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 3247 SDValue Splat = 3248 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 3249 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 3250 } 3251 3252 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 3253 assert(Lane < (int)NumElts && "Unexpected lane!"); 3254 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, 3255 V1, DAG.getConstant(Lane, DL, XLenVT), 3256 DAG.getUNDEF(ContainerVT), TrueMask, VL); 3257 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 3258 } 3259 } 3260 3261 ArrayRef<int> Mask = SVN->getMask(); 3262 3263 if (SDValue V = 3264 lowerVECTOR_SHUFFLEAsVSlidedown(DL, VT, V1, V2, Mask, Subtarget, DAG)) 3265 return V; 3266 3267 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 3268 // be undef which can be handled with a single SLIDEDOWN/UP. 3269 int LoSrc, HiSrc; 3270 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 3271 if (Rotation > 0) { 3272 SDValue LoV, HiV; 3273 if (LoSrc >= 0) { 3274 LoV = LoSrc == 0 ? V1 : V2; 3275 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 3276 } 3277 if (HiSrc >= 0) { 3278 HiV = HiSrc == 0 ? V1 : V2; 3279 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 3280 } 3281 3282 // We found a rotation. We need to slide HiV down by Rotation. Then we need 3283 // to slide LoV up by (NumElts - Rotation). 3284 unsigned InvRotate = NumElts - Rotation; 3285 3286 SDValue Res = DAG.getUNDEF(ContainerVT); 3287 if (HiV) { 3288 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 3289 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 3290 // causes multiple vsetvlis in some test cases such as lowering 3291 // reduce.mul 3292 SDValue DownVL = VL; 3293 if (LoV) 3294 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 3295 Res = getVSlidedown(DAG, Subtarget, DL, ContainerVT, Res, HiV, 3296 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, 3297 DownVL); 3298 } 3299 if (LoV) 3300 Res = getVSlideup(DAG, Subtarget, DL, ContainerVT, Res, LoV, 3301 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL, 3302 RISCVII::TAIL_AGNOSTIC); 3303 3304 return convertFromScalableVector(VT, Res, DAG, Subtarget); 3305 } 3306 3307 if (SDValue V = lowerVECTOR_SHUFFLEAsVNSRL( 3308 DL, VT, ContainerVT, V1, V2, TrueMask, VL, Mask, Subtarget, DAG)) 3309 return V; 3310 3311 // Detect an interleave shuffle and lower to 3312 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 3313 bool SwapSources; 3314 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 3315 // Swap sources if needed. 3316 if (SwapSources) 3317 std::swap(V1, V2); 3318 3319 // Extract the lower half of the vectors. 3320 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 3321 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 3322 DAG.getConstant(0, DL, XLenVT)); 3323 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 3324 DAG.getConstant(0, DL, XLenVT)); 3325 3326 // Double the element width and halve the number of elements in an int type. 3327 unsigned EltBits = VT.getScalarSizeInBits(); 3328 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 3329 MVT WideIntVT = 3330 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 3331 // Convert this to a scalable vector. We need to base this on the 3332 // destination size to ensure there's always a type with a smaller LMUL. 3333 MVT WideIntContainerVT = 3334 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 3335 3336 // Convert sources to scalable vectors with the same element count as the 3337 // larger type. 3338 MVT HalfContainerVT = MVT::getVectorVT( 3339 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 3340 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 3341 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 3342 3343 // Cast sources to integer. 3344 MVT IntEltVT = MVT::getIntegerVT(EltBits); 3345 MVT IntHalfVT = 3346 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 3347 V1 = DAG.getBitcast(IntHalfVT, V1); 3348 V2 = DAG.getBitcast(IntHalfVT, V2); 3349 3350 // Freeze V2 since we use it twice and we need to be sure that the add and 3351 // multiply see the same value. 3352 V2 = DAG.getFreeze(V2); 3353 3354 // Recreate TrueMask using the widened type's element count. 3355 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 3356 3357 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 3358 SDValue Add = 3359 DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, V2, 3360 DAG.getUNDEF(WideIntContainerVT), TrueMask, VL); 3361 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 3362 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 3363 DAG.getUNDEF(IntHalfVT), 3364 DAG.getAllOnesConstant(DL, XLenVT), VL); 3365 SDValue WidenMul = 3366 DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, V2, Multiplier, 3367 DAG.getUNDEF(WideIntContainerVT), TrueMask, VL); 3368 // Add the new copies to our previous addition giving us 2^eltbits copies of 3369 // V2. This is equivalent to shifting V2 left by eltbits. This should 3370 // combine with the vwmulu.vv above to form vwmaccu.vv. 3371 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 3372 DAG.getUNDEF(WideIntContainerVT), TrueMask, VL); 3373 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 3374 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 3375 // vector VT. 3376 ContainerVT = 3377 MVT::getVectorVT(VT.getVectorElementType(), 3378 WideIntContainerVT.getVectorElementCount() * 2); 3379 Add = DAG.getBitcast(ContainerVT, Add); 3380 return convertFromScalableVector(VT, Add, DAG, Subtarget); 3381 } 3382 3383 // Detect shuffles which can be re-expressed as vector selects; these are 3384 // shuffles in which each element in the destination is taken from an element 3385 // at the corresponding index in either source vectors. 3386 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 3387 int MaskIndex = MaskIdx.value(); 3388 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 3389 }); 3390 3391 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 3392 3393 SmallVector<SDValue> MaskVals; 3394 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 3395 // merged with a second vrgather. 3396 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 3397 3398 // By default we preserve the original operand order, and use a mask to 3399 // select LHS as true and RHS as false. However, since RVV vector selects may 3400 // feature splats but only on the LHS, we may choose to invert our mask and 3401 // instead select between RHS and LHS. 3402 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 3403 bool InvertMask = IsSelect == SwapOps; 3404 3405 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 3406 // half. 3407 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 3408 3409 // Now construct the mask that will be used by the vselect or blended 3410 // vrgather operation. For vrgathers, construct the appropriate indices into 3411 // each vector. 3412 for (int MaskIndex : Mask) { 3413 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 3414 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 3415 if (!IsSelect) { 3416 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 3417 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 3418 ? DAG.getConstant(MaskIndex, DL, XLenVT) 3419 : DAG.getUNDEF(XLenVT)); 3420 GatherIndicesRHS.push_back( 3421 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 3422 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 3423 if (IsLHSOrUndefIndex && MaskIndex >= 0) 3424 ++LHSIndexCounts[MaskIndex]; 3425 if (!IsLHSOrUndefIndex) 3426 ++RHSIndexCounts[MaskIndex - NumElts]; 3427 } 3428 } 3429 3430 if (SwapOps) { 3431 std::swap(V1, V2); 3432 std::swap(GatherIndicesLHS, GatherIndicesRHS); 3433 } 3434 3435 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 3436 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 3437 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 3438 3439 if (IsSelect) 3440 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 3441 3442 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 3443 // On such a large vector we're unable to use i8 as the index type. 3444 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 3445 // may involve vector splitting if we're already at LMUL=8, or our 3446 // user-supplied maximum fixed-length LMUL. 3447 return SDValue(); 3448 } 3449 3450 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 3451 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 3452 MVT IndexVT = VT.changeTypeToInteger(); 3453 // Since we can't introduce illegal index types at this stage, use i16 and 3454 // vrgatherei16 if the corresponding index type for plain vrgather is greater 3455 // than XLenVT. 3456 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 3457 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 3458 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 3459 } 3460 3461 MVT IndexContainerVT = 3462 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 3463 3464 SDValue Gather; 3465 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 3466 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 3467 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 3468 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 3469 Subtarget); 3470 } else { 3471 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 3472 // If only one index is used, we can use a "splat" vrgather. 3473 // TODO: We can splat the most-common index and fix-up any stragglers, if 3474 // that's beneficial. 3475 if (LHSIndexCounts.size() == 1) { 3476 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 3477 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 3478 DAG.getConstant(SplatIndex, DL, XLenVT), 3479 DAG.getUNDEF(ContainerVT), TrueMask, VL); 3480 } else { 3481 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 3482 LHSIndices = 3483 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 3484 3485 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 3486 DAG.getUNDEF(ContainerVT), TrueMask, VL); 3487 } 3488 } 3489 3490 // If a second vector operand is used by this shuffle, blend it in with an 3491 // additional vrgather. 3492 if (!V2.isUndef()) { 3493 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 3494 3495 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 3496 SelectMask = 3497 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 3498 3499 // If only one index is used, we can use a "splat" vrgather. 3500 // TODO: We can splat the most-common index and fix-up any stragglers, if 3501 // that's beneficial. 3502 if (RHSIndexCounts.size() == 1) { 3503 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 3504 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 3505 DAG.getConstant(SplatIndex, DL, XLenVT), Gather, 3506 SelectMask, VL); 3507 } else { 3508 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 3509 RHSIndices = 3510 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 3511 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, Gather, 3512 SelectMask, VL); 3513 } 3514 } 3515 3516 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 3517 } 3518 3519 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 3520 // Support splats for any type. These should type legalize well. 3521 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 3522 return true; 3523 3524 // Only support legal VTs for other shuffles for now. 3525 if (!isTypeLegal(VT)) 3526 return false; 3527 3528 MVT SVT = VT.getSimpleVT(); 3529 3530 bool SwapSources; 3531 int LoSrc, HiSrc; 3532 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 3533 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 3534 } 3535 3536 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 3537 // the exponent. 3538 SDValue 3539 RISCVTargetLowering::lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, 3540 SelectionDAG &DAG) const { 3541 MVT VT = Op.getSimpleValueType(); 3542 unsigned EltSize = VT.getScalarSizeInBits(); 3543 SDValue Src = Op.getOperand(0); 3544 SDLoc DL(Op); 3545 3546 // We choose FP type that can represent the value if possible. Otherwise, we 3547 // use rounding to zero conversion for correct exponent of the result. 3548 // TODO: Use f16 for i8 when possible? 3549 MVT FloatEltVT = (EltSize >= 32) ? MVT::f64 : MVT::f32; 3550 if (!isTypeLegal(MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()))) 3551 FloatEltVT = MVT::f32; 3552 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 3553 3554 // Legal types should have been checked in the RISCVTargetLowering 3555 // constructor. 3556 // TODO: Splitting may make sense in some cases. 3557 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 3558 "Expected legal float type!"); 3559 3560 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 3561 // The trailing zero count is equal to log2 of this single bit value. 3562 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 3563 SDValue Neg = DAG.getNegative(Src, DL, VT); 3564 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 3565 } 3566 3567 // We have a legal FP type, convert to it. 3568 SDValue FloatVal; 3569 if (FloatVT.bitsGT(VT)) { 3570 FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 3571 } else { 3572 // Use RTZ to avoid rounding influencing exponent of FloatVal. 3573 MVT ContainerVT = VT; 3574 if (VT.isFixedLengthVector()) { 3575 ContainerVT = getContainerForFixedLengthVector(VT); 3576 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3577 } 3578 3579 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3580 SDValue RTZRM = 3581 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()); 3582 MVT ContainerFloatVT = 3583 MVT::getVectorVT(FloatEltVT, ContainerVT.getVectorElementCount()); 3584 FloatVal = DAG.getNode(RISCVISD::VFCVT_RM_F_XU_VL, DL, ContainerFloatVT, 3585 Src, Mask, RTZRM, VL); 3586 if (VT.isFixedLengthVector()) 3587 FloatVal = convertFromScalableVector(FloatVT, FloatVal, DAG, Subtarget); 3588 } 3589 // Bitcast to integer and shift the exponent to the LSB. 3590 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 3591 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 3592 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 3593 SDValue Exp = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 3594 DAG.getConstant(ShiftAmt, DL, IntVT)); 3595 // Restore back to original type. Truncation after SRL is to generate vnsrl. 3596 if (IntVT.bitsLT(VT)) 3597 Exp = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Exp); 3598 else if (IntVT.bitsGT(VT)) 3599 Exp = DAG.getNode(ISD::TRUNCATE, DL, VT, Exp); 3600 // The exponent contains log2 of the value in biased form. 3601 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 3602 3603 // For trailing zeros, we just need to subtract the bias. 3604 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 3605 return DAG.getNode(ISD::SUB, DL, VT, Exp, 3606 DAG.getConstant(ExponentBias, DL, VT)); 3607 3608 // For leading zeros, we need to remove the bias and convert from log2 to 3609 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 3610 unsigned Adjust = ExponentBias + (EltSize - 1); 3611 SDValue Res = 3612 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Exp); 3613 // The above result with zero input equals to Adjust which is greater than 3614 // EltSize. Hence, we can do min(Res, EltSize) for CTLZ. 3615 if (Op.getOpcode() == ISD::CTLZ) 3616 Res = DAG.getNode(ISD::UMIN, DL, VT, Res, DAG.getConstant(EltSize, DL, VT)); 3617 return Res; 3618 } 3619 3620 // While RVV has alignment restrictions, we should always be able to load as a 3621 // legal equivalently-sized byte-typed vector instead. This method is 3622 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 3623 // the load is already correctly-aligned, it returns SDValue(). 3624 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 3625 SelectionDAG &DAG) const { 3626 auto *Load = cast<LoadSDNode>(Op); 3627 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 3628 3629 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3630 Load->getMemoryVT(), 3631 *Load->getMemOperand())) 3632 return SDValue(); 3633 3634 SDLoc DL(Op); 3635 MVT VT = Op.getSimpleValueType(); 3636 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3637 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3638 "Unexpected unaligned RVV load type"); 3639 MVT NewVT = 3640 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3641 assert(NewVT.isValid() && 3642 "Expecting equally-sized RVV vector types to be legal"); 3643 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 3644 Load->getPointerInfo(), Load->getOriginalAlign(), 3645 Load->getMemOperand()->getFlags()); 3646 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 3647 } 3648 3649 // While RVV has alignment restrictions, we should always be able to store as a 3650 // legal equivalently-sized byte-typed vector instead. This method is 3651 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 3652 // returns SDValue() if the store is already correctly aligned. 3653 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 3654 SelectionDAG &DAG) const { 3655 auto *Store = cast<StoreSDNode>(Op); 3656 assert(Store && Store->getValue().getValueType().isVector() && 3657 "Expected vector store"); 3658 3659 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3660 Store->getMemoryVT(), 3661 *Store->getMemOperand())) 3662 return SDValue(); 3663 3664 SDLoc DL(Op); 3665 SDValue StoredVal = Store->getValue(); 3666 MVT VT = StoredVal.getSimpleValueType(); 3667 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3668 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3669 "Unexpected unaligned RVV store type"); 3670 MVT NewVT = 3671 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3672 assert(NewVT.isValid() && 3673 "Expecting equally-sized RVV vector types to be legal"); 3674 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3675 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3676 Store->getPointerInfo(), Store->getOriginalAlign(), 3677 Store->getMemOperand()->getFlags()); 3678 } 3679 3680 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, 3681 const RISCVSubtarget &Subtarget) { 3682 assert(Op.getValueType() == MVT::i64 && "Unexpected VT"); 3683 3684 int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue(); 3685 3686 // All simm32 constants should be handled by isel. 3687 // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making 3688 // this check redundant, but small immediates are common so this check 3689 // should have better compile time. 3690 if (isInt<32>(Imm)) 3691 return Op; 3692 3693 // We only need to cost the immediate, if constant pool lowering is enabled. 3694 if (!Subtarget.useConstantPoolForLargeInts()) 3695 return Op; 3696 3697 RISCVMatInt::InstSeq Seq = 3698 RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits()); 3699 if (Seq.size() <= Subtarget.getMaxBuildIntsCost()) 3700 return Op; 3701 3702 // Expand to a constant pool using the default expansion code. 3703 return SDValue(); 3704 } 3705 3706 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) { 3707 SDLoc dl(Op); 3708 SyncScope::ID FenceSSID = 3709 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2)); 3710 3711 // singlethread fences only synchronize with signal handlers on the same 3712 // thread and thus only need to preserve instruction order, not actually 3713 // enforce memory ordering. 3714 if (FenceSSID == SyncScope::SingleThread) 3715 // MEMBARRIER is a compiler barrier; it codegens to a no-op. 3716 return DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 3717 3718 return Op; 3719 } 3720 3721 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3722 SelectionDAG &DAG) const { 3723 switch (Op.getOpcode()) { 3724 default: 3725 report_fatal_error("unimplemented operand"); 3726 case ISD::ATOMIC_FENCE: 3727 return LowerATOMIC_FENCE(Op, DAG); 3728 case ISD::GlobalAddress: 3729 return lowerGlobalAddress(Op, DAG); 3730 case ISD::BlockAddress: 3731 return lowerBlockAddress(Op, DAG); 3732 case ISD::ConstantPool: 3733 return lowerConstantPool(Op, DAG); 3734 case ISD::JumpTable: 3735 return lowerJumpTable(Op, DAG); 3736 case ISD::GlobalTLSAddress: 3737 return lowerGlobalTLSAddress(Op, DAG); 3738 case ISD::Constant: 3739 return lowerConstant(Op, DAG, Subtarget); 3740 case ISD::SELECT: 3741 return lowerSELECT(Op, DAG); 3742 case ISD::BRCOND: 3743 return lowerBRCOND(Op, DAG); 3744 case ISD::VASTART: 3745 return lowerVASTART(Op, DAG); 3746 case ISD::FRAMEADDR: 3747 return lowerFRAMEADDR(Op, DAG); 3748 case ISD::RETURNADDR: 3749 return lowerRETURNADDR(Op, DAG); 3750 case ISD::SHL_PARTS: 3751 return lowerShiftLeftParts(Op, DAG); 3752 case ISD::SRA_PARTS: 3753 return lowerShiftRightParts(Op, DAG, true); 3754 case ISD::SRL_PARTS: 3755 return lowerShiftRightParts(Op, DAG, false); 3756 case ISD::BITCAST: { 3757 SDLoc DL(Op); 3758 EVT VT = Op.getValueType(); 3759 SDValue Op0 = Op.getOperand(0); 3760 EVT Op0VT = Op0.getValueType(); 3761 MVT XLenVT = Subtarget.getXLenVT(); 3762 if (VT == MVT::f16 && Op0VT == MVT::i16 && 3763 Subtarget.hasStdExtZfhOrZfhmin()) { 3764 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3765 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3766 return FPConv; 3767 } 3768 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3769 Subtarget.hasStdExtF()) { 3770 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3771 SDValue FPConv = 3772 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3773 return FPConv; 3774 } 3775 3776 // Consider other scalar<->scalar casts as legal if the types are legal. 3777 // Otherwise expand them. 3778 if (!VT.isVector() && !Op0VT.isVector()) { 3779 if (isTypeLegal(VT) && isTypeLegal(Op0VT)) 3780 return Op; 3781 return SDValue(); 3782 } 3783 3784 assert(!VT.isScalableVector() && !Op0VT.isScalableVector() && 3785 "Unexpected types"); 3786 3787 if (VT.isFixedLengthVector()) { 3788 // We can handle fixed length vector bitcasts with a simple replacement 3789 // in isel. 3790 if (Op0VT.isFixedLengthVector()) 3791 return Op; 3792 // When bitcasting from scalar to fixed-length vector, insert the scalar 3793 // into a one-element vector of the result type, and perform a vector 3794 // bitcast. 3795 if (!Op0VT.isVector()) { 3796 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3797 if (!isTypeLegal(BVT)) 3798 return SDValue(); 3799 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3800 DAG.getUNDEF(BVT), Op0, 3801 DAG.getConstant(0, DL, XLenVT))); 3802 } 3803 return SDValue(); 3804 } 3805 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3806 // thus: bitcast the vector to a one-element vector type whose element type 3807 // is the same as the result type, and extract the first element. 3808 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3809 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3810 if (!isTypeLegal(BVT)) 3811 return SDValue(); 3812 SDValue BVec = DAG.getBitcast(BVT, Op0); 3813 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3814 DAG.getConstant(0, DL, XLenVT)); 3815 } 3816 return SDValue(); 3817 } 3818 case ISD::INTRINSIC_WO_CHAIN: 3819 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3820 case ISD::INTRINSIC_W_CHAIN: 3821 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3822 case ISD::INTRINSIC_VOID: 3823 return LowerINTRINSIC_VOID(Op, DAG); 3824 case ISD::BITREVERSE: { 3825 MVT VT = Op.getSimpleValueType(); 3826 SDLoc DL(Op); 3827 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3828 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3829 // Expand bitreverse to a bswap(rev8) followed by brev8. 3830 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3831 return DAG.getNode(RISCVISD::BREV8, DL, VT, BSwap); 3832 } 3833 case ISD::TRUNCATE: 3834 // Only custom-lower vector truncates 3835 if (!Op.getSimpleValueType().isVector()) 3836 return Op; 3837 return lowerVectorTruncLike(Op, DAG); 3838 case ISD::ANY_EXTEND: 3839 case ISD::ZERO_EXTEND: 3840 if (Op.getOperand(0).getValueType().isVector() && 3841 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3842 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3843 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3844 case ISD::SIGN_EXTEND: 3845 if (Op.getOperand(0).getValueType().isVector() && 3846 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3847 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3848 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3849 case ISD::SPLAT_VECTOR_PARTS: 3850 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3851 case ISD::INSERT_VECTOR_ELT: 3852 return lowerINSERT_VECTOR_ELT(Op, DAG); 3853 case ISD::EXTRACT_VECTOR_ELT: 3854 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3855 case ISD::VSCALE: { 3856 MVT VT = Op.getSimpleValueType(); 3857 SDLoc DL(Op); 3858 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3859 // We define our scalable vector types for lmul=1 to use a 64 bit known 3860 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3861 // vscale as VLENB / 8. 3862 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3863 if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock) 3864 report_fatal_error("Support for VLEN==32 is incomplete."); 3865 // We assume VLENB is a multiple of 8. We manually choose the best shift 3866 // here because SimplifyDemandedBits isn't always able to simplify it. 3867 uint64_t Val = Op.getConstantOperandVal(0); 3868 if (isPowerOf2_64(Val)) { 3869 uint64_t Log2 = Log2_64(Val); 3870 if (Log2 < 3) 3871 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3872 DAG.getConstant(3 - Log2, DL, VT)); 3873 if (Log2 > 3) 3874 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3875 DAG.getConstant(Log2 - 3, DL, VT)); 3876 return VLENB; 3877 } 3878 // If the multiplier is a multiple of 8, scale it down to avoid needing 3879 // to shift the VLENB value. 3880 if ((Val % 8) == 0) 3881 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3882 DAG.getConstant(Val / 8, DL, VT)); 3883 3884 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3885 DAG.getConstant(3, DL, VT)); 3886 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3887 } 3888 case ISD::FPOWI: { 3889 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3890 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3891 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3892 Op.getOperand(1).getValueType() == MVT::i32) { 3893 SDLoc DL(Op); 3894 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3895 SDValue Powi = 3896 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3897 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3898 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true)); 3899 } 3900 return SDValue(); 3901 } 3902 case ISD::FP_EXTEND: 3903 case ISD::FP_ROUND: 3904 if (!Op.getValueType().isVector()) 3905 return Op; 3906 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3907 case ISD::FP_TO_SINT: 3908 case ISD::FP_TO_UINT: 3909 case ISD::SINT_TO_FP: 3910 case ISD::UINT_TO_FP: { 3911 // RVV can only do fp<->int conversions to types half/double the size as 3912 // the source. We custom-lower any conversions that do two hops into 3913 // sequences. 3914 MVT VT = Op.getSimpleValueType(); 3915 if (!VT.isVector()) 3916 return Op; 3917 SDLoc DL(Op); 3918 SDValue Src = Op.getOperand(0); 3919 MVT EltVT = VT.getVectorElementType(); 3920 MVT SrcVT = Src.getSimpleValueType(); 3921 MVT SrcEltVT = SrcVT.getVectorElementType(); 3922 unsigned EltSize = EltVT.getSizeInBits(); 3923 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3924 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3925 "Unexpected vector element types"); 3926 3927 bool IsInt2FP = SrcEltVT.isInteger(); 3928 // Widening conversions 3929 if (EltSize > (2 * SrcEltSize)) { 3930 if (IsInt2FP) { 3931 // Do a regular integer sign/zero extension then convert to float. 3932 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize / 2), 3933 VT.getVectorElementCount()); 3934 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3935 ? ISD::ZERO_EXTEND 3936 : ISD::SIGN_EXTEND; 3937 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3938 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3939 } 3940 // FP2Int 3941 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3942 // Do one doubling fp_extend then complete the operation by converting 3943 // to int. 3944 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3945 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3946 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3947 } 3948 3949 // Narrowing conversions 3950 if (SrcEltSize > (2 * EltSize)) { 3951 if (IsInt2FP) { 3952 // One narrowing int_to_fp, then an fp_round. 3953 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3954 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3955 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3956 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3957 } 3958 // FP2Int 3959 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3960 // representable by the integer, the result is poison. 3961 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3962 VT.getVectorElementCount()); 3963 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3964 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3965 } 3966 3967 // Scalable vectors can exit here. Patterns will handle equally-sized 3968 // conversions halving/doubling ones. 3969 if (!VT.isFixedLengthVector()) 3970 return Op; 3971 3972 // For fixed-length vectors we lower to a custom "VL" node. 3973 unsigned RVVOpc = 0; 3974 switch (Op.getOpcode()) { 3975 default: 3976 llvm_unreachable("Impossible opcode"); 3977 case ISD::FP_TO_SINT: 3978 RVVOpc = RISCVISD::VFCVT_RTZ_X_F_VL; 3979 break; 3980 case ISD::FP_TO_UINT: 3981 RVVOpc = RISCVISD::VFCVT_RTZ_XU_F_VL; 3982 break; 3983 case ISD::SINT_TO_FP: 3984 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3985 break; 3986 case ISD::UINT_TO_FP: 3987 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3988 break; 3989 } 3990 3991 MVT ContainerVT = getContainerForFixedLengthVector(VT); 3992 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3993 assert(ContainerVT.getVectorElementCount() == SrcContainerVT.getVectorElementCount() && 3994 "Expected same element count"); 3995 3996 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3997 3998 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3999 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 4000 return convertFromScalableVector(VT, Src, DAG, Subtarget); 4001 } 4002 case ISD::FP_TO_SINT_SAT: 4003 case ISD::FP_TO_UINT_SAT: 4004 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 4005 case ISD::FTRUNC: 4006 case ISD::FCEIL: 4007 case ISD::FFLOOR: 4008 case ISD::FRINT: 4009 case ISD::FROUND: 4010 case ISD::FROUNDEVEN: 4011 return lowerFTRUNC_FCEIL_FFLOOR_FROUND(Op, DAG, Subtarget); 4012 case ISD::VECREDUCE_ADD: 4013 case ISD::VECREDUCE_UMAX: 4014 case ISD::VECREDUCE_SMAX: 4015 case ISD::VECREDUCE_UMIN: 4016 case ISD::VECREDUCE_SMIN: 4017 return lowerVECREDUCE(Op, DAG); 4018 case ISD::VECREDUCE_AND: 4019 case ISD::VECREDUCE_OR: 4020 case ISD::VECREDUCE_XOR: 4021 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 4022 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 4023 return lowerVECREDUCE(Op, DAG); 4024 case ISD::VECREDUCE_FADD: 4025 case ISD::VECREDUCE_SEQ_FADD: 4026 case ISD::VECREDUCE_FMIN: 4027 case ISD::VECREDUCE_FMAX: 4028 return lowerFPVECREDUCE(Op, DAG); 4029 case ISD::VP_REDUCE_ADD: 4030 case ISD::VP_REDUCE_UMAX: 4031 case ISD::VP_REDUCE_SMAX: 4032 case ISD::VP_REDUCE_UMIN: 4033 case ISD::VP_REDUCE_SMIN: 4034 case ISD::VP_REDUCE_FADD: 4035 case ISD::VP_REDUCE_SEQ_FADD: 4036 case ISD::VP_REDUCE_FMIN: 4037 case ISD::VP_REDUCE_FMAX: 4038 return lowerVPREDUCE(Op, DAG); 4039 case ISD::VP_REDUCE_AND: 4040 case ISD::VP_REDUCE_OR: 4041 case ISD::VP_REDUCE_XOR: 4042 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 4043 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 4044 return lowerVPREDUCE(Op, DAG); 4045 case ISD::INSERT_SUBVECTOR: 4046 return lowerINSERT_SUBVECTOR(Op, DAG); 4047 case ISD::EXTRACT_SUBVECTOR: 4048 return lowerEXTRACT_SUBVECTOR(Op, DAG); 4049 case ISD::STEP_VECTOR: 4050 return lowerSTEP_VECTOR(Op, DAG); 4051 case ISD::VECTOR_REVERSE: 4052 return lowerVECTOR_REVERSE(Op, DAG); 4053 case ISD::VECTOR_SPLICE: 4054 return lowerVECTOR_SPLICE(Op, DAG); 4055 case ISD::BUILD_VECTOR: 4056 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 4057 case ISD::SPLAT_VECTOR: 4058 if (Op.getValueType().getVectorElementType() == MVT::i1) 4059 return lowerVectorMaskSplat(Op, DAG); 4060 return SDValue(); 4061 case ISD::VECTOR_SHUFFLE: 4062 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 4063 case ISD::CONCAT_VECTORS: { 4064 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 4065 // better than going through the stack, as the default expansion does. 4066 SDLoc DL(Op); 4067 MVT VT = Op.getSimpleValueType(); 4068 unsigned NumOpElts = 4069 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 4070 SDValue Vec = DAG.getUNDEF(VT); 4071 for (const auto &OpIdx : enumerate(Op->ops())) { 4072 SDValue SubVec = OpIdx.value(); 4073 // Don't insert undef subvectors. 4074 if (SubVec.isUndef()) 4075 continue; 4076 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 4077 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 4078 } 4079 return Vec; 4080 } 4081 case ISD::LOAD: 4082 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 4083 return V; 4084 if (Op.getValueType().isFixedLengthVector()) 4085 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 4086 return Op; 4087 case ISD::STORE: 4088 if (auto V = expandUnalignedRVVStore(Op, DAG)) 4089 return V; 4090 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 4091 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 4092 return Op; 4093 case ISD::MLOAD: 4094 case ISD::VP_LOAD: 4095 return lowerMaskedLoad(Op, DAG); 4096 case ISD::MSTORE: 4097 case ISD::VP_STORE: 4098 return lowerMaskedStore(Op, DAG); 4099 case ISD::SELECT_CC: { 4100 // This occurs because we custom legalize SETGT and SETUGT for setcc. That 4101 // causes LegalizeDAG to think we need to custom legalize select_cc. Expand 4102 // into separate SETCC+SELECT_CC just like LegalizeDAG. 4103 SDValue Tmp1 = Op.getOperand(0); 4104 SDValue Tmp2 = Op.getOperand(1); 4105 SDValue True = Op.getOperand(2); 4106 SDValue False = Op.getOperand(3); 4107 EVT VT = Op.getValueType(); 4108 SDValue CC = Op.getOperand(4); 4109 EVT CmpVT = Tmp1.getValueType(); 4110 EVT CCVT = 4111 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT); 4112 SDLoc DL(Op); 4113 SDValue Cond = 4114 DAG.getNode(ISD::SETCC, DL, CCVT, Tmp1, Tmp2, CC, Op->getFlags()); 4115 return DAG.getSelect(DL, VT, Cond, True, False); 4116 } 4117 case ISD::SETCC: { 4118 MVT OpVT = Op.getOperand(0).getSimpleValueType(); 4119 if (OpVT.isScalarInteger()) { 4120 MVT VT = Op.getSimpleValueType(); 4121 SDValue LHS = Op.getOperand(0); 4122 SDValue RHS = Op.getOperand(1); 4123 ISD::CondCode CCVal = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 4124 assert((CCVal == ISD::SETGT || CCVal == ISD::SETUGT) && 4125 "Unexpected CondCode"); 4126 4127 SDLoc DL(Op); 4128 4129 // If the RHS is a constant in the range [-2049, 0) or (0, 2046], we can 4130 // convert this to the equivalent of (set(u)ge X, C+1) by using 4131 // (xori (slti(u) X, C+1), 1). This avoids materializing a small constant 4132 // in a register. 4133 if (isa<ConstantSDNode>(RHS)) { 4134 int64_t Imm = cast<ConstantSDNode>(RHS)->getSExtValue(); 4135 if (Imm != 0 && isInt<12>((uint64_t)Imm + 1)) { 4136 // X > -1 should have been replaced with false. 4137 assert((CCVal != ISD::SETUGT || Imm != -1) && 4138 "Missing canonicalization"); 4139 // Using getSetCCSwappedOperands will convert SET(U)GT->SET(U)LT. 4140 CCVal = ISD::getSetCCSwappedOperands(CCVal); 4141 SDValue SetCC = DAG.getSetCC( 4142 DL, VT, LHS, DAG.getConstant(Imm + 1, DL, OpVT), CCVal); 4143 return DAG.getLogicalNOT(DL, SetCC, VT); 4144 } 4145 } 4146 4147 // Not a constant we could handle, swap the operands and condition code to 4148 // SETLT/SETULT. 4149 CCVal = ISD::getSetCCSwappedOperands(CCVal); 4150 return DAG.getSetCC(DL, VT, RHS, LHS, CCVal); 4151 } 4152 4153 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 4154 } 4155 case ISD::ADD: 4156 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL, /*HasMergeOp*/ true); 4157 case ISD::SUB: 4158 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL, /*HasMergeOp*/ true); 4159 case ISD::MUL: 4160 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL, /*HasMergeOp*/ true); 4161 case ISD::MULHS: 4162 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL, /*HasMergeOp*/ true); 4163 case ISD::MULHU: 4164 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL, /*HasMergeOp*/ true); 4165 case ISD::AND: 4166 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 4167 RISCVISD::AND_VL); 4168 case ISD::OR: 4169 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 4170 RISCVISD::OR_VL); 4171 case ISD::XOR: 4172 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 4173 RISCVISD::XOR_VL); 4174 case ISD::SDIV: 4175 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL, /*HasMergeOp*/ true); 4176 case ISD::SREM: 4177 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL, /*HasMergeOp*/ true); 4178 case ISD::UDIV: 4179 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL, /*HasMergeOp*/ true); 4180 case ISD::UREM: 4181 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL, /*HasMergeOp*/ true); 4182 case ISD::SHL: 4183 case ISD::SRA: 4184 case ISD::SRL: 4185 if (Op.getSimpleValueType().isFixedLengthVector()) 4186 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 4187 // This can be called for an i32 shift amount that needs to be promoted. 4188 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 4189 "Unexpected custom legalisation"); 4190 return SDValue(); 4191 case ISD::SADDSAT: 4192 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL, 4193 /*HasMergeOp*/ true); 4194 case ISD::UADDSAT: 4195 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL, 4196 /*HasMergeOp*/ true); 4197 case ISD::SSUBSAT: 4198 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL, 4199 /*HasMergeOp*/ true); 4200 case ISD::USUBSAT: 4201 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL, 4202 /*HasMergeOp*/ true); 4203 case ISD::FADD: 4204 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL, /*HasMergeOp*/ true); 4205 case ISD::FSUB: 4206 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL, /*HasMergeOp*/ true); 4207 case ISD::FMUL: 4208 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL, /*HasMergeOp*/ true); 4209 case ISD::FDIV: 4210 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL, /*HasMergeOp*/ true); 4211 case ISD::FNEG: 4212 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 4213 case ISD::FABS: 4214 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 4215 case ISD::FSQRT: 4216 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 4217 case ISD::FMA: 4218 return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL); 4219 case ISD::SMIN: 4220 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL, /*HasMergeOp*/ true); 4221 case ISD::SMAX: 4222 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL, /*HasMergeOp*/ true); 4223 case ISD::UMIN: 4224 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL, /*HasMergeOp*/ true); 4225 case ISD::UMAX: 4226 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL, /*HasMergeOp*/ true); 4227 case ISD::FMINNUM: 4228 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL, 4229 /*HasMergeOp*/ true); 4230 case ISD::FMAXNUM: 4231 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL, 4232 /*HasMergeOp*/ true); 4233 case ISD::ABS: 4234 case ISD::VP_ABS: 4235 return lowerABS(Op, DAG); 4236 case ISD::CTLZ: 4237 case ISD::CTLZ_ZERO_UNDEF: 4238 case ISD::CTTZ_ZERO_UNDEF: 4239 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 4240 case ISD::VSELECT: 4241 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 4242 case ISD::FCOPYSIGN: 4243 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 4244 case ISD::MGATHER: 4245 case ISD::VP_GATHER: 4246 return lowerMaskedGather(Op, DAG); 4247 case ISD::MSCATTER: 4248 case ISD::VP_SCATTER: 4249 return lowerMaskedScatter(Op, DAG); 4250 case ISD::GET_ROUNDING: 4251 return lowerGET_ROUNDING(Op, DAG); 4252 case ISD::SET_ROUNDING: 4253 return lowerSET_ROUNDING(Op, DAG); 4254 case ISD::EH_DWARF_CFA: 4255 return lowerEH_DWARF_CFA(Op, DAG); 4256 case ISD::VP_SELECT: 4257 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 4258 case ISD::VP_MERGE: 4259 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 4260 case ISD::VP_ADD: 4261 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL, /*HasMergeOp*/ true); 4262 case ISD::VP_SUB: 4263 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL, /*HasMergeOp*/ true); 4264 case ISD::VP_MUL: 4265 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL, /*HasMergeOp*/ true); 4266 case ISD::VP_SDIV: 4267 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL, /*HasMergeOp*/ true); 4268 case ISD::VP_UDIV: 4269 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL, /*HasMergeOp*/ true); 4270 case ISD::VP_SREM: 4271 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL, /*HasMergeOp*/ true); 4272 case ISD::VP_UREM: 4273 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL, /*HasMergeOp*/ true); 4274 case ISD::VP_AND: 4275 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 4276 case ISD::VP_OR: 4277 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 4278 case ISD::VP_XOR: 4279 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 4280 case ISD::VP_ASHR: 4281 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL, /*HasMergeOp*/ true); 4282 case ISD::VP_LSHR: 4283 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL, /*HasMergeOp*/ true); 4284 case ISD::VP_SHL: 4285 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL, /*HasMergeOp*/ true); 4286 case ISD::VP_FADD: 4287 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL, /*HasMergeOp*/ true); 4288 case ISD::VP_FSUB: 4289 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL, /*HasMergeOp*/ true); 4290 case ISD::VP_FMUL: 4291 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL, /*HasMergeOp*/ true); 4292 case ISD::VP_FDIV: 4293 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL, /*HasMergeOp*/ true); 4294 case ISD::VP_FNEG: 4295 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 4296 case ISD::VP_FABS: 4297 return lowerVPOp(Op, DAG, RISCVISD::FABS_VL); 4298 case ISD::VP_SQRT: 4299 return lowerVPOp(Op, DAG, RISCVISD::FSQRT_VL); 4300 case ISD::VP_FMA: 4301 return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL); 4302 case ISD::VP_FMINNUM: 4303 return lowerVPOp(Op, DAG, RISCVISD::FMINNUM_VL, /*HasMergeOp*/ true); 4304 case ISD::VP_FMAXNUM: 4305 return lowerVPOp(Op, DAG, RISCVISD::FMAXNUM_VL, /*HasMergeOp*/ true); 4306 case ISD::VP_FCOPYSIGN: 4307 return lowerVPOp(Op, DAG, RISCVISD::FCOPYSIGN_VL, /*HasMergeOp*/ true); 4308 case ISD::VP_SIGN_EXTEND: 4309 case ISD::VP_ZERO_EXTEND: 4310 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 4311 return lowerVPExtMaskOp(Op, DAG); 4312 return lowerVPOp(Op, DAG, 4313 Op.getOpcode() == ISD::VP_SIGN_EXTEND 4314 ? RISCVISD::VSEXT_VL 4315 : RISCVISD::VZEXT_VL); 4316 case ISD::VP_TRUNCATE: 4317 return lowerVectorTruncLike(Op, DAG); 4318 case ISD::VP_FP_EXTEND: 4319 case ISD::VP_FP_ROUND: 4320 return lowerVectorFPExtendOrRoundLike(Op, DAG); 4321 case ISD::VP_FP_TO_SINT: 4322 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::VFCVT_RTZ_X_F_VL); 4323 case ISD::VP_FP_TO_UINT: 4324 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::VFCVT_RTZ_XU_F_VL); 4325 case ISD::VP_SINT_TO_FP: 4326 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 4327 case ISD::VP_UINT_TO_FP: 4328 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 4329 case ISD::VP_SETCC: 4330 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 4331 return lowerVPSetCCMaskOp(Op, DAG); 4332 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL, /*HasMergeOp*/ true); 4333 case ISD::VP_SMIN: 4334 return lowerVPOp(Op, DAG, RISCVISD::SMIN_VL, /*HasMergeOp*/ true); 4335 case ISD::VP_SMAX: 4336 return lowerVPOp(Op, DAG, RISCVISD::SMAX_VL, /*HasMergeOp*/ true); 4337 case ISD::VP_UMIN: 4338 return lowerVPOp(Op, DAG, RISCVISD::UMIN_VL, /*HasMergeOp*/ true); 4339 case ISD::VP_UMAX: 4340 return lowerVPOp(Op, DAG, RISCVISD::UMAX_VL, /*HasMergeOp*/ true); 4341 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 4342 return lowerVPStridedLoad(Op, DAG); 4343 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 4344 return lowerVPStridedStore(Op, DAG); 4345 case ISD::VP_FCEIL: 4346 case ISD::VP_FFLOOR: 4347 case ISD::VP_FRINT: 4348 case ISD::VP_FNEARBYINT: 4349 case ISD::VP_FROUND: 4350 case ISD::VP_FROUNDEVEN: 4351 case ISD::VP_FROUNDTOZERO: 4352 return lowerVectorFTRUNC_FCEIL_FFLOOR_FROUND(Op, DAG, Subtarget); 4353 } 4354 } 4355 4356 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 4357 SelectionDAG &DAG, unsigned Flags) { 4358 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 4359 } 4360 4361 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 4362 SelectionDAG &DAG, unsigned Flags) { 4363 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 4364 Flags); 4365 } 4366 4367 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 4368 SelectionDAG &DAG, unsigned Flags) { 4369 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 4370 N->getOffset(), Flags); 4371 } 4372 4373 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 4374 SelectionDAG &DAG, unsigned Flags) { 4375 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 4376 } 4377 4378 template <class NodeTy> 4379 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 4380 bool IsLocal) const { 4381 SDLoc DL(N); 4382 EVT Ty = getPointerTy(DAG.getDataLayout()); 4383 4384 // When HWASAN is used and tagging of global variables is enabled 4385 // they should be accessed via the GOT, since the tagged address of a global 4386 // is incompatible with existing code models. This also applies to non-pic 4387 // mode. 4388 if (isPositionIndependent() || Subtarget.allowTaggedGlobals()) { 4389 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 4390 if (IsLocal && !Subtarget.allowTaggedGlobals()) 4391 // Use PC-relative addressing to access the symbol. This generates the 4392 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 4393 // %pcrel_lo(auipc)). 4394 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 4395 4396 // Use PC-relative addressing to access the GOT for this symbol, then load 4397 // the address from the GOT. This generates the pattern (PseudoLA sym), 4398 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 4399 MachineFunction &MF = DAG.getMachineFunction(); 4400 MachineMemOperand *MemOp = MF.getMachineMemOperand( 4401 MachinePointerInfo::getGOT(MF), 4402 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 4403 MachineMemOperand::MOInvariant, 4404 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 4405 SDValue Load = 4406 DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other), 4407 {DAG.getEntryNode(), Addr}, Ty, MemOp); 4408 return Load; 4409 } 4410 4411 switch (getTargetMachine().getCodeModel()) { 4412 default: 4413 report_fatal_error("Unsupported code model for lowering"); 4414 case CodeModel::Small: { 4415 // Generate a sequence for accessing addresses within the first 2 GiB of 4416 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 4417 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 4418 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 4419 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 4420 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo); 4421 } 4422 case CodeModel::Medium: { 4423 // Generate a sequence for accessing addresses within any 2GiB range within 4424 // the address space. This generates the pattern (PseudoLLA sym), which 4425 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 4426 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 4427 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 4428 } 4429 } 4430 } 4431 4432 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 4433 SelectionDAG &DAG) const { 4434 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 4435 assert(N->getOffset() == 0 && "unexpected offset in global node"); 4436 return getAddr(N, DAG, N->getGlobal()->isDSOLocal()); 4437 } 4438 4439 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 4440 SelectionDAG &DAG) const { 4441 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 4442 4443 return getAddr(N, DAG); 4444 } 4445 4446 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 4447 SelectionDAG &DAG) const { 4448 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 4449 4450 return getAddr(N, DAG); 4451 } 4452 4453 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 4454 SelectionDAG &DAG) const { 4455 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 4456 4457 return getAddr(N, DAG); 4458 } 4459 4460 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 4461 SelectionDAG &DAG, 4462 bool UseGOT) const { 4463 SDLoc DL(N); 4464 EVT Ty = getPointerTy(DAG.getDataLayout()); 4465 const GlobalValue *GV = N->getGlobal(); 4466 MVT XLenVT = Subtarget.getXLenVT(); 4467 4468 if (UseGOT) { 4469 // Use PC-relative addressing to access the GOT for this TLS symbol, then 4470 // load the address from the GOT and add the thread pointer. This generates 4471 // the pattern (PseudoLA_TLS_IE sym), which expands to 4472 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 4473 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 4474 MachineFunction &MF = DAG.getMachineFunction(); 4475 MachineMemOperand *MemOp = MF.getMachineMemOperand( 4476 MachinePointerInfo::getGOT(MF), 4477 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 4478 MachineMemOperand::MOInvariant, 4479 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 4480 SDValue Load = DAG.getMemIntrinsicNode( 4481 RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other), 4482 {DAG.getEntryNode(), Addr}, Ty, MemOp); 4483 4484 // Add the thread pointer. 4485 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 4486 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 4487 } 4488 4489 // Generate a sequence for accessing the address relative to the thread 4490 // pointer, with the appropriate adjustment for the thread pointer offset. 4491 // This generates the pattern 4492 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 4493 SDValue AddrHi = 4494 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 4495 SDValue AddrAdd = 4496 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 4497 SDValue AddrLo = 4498 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 4499 4500 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 4501 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 4502 SDValue MNAdd = 4503 DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd); 4504 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo); 4505 } 4506 4507 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 4508 SelectionDAG &DAG) const { 4509 SDLoc DL(N); 4510 EVT Ty = getPointerTy(DAG.getDataLayout()); 4511 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 4512 const GlobalValue *GV = N->getGlobal(); 4513 4514 // Use a PC-relative addressing mode to access the global dynamic GOT address. 4515 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 4516 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 4517 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 4518 SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr); 4519 4520 // Prepare argument list to generate call. 4521 ArgListTy Args; 4522 ArgListEntry Entry; 4523 Entry.Node = Load; 4524 Entry.Ty = CallTy; 4525 Args.push_back(Entry); 4526 4527 // Setup call to __tls_get_addr. 4528 TargetLowering::CallLoweringInfo CLI(DAG); 4529 CLI.setDebugLoc(DL) 4530 .setChain(DAG.getEntryNode()) 4531 .setLibCallee(CallingConv::C, CallTy, 4532 DAG.getExternalSymbol("__tls_get_addr", Ty), 4533 std::move(Args)); 4534 4535 return LowerCallTo(CLI).first; 4536 } 4537 4538 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 4539 SelectionDAG &DAG) const { 4540 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 4541 assert(N->getOffset() == 0 && "unexpected offset in global node"); 4542 4543 if (DAG.getTarget().useEmulatedTLS()) 4544 return LowerToTLSEmulatedModel(N, DAG); 4545 4546 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 4547 4548 if (DAG.getMachineFunction().getFunction().getCallingConv() == 4549 CallingConv::GHC) 4550 report_fatal_error("In GHC calling convention TLS is not supported"); 4551 4552 SDValue Addr; 4553 switch (Model) { 4554 case TLSModel::LocalExec: 4555 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 4556 break; 4557 case TLSModel::InitialExec: 4558 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 4559 break; 4560 case TLSModel::LocalDynamic: 4561 case TLSModel::GeneralDynamic: 4562 Addr = getDynamicTLSAddr(N, DAG); 4563 break; 4564 } 4565 4566 return Addr; 4567 } 4568 4569 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4570 SDValue CondV = Op.getOperand(0); 4571 SDValue TrueV = Op.getOperand(1); 4572 SDValue FalseV = Op.getOperand(2); 4573 SDLoc DL(Op); 4574 MVT VT = Op.getSimpleValueType(); 4575 MVT XLenVT = Subtarget.getXLenVT(); 4576 4577 // Lower vector SELECTs to VSELECTs by splatting the condition. 4578 if (VT.isVector()) { 4579 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 4580 SDValue CondSplat = DAG.getSplat(SplatCondVT, DL, CondV); 4581 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 4582 } 4583 4584 if (!Subtarget.hasShortForwardBranchOpt()) { 4585 // (select c, -1, y) -> -c | y 4586 if (isAllOnesConstant(TrueV)) { 4587 SDValue Neg = DAG.getNegative(CondV, DL, VT); 4588 return DAG.getNode(ISD::OR, DL, VT, Neg, FalseV); 4589 } 4590 // (select c, y, -1) -> (c-1) | y 4591 if (isAllOnesConstant(FalseV)) { 4592 SDValue Neg = DAG.getNode(ISD::ADD, DL, VT, CondV, 4593 DAG.getAllOnesConstant(DL, VT)); 4594 return DAG.getNode(ISD::OR, DL, VT, Neg, TrueV); 4595 } 4596 4597 // (select c, 0, y) -> (c-1) & y 4598 if (isNullConstant(TrueV)) { 4599 SDValue Neg = DAG.getNode(ISD::ADD, DL, VT, CondV, 4600 DAG.getAllOnesConstant(DL, VT)); 4601 return DAG.getNode(ISD::AND, DL, VT, Neg, FalseV); 4602 } 4603 // (select c, y, 0) -> -c & y 4604 if (isNullConstant(FalseV)) { 4605 SDValue Neg = DAG.getNegative(CondV, DL, VT); 4606 return DAG.getNode(ISD::AND, DL, VT, Neg, TrueV); 4607 } 4608 } 4609 4610 // If the condition is not an integer SETCC which operates on XLenVT, we need 4611 // to emit a RISCVISD::SELECT_CC comparing the condition to zero. i.e.: 4612 // (select condv, truev, falsev) 4613 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 4614 if (CondV.getOpcode() != ISD::SETCC || 4615 CondV.getOperand(0).getSimpleValueType() != XLenVT) { 4616 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4617 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 4618 4619 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 4620 4621 return DAG.getNode(RISCVISD::SELECT_CC, DL, VT, Ops); 4622 } 4623 4624 // If the CondV is the output of a SETCC node which operates on XLenVT inputs, 4625 // then merge the SETCC node into the lowered RISCVISD::SELECT_CC to take 4626 // advantage of the integer compare+branch instructions. i.e.: 4627 // (select (setcc lhs, rhs, cc), truev, falsev) 4628 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 4629 SDValue LHS = CondV.getOperand(0); 4630 SDValue RHS = CondV.getOperand(1); 4631 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 4632 4633 // Special case for a select of 2 constants that have a diffence of 1. 4634 // Normally this is done by DAGCombine, but if the select is introduced by 4635 // type legalization or op legalization, we miss it. Restricting to SETLT 4636 // case for now because that is what signed saturating add/sub need. 4637 // FIXME: We don't need the condition to be SETLT or even a SETCC, 4638 // but we would probably want to swap the true/false values if the condition 4639 // is SETGE/SETLE to avoid an XORI. 4640 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 4641 CCVal == ISD::SETLT) { 4642 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 4643 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 4644 if (TrueVal - 1 == FalseVal) 4645 return DAG.getNode(ISD::ADD, DL, VT, CondV, FalseV); 4646 if (TrueVal + 1 == FalseVal) 4647 return DAG.getNode(ISD::SUB, DL, VT, FalseV, CondV); 4648 } 4649 4650 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 4651 // 1 < x ? x : 1 -> 0 < x ? x : 1 4652 if (isOneConstant(LHS) && (CCVal == ISD::SETLT || CCVal == ISD::SETULT) && 4653 RHS == TrueV && LHS == FalseV) { 4654 LHS = DAG.getConstant(0, DL, VT); 4655 // 0 <u x is the same as x != 0. 4656 if (CCVal == ISD::SETULT) { 4657 std::swap(LHS, RHS); 4658 CCVal = ISD::SETNE; 4659 } 4660 } 4661 4662 // x <s -1 ? x : -1 -> x <s 0 ? x : -1 4663 if (isAllOnesConstant(RHS) && CCVal == ISD::SETLT && LHS == TrueV && 4664 RHS == FalseV) { 4665 RHS = DAG.getConstant(0, DL, VT); 4666 } 4667 4668 SDValue TargetCC = DAG.getCondCode(CCVal); 4669 4670 if (isa<ConstantSDNode>(TrueV) && !isa<ConstantSDNode>(FalseV)) { 4671 // (select (setcc lhs, rhs, CC), constant, falsev) 4672 // -> (select (setcc lhs, rhs, InverseCC), falsev, constant) 4673 std::swap(TrueV, FalseV); 4674 TargetCC = DAG.getCondCode(ISD::getSetCCInverse(CCVal, LHS.getValueType())); 4675 } 4676 4677 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 4678 return DAG.getNode(RISCVISD::SELECT_CC, DL, VT, Ops); 4679 } 4680 4681 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4682 SDValue CondV = Op.getOperand(1); 4683 SDLoc DL(Op); 4684 MVT XLenVT = Subtarget.getXLenVT(); 4685 4686 if (CondV.getOpcode() == ISD::SETCC && 4687 CondV.getOperand(0).getValueType() == XLenVT) { 4688 SDValue LHS = CondV.getOperand(0); 4689 SDValue RHS = CondV.getOperand(1); 4690 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 4691 4692 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 4693 4694 SDValue TargetCC = DAG.getCondCode(CCVal); 4695 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 4696 LHS, RHS, TargetCC, Op.getOperand(2)); 4697 } 4698 4699 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 4700 CondV, DAG.getConstant(0, DL, XLenVT), 4701 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 4702 } 4703 4704 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 4705 MachineFunction &MF = DAG.getMachineFunction(); 4706 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 4707 4708 SDLoc DL(Op); 4709 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 4710 getPointerTy(MF.getDataLayout())); 4711 4712 // vastart just stores the address of the VarArgsFrameIndex slot into the 4713 // memory location argument. 4714 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4715 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 4716 MachinePointerInfo(SV)); 4717 } 4718 4719 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 4720 SelectionDAG &DAG) const { 4721 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4722 MachineFunction &MF = DAG.getMachineFunction(); 4723 MachineFrameInfo &MFI = MF.getFrameInfo(); 4724 MFI.setFrameAddressIsTaken(true); 4725 Register FrameReg = RI.getFrameRegister(MF); 4726 int XLenInBytes = Subtarget.getXLen() / 8; 4727 4728 EVT VT = Op.getValueType(); 4729 SDLoc DL(Op); 4730 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 4731 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4732 while (Depth--) { 4733 int Offset = -(XLenInBytes * 2); 4734 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 4735 DAG.getIntPtrConstant(Offset, DL)); 4736 FrameAddr = 4737 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 4738 } 4739 return FrameAddr; 4740 } 4741 4742 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 4743 SelectionDAG &DAG) const { 4744 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4745 MachineFunction &MF = DAG.getMachineFunction(); 4746 MachineFrameInfo &MFI = MF.getFrameInfo(); 4747 MFI.setReturnAddressIsTaken(true); 4748 MVT XLenVT = Subtarget.getXLenVT(); 4749 int XLenInBytes = Subtarget.getXLen() / 8; 4750 4751 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4752 return SDValue(); 4753 4754 EVT VT = Op.getValueType(); 4755 SDLoc DL(Op); 4756 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4757 if (Depth) { 4758 int Off = -XLenInBytes; 4759 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 4760 SDValue Offset = DAG.getConstant(Off, DL, VT); 4761 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4762 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4763 MachinePointerInfo()); 4764 } 4765 4766 // Return the value of the return address register, marking it an implicit 4767 // live-in. 4768 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 4769 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 4770 } 4771 4772 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4773 SelectionDAG &DAG) const { 4774 SDLoc DL(Op); 4775 SDValue Lo = Op.getOperand(0); 4776 SDValue Hi = Op.getOperand(1); 4777 SDValue Shamt = Op.getOperand(2); 4778 EVT VT = Lo.getValueType(); 4779 4780 // if Shamt-XLEN < 0: // Shamt < XLEN 4781 // Lo = Lo << Shamt 4782 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4783 // else: 4784 // Lo = 0 4785 // Hi = Lo << (Shamt-XLEN) 4786 4787 SDValue Zero = DAG.getConstant(0, DL, VT); 4788 SDValue One = DAG.getConstant(1, DL, VT); 4789 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4790 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4791 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4792 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 4793 4794 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4795 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4796 SDValue ShiftRightLo = 4797 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4798 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4799 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4800 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4801 4802 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4803 4804 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4805 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4806 4807 SDValue Parts[2] = {Lo, Hi}; 4808 return DAG.getMergeValues(Parts, DL); 4809 } 4810 4811 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4812 bool IsSRA) const { 4813 SDLoc DL(Op); 4814 SDValue Lo = Op.getOperand(0); 4815 SDValue Hi = Op.getOperand(1); 4816 SDValue Shamt = Op.getOperand(2); 4817 EVT VT = Lo.getValueType(); 4818 4819 // SRA expansion: 4820 // if Shamt-XLEN < 0: // Shamt < XLEN 4821 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4822 // Hi = Hi >>s Shamt 4823 // else: 4824 // Lo = Hi >>s (Shamt-XLEN); 4825 // Hi = Hi >>s (XLEN-1) 4826 // 4827 // SRL expansion: 4828 // if Shamt-XLEN < 0: // Shamt < XLEN 4829 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4830 // Hi = Hi >>u Shamt 4831 // else: 4832 // Lo = Hi >>u (Shamt-XLEN); 4833 // Hi = 0; 4834 4835 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4836 4837 SDValue Zero = DAG.getConstant(0, DL, VT); 4838 SDValue One = DAG.getConstant(1, DL, VT); 4839 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4840 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4841 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4842 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 4843 4844 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4845 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4846 SDValue ShiftLeftHi = 4847 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4848 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4849 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4850 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4851 SDValue HiFalse = 4852 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4853 4854 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4855 4856 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4857 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4858 4859 SDValue Parts[2] = {Lo, Hi}; 4860 return DAG.getMergeValues(Parts, DL); 4861 } 4862 4863 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4864 // legal equivalently-sized i8 type, so we can use that as a go-between. 4865 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4866 SelectionDAG &DAG) const { 4867 SDLoc DL(Op); 4868 MVT VT = Op.getSimpleValueType(); 4869 SDValue SplatVal = Op.getOperand(0); 4870 // All-zeros or all-ones splats are handled specially. 4871 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4872 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4873 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4874 } 4875 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4876 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4877 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4878 } 4879 MVT XLenVT = Subtarget.getXLenVT(); 4880 assert(SplatVal.getValueType() == XLenVT && 4881 "Unexpected type for i1 splat value"); 4882 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4883 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4884 DAG.getConstant(1, DL, XLenVT)); 4885 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4886 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4887 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4888 } 4889 4890 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4891 // illegal (currently only vXi64 RV32). 4892 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4893 // them to VMV_V_X_VL. 4894 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4895 SelectionDAG &DAG) const { 4896 SDLoc DL(Op); 4897 MVT VecVT = Op.getSimpleValueType(); 4898 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4899 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4900 4901 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4902 SDValue Lo = Op.getOperand(0); 4903 SDValue Hi = Op.getOperand(1); 4904 4905 if (VecVT.isFixedLengthVector()) { 4906 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4907 SDLoc DL(Op); 4908 auto VL = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).second; 4909 4910 SDValue Res = 4911 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4912 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4913 } 4914 4915 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4916 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4917 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4918 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4919 // node in order to try and match RVV vector/scalar instructions. 4920 if ((LoC >> 31) == HiC) 4921 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4922 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4923 } 4924 4925 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4926 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4927 isa<ConstantSDNode>(Hi.getOperand(1)) && 4928 Hi.getConstantOperandVal(1) == 31) 4929 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4930 DAG.getRegister(RISCV::X0, MVT::i32)); 4931 4932 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4933 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4934 DAG.getUNDEF(VecVT), Lo, Hi, 4935 DAG.getRegister(RISCV::X0, MVT::i32)); 4936 } 4937 4938 // Custom-lower extensions from mask vectors by using a vselect either with 1 4939 // for zero/any-extension or -1 for sign-extension: 4940 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4941 // Note that any-extension is lowered identically to zero-extension. 4942 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4943 int64_t ExtTrueVal) const { 4944 SDLoc DL(Op); 4945 MVT VecVT = Op.getSimpleValueType(); 4946 SDValue Src = Op.getOperand(0); 4947 // Only custom-lower extensions from mask types 4948 assert(Src.getValueType().isVector() && 4949 Src.getValueType().getVectorElementType() == MVT::i1); 4950 4951 if (VecVT.isScalableVector()) { 4952 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4953 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4954 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4955 } 4956 4957 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4958 MVT I1ContainerVT = 4959 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4960 4961 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4962 4963 SDValue VL = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).second; 4964 4965 MVT XLenVT = Subtarget.getXLenVT(); 4966 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4967 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4968 4969 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4970 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4971 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4972 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4973 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4974 SplatTrueVal, SplatZero, VL); 4975 4976 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4977 } 4978 4979 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4980 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4981 MVT ExtVT = Op.getSimpleValueType(); 4982 // Only custom-lower extensions from fixed-length vector types. 4983 if (!ExtVT.isFixedLengthVector()) 4984 return Op; 4985 MVT VT = Op.getOperand(0).getSimpleValueType(); 4986 // Grab the canonical container type for the extended type. Infer the smaller 4987 // type from that to ensure the same number of vector elements, as we know 4988 // the LMUL will be sufficient to hold the smaller type. 4989 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4990 // Get the extended container type manually to ensure the same number of 4991 // vector elements between source and dest. 4992 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4993 ContainerExtVT.getVectorElementCount()); 4994 4995 SDValue Op1 = 4996 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4997 4998 SDLoc DL(Op); 4999 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5000 5001 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 5002 5003 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 5004 } 5005 5006 // Custom-lower truncations from vectors to mask vectors by using a mask and a 5007 // setcc operation: 5008 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 5009 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 5010 SelectionDAG &DAG) const { 5011 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 5012 SDLoc DL(Op); 5013 EVT MaskVT = Op.getValueType(); 5014 // Only expect to custom-lower truncations to mask types 5015 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 5016 "Unexpected type for vector mask lowering"); 5017 SDValue Src = Op.getOperand(0); 5018 MVT VecVT = Src.getSimpleValueType(); 5019 SDValue Mask, VL; 5020 if (IsVPTrunc) { 5021 Mask = Op.getOperand(1); 5022 VL = Op.getOperand(2); 5023 } 5024 // If this is a fixed vector, we need to convert it to a scalable vector. 5025 MVT ContainerVT = VecVT; 5026 5027 if (VecVT.isFixedLengthVector()) { 5028 ContainerVT = getContainerForFixedLengthVector(VecVT); 5029 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 5030 if (IsVPTrunc) { 5031 MVT MaskContainerVT = 5032 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 5033 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 5034 } 5035 } 5036 5037 if (!IsVPTrunc) { 5038 std::tie(Mask, VL) = 5039 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5040 } 5041 5042 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 5043 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 5044 5045 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5046 DAG.getUNDEF(ContainerVT), SplatOne, VL); 5047 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5048 DAG.getUNDEF(ContainerVT), SplatZero, VL); 5049 5050 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 5051 SDValue Trunc = DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, 5052 DAG.getUNDEF(ContainerVT), Mask, VL); 5053 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, 5054 {Trunc, SplatZero, DAG.getCondCode(ISD::SETNE), 5055 DAG.getUNDEF(MaskContainerVT), Mask, VL}); 5056 if (MaskVT.isFixedLengthVector()) 5057 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 5058 return Trunc; 5059 } 5060 5061 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 5062 SelectionDAG &DAG) const { 5063 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 5064 SDLoc DL(Op); 5065 5066 MVT VT = Op.getSimpleValueType(); 5067 // Only custom-lower vector truncates 5068 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 5069 5070 // Truncates to mask types are handled differently 5071 if (VT.getVectorElementType() == MVT::i1) 5072 return lowerVectorMaskTruncLike(Op, DAG); 5073 5074 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 5075 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 5076 // truncate by one power of two at a time. 5077 MVT DstEltVT = VT.getVectorElementType(); 5078 5079 SDValue Src = Op.getOperand(0); 5080 MVT SrcVT = Src.getSimpleValueType(); 5081 MVT SrcEltVT = SrcVT.getVectorElementType(); 5082 5083 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 5084 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 5085 "Unexpected vector truncate lowering"); 5086 5087 MVT ContainerVT = SrcVT; 5088 SDValue Mask, VL; 5089 if (IsVPTrunc) { 5090 Mask = Op.getOperand(1); 5091 VL = Op.getOperand(2); 5092 } 5093 if (SrcVT.isFixedLengthVector()) { 5094 ContainerVT = getContainerForFixedLengthVector(SrcVT); 5095 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 5096 if (IsVPTrunc) { 5097 MVT MaskVT = getMaskTypeFor(ContainerVT); 5098 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5099 } 5100 } 5101 5102 SDValue Result = Src; 5103 if (!IsVPTrunc) { 5104 std::tie(Mask, VL) = 5105 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 5106 } 5107 5108 LLVMContext &Context = *DAG.getContext(); 5109 const ElementCount Count = ContainerVT.getVectorElementCount(); 5110 do { 5111 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 5112 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 5113 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 5114 Mask, VL); 5115 } while (SrcEltVT != DstEltVT); 5116 5117 if (SrcVT.isFixedLengthVector()) 5118 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5119 5120 return Result; 5121 } 5122 5123 SDValue 5124 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 5125 SelectionDAG &DAG) const { 5126 bool IsVP = 5127 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 5128 bool IsExtend = 5129 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 5130 // RVV can only do truncate fp to types half the size as the source. We 5131 // custom-lower f64->f16 rounds via RVV's round-to-odd float 5132 // conversion instruction. 5133 SDLoc DL(Op); 5134 MVT VT = Op.getSimpleValueType(); 5135 5136 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 5137 5138 SDValue Src = Op.getOperand(0); 5139 MVT SrcVT = Src.getSimpleValueType(); 5140 5141 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 5142 SrcVT.getVectorElementType() != MVT::f16); 5143 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 5144 SrcVT.getVectorElementType() != MVT::f64); 5145 5146 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 5147 5148 // Prepare any fixed-length vector operands. 5149 MVT ContainerVT = VT; 5150 SDValue Mask, VL; 5151 if (IsVP) { 5152 Mask = Op.getOperand(1); 5153 VL = Op.getOperand(2); 5154 } 5155 if (VT.isFixedLengthVector()) { 5156 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 5157 ContainerVT = 5158 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 5159 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 5160 if (IsVP) { 5161 MVT MaskVT = getMaskTypeFor(ContainerVT); 5162 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5163 } 5164 } 5165 5166 if (!IsVP) 5167 std::tie(Mask, VL) = 5168 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 5169 5170 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 5171 5172 if (IsDirectConv) { 5173 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 5174 if (VT.isFixedLengthVector()) 5175 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 5176 return Src; 5177 } 5178 5179 unsigned InterConvOpc = 5180 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 5181 5182 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 5183 SDValue IntermediateConv = 5184 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 5185 SDValue Result = 5186 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 5187 if (VT.isFixedLengthVector()) 5188 return convertFromScalableVector(VT, Result, DAG, Subtarget); 5189 return Result; 5190 } 5191 5192 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 5193 // first position of a vector, and that vector is slid up to the insert index. 5194 // By limiting the active vector length to index+1 and merging with the 5195 // original vector (with an undisturbed tail policy for elements >= VL), we 5196 // achieve the desired result of leaving all elements untouched except the one 5197 // at VL-1, which is replaced with the desired value. 5198 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5199 SelectionDAG &DAG) const { 5200 SDLoc DL(Op); 5201 MVT VecVT = Op.getSimpleValueType(); 5202 SDValue Vec = Op.getOperand(0); 5203 SDValue Val = Op.getOperand(1); 5204 SDValue Idx = Op.getOperand(2); 5205 5206 if (VecVT.getVectorElementType() == MVT::i1) { 5207 // FIXME: For now we just promote to an i8 vector and insert into that, 5208 // but this is probably not optimal. 5209 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 5210 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 5211 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 5212 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 5213 } 5214 5215 MVT ContainerVT = VecVT; 5216 // If the operand is a fixed-length vector, convert to a scalable one. 5217 if (VecVT.isFixedLengthVector()) { 5218 ContainerVT = getContainerForFixedLengthVector(VecVT); 5219 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5220 } 5221 5222 MVT XLenVT = Subtarget.getXLenVT(); 5223 5224 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5225 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 5226 // Even i64-element vectors on RV32 can be lowered without scalar 5227 // legalization if the most-significant 32 bits of the value are not affected 5228 // by the sign-extension of the lower 32 bits. 5229 // TODO: We could also catch sign extensions of a 32-bit value. 5230 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 5231 const auto *CVal = cast<ConstantSDNode>(Val); 5232 if (isInt<32>(CVal->getSExtValue())) { 5233 IsLegalInsert = true; 5234 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 5235 } 5236 } 5237 5238 auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5239 5240 SDValue ValInVec; 5241 5242 if (IsLegalInsert) { 5243 unsigned Opc = 5244 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 5245 if (isNullConstant(Idx)) { 5246 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 5247 if (!VecVT.isFixedLengthVector()) 5248 return Vec; 5249 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 5250 } 5251 ValInVec = lowerScalarInsert(Val, VL, ContainerVT, DL, DAG, Subtarget); 5252 } else { 5253 // On RV32, i64-element vectors must be specially handled to place the 5254 // value at element 0, by using two vslide1down instructions in sequence on 5255 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 5256 // this. 5257 SDValue One = DAG.getConstant(1, DL, XLenVT); 5258 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 5259 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 5260 MVT I32ContainerVT = 5261 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 5262 SDValue I32Mask = 5263 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 5264 // Limit the active VL to two. 5265 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 5266 // If the Idx is 0 we can insert directly into the vector. 5267 if (isNullConstant(Idx)) { 5268 // First slide in the lo value, then the hi in above it. We use slide1down 5269 // to avoid the register group overlap constraint of vslide1up. 5270 ValInVec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32ContainerVT, 5271 Vec, Vec, ValLo, I32Mask, InsertI64VL); 5272 // If the source vector is undef don't pass along the tail elements from 5273 // the previous slide1down. 5274 SDValue Tail = Vec.isUndef() ? Vec : ValInVec; 5275 ValInVec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32ContainerVT, 5276 Tail, ValInVec, ValHi, I32Mask, InsertI64VL); 5277 // Bitcast back to the right container type. 5278 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 5279 5280 if (!VecVT.isFixedLengthVector()) 5281 return ValInVec; 5282 return convertFromScalableVector(VecVT, ValInVec, DAG, Subtarget); 5283 } 5284 5285 // First slide in the lo value, then the hi in above it. We use slide1down 5286 // to avoid the register group overlap constraint of vslide1up. 5287 ValInVec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32ContainerVT, 5288 DAG.getUNDEF(I32ContainerVT), 5289 DAG.getUNDEF(I32ContainerVT), ValLo, 5290 I32Mask, InsertI64VL); 5291 ValInVec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32ContainerVT, 5292 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 5293 I32Mask, InsertI64VL); 5294 // Bitcast back to the right container type. 5295 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 5296 } 5297 5298 // Now that the value is in a vector, slide it into position. 5299 SDValue InsertVL = 5300 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 5301 5302 // Use tail agnostic policy if Idx is the last index of Vec. 5303 unsigned Policy = RISCVII::TAIL_UNDISTURBED_MASK_UNDISTURBED; 5304 if (VecVT.isFixedLengthVector() && isa<ConstantSDNode>(Idx) && 5305 cast<ConstantSDNode>(Idx)->getZExtValue() + 1 == 5306 VecVT.getVectorNumElements()) 5307 Policy = RISCVII::TAIL_AGNOSTIC; 5308 SDValue Slideup = getVSlideup(DAG, Subtarget, DL, ContainerVT, Vec, ValInVec, 5309 Idx, Mask, InsertVL, Policy); 5310 if (!VecVT.isFixedLengthVector()) 5311 return Slideup; 5312 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5313 } 5314 5315 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 5316 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 5317 // types this is done using VMV_X_S to allow us to glean information about the 5318 // sign bits of the result. 5319 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5320 SelectionDAG &DAG) const { 5321 SDLoc DL(Op); 5322 SDValue Idx = Op.getOperand(1); 5323 SDValue Vec = Op.getOperand(0); 5324 EVT EltVT = Op.getValueType(); 5325 MVT VecVT = Vec.getSimpleValueType(); 5326 MVT XLenVT = Subtarget.getXLenVT(); 5327 5328 if (VecVT.getVectorElementType() == MVT::i1) { 5329 // Use vfirst.m to extract the first bit. 5330 if (isNullConstant(Idx)) { 5331 MVT ContainerVT = VecVT; 5332 if (VecVT.isFixedLengthVector()) { 5333 ContainerVT = getContainerForFixedLengthVector(VecVT); 5334 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5335 } 5336 auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5337 SDValue Vfirst = 5338 DAG.getNode(RISCVISD::VFIRST_VL, DL, XLenVT, Vec, Mask, VL); 5339 return DAG.getSetCC(DL, XLenVT, Vfirst, DAG.getConstant(0, DL, XLenVT), 5340 ISD::SETEQ); 5341 } 5342 if (VecVT.isFixedLengthVector()) { 5343 unsigned NumElts = VecVT.getVectorNumElements(); 5344 if (NumElts >= 8) { 5345 MVT WideEltVT; 5346 unsigned WidenVecLen; 5347 SDValue ExtractElementIdx; 5348 SDValue ExtractBitIdx; 5349 unsigned MaxEEW = Subtarget.getELEN(); 5350 MVT LargestEltVT = MVT::getIntegerVT( 5351 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 5352 if (NumElts <= LargestEltVT.getSizeInBits()) { 5353 assert(isPowerOf2_32(NumElts) && 5354 "the number of elements should be power of 2"); 5355 WideEltVT = MVT::getIntegerVT(NumElts); 5356 WidenVecLen = 1; 5357 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 5358 ExtractBitIdx = Idx; 5359 } else { 5360 WideEltVT = LargestEltVT; 5361 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 5362 // extract element index = index / element width 5363 ExtractElementIdx = DAG.getNode( 5364 ISD::SRL, DL, XLenVT, Idx, 5365 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 5366 // mask bit index = index % element width 5367 ExtractBitIdx = DAG.getNode( 5368 ISD::AND, DL, XLenVT, Idx, 5369 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 5370 } 5371 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 5372 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 5373 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 5374 Vec, ExtractElementIdx); 5375 // Extract the bit from GPR. 5376 SDValue ShiftRight = 5377 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 5378 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 5379 DAG.getConstant(1, DL, XLenVT)); 5380 } 5381 } 5382 // Otherwise, promote to an i8 vector and extract from that. 5383 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 5384 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 5385 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 5386 } 5387 5388 // If this is a fixed vector, we need to convert it to a scalable vector. 5389 MVT ContainerVT = VecVT; 5390 if (VecVT.isFixedLengthVector()) { 5391 ContainerVT = getContainerForFixedLengthVector(VecVT); 5392 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5393 } 5394 5395 // If the index is 0, the vector is already in the right position. 5396 if (!isNullConstant(Idx)) { 5397 // Use a VL of 1 to avoid processing more elements than we need. 5398 auto [Mask, VL] = getDefaultVLOps(1, ContainerVT, DL, DAG, Subtarget); 5399 Vec = getVSlidedown(DAG, Subtarget, DL, ContainerVT, 5400 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 5401 } 5402 5403 if (!EltVT.isInteger()) { 5404 // Floating-point extracts are handled in TableGen. 5405 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 5406 DAG.getConstant(0, DL, XLenVT)); 5407 } 5408 5409 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 5410 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 5411 } 5412 5413 // Some RVV intrinsics may claim that they want an integer operand to be 5414 // promoted or expanded. 5415 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 5416 const RISCVSubtarget &Subtarget) { 5417 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 5418 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 5419 "Unexpected opcode"); 5420 5421 if (!Subtarget.hasVInstructions()) 5422 return SDValue(); 5423 5424 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 5425 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 5426 SDLoc DL(Op); 5427 5428 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 5429 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 5430 if (!II || !II->hasScalarOperand()) 5431 return SDValue(); 5432 5433 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 5434 assert(SplatOp < Op.getNumOperands()); 5435 5436 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 5437 SDValue &ScalarOp = Operands[SplatOp]; 5438 MVT OpVT = ScalarOp.getSimpleValueType(); 5439 MVT XLenVT = Subtarget.getXLenVT(); 5440 5441 // If this isn't a scalar, or its type is XLenVT we're done. 5442 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 5443 return SDValue(); 5444 5445 // Simplest case is that the operand needs to be promoted to XLenVT. 5446 if (OpVT.bitsLT(XLenVT)) { 5447 // If the operand is a constant, sign extend to increase our chances 5448 // of being able to use a .vi instruction. ANY_EXTEND would become a 5449 // a zero extend and the simm5 check in isel would fail. 5450 // FIXME: Should we ignore the upper bits in isel instead? 5451 unsigned ExtOpc = 5452 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 5453 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 5454 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 5455 } 5456 5457 // Use the previous operand to get the vXi64 VT. The result might be a mask 5458 // VT for compares. Using the previous operand assumes that the previous 5459 // operand will never have a smaller element size than a scalar operand and 5460 // that a widening operation never uses SEW=64. 5461 // NOTE: If this fails the below assert, we can probably just find the 5462 // element count from any operand or result and use it to construct the VT. 5463 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 5464 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 5465 5466 // The more complex case is when the scalar is larger than XLenVT. 5467 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 5468 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 5469 5470 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 5471 // instruction to sign-extend since SEW>XLEN. 5472 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 5473 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 5474 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 5475 } 5476 5477 switch (IntNo) { 5478 case Intrinsic::riscv_vslide1up: 5479 case Intrinsic::riscv_vslide1down: 5480 case Intrinsic::riscv_vslide1up_mask: 5481 case Intrinsic::riscv_vslide1down_mask: { 5482 // We need to special case these when the scalar is larger than XLen. 5483 unsigned NumOps = Op.getNumOperands(); 5484 bool IsMasked = NumOps == 7; 5485 5486 // Convert the vector source to the equivalent nxvXi32 vector. 5487 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 5488 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 5489 5490 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 5491 DAG.getConstant(0, DL, XLenVT)); 5492 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 5493 DAG.getConstant(1, DL, XLenVT)); 5494 5495 // Double the VL since we halved SEW. 5496 SDValue AVL = getVLOperand(Op); 5497 SDValue I32VL; 5498 5499 // Optimize for constant AVL 5500 if (isa<ConstantSDNode>(AVL)) { 5501 unsigned EltSize = VT.getScalarSizeInBits(); 5502 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 5503 5504 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 5505 unsigned MaxVLMAX = 5506 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5507 5508 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 5509 unsigned MinVLMAX = 5510 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 5511 5512 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 5513 if (AVLInt <= MinVLMAX) { 5514 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 5515 } else if (AVLInt >= 2 * MaxVLMAX) { 5516 // Just set vl to VLMAX in this situation 5517 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 5518 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 5519 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 5520 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 5521 SDValue SETVLMAX = DAG.getTargetConstant( 5522 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 5523 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 5524 LMUL); 5525 } else { 5526 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 5527 // is related to the hardware implementation. 5528 // So let the following code handle 5529 } 5530 } 5531 if (!I32VL) { 5532 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 5533 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 5534 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 5535 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 5536 SDValue SETVL = 5537 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 5538 // Using vsetvli instruction to get actually used length which related to 5539 // the hardware implementation 5540 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 5541 SEW, LMUL); 5542 I32VL = 5543 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 5544 } 5545 5546 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 5547 5548 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 5549 // instructions. 5550 SDValue Passthru; 5551 if (IsMasked) 5552 Passthru = DAG.getUNDEF(I32VT); 5553 else 5554 Passthru = DAG.getBitcast(I32VT, Operands[1]); 5555 5556 if (IntNo == Intrinsic::riscv_vslide1up || 5557 IntNo == Intrinsic::riscv_vslide1up_mask) { 5558 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 5559 ScalarHi, I32Mask, I32VL); 5560 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 5561 ScalarLo, I32Mask, I32VL); 5562 } else { 5563 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 5564 ScalarLo, I32Mask, I32VL); 5565 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 5566 ScalarHi, I32Mask, I32VL); 5567 } 5568 5569 // Convert back to nxvXi64. 5570 Vec = DAG.getBitcast(VT, Vec); 5571 5572 if (!IsMasked) 5573 return Vec; 5574 // Apply mask after the operation. 5575 SDValue Mask = Operands[NumOps - 3]; 5576 SDValue MaskedOff = Operands[1]; 5577 // Assume Policy operand is the last operand. 5578 uint64_t Policy = 5579 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 5580 // We don't need to select maskedoff if it's undef. 5581 if (MaskedOff.isUndef()) 5582 return Vec; 5583 // TAMU 5584 if (Policy == RISCVII::TAIL_AGNOSTIC) 5585 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 5586 AVL); 5587 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 5588 // It's fine because vmerge does not care mask policy. 5589 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 5590 AVL); 5591 } 5592 } 5593 5594 // We need to convert the scalar to a splat vector. 5595 SDValue VL = getVLOperand(Op); 5596 assert(VL.getValueType() == XLenVT); 5597 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 5598 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 5599 } 5600 5601 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5602 SelectionDAG &DAG) const { 5603 unsigned IntNo = Op.getConstantOperandVal(0); 5604 SDLoc DL(Op); 5605 MVT XLenVT = Subtarget.getXLenVT(); 5606 5607 switch (IntNo) { 5608 default: 5609 break; // Don't custom lower most intrinsics. 5610 case Intrinsic::thread_pointer: { 5611 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5612 return DAG.getRegister(RISCV::X4, PtrVT); 5613 } 5614 case Intrinsic::riscv_orc_b: 5615 case Intrinsic::riscv_brev8: { 5616 unsigned Opc = 5617 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::BREV8 : RISCVISD::ORC_B; 5618 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1)); 5619 } 5620 case Intrinsic::riscv_zip: 5621 case Intrinsic::riscv_unzip: { 5622 unsigned Opc = 5623 IntNo == Intrinsic::riscv_zip ? RISCVISD::ZIP : RISCVISD::UNZIP; 5624 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1)); 5625 } 5626 case Intrinsic::riscv_vmv_x_s: 5627 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 5628 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 5629 Op.getOperand(1)); 5630 case Intrinsic::riscv_vfmv_f_s: 5631 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getValueType(), 5632 Op.getOperand(1), DAG.getConstant(0, DL, XLenVT)); 5633 case Intrinsic::riscv_vmv_v_x: 5634 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 5635 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 5636 Subtarget); 5637 case Intrinsic::riscv_vfmv_v_f: 5638 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 5639 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5640 case Intrinsic::riscv_vmv_s_x: { 5641 SDValue Scalar = Op.getOperand(2); 5642 5643 if (Scalar.getValueType().bitsLE(XLenVT)) { 5644 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 5645 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 5646 Op.getOperand(1), Scalar, Op.getOperand(3)); 5647 } 5648 5649 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 5650 5651 // This is an i64 value that lives in two scalar registers. We have to 5652 // insert this in a convoluted way. First we build vXi64 splat containing 5653 // the two values that we assemble using some bit math. Next we'll use 5654 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 5655 // to merge element 0 from our splat into the source vector. 5656 // FIXME: This is probably not the best way to do this, but it is 5657 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 5658 // point. 5659 // sw lo, (a0) 5660 // sw hi, 4(a0) 5661 // vlse vX, (a0) 5662 // 5663 // vid.v vVid 5664 // vmseq.vx mMask, vVid, 0 5665 // vmerge.vvm vDest, vSrc, vVal, mMask 5666 MVT VT = Op.getSimpleValueType(); 5667 SDValue Vec = Op.getOperand(1); 5668 SDValue VL = getVLOperand(Op); 5669 5670 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 5671 if (Op.getOperand(1).isUndef()) 5672 return SplattedVal; 5673 SDValue SplattedIdx = 5674 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5675 DAG.getConstant(0, DL, MVT::i32), VL); 5676 5677 MVT MaskVT = getMaskTypeFor(VT); 5678 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 5679 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5680 SDValue SelectCond = 5681 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, 5682 {VID, SplattedIdx, DAG.getCondCode(ISD::SETEQ), 5683 DAG.getUNDEF(MaskVT), Mask, VL}); 5684 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 5685 Vec, VL); 5686 } 5687 } 5688 5689 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 5690 } 5691 5692 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 5693 SelectionDAG &DAG) const { 5694 unsigned IntNo = Op.getConstantOperandVal(1); 5695 switch (IntNo) { 5696 default: 5697 break; 5698 case Intrinsic::riscv_masked_strided_load: { 5699 SDLoc DL(Op); 5700 MVT XLenVT = Subtarget.getXLenVT(); 5701 5702 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5703 // the selection of the masked intrinsics doesn't do this for us. 5704 SDValue Mask = Op.getOperand(5); 5705 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5706 5707 MVT VT = Op->getSimpleValueType(0); 5708 MVT ContainerVT = VT; 5709 if (VT.isFixedLengthVector()) 5710 ContainerVT = getContainerForFixedLengthVector(VT); 5711 5712 SDValue PassThru = Op.getOperand(2); 5713 if (!IsUnmasked) { 5714 MVT MaskVT = getMaskTypeFor(ContainerVT); 5715 if (VT.isFixedLengthVector()) { 5716 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5717 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5718 } 5719 } 5720 5721 auto *Load = cast<MemIntrinsicSDNode>(Op); 5722 SDValue VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5723 SDValue Ptr = Op.getOperand(3); 5724 SDValue Stride = Op.getOperand(4); 5725 SDValue Result, Chain; 5726 5727 // TODO: We restrict this to unmasked loads currently in consideration of 5728 // the complexity of hanlding all falses masks. 5729 if (IsUnmasked && isNullConstant(Stride)) { 5730 MVT ScalarVT = ContainerVT.getVectorElementType(); 5731 SDValue ScalarLoad = 5732 DAG.getExtLoad(ISD::ZEXTLOAD, DL, XLenVT, Load->getChain(), Ptr, 5733 ScalarVT, Load->getMemOperand()); 5734 Chain = ScalarLoad.getValue(1); 5735 Result = lowerScalarSplat(SDValue(), ScalarLoad, VL, ContainerVT, DL, DAG, 5736 Subtarget); 5737 } else { 5738 SDValue IntID = DAG.getTargetConstant( 5739 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 5740 XLenVT); 5741 5742 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 5743 if (IsUnmasked) 5744 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5745 else 5746 Ops.push_back(PassThru); 5747 Ops.push_back(Ptr); 5748 Ops.push_back(Stride); 5749 if (!IsUnmasked) 5750 Ops.push_back(Mask); 5751 Ops.push_back(VL); 5752 if (!IsUnmasked) { 5753 SDValue Policy = 5754 DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 5755 Ops.push_back(Policy); 5756 } 5757 5758 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5759 Result = 5760 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5761 Load->getMemoryVT(), Load->getMemOperand()); 5762 Chain = Result.getValue(1); 5763 } 5764 if (VT.isFixedLengthVector()) 5765 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5766 return DAG.getMergeValues({Result, Chain}, DL); 5767 } 5768 case Intrinsic::riscv_seg2_load: 5769 case Intrinsic::riscv_seg3_load: 5770 case Intrinsic::riscv_seg4_load: 5771 case Intrinsic::riscv_seg5_load: 5772 case Intrinsic::riscv_seg6_load: 5773 case Intrinsic::riscv_seg7_load: 5774 case Intrinsic::riscv_seg8_load: { 5775 SDLoc DL(Op); 5776 static const Intrinsic::ID VlsegInts[7] = { 5777 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 5778 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 5779 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 5780 Intrinsic::riscv_vlseg8}; 5781 unsigned NF = Op->getNumValues() - 1; 5782 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 5783 MVT XLenVT = Subtarget.getXLenVT(); 5784 MVT VT = Op->getSimpleValueType(0); 5785 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5786 5787 SDValue VL = getVLOp(VT.getVectorNumElements(), DL, DAG, Subtarget); 5788 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 5789 auto *Load = cast<MemIntrinsicSDNode>(Op); 5790 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 5791 ContainerVTs.push_back(MVT::Other); 5792 SDVTList VTs = DAG.getVTList(ContainerVTs); 5793 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 5794 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 5795 Ops.push_back(Op.getOperand(2)); 5796 Ops.push_back(VL); 5797 SDValue Result = 5798 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5799 Load->getMemoryVT(), Load->getMemOperand()); 5800 SmallVector<SDValue, 9> Results; 5801 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 5802 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 5803 DAG, Subtarget)); 5804 Results.push_back(Result.getValue(NF)); 5805 return DAG.getMergeValues(Results, DL); 5806 } 5807 } 5808 5809 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 5810 } 5811 5812 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 5813 SelectionDAG &DAG) const { 5814 unsigned IntNo = Op.getConstantOperandVal(1); 5815 switch (IntNo) { 5816 default: 5817 break; 5818 case Intrinsic::riscv_masked_strided_store: { 5819 SDLoc DL(Op); 5820 MVT XLenVT = Subtarget.getXLenVT(); 5821 5822 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5823 // the selection of the masked intrinsics doesn't do this for us. 5824 SDValue Mask = Op.getOperand(5); 5825 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5826 5827 SDValue Val = Op.getOperand(2); 5828 MVT VT = Val.getSimpleValueType(); 5829 MVT ContainerVT = VT; 5830 if (VT.isFixedLengthVector()) { 5831 ContainerVT = getContainerForFixedLengthVector(VT); 5832 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5833 } 5834 if (!IsUnmasked) { 5835 MVT MaskVT = getMaskTypeFor(ContainerVT); 5836 if (VT.isFixedLengthVector()) 5837 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5838 } 5839 5840 SDValue VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5841 5842 SDValue IntID = DAG.getTargetConstant( 5843 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5844 XLenVT); 5845 5846 auto *Store = cast<MemIntrinsicSDNode>(Op); 5847 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5848 Ops.push_back(Val); 5849 Ops.push_back(Op.getOperand(3)); // Ptr 5850 Ops.push_back(Op.getOperand(4)); // Stride 5851 if (!IsUnmasked) 5852 Ops.push_back(Mask); 5853 Ops.push_back(VL); 5854 5855 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5856 Ops, Store->getMemoryVT(), 5857 Store->getMemOperand()); 5858 } 5859 } 5860 5861 return SDValue(); 5862 } 5863 5864 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5865 switch (ISDOpcode) { 5866 default: 5867 llvm_unreachable("Unhandled reduction"); 5868 case ISD::VECREDUCE_ADD: 5869 return RISCVISD::VECREDUCE_ADD_VL; 5870 case ISD::VECREDUCE_UMAX: 5871 return RISCVISD::VECREDUCE_UMAX_VL; 5872 case ISD::VECREDUCE_SMAX: 5873 return RISCVISD::VECREDUCE_SMAX_VL; 5874 case ISD::VECREDUCE_UMIN: 5875 return RISCVISD::VECREDUCE_UMIN_VL; 5876 case ISD::VECREDUCE_SMIN: 5877 return RISCVISD::VECREDUCE_SMIN_VL; 5878 case ISD::VECREDUCE_AND: 5879 return RISCVISD::VECREDUCE_AND_VL; 5880 case ISD::VECREDUCE_OR: 5881 return RISCVISD::VECREDUCE_OR_VL; 5882 case ISD::VECREDUCE_XOR: 5883 return RISCVISD::VECREDUCE_XOR_VL; 5884 } 5885 } 5886 5887 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5888 SelectionDAG &DAG, 5889 bool IsVP) const { 5890 SDLoc DL(Op); 5891 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5892 MVT VecVT = Vec.getSimpleValueType(); 5893 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5894 Op.getOpcode() == ISD::VECREDUCE_OR || 5895 Op.getOpcode() == ISD::VECREDUCE_XOR || 5896 Op.getOpcode() == ISD::VP_REDUCE_AND || 5897 Op.getOpcode() == ISD::VP_REDUCE_OR || 5898 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5899 "Unexpected reduction lowering"); 5900 5901 MVT XLenVT = Subtarget.getXLenVT(); 5902 assert(Op.getValueType() == XLenVT && 5903 "Expected reduction output to be legalized to XLenVT"); 5904 5905 MVT ContainerVT = VecVT; 5906 if (VecVT.isFixedLengthVector()) { 5907 ContainerVT = getContainerForFixedLengthVector(VecVT); 5908 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5909 } 5910 5911 SDValue Mask, VL; 5912 if (IsVP) { 5913 Mask = Op.getOperand(2); 5914 VL = Op.getOperand(3); 5915 } else { 5916 std::tie(Mask, VL) = 5917 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5918 } 5919 5920 unsigned BaseOpc; 5921 ISD::CondCode CC; 5922 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5923 5924 switch (Op.getOpcode()) { 5925 default: 5926 llvm_unreachable("Unhandled reduction"); 5927 case ISD::VECREDUCE_AND: 5928 case ISD::VP_REDUCE_AND: { 5929 // vcpop ~x == 0 5930 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5931 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5932 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5933 CC = ISD::SETEQ; 5934 BaseOpc = ISD::AND; 5935 break; 5936 } 5937 case ISD::VECREDUCE_OR: 5938 case ISD::VP_REDUCE_OR: 5939 // vcpop x != 0 5940 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5941 CC = ISD::SETNE; 5942 BaseOpc = ISD::OR; 5943 break; 5944 case ISD::VECREDUCE_XOR: 5945 case ISD::VP_REDUCE_XOR: { 5946 // ((vcpop x) & 1) != 0 5947 SDValue One = DAG.getConstant(1, DL, XLenVT); 5948 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5949 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5950 CC = ISD::SETNE; 5951 BaseOpc = ISD::XOR; 5952 break; 5953 } 5954 } 5955 5956 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5957 5958 if (!IsVP) 5959 return SetCC; 5960 5961 // Now include the start value in the operation. 5962 // Note that we must return the start value when no elements are operated 5963 // upon. The vcpop instructions we've emitted in each case above will return 5964 // 0 for an inactive vector, and so we've already received the neutral value: 5965 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5966 // can simply include the start value. 5967 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5968 } 5969 5970 static bool hasNonZeroAVL(SDValue AVL) { 5971 auto *RegisterAVL = dyn_cast<RegisterSDNode>(AVL); 5972 auto *ImmAVL = dyn_cast<ConstantSDNode>(AVL); 5973 return (RegisterAVL && RegisterAVL->getReg() == RISCV::X0) || 5974 (ImmAVL && ImmAVL->getZExtValue() >= 1); 5975 } 5976 5977 /// Helper to lower a reduction sequence of the form: 5978 /// scalar = reduce_op vec, scalar_start 5979 static SDValue lowerReductionSeq(unsigned RVVOpcode, MVT ResVT, 5980 SDValue StartValue, SDValue Vec, SDValue Mask, 5981 SDValue VL, SDLoc DL, SelectionDAG &DAG, 5982 const RISCVSubtarget &Subtarget) { 5983 const MVT VecVT = Vec.getSimpleValueType(); 5984 const MVT M1VT = getLMUL1VT(VecVT); 5985 const MVT XLenVT = Subtarget.getXLenVT(); 5986 const bool NonZeroAVL = hasNonZeroAVL(VL); 5987 5988 // The reduction needs an LMUL1 input; do the splat at either LMUL1 5989 // or the original VT if fractional. 5990 auto InnerVT = VecVT.bitsLE(M1VT) ? VecVT : M1VT; 5991 // We reuse the VL of the reduction to reduce vsetvli toggles if we can 5992 // prove it is non-zero. For the AVL=0 case, we need the scalar to 5993 // be the result of the reduction operation. 5994 auto InnerVL = NonZeroAVL ? VL : DAG.getConstant(1, DL, XLenVT); 5995 SDValue InitialValue = lowerScalarInsert(StartValue, InnerVL, InnerVT, DL, 5996 DAG, Subtarget); 5997 if (M1VT != InnerVT) 5998 InitialValue = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, M1VT, 5999 DAG.getUNDEF(M1VT), 6000 InitialValue, DAG.getConstant(0, DL, XLenVT)); 6001 SDValue PassThru = NonZeroAVL ? DAG.getUNDEF(M1VT) : InitialValue; 6002 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, PassThru, Vec, 6003 InitialValue, Mask, VL); 6004 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 6005 DAG.getConstant(0, DL, XLenVT)); 6006 } 6007 6008 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 6009 SelectionDAG &DAG) const { 6010 SDLoc DL(Op); 6011 SDValue Vec = Op.getOperand(0); 6012 EVT VecEVT = Vec.getValueType(); 6013 6014 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 6015 6016 // Due to ordering in legalize types we may have a vector type that needs to 6017 // be split. Do that manually so we can get down to a legal type. 6018 while (getTypeAction(*DAG.getContext(), VecEVT) == 6019 TargetLowering::TypeSplitVector) { 6020 auto [Lo, Hi] = DAG.SplitVector(Vec, DL); 6021 VecEVT = Lo.getValueType(); 6022 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 6023 } 6024 6025 // TODO: The type may need to be widened rather than split. Or widened before 6026 // it can be split. 6027 if (!isTypeLegal(VecEVT)) 6028 return SDValue(); 6029 6030 MVT VecVT = VecEVT.getSimpleVT(); 6031 MVT VecEltVT = VecVT.getVectorElementType(); 6032 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 6033 6034 MVT ContainerVT = VecVT; 6035 if (VecVT.isFixedLengthVector()) { 6036 ContainerVT = getContainerForFixedLengthVector(VecVT); 6037 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6038 } 6039 6040 auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 6041 6042 SDValue NeutralElem = 6043 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 6044 return lowerReductionSeq(RVVOpcode, Op.getSimpleValueType(), NeutralElem, Vec, 6045 Mask, VL, DL, DAG, Subtarget); 6046 } 6047 6048 // Given a reduction op, this function returns the matching reduction opcode, 6049 // the vector SDValue and the scalar SDValue required to lower this to a 6050 // RISCVISD node. 6051 static std::tuple<unsigned, SDValue, SDValue> 6052 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 6053 SDLoc DL(Op); 6054 auto Flags = Op->getFlags(); 6055 unsigned Opcode = Op.getOpcode(); 6056 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 6057 switch (Opcode) { 6058 default: 6059 llvm_unreachable("Unhandled reduction"); 6060 case ISD::VECREDUCE_FADD: { 6061 // Use positive zero if we can. It is cheaper to materialize. 6062 SDValue Zero = 6063 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 6064 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 6065 } 6066 case ISD::VECREDUCE_SEQ_FADD: 6067 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 6068 Op.getOperand(0)); 6069 case ISD::VECREDUCE_FMIN: 6070 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 6071 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 6072 case ISD::VECREDUCE_FMAX: 6073 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 6074 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 6075 } 6076 } 6077 6078 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 6079 SelectionDAG &DAG) const { 6080 SDLoc DL(Op); 6081 MVT VecEltVT = Op.getSimpleValueType(); 6082 6083 unsigned RVVOpcode; 6084 SDValue VectorVal, ScalarVal; 6085 std::tie(RVVOpcode, VectorVal, ScalarVal) = 6086 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 6087 MVT VecVT = VectorVal.getSimpleValueType(); 6088 6089 MVT ContainerVT = VecVT; 6090 if (VecVT.isFixedLengthVector()) { 6091 ContainerVT = getContainerForFixedLengthVector(VecVT); 6092 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 6093 } 6094 6095 auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 6096 return lowerReductionSeq(RVVOpcode, Op.getSimpleValueType(), ScalarVal, 6097 VectorVal, Mask, VL, DL, DAG, Subtarget); 6098 } 6099 6100 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 6101 switch (ISDOpcode) { 6102 default: 6103 llvm_unreachable("Unhandled reduction"); 6104 case ISD::VP_REDUCE_ADD: 6105 return RISCVISD::VECREDUCE_ADD_VL; 6106 case ISD::VP_REDUCE_UMAX: 6107 return RISCVISD::VECREDUCE_UMAX_VL; 6108 case ISD::VP_REDUCE_SMAX: 6109 return RISCVISD::VECREDUCE_SMAX_VL; 6110 case ISD::VP_REDUCE_UMIN: 6111 return RISCVISD::VECREDUCE_UMIN_VL; 6112 case ISD::VP_REDUCE_SMIN: 6113 return RISCVISD::VECREDUCE_SMIN_VL; 6114 case ISD::VP_REDUCE_AND: 6115 return RISCVISD::VECREDUCE_AND_VL; 6116 case ISD::VP_REDUCE_OR: 6117 return RISCVISD::VECREDUCE_OR_VL; 6118 case ISD::VP_REDUCE_XOR: 6119 return RISCVISD::VECREDUCE_XOR_VL; 6120 case ISD::VP_REDUCE_FADD: 6121 return RISCVISD::VECREDUCE_FADD_VL; 6122 case ISD::VP_REDUCE_SEQ_FADD: 6123 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 6124 case ISD::VP_REDUCE_FMAX: 6125 return RISCVISD::VECREDUCE_FMAX_VL; 6126 case ISD::VP_REDUCE_FMIN: 6127 return RISCVISD::VECREDUCE_FMIN_VL; 6128 } 6129 } 6130 6131 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 6132 SelectionDAG &DAG) const { 6133 SDLoc DL(Op); 6134 SDValue Vec = Op.getOperand(1); 6135 EVT VecEVT = Vec.getValueType(); 6136 6137 // TODO: The type may need to be widened rather than split. Or widened before 6138 // it can be split. 6139 if (!isTypeLegal(VecEVT)) 6140 return SDValue(); 6141 6142 MVT VecVT = VecEVT.getSimpleVT(); 6143 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 6144 6145 if (VecVT.isFixedLengthVector()) { 6146 auto ContainerVT = getContainerForFixedLengthVector(VecVT); 6147 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6148 } 6149 6150 SDValue VL = Op.getOperand(3); 6151 SDValue Mask = Op.getOperand(2); 6152 return lowerReductionSeq(RVVOpcode, Op.getSimpleValueType(), Op.getOperand(0), 6153 Vec, Mask, VL, DL, DAG, Subtarget); 6154 } 6155 6156 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 6157 SelectionDAG &DAG) const { 6158 SDValue Vec = Op.getOperand(0); 6159 SDValue SubVec = Op.getOperand(1); 6160 MVT VecVT = Vec.getSimpleValueType(); 6161 MVT SubVecVT = SubVec.getSimpleValueType(); 6162 6163 SDLoc DL(Op); 6164 MVT XLenVT = Subtarget.getXLenVT(); 6165 unsigned OrigIdx = Op.getConstantOperandVal(2); 6166 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6167 6168 // We don't have the ability to slide mask vectors up indexed by their i1 6169 // elements; the smallest we can do is i8. Often we are able to bitcast to 6170 // equivalent i8 vectors. Note that when inserting a fixed-length vector 6171 // into a scalable one, we might not necessarily have enough scalable 6172 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 6173 if (SubVecVT.getVectorElementType() == MVT::i1 && 6174 (OrigIdx != 0 || !Vec.isUndef())) { 6175 if (VecVT.getVectorMinNumElements() >= 8 && 6176 SubVecVT.getVectorMinNumElements() >= 8) { 6177 assert(OrigIdx % 8 == 0 && "Invalid index"); 6178 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 6179 SubVecVT.getVectorMinNumElements() % 8 == 0 && 6180 "Unexpected mask vector lowering"); 6181 OrigIdx /= 8; 6182 SubVecVT = 6183 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 6184 SubVecVT.isScalableVector()); 6185 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 6186 VecVT.isScalableVector()); 6187 Vec = DAG.getBitcast(VecVT, Vec); 6188 SubVec = DAG.getBitcast(SubVecVT, SubVec); 6189 } else { 6190 // We can't slide this mask vector up indexed by its i1 elements. 6191 // This poses a problem when we wish to insert a scalable vector which 6192 // can't be re-expressed as a larger type. Just choose the slow path and 6193 // extend to a larger type, then truncate back down. 6194 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 6195 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 6196 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 6197 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 6198 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 6199 Op.getOperand(2)); 6200 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 6201 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 6202 } 6203 } 6204 6205 // If the subvector vector is a fixed-length type, we cannot use subregister 6206 // manipulation to simplify the codegen; we don't know which register of a 6207 // LMUL group contains the specific subvector as we only know the minimum 6208 // register size. Therefore we must slide the vector group up the full 6209 // amount. 6210 if (SubVecVT.isFixedLengthVector()) { 6211 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 6212 return Op; 6213 MVT ContainerVT = VecVT; 6214 if (VecVT.isFixedLengthVector()) { 6215 ContainerVT = getContainerForFixedLengthVector(VecVT); 6216 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6217 } 6218 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 6219 DAG.getUNDEF(ContainerVT), SubVec, 6220 DAG.getConstant(0, DL, XLenVT)); 6221 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 6222 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 6223 return DAG.getBitcast(Op.getValueType(), SubVec); 6224 } 6225 SDValue Mask = 6226 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 6227 // Set the vector length to only the number of elements we care about. Note 6228 // that for slideup this includes the offset. 6229 SDValue VL = 6230 getVLOp(OrigIdx + SubVecVT.getVectorNumElements(), DL, DAG, Subtarget); 6231 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 6232 6233 // Use tail agnostic policy if OrigIdx is the last index of Vec. 6234 unsigned Policy = RISCVII::TAIL_UNDISTURBED_MASK_UNDISTURBED; 6235 if (VecVT.isFixedLengthVector() && 6236 OrigIdx + 1 == VecVT.getVectorNumElements()) 6237 Policy = RISCVII::TAIL_AGNOSTIC; 6238 SDValue Slideup = getVSlideup(DAG, Subtarget, DL, ContainerVT, Vec, SubVec, 6239 SlideupAmt, Mask, VL, Policy); 6240 if (VecVT.isFixedLengthVector()) 6241 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 6242 return DAG.getBitcast(Op.getValueType(), Slideup); 6243 } 6244 6245 unsigned SubRegIdx, RemIdx; 6246 std::tie(SubRegIdx, RemIdx) = 6247 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 6248 VecVT, SubVecVT, OrigIdx, TRI); 6249 6250 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 6251 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 6252 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 6253 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 6254 6255 // 1. If the Idx has been completely eliminated and this subvector's size is 6256 // a vector register or a multiple thereof, or the surrounding elements are 6257 // undef, then this is a subvector insert which naturally aligns to a vector 6258 // register. These can easily be handled using subregister manipulation. 6259 // 2. If the subvector is smaller than a vector register, then the insertion 6260 // must preserve the undisturbed elements of the register. We do this by 6261 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 6262 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 6263 // subvector within the vector register, and an INSERT_SUBVECTOR of that 6264 // LMUL=1 type back into the larger vector (resolving to another subregister 6265 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 6266 // to avoid allocating a large register group to hold our subvector. 6267 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 6268 return Op; 6269 6270 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 6271 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 6272 // (in our case undisturbed). This means we can set up a subvector insertion 6273 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 6274 // size of the subvector. 6275 MVT InterSubVT = VecVT; 6276 SDValue AlignedExtract = Vec; 6277 unsigned AlignedIdx = OrigIdx - RemIdx; 6278 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 6279 InterSubVT = getLMUL1VT(VecVT); 6280 // Extract a subvector equal to the nearest full vector register type. This 6281 // should resolve to a EXTRACT_SUBREG instruction. 6282 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 6283 DAG.getConstant(AlignedIdx, DL, XLenVT)); 6284 } 6285 6286 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 6287 // For scalable vectors this must be further multiplied by vscale. 6288 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 6289 6290 auto [Mask, VL] = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 6291 6292 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 6293 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 6294 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 6295 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 6296 6297 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 6298 DAG.getUNDEF(InterSubVT), SubVec, 6299 DAG.getConstant(0, DL, XLenVT)); 6300 6301 SDValue Slideup = getVSlideup(DAG, Subtarget, DL, InterSubVT, AlignedExtract, 6302 SubVec, SlideupAmt, Mask, VL); 6303 6304 // If required, insert this subvector back into the correct vector register. 6305 // This should resolve to an INSERT_SUBREG instruction. 6306 if (VecVT.bitsGT(InterSubVT)) 6307 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 6308 DAG.getConstant(AlignedIdx, DL, XLenVT)); 6309 6310 // We might have bitcast from a mask type: cast back to the original type if 6311 // required. 6312 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 6313 } 6314 6315 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 6316 SelectionDAG &DAG) const { 6317 SDValue Vec = Op.getOperand(0); 6318 MVT SubVecVT = Op.getSimpleValueType(); 6319 MVT VecVT = Vec.getSimpleValueType(); 6320 6321 SDLoc DL(Op); 6322 MVT XLenVT = Subtarget.getXLenVT(); 6323 unsigned OrigIdx = Op.getConstantOperandVal(1); 6324 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6325 6326 // We don't have the ability to slide mask vectors down indexed by their i1 6327 // elements; the smallest we can do is i8. Often we are able to bitcast to 6328 // equivalent i8 vectors. Note that when extracting a fixed-length vector 6329 // from a scalable one, we might not necessarily have enough scalable 6330 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 6331 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 6332 if (VecVT.getVectorMinNumElements() >= 8 && 6333 SubVecVT.getVectorMinNumElements() >= 8) { 6334 assert(OrigIdx % 8 == 0 && "Invalid index"); 6335 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 6336 SubVecVT.getVectorMinNumElements() % 8 == 0 && 6337 "Unexpected mask vector lowering"); 6338 OrigIdx /= 8; 6339 SubVecVT = 6340 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 6341 SubVecVT.isScalableVector()); 6342 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 6343 VecVT.isScalableVector()); 6344 Vec = DAG.getBitcast(VecVT, Vec); 6345 } else { 6346 // We can't slide this mask vector down, indexed by its i1 elements. 6347 // This poses a problem when we wish to extract a scalable vector which 6348 // can't be re-expressed as a larger type. Just choose the slow path and 6349 // extend to a larger type, then truncate back down. 6350 // TODO: We could probably improve this when extracting certain fixed 6351 // from fixed, where we can extract as i8 and shift the correct element 6352 // right to reach the desired subvector? 6353 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 6354 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 6355 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 6356 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 6357 Op.getOperand(1)); 6358 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 6359 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 6360 } 6361 } 6362 6363 // If the subvector vector is a fixed-length type, we cannot use subregister 6364 // manipulation to simplify the codegen; we don't know which register of a 6365 // LMUL group contains the specific subvector as we only know the minimum 6366 // register size. Therefore we must slide the vector group down the full 6367 // amount. 6368 if (SubVecVT.isFixedLengthVector()) { 6369 // With an index of 0 this is a cast-like subvector, which can be performed 6370 // with subregister operations. 6371 if (OrigIdx == 0) 6372 return Op; 6373 MVT ContainerVT = VecVT; 6374 if (VecVT.isFixedLengthVector()) { 6375 ContainerVT = getContainerForFixedLengthVector(VecVT); 6376 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6377 } 6378 SDValue Mask = 6379 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 6380 // Set the vector length to only the number of elements we care about. This 6381 // avoids sliding down elements we're going to discard straight away. 6382 SDValue VL = getVLOp(SubVecVT.getVectorNumElements(), DL, DAG, Subtarget); 6383 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 6384 SDValue Slidedown = 6385 getVSlidedown(DAG, Subtarget, DL, ContainerVT, 6386 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 6387 // Now we can use a cast-like subvector extract to get the result. 6388 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 6389 DAG.getConstant(0, DL, XLenVT)); 6390 return DAG.getBitcast(Op.getValueType(), Slidedown); 6391 } 6392 6393 unsigned SubRegIdx, RemIdx; 6394 std::tie(SubRegIdx, RemIdx) = 6395 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 6396 VecVT, SubVecVT, OrigIdx, TRI); 6397 6398 // If the Idx has been completely eliminated then this is a subvector extract 6399 // which naturally aligns to a vector register. These can easily be handled 6400 // using subregister manipulation. 6401 if (RemIdx == 0) 6402 return Op; 6403 6404 // Else we must shift our vector register directly to extract the subvector. 6405 // Do this using VSLIDEDOWN. 6406 6407 // If the vector type is an LMUL-group type, extract a subvector equal to the 6408 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 6409 // instruction. 6410 MVT InterSubVT = VecVT; 6411 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 6412 InterSubVT = getLMUL1VT(VecVT); 6413 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 6414 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 6415 } 6416 6417 // Slide this vector register down by the desired number of elements in order 6418 // to place the desired subvector starting at element 0. 6419 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 6420 // For scalable vectors this must be further multiplied by vscale. 6421 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 6422 6423 auto [Mask, VL] = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 6424 SDValue Slidedown = 6425 getVSlidedown(DAG, Subtarget, DL, InterSubVT, DAG.getUNDEF(InterSubVT), 6426 Vec, SlidedownAmt, Mask, VL); 6427 6428 // Now the vector is in the right position, extract our final subvector. This 6429 // should resolve to a COPY. 6430 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 6431 DAG.getConstant(0, DL, XLenVT)); 6432 6433 // We might have bitcast from a mask type: cast back to the original type if 6434 // required. 6435 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 6436 } 6437 6438 // Lower step_vector to the vid instruction. Any non-identity step value must 6439 // be accounted for my manual expansion. 6440 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 6441 SelectionDAG &DAG) const { 6442 SDLoc DL(Op); 6443 MVT VT = Op.getSimpleValueType(); 6444 assert(VT.isScalableVector() && "Expected scalable vector"); 6445 MVT XLenVT = Subtarget.getXLenVT(); 6446 auto [Mask, VL] = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 6447 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 6448 uint64_t StepValImm = Op.getConstantOperandVal(0); 6449 if (StepValImm != 1) { 6450 if (isPowerOf2_64(StepValImm)) { 6451 SDValue StepVal = 6452 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 6453 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT), VL); 6454 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 6455 } else { 6456 SDValue StepVal = lowerScalarSplat( 6457 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 6458 VL, VT, DL, DAG, Subtarget); 6459 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 6460 } 6461 } 6462 return StepVec; 6463 } 6464 6465 // Implement vector_reverse using vrgather.vv with indices determined by 6466 // subtracting the id of each element from (VLMAX-1). This will convert 6467 // the indices like so: 6468 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 6469 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 6470 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 6471 SelectionDAG &DAG) const { 6472 SDLoc DL(Op); 6473 MVT VecVT = Op.getSimpleValueType(); 6474 if (VecVT.getVectorElementType() == MVT::i1) { 6475 MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 6476 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0)); 6477 SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1); 6478 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Op2); 6479 } 6480 unsigned EltSize = VecVT.getScalarSizeInBits(); 6481 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 6482 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 6483 unsigned MaxVLMAX = 6484 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 6485 6486 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 6487 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 6488 6489 // If this is SEW=8 and VLMAX is potentially more than 256, we need 6490 // to use vrgatherei16.vv. 6491 // TODO: It's also possible to use vrgatherei16.vv for other types to 6492 // decrease register width for the index calculation. 6493 if (MaxVLMAX > 256 && EltSize == 8) { 6494 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 6495 // Reverse each half, then reassemble them in reverse order. 6496 // NOTE: It's also possible that after splitting that VLMAX no longer 6497 // requires vrgatherei16.vv. 6498 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 6499 auto [Lo, Hi] = DAG.SplitVectorOperand(Op.getNode(), 0); 6500 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VecVT); 6501 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 6502 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 6503 // Reassemble the low and high pieces reversed. 6504 // FIXME: This is a CONCAT_VECTORS. 6505 SDValue Res = 6506 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 6507 DAG.getIntPtrConstant(0, DL)); 6508 return DAG.getNode( 6509 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 6510 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 6511 } 6512 6513 // Just promote the int type to i16 which will double the LMUL. 6514 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 6515 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 6516 } 6517 6518 MVT XLenVT = Subtarget.getXLenVT(); 6519 auto [Mask, VL] = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 6520 6521 // Calculate VLMAX-1 for the desired SEW. 6522 unsigned MinElts = VecVT.getVectorMinNumElements(); 6523 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 6524 getVLOp(MinElts, DL, DAG, Subtarget)); 6525 SDValue VLMinus1 = 6526 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 6527 6528 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 6529 bool IsRV32E64 = 6530 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 6531 SDValue SplatVL; 6532 if (!IsRV32E64) 6533 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 6534 else 6535 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 6536 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 6537 6538 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 6539 SDValue Indices = DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, 6540 DAG.getUNDEF(IntVT), Mask, VL); 6541 6542 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, 6543 DAG.getUNDEF(VecVT), Mask, VL); 6544 } 6545 6546 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 6547 SelectionDAG &DAG) const { 6548 SDLoc DL(Op); 6549 SDValue V1 = Op.getOperand(0); 6550 SDValue V2 = Op.getOperand(1); 6551 MVT XLenVT = Subtarget.getXLenVT(); 6552 MVT VecVT = Op.getSimpleValueType(); 6553 6554 unsigned MinElts = VecVT.getVectorMinNumElements(); 6555 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 6556 getVLOp(MinElts, DL, DAG, Subtarget)); 6557 6558 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 6559 SDValue DownOffset, UpOffset; 6560 if (ImmValue >= 0) { 6561 // The operand is a TargetConstant, we need to rebuild it as a regular 6562 // constant. 6563 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 6564 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 6565 } else { 6566 // The operand is a TargetConstant, we need to rebuild it as a regular 6567 // constant rather than negating the original operand. 6568 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 6569 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 6570 } 6571 6572 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 6573 6574 SDValue SlideDown = 6575 getVSlidedown(DAG, Subtarget, DL, VecVT, DAG.getUNDEF(VecVT), V1, 6576 DownOffset, TrueMask, UpOffset); 6577 return getVSlideup(DAG, Subtarget, DL, VecVT, SlideDown, V2, UpOffset, 6578 TrueMask, DAG.getRegister(RISCV::X0, XLenVT), 6579 RISCVII::TAIL_AGNOSTIC); 6580 } 6581 6582 SDValue 6583 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 6584 SelectionDAG &DAG) const { 6585 SDLoc DL(Op); 6586 auto *Load = cast<LoadSDNode>(Op); 6587 6588 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 6589 Load->getMemoryVT(), 6590 *Load->getMemOperand()) && 6591 "Expecting a correctly-aligned load"); 6592 6593 MVT VT = Op.getSimpleValueType(); 6594 MVT XLenVT = Subtarget.getXLenVT(); 6595 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6596 6597 SDValue VL = getVLOp(VT.getVectorNumElements(), DL, DAG, Subtarget); 6598 6599 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 6600 SDValue IntID = DAG.getTargetConstant( 6601 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 6602 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 6603 if (!IsMaskOp) 6604 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6605 Ops.push_back(Load->getBasePtr()); 6606 Ops.push_back(VL); 6607 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6608 SDValue NewLoad = 6609 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 6610 Load->getMemoryVT(), Load->getMemOperand()); 6611 6612 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 6613 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 6614 } 6615 6616 SDValue 6617 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 6618 SelectionDAG &DAG) const { 6619 SDLoc DL(Op); 6620 auto *Store = cast<StoreSDNode>(Op); 6621 6622 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 6623 Store->getMemoryVT(), 6624 *Store->getMemOperand()) && 6625 "Expecting a correctly-aligned store"); 6626 6627 SDValue StoreVal = Store->getValue(); 6628 MVT VT = StoreVal.getSimpleValueType(); 6629 MVT XLenVT = Subtarget.getXLenVT(); 6630 6631 // If the size less than a byte, we need to pad with zeros to make a byte. 6632 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 6633 VT = MVT::v8i1; 6634 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 6635 DAG.getConstant(0, DL, VT), StoreVal, 6636 DAG.getIntPtrConstant(0, DL)); 6637 } 6638 6639 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6640 6641 SDValue VL = getVLOp(VT.getVectorNumElements(), DL, DAG, Subtarget); 6642 6643 SDValue NewValue = 6644 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 6645 6646 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 6647 SDValue IntID = DAG.getTargetConstant( 6648 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 6649 return DAG.getMemIntrinsicNode( 6650 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 6651 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 6652 Store->getMemoryVT(), Store->getMemOperand()); 6653 } 6654 6655 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 6656 SelectionDAG &DAG) const { 6657 SDLoc DL(Op); 6658 MVT VT = Op.getSimpleValueType(); 6659 6660 const auto *MemSD = cast<MemSDNode>(Op); 6661 EVT MemVT = MemSD->getMemoryVT(); 6662 MachineMemOperand *MMO = MemSD->getMemOperand(); 6663 SDValue Chain = MemSD->getChain(); 6664 SDValue BasePtr = MemSD->getBasePtr(); 6665 6666 SDValue Mask, PassThru, VL; 6667 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 6668 Mask = VPLoad->getMask(); 6669 PassThru = DAG.getUNDEF(VT); 6670 VL = VPLoad->getVectorLength(); 6671 } else { 6672 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 6673 Mask = MLoad->getMask(); 6674 PassThru = MLoad->getPassThru(); 6675 } 6676 6677 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6678 6679 MVT XLenVT = Subtarget.getXLenVT(); 6680 6681 MVT ContainerVT = VT; 6682 if (VT.isFixedLengthVector()) { 6683 ContainerVT = getContainerForFixedLengthVector(VT); 6684 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6685 if (!IsUnmasked) { 6686 MVT MaskVT = getMaskTypeFor(ContainerVT); 6687 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6688 } 6689 } 6690 6691 if (!VL) 6692 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6693 6694 unsigned IntID = 6695 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 6696 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6697 if (IsUnmasked) 6698 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6699 else 6700 Ops.push_back(PassThru); 6701 Ops.push_back(BasePtr); 6702 if (!IsUnmasked) 6703 Ops.push_back(Mask); 6704 Ops.push_back(VL); 6705 if (!IsUnmasked) 6706 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6707 6708 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6709 6710 SDValue Result = 6711 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6712 Chain = Result.getValue(1); 6713 6714 if (VT.isFixedLengthVector()) 6715 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6716 6717 return DAG.getMergeValues({Result, Chain}, DL); 6718 } 6719 6720 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 6721 SelectionDAG &DAG) const { 6722 SDLoc DL(Op); 6723 6724 const auto *MemSD = cast<MemSDNode>(Op); 6725 EVT MemVT = MemSD->getMemoryVT(); 6726 MachineMemOperand *MMO = MemSD->getMemOperand(); 6727 SDValue Chain = MemSD->getChain(); 6728 SDValue BasePtr = MemSD->getBasePtr(); 6729 SDValue Val, Mask, VL; 6730 6731 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 6732 Val = VPStore->getValue(); 6733 Mask = VPStore->getMask(); 6734 VL = VPStore->getVectorLength(); 6735 } else { 6736 const auto *MStore = cast<MaskedStoreSDNode>(Op); 6737 Val = MStore->getValue(); 6738 Mask = MStore->getMask(); 6739 } 6740 6741 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6742 6743 MVT VT = Val.getSimpleValueType(); 6744 MVT XLenVT = Subtarget.getXLenVT(); 6745 6746 MVT ContainerVT = VT; 6747 if (VT.isFixedLengthVector()) { 6748 ContainerVT = getContainerForFixedLengthVector(VT); 6749 6750 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6751 if (!IsUnmasked) { 6752 MVT MaskVT = getMaskTypeFor(ContainerVT); 6753 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6754 } 6755 } 6756 6757 if (!VL) 6758 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6759 6760 unsigned IntID = 6761 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 6762 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6763 Ops.push_back(Val); 6764 Ops.push_back(BasePtr); 6765 if (!IsUnmasked) 6766 Ops.push_back(Mask); 6767 Ops.push_back(VL); 6768 6769 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6770 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6771 } 6772 6773 SDValue 6774 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 6775 SelectionDAG &DAG) const { 6776 MVT InVT = Op.getOperand(0).getSimpleValueType(); 6777 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 6778 6779 MVT VT = Op.getSimpleValueType(); 6780 6781 SDValue Op1 = 6782 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 6783 SDValue Op2 = 6784 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6785 6786 SDLoc DL(Op); 6787 auto [Mask, VL] = getDefaultVLOps(VT.getVectorNumElements(), ContainerVT, DL, 6788 DAG, Subtarget); 6789 MVT MaskVT = getMaskTypeFor(ContainerVT); 6790 6791 SDValue Cmp = 6792 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, 6793 {Op1, Op2, Op.getOperand(2), DAG.getUNDEF(MaskVT), Mask, VL}); 6794 6795 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 6796 } 6797 6798 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 6799 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 6800 MVT VT = Op.getSimpleValueType(); 6801 6802 if (VT.getVectorElementType() == MVT::i1) 6803 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMergeOp*/ false, 6804 /*HasMask*/ false); 6805 6806 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMergeOp*/ true); 6807 } 6808 6809 SDValue 6810 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 6811 SelectionDAG &DAG) const { 6812 unsigned Opc; 6813 switch (Op.getOpcode()) { 6814 default: llvm_unreachable("Unexpected opcode!"); 6815 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 6816 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 6817 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 6818 } 6819 6820 return lowerToScalableOp(Op, DAG, Opc, /*HasMergeOp*/ true); 6821 } 6822 6823 // Lower vector ABS to smax(X, sub(0, X)). 6824 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 6825 SDLoc DL(Op); 6826 MVT VT = Op.getSimpleValueType(); 6827 SDValue X = Op.getOperand(0); 6828 6829 assert((Op.getOpcode() == ISD::VP_ABS || VT.isFixedLengthVector()) && 6830 "Unexpected type for ISD::ABS"); 6831 6832 MVT ContainerVT = VT; 6833 if (VT.isFixedLengthVector()) { 6834 ContainerVT = getContainerForFixedLengthVector(VT); 6835 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6836 } 6837 6838 SDValue Mask, VL; 6839 if (Op->getOpcode() == ISD::VP_ABS) { 6840 Mask = Op->getOperand(1); 6841 VL = Op->getOperand(2); 6842 } else 6843 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6844 6845 SDValue SplatZero = DAG.getNode( 6846 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6847 DAG.getConstant(0, DL, Subtarget.getXLenVT()), VL); 6848 SDValue NegX = DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, 6849 DAG.getUNDEF(ContainerVT), Mask, VL); 6850 SDValue Max = DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, 6851 DAG.getUNDEF(ContainerVT), Mask, VL); 6852 6853 if (VT.isFixedLengthVector()) 6854 Max = convertFromScalableVector(VT, Max, DAG, Subtarget); 6855 return Max; 6856 } 6857 6858 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6859 SDValue Op, SelectionDAG &DAG) const { 6860 SDLoc DL(Op); 6861 MVT VT = Op.getSimpleValueType(); 6862 SDValue Mag = Op.getOperand(0); 6863 SDValue Sign = Op.getOperand(1); 6864 assert(Mag.getValueType() == Sign.getValueType() && 6865 "Can only handle COPYSIGN with matching types."); 6866 6867 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6868 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6869 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6870 6871 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6872 6873 SDValue CopySign = DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, 6874 Sign, DAG.getUNDEF(ContainerVT), Mask, VL); 6875 6876 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6877 } 6878 6879 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6880 SDValue Op, SelectionDAG &DAG) const { 6881 MVT VT = Op.getSimpleValueType(); 6882 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6883 6884 MVT I1ContainerVT = 6885 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6886 6887 SDValue CC = 6888 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6889 SDValue Op1 = 6890 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6891 SDValue Op2 = 6892 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6893 6894 SDLoc DL(Op); 6895 SDValue VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6896 6897 SDValue Select = 6898 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6899 6900 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6901 } 6902 6903 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6904 unsigned NewOpc, bool HasMergeOp, 6905 bool HasMask) const { 6906 MVT VT = Op.getSimpleValueType(); 6907 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6908 6909 // Create list of operands by converting existing ones to scalable types. 6910 SmallVector<SDValue, 6> Ops; 6911 for (const SDValue &V : Op->op_values()) { 6912 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6913 6914 // Pass through non-vector operands. 6915 if (!V.getValueType().isVector()) { 6916 Ops.push_back(V); 6917 continue; 6918 } 6919 6920 // "cast" fixed length vector to a scalable vector. 6921 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6922 "Only fixed length vectors are supported!"); 6923 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6924 } 6925 6926 SDLoc DL(Op); 6927 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6928 if (HasMergeOp) 6929 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6930 if (HasMask) 6931 Ops.push_back(Mask); 6932 Ops.push_back(VL); 6933 6934 SDValue ScalableRes = 6935 DAG.getNode(NewOpc, DL, ContainerVT, Ops, Op->getFlags()); 6936 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6937 } 6938 6939 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6940 // * Operands of each node are assumed to be in the same order. 6941 // * The EVL operand is promoted from i32 to i64 on RV64. 6942 // * Fixed-length vectors are converted to their scalable-vector container 6943 // types. 6944 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6945 unsigned RISCVISDOpc, 6946 bool HasMergeOp) const { 6947 SDLoc DL(Op); 6948 MVT VT = Op.getSimpleValueType(); 6949 SmallVector<SDValue, 4> Ops; 6950 6951 MVT ContainerVT = VT; 6952 if (VT.isFixedLengthVector()) 6953 ContainerVT = getContainerForFixedLengthVector(VT); 6954 6955 for (const auto &OpIdx : enumerate(Op->ops())) { 6956 SDValue V = OpIdx.value(); 6957 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6958 // Add dummy merge value before the mask. 6959 if (HasMergeOp && *ISD::getVPMaskIdx(Op.getOpcode()) == OpIdx.index()) 6960 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6961 // Pass through operands which aren't fixed-length vectors. 6962 if (!V.getValueType().isFixedLengthVector()) { 6963 Ops.push_back(V); 6964 continue; 6965 } 6966 // "cast" fixed length vector to a scalable vector. 6967 MVT OpVT = V.getSimpleValueType(); 6968 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6969 assert(useRVVForFixedLengthVectorVT(OpVT) && 6970 "Only fixed length vectors are supported!"); 6971 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6972 } 6973 6974 if (!VT.isFixedLengthVector()) 6975 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags()); 6976 6977 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags()); 6978 6979 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6980 } 6981 6982 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6983 SelectionDAG &DAG) const { 6984 SDLoc DL(Op); 6985 MVT VT = Op.getSimpleValueType(); 6986 6987 SDValue Src = Op.getOperand(0); 6988 // NOTE: Mask is dropped. 6989 SDValue VL = Op.getOperand(2); 6990 6991 MVT ContainerVT = VT; 6992 if (VT.isFixedLengthVector()) { 6993 ContainerVT = getContainerForFixedLengthVector(VT); 6994 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6995 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6996 } 6997 6998 MVT XLenVT = Subtarget.getXLenVT(); 6999 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 7000 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7001 DAG.getUNDEF(ContainerVT), Zero, VL); 7002 7003 SDValue SplatValue = DAG.getConstant( 7004 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 7005 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7006 DAG.getUNDEF(ContainerVT), SplatValue, VL); 7007 7008 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 7009 Splat, ZeroSplat, VL); 7010 if (!VT.isFixedLengthVector()) 7011 return Result; 7012 return convertFromScalableVector(VT, Result, DAG, Subtarget); 7013 } 7014 7015 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 7016 SelectionDAG &DAG) const { 7017 SDLoc DL(Op); 7018 MVT VT = Op.getSimpleValueType(); 7019 7020 SDValue Op1 = Op.getOperand(0); 7021 SDValue Op2 = Op.getOperand(1); 7022 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 7023 // NOTE: Mask is dropped. 7024 SDValue VL = Op.getOperand(4); 7025 7026 MVT ContainerVT = VT; 7027 if (VT.isFixedLengthVector()) { 7028 ContainerVT = getContainerForFixedLengthVector(VT); 7029 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 7030 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 7031 } 7032 7033 SDValue Result; 7034 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 7035 7036 switch (Condition) { 7037 default: 7038 break; 7039 // X != Y --> (X^Y) 7040 case ISD::SETNE: 7041 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 7042 break; 7043 // X == Y --> ~(X^Y) 7044 case ISD::SETEQ: { 7045 SDValue Temp = 7046 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 7047 Result = 7048 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 7049 break; 7050 } 7051 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 7052 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 7053 case ISD::SETGT: 7054 case ISD::SETULT: { 7055 SDValue Temp = 7056 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 7057 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 7058 break; 7059 } 7060 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 7061 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 7062 case ISD::SETLT: 7063 case ISD::SETUGT: { 7064 SDValue Temp = 7065 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 7066 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 7067 break; 7068 } 7069 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 7070 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 7071 case ISD::SETGE: 7072 case ISD::SETULE: { 7073 SDValue Temp = 7074 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 7075 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 7076 break; 7077 } 7078 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 7079 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 7080 case ISD::SETLE: 7081 case ISD::SETUGE: { 7082 SDValue Temp = 7083 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 7084 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 7085 break; 7086 } 7087 } 7088 7089 if (!VT.isFixedLengthVector()) 7090 return Result; 7091 return convertFromScalableVector(VT, Result, DAG, Subtarget); 7092 } 7093 7094 // Lower Floating-Point/Integer Type-Convert VP SDNodes 7095 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 7096 unsigned RISCVISDOpc) const { 7097 SDLoc DL(Op); 7098 7099 SDValue Src = Op.getOperand(0); 7100 SDValue Mask = Op.getOperand(1); 7101 SDValue VL = Op.getOperand(2); 7102 7103 MVT DstVT = Op.getSimpleValueType(); 7104 MVT SrcVT = Src.getSimpleValueType(); 7105 if (DstVT.isFixedLengthVector()) { 7106 DstVT = getContainerForFixedLengthVector(DstVT); 7107 SrcVT = getContainerForFixedLengthVector(SrcVT); 7108 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 7109 MVT MaskVT = getMaskTypeFor(DstVT); 7110 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 7111 } 7112 7113 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 7114 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 7115 7116 SDValue Result; 7117 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 7118 if (SrcVT.isInteger()) { 7119 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 7120 7121 unsigned RISCVISDExtOpc = RISCVISDOpc == RISCVISD::SINT_TO_FP_VL 7122 ? RISCVISD::VSEXT_VL 7123 : RISCVISD::VZEXT_VL; 7124 7125 // Do we need to do any pre-widening before converting? 7126 if (SrcEltSize == 1) { 7127 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 7128 MVT XLenVT = Subtarget.getXLenVT(); 7129 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 7130 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 7131 DAG.getUNDEF(IntVT), Zero, VL); 7132 SDValue One = DAG.getConstant( 7133 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 7134 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 7135 DAG.getUNDEF(IntVT), One, VL); 7136 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 7137 ZeroSplat, VL); 7138 } else if (DstEltSize > (2 * SrcEltSize)) { 7139 // Widen before converting. 7140 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 7141 DstVT.getVectorElementCount()); 7142 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 7143 } 7144 7145 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 7146 } else { 7147 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 7148 "Wrong input/output vector types"); 7149 7150 // Convert f16 to f32 then convert f32 to i64. 7151 if (DstEltSize > (2 * SrcEltSize)) { 7152 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 7153 MVT InterimFVT = 7154 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 7155 Src = 7156 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 7157 } 7158 7159 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 7160 } 7161 } else { // Narrowing + Conversion 7162 if (SrcVT.isInteger()) { 7163 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 7164 // First do a narrowing convert to an FP type half the size, then round 7165 // the FP type to a small FP type if needed. 7166 7167 MVT InterimFVT = DstVT; 7168 if (SrcEltSize > (2 * DstEltSize)) { 7169 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 7170 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 7171 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 7172 } 7173 7174 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 7175 7176 if (InterimFVT != DstVT) { 7177 Src = Result; 7178 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 7179 } 7180 } else { 7181 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 7182 "Wrong input/output vector types"); 7183 // First do a narrowing conversion to an integer half the size, then 7184 // truncate if needed. 7185 7186 if (DstEltSize == 1) { 7187 // First convert to the same size integer, then convert to mask using 7188 // setcc. 7189 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 7190 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 7191 DstVT.getVectorElementCount()); 7192 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 7193 7194 // Compare the integer result to 0. The integer should be 0 or 1/-1, 7195 // otherwise the conversion was undefined. 7196 MVT XLenVT = Subtarget.getXLenVT(); 7197 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 7198 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 7199 DAG.getUNDEF(InterimIVT), SplatZero, VL); 7200 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, 7201 {Result, SplatZero, DAG.getCondCode(ISD::SETNE), 7202 DAG.getUNDEF(DstVT), Mask, VL}); 7203 } else { 7204 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 7205 DstVT.getVectorElementCount()); 7206 7207 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 7208 7209 while (InterimIVT != DstVT) { 7210 SrcEltSize /= 2; 7211 Src = Result; 7212 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 7213 DstVT.getVectorElementCount()); 7214 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 7215 Src, Mask, VL); 7216 } 7217 } 7218 } 7219 } 7220 7221 MVT VT = Op.getSimpleValueType(); 7222 if (!VT.isFixedLengthVector()) 7223 return Result; 7224 return convertFromScalableVector(VT, Result, DAG, Subtarget); 7225 } 7226 7227 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 7228 unsigned MaskOpc, 7229 unsigned VecOpc) const { 7230 MVT VT = Op.getSimpleValueType(); 7231 if (VT.getVectorElementType() != MVT::i1) 7232 return lowerVPOp(Op, DAG, VecOpc, true); 7233 7234 // It is safe to drop mask parameter as masked-off elements are undef. 7235 SDValue Op1 = Op->getOperand(0); 7236 SDValue Op2 = Op->getOperand(1); 7237 SDValue VL = Op->getOperand(3); 7238 7239 MVT ContainerVT = VT; 7240 const bool IsFixed = VT.isFixedLengthVector(); 7241 if (IsFixed) { 7242 ContainerVT = getContainerForFixedLengthVector(VT); 7243 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 7244 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 7245 } 7246 7247 SDLoc DL(Op); 7248 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 7249 if (!IsFixed) 7250 return Val; 7251 return convertFromScalableVector(VT, Val, DAG, Subtarget); 7252 } 7253 7254 SDValue RISCVTargetLowering::lowerVPStridedLoad(SDValue Op, 7255 SelectionDAG &DAG) const { 7256 SDLoc DL(Op); 7257 MVT XLenVT = Subtarget.getXLenVT(); 7258 MVT VT = Op.getSimpleValueType(); 7259 MVT ContainerVT = VT; 7260 if (VT.isFixedLengthVector()) 7261 ContainerVT = getContainerForFixedLengthVector(VT); 7262 7263 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 7264 7265 auto *VPNode = cast<VPStridedLoadSDNode>(Op); 7266 // Check if the mask is known to be all ones 7267 SDValue Mask = VPNode->getMask(); 7268 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 7269 7270 SDValue IntID = DAG.getTargetConstant(IsUnmasked ? Intrinsic::riscv_vlse 7271 : Intrinsic::riscv_vlse_mask, 7272 DL, XLenVT); 7273 SmallVector<SDValue, 8> Ops{VPNode->getChain(), IntID, 7274 DAG.getUNDEF(ContainerVT), VPNode->getBasePtr(), 7275 VPNode->getStride()}; 7276 if (!IsUnmasked) { 7277 if (VT.isFixedLengthVector()) { 7278 MVT MaskVT = ContainerVT.changeVectorElementType(MVT::i1); 7279 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 7280 } 7281 Ops.push_back(Mask); 7282 } 7283 Ops.push_back(VPNode->getVectorLength()); 7284 if (!IsUnmasked) { 7285 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 7286 Ops.push_back(Policy); 7287 } 7288 7289 SDValue Result = 7290 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 7291 VPNode->getMemoryVT(), VPNode->getMemOperand()); 7292 SDValue Chain = Result.getValue(1); 7293 7294 if (VT.isFixedLengthVector()) 7295 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 7296 7297 return DAG.getMergeValues({Result, Chain}, DL); 7298 } 7299 7300 SDValue RISCVTargetLowering::lowerVPStridedStore(SDValue Op, 7301 SelectionDAG &DAG) const { 7302 SDLoc DL(Op); 7303 MVT XLenVT = Subtarget.getXLenVT(); 7304 7305 auto *VPNode = cast<VPStridedStoreSDNode>(Op); 7306 SDValue StoreVal = VPNode->getValue(); 7307 MVT VT = StoreVal.getSimpleValueType(); 7308 MVT ContainerVT = VT; 7309 if (VT.isFixedLengthVector()) { 7310 ContainerVT = getContainerForFixedLengthVector(VT); 7311 StoreVal = convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 7312 } 7313 7314 // Check if the mask is known to be all ones 7315 SDValue Mask = VPNode->getMask(); 7316 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 7317 7318 SDValue IntID = DAG.getTargetConstant(IsUnmasked ? Intrinsic::riscv_vsse 7319 : Intrinsic::riscv_vsse_mask, 7320 DL, XLenVT); 7321 SmallVector<SDValue, 8> Ops{VPNode->getChain(), IntID, StoreVal, 7322 VPNode->getBasePtr(), VPNode->getStride()}; 7323 if (!IsUnmasked) { 7324 if (VT.isFixedLengthVector()) { 7325 MVT MaskVT = ContainerVT.changeVectorElementType(MVT::i1); 7326 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 7327 } 7328 Ops.push_back(Mask); 7329 } 7330 Ops.push_back(VPNode->getVectorLength()); 7331 7332 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, VPNode->getVTList(), 7333 Ops, VPNode->getMemoryVT(), 7334 VPNode->getMemOperand()); 7335 } 7336 7337 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 7338 // matched to a RVV indexed load. The RVV indexed load instructions only 7339 // support the "unsigned unscaled" addressing mode; indices are implicitly 7340 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 7341 // signed or scaled indexing is extended to the XLEN value type and scaled 7342 // accordingly. 7343 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 7344 SelectionDAG &DAG) const { 7345 SDLoc DL(Op); 7346 MVT VT = Op.getSimpleValueType(); 7347 7348 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 7349 EVT MemVT = MemSD->getMemoryVT(); 7350 MachineMemOperand *MMO = MemSD->getMemOperand(); 7351 SDValue Chain = MemSD->getChain(); 7352 SDValue BasePtr = MemSD->getBasePtr(); 7353 7354 ISD::LoadExtType LoadExtType; 7355 SDValue Index, Mask, PassThru, VL; 7356 7357 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 7358 Index = VPGN->getIndex(); 7359 Mask = VPGN->getMask(); 7360 PassThru = DAG.getUNDEF(VT); 7361 VL = VPGN->getVectorLength(); 7362 // VP doesn't support extending loads. 7363 LoadExtType = ISD::NON_EXTLOAD; 7364 } else { 7365 // Else it must be a MGATHER. 7366 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 7367 Index = MGN->getIndex(); 7368 Mask = MGN->getMask(); 7369 PassThru = MGN->getPassThru(); 7370 LoadExtType = MGN->getExtensionType(); 7371 } 7372 7373 MVT IndexVT = Index.getSimpleValueType(); 7374 MVT XLenVT = Subtarget.getXLenVT(); 7375 7376 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 7377 "Unexpected VTs!"); 7378 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 7379 // Targets have to explicitly opt-in for extending vector loads. 7380 assert(LoadExtType == ISD::NON_EXTLOAD && 7381 "Unexpected extending MGATHER/VP_GATHER"); 7382 (void)LoadExtType; 7383 7384 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 7385 // the selection of the masked intrinsics doesn't do this for us. 7386 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 7387 7388 MVT ContainerVT = VT; 7389 if (VT.isFixedLengthVector()) { 7390 ContainerVT = getContainerForFixedLengthVector(VT); 7391 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 7392 ContainerVT.getVectorElementCount()); 7393 7394 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 7395 7396 if (!IsUnmasked) { 7397 MVT MaskVT = getMaskTypeFor(ContainerVT); 7398 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 7399 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 7400 } 7401 } 7402 7403 if (!VL) 7404 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 7405 7406 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 7407 IndexVT = IndexVT.changeVectorElementType(XLenVT); 7408 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 7409 VL); 7410 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 7411 TrueMask, VL); 7412 } 7413 7414 unsigned IntID = 7415 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 7416 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 7417 if (IsUnmasked) 7418 Ops.push_back(DAG.getUNDEF(ContainerVT)); 7419 else 7420 Ops.push_back(PassThru); 7421 Ops.push_back(BasePtr); 7422 Ops.push_back(Index); 7423 if (!IsUnmasked) 7424 Ops.push_back(Mask); 7425 Ops.push_back(VL); 7426 if (!IsUnmasked) 7427 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 7428 7429 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 7430 SDValue Result = 7431 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 7432 Chain = Result.getValue(1); 7433 7434 if (VT.isFixedLengthVector()) 7435 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 7436 7437 return DAG.getMergeValues({Result, Chain}, DL); 7438 } 7439 7440 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 7441 // matched to a RVV indexed store. The RVV indexed store instructions only 7442 // support the "unsigned unscaled" addressing mode; indices are implicitly 7443 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 7444 // signed or scaled indexing is extended to the XLEN value type and scaled 7445 // accordingly. 7446 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 7447 SelectionDAG &DAG) const { 7448 SDLoc DL(Op); 7449 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 7450 EVT MemVT = MemSD->getMemoryVT(); 7451 MachineMemOperand *MMO = MemSD->getMemOperand(); 7452 SDValue Chain = MemSD->getChain(); 7453 SDValue BasePtr = MemSD->getBasePtr(); 7454 7455 bool IsTruncatingStore = false; 7456 SDValue Index, Mask, Val, VL; 7457 7458 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 7459 Index = VPSN->getIndex(); 7460 Mask = VPSN->getMask(); 7461 Val = VPSN->getValue(); 7462 VL = VPSN->getVectorLength(); 7463 // VP doesn't support truncating stores. 7464 IsTruncatingStore = false; 7465 } else { 7466 // Else it must be a MSCATTER. 7467 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 7468 Index = MSN->getIndex(); 7469 Mask = MSN->getMask(); 7470 Val = MSN->getValue(); 7471 IsTruncatingStore = MSN->isTruncatingStore(); 7472 } 7473 7474 MVT VT = Val.getSimpleValueType(); 7475 MVT IndexVT = Index.getSimpleValueType(); 7476 MVT XLenVT = Subtarget.getXLenVT(); 7477 7478 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 7479 "Unexpected VTs!"); 7480 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 7481 // Targets have to explicitly opt-in for extending vector loads and 7482 // truncating vector stores. 7483 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 7484 (void)IsTruncatingStore; 7485 7486 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 7487 // the selection of the masked intrinsics doesn't do this for us. 7488 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 7489 7490 MVT ContainerVT = VT; 7491 if (VT.isFixedLengthVector()) { 7492 ContainerVT = getContainerForFixedLengthVector(VT); 7493 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 7494 ContainerVT.getVectorElementCount()); 7495 7496 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 7497 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 7498 7499 if (!IsUnmasked) { 7500 MVT MaskVT = getMaskTypeFor(ContainerVT); 7501 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 7502 } 7503 } 7504 7505 if (!VL) 7506 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 7507 7508 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 7509 IndexVT = IndexVT.changeVectorElementType(XLenVT); 7510 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 7511 VL); 7512 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 7513 TrueMask, VL); 7514 } 7515 7516 unsigned IntID = 7517 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 7518 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 7519 Ops.push_back(Val); 7520 Ops.push_back(BasePtr); 7521 Ops.push_back(Index); 7522 if (!IsUnmasked) 7523 Ops.push_back(Mask); 7524 Ops.push_back(VL); 7525 7526 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 7527 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 7528 } 7529 7530 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 7531 SelectionDAG &DAG) const { 7532 const MVT XLenVT = Subtarget.getXLenVT(); 7533 SDLoc DL(Op); 7534 SDValue Chain = Op->getOperand(0); 7535 SDValue SysRegNo = DAG.getTargetConstant( 7536 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 7537 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 7538 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 7539 7540 // Encoding used for rounding mode in RISCV differs from that used in 7541 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 7542 // table, which consists of a sequence of 4-bit fields, each representing 7543 // corresponding FLT_ROUNDS mode. 7544 static const int Table = 7545 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 7546 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 7547 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 7548 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 7549 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 7550 7551 SDValue Shift = 7552 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 7553 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 7554 DAG.getConstant(Table, DL, XLenVT), Shift); 7555 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 7556 DAG.getConstant(7, DL, XLenVT)); 7557 7558 return DAG.getMergeValues({Masked, Chain}, DL); 7559 } 7560 7561 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 7562 SelectionDAG &DAG) const { 7563 const MVT XLenVT = Subtarget.getXLenVT(); 7564 SDLoc DL(Op); 7565 SDValue Chain = Op->getOperand(0); 7566 SDValue RMValue = Op->getOperand(1); 7567 SDValue SysRegNo = DAG.getTargetConstant( 7568 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 7569 7570 // Encoding used for rounding mode in RISCV differs from that used in 7571 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 7572 // a table, which consists of a sequence of 4-bit fields, each representing 7573 // corresponding RISCV mode. 7574 static const unsigned Table = 7575 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 7576 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 7577 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 7578 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 7579 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 7580 7581 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 7582 DAG.getConstant(2, DL, XLenVT)); 7583 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 7584 DAG.getConstant(Table, DL, XLenVT), Shift); 7585 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 7586 DAG.getConstant(0x7, DL, XLenVT)); 7587 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 7588 RMValue); 7589 } 7590 7591 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op, 7592 SelectionDAG &DAG) const { 7593 MachineFunction &MF = DAG.getMachineFunction(); 7594 7595 bool isRISCV64 = Subtarget.is64Bit(); 7596 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7597 7598 int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false); 7599 return DAG.getFrameIndex(FI, PtrVT); 7600 } 7601 7602 // Returns the opcode of the target-specific SDNode that implements the 32-bit 7603 // form of the given Opcode. 7604 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 7605 switch (Opcode) { 7606 default: 7607 llvm_unreachable("Unexpected opcode"); 7608 case ISD::SHL: 7609 return RISCVISD::SLLW; 7610 case ISD::SRA: 7611 return RISCVISD::SRAW; 7612 case ISD::SRL: 7613 return RISCVISD::SRLW; 7614 case ISD::SDIV: 7615 return RISCVISD::DIVW; 7616 case ISD::UDIV: 7617 return RISCVISD::DIVUW; 7618 case ISD::UREM: 7619 return RISCVISD::REMUW; 7620 case ISD::ROTL: 7621 return RISCVISD::ROLW; 7622 case ISD::ROTR: 7623 return RISCVISD::RORW; 7624 } 7625 } 7626 7627 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 7628 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 7629 // otherwise be promoted to i64, making it difficult to select the 7630 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 7631 // type i8/i16/i32 is lost. 7632 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 7633 unsigned ExtOpc = ISD::ANY_EXTEND) { 7634 SDLoc DL(N); 7635 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 7636 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 7637 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 7638 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 7639 // ReplaceNodeResults requires we maintain the same type for the return value. 7640 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 7641 } 7642 7643 // Converts the given 32-bit operation to a i64 operation with signed extension 7644 // semantic to reduce the signed extension instructions. 7645 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 7646 SDLoc DL(N); 7647 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7648 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7649 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 7650 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 7651 DAG.getValueType(MVT::i32)); 7652 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 7653 } 7654 7655 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 7656 SmallVectorImpl<SDValue> &Results, 7657 SelectionDAG &DAG) const { 7658 SDLoc DL(N); 7659 switch (N->getOpcode()) { 7660 default: 7661 llvm_unreachable("Don't know how to custom type legalize this operation!"); 7662 case ISD::STRICT_FP_TO_SINT: 7663 case ISD::STRICT_FP_TO_UINT: 7664 case ISD::FP_TO_SINT: 7665 case ISD::FP_TO_UINT: { 7666 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7667 "Unexpected custom legalisation"); 7668 bool IsStrict = N->isStrictFPOpcode(); 7669 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 7670 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 7671 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 7672 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 7673 TargetLowering::TypeSoftenFloat) { 7674 if (!isTypeLegal(Op0.getValueType())) 7675 return; 7676 if (IsStrict) { 7677 SDValue Chain = N->getOperand(0); 7678 // In absense of Zfh, promote f16 to f32, then convert. 7679 if (Op0.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) { 7680 Op0 = DAG.getNode(ISD::STRICT_FP_EXTEND, DL, {MVT::f32, MVT::Other}, 7681 {Chain, Op0}); 7682 Chain = Op0.getValue(1); 7683 } 7684 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 7685 : RISCVISD::STRICT_FCVT_WU_RV64; 7686 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 7687 SDValue Res = DAG.getNode( 7688 Opc, DL, VTs, Chain, Op0, 7689 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 7690 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7691 Results.push_back(Res.getValue(1)); 7692 return; 7693 } 7694 // In absense of Zfh, promote f16 to f32, then convert. 7695 if (Op0.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7696 Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op0); 7697 7698 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7699 SDValue Res = 7700 DAG.getNode(Opc, DL, MVT::i64, Op0, 7701 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 7702 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7703 return; 7704 } 7705 // If the FP type needs to be softened, emit a library call using the 'si' 7706 // version. If we left it to default legalization we'd end up with 'di'. If 7707 // the FP type doesn't need to be softened just let generic type 7708 // legalization promote the result type. 7709 RTLIB::Libcall LC; 7710 if (IsSigned) 7711 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 7712 else 7713 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 7714 MakeLibCallOptions CallOptions; 7715 EVT OpVT = Op0.getValueType(); 7716 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 7717 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 7718 SDValue Result; 7719 std::tie(Result, Chain) = 7720 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 7721 Results.push_back(Result); 7722 if (IsStrict) 7723 Results.push_back(Chain); 7724 break; 7725 } 7726 case ISD::READCYCLECOUNTER: { 7727 assert(!Subtarget.is64Bit() && 7728 "READCYCLECOUNTER only has custom type legalization on riscv32"); 7729 7730 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 7731 SDValue RCW = 7732 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 7733 7734 Results.push_back( 7735 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 7736 Results.push_back(RCW.getValue(2)); 7737 break; 7738 } 7739 case ISD::LOAD: { 7740 if (!ISD::isNON_EXTLoad(N)) 7741 return; 7742 7743 // Use a SEXTLOAD instead of the default EXTLOAD. Similar to the 7744 // sext_inreg we emit for ADD/SUB/MUL/SLLI. 7745 LoadSDNode *Ld = cast<LoadSDNode>(N); 7746 7747 SDLoc dl(N); 7748 SDValue Res = DAG.getExtLoad(ISD::SEXTLOAD, dl, MVT::i64, Ld->getChain(), 7749 Ld->getBasePtr(), Ld->getMemoryVT(), 7750 Ld->getMemOperand()); 7751 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Res)); 7752 Results.push_back(Res.getValue(1)); 7753 return; 7754 } 7755 case ISD::MUL: { 7756 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 7757 unsigned XLen = Subtarget.getXLen(); 7758 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 7759 if (Size > XLen) { 7760 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 7761 SDValue LHS = N->getOperand(0); 7762 SDValue RHS = N->getOperand(1); 7763 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 7764 7765 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 7766 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 7767 // We need exactly one side to be unsigned. 7768 if (LHSIsU == RHSIsU) 7769 return; 7770 7771 auto MakeMULPair = [&](SDValue S, SDValue U) { 7772 MVT XLenVT = Subtarget.getXLenVT(); 7773 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 7774 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 7775 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 7776 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 7777 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 7778 }; 7779 7780 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 7781 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 7782 7783 // The other operand should be signed, but still prefer MULH when 7784 // possible. 7785 if (RHSIsU && LHSIsS && !RHSIsS) 7786 Results.push_back(MakeMULPair(LHS, RHS)); 7787 else if (LHSIsU && RHSIsS && !LHSIsS) 7788 Results.push_back(MakeMULPair(RHS, LHS)); 7789 7790 return; 7791 } 7792 [[fallthrough]]; 7793 } 7794 case ISD::ADD: 7795 case ISD::SUB: 7796 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7797 "Unexpected custom legalisation"); 7798 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 7799 break; 7800 case ISD::SHL: 7801 case ISD::SRA: 7802 case ISD::SRL: 7803 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7804 "Unexpected custom legalisation"); 7805 if (N->getOperand(1).getOpcode() != ISD::Constant) { 7806 // If we can use a BSET instruction, allow default promotion to apply. 7807 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 7808 isOneConstant(N->getOperand(0))) 7809 break; 7810 Results.push_back(customLegalizeToWOp(N, DAG)); 7811 break; 7812 } 7813 7814 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 7815 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 7816 // shift amount. 7817 if (N->getOpcode() == ISD::SHL) { 7818 SDLoc DL(N); 7819 SDValue NewOp0 = 7820 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7821 SDValue NewOp1 = 7822 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 7823 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 7824 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 7825 DAG.getValueType(MVT::i32)); 7826 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 7827 } 7828 7829 break; 7830 case ISD::ROTL: 7831 case ISD::ROTR: 7832 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7833 "Unexpected custom legalisation"); 7834 Results.push_back(customLegalizeToWOp(N, DAG)); 7835 break; 7836 case ISD::CTTZ: 7837 case ISD::CTTZ_ZERO_UNDEF: 7838 case ISD::CTLZ: 7839 case ISD::CTLZ_ZERO_UNDEF: { 7840 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7841 "Unexpected custom legalisation"); 7842 7843 SDValue NewOp0 = 7844 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7845 bool IsCTZ = 7846 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 7847 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 7848 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 7849 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7850 return; 7851 } 7852 case ISD::SDIV: 7853 case ISD::UDIV: 7854 case ISD::UREM: { 7855 MVT VT = N->getSimpleValueType(0); 7856 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 7857 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 7858 "Unexpected custom legalisation"); 7859 // Don't promote division/remainder by constant since we should expand those 7860 // to multiply by magic constant. 7861 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 7862 if (N->getOperand(1).getOpcode() == ISD::Constant && 7863 !isIntDivCheap(N->getValueType(0), Attr)) 7864 return; 7865 7866 // If the input is i32, use ANY_EXTEND since the W instructions don't read 7867 // the upper 32 bits. For other types we need to sign or zero extend 7868 // based on the opcode. 7869 unsigned ExtOpc = ISD::ANY_EXTEND; 7870 if (VT != MVT::i32) 7871 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 7872 : ISD::ZERO_EXTEND; 7873 7874 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 7875 break; 7876 } 7877 case ISD::UADDO: 7878 case ISD::USUBO: { 7879 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7880 "Unexpected custom legalisation"); 7881 bool IsAdd = N->getOpcode() == ISD::UADDO; 7882 // Create an ADDW or SUBW. 7883 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7884 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7885 SDValue Res = 7886 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 7887 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 7888 DAG.getValueType(MVT::i32)); 7889 7890 SDValue Overflow; 7891 if (IsAdd && isOneConstant(RHS)) { 7892 // Special case uaddo X, 1 overflowed if the addition result is 0. 7893 // The general case (X + C) < C is not necessarily beneficial. Although we 7894 // reduce the live range of X, we may introduce the materialization of 7895 // constant C, especially when the setcc result is used by branch. We have 7896 // no compare with constant and branch instructions. 7897 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 7898 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 7899 } else { 7900 // Sign extend the LHS and perform an unsigned compare with the ADDW 7901 // result. Since the inputs are sign extended from i32, this is equivalent 7902 // to comparing the lower 32 bits. 7903 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7904 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 7905 IsAdd ? ISD::SETULT : ISD::SETUGT); 7906 } 7907 7908 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7909 Results.push_back(Overflow); 7910 return; 7911 } 7912 case ISD::UADDSAT: 7913 case ISD::USUBSAT: { 7914 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7915 "Unexpected custom legalisation"); 7916 if (Subtarget.hasStdExtZbb()) { 7917 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 7918 // sign extend allows overflow of the lower 32 bits to be detected on 7919 // the promoted size. 7920 SDValue LHS = 7921 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7922 SDValue RHS = 7923 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 7924 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 7925 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7926 return; 7927 } 7928 7929 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 7930 // promotion for UADDO/USUBO. 7931 Results.push_back(expandAddSubSat(N, DAG)); 7932 return; 7933 } 7934 case ISD::ABS: { 7935 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7936 "Unexpected custom legalisation"); 7937 7938 if (Subtarget.hasStdExtZbb()) { 7939 // Emit a special ABSW node that will be expanded to NEGW+MAX at isel. 7940 // This allows us to remember that the result is sign extended. Expanding 7941 // to NEGW+MAX here requires a Freeze which breaks ComputeNumSignBits. 7942 SDValue Src = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, 7943 N->getOperand(0)); 7944 SDValue Abs = DAG.getNode(RISCVISD::ABSW, DL, MVT::i64, Src); 7945 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Abs)); 7946 return; 7947 } 7948 7949 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 7950 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7951 7952 // Freeze the source so we can increase it's use count. 7953 Src = DAG.getFreeze(Src); 7954 7955 // Copy sign bit to all bits using the sraiw pattern. 7956 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 7957 DAG.getValueType(MVT::i32)); 7958 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 7959 DAG.getConstant(31, DL, MVT::i64)); 7960 7961 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 7962 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 7963 7964 // NOTE: The result is only required to be anyextended, but sext is 7965 // consistent with type legalization of sub. 7966 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 7967 DAG.getValueType(MVT::i32)); 7968 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 7969 return; 7970 } 7971 case ISD::BITCAST: { 7972 EVT VT = N->getValueType(0); 7973 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 7974 SDValue Op0 = N->getOperand(0); 7975 EVT Op0VT = Op0.getValueType(); 7976 MVT XLenVT = Subtarget.getXLenVT(); 7977 if (VT == MVT::i16 && Op0VT == MVT::f16 && 7978 Subtarget.hasStdExtZfhOrZfhmin()) { 7979 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 7980 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 7981 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 7982 Subtarget.hasStdExtF()) { 7983 SDValue FPConv = 7984 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 7985 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 7986 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 7987 isTypeLegal(Op0VT)) { 7988 // Custom-legalize bitcasts from fixed-length vector types to illegal 7989 // scalar types in order to improve codegen. Bitcast the vector to a 7990 // one-element vector type whose element type is the same as the result 7991 // type, and extract the first element. 7992 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7993 if (isTypeLegal(BVT)) { 7994 SDValue BVec = DAG.getBitcast(BVT, Op0); 7995 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7996 DAG.getConstant(0, DL, XLenVT))); 7997 } 7998 } 7999 break; 8000 } 8001 case RISCVISD::BREV8: { 8002 MVT VT = N->getSimpleValueType(0); 8003 MVT XLenVT = Subtarget.getXLenVT(); 8004 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 8005 "Unexpected custom legalisation"); 8006 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8007 SDValue NewOp = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 8008 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp); 8009 // ReplaceNodeResults requires we maintain the same type for the return 8010 // value. 8011 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 8012 break; 8013 } 8014 case ISD::EXTRACT_VECTOR_ELT: { 8015 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 8016 // type is illegal (currently only vXi64 RV32). 8017 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 8018 // transferred to the destination register. We issue two of these from the 8019 // upper- and lower- halves of the SEW-bit vector element, slid down to the 8020 // first element. 8021 SDValue Vec = N->getOperand(0); 8022 SDValue Idx = N->getOperand(1); 8023 8024 // The vector type hasn't been legalized yet so we can't issue target 8025 // specific nodes if it needs legalization. 8026 // FIXME: We would manually legalize if it's important. 8027 if (!isTypeLegal(Vec.getValueType())) 8028 return; 8029 8030 MVT VecVT = Vec.getSimpleValueType(); 8031 8032 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 8033 VecVT.getVectorElementType() == MVT::i64 && 8034 "Unexpected EXTRACT_VECTOR_ELT legalization"); 8035 8036 // If this is a fixed vector, we need to convert it to a scalable vector. 8037 MVT ContainerVT = VecVT; 8038 if (VecVT.isFixedLengthVector()) { 8039 ContainerVT = getContainerForFixedLengthVector(VecVT); 8040 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 8041 } 8042 8043 MVT XLenVT = Subtarget.getXLenVT(); 8044 8045 // Use a VL of 1 to avoid processing more elements than we need. 8046 auto [Mask, VL] = getDefaultVLOps(1, ContainerVT, DL, DAG, Subtarget); 8047 8048 // Unless the index is known to be 0, we must slide the vector down to get 8049 // the desired element into index 0. 8050 if (!isNullConstant(Idx)) { 8051 Vec = getVSlidedown(DAG, Subtarget, DL, ContainerVT, 8052 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 8053 } 8054 8055 // Extract the lower XLEN bits of the correct vector element. 8056 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 8057 8058 // To extract the upper XLEN bits of the vector element, shift the first 8059 // element right by 32 bits and re-extract the lower XLEN bits. 8060 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 8061 DAG.getUNDEF(ContainerVT), 8062 DAG.getConstant(32, DL, XLenVT), VL); 8063 SDValue LShr32 = 8064 DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, ThirtyTwoV, 8065 DAG.getUNDEF(ContainerVT), Mask, VL); 8066 8067 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 8068 8069 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 8070 break; 8071 } 8072 case ISD::INTRINSIC_WO_CHAIN: { 8073 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8074 switch (IntNo) { 8075 default: 8076 llvm_unreachable( 8077 "Don't know how to custom type legalize this intrinsic!"); 8078 case Intrinsic::riscv_orc_b: { 8079 SDValue NewOp = 8080 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 8081 SDValue Res = DAG.getNode(RISCVISD::ORC_B, DL, MVT::i64, NewOp); 8082 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 8083 return; 8084 } 8085 case Intrinsic::riscv_vmv_x_s: { 8086 EVT VT = N->getValueType(0); 8087 MVT XLenVT = Subtarget.getXLenVT(); 8088 if (VT.bitsLT(XLenVT)) { 8089 // Simple case just extract using vmv.x.s and truncate. 8090 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 8091 Subtarget.getXLenVT(), N->getOperand(1)); 8092 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 8093 return; 8094 } 8095 8096 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 8097 "Unexpected custom legalization"); 8098 8099 // We need to do the move in two steps. 8100 SDValue Vec = N->getOperand(1); 8101 MVT VecVT = Vec.getSimpleValueType(); 8102 8103 // First extract the lower XLEN bits of the element. 8104 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 8105 8106 // To extract the upper XLEN bits of the vector element, shift the first 8107 // element right by 32 bits and re-extract the lower XLEN bits. 8108 auto [Mask, VL] = getDefaultVLOps(1, VecVT, DL, DAG, Subtarget); 8109 8110 SDValue ThirtyTwoV = 8111 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 8112 DAG.getConstant(32, DL, XLenVT), VL); 8113 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, 8114 DAG.getUNDEF(VecVT), Mask, VL); 8115 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 8116 8117 Results.push_back( 8118 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 8119 break; 8120 } 8121 } 8122 break; 8123 } 8124 case ISD::VECREDUCE_ADD: 8125 case ISD::VECREDUCE_AND: 8126 case ISD::VECREDUCE_OR: 8127 case ISD::VECREDUCE_XOR: 8128 case ISD::VECREDUCE_SMAX: 8129 case ISD::VECREDUCE_UMAX: 8130 case ISD::VECREDUCE_SMIN: 8131 case ISD::VECREDUCE_UMIN: 8132 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 8133 Results.push_back(V); 8134 break; 8135 case ISD::VP_REDUCE_ADD: 8136 case ISD::VP_REDUCE_AND: 8137 case ISD::VP_REDUCE_OR: 8138 case ISD::VP_REDUCE_XOR: 8139 case ISD::VP_REDUCE_SMAX: 8140 case ISD::VP_REDUCE_UMAX: 8141 case ISD::VP_REDUCE_SMIN: 8142 case ISD::VP_REDUCE_UMIN: 8143 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 8144 Results.push_back(V); 8145 break; 8146 case ISD::GET_ROUNDING: { 8147 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 8148 SDValue Res = DAG.getNode(ISD::GET_ROUNDING, DL, VTs, N->getOperand(0)); 8149 Results.push_back(Res.getValue(0)); 8150 Results.push_back(Res.getValue(1)); 8151 break; 8152 } 8153 } 8154 } 8155 8156 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 8157 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG, 8158 const RISCVSubtarget &Subtarget) { 8159 auto BinOpToRVVReduce = [](unsigned Opc) { 8160 switch (Opc) { 8161 default: 8162 llvm_unreachable("Unhandled binary to transfrom reduction"); 8163 case ISD::ADD: 8164 return RISCVISD::VECREDUCE_ADD_VL; 8165 case ISD::UMAX: 8166 return RISCVISD::VECREDUCE_UMAX_VL; 8167 case ISD::SMAX: 8168 return RISCVISD::VECREDUCE_SMAX_VL; 8169 case ISD::UMIN: 8170 return RISCVISD::VECREDUCE_UMIN_VL; 8171 case ISD::SMIN: 8172 return RISCVISD::VECREDUCE_SMIN_VL; 8173 case ISD::AND: 8174 return RISCVISD::VECREDUCE_AND_VL; 8175 case ISD::OR: 8176 return RISCVISD::VECREDUCE_OR_VL; 8177 case ISD::XOR: 8178 return RISCVISD::VECREDUCE_XOR_VL; 8179 case ISD::FADD: 8180 return RISCVISD::VECREDUCE_FADD_VL; 8181 case ISD::FMAXNUM: 8182 return RISCVISD::VECREDUCE_FMAX_VL; 8183 case ISD::FMINNUM: 8184 return RISCVISD::VECREDUCE_FMIN_VL; 8185 } 8186 }; 8187 8188 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 8189 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 8190 isNullConstant(V.getOperand(1)) && 8191 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 8192 }; 8193 8194 unsigned Opc = N->getOpcode(); 8195 unsigned ReduceIdx; 8196 if (IsReduction(N->getOperand(0), Opc)) 8197 ReduceIdx = 0; 8198 else if (IsReduction(N->getOperand(1), Opc)) 8199 ReduceIdx = 1; 8200 else 8201 return SDValue(); 8202 8203 // Skip if FADD disallows reassociation but the combiner needs. 8204 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 8205 return SDValue(); 8206 8207 SDValue Extract = N->getOperand(ReduceIdx); 8208 SDValue Reduce = Extract.getOperand(0); 8209 if (!Reduce.hasOneUse()) 8210 return SDValue(); 8211 8212 SDValue ScalarV = Reduce.getOperand(2); 8213 EVT ScalarVT = ScalarV.getValueType(); 8214 if (ScalarV.getOpcode() == ISD::INSERT_SUBVECTOR && 8215 ScalarV.getOperand(0)->isUndef()) 8216 ScalarV = ScalarV.getOperand(1); 8217 8218 // Make sure that ScalarV is a splat with VL=1. 8219 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 8220 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 8221 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 8222 return SDValue(); 8223 8224 if (!hasNonZeroAVL(ScalarV.getOperand(2))) 8225 return SDValue(); 8226 8227 // Check the scalar of ScalarV is neutral element 8228 // TODO: Deal with value other than neutral element. 8229 if (!isNeutralConstant(N->getOpcode(), N->getFlags(), ScalarV.getOperand(1), 8230 0)) 8231 return SDValue(); 8232 8233 if (!ScalarV.hasOneUse()) 8234 return SDValue(); 8235 8236 SDValue NewStart = N->getOperand(1 - ReduceIdx); 8237 8238 SDLoc DL(N); 8239 SDValue NewScalarV = 8240 lowerScalarInsert(NewStart, ScalarV.getOperand(2), 8241 ScalarV.getSimpleValueType(), DL, DAG, Subtarget); 8242 8243 // If we looked through an INSERT_SUBVECTOR we need to restore it. 8244 if (ScalarVT != ScalarV.getValueType()) 8245 NewScalarV = 8246 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ScalarVT, DAG.getUNDEF(ScalarVT), 8247 NewScalarV, DAG.getConstant(0, DL, Subtarget.getXLenVT())); 8248 8249 SDValue NewReduce = 8250 DAG.getNode(Reduce.getOpcode(), DL, Reduce.getValueType(), 8251 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 8252 Reduce.getOperand(3), Reduce.getOperand(4)); 8253 return DAG.getNode(Extract.getOpcode(), DL, Extract.getValueType(), NewReduce, 8254 Extract.getOperand(1)); 8255 } 8256 8257 // Optimize (add (shl x, c0), (shl y, c1)) -> 8258 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 8259 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 8260 const RISCVSubtarget &Subtarget) { 8261 // Perform this optimization only in the zba extension. 8262 if (!Subtarget.hasStdExtZba()) 8263 return SDValue(); 8264 8265 // Skip for vector types and larger types. 8266 EVT VT = N->getValueType(0); 8267 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 8268 return SDValue(); 8269 8270 // The two operand nodes must be SHL and have no other use. 8271 SDValue N0 = N->getOperand(0); 8272 SDValue N1 = N->getOperand(1); 8273 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 8274 !N0->hasOneUse() || !N1->hasOneUse()) 8275 return SDValue(); 8276 8277 // Check c0 and c1. 8278 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8279 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 8280 if (!N0C || !N1C) 8281 return SDValue(); 8282 int64_t C0 = N0C->getSExtValue(); 8283 int64_t C1 = N1C->getSExtValue(); 8284 if (C0 <= 0 || C1 <= 0) 8285 return SDValue(); 8286 8287 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 8288 int64_t Bits = std::min(C0, C1); 8289 int64_t Diff = std::abs(C0 - C1); 8290 if (Diff != 1 && Diff != 2 && Diff != 3) 8291 return SDValue(); 8292 8293 // Build nodes. 8294 SDLoc DL(N); 8295 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 8296 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 8297 SDValue NA0 = 8298 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 8299 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 8300 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 8301 } 8302 8303 // Combine a constant select operand into its use: 8304 // 8305 // (and (select cond, -1, c), x) 8306 // -> (select cond, x, (and x, c)) [AllOnes=1] 8307 // (or (select cond, 0, c), x) 8308 // -> (select cond, x, (or x, c)) [AllOnes=0] 8309 // (xor (select cond, 0, c), x) 8310 // -> (select cond, x, (xor x, c)) [AllOnes=0] 8311 // (add (select cond, 0, c), x) 8312 // -> (select cond, x, (add x, c)) [AllOnes=0] 8313 // (sub x, (select cond, 0, c)) 8314 // -> (select cond, x, (sub x, c)) [AllOnes=0] 8315 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 8316 SelectionDAG &DAG, bool AllOnes, 8317 const RISCVSubtarget &Subtarget) { 8318 EVT VT = N->getValueType(0); 8319 8320 // Skip vectors. 8321 if (VT.isVector()) 8322 return SDValue(); 8323 8324 if (!Subtarget.hasShortForwardBranchOpt() || 8325 (Slct.getOpcode() != ISD::SELECT && 8326 Slct.getOpcode() != RISCVISD::SELECT_CC) || 8327 !Slct.hasOneUse()) 8328 return SDValue(); 8329 8330 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 8331 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 8332 }; 8333 8334 bool SwapSelectOps; 8335 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 8336 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 8337 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 8338 SDValue NonConstantVal; 8339 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 8340 SwapSelectOps = false; 8341 NonConstantVal = FalseVal; 8342 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 8343 SwapSelectOps = true; 8344 NonConstantVal = TrueVal; 8345 } else 8346 return SDValue(); 8347 8348 // Slct is now know to be the desired identity constant when CC is true. 8349 TrueVal = OtherOp; 8350 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 8351 // Unless SwapSelectOps says the condition should be false. 8352 if (SwapSelectOps) 8353 std::swap(TrueVal, FalseVal); 8354 8355 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 8356 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 8357 {Slct.getOperand(0), Slct.getOperand(1), 8358 Slct.getOperand(2), TrueVal, FalseVal}); 8359 8360 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 8361 {Slct.getOperand(0), TrueVal, FalseVal}); 8362 } 8363 8364 // Attempt combineSelectAndUse on each operand of a commutative operator N. 8365 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 8366 bool AllOnes, 8367 const RISCVSubtarget &Subtarget) { 8368 SDValue N0 = N->getOperand(0); 8369 SDValue N1 = N->getOperand(1); 8370 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes, Subtarget)) 8371 return Result; 8372 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes, Subtarget)) 8373 return Result; 8374 return SDValue(); 8375 } 8376 8377 // Transform (add (mul x, c0), c1) -> 8378 // (add (mul (add x, c1/c0), c0), c1%c0). 8379 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 8380 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 8381 // to an infinite loop in DAGCombine if transformed. 8382 // Or transform (add (mul x, c0), c1) -> 8383 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 8384 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 8385 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 8386 // lead to an infinite loop in DAGCombine if transformed. 8387 // Or transform (add (mul x, c0), c1) -> 8388 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 8389 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 8390 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 8391 // lead to an infinite loop in DAGCombine if transformed. 8392 // Or transform (add (mul x, c0), c1) -> 8393 // (mul (add x, c1/c0), c0). 8394 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 8395 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 8396 const RISCVSubtarget &Subtarget) { 8397 // Skip for vector types and larger types. 8398 EVT VT = N->getValueType(0); 8399 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 8400 return SDValue(); 8401 // The first operand node must be a MUL and has no other use. 8402 SDValue N0 = N->getOperand(0); 8403 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 8404 return SDValue(); 8405 // Check if c0 and c1 match above conditions. 8406 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8407 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8408 if (!N0C || !N1C) 8409 return SDValue(); 8410 // If N0C has multiple uses it's possible one of the cases in 8411 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 8412 // in an infinite loop. 8413 if (!N0C->hasOneUse()) 8414 return SDValue(); 8415 int64_t C0 = N0C->getSExtValue(); 8416 int64_t C1 = N1C->getSExtValue(); 8417 int64_t CA, CB; 8418 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 8419 return SDValue(); 8420 // Search for proper CA (non-zero) and CB that both are simm12. 8421 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 8422 !isInt<12>(C0 * (C1 / C0))) { 8423 CA = C1 / C0; 8424 CB = C1 % C0; 8425 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 8426 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 8427 CA = C1 / C0 + 1; 8428 CB = C1 % C0 - C0; 8429 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 8430 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 8431 CA = C1 / C0 - 1; 8432 CB = C1 % C0 + C0; 8433 } else 8434 return SDValue(); 8435 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 8436 SDLoc DL(N); 8437 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 8438 DAG.getConstant(CA, DL, VT)); 8439 SDValue New1 = 8440 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 8441 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 8442 } 8443 8444 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 8445 const RISCVSubtarget &Subtarget) { 8446 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 8447 return V; 8448 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 8449 return V; 8450 if (SDValue V = combineBinOpToReduce(N, DAG, Subtarget)) 8451 return V; 8452 // fold (add (select lhs, rhs, cc, 0, y), x) -> 8453 // (select lhs, rhs, cc, x, (add x, y)) 8454 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false, Subtarget); 8455 } 8456 8457 // Try to turn a sub boolean RHS and constant LHS into an addi. 8458 static SDValue combineSubOfBoolean(SDNode *N, SelectionDAG &DAG) { 8459 SDValue N0 = N->getOperand(0); 8460 SDValue N1 = N->getOperand(1); 8461 EVT VT = N->getValueType(0); 8462 SDLoc DL(N); 8463 8464 // Require a constant LHS. 8465 auto *N0C = dyn_cast<ConstantSDNode>(N0); 8466 if (!N0C) 8467 return SDValue(); 8468 8469 // All our optimizations involve subtracting 1 from the immediate and forming 8470 // an ADDI. Make sure the new immediate is valid for an ADDI. 8471 APInt ImmValMinus1 = N0C->getAPIntValue() - 1; 8472 if (!ImmValMinus1.isSignedIntN(12)) 8473 return SDValue(); 8474 8475 SDValue NewLHS; 8476 if (N1.getOpcode() == ISD::SETCC && N1.hasOneUse()) { 8477 // (sub constant, (setcc x, y, eq/neq)) -> 8478 // (add (setcc x, y, neq/eq), constant - 1) 8479 ISD::CondCode CCVal = cast<CondCodeSDNode>(N1.getOperand(2))->get(); 8480 EVT SetCCOpVT = N1.getOperand(0).getValueType(); 8481 if (!isIntEqualitySetCC(CCVal) || !SetCCOpVT.isInteger()) 8482 return SDValue(); 8483 CCVal = ISD::getSetCCInverse(CCVal, SetCCOpVT); 8484 NewLHS = 8485 DAG.getSetCC(SDLoc(N1), VT, N1.getOperand(0), N1.getOperand(1), CCVal); 8486 } else if (N1.getOpcode() == ISD::XOR && isOneConstant(N1.getOperand(1)) && 8487 N1.getOperand(0).getOpcode() == ISD::SETCC) { 8488 // (sub C, (xor (setcc), 1)) -> (add (setcc), C-1). 8489 // Since setcc returns a bool the xor is equivalent to 1-setcc. 8490 NewLHS = N1.getOperand(0); 8491 } else 8492 return SDValue(); 8493 8494 SDValue NewRHS = DAG.getConstant(ImmValMinus1, DL, VT); 8495 return DAG.getNode(ISD::ADD, DL, VT, NewLHS, NewRHS); 8496 } 8497 8498 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG, 8499 const RISCVSubtarget &Subtarget) { 8500 if (SDValue V = combineSubOfBoolean(N, DAG)) 8501 return V; 8502 8503 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 8504 // (select lhs, rhs, cc, x, (sub x, y)) 8505 SDValue N0 = N->getOperand(0); 8506 SDValue N1 = N->getOperand(1); 8507 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false, Subtarget); 8508 } 8509 8510 // Apply DeMorgan's law to (and/or (xor X, 1), (xor Y, 1)) if X and Y are 0/1. 8511 // Legalizing setcc can introduce xors like this. Doing this transform reduces 8512 // the number of xors and may allow the xor to fold into a branch condition. 8513 static SDValue combineDeMorganOfBoolean(SDNode *N, SelectionDAG &DAG) { 8514 SDValue N0 = N->getOperand(0); 8515 SDValue N1 = N->getOperand(1); 8516 bool IsAnd = N->getOpcode() == ISD::AND; 8517 8518 if (N0.getOpcode() != ISD::XOR || N1.getOpcode() != ISD::XOR) 8519 return SDValue(); 8520 8521 if (!N0.hasOneUse() || !N1.hasOneUse()) 8522 return SDValue(); 8523 8524 SDValue N01 = N0.getOperand(1); 8525 SDValue N11 = N1.getOperand(1); 8526 8527 // For AND, SimplifyDemandedBits may have turned one of the (xor X, 1) into 8528 // (xor X, -1) based on the upper bits of the other operand being 0. If the 8529 // operation is And, allow one of the Xors to use -1. 8530 if (isOneConstant(N01)) { 8531 if (!isOneConstant(N11) && !(IsAnd && isAllOnesConstant(N11))) 8532 return SDValue(); 8533 } else if (isOneConstant(N11)) { 8534 // N01 and N11 being 1 was already handled. Handle N11==1 and N01==-1. 8535 if (!(IsAnd && isAllOnesConstant(N01))) 8536 return SDValue(); 8537 } else 8538 return SDValue(); 8539 8540 EVT VT = N->getValueType(0); 8541 8542 SDValue N00 = N0.getOperand(0); 8543 SDValue N10 = N1.getOperand(0); 8544 8545 // The LHS of the xors needs to be 0/1. 8546 APInt Mask = APInt::getBitsSetFrom(VT.getSizeInBits(), 1); 8547 if (!DAG.MaskedValueIsZero(N00, Mask) || !DAG.MaskedValueIsZero(N10, Mask)) 8548 return SDValue(); 8549 8550 // Invert the opcode and insert a new xor. 8551 SDLoc DL(N); 8552 unsigned Opc = IsAnd ? ISD::OR : ISD::AND; 8553 SDValue Logic = DAG.getNode(Opc, DL, VT, N00, N10); 8554 return DAG.getNode(ISD::XOR, DL, VT, Logic, DAG.getConstant(1, DL, VT)); 8555 } 8556 8557 static SDValue performTRUNCATECombine(SDNode *N, SelectionDAG &DAG, 8558 const RISCVSubtarget &Subtarget) { 8559 SDValue N0 = N->getOperand(0); 8560 EVT VT = N->getValueType(0); 8561 8562 // Pre-promote (i1 (truncate (srl X, Y))) on RV64 with Zbs without zero 8563 // extending X. This is safe since we only need the LSB after the shift and 8564 // shift amounts larger than 31 would produce poison. If we wait until 8565 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 8566 // to use a BEXT instruction. 8567 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && VT == MVT::i1 && 8568 N0.getValueType() == MVT::i32 && N0.getOpcode() == ISD::SRL && 8569 !isa<ConstantSDNode>(N0.getOperand(1)) && N0.hasOneUse()) { 8570 SDLoc DL(N0); 8571 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 8572 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 8573 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 8574 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Srl); 8575 } 8576 8577 return SDValue(); 8578 } 8579 8580 namespace { 8581 // Helper class contains information about comparison operation. 8582 // The first two operands of this operation are compared values and the 8583 // last one is the operation. 8584 // Compared values are stored in Ops. 8585 // Comparison operation is stored in CCode. 8586 class CmpOpInfo { 8587 static unsigned constexpr Size = 2u; 8588 8589 // Type for storing operands of compare operation. 8590 using OpsArray = std::array<SDValue, Size>; 8591 OpsArray Ops; 8592 8593 using const_iterator = OpsArray::const_iterator; 8594 const_iterator begin() const { return Ops.begin(); } 8595 const_iterator end() const { return Ops.end(); } 8596 8597 ISD::CondCode CCode; 8598 8599 unsigned CommonPos{Size}; 8600 unsigned DifferPos{Size}; 8601 8602 // Sets CommonPos and DifferPos based on incoming position 8603 // of common operand CPos. 8604 void setPositions(const_iterator CPos) { 8605 assert(CPos != Ops.end() && "Common operand has to be in OpsArray.\n"); 8606 CommonPos = CPos == Ops.begin() ? 0 : 1; 8607 DifferPos = 1 - CommonPos; 8608 assert((DifferPos == 0 || DifferPos == 1) && 8609 "Positions can be only 0 or 1."); 8610 } 8611 8612 // Private constructor of comparison info based on comparison operator. 8613 // It is private because CmpOpInfo only reasonable relative to other 8614 // comparison operator. Therefore, infos about comparison operation 8615 // have to be collected simultaneously via CmpOpInfo::getInfoAbout(). 8616 CmpOpInfo(const SDValue &CmpOp) 8617 : Ops{CmpOp.getOperand(0), CmpOp.getOperand(1)}, 8618 CCode{cast<CondCodeSDNode>(CmpOp.getOperand(2))->get()} {} 8619 8620 // Finds common operand of Op1 and Op2 and finishes filling CmpOpInfos. 8621 // Returns true if common operand is found. Otherwise - false. 8622 static bool establishCorrespondence(CmpOpInfo &Op1, CmpOpInfo &Op2) { 8623 const auto CommonOpIt1 = 8624 std::find_first_of(Op1.begin(), Op1.end(), Op2.begin(), Op2.end()); 8625 if (CommonOpIt1 == Op1.end()) 8626 return false; 8627 8628 const auto CommonOpIt2 = std::find(Op2.begin(), Op2.end(), *CommonOpIt1); 8629 assert(CommonOpIt2 != Op2.end() && 8630 "Cannot find common operand in the second comparison operation."); 8631 8632 Op1.setPositions(CommonOpIt1); 8633 Op2.setPositions(CommonOpIt2); 8634 8635 return true; 8636 } 8637 8638 public: 8639 CmpOpInfo(const CmpOpInfo &) = default; 8640 CmpOpInfo(CmpOpInfo &&) = default; 8641 8642 SDValue const &operator[](unsigned Pos) const { 8643 assert(Pos < Size && "Out of range\n"); 8644 return Ops[Pos]; 8645 } 8646 8647 // Creates infos about comparison operations CmpOp0 and CmpOp1. 8648 // If there is no common operand returns None. Otherwise, returns 8649 // correspondence info about comparison operations. 8650 static std::optional<std::pair<CmpOpInfo, CmpOpInfo>> 8651 getInfoAbout(SDValue const &CmpOp0, SDValue const &CmpOp1) { 8652 CmpOpInfo Op0{CmpOp0}; 8653 CmpOpInfo Op1{CmpOp1}; 8654 if (!establishCorrespondence(Op0, Op1)) 8655 return std::nullopt; 8656 return std::make_pair(Op0, Op1); 8657 } 8658 8659 // Returns position of common operand. 8660 unsigned getCPos() const { return CommonPos; } 8661 8662 // Returns position of differ operand. 8663 unsigned getDPos() const { return DifferPos; } 8664 8665 // Returns common operand. 8666 SDValue const &getCOp() const { return operator[](CommonPos); } 8667 8668 // Returns differ operand. 8669 SDValue const &getDOp() const { return operator[](DifferPos); } 8670 8671 // Returns consition code of comparison operation. 8672 ISD::CondCode getCondCode() const { return CCode; } 8673 }; 8674 } // namespace 8675 8676 // Verifies conditions to apply an optimization. 8677 // Returns Reference comparison code and three operands A, B, C. 8678 // Conditions for optimization: 8679 // One operand of the compasions has to be common. 8680 // This operand is written to C. 8681 // Two others operands are differend. They are written to A and B. 8682 // Comparisons has to be similar with respect to common operand C. 8683 // e.g. A < C; C > B are similar 8684 // but A < C; B > C are not. 8685 // Reference comparison code is the comparison code if 8686 // common operand is right placed. 8687 // e.g. C > A will be swapped to A < C. 8688 static std::optional<std::tuple<ISD::CondCode, SDValue, SDValue, SDValue>> 8689 verifyCompareConds(SDNode *N, SelectionDAG &DAG) { 8690 LLVM_DEBUG( 8691 dbgs() << "Checking conditions for comparison operation combining.\n";); 8692 8693 SDValue V0 = N->getOperand(0); 8694 SDValue V1 = N->getOperand(1); 8695 assert(V0.getValueType() == V1.getValueType() && 8696 "Operations must have the same value type."); 8697 8698 // Condition 1. Operations have to be used only in logic operation. 8699 if (!V0.hasOneUse() || !V1.hasOneUse()) 8700 return std::nullopt; 8701 8702 // Condition 2. Operands have to be comparison operations. 8703 if (V0.getOpcode() != ISD::SETCC || V1.getOpcode() != ISD::SETCC) 8704 return std::nullopt; 8705 8706 // Condition 3.1. Operations only with integers. 8707 if (!V0.getOperand(0).getValueType().isInteger()) 8708 return std::nullopt; 8709 8710 const auto ComparisonInfo = CmpOpInfo::getInfoAbout(V0, V1); 8711 // Condition 3.2. Common operand has to be in comparison. 8712 if (!ComparisonInfo) 8713 return std::nullopt; 8714 8715 const auto [Op0, Op1] = ComparisonInfo.value(); 8716 8717 LLVM_DEBUG(dbgs() << "Shared operands are on positions: " << Op0.getCPos() 8718 << " and " << Op1.getCPos() << '\n';); 8719 // If common operand at the first position then swap operation to convert to 8720 // strict pattern. Common operand has to be right hand side. 8721 ISD::CondCode RefCond = Op0.getCondCode(); 8722 ISD::CondCode AssistCode = Op1.getCondCode(); 8723 if (!Op0.getCPos()) 8724 RefCond = ISD::getSetCCSwappedOperands(RefCond); 8725 if (!Op1.getCPos()) 8726 AssistCode = ISD::getSetCCSwappedOperands(AssistCode); 8727 LLVM_DEBUG(dbgs() << "Reference condition is: " << RefCond << '\n';); 8728 // If there are different comparison operations then do not perform an 8729 // optimization. a < c; c < b -> will be changed to b > c. 8730 if (RefCond != AssistCode) 8731 return std::nullopt; 8732 8733 // Conditions can be only similar to Less or Greater. (>, >=, <, <=) 8734 // Applying this mask to the operation will determine Less and Greater 8735 // operations. 8736 const unsigned CmpMask = 0b110; 8737 const unsigned MaskedOpcode = CmpMask & RefCond; 8738 // If masking gave 0b110, then this is an operation NE, O or TRUE. 8739 if (MaskedOpcode == CmpMask) 8740 return std::nullopt; 8741 // If masking gave 00000, then this is an operation E, O or FALSE. 8742 if (MaskedOpcode == 0) 8743 return std::nullopt; 8744 // Everything else is similar to Less or Greater. 8745 8746 SDValue A = Op0.getDOp(); 8747 SDValue B = Op1.getDOp(); 8748 SDValue C = Op0.getCOp(); 8749 8750 LLVM_DEBUG( 8751 dbgs() << "The conditions for combining comparisons are satisfied.\n";); 8752 return std::make_tuple(RefCond, A, B, C); 8753 } 8754 8755 static ISD::NodeType getSelectionCode(bool IsUnsigned, bool IsAnd, 8756 bool IsGreaterOp) { 8757 // Codes of selection operation. The first index selects signed or unsigned, 8758 // the second index selects MIN/MAX. 8759 static constexpr ISD::NodeType SelectionCodes[2][2] = { 8760 {ISD::SMIN, ISD::SMAX}, {ISD::UMIN, ISD::UMAX}}; 8761 const bool ChooseSelCode = IsAnd ^ IsGreaterOp; 8762 return SelectionCodes[IsUnsigned][ChooseSelCode]; 8763 } 8764 8765 // Combines two comparison operation and logic operation to one selection 8766 // operation(min, max) and logic operation. Returns new constructed Node if 8767 // conditions for optimization are satisfied. 8768 static SDValue combineCmpOp(SDNode *N, SelectionDAG &DAG, 8769 const RISCVSubtarget &Subtarget) { 8770 if (!Subtarget.hasStdExtZbb()) 8771 return SDValue(); 8772 8773 const unsigned BitOpcode = N->getOpcode(); 8774 assert((BitOpcode == ISD::AND || BitOpcode == ISD::OR) && 8775 "This optimization can be used only with AND/OR operations"); 8776 8777 const auto Props = verifyCompareConds(N, DAG); 8778 // If conditions are invalidated then do not perform an optimization. 8779 if (!Props) 8780 return SDValue(); 8781 8782 const auto [RefOpcode, A, B, C] = Props.value(); 8783 const EVT CmpOpVT = A.getValueType(); 8784 8785 const bool IsGreaterOp = RefOpcode & 0b10; 8786 const bool IsUnsigned = ISD::isUnsignedIntSetCC(RefOpcode); 8787 assert((IsUnsigned || ISD::isSignedIntSetCC(RefOpcode)) && 8788 "Operation neither with signed or unsigned integers."); 8789 8790 const bool IsAnd = BitOpcode == ISD::AND; 8791 const ISD::NodeType PickCode = 8792 getSelectionCode(IsUnsigned, IsAnd, IsGreaterOp); 8793 8794 SDLoc DL(N); 8795 SDValue Pick = DAG.getNode(PickCode, DL, CmpOpVT, A, B); 8796 SDValue Cmp = 8797 DAG.getSetCC(DL, N->getOperand(0).getValueType(), Pick, C, RefOpcode); 8798 8799 return Cmp; 8800 } 8801 8802 static SDValue performANDCombine(SDNode *N, 8803 TargetLowering::DAGCombinerInfo &DCI, 8804 const RISCVSubtarget &Subtarget) { 8805 SelectionDAG &DAG = DCI.DAG; 8806 8807 SDValue N0 = N->getOperand(0); 8808 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 8809 // extending X. This is safe since we only need the LSB after the shift and 8810 // shift amounts larger than 31 would produce poison. If we wait until 8811 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 8812 // to use a BEXT instruction. 8813 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 8814 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 8815 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 8816 N0.hasOneUse()) { 8817 SDLoc DL(N); 8818 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 8819 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 8820 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 8821 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 8822 DAG.getConstant(1, DL, MVT::i64)); 8823 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 8824 } 8825 8826 if (SDValue V = combineCmpOp(N, DAG, Subtarget)) 8827 return V; 8828 8829 if (SDValue V = combineBinOpToReduce(N, DAG, Subtarget)) 8830 return V; 8831 8832 if (DCI.isAfterLegalizeDAG()) 8833 if (SDValue V = combineDeMorganOfBoolean(N, DAG)) 8834 return V; 8835 8836 // fold (and (select lhs, rhs, cc, -1, y), x) -> 8837 // (select lhs, rhs, cc, x, (and x, y)) 8838 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true, Subtarget); 8839 } 8840 8841 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 8842 const RISCVSubtarget &Subtarget) { 8843 SelectionDAG &DAG = DCI.DAG; 8844 8845 if (SDValue V = combineCmpOp(N, DAG, Subtarget)) 8846 return V; 8847 8848 if (SDValue V = combineBinOpToReduce(N, DAG, Subtarget)) 8849 return V; 8850 8851 if (DCI.isAfterLegalizeDAG()) 8852 if (SDValue V = combineDeMorganOfBoolean(N, DAG)) 8853 return V; 8854 8855 // fold (or (select cond, 0, y), x) -> 8856 // (select cond, x, (or x, y)) 8857 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false, Subtarget); 8858 } 8859 8860 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG, 8861 const RISCVSubtarget &Subtarget) { 8862 SDValue N0 = N->getOperand(0); 8863 SDValue N1 = N->getOperand(1); 8864 8865 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8866 // NOTE: Assumes ROL being legal means ROLW is legal. 8867 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8868 if (N0.getOpcode() == RISCVISD::SLLW && 8869 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8870 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8871 SDLoc DL(N); 8872 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8873 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8874 } 8875 8876 if (SDValue V = combineBinOpToReduce(N, DAG, Subtarget)) 8877 return V; 8878 // fold (xor (select cond, 0, y), x) -> 8879 // (select cond, x, (xor x, y)) 8880 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false, Subtarget); 8881 } 8882 8883 // Replace (seteq (i64 (and X, 0xffffffff)), C1) with 8884 // (seteq (i64 (sext_inreg (X, i32)), C1')) where C1' is C1 sign extended from 8885 // bit 31. Same for setne. C1' may be cheaper to materialize and the sext_inreg 8886 // can become a sext.w instead of a shift pair. 8887 static SDValue performSETCCCombine(SDNode *N, SelectionDAG &DAG, 8888 const RISCVSubtarget &Subtarget) { 8889 SDValue N0 = N->getOperand(0); 8890 SDValue N1 = N->getOperand(1); 8891 EVT VT = N->getValueType(0); 8892 EVT OpVT = N0.getValueType(); 8893 8894 if (OpVT != MVT::i64 || !Subtarget.is64Bit()) 8895 return SDValue(); 8896 8897 // RHS needs to be a constant. 8898 auto *N1C = dyn_cast<ConstantSDNode>(N1); 8899 if (!N1C) 8900 return SDValue(); 8901 8902 // LHS needs to be (and X, 0xffffffff). 8903 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse() || 8904 !isa<ConstantSDNode>(N0.getOperand(1)) || 8905 N0.getConstantOperandVal(1) != UINT64_C(0xffffffff)) 8906 return SDValue(); 8907 8908 // Looking for an equality compare. 8909 ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8910 if (!isIntEqualitySetCC(Cond)) 8911 return SDValue(); 8912 8913 // Don't do this if the sign bit is provably zero, it will be turned back into 8914 // an AND. 8915 APInt SignMask = APInt::getOneBitSet(64, 31); 8916 if (DAG.MaskedValueIsZero(N0.getOperand(0), SignMask)) 8917 return SDValue(); 8918 8919 const APInt &C1 = N1C->getAPIntValue(); 8920 8921 SDLoc dl(N); 8922 // If the constant is larger than 2^32 - 1 it is impossible for both sides 8923 // to be equal. 8924 if (C1.getActiveBits() > 32) 8925 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 8926 8927 SDValue SExtOp = DAG.getNode(ISD::SIGN_EXTEND_INREG, N, OpVT, 8928 N0.getOperand(0), DAG.getValueType(MVT::i32)); 8929 return DAG.getSetCC(dl, VT, SExtOp, DAG.getConstant(C1.trunc(32).sext(64), 8930 dl, OpVT), Cond); 8931 } 8932 8933 static SDValue 8934 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8935 const RISCVSubtarget &Subtarget) { 8936 SDValue Src = N->getOperand(0); 8937 EVT VT = N->getValueType(0); 8938 8939 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8940 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8941 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8942 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8943 Src.getOperand(0)); 8944 8945 return SDValue(); 8946 } 8947 8948 namespace { 8949 // Forward declaration of the structure holding the necessary information to 8950 // apply a combine. 8951 struct CombineResult; 8952 8953 /// Helper class for folding sign/zero extensions. 8954 /// In particular, this class is used for the following combines: 8955 /// add_vl -> vwadd(u) | vwadd(u)_w 8956 /// sub_vl -> vwsub(u) | vwsub(u)_w 8957 /// mul_vl -> vwmul(u) | vwmul_su 8958 /// 8959 /// An object of this class represents an operand of the operation we want to 8960 /// combine. 8961 /// E.g., when trying to combine `mul_vl a, b`, we will have one instance of 8962 /// NodeExtensionHelper for `a` and one for `b`. 8963 /// 8964 /// This class abstracts away how the extension is materialized and 8965 /// how its Mask, VL, number of users affect the combines. 8966 /// 8967 /// In particular: 8968 /// - VWADD_W is conceptually == add(op0, sext(op1)) 8969 /// - VWADDU_W == add(op0, zext(op1)) 8970 /// - VWSUB_W == sub(op0, sext(op1)) 8971 /// - VWSUBU_W == sub(op0, zext(op1)) 8972 /// 8973 /// And VMV_V_X_VL, depending on the value, is conceptually equivalent to 8974 /// zext|sext(smaller_value). 8975 struct NodeExtensionHelper { 8976 /// Records if this operand is like being zero extended. 8977 bool SupportsZExt; 8978 /// Records if this operand is like being sign extended. 8979 /// Note: SupportsZExt and SupportsSExt are not mutually exclusive. For 8980 /// instance, a splat constant (e.g., 3), would support being both sign and 8981 /// zero extended. 8982 bool SupportsSExt; 8983 /// This boolean captures whether we care if this operand would still be 8984 /// around after the folding happens. 8985 bool EnforceOneUse; 8986 /// Records if this operand's mask needs to match the mask of the operation 8987 /// that it will fold into. 8988 bool CheckMask; 8989 /// Value of the Mask for this operand. 8990 /// It may be SDValue(). 8991 SDValue Mask; 8992 /// Value of the vector length operand. 8993 /// It may be SDValue(). 8994 SDValue VL; 8995 /// Original value that this NodeExtensionHelper represents. 8996 SDValue OrigOperand; 8997 8998 /// Get the value feeding the extension or the value itself. 8999 /// E.g., for zext(a), this would return a. 9000 SDValue getSource() const { 9001 switch (OrigOperand.getOpcode()) { 9002 case RISCVISD::VSEXT_VL: 9003 case RISCVISD::VZEXT_VL: 9004 return OrigOperand.getOperand(0); 9005 default: 9006 return OrigOperand; 9007 } 9008 } 9009 9010 /// Check if this instance represents a splat. 9011 bool isSplat() const { 9012 return OrigOperand.getOpcode() == RISCVISD::VMV_V_X_VL; 9013 } 9014 9015 /// Get or create a value that can feed \p Root with the given extension \p 9016 /// SExt. If \p SExt is None, this returns the source of this operand. 9017 /// \see ::getSource(). 9018 SDValue getOrCreateExtendedOp(const SDNode *Root, SelectionDAG &DAG, 9019 std::optional<bool> SExt) const { 9020 if (!SExt.has_value()) 9021 return OrigOperand; 9022 9023 MVT NarrowVT = getNarrowType(Root); 9024 9025 SDValue Source = getSource(); 9026 if (Source.getValueType() == NarrowVT) 9027 return Source; 9028 9029 unsigned ExtOpc = *SExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 9030 9031 // If we need an extension, we should be changing the type. 9032 SDLoc DL(Root); 9033 auto [Mask, VL] = getMaskAndVL(Root); 9034 switch (OrigOperand.getOpcode()) { 9035 case RISCVISD::VSEXT_VL: 9036 case RISCVISD::VZEXT_VL: 9037 return DAG.getNode(ExtOpc, DL, NarrowVT, Source, Mask, VL); 9038 case RISCVISD::VMV_V_X_VL: 9039 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 9040 DAG.getUNDEF(NarrowVT), Source.getOperand(1), VL); 9041 default: 9042 // Other opcodes can only come from the original LHS of VW(ADD|SUB)_W_VL 9043 // and that operand should already have the right NarrowVT so no 9044 // extension should be required at this point. 9045 llvm_unreachable("Unsupported opcode"); 9046 } 9047 } 9048 9049 /// Helper function to get the narrow type for \p Root. 9050 /// The narrow type is the type of \p Root where we divided the size of each 9051 /// element by 2. E.g., if Root's type <2xi16> -> narrow type <2xi8>. 9052 /// \pre The size of the type of the elements of Root must be a multiple of 2 9053 /// and be greater than 16. 9054 static MVT getNarrowType(const SDNode *Root) { 9055 MVT VT = Root->getSimpleValueType(0); 9056 9057 // Determine the narrow size. 9058 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 9059 assert(NarrowSize >= 8 && "Trying to extend something we can't represent"); 9060 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 9061 VT.getVectorElementCount()); 9062 return NarrowVT; 9063 } 9064 9065 /// Return the opcode required to materialize the folding of the sign 9066 /// extensions (\p IsSExt == true) or zero extensions (IsSExt == false) for 9067 /// both operands for \p Opcode. 9068 /// Put differently, get the opcode to materialize: 9069 /// - ISExt == true: \p Opcode(sext(a), sext(b)) -> newOpcode(a, b) 9070 /// - ISExt == false: \p Opcode(zext(a), zext(b)) -> newOpcode(a, b) 9071 /// \pre \p Opcode represents a supported root (\see ::isSupportedRoot()). 9072 static unsigned getSameExtensionOpcode(unsigned Opcode, bool IsSExt) { 9073 switch (Opcode) { 9074 case RISCVISD::ADD_VL: 9075 case RISCVISD::VWADD_W_VL: 9076 case RISCVISD::VWADDU_W_VL: 9077 return IsSExt ? RISCVISD::VWADD_VL : RISCVISD::VWADDU_VL; 9078 case RISCVISD::MUL_VL: 9079 return IsSExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 9080 case RISCVISD::SUB_VL: 9081 case RISCVISD::VWSUB_W_VL: 9082 case RISCVISD::VWSUBU_W_VL: 9083 return IsSExt ? RISCVISD::VWSUB_VL : RISCVISD::VWSUBU_VL; 9084 default: 9085 llvm_unreachable("Unexpected opcode"); 9086 } 9087 } 9088 9089 /// Get the opcode to materialize \p Opcode(sext(a), zext(b)) -> 9090 /// newOpcode(a, b). 9091 static unsigned getSUOpcode(unsigned Opcode) { 9092 assert(Opcode == RISCVISD::MUL_VL && "SU is only supported for MUL"); 9093 return RISCVISD::VWMULSU_VL; 9094 } 9095 9096 /// Get the opcode to materialize \p Opcode(a, s|zext(b)) -> 9097 /// newOpcode(a, b). 9098 static unsigned getWOpcode(unsigned Opcode, bool IsSExt) { 9099 switch (Opcode) { 9100 case RISCVISD::ADD_VL: 9101 return IsSExt ? RISCVISD::VWADD_W_VL : RISCVISD::VWADDU_W_VL; 9102 case RISCVISD::SUB_VL: 9103 return IsSExt ? RISCVISD::VWSUB_W_VL : RISCVISD::VWSUBU_W_VL; 9104 default: 9105 llvm_unreachable("Unexpected opcode"); 9106 } 9107 } 9108 9109 using CombineToTry = std::function<std::optional<CombineResult>( 9110 SDNode * /*Root*/, const NodeExtensionHelper & /*LHS*/, 9111 const NodeExtensionHelper & /*RHS*/)>; 9112 9113 /// Check if this node needs to be fully folded or extended for all users. 9114 bool needToPromoteOtherUsers() const { return EnforceOneUse; } 9115 9116 /// Helper method to set the various fields of this struct based on the 9117 /// type of \p Root. 9118 void fillUpExtensionSupport(SDNode *Root, SelectionDAG &DAG) { 9119 SupportsZExt = false; 9120 SupportsSExt = false; 9121 EnforceOneUse = true; 9122 CheckMask = true; 9123 switch (OrigOperand.getOpcode()) { 9124 case RISCVISD::VZEXT_VL: 9125 SupportsZExt = true; 9126 Mask = OrigOperand.getOperand(1); 9127 VL = OrigOperand.getOperand(2); 9128 break; 9129 case RISCVISD::VSEXT_VL: 9130 SupportsSExt = true; 9131 Mask = OrigOperand.getOperand(1); 9132 VL = OrigOperand.getOperand(2); 9133 break; 9134 case RISCVISD::VMV_V_X_VL: { 9135 // Historically, we didn't care about splat values not disappearing during 9136 // combines. 9137 EnforceOneUse = false; 9138 CheckMask = false; 9139 VL = OrigOperand.getOperand(2); 9140 9141 // The operand is a splat of a scalar. 9142 9143 // The pasthru must be undef for tail agnostic. 9144 if (!OrigOperand.getOperand(0).isUndef()) 9145 break; 9146 9147 // Get the scalar value. 9148 SDValue Op = OrigOperand.getOperand(1); 9149 9150 // See if we have enough sign bits or zero bits in the scalar to use a 9151 // widening opcode by splatting to smaller element size. 9152 MVT VT = Root->getSimpleValueType(0); 9153 unsigned EltBits = VT.getScalarSizeInBits(); 9154 unsigned ScalarBits = Op.getValueSizeInBits(); 9155 // Make sure we're getting all element bits from the scalar register. 9156 // FIXME: Support implicit sign extension of vmv.v.x? 9157 if (ScalarBits < EltBits) 9158 break; 9159 9160 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 9161 // If the narrow type cannot be expressed with a legal VMV, 9162 // this is not a valid candidate. 9163 if (NarrowSize < 8) 9164 break; 9165 9166 if (DAG.ComputeMaxSignificantBits(Op) <= NarrowSize) 9167 SupportsSExt = true; 9168 if (DAG.MaskedValueIsZero(Op, 9169 APInt::getBitsSetFrom(ScalarBits, NarrowSize))) 9170 SupportsZExt = true; 9171 break; 9172 } 9173 default: 9174 break; 9175 } 9176 } 9177 9178 /// Check if \p Root supports any extension folding combines. 9179 static bool isSupportedRoot(const SDNode *Root) { 9180 switch (Root->getOpcode()) { 9181 case RISCVISD::ADD_VL: 9182 case RISCVISD::MUL_VL: 9183 case RISCVISD::VWADD_W_VL: 9184 case RISCVISD::VWADDU_W_VL: 9185 case RISCVISD::SUB_VL: 9186 case RISCVISD::VWSUB_W_VL: 9187 case RISCVISD::VWSUBU_W_VL: 9188 return true; 9189 default: 9190 return false; 9191 } 9192 } 9193 9194 /// Build a NodeExtensionHelper for \p Root.getOperand(\p OperandIdx). 9195 NodeExtensionHelper(SDNode *Root, unsigned OperandIdx, SelectionDAG &DAG) { 9196 assert(isSupportedRoot(Root) && "Trying to build an helper with an " 9197 "unsupported root"); 9198 assert(OperandIdx < 2 && "Requesting something else than LHS or RHS"); 9199 OrigOperand = Root->getOperand(OperandIdx); 9200 9201 unsigned Opc = Root->getOpcode(); 9202 switch (Opc) { 9203 // We consider VW<ADD|SUB>(U)_W(LHS, RHS) as if they were 9204 // <ADD|SUB>(LHS, S|ZEXT(RHS)) 9205 case RISCVISD::VWADD_W_VL: 9206 case RISCVISD::VWADDU_W_VL: 9207 case RISCVISD::VWSUB_W_VL: 9208 case RISCVISD::VWSUBU_W_VL: 9209 if (OperandIdx == 1) { 9210 SupportsZExt = 9211 Opc == RISCVISD::VWADDU_W_VL || Opc == RISCVISD::VWSUBU_W_VL; 9212 SupportsSExt = !SupportsZExt; 9213 std::tie(Mask, VL) = getMaskAndVL(Root); 9214 CheckMask = true; 9215 // There's no existing extension here, so we don't have to worry about 9216 // making sure it gets removed. 9217 EnforceOneUse = false; 9218 break; 9219 } 9220 [[fallthrough]]; 9221 default: 9222 fillUpExtensionSupport(Root, DAG); 9223 break; 9224 } 9225 } 9226 9227 /// Check if this operand is compatible with the given vector length \p VL. 9228 bool isVLCompatible(SDValue VL) const { 9229 return this->VL != SDValue() && this->VL == VL; 9230 } 9231 9232 /// Check if this operand is compatible with the given \p Mask. 9233 bool isMaskCompatible(SDValue Mask) const { 9234 return !CheckMask || (this->Mask != SDValue() && this->Mask == Mask); 9235 } 9236 9237 /// Helper function to get the Mask and VL from \p Root. 9238 static std::pair<SDValue, SDValue> getMaskAndVL(const SDNode *Root) { 9239 assert(isSupportedRoot(Root) && "Unexpected root"); 9240 return std::make_pair(Root->getOperand(3), Root->getOperand(4)); 9241 } 9242 9243 /// Check if the Mask and VL of this operand are compatible with \p Root. 9244 bool areVLAndMaskCompatible(const SDNode *Root) const { 9245 auto [Mask, VL] = getMaskAndVL(Root); 9246 return isMaskCompatible(Mask) && isVLCompatible(VL); 9247 } 9248 9249 /// Helper function to check if \p N is commutative with respect to the 9250 /// foldings that are supported by this class. 9251 static bool isCommutative(const SDNode *N) { 9252 switch (N->getOpcode()) { 9253 case RISCVISD::ADD_VL: 9254 case RISCVISD::MUL_VL: 9255 case RISCVISD::VWADD_W_VL: 9256 case RISCVISD::VWADDU_W_VL: 9257 return true; 9258 case RISCVISD::SUB_VL: 9259 case RISCVISD::VWSUB_W_VL: 9260 case RISCVISD::VWSUBU_W_VL: 9261 return false; 9262 default: 9263 llvm_unreachable("Unexpected opcode"); 9264 } 9265 } 9266 9267 /// Get a list of combine to try for folding extensions in \p Root. 9268 /// Note that each returned CombineToTry function doesn't actually modify 9269 /// anything. Instead they produce an optional CombineResult that if not None, 9270 /// need to be materialized for the combine to be applied. 9271 /// \see CombineResult::materialize. 9272 /// If the related CombineToTry function returns std::nullopt, that means the 9273 /// combine didn't match. 9274 static SmallVector<CombineToTry> getSupportedFoldings(const SDNode *Root); 9275 }; 9276 9277 /// Helper structure that holds all the necessary information to materialize a 9278 /// combine that does some extension folding. 9279 struct CombineResult { 9280 /// Opcode to be generated when materializing the combine. 9281 unsigned TargetOpcode; 9282 // No value means no extension is needed. If extension is needed, the value 9283 // indicates if it needs to be sign extended. 9284 std::optional<bool> SExtLHS; 9285 std::optional<bool> SExtRHS; 9286 /// Root of the combine. 9287 SDNode *Root; 9288 /// LHS of the TargetOpcode. 9289 NodeExtensionHelper LHS; 9290 /// RHS of the TargetOpcode. 9291 NodeExtensionHelper RHS; 9292 9293 CombineResult(unsigned TargetOpcode, SDNode *Root, 9294 const NodeExtensionHelper &LHS, std::optional<bool> SExtLHS, 9295 const NodeExtensionHelper &RHS, std::optional<bool> SExtRHS) 9296 : TargetOpcode(TargetOpcode), SExtLHS(SExtLHS), SExtRHS(SExtRHS), 9297 Root(Root), LHS(LHS), RHS(RHS) {} 9298 9299 /// Return a value that uses TargetOpcode and that can be used to replace 9300 /// Root. 9301 /// The actual replacement is *not* done in that method. 9302 SDValue materialize(SelectionDAG &DAG) const { 9303 SDValue Mask, VL, Merge; 9304 std::tie(Mask, VL) = NodeExtensionHelper::getMaskAndVL(Root); 9305 Merge = Root->getOperand(2); 9306 return DAG.getNode(TargetOpcode, SDLoc(Root), Root->getValueType(0), 9307 LHS.getOrCreateExtendedOp(Root, DAG, SExtLHS), 9308 RHS.getOrCreateExtendedOp(Root, DAG, SExtRHS), Merge, 9309 Mask, VL); 9310 } 9311 }; 9312 9313 /// Check if \p Root follows a pattern Root(ext(LHS), ext(RHS)) 9314 /// where `ext` is the same for both LHS and RHS (i.e., both are sext or both 9315 /// are zext) and LHS and RHS can be folded into Root. 9316 /// AllowSExt and AllozZExt define which form `ext` can take in this pattern. 9317 /// 9318 /// \note If the pattern can match with both zext and sext, the returned 9319 /// CombineResult will feature the zext result. 9320 /// 9321 /// \returns std::nullopt if the pattern doesn't match or a CombineResult that 9322 /// can be used to apply the pattern. 9323 static std::optional<CombineResult> 9324 canFoldToVWWithSameExtensionImpl(SDNode *Root, const NodeExtensionHelper &LHS, 9325 const NodeExtensionHelper &RHS, bool AllowSExt, 9326 bool AllowZExt) { 9327 assert((AllowSExt || AllowZExt) && "Forgot to set what you want?"); 9328 if (!LHS.areVLAndMaskCompatible(Root) || !RHS.areVLAndMaskCompatible(Root)) 9329 return std::nullopt; 9330 if (AllowZExt && LHS.SupportsZExt && RHS.SupportsZExt) 9331 return CombineResult(NodeExtensionHelper::getSameExtensionOpcode( 9332 Root->getOpcode(), /*IsSExt=*/false), 9333 Root, LHS, /*SExtLHS=*/false, RHS, 9334 /*SExtRHS=*/false); 9335 if (AllowSExt && LHS.SupportsSExt && RHS.SupportsSExt) 9336 return CombineResult(NodeExtensionHelper::getSameExtensionOpcode( 9337 Root->getOpcode(), /*IsSExt=*/true), 9338 Root, LHS, /*SExtLHS=*/true, RHS, 9339 /*SExtRHS=*/true); 9340 return std::nullopt; 9341 } 9342 9343 /// Check if \p Root follows a pattern Root(ext(LHS), ext(RHS)) 9344 /// where `ext` is the same for both LHS and RHS (i.e., both are sext or both 9345 /// are zext) and LHS and RHS can be folded into Root. 9346 /// 9347 /// \returns std::nullopt if the pattern doesn't match or a CombineResult that 9348 /// can be used to apply the pattern. 9349 static std::optional<CombineResult> 9350 canFoldToVWWithSameExtension(SDNode *Root, const NodeExtensionHelper &LHS, 9351 const NodeExtensionHelper &RHS) { 9352 return canFoldToVWWithSameExtensionImpl(Root, LHS, RHS, /*AllowSExt=*/true, 9353 /*AllowZExt=*/true); 9354 } 9355 9356 /// Check if \p Root follows a pattern Root(LHS, ext(RHS)) 9357 /// 9358 /// \returns std::nullopt if the pattern doesn't match or a CombineResult that 9359 /// can be used to apply the pattern. 9360 static std::optional<CombineResult> 9361 canFoldToVW_W(SDNode *Root, const NodeExtensionHelper &LHS, 9362 const NodeExtensionHelper &RHS) { 9363 if (!RHS.areVLAndMaskCompatible(Root)) 9364 return std::nullopt; 9365 9366 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 9367 // sext/zext? 9368 // Control this behavior behind an option (AllowSplatInVW_W) for testing 9369 // purposes. 9370 if (RHS.SupportsZExt && (!RHS.isSplat() || AllowSplatInVW_W)) 9371 return CombineResult( 9372 NodeExtensionHelper::getWOpcode(Root->getOpcode(), /*IsSExt=*/false), 9373 Root, LHS, /*SExtLHS=*/std::nullopt, RHS, /*SExtRHS=*/false); 9374 if (RHS.SupportsSExt && (!RHS.isSplat() || AllowSplatInVW_W)) 9375 return CombineResult( 9376 NodeExtensionHelper::getWOpcode(Root->getOpcode(), /*IsSExt=*/true), 9377 Root, LHS, /*SExtLHS=*/std::nullopt, RHS, /*SExtRHS=*/true); 9378 return std::nullopt; 9379 } 9380 9381 /// Check if \p Root follows a pattern Root(sext(LHS), sext(RHS)) 9382 /// 9383 /// \returns std::nullopt if the pattern doesn't match or a CombineResult that 9384 /// can be used to apply the pattern. 9385 static std::optional<CombineResult> 9386 canFoldToVWWithSEXT(SDNode *Root, const NodeExtensionHelper &LHS, 9387 const NodeExtensionHelper &RHS) { 9388 return canFoldToVWWithSameExtensionImpl(Root, LHS, RHS, /*AllowSExt=*/true, 9389 /*AllowZExt=*/false); 9390 } 9391 9392 /// Check if \p Root follows a pattern Root(zext(LHS), zext(RHS)) 9393 /// 9394 /// \returns std::nullopt if the pattern doesn't match or a CombineResult that 9395 /// can be used to apply the pattern. 9396 static std::optional<CombineResult> 9397 canFoldToVWWithZEXT(SDNode *Root, const NodeExtensionHelper &LHS, 9398 const NodeExtensionHelper &RHS) { 9399 return canFoldToVWWithSameExtensionImpl(Root, LHS, RHS, /*AllowSExt=*/false, 9400 /*AllowZExt=*/true); 9401 } 9402 9403 /// Check if \p Root follows a pattern Root(sext(LHS), zext(RHS)) 9404 /// 9405 /// \returns std::nullopt if the pattern doesn't match or a CombineResult that 9406 /// can be used to apply the pattern. 9407 static std::optional<CombineResult> 9408 canFoldToVW_SU(SDNode *Root, const NodeExtensionHelper &LHS, 9409 const NodeExtensionHelper &RHS) { 9410 if (!LHS.SupportsSExt || !RHS.SupportsZExt) 9411 return std::nullopt; 9412 if (!LHS.areVLAndMaskCompatible(Root) || !RHS.areVLAndMaskCompatible(Root)) 9413 return std::nullopt; 9414 return CombineResult(NodeExtensionHelper::getSUOpcode(Root->getOpcode()), 9415 Root, LHS, /*SExtLHS=*/true, RHS, /*SExtRHS=*/false); 9416 } 9417 9418 SmallVector<NodeExtensionHelper::CombineToTry> 9419 NodeExtensionHelper::getSupportedFoldings(const SDNode *Root) { 9420 SmallVector<CombineToTry> Strategies; 9421 switch (Root->getOpcode()) { 9422 case RISCVISD::ADD_VL: 9423 case RISCVISD::SUB_VL: 9424 // add|sub -> vwadd(u)|vwsub(u) 9425 Strategies.push_back(canFoldToVWWithSameExtension); 9426 // add|sub -> vwadd(u)_w|vwsub(u)_w 9427 Strategies.push_back(canFoldToVW_W); 9428 break; 9429 case RISCVISD::MUL_VL: 9430 // mul -> vwmul(u) 9431 Strategies.push_back(canFoldToVWWithSameExtension); 9432 // mul -> vwmulsu 9433 Strategies.push_back(canFoldToVW_SU); 9434 break; 9435 case RISCVISD::VWADD_W_VL: 9436 case RISCVISD::VWSUB_W_VL: 9437 // vwadd_w|vwsub_w -> vwadd|vwsub 9438 Strategies.push_back(canFoldToVWWithSEXT); 9439 break; 9440 case RISCVISD::VWADDU_W_VL: 9441 case RISCVISD::VWSUBU_W_VL: 9442 // vwaddu_w|vwsubu_w -> vwaddu|vwsubu 9443 Strategies.push_back(canFoldToVWWithZEXT); 9444 break; 9445 default: 9446 llvm_unreachable("Unexpected opcode"); 9447 } 9448 return Strategies; 9449 } 9450 } // End anonymous namespace. 9451 9452 /// Combine a binary operation to its equivalent VW or VW_W form. 9453 /// The supported combines are: 9454 /// add_vl -> vwadd(u) | vwadd(u)_w 9455 /// sub_vl -> vwsub(u) | vwsub(u)_w 9456 /// mul_vl -> vwmul(u) | vwmul_su 9457 /// vwadd_w(u) -> vwadd(u) 9458 /// vwub_w(u) -> vwadd(u) 9459 static SDValue 9460 combineBinOp_VLToVWBinOp_VL(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 9461 SelectionDAG &DAG = DCI.DAG; 9462 9463 assert(NodeExtensionHelper::isSupportedRoot(N) && 9464 "Shouldn't have called this method"); 9465 SmallVector<SDNode *> Worklist; 9466 SmallSet<SDNode *, 8> Inserted; 9467 Worklist.push_back(N); 9468 Inserted.insert(N); 9469 SmallVector<CombineResult> CombinesToApply; 9470 9471 while (!Worklist.empty()) { 9472 SDNode *Root = Worklist.pop_back_val(); 9473 if (!NodeExtensionHelper::isSupportedRoot(Root)) 9474 return SDValue(); 9475 9476 NodeExtensionHelper LHS(N, 0, DAG); 9477 NodeExtensionHelper RHS(N, 1, DAG); 9478 auto AppendUsersIfNeeded = [&Worklist, 9479 &Inserted](const NodeExtensionHelper &Op) { 9480 if (Op.needToPromoteOtherUsers()) { 9481 for (SDNode *TheUse : Op.OrigOperand->uses()) { 9482 if (Inserted.insert(TheUse).second) 9483 Worklist.push_back(TheUse); 9484 } 9485 } 9486 }; 9487 9488 // Control the compile time by limiting the number of node we look at in 9489 // total. 9490 if (Inserted.size() > ExtensionMaxWebSize) 9491 return SDValue(); 9492 9493 SmallVector<NodeExtensionHelper::CombineToTry> FoldingStrategies = 9494 NodeExtensionHelper::getSupportedFoldings(N); 9495 9496 assert(!FoldingStrategies.empty() && "Nothing to be folded"); 9497 bool Matched = false; 9498 for (int Attempt = 0; 9499 (Attempt != 1 + NodeExtensionHelper::isCommutative(N)) && !Matched; 9500 ++Attempt) { 9501 9502 for (NodeExtensionHelper::CombineToTry FoldingStrategy : 9503 FoldingStrategies) { 9504 std::optional<CombineResult> Res = FoldingStrategy(N, LHS, RHS); 9505 if (Res) { 9506 Matched = true; 9507 CombinesToApply.push_back(*Res); 9508 // All the inputs that are extended need to be folded, otherwise 9509 // we would be leaving the old input (since it is may still be used), 9510 // and the new one. 9511 if (Res->SExtLHS.has_value()) 9512 AppendUsersIfNeeded(LHS); 9513 if (Res->SExtRHS.has_value()) 9514 AppendUsersIfNeeded(RHS); 9515 break; 9516 } 9517 } 9518 std::swap(LHS, RHS); 9519 } 9520 // Right now we do an all or nothing approach. 9521 if (!Matched) 9522 return SDValue(); 9523 } 9524 // Store the value for the replacement of the input node separately. 9525 SDValue InputRootReplacement; 9526 // We do the RAUW after we materialize all the combines, because some replaced 9527 // nodes may be feeding some of the yet-to-be-replaced nodes. Put differently, 9528 // some of these nodes may appear in the NodeExtensionHelpers of some of the 9529 // yet-to-be-visited CombinesToApply roots. 9530 SmallVector<std::pair<SDValue, SDValue>> ValuesToReplace; 9531 ValuesToReplace.reserve(CombinesToApply.size()); 9532 for (CombineResult Res : CombinesToApply) { 9533 SDValue NewValue = Res.materialize(DAG); 9534 if (!InputRootReplacement) { 9535 assert(Res.Root == N && 9536 "First element is expected to be the current node"); 9537 InputRootReplacement = NewValue; 9538 } else { 9539 ValuesToReplace.emplace_back(SDValue(Res.Root, 0), NewValue); 9540 } 9541 } 9542 for (std::pair<SDValue, SDValue> OldNewValues : ValuesToReplace) { 9543 DAG.ReplaceAllUsesOfValueWith(OldNewValues.first, OldNewValues.second); 9544 DCI.AddToWorklist(OldNewValues.second.getNode()); 9545 } 9546 return InputRootReplacement; 9547 } 9548 9549 // Fold 9550 // (fp_to_int (froundeven X)) -> fcvt X, rne 9551 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 9552 // (fp_to_int (ffloor X)) -> fcvt X, rdn 9553 // (fp_to_int (fceil X)) -> fcvt X, rup 9554 // (fp_to_int (fround X)) -> fcvt X, rmm 9555 static SDValue performFP_TO_INTCombine(SDNode *N, 9556 TargetLowering::DAGCombinerInfo &DCI, 9557 const RISCVSubtarget &Subtarget) { 9558 SelectionDAG &DAG = DCI.DAG; 9559 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9560 MVT XLenVT = Subtarget.getXLenVT(); 9561 9562 SDValue Src = N->getOperand(0); 9563 9564 // Ensure the FP type is legal. 9565 if (!TLI.isTypeLegal(Src.getValueType())) 9566 return SDValue(); 9567 9568 // Don't do this for f16 with Zfhmin and not Zfh. 9569 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 9570 return SDValue(); 9571 9572 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src.getOpcode()); 9573 if (FRM == RISCVFPRndMode::Invalid) 9574 return SDValue(); 9575 9576 SDLoc DL(N); 9577 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 9578 EVT VT = N->getValueType(0); 9579 9580 if (VT.isVector() && TLI.isTypeLegal(VT)) { 9581 MVT SrcVT = Src.getSimpleValueType(); 9582 MVT SrcContainerVT = SrcVT; 9583 MVT ContainerVT = VT.getSimpleVT(); 9584 SDValue XVal = Src.getOperand(0); 9585 9586 // For widening and narrowing conversions we just combine it into a 9587 // VFCVT_..._VL node, as there are no specific VFWCVT/VFNCVT VL nodes. They 9588 // end up getting lowered to their appropriate pseudo instructions based on 9589 // their operand types 9590 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits() * 2 || 9591 VT.getScalarSizeInBits() * 2 < SrcVT.getScalarSizeInBits()) 9592 return SDValue(); 9593 9594 // Make fixed-length vectors scalable first 9595 if (SrcVT.isFixedLengthVector()) { 9596 SrcContainerVT = getContainerForFixedLengthVector(DAG, SrcVT, Subtarget); 9597 XVal = convertToScalableVector(SrcContainerVT, XVal, DAG, Subtarget); 9598 ContainerVT = 9599 getContainerForFixedLengthVector(DAG, ContainerVT, Subtarget); 9600 } 9601 9602 auto [Mask, VL] = 9603 getDefaultVLOps(SrcVT, SrcContainerVT, DL, DAG, Subtarget); 9604 9605 SDValue FpToInt; 9606 if (FRM == RISCVFPRndMode::RTZ) { 9607 // Use the dedicated trunc static rounding mode if we're truncating so we 9608 // don't need to generate calls to fsrmi/fsrm 9609 unsigned Opc = 9610 IsSigned ? RISCVISD::VFCVT_RTZ_X_F_VL : RISCVISD::VFCVT_RTZ_XU_F_VL; 9611 FpToInt = DAG.getNode(Opc, DL, ContainerVT, XVal, Mask, VL); 9612 } else { 9613 unsigned Opc = 9614 IsSigned ? RISCVISD::VFCVT_RM_X_F_VL : RISCVISD::VFCVT_RM_XU_F_VL; 9615 FpToInt = DAG.getNode(Opc, DL, ContainerVT, XVal, Mask, 9616 DAG.getTargetConstant(FRM, DL, XLenVT), VL); 9617 } 9618 9619 // If converted from fixed-length to scalable, convert back 9620 if (VT.isFixedLengthVector()) 9621 FpToInt = convertFromScalableVector(VT, FpToInt, DAG, Subtarget); 9622 9623 return FpToInt; 9624 } 9625 9626 // Only handle XLen or i32 types. Other types narrower than XLen will 9627 // eventually be legalized to XLenVT. 9628 if (VT != MVT::i32 && VT != XLenVT) 9629 return SDValue(); 9630 9631 unsigned Opc; 9632 if (VT == XLenVT) 9633 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 9634 else 9635 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 9636 9637 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 9638 DAG.getTargetConstant(FRM, DL, XLenVT)); 9639 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 9640 } 9641 9642 // Fold 9643 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 9644 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 9645 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 9646 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 9647 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 9648 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 9649 TargetLowering::DAGCombinerInfo &DCI, 9650 const RISCVSubtarget &Subtarget) { 9651 SelectionDAG &DAG = DCI.DAG; 9652 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9653 MVT XLenVT = Subtarget.getXLenVT(); 9654 9655 // Only handle XLen types. Other types narrower than XLen will eventually be 9656 // legalized to XLenVT. 9657 EVT DstVT = N->getValueType(0); 9658 if (DstVT != XLenVT) 9659 return SDValue(); 9660 9661 SDValue Src = N->getOperand(0); 9662 9663 // Ensure the FP type is also legal. 9664 if (!TLI.isTypeLegal(Src.getValueType())) 9665 return SDValue(); 9666 9667 // Don't do this for f16 with Zfhmin and not Zfh. 9668 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 9669 return SDValue(); 9670 9671 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9672 9673 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src.getOpcode()); 9674 if (FRM == RISCVFPRndMode::Invalid) 9675 return SDValue(); 9676 9677 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 9678 9679 unsigned Opc; 9680 if (SatVT == DstVT) 9681 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 9682 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 9683 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 9684 else 9685 return SDValue(); 9686 // FIXME: Support other SatVTs by clamping before or after the conversion. 9687 9688 Src = Src.getOperand(0); 9689 9690 SDLoc DL(N); 9691 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 9692 DAG.getTargetConstant(FRM, DL, XLenVT)); 9693 9694 // fcvt.wu.* sign extends bit 31 on RV64. FP_TO_UINT_SAT expects to zero 9695 // extend. 9696 if (Opc == RISCVISD::FCVT_WU_RV64) 9697 FpToInt = DAG.getZeroExtendInReg(FpToInt, DL, MVT::i32); 9698 9699 // RISCV FP-to-int conversions saturate to the destination register size, but 9700 // don't produce 0 for nan. 9701 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 9702 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 9703 } 9704 9705 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 9706 // smaller than XLenVT. 9707 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 9708 const RISCVSubtarget &Subtarget) { 9709 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 9710 9711 SDValue Src = N->getOperand(0); 9712 if (Src.getOpcode() != ISD::BSWAP) 9713 return SDValue(); 9714 9715 EVT VT = N->getValueType(0); 9716 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 9717 !isPowerOf2_32(VT.getSizeInBits())) 9718 return SDValue(); 9719 9720 SDLoc DL(N); 9721 return DAG.getNode(RISCVISD::BREV8, DL, VT, Src.getOperand(0)); 9722 } 9723 9724 // Convert from one FMA opcode to another based on whether we are negating the 9725 // multiply result and/or the accumulator. 9726 // NOTE: Only supports RVV operations with VL. 9727 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) { 9728 assert((NegMul || NegAcc) && "Not negating anything?"); 9729 9730 // Negating the multiply result changes ADD<->SUB and toggles 'N'. 9731 if (NegMul) { 9732 // clang-format off 9733 switch (Opcode) { 9734 default: llvm_unreachable("Unexpected opcode"); 9735 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 9736 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 9737 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 9738 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 9739 } 9740 // clang-format on 9741 } 9742 9743 // Negating the accumulator changes ADD<->SUB. 9744 if (NegAcc) { 9745 // clang-format off 9746 switch (Opcode) { 9747 default: llvm_unreachable("Unexpected opcode"); 9748 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 9749 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 9750 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 9751 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 9752 } 9753 // clang-format on 9754 } 9755 9756 return Opcode; 9757 } 9758 9759 static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG, 9760 const RISCVSubtarget &Subtarget) { 9761 assert(N->getOpcode() == ISD::SRA && "Unexpected opcode"); 9762 9763 if (N->getValueType(0) != MVT::i64 || !Subtarget.is64Bit()) 9764 return SDValue(); 9765 9766 if (!isa<ConstantSDNode>(N->getOperand(1))) 9767 return SDValue(); 9768 uint64_t ShAmt = N->getConstantOperandVal(1); 9769 if (ShAmt > 32) 9770 return SDValue(); 9771 9772 SDValue N0 = N->getOperand(0); 9773 9774 // Combine (sra (sext_inreg (shl X, C1), i32), C2) -> 9775 // (sra (shl X, C1+32), C2+32) so it gets selected as SLLI+SRAI instead of 9776 // SLLIW+SRAIW. SLLI+SRAI have compressed forms. 9777 if (ShAmt < 32 && 9778 N0.getOpcode() == ISD::SIGN_EXTEND_INREG && N0.hasOneUse() && 9779 cast<VTSDNode>(N0.getOperand(1))->getVT() == MVT::i32 && 9780 N0.getOperand(0).getOpcode() == ISD::SHL && N0.getOperand(0).hasOneUse() && 9781 isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) { 9782 uint64_t LShAmt = N0.getOperand(0).getConstantOperandVal(1); 9783 if (LShAmt < 32) { 9784 SDLoc ShlDL(N0.getOperand(0)); 9785 SDValue Shl = DAG.getNode(ISD::SHL, ShlDL, MVT::i64, 9786 N0.getOperand(0).getOperand(0), 9787 DAG.getConstant(LShAmt + 32, ShlDL, MVT::i64)); 9788 SDLoc DL(N); 9789 return DAG.getNode(ISD::SRA, DL, MVT::i64, Shl, 9790 DAG.getConstant(ShAmt + 32, DL, MVT::i64)); 9791 } 9792 } 9793 9794 // Combine (sra (shl X, 32), 32 - C) -> (shl (sext_inreg X, i32), C) 9795 // FIXME: Should this be a generic combine? There's a similar combine on X86. 9796 // 9797 // Also try these folds where an add or sub is in the middle. 9798 // (sra (add (shl X, 32), C1), 32 - C) -> (shl (sext_inreg (add X, C1), C) 9799 // (sra (sub C1, (shl X, 32)), 32 - C) -> (shl (sext_inreg (sub C1, X), C) 9800 SDValue Shl; 9801 ConstantSDNode *AddC = nullptr; 9802 9803 // We might have an ADD or SUB between the SRA and SHL. 9804 bool IsAdd = N0.getOpcode() == ISD::ADD; 9805 if ((IsAdd || N0.getOpcode() == ISD::SUB)) { 9806 // Other operand needs to be a constant we can modify. 9807 AddC = dyn_cast<ConstantSDNode>(N0.getOperand(IsAdd ? 1 : 0)); 9808 if (!AddC) 9809 return SDValue(); 9810 9811 // AddC needs to have at least 32 trailing zeros. 9812 if (AddC->getAPIntValue().countTrailingZeros() < 32) 9813 return SDValue(); 9814 9815 // All users should be a shift by constant less than or equal to 32. This 9816 // ensures we'll do this optimization for each of them to produce an 9817 // add/sub+sext_inreg they can all share. 9818 for (SDNode *U : N0->uses()) { 9819 if (U->getOpcode() != ISD::SRA || 9820 !isa<ConstantSDNode>(U->getOperand(1)) || 9821 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() > 32) 9822 return SDValue(); 9823 } 9824 9825 Shl = N0.getOperand(IsAdd ? 0 : 1); 9826 } else { 9827 // Not an ADD or SUB. 9828 Shl = N0; 9829 } 9830 9831 // Look for a shift left by 32. 9832 if (Shl.getOpcode() != ISD::SHL || !isa<ConstantSDNode>(Shl.getOperand(1)) || 9833 Shl.getConstantOperandVal(1) != 32) 9834 return SDValue(); 9835 9836 // We if we didn't look through an add/sub, then the shl should have one use. 9837 // If we did look through an add/sub, the sext_inreg we create is free so 9838 // we're only creating 2 new instructions. It's enough to only remove the 9839 // original sra+add/sub. 9840 if (!AddC && !Shl.hasOneUse()) 9841 return SDValue(); 9842 9843 SDLoc DL(N); 9844 SDValue In = Shl.getOperand(0); 9845 9846 // If we looked through an ADD or SUB, we need to rebuild it with the shifted 9847 // constant. 9848 if (AddC) { 9849 SDValue ShiftedAddC = 9850 DAG.getConstant(AddC->getAPIntValue().lshr(32), DL, MVT::i64); 9851 if (IsAdd) 9852 In = DAG.getNode(ISD::ADD, DL, MVT::i64, In, ShiftedAddC); 9853 else 9854 In = DAG.getNode(ISD::SUB, DL, MVT::i64, ShiftedAddC, In); 9855 } 9856 9857 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, In, 9858 DAG.getValueType(MVT::i32)); 9859 if (ShAmt == 32) 9860 return SExt; 9861 9862 return DAG.getNode( 9863 ISD::SHL, DL, MVT::i64, SExt, 9864 DAG.getConstant(32 - ShAmt, DL, MVT::i64)); 9865 } 9866 9867 // Invert (and/or (set cc X, Y), (xor Z, 1)) to (or/and (set !cc X, Y)), Z) if 9868 // the result is used as the conditon of a br_cc or select_cc we can invert, 9869 // inverting the setcc is free, and Z is 0/1. Caller will invert the 9870 // br_cc/select_cc. 9871 static SDValue tryDemorganOfBooleanCondition(SDValue Cond, SelectionDAG &DAG) { 9872 bool IsAnd = Cond.getOpcode() == ISD::AND; 9873 if (!IsAnd && Cond.getOpcode() != ISD::OR) 9874 return SDValue(); 9875 9876 if (!Cond.hasOneUse()) 9877 return SDValue(); 9878 9879 SDValue Setcc = Cond.getOperand(0); 9880 SDValue Xor = Cond.getOperand(1); 9881 // Canonicalize setcc to LHS. 9882 if (Setcc.getOpcode() != ISD::SETCC) 9883 std::swap(Setcc, Xor); 9884 // LHS should be a setcc and RHS should be an xor. 9885 if (Setcc.getOpcode() != ISD::SETCC || !Setcc.hasOneUse() || 9886 Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse()) 9887 return SDValue(); 9888 9889 // If the condition is an And, SimplifyDemandedBits may have changed 9890 // (xor Z, 1) to (not Z). 9891 SDValue Xor1 = Xor.getOperand(1); 9892 if (!isOneConstant(Xor1) && !(IsAnd && isAllOnesConstant(Xor1))) 9893 return SDValue(); 9894 9895 EVT VT = Cond.getValueType(); 9896 SDValue Xor0 = Xor.getOperand(0); 9897 9898 // The LHS of the xor needs to be 0/1. 9899 APInt Mask = APInt::getBitsSetFrom(VT.getSizeInBits(), 1); 9900 if (!DAG.MaskedValueIsZero(Xor0, Mask)) 9901 return SDValue(); 9902 9903 // We can only invert integer setccs. 9904 EVT SetCCOpVT = Setcc.getOperand(0).getValueType(); 9905 if (!SetCCOpVT.isScalarInteger()) 9906 return SDValue(); 9907 9908 ISD::CondCode CCVal = cast<CondCodeSDNode>(Setcc.getOperand(2))->get(); 9909 if (ISD::isIntEqualitySetCC(CCVal)) { 9910 CCVal = ISD::getSetCCInverse(CCVal, SetCCOpVT); 9911 Setcc = DAG.getSetCC(SDLoc(Setcc), VT, Setcc.getOperand(0), 9912 Setcc.getOperand(1), CCVal); 9913 } else if (CCVal == ISD::SETLT && isNullConstant(Setcc.getOperand(0))) { 9914 // Invert (setlt 0, X) by converting to (setlt X, 1). 9915 Setcc = DAG.getSetCC(SDLoc(Setcc), VT, Setcc.getOperand(1), 9916 DAG.getConstant(1, SDLoc(Setcc), VT), CCVal); 9917 } else if (CCVal == ISD::SETLT && isOneConstant(Setcc.getOperand(1))) { 9918 // (setlt X, 1) by converting to (setlt 0, X). 9919 Setcc = DAG.getSetCC(SDLoc(Setcc), VT, 9920 DAG.getConstant(0, SDLoc(Setcc), VT), 9921 Setcc.getOperand(0), CCVal); 9922 } else 9923 return SDValue(); 9924 9925 unsigned Opc = IsAnd ? ISD::OR : ISD::AND; 9926 return DAG.getNode(Opc, SDLoc(Cond), VT, Setcc, Xor.getOperand(0)); 9927 } 9928 9929 // Perform common combines for BR_CC and SELECT_CC condtions. 9930 static bool combine_CC(SDValue &LHS, SDValue &RHS, SDValue &CC, const SDLoc &DL, 9931 SelectionDAG &DAG, const RISCVSubtarget &Subtarget) { 9932 ISD::CondCode CCVal = cast<CondCodeSDNode>(CC)->get(); 9933 9934 // As far as arithmetic right shift always saves the sign, 9935 // shift can be omitted. 9936 // Fold setlt (sra X, N), 0 -> setlt X, 0 and 9937 // setge (sra X, N), 0 -> setge X, 0 9938 if (auto *RHSConst = dyn_cast<ConstantSDNode>(RHS.getNode())) { 9939 if ((CCVal == ISD::SETGE || CCVal == ISD::SETLT) && 9940 LHS.getOpcode() == ISD::SRA && RHSConst->isZero()) { 9941 LHS = LHS.getOperand(0); 9942 return true; 9943 } 9944 } 9945 9946 if (!ISD::isIntEqualitySetCC(CCVal)) 9947 return false; 9948 9949 // Fold ((setlt X, Y), 0, ne) -> (X, Y, lt) 9950 // Sometimes the setcc is introduced after br_cc/select_cc has been formed. 9951 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 9952 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 9953 // If we're looking for eq 0 instead of ne 0, we need to invert the 9954 // condition. 9955 bool Invert = CCVal == ISD::SETEQ; 9956 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9957 if (Invert) 9958 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 9959 9960 RHS = LHS.getOperand(1); 9961 LHS = LHS.getOperand(0); 9962 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 9963 9964 CC = DAG.getCondCode(CCVal); 9965 return true; 9966 } 9967 9968 // Fold ((xor X, Y), 0, eq/ne) -> (X, Y, eq/ne) 9969 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) { 9970 RHS = LHS.getOperand(1); 9971 LHS = LHS.getOperand(0); 9972 return true; 9973 } 9974 9975 // Fold ((srl (and X, 1<<C), C), 0, eq/ne) -> ((shl X, XLen-1-C), 0, ge/lt) 9976 if (isNullConstant(RHS) && LHS.getOpcode() == ISD::SRL && LHS.hasOneUse() && 9977 LHS.getOperand(1).getOpcode() == ISD::Constant) { 9978 SDValue LHS0 = LHS.getOperand(0); 9979 if (LHS0.getOpcode() == ISD::AND && 9980 LHS0.getOperand(1).getOpcode() == ISD::Constant) { 9981 uint64_t Mask = LHS0.getConstantOperandVal(1); 9982 uint64_t ShAmt = LHS.getConstantOperandVal(1); 9983 if (isPowerOf2_64(Mask) && Log2_64(Mask) == ShAmt) { 9984 CCVal = CCVal == ISD::SETEQ ? ISD::SETGE : ISD::SETLT; 9985 CC = DAG.getCondCode(CCVal); 9986 9987 ShAmt = LHS.getValueSizeInBits() - 1 - ShAmt; 9988 LHS = LHS0.getOperand(0); 9989 if (ShAmt != 0) 9990 LHS = 9991 DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS0.getOperand(0), 9992 DAG.getConstant(ShAmt, DL, LHS.getValueType())); 9993 return true; 9994 } 9995 } 9996 } 9997 9998 // (X, 1, setne) -> // (X, 0, seteq) if we can prove X is 0/1. 9999 // This can occur when legalizing some floating point comparisons. 10000 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 10001 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 10002 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 10003 CC = DAG.getCondCode(CCVal); 10004 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 10005 return true; 10006 } 10007 10008 if (isNullConstant(RHS)) { 10009 if (SDValue NewCond = tryDemorganOfBooleanCondition(LHS, DAG)) { 10010 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 10011 CC = DAG.getCondCode(CCVal); 10012 LHS = NewCond; 10013 return true; 10014 } 10015 } 10016 10017 return false; 10018 } 10019 10020 // Fold 10021 // (select C, (add Y, X), Y) -> (add Y, (select C, X, 0)). 10022 // (select C, (sub Y, X), Y) -> (sub Y, (select C, X, 0)). 10023 // (select C, (or Y, X), Y) -> (or Y, (select C, X, 0)). 10024 // (select C, (xor Y, X), Y) -> (xor Y, (select C, X, 0)). 10025 static SDValue tryFoldSelectIntoOp(SDNode *N, SelectionDAG &DAG, 10026 SDValue TrueVal, SDValue FalseVal, 10027 bool Swapped) { 10028 bool Commutative = true; 10029 switch (TrueVal.getOpcode()) { 10030 default: 10031 return SDValue(); 10032 case ISD::SUB: 10033 Commutative = false; 10034 break; 10035 case ISD::ADD: 10036 case ISD::OR: 10037 case ISD::XOR: 10038 break; 10039 } 10040 10041 if (!TrueVal.hasOneUse() || isa<ConstantSDNode>(FalseVal)) 10042 return SDValue(); 10043 10044 unsigned OpToFold; 10045 if (FalseVal == TrueVal.getOperand(0)) 10046 OpToFold = 0; 10047 else if (Commutative && FalseVal == TrueVal.getOperand(1)) 10048 OpToFold = 1; 10049 else 10050 return SDValue(); 10051 10052 EVT VT = N->getValueType(0); 10053 SDLoc DL(N); 10054 SDValue Zero = DAG.getConstant(0, DL, VT); 10055 SDValue OtherOp = TrueVal.getOperand(1 - OpToFold); 10056 10057 if (Swapped) 10058 std::swap(OtherOp, Zero); 10059 SDValue NewSel = DAG.getSelect(DL, VT, N->getOperand(0), OtherOp, Zero); 10060 return DAG.getNode(TrueVal.getOpcode(), DL, VT, FalseVal, NewSel); 10061 } 10062 10063 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG, 10064 const RISCVSubtarget &Subtarget) { 10065 if (Subtarget.hasShortForwardBranchOpt()) 10066 return SDValue(); 10067 10068 // Only support XLenVT. 10069 if (N->getValueType(0) != Subtarget.getXLenVT()) 10070 return SDValue(); 10071 10072 SDValue TrueVal = N->getOperand(1); 10073 SDValue FalseVal = N->getOperand(2); 10074 if (SDValue V = tryFoldSelectIntoOp(N, DAG, TrueVal, FalseVal, /*Swapped*/false)) 10075 return V; 10076 return tryFoldSelectIntoOp(N, DAG, FalseVal, TrueVal, /*Swapped*/true); 10077 } 10078 10079 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 10080 DAGCombinerInfo &DCI) const { 10081 SelectionDAG &DAG = DCI.DAG; 10082 10083 // Helper to call SimplifyDemandedBits on an operand of N where only some low 10084 // bits are demanded. N will be added to the Worklist if it was not deleted. 10085 // Caller should return SDValue(N, 0) if this returns true. 10086 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 10087 SDValue Op = N->getOperand(OpNo); 10088 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 10089 if (!SimplifyDemandedBits(Op, Mask, DCI)) 10090 return false; 10091 10092 if (N->getOpcode() != ISD::DELETED_NODE) 10093 DCI.AddToWorklist(N); 10094 return true; 10095 }; 10096 10097 switch (N->getOpcode()) { 10098 default: 10099 break; 10100 case RISCVISD::SplitF64: { 10101 SDValue Op0 = N->getOperand(0); 10102 // If the input to SplitF64 is just BuildPairF64 then the operation is 10103 // redundant. Instead, use BuildPairF64's operands directly. 10104 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 10105 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 10106 10107 if (Op0->isUndef()) { 10108 SDValue Lo = DAG.getUNDEF(MVT::i32); 10109 SDValue Hi = DAG.getUNDEF(MVT::i32); 10110 return DCI.CombineTo(N, Lo, Hi); 10111 } 10112 10113 SDLoc DL(N); 10114 10115 // It's cheaper to materialise two 32-bit integers than to load a double 10116 // from the constant pool and transfer it to integer registers through the 10117 // stack. 10118 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 10119 APInt V = C->getValueAPF().bitcastToAPInt(); 10120 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 10121 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 10122 return DCI.CombineTo(N, Lo, Hi); 10123 } 10124 10125 // This is a target-specific version of a DAGCombine performed in 10126 // DAGCombiner::visitBITCAST. It performs the equivalent of: 10127 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 10128 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 10129 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 10130 !Op0.getNode()->hasOneUse()) 10131 break; 10132 SDValue NewSplitF64 = 10133 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 10134 Op0.getOperand(0)); 10135 SDValue Lo = NewSplitF64.getValue(0); 10136 SDValue Hi = NewSplitF64.getValue(1); 10137 APInt SignBit = APInt::getSignMask(32); 10138 if (Op0.getOpcode() == ISD::FNEG) { 10139 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 10140 DAG.getConstant(SignBit, DL, MVT::i32)); 10141 return DCI.CombineTo(N, Lo, NewHi); 10142 } 10143 assert(Op0.getOpcode() == ISD::FABS); 10144 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 10145 DAG.getConstant(~SignBit, DL, MVT::i32)); 10146 return DCI.CombineTo(N, Lo, NewHi); 10147 } 10148 case RISCVISD::SLLW: 10149 case RISCVISD::SRAW: 10150 case RISCVISD::SRLW: 10151 case RISCVISD::RORW: 10152 case RISCVISD::ROLW: { 10153 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 10154 if (SimplifyDemandedLowBitsHelper(0, 32) || 10155 SimplifyDemandedLowBitsHelper(1, 5)) 10156 return SDValue(N, 0); 10157 10158 break; 10159 } 10160 case RISCVISD::CLZW: 10161 case RISCVISD::CTZW: { 10162 // Only the lower 32 bits of the first operand are read 10163 if (SimplifyDemandedLowBitsHelper(0, 32)) 10164 return SDValue(N, 0); 10165 break; 10166 } 10167 case RISCVISD::FMV_X_ANYEXTH: 10168 case RISCVISD::FMV_X_ANYEXTW_RV64: { 10169 SDLoc DL(N); 10170 SDValue Op0 = N->getOperand(0); 10171 MVT VT = N->getSimpleValueType(0); 10172 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 10173 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 10174 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 10175 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 10176 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 10177 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 10178 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 10179 assert(Op0.getOperand(0).getValueType() == VT && 10180 "Unexpected value type!"); 10181 return Op0.getOperand(0); 10182 } 10183 10184 // This is a target-specific version of a DAGCombine performed in 10185 // DAGCombiner::visitBITCAST. It performs the equivalent of: 10186 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 10187 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 10188 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 10189 !Op0.getNode()->hasOneUse()) 10190 break; 10191 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 10192 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 10193 APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits()); 10194 if (Op0.getOpcode() == ISD::FNEG) 10195 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 10196 DAG.getConstant(SignBit, DL, VT)); 10197 10198 assert(Op0.getOpcode() == ISD::FABS); 10199 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 10200 DAG.getConstant(~SignBit, DL, VT)); 10201 } 10202 case ISD::ADD: 10203 return performADDCombine(N, DAG, Subtarget); 10204 case ISD::SUB: 10205 return performSUBCombine(N, DAG, Subtarget); 10206 case ISD::AND: 10207 return performANDCombine(N, DCI, Subtarget); 10208 case ISD::OR: 10209 return performORCombine(N, DCI, Subtarget); 10210 case ISD::XOR: 10211 return performXORCombine(N, DAG, Subtarget); 10212 case ISD::FADD: 10213 case ISD::UMAX: 10214 case ISD::UMIN: 10215 case ISD::SMAX: 10216 case ISD::SMIN: 10217 case ISD::FMAXNUM: 10218 case ISD::FMINNUM: 10219 return combineBinOpToReduce(N, DAG, Subtarget); 10220 case ISD::SETCC: 10221 return performSETCCCombine(N, DAG, Subtarget); 10222 case ISD::SIGN_EXTEND_INREG: 10223 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 10224 case ISD::ZERO_EXTEND: 10225 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 10226 // type legalization. This is safe because fp_to_uint produces poison if 10227 // it overflows. 10228 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 10229 SDValue Src = N->getOperand(0); 10230 if (Src.getOpcode() == ISD::FP_TO_UINT && 10231 isTypeLegal(Src.getOperand(0).getValueType())) 10232 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 10233 Src.getOperand(0)); 10234 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 10235 isTypeLegal(Src.getOperand(1).getValueType())) { 10236 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 10237 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 10238 Src.getOperand(0), Src.getOperand(1)); 10239 DCI.CombineTo(N, Res); 10240 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 10241 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 10242 return SDValue(N, 0); // Return N so it doesn't get rechecked. 10243 } 10244 } 10245 return SDValue(); 10246 case ISD::TRUNCATE: 10247 return performTRUNCATECombine(N, DAG, Subtarget); 10248 case ISD::SELECT: 10249 return performSELECTCombine(N, DAG, Subtarget); 10250 case RISCVISD::SELECT_CC: { 10251 // Transform 10252 SDValue LHS = N->getOperand(0); 10253 SDValue RHS = N->getOperand(1); 10254 SDValue CC = N->getOperand(2); 10255 ISD::CondCode CCVal = cast<CondCodeSDNode>(CC)->get(); 10256 SDValue TrueV = N->getOperand(3); 10257 SDValue FalseV = N->getOperand(4); 10258 SDLoc DL(N); 10259 EVT VT = N->getValueType(0); 10260 10261 // If the True and False values are the same, we don't need a select_cc. 10262 if (TrueV == FalseV) 10263 return TrueV; 10264 10265 // (select (x < 0), y, z) -> x >> (XLEN - 1) & (y - z) + z 10266 // (select (x >= 0), y, z) -> x >> (XLEN - 1) & (z - y) + y 10267 if (!Subtarget.hasShortForwardBranchOpt() && isa<ConstantSDNode>(TrueV) && 10268 isa<ConstantSDNode>(FalseV) && isNullConstant(RHS) && 10269 (CCVal == ISD::CondCode::SETLT || CCVal == ISD::CondCode::SETGE)) { 10270 if (CCVal == ISD::CondCode::SETGE) 10271 std::swap(TrueV, FalseV); 10272 10273 int64_t TrueSImm = cast<ConstantSDNode>(TrueV)->getSExtValue(); 10274 int64_t FalseSImm = cast<ConstantSDNode>(FalseV)->getSExtValue(); 10275 // Only handle simm12, if it is not in this range, it can be considered as 10276 // register. 10277 if (isInt<12>(TrueSImm) && isInt<12>(FalseSImm) && 10278 isInt<12>(TrueSImm - FalseSImm)) { 10279 SDValue SRA = 10280 DAG.getNode(ISD::SRA, DL, VT, LHS, 10281 DAG.getConstant(Subtarget.getXLen() - 1, DL, VT)); 10282 SDValue AND = 10283 DAG.getNode(ISD::AND, DL, VT, SRA, 10284 DAG.getConstant(TrueSImm - FalseSImm, DL, VT)); 10285 return DAG.getNode(ISD::ADD, DL, VT, AND, FalseV); 10286 } 10287 10288 if (CCVal == ISD::CondCode::SETGE) 10289 std::swap(TrueV, FalseV); 10290 } 10291 10292 if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget)) 10293 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 10294 {LHS, RHS, CC, TrueV, FalseV}); 10295 10296 if (!Subtarget.hasShortForwardBranchOpt()) { 10297 // (select c, -1, y) -> -c | y 10298 if (isAllOnesConstant(TrueV)) { 10299 SDValue C = DAG.getSetCC(DL, VT, LHS, RHS, CCVal); 10300 SDValue Neg = DAG.getNegative(C, DL, VT); 10301 return DAG.getNode(ISD::OR, DL, VT, Neg, FalseV); 10302 } 10303 // (select c, y, -1) -> -!c | y 10304 if (isAllOnesConstant(FalseV)) { 10305 SDValue C = 10306 DAG.getSetCC(DL, VT, LHS, RHS, ISD::getSetCCInverse(CCVal, VT)); 10307 SDValue Neg = DAG.getNegative(C, DL, VT); 10308 return DAG.getNode(ISD::OR, DL, VT, Neg, TrueV); 10309 } 10310 10311 // (select c, 0, y) -> -!c & y 10312 if (isNullConstant(TrueV)) { 10313 SDValue C = 10314 DAG.getSetCC(DL, VT, LHS, RHS, ISD::getSetCCInverse(CCVal, VT)); 10315 SDValue Neg = DAG.getNegative(C, DL, VT); 10316 return DAG.getNode(ISD::AND, DL, VT, Neg, FalseV); 10317 } 10318 // (select c, y, 0) -> -c & y 10319 if (isNullConstant(FalseV)) { 10320 SDValue C = DAG.getSetCC(DL, VT, LHS, RHS, CCVal); 10321 SDValue Neg = DAG.getNegative(C, DL, VT); 10322 return DAG.getNode(ISD::AND, DL, VT, Neg, TrueV); 10323 } 10324 } 10325 10326 return SDValue(); 10327 } 10328 case RISCVISD::BR_CC: { 10329 SDValue LHS = N->getOperand(1); 10330 SDValue RHS = N->getOperand(2); 10331 SDValue CC = N->getOperand(3); 10332 SDLoc DL(N); 10333 10334 if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget)) 10335 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 10336 N->getOperand(0), LHS, RHS, CC, N->getOperand(4)); 10337 10338 return SDValue(); 10339 } 10340 case ISD::BITREVERSE: 10341 return performBITREVERSECombine(N, DAG, Subtarget); 10342 case ISD::FP_TO_SINT: 10343 case ISD::FP_TO_UINT: 10344 return performFP_TO_INTCombine(N, DCI, Subtarget); 10345 case ISD::FP_TO_SINT_SAT: 10346 case ISD::FP_TO_UINT_SAT: 10347 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 10348 case ISD::FCOPYSIGN: { 10349 EVT VT = N->getValueType(0); 10350 if (!VT.isVector()) 10351 break; 10352 // There is a form of VFSGNJ which injects the negated sign of its second 10353 // operand. Try and bubble any FNEG up after the extend/round to produce 10354 // this optimized pattern. Avoid modifying cases where FP_ROUND and 10355 // TRUNC=1. 10356 SDValue In2 = N->getOperand(1); 10357 // Avoid cases where the extend/round has multiple uses, as duplicating 10358 // those is typically more expensive than removing a fneg. 10359 if (!In2.hasOneUse()) 10360 break; 10361 if (In2.getOpcode() != ISD::FP_EXTEND && 10362 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 10363 break; 10364 In2 = In2.getOperand(0); 10365 if (In2.getOpcode() != ISD::FNEG) 10366 break; 10367 SDLoc DL(N); 10368 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 10369 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 10370 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 10371 } 10372 case ISD::MGATHER: 10373 case ISD::MSCATTER: 10374 case ISD::VP_GATHER: 10375 case ISD::VP_SCATTER: { 10376 if (!DCI.isBeforeLegalize()) 10377 break; 10378 SDValue Index, ScaleOp; 10379 bool IsIndexSigned = false; 10380 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 10381 Index = VPGSN->getIndex(); 10382 ScaleOp = VPGSN->getScale(); 10383 IsIndexSigned = VPGSN->isIndexSigned(); 10384 assert(!VPGSN->isIndexScaled() && 10385 "Scaled gather/scatter should not be formed"); 10386 } else { 10387 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 10388 Index = MGSN->getIndex(); 10389 ScaleOp = MGSN->getScale(); 10390 IsIndexSigned = MGSN->isIndexSigned(); 10391 assert(!MGSN->isIndexScaled() && 10392 "Scaled gather/scatter should not be formed"); 10393 10394 } 10395 EVT IndexVT = Index.getValueType(); 10396 MVT XLenVT = Subtarget.getXLenVT(); 10397 // RISCV indexed loads only support the "unsigned unscaled" addressing 10398 // mode, so anything else must be manually legalized. 10399 bool NeedsIdxLegalization = 10400 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 10401 if (!NeedsIdxLegalization) 10402 break; 10403 10404 SDLoc DL(N); 10405 10406 // Any index legalization should first promote to XLenVT, so we don't lose 10407 // bits when scaling. This may create an illegal index type so we let 10408 // LLVM's legalization take care of the splitting. 10409 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 10410 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 10411 IndexVT = IndexVT.changeVectorElementType(XLenVT); 10412 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 10413 DL, IndexVT, Index); 10414 } 10415 10416 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED; 10417 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 10418 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 10419 {VPGN->getChain(), VPGN->getBasePtr(), Index, 10420 ScaleOp, VPGN->getMask(), 10421 VPGN->getVectorLength()}, 10422 VPGN->getMemOperand(), NewIndexTy); 10423 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 10424 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 10425 {VPSN->getChain(), VPSN->getValue(), 10426 VPSN->getBasePtr(), Index, ScaleOp, 10427 VPSN->getMask(), VPSN->getVectorLength()}, 10428 VPSN->getMemOperand(), NewIndexTy); 10429 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 10430 return DAG.getMaskedGather( 10431 N->getVTList(), MGN->getMemoryVT(), DL, 10432 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 10433 MGN->getBasePtr(), Index, ScaleOp}, 10434 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 10435 const auto *MSN = cast<MaskedScatterSDNode>(N); 10436 return DAG.getMaskedScatter( 10437 N->getVTList(), MSN->getMemoryVT(), DL, 10438 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 10439 Index, ScaleOp}, 10440 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 10441 } 10442 case RISCVISD::SRA_VL: 10443 case RISCVISD::SRL_VL: 10444 case RISCVISD::SHL_VL: { 10445 SDValue ShAmt = N->getOperand(1); 10446 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 10447 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 10448 SDLoc DL(N); 10449 SDValue VL = N->getOperand(3); 10450 EVT VT = N->getValueType(0); 10451 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 10452 ShAmt.getOperand(1), VL); 10453 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 10454 N->getOperand(2), N->getOperand(3), N->getOperand(4)); 10455 } 10456 break; 10457 } 10458 case ISD::SRA: 10459 if (SDValue V = performSRACombine(N, DAG, Subtarget)) 10460 return V; 10461 [[fallthrough]]; 10462 case ISD::SRL: 10463 case ISD::SHL: { 10464 SDValue ShAmt = N->getOperand(1); 10465 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 10466 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 10467 SDLoc DL(N); 10468 EVT VT = N->getValueType(0); 10469 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 10470 ShAmt.getOperand(1), 10471 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 10472 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 10473 } 10474 break; 10475 } 10476 case RISCVISD::ADD_VL: 10477 case RISCVISD::SUB_VL: 10478 case RISCVISD::VWADD_W_VL: 10479 case RISCVISD::VWADDU_W_VL: 10480 case RISCVISD::VWSUB_W_VL: 10481 case RISCVISD::VWSUBU_W_VL: 10482 case RISCVISD::MUL_VL: 10483 return combineBinOp_VLToVWBinOp_VL(N, DCI); 10484 case RISCVISD::VFMADD_VL: 10485 case RISCVISD::VFNMADD_VL: 10486 case RISCVISD::VFMSUB_VL: 10487 case RISCVISD::VFNMSUB_VL: { 10488 // Fold FNEG_VL into FMA opcodes. 10489 SDValue A = N->getOperand(0); 10490 SDValue B = N->getOperand(1); 10491 SDValue C = N->getOperand(2); 10492 SDValue Mask = N->getOperand(3); 10493 SDValue VL = N->getOperand(4); 10494 10495 auto invertIfNegative = [&Mask, &VL](SDValue &V) { 10496 if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask && 10497 V.getOperand(2) == VL) { 10498 // Return the negated input. 10499 V = V.getOperand(0); 10500 return true; 10501 } 10502 10503 return false; 10504 }; 10505 10506 bool NegA = invertIfNegative(A); 10507 bool NegB = invertIfNegative(B); 10508 bool NegC = invertIfNegative(C); 10509 10510 // If no operands are negated, we're done. 10511 if (!NegA && !NegB && !NegC) 10512 return SDValue(); 10513 10514 unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC); 10515 return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask, 10516 VL); 10517 } 10518 case ISD::STORE: { 10519 auto *Store = cast<StoreSDNode>(N); 10520 SDValue Val = Store->getValue(); 10521 // Combine store of vmv.x.s/vfmv.f.s to vse with VL of 1. 10522 // vfmv.f.s is represented as extract element from 0. Match it late to avoid 10523 // any illegal types. 10524 if (Val.getOpcode() == RISCVISD::VMV_X_S || 10525 (DCI.isAfterLegalizeDAG() && 10526 Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 10527 isNullConstant(Val.getOperand(1)))) { 10528 SDValue Src = Val.getOperand(0); 10529 MVT VecVT = Src.getSimpleValueType(); 10530 EVT MemVT = Store->getMemoryVT(); 10531 // VecVT should be scalable and memory VT should match the element type. 10532 if (VecVT.isScalableVector() && 10533 MemVT == VecVT.getVectorElementType()) { 10534 SDLoc DL(N); 10535 MVT MaskVT = getMaskTypeFor(VecVT); 10536 return DAG.getStoreVP( 10537 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 10538 DAG.getConstant(1, DL, MaskVT), 10539 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 10540 Store->getMemOperand(), Store->getAddressingMode(), 10541 Store->isTruncatingStore(), /*IsCompress*/ false); 10542 } 10543 } 10544 10545 break; 10546 } 10547 case ISD::SPLAT_VECTOR: { 10548 EVT VT = N->getValueType(0); 10549 // Only perform this combine on legal MVT types. 10550 if (!isTypeLegal(VT)) 10551 break; 10552 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 10553 DAG, Subtarget)) 10554 return Gather; 10555 break; 10556 } 10557 case RISCVISD::VMV_V_X_VL: { 10558 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 10559 // scalar input. 10560 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 10561 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 10562 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 10563 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 10564 return SDValue(N, 0); 10565 10566 break; 10567 } 10568 case RISCVISD::VFMV_S_F_VL: { 10569 SDValue Src = N->getOperand(1); 10570 // Try to remove vector->scalar->vector if the scalar->vector is inserting 10571 // into an undef vector. 10572 // TODO: Could use a vslide or vmv.v.v for non-undef. 10573 if (N->getOperand(0).isUndef() && 10574 Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 10575 isNullConstant(Src.getOperand(1)) && 10576 Src.getOperand(0).getValueType().isScalableVector()) { 10577 EVT VT = N->getValueType(0); 10578 EVT SrcVT = Src.getOperand(0).getValueType(); 10579 assert(SrcVT.getVectorElementType() == VT.getVectorElementType()); 10580 // Widths match, just return the original vector. 10581 if (SrcVT == VT) 10582 return Src.getOperand(0); 10583 // TODO: Use insert_subvector/extract_subvector to change widen/narrow? 10584 } 10585 break; 10586 } 10587 case ISD::INTRINSIC_WO_CHAIN: { 10588 unsigned IntNo = N->getConstantOperandVal(0); 10589 switch (IntNo) { 10590 // By default we do not combine any intrinsic. 10591 default: 10592 return SDValue(); 10593 case Intrinsic::riscv_vcpop: 10594 case Intrinsic::riscv_vcpop_mask: 10595 case Intrinsic::riscv_vfirst: 10596 case Intrinsic::riscv_vfirst_mask: { 10597 SDValue VL = N->getOperand(2); 10598 if (IntNo == Intrinsic::riscv_vcpop_mask || 10599 IntNo == Intrinsic::riscv_vfirst_mask) 10600 VL = N->getOperand(3); 10601 if (!isNullConstant(VL)) 10602 return SDValue(); 10603 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 10604 SDLoc DL(N); 10605 EVT VT = N->getValueType(0); 10606 if (IntNo == Intrinsic::riscv_vfirst || 10607 IntNo == Intrinsic::riscv_vfirst_mask) 10608 return DAG.getConstant(-1, DL, VT); 10609 return DAG.getConstant(0, DL, VT); 10610 } 10611 } 10612 } 10613 case ISD::BITCAST: { 10614 assert(Subtarget.useRVVForFixedLengthVectors()); 10615 SDValue N0 = N->getOperand(0); 10616 EVT VT = N->getValueType(0); 10617 EVT SrcVT = N0.getValueType(); 10618 // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer 10619 // type, widen both sides to avoid a trip through memory. 10620 if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) && 10621 VT.isScalarInteger()) { 10622 unsigned NumConcats = 8 / SrcVT.getVectorNumElements(); 10623 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT)); 10624 Ops[0] = N0; 10625 SDLoc DL(N); 10626 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops); 10627 N0 = DAG.getBitcast(MVT::i8, N0); 10628 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0); 10629 } 10630 10631 return SDValue(); 10632 } 10633 } 10634 10635 return SDValue(); 10636 } 10637 10638 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 10639 const SDNode *N, CombineLevel Level) const { 10640 assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA || 10641 N->getOpcode() == ISD::SRL) && 10642 "Expected shift op"); 10643 10644 // The following folds are only desirable if `(OP _, c1 << c2)` can be 10645 // materialised in fewer instructions than `(OP _, c1)`: 10646 // 10647 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 10648 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 10649 SDValue N0 = N->getOperand(0); 10650 EVT Ty = N0.getValueType(); 10651 if (Ty.isScalarInteger() && 10652 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 10653 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 10654 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10655 if (C1 && C2) { 10656 const APInt &C1Int = C1->getAPIntValue(); 10657 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 10658 10659 // We can materialise `c1 << c2` into an add immediate, so it's "free", 10660 // and the combine should happen, to potentially allow further combines 10661 // later. 10662 if (ShiftedC1Int.getMinSignedBits() <= 64 && 10663 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 10664 return true; 10665 10666 // We can materialise `c1` in an add immediate, so it's "free", and the 10667 // combine should be prevented. 10668 if (C1Int.getMinSignedBits() <= 64 && 10669 isLegalAddImmediate(C1Int.getSExtValue())) 10670 return false; 10671 10672 // Neither constant will fit into an immediate, so find materialisation 10673 // costs. 10674 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 10675 Subtarget.getFeatureBits(), 10676 /*CompressionCost*/true); 10677 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 10678 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 10679 /*CompressionCost*/true); 10680 10681 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 10682 // combine should be prevented. 10683 if (C1Cost < ShiftedC1Cost) 10684 return false; 10685 } 10686 } 10687 return true; 10688 } 10689 10690 bool RISCVTargetLowering::targetShrinkDemandedConstant( 10691 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 10692 TargetLoweringOpt &TLO) const { 10693 // Delay this optimization as late as possible. 10694 if (!TLO.LegalOps) 10695 return false; 10696 10697 EVT VT = Op.getValueType(); 10698 if (VT.isVector()) 10699 return false; 10700 10701 unsigned Opcode = Op.getOpcode(); 10702 if (Opcode != ISD::AND && Opcode != ISD::OR && Opcode != ISD::XOR) 10703 return false; 10704 10705 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 10706 if (!C) 10707 return false; 10708 10709 const APInt &Mask = C->getAPIntValue(); 10710 10711 // Clear all non-demanded bits initially. 10712 APInt ShrunkMask = Mask & DemandedBits; 10713 10714 // Try to make a smaller immediate by setting undemanded bits. 10715 10716 APInt ExpandedMask = Mask | ~DemandedBits; 10717 10718 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 10719 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 10720 }; 10721 auto UseMask = [Mask, Op, &TLO](const APInt &NewMask) -> bool { 10722 if (NewMask == Mask) 10723 return true; 10724 SDLoc DL(Op); 10725 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, Op.getValueType()); 10726 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), DL, Op.getValueType(), 10727 Op.getOperand(0), NewC); 10728 return TLO.CombineTo(Op, NewOp); 10729 }; 10730 10731 // If the shrunk mask fits in sign extended 12 bits, let the target 10732 // independent code apply it. 10733 if (ShrunkMask.isSignedIntN(12)) 10734 return false; 10735 10736 // And has a few special cases for zext. 10737 if (Opcode == ISD::AND) { 10738 // Preserve (and X, 0xffff), if zext.h exists use zext.h, 10739 // otherwise use SLLI + SRLI. 10740 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 10741 if (IsLegalMask(NewMask)) 10742 return UseMask(NewMask); 10743 10744 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 10745 if (VT == MVT::i64) { 10746 APInt NewMask = APInt(64, 0xffffffff); 10747 if (IsLegalMask(NewMask)) 10748 return UseMask(NewMask); 10749 } 10750 } 10751 10752 // For the remaining optimizations, we need to be able to make a negative 10753 // number through a combination of mask and undemanded bits. 10754 if (!ExpandedMask.isNegative()) 10755 return false; 10756 10757 // What is the fewest number of bits we need to represent the negative number. 10758 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 10759 10760 // Try to make a 12 bit negative immediate. If that fails try to make a 32 10761 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 10762 // If we can't create a simm12, we shouldn't change opaque constants. 10763 APInt NewMask = ShrunkMask; 10764 if (MinSignedBits <= 12) 10765 NewMask.setBitsFrom(11); 10766 else if (!C->isOpaque() && MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 10767 NewMask.setBitsFrom(31); 10768 else 10769 return false; 10770 10771 // Check that our new mask is a subset of the demanded mask. 10772 assert(IsLegalMask(NewMask)); 10773 return UseMask(NewMask); 10774 } 10775 10776 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 10777 static const uint64_t GREVMasks[] = { 10778 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 10779 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 10780 10781 for (unsigned Stage = 0; Stage != 6; ++Stage) { 10782 unsigned Shift = 1 << Stage; 10783 if (ShAmt & Shift) { 10784 uint64_t Mask = GREVMasks[Stage]; 10785 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 10786 if (IsGORC) 10787 Res |= x; 10788 x = Res; 10789 } 10790 } 10791 10792 return x; 10793 } 10794 10795 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 10796 KnownBits &Known, 10797 const APInt &DemandedElts, 10798 const SelectionDAG &DAG, 10799 unsigned Depth) const { 10800 unsigned BitWidth = Known.getBitWidth(); 10801 unsigned Opc = Op.getOpcode(); 10802 assert((Opc >= ISD::BUILTIN_OP_END || 10803 Opc == ISD::INTRINSIC_WO_CHAIN || 10804 Opc == ISD::INTRINSIC_W_CHAIN || 10805 Opc == ISD::INTRINSIC_VOID) && 10806 "Should use MaskedValueIsZero if you don't know whether Op" 10807 " is a target node!"); 10808 10809 Known.resetAll(); 10810 switch (Opc) { 10811 default: break; 10812 case RISCVISD::SELECT_CC: { 10813 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 10814 // If we don't know any bits, early out. 10815 if (Known.isUnknown()) 10816 break; 10817 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 10818 10819 // Only known if known in both the LHS and RHS. 10820 Known = KnownBits::commonBits(Known, Known2); 10821 break; 10822 } 10823 case RISCVISD::REMUW: { 10824 KnownBits Known2; 10825 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 10826 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 10827 // We only care about the lower 32 bits. 10828 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 10829 // Restore the original width by sign extending. 10830 Known = Known.sext(BitWidth); 10831 break; 10832 } 10833 case RISCVISD::DIVUW: { 10834 KnownBits Known2; 10835 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 10836 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 10837 // We only care about the lower 32 bits. 10838 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 10839 // Restore the original width by sign extending. 10840 Known = Known.sext(BitWidth); 10841 break; 10842 } 10843 case RISCVISD::CTZW: { 10844 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 10845 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 10846 unsigned LowBits = llvm::bit_width(PossibleTZ); 10847 Known.Zero.setBitsFrom(LowBits); 10848 break; 10849 } 10850 case RISCVISD::CLZW: { 10851 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 10852 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 10853 unsigned LowBits = llvm::bit_width(PossibleLZ); 10854 Known.Zero.setBitsFrom(LowBits); 10855 break; 10856 } 10857 case RISCVISD::BREV8: 10858 case RISCVISD::ORC_B: { 10859 // FIXME: This is based on the non-ratified Zbp GREV and GORC where a 10860 // control value of 7 is equivalent to brev8 and orc.b. 10861 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 10862 bool IsGORC = Op.getOpcode() == RISCVISD::ORC_B; 10863 // To compute zeros, we need to invert the value and invert it back after. 10864 Known.Zero = 10865 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), 7, IsGORC); 10866 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), 7, IsGORC); 10867 break; 10868 } 10869 case RISCVISD::READ_VLENB: { 10870 // We can use the minimum and maximum VLEN values to bound VLENB. We 10871 // know VLEN must be a power of two. 10872 const unsigned MinVLenB = Subtarget.getRealMinVLen() / 8; 10873 const unsigned MaxVLenB = Subtarget.getRealMaxVLen() / 8; 10874 assert(MinVLenB > 0 && "READ_VLENB without vector extension enabled?"); 10875 Known.Zero.setLowBits(Log2_32(MinVLenB)); 10876 Known.Zero.setBitsFrom(Log2_32(MaxVLenB)+1); 10877 if (MaxVLenB == MinVLenB) 10878 Known.One.setBit(Log2_32(MinVLenB)); 10879 break; 10880 } 10881 case ISD::INTRINSIC_W_CHAIN: 10882 case ISD::INTRINSIC_WO_CHAIN: { 10883 unsigned IntNo = 10884 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 10885 switch (IntNo) { 10886 default: 10887 // We can't do anything for most intrinsics. 10888 break; 10889 case Intrinsic::riscv_vsetvli: 10890 case Intrinsic::riscv_vsetvlimax: 10891 case Intrinsic::riscv_vsetvli_opt: 10892 case Intrinsic::riscv_vsetvlimax_opt: 10893 // Assume that VL output is positive and would fit in an int32_t. 10894 // TODO: VLEN might be capped at 16 bits in a future V spec update. 10895 if (BitWidth >= 32) 10896 Known.Zero.setBitsFrom(31); 10897 break; 10898 } 10899 break; 10900 } 10901 } 10902 } 10903 10904 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 10905 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 10906 unsigned Depth) const { 10907 switch (Op.getOpcode()) { 10908 default: 10909 break; 10910 case RISCVISD::SELECT_CC: { 10911 unsigned Tmp = 10912 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 10913 if (Tmp == 1) return 1; // Early out. 10914 unsigned Tmp2 = 10915 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 10916 return std::min(Tmp, Tmp2); 10917 } 10918 case RISCVISD::ABSW: { 10919 // We expand this at isel to negw+max. The result will have 33 sign bits 10920 // if the input has at least 33 sign bits. 10921 unsigned Tmp = 10922 DAG.ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 10923 if (Tmp < 33) return 1; 10924 return 33; 10925 } 10926 case RISCVISD::SLLW: 10927 case RISCVISD::SRAW: 10928 case RISCVISD::SRLW: 10929 case RISCVISD::DIVW: 10930 case RISCVISD::DIVUW: 10931 case RISCVISD::REMUW: 10932 case RISCVISD::ROLW: 10933 case RISCVISD::RORW: 10934 case RISCVISD::FCVT_W_RV64: 10935 case RISCVISD::FCVT_WU_RV64: 10936 case RISCVISD::STRICT_FCVT_W_RV64: 10937 case RISCVISD::STRICT_FCVT_WU_RV64: 10938 // TODO: As the result is sign-extended, this is conservatively correct. A 10939 // more precise answer could be calculated for SRAW depending on known 10940 // bits in the shift amount. 10941 return 33; 10942 case RISCVISD::VMV_X_S: { 10943 // The number of sign bits of the scalar result is computed by obtaining the 10944 // element type of the input vector operand, subtracting its width from the 10945 // XLEN, and then adding one (sign bit within the element type). If the 10946 // element type is wider than XLen, the least-significant XLEN bits are 10947 // taken. 10948 unsigned XLen = Subtarget.getXLen(); 10949 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 10950 if (EltBits <= XLen) 10951 return XLen - EltBits + 1; 10952 break; 10953 } 10954 case ISD::INTRINSIC_W_CHAIN: { 10955 unsigned IntNo = Op.getConstantOperandVal(1); 10956 switch (IntNo) { 10957 default: 10958 break; 10959 case Intrinsic::riscv_masked_atomicrmw_xchg_i64: 10960 case Intrinsic::riscv_masked_atomicrmw_add_i64: 10961 case Intrinsic::riscv_masked_atomicrmw_sub_i64: 10962 case Intrinsic::riscv_masked_atomicrmw_nand_i64: 10963 case Intrinsic::riscv_masked_atomicrmw_max_i64: 10964 case Intrinsic::riscv_masked_atomicrmw_min_i64: 10965 case Intrinsic::riscv_masked_atomicrmw_umax_i64: 10966 case Intrinsic::riscv_masked_atomicrmw_umin_i64: 10967 case Intrinsic::riscv_masked_cmpxchg_i64: 10968 // riscv_masked_{atomicrmw_*,cmpxchg} intrinsics represent an emulated 10969 // narrow atomic operation. These are implemented using atomic 10970 // operations at the minimum supported atomicrmw/cmpxchg width whose 10971 // result is then sign extended to XLEN. With +A, the minimum width is 10972 // 32 for both 64 and 32. 10973 assert(Subtarget.getXLen() == 64); 10974 assert(getMinCmpXchgSizeInBits() == 32); 10975 assert(Subtarget.hasStdExtA()); 10976 return 33; 10977 } 10978 } 10979 } 10980 10981 return 1; 10982 } 10983 10984 const Constant * 10985 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const { 10986 assert(Ld && "Unexpected null LoadSDNode"); 10987 if (!ISD::isNormalLoad(Ld)) 10988 return nullptr; 10989 10990 SDValue Ptr = Ld->getBasePtr(); 10991 10992 // Only constant pools with no offset are supported. 10993 auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * { 10994 auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr); 10995 if (!CNode || CNode->isMachineConstantPoolEntry() || 10996 CNode->getOffset() != 0) 10997 return nullptr; 10998 10999 return CNode; 11000 }; 11001 11002 // Simple case, LLA. 11003 if (Ptr.getOpcode() == RISCVISD::LLA) { 11004 auto *CNode = GetSupportedConstantPool(Ptr); 11005 if (!CNode || CNode->getTargetFlags() != 0) 11006 return nullptr; 11007 11008 return CNode->getConstVal(); 11009 } 11010 11011 // Look for a HI and ADD_LO pair. 11012 if (Ptr.getOpcode() != RISCVISD::ADD_LO || 11013 Ptr.getOperand(0).getOpcode() != RISCVISD::HI) 11014 return nullptr; 11015 11016 auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1)); 11017 auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0)); 11018 11019 if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO || 11020 !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI) 11021 return nullptr; 11022 11023 if (CNodeLo->getConstVal() != CNodeHi->getConstVal()) 11024 return nullptr; 11025 11026 return CNodeLo->getConstVal(); 11027 } 11028 11029 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 11030 MachineBasicBlock *BB) { 11031 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 11032 11033 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 11034 // Should the count have wrapped while it was being read, we need to try 11035 // again. 11036 // ... 11037 // read: 11038 // rdcycleh x3 # load high word of cycle 11039 // rdcycle x2 # load low word of cycle 11040 // rdcycleh x4 # load high word of cycle 11041 // bne x3, x4, read # check if high word reads match, otherwise try again 11042 // ... 11043 11044 MachineFunction &MF = *BB->getParent(); 11045 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11046 MachineFunction::iterator It = ++BB->getIterator(); 11047 11048 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 11049 MF.insert(It, LoopMBB); 11050 11051 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 11052 MF.insert(It, DoneMBB); 11053 11054 // Transfer the remainder of BB and its successor edges to DoneMBB. 11055 DoneMBB->splice(DoneMBB->begin(), BB, 11056 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11057 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 11058 11059 BB->addSuccessor(LoopMBB); 11060 11061 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 11062 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 11063 Register LoReg = MI.getOperand(0).getReg(); 11064 Register HiReg = MI.getOperand(1).getReg(); 11065 DebugLoc DL = MI.getDebugLoc(); 11066 11067 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 11068 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 11069 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 11070 .addReg(RISCV::X0); 11071 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 11072 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 11073 .addReg(RISCV::X0); 11074 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 11075 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 11076 .addReg(RISCV::X0); 11077 11078 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 11079 .addReg(HiReg) 11080 .addReg(ReadAgainReg) 11081 .addMBB(LoopMBB); 11082 11083 LoopMBB->addSuccessor(LoopMBB); 11084 LoopMBB->addSuccessor(DoneMBB); 11085 11086 MI.eraseFromParent(); 11087 11088 return DoneMBB; 11089 } 11090 11091 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 11092 MachineBasicBlock *BB) { 11093 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 11094 11095 MachineFunction &MF = *BB->getParent(); 11096 DebugLoc DL = MI.getDebugLoc(); 11097 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 11098 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 11099 Register LoReg = MI.getOperand(0).getReg(); 11100 Register HiReg = MI.getOperand(1).getReg(); 11101 Register SrcReg = MI.getOperand(2).getReg(); 11102 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 11103 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 11104 11105 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 11106 RI, Register()); 11107 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 11108 MachineMemOperand *MMOLo = 11109 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 11110 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 11111 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 11112 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 11113 .addFrameIndex(FI) 11114 .addImm(0) 11115 .addMemOperand(MMOLo); 11116 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 11117 .addFrameIndex(FI) 11118 .addImm(4) 11119 .addMemOperand(MMOHi); 11120 MI.eraseFromParent(); // The pseudo instruction is gone now. 11121 return BB; 11122 } 11123 11124 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 11125 MachineBasicBlock *BB) { 11126 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 11127 "Unexpected instruction"); 11128 11129 MachineFunction &MF = *BB->getParent(); 11130 DebugLoc DL = MI.getDebugLoc(); 11131 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 11132 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 11133 Register DstReg = MI.getOperand(0).getReg(); 11134 Register LoReg = MI.getOperand(1).getReg(); 11135 Register HiReg = MI.getOperand(2).getReg(); 11136 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 11137 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 11138 11139 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 11140 MachineMemOperand *MMOLo = 11141 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 11142 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 11143 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 11144 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 11145 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 11146 .addFrameIndex(FI) 11147 .addImm(0) 11148 .addMemOperand(MMOLo); 11149 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 11150 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 11151 .addFrameIndex(FI) 11152 .addImm(4) 11153 .addMemOperand(MMOHi); 11154 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI, Register()); 11155 MI.eraseFromParent(); // The pseudo instruction is gone now. 11156 return BB; 11157 } 11158 11159 static bool isSelectPseudo(MachineInstr &MI) { 11160 switch (MI.getOpcode()) { 11161 default: 11162 return false; 11163 case RISCV::Select_GPR_Using_CC_GPR: 11164 case RISCV::Select_FPR16_Using_CC_GPR: 11165 case RISCV::Select_FPR32_Using_CC_GPR: 11166 case RISCV::Select_FPR64_Using_CC_GPR: 11167 return true; 11168 } 11169 } 11170 11171 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 11172 unsigned RelOpcode, unsigned EqOpcode, 11173 const RISCVSubtarget &Subtarget) { 11174 DebugLoc DL = MI.getDebugLoc(); 11175 Register DstReg = MI.getOperand(0).getReg(); 11176 Register Src1Reg = MI.getOperand(1).getReg(); 11177 Register Src2Reg = MI.getOperand(2).getReg(); 11178 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 11179 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 11180 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 11181 11182 // Save the current FFLAGS. 11183 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 11184 11185 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 11186 .addReg(Src1Reg) 11187 .addReg(Src2Reg); 11188 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 11189 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 11190 11191 // Restore the FFLAGS. 11192 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 11193 .addReg(SavedFFlags, RegState::Kill); 11194 11195 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 11196 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 11197 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 11198 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 11199 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 11200 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 11201 11202 // Erase the pseudoinstruction. 11203 MI.eraseFromParent(); 11204 return BB; 11205 } 11206 11207 static MachineBasicBlock * 11208 EmitLoweredCascadedSelect(MachineInstr &First, MachineInstr &Second, 11209 MachineBasicBlock *ThisMBB, 11210 const RISCVSubtarget &Subtarget) { 11211 // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5) 11212 // Without this, custom-inserter would have generated: 11213 // 11214 // A 11215 // | \ 11216 // | B 11217 // | / 11218 // C 11219 // | \ 11220 // | D 11221 // | / 11222 // E 11223 // 11224 // A: X = ...; Y = ... 11225 // B: empty 11226 // C: Z = PHI [X, A], [Y, B] 11227 // D: empty 11228 // E: PHI [X, C], [Z, D] 11229 // 11230 // If we lower both Select_FPRX_ in a single step, we can instead generate: 11231 // 11232 // A 11233 // | \ 11234 // | C 11235 // | /| 11236 // |/ | 11237 // | | 11238 // | D 11239 // | / 11240 // E 11241 // 11242 // A: X = ...; Y = ... 11243 // D: empty 11244 // E: PHI [X, A], [X, C], [Y, D] 11245 11246 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 11247 const DebugLoc &DL = First.getDebugLoc(); 11248 const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock(); 11249 MachineFunction *F = ThisMBB->getParent(); 11250 MachineBasicBlock *FirstMBB = F->CreateMachineBasicBlock(LLVM_BB); 11251 MachineBasicBlock *SecondMBB = F->CreateMachineBasicBlock(LLVM_BB); 11252 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11253 MachineFunction::iterator It = ++ThisMBB->getIterator(); 11254 F->insert(It, FirstMBB); 11255 F->insert(It, SecondMBB); 11256 F->insert(It, SinkMBB); 11257 11258 // Transfer the remainder of ThisMBB and its successor edges to SinkMBB. 11259 SinkMBB->splice(SinkMBB->begin(), ThisMBB, 11260 std::next(MachineBasicBlock::iterator(First)), 11261 ThisMBB->end()); 11262 SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB); 11263 11264 // Fallthrough block for ThisMBB. 11265 ThisMBB->addSuccessor(FirstMBB); 11266 // Fallthrough block for FirstMBB. 11267 FirstMBB->addSuccessor(SecondMBB); 11268 ThisMBB->addSuccessor(SinkMBB); 11269 FirstMBB->addSuccessor(SinkMBB); 11270 // This is fallthrough. 11271 SecondMBB->addSuccessor(SinkMBB); 11272 11273 auto FirstCC = static_cast<RISCVCC::CondCode>(First.getOperand(3).getImm()); 11274 Register FLHS = First.getOperand(1).getReg(); 11275 Register FRHS = First.getOperand(2).getReg(); 11276 // Insert appropriate branch. 11277 BuildMI(FirstMBB, DL, TII.getBrCond(FirstCC)) 11278 .addReg(FLHS) 11279 .addReg(FRHS) 11280 .addMBB(SinkMBB); 11281 11282 Register SLHS = Second.getOperand(1).getReg(); 11283 Register SRHS = Second.getOperand(2).getReg(); 11284 Register Op1Reg4 = First.getOperand(4).getReg(); 11285 Register Op1Reg5 = First.getOperand(5).getReg(); 11286 11287 auto SecondCC = static_cast<RISCVCC::CondCode>(Second.getOperand(3).getImm()); 11288 // Insert appropriate branch. 11289 BuildMI(ThisMBB, DL, TII.getBrCond(SecondCC)) 11290 .addReg(SLHS) 11291 .addReg(SRHS) 11292 .addMBB(SinkMBB); 11293 11294 Register DestReg = Second.getOperand(0).getReg(); 11295 Register Op2Reg4 = Second.getOperand(4).getReg(); 11296 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII.get(RISCV::PHI), DestReg) 11297 .addReg(Op2Reg4) 11298 .addMBB(ThisMBB) 11299 .addReg(Op1Reg4) 11300 .addMBB(FirstMBB) 11301 .addReg(Op1Reg5) 11302 .addMBB(SecondMBB); 11303 11304 // Now remove the Select_FPRX_s. 11305 First.eraseFromParent(); 11306 Second.eraseFromParent(); 11307 return SinkMBB; 11308 } 11309 11310 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 11311 MachineBasicBlock *BB, 11312 const RISCVSubtarget &Subtarget) { 11313 // To "insert" Select_* instructions, we actually have to insert the triangle 11314 // control-flow pattern. The incoming instructions know the destination vreg 11315 // to set, the condition code register to branch on, the true/false values to 11316 // select between, and the condcode to use to select the appropriate branch. 11317 // 11318 // We produce the following control flow: 11319 // HeadMBB 11320 // | \ 11321 // | IfFalseMBB 11322 // | / 11323 // TailMBB 11324 // 11325 // When we find a sequence of selects we attempt to optimize their emission 11326 // by sharing the control flow. Currently we only handle cases where we have 11327 // multiple selects with the exact same condition (same LHS, RHS and CC). 11328 // The selects may be interleaved with other instructions if the other 11329 // instructions meet some requirements we deem safe: 11330 // - They are not pseudo instructions. 11331 // - They are debug instructions. Otherwise, 11332 // - They do not have side-effects, do not access memory and their inputs do 11333 // not depend on the results of the select pseudo-instructions. 11334 // The TrueV/FalseV operands of the selects cannot depend on the result of 11335 // previous selects in the sequence. 11336 // These conditions could be further relaxed. See the X86 target for a 11337 // related approach and more information. 11338 // 11339 // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5)) 11340 // is checked here and handled by a separate function - 11341 // EmitLoweredCascadedSelect. 11342 Register LHS = MI.getOperand(1).getReg(); 11343 Register RHS = MI.getOperand(2).getReg(); 11344 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 11345 11346 SmallVector<MachineInstr *, 4> SelectDebugValues; 11347 SmallSet<Register, 4> SelectDests; 11348 SelectDests.insert(MI.getOperand(0).getReg()); 11349 11350 MachineInstr *LastSelectPseudo = &MI; 11351 auto Next = next_nodbg(MI.getIterator(), BB->instr_end()); 11352 if (MI.getOpcode() != RISCV::Select_GPR_Using_CC_GPR && Next != BB->end() && 11353 Next->getOpcode() == MI.getOpcode() && 11354 Next->getOperand(5).getReg() == MI.getOperand(0).getReg() && 11355 Next->getOperand(5).isKill()) { 11356 return EmitLoweredCascadedSelect(MI, *Next, BB, Subtarget); 11357 } 11358 11359 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 11360 SequenceMBBI != E; ++SequenceMBBI) { 11361 if (SequenceMBBI->isDebugInstr()) 11362 continue; 11363 if (isSelectPseudo(*SequenceMBBI)) { 11364 if (SequenceMBBI->getOperand(1).getReg() != LHS || 11365 SequenceMBBI->getOperand(2).getReg() != RHS || 11366 SequenceMBBI->getOperand(3).getImm() != CC || 11367 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 11368 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 11369 break; 11370 LastSelectPseudo = &*SequenceMBBI; 11371 SequenceMBBI->collectDebugValues(SelectDebugValues); 11372 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 11373 continue; 11374 } 11375 if (SequenceMBBI->hasUnmodeledSideEffects() || 11376 SequenceMBBI->mayLoadOrStore() || 11377 SequenceMBBI->usesCustomInsertionHook()) 11378 break; 11379 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 11380 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 11381 })) 11382 break; 11383 } 11384 11385 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 11386 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11387 DebugLoc DL = MI.getDebugLoc(); 11388 MachineFunction::iterator I = ++BB->getIterator(); 11389 11390 MachineBasicBlock *HeadMBB = BB; 11391 MachineFunction *F = BB->getParent(); 11392 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 11393 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 11394 11395 F->insert(I, IfFalseMBB); 11396 F->insert(I, TailMBB); 11397 11398 // Transfer debug instructions associated with the selects to TailMBB. 11399 for (MachineInstr *DebugInstr : SelectDebugValues) { 11400 TailMBB->push_back(DebugInstr->removeFromParent()); 11401 } 11402 11403 // Move all instructions after the sequence to TailMBB. 11404 TailMBB->splice(TailMBB->end(), HeadMBB, 11405 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 11406 // Update machine-CFG edges by transferring all successors of the current 11407 // block to the new block which will contain the Phi nodes for the selects. 11408 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 11409 // Set the successors for HeadMBB. 11410 HeadMBB->addSuccessor(IfFalseMBB); 11411 HeadMBB->addSuccessor(TailMBB); 11412 11413 // Insert appropriate branch. 11414 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 11415 .addReg(LHS) 11416 .addReg(RHS) 11417 .addMBB(TailMBB); 11418 11419 // IfFalseMBB just falls through to TailMBB. 11420 IfFalseMBB->addSuccessor(TailMBB); 11421 11422 // Create PHIs for all of the select pseudo-instructions. 11423 auto SelectMBBI = MI.getIterator(); 11424 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 11425 auto InsertionPoint = TailMBB->begin(); 11426 while (SelectMBBI != SelectEnd) { 11427 auto Next = std::next(SelectMBBI); 11428 if (isSelectPseudo(*SelectMBBI)) { 11429 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 11430 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 11431 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 11432 .addReg(SelectMBBI->getOperand(4).getReg()) 11433 .addMBB(HeadMBB) 11434 .addReg(SelectMBBI->getOperand(5).getReg()) 11435 .addMBB(IfFalseMBB); 11436 SelectMBBI->eraseFromParent(); 11437 } 11438 SelectMBBI = Next; 11439 } 11440 11441 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 11442 return TailMBB; 11443 } 11444 11445 static MachineBasicBlock * 11446 emitVFCVT_RM_MASK(MachineInstr &MI, MachineBasicBlock *BB, unsigned Opcode) { 11447 DebugLoc DL = MI.getDebugLoc(); 11448 11449 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 11450 11451 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 11452 Register SavedFRM = MRI.createVirtualRegister(&RISCV::GPRRegClass); 11453 11454 // Update FRM and save the old value. 11455 BuildMI(*BB, MI, DL, TII.get(RISCV::SwapFRMImm), SavedFRM) 11456 .addImm(MI.getOperand(4).getImm()); 11457 11458 // Emit an VFCVT without the FRM operand. 11459 assert(MI.getNumOperands() == 8); 11460 auto MIB = BuildMI(*BB, MI, DL, TII.get(Opcode)) 11461 .add(MI.getOperand(0)) 11462 .add(MI.getOperand(1)) 11463 .add(MI.getOperand(2)) 11464 .add(MI.getOperand(3)) 11465 .add(MI.getOperand(5)) 11466 .add(MI.getOperand(6)) 11467 .add(MI.getOperand(7)); 11468 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 11469 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 11470 11471 // Restore FRM. 11472 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFRM)) 11473 .addReg(SavedFRM, RegState::Kill); 11474 11475 // Erase the pseudoinstruction. 11476 MI.eraseFromParent(); 11477 return BB; 11478 } 11479 11480 static MachineBasicBlock *emitVFROUND_NOEXCEPT_MASK(MachineInstr &MI, 11481 MachineBasicBlock *BB, 11482 unsigned CVTXOpc, 11483 unsigned CVTFOpc) { 11484 DebugLoc DL = MI.getDebugLoc(); 11485 11486 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 11487 11488 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 11489 Register SavedFFLAGS = MRI.createVirtualRegister(&RISCV::GPRRegClass); 11490 11491 // Save the old value of FFLAGS. 11492 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFLAGS); 11493 11494 assert(MI.getNumOperands() == 7); 11495 11496 // Emit a VFCVT_X_F 11497 const TargetRegisterInfo *TRI = 11498 BB->getParent()->getSubtarget().getRegisterInfo(); 11499 const TargetRegisterClass *RC = MI.getRegClassConstraint(0, &TII, TRI); 11500 Register Tmp = MRI.createVirtualRegister(RC); 11501 BuildMI(*BB, MI, DL, TII.get(CVTXOpc), Tmp) 11502 .add(MI.getOperand(1)) 11503 .add(MI.getOperand(2)) 11504 .add(MI.getOperand(3)) 11505 .add(MI.getOperand(4)) 11506 .add(MI.getOperand(5)) 11507 .add(MI.getOperand(6)); 11508 11509 // Emit a VFCVT_F_X 11510 BuildMI(*BB, MI, DL, TII.get(CVTFOpc)) 11511 .add(MI.getOperand(0)) 11512 .add(MI.getOperand(1)) 11513 .addReg(Tmp) 11514 .add(MI.getOperand(3)) 11515 .add(MI.getOperand(4)) 11516 .add(MI.getOperand(5)) 11517 .add(MI.getOperand(6)); 11518 11519 // Restore FFLAGS. 11520 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 11521 .addReg(SavedFFLAGS, RegState::Kill); 11522 11523 // Erase the pseudoinstruction. 11524 MI.eraseFromParent(); 11525 return BB; 11526 } 11527 11528 static MachineBasicBlock *emitFROUND(MachineInstr &MI, MachineBasicBlock *MBB, 11529 const RISCVSubtarget &Subtarget) { 11530 unsigned CmpOpc, F2IOpc, I2FOpc, FSGNJOpc, FSGNJXOpc; 11531 const TargetRegisterClass *RC; 11532 switch (MI.getOpcode()) { 11533 default: 11534 llvm_unreachable("Unexpected opcode"); 11535 case RISCV::PseudoFROUND_H: 11536 CmpOpc = RISCV::FLT_H; 11537 F2IOpc = RISCV::FCVT_W_H; 11538 I2FOpc = RISCV::FCVT_H_W; 11539 FSGNJOpc = RISCV::FSGNJ_H; 11540 FSGNJXOpc = RISCV::FSGNJX_H; 11541 RC = &RISCV::FPR16RegClass; 11542 break; 11543 case RISCV::PseudoFROUND_S: 11544 CmpOpc = RISCV::FLT_S; 11545 F2IOpc = RISCV::FCVT_W_S; 11546 I2FOpc = RISCV::FCVT_S_W; 11547 FSGNJOpc = RISCV::FSGNJ_S; 11548 FSGNJXOpc = RISCV::FSGNJX_S; 11549 RC = &RISCV::FPR32RegClass; 11550 break; 11551 case RISCV::PseudoFROUND_D: 11552 assert(Subtarget.is64Bit() && "Expected 64-bit GPR."); 11553 CmpOpc = RISCV::FLT_D; 11554 F2IOpc = RISCV::FCVT_L_D; 11555 I2FOpc = RISCV::FCVT_D_L; 11556 FSGNJOpc = RISCV::FSGNJ_D; 11557 FSGNJXOpc = RISCV::FSGNJX_D; 11558 RC = &RISCV::FPR64RegClass; 11559 break; 11560 } 11561 11562 const BasicBlock *BB = MBB->getBasicBlock(); 11563 DebugLoc DL = MI.getDebugLoc(); 11564 MachineFunction::iterator I = ++MBB->getIterator(); 11565 11566 MachineFunction *F = MBB->getParent(); 11567 MachineBasicBlock *CvtMBB = F->CreateMachineBasicBlock(BB); 11568 MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(BB); 11569 11570 F->insert(I, CvtMBB); 11571 F->insert(I, DoneMBB); 11572 // Move all instructions after the sequence to DoneMBB. 11573 DoneMBB->splice(DoneMBB->end(), MBB, MachineBasicBlock::iterator(MI), 11574 MBB->end()); 11575 // Update machine-CFG edges by transferring all successors of the current 11576 // block to the new block which will contain the Phi nodes for the selects. 11577 DoneMBB->transferSuccessorsAndUpdatePHIs(MBB); 11578 // Set the successors for MBB. 11579 MBB->addSuccessor(CvtMBB); 11580 MBB->addSuccessor(DoneMBB); 11581 11582 Register DstReg = MI.getOperand(0).getReg(); 11583 Register SrcReg = MI.getOperand(1).getReg(); 11584 Register MaxReg = MI.getOperand(2).getReg(); 11585 int64_t FRM = MI.getOperand(3).getImm(); 11586 11587 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 11588 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 11589 11590 Register FabsReg = MRI.createVirtualRegister(RC); 11591 BuildMI(MBB, DL, TII.get(FSGNJXOpc), FabsReg).addReg(SrcReg).addReg(SrcReg); 11592 11593 // Compare the FP value to the max value. 11594 Register CmpReg = MRI.createVirtualRegister(&RISCV::GPRRegClass); 11595 auto MIB = 11596 BuildMI(MBB, DL, TII.get(CmpOpc), CmpReg).addReg(FabsReg).addReg(MaxReg); 11597 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 11598 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 11599 11600 // Insert branch. 11601 BuildMI(MBB, DL, TII.get(RISCV::BEQ)) 11602 .addReg(CmpReg) 11603 .addReg(RISCV::X0) 11604 .addMBB(DoneMBB); 11605 11606 CvtMBB->addSuccessor(DoneMBB); 11607 11608 // Convert to integer. 11609 Register F2IReg = MRI.createVirtualRegister(&RISCV::GPRRegClass); 11610 MIB = BuildMI(CvtMBB, DL, TII.get(F2IOpc), F2IReg).addReg(SrcReg).addImm(FRM); 11611 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 11612 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 11613 11614 // Convert back to FP. 11615 Register I2FReg = MRI.createVirtualRegister(RC); 11616 MIB = BuildMI(CvtMBB, DL, TII.get(I2FOpc), I2FReg).addReg(F2IReg).addImm(FRM); 11617 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 11618 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 11619 11620 // Restore the sign bit. 11621 Register CvtReg = MRI.createVirtualRegister(RC); 11622 BuildMI(CvtMBB, DL, TII.get(FSGNJOpc), CvtReg).addReg(I2FReg).addReg(SrcReg); 11623 11624 // Merge the results. 11625 BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(RISCV::PHI), DstReg) 11626 .addReg(SrcReg) 11627 .addMBB(MBB) 11628 .addReg(CvtReg) 11629 .addMBB(CvtMBB); 11630 11631 MI.eraseFromParent(); 11632 return DoneMBB; 11633 } 11634 11635 MachineBasicBlock * 11636 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11637 MachineBasicBlock *BB) const { 11638 switch (MI.getOpcode()) { 11639 default: 11640 llvm_unreachable("Unexpected instr type to insert"); 11641 case RISCV::ReadCycleWide: 11642 assert(!Subtarget.is64Bit() && 11643 "ReadCycleWrite is only to be used on riscv32"); 11644 return emitReadCycleWidePseudo(MI, BB); 11645 case RISCV::Select_GPR_Using_CC_GPR: 11646 case RISCV::Select_FPR16_Using_CC_GPR: 11647 case RISCV::Select_FPR32_Using_CC_GPR: 11648 case RISCV::Select_FPR64_Using_CC_GPR: 11649 return emitSelectPseudo(MI, BB, Subtarget); 11650 case RISCV::BuildPairF64Pseudo: 11651 return emitBuildPairF64Pseudo(MI, BB); 11652 case RISCV::SplitF64Pseudo: 11653 return emitSplitF64Pseudo(MI, BB); 11654 case RISCV::PseudoQuietFLE_H: 11655 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 11656 case RISCV::PseudoQuietFLT_H: 11657 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 11658 case RISCV::PseudoQuietFLE_S: 11659 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 11660 case RISCV::PseudoQuietFLT_S: 11661 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 11662 case RISCV::PseudoQuietFLE_D: 11663 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 11664 case RISCV::PseudoQuietFLT_D: 11665 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 11666 11667 // ========================================================================= 11668 // VFCVT 11669 // ========================================================================= 11670 11671 case RISCV::PseudoVFCVT_RM_X_F_V_M1_MASK: 11672 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M1_MASK); 11673 case RISCV::PseudoVFCVT_RM_X_F_V_M2_MASK: 11674 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M2_MASK); 11675 case RISCV::PseudoVFCVT_RM_X_F_V_M4_MASK: 11676 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M4_MASK); 11677 case RISCV::PseudoVFCVT_RM_X_F_V_M8_MASK: 11678 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M8_MASK); 11679 case RISCV::PseudoVFCVT_RM_X_F_V_MF2_MASK: 11680 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_MF2_MASK); 11681 case RISCV::PseudoVFCVT_RM_X_F_V_MF4_MASK: 11682 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_MF4_MASK); 11683 11684 case RISCV::PseudoVFCVT_RM_XU_F_V_M1_MASK: 11685 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_XU_F_V_M1_MASK); 11686 case RISCV::PseudoVFCVT_RM_XU_F_V_M2_MASK: 11687 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_XU_F_V_M2_MASK); 11688 case RISCV::PseudoVFCVT_RM_XU_F_V_M4_MASK: 11689 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_XU_F_V_M4_MASK); 11690 case RISCV::PseudoVFCVT_RM_XU_F_V_M8_MASK: 11691 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_XU_F_V_M8_MASK); 11692 case RISCV::PseudoVFCVT_RM_XU_F_V_MF2_MASK: 11693 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_XU_F_V_MF2_MASK); 11694 case RISCV::PseudoVFCVT_RM_XU_F_V_MF4_MASK: 11695 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_XU_F_V_MF4_MASK); 11696 11697 case RISCV::PseudoVFCVT_RM_F_XU_V_M1_MASK: 11698 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_XU_V_M1_MASK); 11699 case RISCV::PseudoVFCVT_RM_F_XU_V_M2_MASK: 11700 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_XU_V_M2_MASK); 11701 case RISCV::PseudoVFCVT_RM_F_XU_V_M4_MASK: 11702 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_XU_V_M4_MASK); 11703 case RISCV::PseudoVFCVT_RM_F_XU_V_M8_MASK: 11704 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_XU_V_M8_MASK); 11705 case RISCV::PseudoVFCVT_RM_F_XU_V_MF2_MASK: 11706 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_XU_V_MF2_MASK); 11707 case RISCV::PseudoVFCVT_RM_F_XU_V_MF4_MASK: 11708 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_XU_V_MF4_MASK); 11709 11710 case RISCV::PseudoVFCVT_RM_F_X_V_M1_MASK: 11711 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_X_V_M1_MASK); 11712 case RISCV::PseudoVFCVT_RM_F_X_V_M2_MASK: 11713 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_X_V_M2_MASK); 11714 case RISCV::PseudoVFCVT_RM_F_X_V_M4_MASK: 11715 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_X_V_M4_MASK); 11716 case RISCV::PseudoVFCVT_RM_F_X_V_M8_MASK: 11717 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_X_V_M8_MASK); 11718 case RISCV::PseudoVFCVT_RM_F_X_V_MF2_MASK: 11719 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_X_V_MF2_MASK); 11720 case RISCV::PseudoVFCVT_RM_F_X_V_MF4_MASK: 11721 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_X_V_MF4_MASK); 11722 11723 // ========================================================================= 11724 // VFWCVT 11725 // ========================================================================= 11726 11727 case RISCV::PseudoVFWCVT_RM_XU_F_V_M1_MASK: 11728 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_M1_MASK); 11729 case RISCV::PseudoVFWCVT_RM_XU_F_V_M2_MASK: 11730 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_M2_MASK); 11731 case RISCV::PseudoVFWCVT_RM_XU_F_V_M4_MASK: 11732 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_M4_MASK); 11733 case RISCV::PseudoVFWCVT_RM_XU_F_V_MF2_MASK: 11734 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_MF2_MASK); 11735 case RISCV::PseudoVFWCVT_RM_XU_F_V_MF4_MASK: 11736 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_MF4_MASK); 11737 11738 case RISCV::PseudoVFWCVT_RM_X_F_V_M1_MASK: 11739 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_M1_MASK); 11740 case RISCV::PseudoVFWCVT_RM_X_F_V_M2_MASK: 11741 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_M2_MASK); 11742 case RISCV::PseudoVFWCVT_RM_X_F_V_M4_MASK: 11743 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_M4_MASK); 11744 case RISCV::PseudoVFWCVT_RM_X_F_V_MF2_MASK: 11745 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_MF2_MASK); 11746 case RISCV::PseudoVFWCVT_RM_X_F_V_MF4_MASK: 11747 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_MF4_MASK); 11748 11749 case RISCV::PseudoVFWCVT_RM_F_XU_V_M1_MASK: 11750 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_M1_MASK); 11751 case RISCV::PseudoVFWCVT_RM_F_XU_V_M2_MASK: 11752 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_M2_MASK); 11753 case RISCV::PseudoVFWCVT_RM_F_XU_V_M4_MASK: 11754 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_M4_MASK); 11755 case RISCV::PseudoVFWCVT_RM_F_XU_V_MF2_MASK: 11756 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_MF2_MASK); 11757 case RISCV::PseudoVFWCVT_RM_F_XU_V_MF4_MASK: 11758 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_MF4_MASK); 11759 case RISCV::PseudoVFWCVT_RM_F_XU_V_MF8_MASK: 11760 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_MF8_MASK); 11761 11762 case RISCV::PseudoVFWCVT_RM_F_X_V_M1_MASK: 11763 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_M1_MASK); 11764 case RISCV::PseudoVFWCVT_RM_F_X_V_M2_MASK: 11765 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_M2_MASK); 11766 case RISCV::PseudoVFWCVT_RM_F_X_V_M4_MASK: 11767 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_M4_MASK); 11768 case RISCV::PseudoVFWCVT_RM_F_X_V_MF2_MASK: 11769 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_MF2_MASK); 11770 case RISCV::PseudoVFWCVT_RM_F_X_V_MF4_MASK: 11771 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_MF4_MASK); 11772 case RISCV::PseudoVFWCVT_RM_F_X_V_MF8_MASK: 11773 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_MF8_MASK); 11774 11775 // ========================================================================= 11776 // VFNCVT 11777 // ========================================================================= 11778 11779 case RISCV::PseudoVFNCVT_RM_XU_F_W_M1_MASK: 11780 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_M1_MASK); 11781 case RISCV::PseudoVFNCVT_RM_XU_F_W_M2_MASK: 11782 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_M2_MASK); 11783 case RISCV::PseudoVFNCVT_RM_XU_F_W_M4_MASK: 11784 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_M4_MASK); 11785 case RISCV::PseudoVFNCVT_RM_XU_F_W_MF2_MASK: 11786 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_MF2_MASK); 11787 case RISCV::PseudoVFNCVT_RM_XU_F_W_MF4_MASK: 11788 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_MF4_MASK); 11789 case RISCV::PseudoVFNCVT_RM_XU_F_W_MF8_MASK: 11790 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_XU_F_W_MF8_MASK); 11791 11792 case RISCV::PseudoVFNCVT_RM_X_F_W_M1_MASK: 11793 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_M1_MASK); 11794 case RISCV::PseudoVFNCVT_RM_X_F_W_M2_MASK: 11795 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_M2_MASK); 11796 case RISCV::PseudoVFNCVT_RM_X_F_W_M4_MASK: 11797 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_M4_MASK); 11798 case RISCV::PseudoVFNCVT_RM_X_F_W_MF2_MASK: 11799 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_MF2_MASK); 11800 case RISCV::PseudoVFNCVT_RM_X_F_W_MF4_MASK: 11801 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_MF4_MASK); 11802 case RISCV::PseudoVFNCVT_RM_X_F_W_MF8_MASK: 11803 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_MF8_MASK); 11804 11805 case RISCV::PseudoVFNCVT_RM_F_XU_W_M1_MASK: 11806 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_M1_MASK); 11807 case RISCV::PseudoVFNCVT_RM_F_XU_W_M2_MASK: 11808 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_M2_MASK); 11809 case RISCV::PseudoVFNCVT_RM_F_XU_W_M4_MASK: 11810 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_M4_MASK); 11811 case RISCV::PseudoVFNCVT_RM_F_XU_W_MF2_MASK: 11812 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_MF2_MASK); 11813 case RISCV::PseudoVFNCVT_RM_F_XU_W_MF4_MASK: 11814 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_MF4_MASK); 11815 11816 case RISCV::PseudoVFNCVT_RM_F_X_W_M1_MASK: 11817 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_M1_MASK); 11818 case RISCV::PseudoVFNCVT_RM_F_X_W_M2_MASK: 11819 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_M2_MASK); 11820 case RISCV::PseudoVFNCVT_RM_F_X_W_M4_MASK: 11821 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_M4_MASK); 11822 case RISCV::PseudoVFNCVT_RM_F_X_W_MF2_MASK: 11823 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_MF2_MASK); 11824 case RISCV::PseudoVFNCVT_RM_F_X_W_MF4_MASK: 11825 return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_MF4_MASK); 11826 11827 case RISCV::PseudoVFROUND_NOEXCEPT_V_M1_MASK: 11828 return emitVFROUND_NOEXCEPT_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M1_MASK, 11829 RISCV::PseudoVFCVT_F_X_V_M1_MASK); 11830 case RISCV::PseudoVFROUND_NOEXCEPT_V_M2_MASK: 11831 return emitVFROUND_NOEXCEPT_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M2_MASK, 11832 RISCV::PseudoVFCVT_F_X_V_M2_MASK); 11833 case RISCV::PseudoVFROUND_NOEXCEPT_V_M4_MASK: 11834 return emitVFROUND_NOEXCEPT_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M4_MASK, 11835 RISCV::PseudoVFCVT_F_X_V_M4_MASK); 11836 case RISCV::PseudoVFROUND_NOEXCEPT_V_M8_MASK: 11837 return emitVFROUND_NOEXCEPT_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M8_MASK, 11838 RISCV::PseudoVFCVT_F_X_V_M8_MASK); 11839 case RISCV::PseudoVFROUND_NOEXCEPT_V_MF2_MASK: 11840 return emitVFROUND_NOEXCEPT_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_MF2_MASK, 11841 RISCV::PseudoVFCVT_F_X_V_MF2_MASK); 11842 case RISCV::PseudoVFROUND_NOEXCEPT_V_MF4_MASK: 11843 return emitVFROUND_NOEXCEPT_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_MF4_MASK, 11844 RISCV::PseudoVFCVT_F_X_V_MF4_MASK); 11845 case RISCV::PseudoFROUND_H: 11846 case RISCV::PseudoFROUND_S: 11847 case RISCV::PseudoFROUND_D: 11848 return emitFROUND(MI, BB, Subtarget); 11849 } 11850 } 11851 11852 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11853 SDNode *Node) const { 11854 // Add FRM dependency to any instructions with dynamic rounding mode. 11855 unsigned Opc = MI.getOpcode(); 11856 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 11857 if (Idx < 0) 11858 return; 11859 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 11860 return; 11861 // If the instruction already reads FRM, don't add another read. 11862 if (MI.readsRegister(RISCV::FRM)) 11863 return; 11864 MI.addOperand( 11865 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 11866 } 11867 11868 // Calling Convention Implementation. 11869 // The expectations for frontend ABI lowering vary from target to target. 11870 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 11871 // details, but this is a longer term goal. For now, we simply try to keep the 11872 // role of the frontend as simple and well-defined as possible. The rules can 11873 // be summarised as: 11874 // * Never split up large scalar arguments. We handle them here. 11875 // * If a hardfloat calling convention is being used, and the struct may be 11876 // passed in a pair of registers (fp+fp, int+fp), and both registers are 11877 // available, then pass as two separate arguments. If either the GPRs or FPRs 11878 // are exhausted, then pass according to the rule below. 11879 // * If a struct could never be passed in registers or directly in a stack 11880 // slot (as it is larger than 2*XLEN and the floating point rules don't 11881 // apply), then pass it using a pointer with the byval attribute. 11882 // * If a struct is less than 2*XLEN, then coerce to either a two-element 11883 // word-sized array or a 2*XLEN scalar (depending on alignment). 11884 // * The frontend can determine whether a struct is returned by reference or 11885 // not based on its size and fields. If it will be returned by reference, the 11886 // frontend must modify the prototype so a pointer with the sret annotation is 11887 // passed as the first argument. This is not necessary for large scalar 11888 // returns. 11889 // * Struct return values and varargs should be coerced to structs containing 11890 // register-size fields in the same situations they would be for fixed 11891 // arguments. 11892 11893 static const MCPhysReg ArgGPRs[] = { 11894 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 11895 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 11896 }; 11897 static const MCPhysReg ArgFPR16s[] = { 11898 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 11899 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 11900 }; 11901 static const MCPhysReg ArgFPR32s[] = { 11902 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 11903 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 11904 }; 11905 static const MCPhysReg ArgFPR64s[] = { 11906 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 11907 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 11908 }; 11909 // This is an interim calling convention and it may be changed in the future. 11910 static const MCPhysReg ArgVRs[] = { 11911 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 11912 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 11913 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 11914 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 11915 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 11916 RISCV::V20M2, RISCV::V22M2}; 11917 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 11918 RISCV::V20M4}; 11919 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 11920 11921 // Pass a 2*XLEN argument that has been split into two XLEN values through 11922 // registers or the stack as necessary. 11923 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 11924 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 11925 MVT ValVT2, MVT LocVT2, 11926 ISD::ArgFlagsTy ArgFlags2) { 11927 unsigned XLenInBytes = XLen / 8; 11928 if (Register Reg = State.AllocateReg(ArgGPRs)) { 11929 // At least one half can be passed via register. 11930 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 11931 VA1.getLocVT(), CCValAssign::Full)); 11932 } else { 11933 // Both halves must be passed on the stack, with proper alignment. 11934 Align StackAlign = 11935 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 11936 State.addLoc( 11937 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 11938 State.AllocateStack(XLenInBytes, StackAlign), 11939 VA1.getLocVT(), CCValAssign::Full)); 11940 State.addLoc(CCValAssign::getMem( 11941 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 11942 LocVT2, CCValAssign::Full)); 11943 return false; 11944 } 11945 11946 if (Register Reg = State.AllocateReg(ArgGPRs)) { 11947 // The second half can also be passed via register. 11948 State.addLoc( 11949 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 11950 } else { 11951 // The second half is passed via the stack, without additional alignment. 11952 State.addLoc(CCValAssign::getMem( 11953 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 11954 LocVT2, CCValAssign::Full)); 11955 } 11956 11957 return false; 11958 } 11959 11960 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 11961 std::optional<unsigned> FirstMaskArgument, 11962 CCState &State, const RISCVTargetLowering &TLI) { 11963 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 11964 if (RC == &RISCV::VRRegClass) { 11965 // Assign the first mask argument to V0. 11966 // This is an interim calling convention and it may be changed in the 11967 // future. 11968 if (FirstMaskArgument && ValNo == *FirstMaskArgument) 11969 return State.AllocateReg(RISCV::V0); 11970 return State.AllocateReg(ArgVRs); 11971 } 11972 if (RC == &RISCV::VRM2RegClass) 11973 return State.AllocateReg(ArgVRM2s); 11974 if (RC == &RISCV::VRM4RegClass) 11975 return State.AllocateReg(ArgVRM4s); 11976 if (RC == &RISCV::VRM8RegClass) 11977 return State.AllocateReg(ArgVRM8s); 11978 llvm_unreachable("Unhandled register class for ValueType"); 11979 } 11980 11981 // Implements the RISC-V calling convention. Returns true upon failure. 11982 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 11983 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 11984 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 11985 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 11986 std::optional<unsigned> FirstMaskArgument) { 11987 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 11988 assert(XLen == 32 || XLen == 64); 11989 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 11990 11991 // Static chain parameter must not be passed in normal argument registers, 11992 // so we assign t2 for it as done in GCC's __builtin_call_with_static_chain 11993 if (ArgFlags.isNest()) { 11994 if (unsigned Reg = State.AllocateReg(RISCV::X7)) { 11995 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 11996 return false; 11997 } 11998 } 11999 12000 // Any return value split in to more than two values can't be returned 12001 // directly. Vectors are returned via the available vector registers. 12002 if (!LocVT.isVector() && IsRet && ValNo > 1) 12003 return true; 12004 12005 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 12006 // variadic argument, or if no F16/F32 argument registers are available. 12007 bool UseGPRForF16_F32 = true; 12008 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 12009 // variadic argument, or if no F64 argument registers are available. 12010 bool UseGPRForF64 = true; 12011 12012 switch (ABI) { 12013 default: 12014 llvm_unreachable("Unexpected ABI"); 12015 case RISCVABI::ABI_ILP32: 12016 case RISCVABI::ABI_LP64: 12017 break; 12018 case RISCVABI::ABI_ILP32F: 12019 case RISCVABI::ABI_LP64F: 12020 UseGPRForF16_F32 = !IsFixed; 12021 break; 12022 case RISCVABI::ABI_ILP32D: 12023 case RISCVABI::ABI_LP64D: 12024 UseGPRForF16_F32 = !IsFixed; 12025 UseGPRForF64 = !IsFixed; 12026 break; 12027 } 12028 12029 // FPR16, FPR32, and FPR64 alias each other. 12030 if (State.getFirstUnallocated(ArgFPR32s) == std::size(ArgFPR32s)) { 12031 UseGPRForF16_F32 = true; 12032 UseGPRForF64 = true; 12033 } 12034 12035 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 12036 // similar local variables rather than directly checking against the target 12037 // ABI. 12038 12039 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 12040 LocVT = XLenVT; 12041 LocInfo = CCValAssign::BCvt; 12042 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 12043 LocVT = MVT::i64; 12044 LocInfo = CCValAssign::BCvt; 12045 } 12046 12047 // If this is a variadic argument, the RISC-V calling convention requires 12048 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 12049 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 12050 // be used regardless of whether the original argument was split during 12051 // legalisation or not. The argument will not be passed by registers if the 12052 // original type is larger than 2*XLEN, so the register alignment rule does 12053 // not apply. 12054 unsigned TwoXLenInBytes = (2 * XLen) / 8; 12055 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 12056 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 12057 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 12058 // Skip 'odd' register if necessary. 12059 if (RegIdx != std::size(ArgGPRs) && RegIdx % 2 == 1) 12060 State.AllocateReg(ArgGPRs); 12061 } 12062 12063 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 12064 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 12065 State.getPendingArgFlags(); 12066 12067 assert(PendingLocs.size() == PendingArgFlags.size() && 12068 "PendingLocs and PendingArgFlags out of sync"); 12069 12070 // Handle passing f64 on RV32D with a soft float ABI or when floating point 12071 // registers are exhausted. 12072 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 12073 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 12074 "Can't lower f64 if it is split"); 12075 // Depending on available argument GPRS, f64 may be passed in a pair of 12076 // GPRs, split between a GPR and the stack, or passed completely on the 12077 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 12078 // cases. 12079 Register Reg = State.AllocateReg(ArgGPRs); 12080 LocVT = MVT::i32; 12081 if (!Reg) { 12082 unsigned StackOffset = State.AllocateStack(8, Align(8)); 12083 State.addLoc( 12084 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 12085 return false; 12086 } 12087 if (!State.AllocateReg(ArgGPRs)) 12088 State.AllocateStack(4, Align(4)); 12089 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 12090 return false; 12091 } 12092 12093 // Fixed-length vectors are located in the corresponding scalable-vector 12094 // container types. 12095 if (ValVT.isFixedLengthVector()) 12096 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 12097 12098 // Split arguments might be passed indirectly, so keep track of the pending 12099 // values. Split vectors are passed via a mix of registers and indirectly, so 12100 // treat them as we would any other argument. 12101 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 12102 LocVT = XLenVT; 12103 LocInfo = CCValAssign::Indirect; 12104 PendingLocs.push_back( 12105 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 12106 PendingArgFlags.push_back(ArgFlags); 12107 if (!ArgFlags.isSplitEnd()) { 12108 return false; 12109 } 12110 } 12111 12112 // If the split argument only had two elements, it should be passed directly 12113 // in registers or on the stack. 12114 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 12115 PendingLocs.size() <= 2) { 12116 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 12117 // Apply the normal calling convention rules to the first half of the 12118 // split argument. 12119 CCValAssign VA = PendingLocs[0]; 12120 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 12121 PendingLocs.clear(); 12122 PendingArgFlags.clear(); 12123 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 12124 ArgFlags); 12125 } 12126 12127 // Allocate to a register if possible, or else a stack slot. 12128 Register Reg; 12129 unsigned StoreSizeBytes = XLen / 8; 12130 Align StackAlign = Align(XLen / 8); 12131 12132 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 12133 Reg = State.AllocateReg(ArgFPR16s); 12134 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 12135 Reg = State.AllocateReg(ArgFPR32s); 12136 else if (ValVT == MVT::f64 && !UseGPRForF64) 12137 Reg = State.AllocateReg(ArgFPR64s); 12138 else if (ValVT.isVector()) { 12139 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 12140 if (!Reg) { 12141 // For return values, the vector must be passed fully via registers or 12142 // via the stack. 12143 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 12144 // but we're using all of them. 12145 if (IsRet) 12146 return true; 12147 // Try using a GPR to pass the address 12148 if ((Reg = State.AllocateReg(ArgGPRs))) { 12149 LocVT = XLenVT; 12150 LocInfo = CCValAssign::Indirect; 12151 } else if (ValVT.isScalableVector()) { 12152 LocVT = XLenVT; 12153 LocInfo = CCValAssign::Indirect; 12154 } else { 12155 // Pass fixed-length vectors on the stack. 12156 LocVT = ValVT; 12157 StoreSizeBytes = ValVT.getStoreSize(); 12158 // Align vectors to their element sizes, being careful for vXi1 12159 // vectors. 12160 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 12161 } 12162 } 12163 } else { 12164 Reg = State.AllocateReg(ArgGPRs); 12165 } 12166 12167 unsigned StackOffset = 12168 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 12169 12170 // If we reach this point and PendingLocs is non-empty, we must be at the 12171 // end of a split argument that must be passed indirectly. 12172 if (!PendingLocs.empty()) { 12173 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 12174 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 12175 12176 for (auto &It : PendingLocs) { 12177 if (Reg) 12178 It.convertToReg(Reg); 12179 else 12180 It.convertToMem(StackOffset); 12181 State.addLoc(It); 12182 } 12183 PendingLocs.clear(); 12184 PendingArgFlags.clear(); 12185 return false; 12186 } 12187 12188 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 12189 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 12190 "Expected an XLenVT or vector types at this stage"); 12191 12192 if (Reg) { 12193 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 12194 return false; 12195 } 12196 12197 // When a floating-point value is passed on the stack, no bit-conversion is 12198 // needed. 12199 if (ValVT.isFloatingPoint()) { 12200 LocVT = ValVT; 12201 LocInfo = CCValAssign::Full; 12202 } 12203 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 12204 return false; 12205 } 12206 12207 template <typename ArgTy> 12208 static std::optional<unsigned> preAssignMask(const ArgTy &Args) { 12209 for (const auto &ArgIdx : enumerate(Args)) { 12210 MVT ArgVT = ArgIdx.value().VT; 12211 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 12212 return ArgIdx.index(); 12213 } 12214 return std::nullopt; 12215 } 12216 12217 void RISCVTargetLowering::analyzeInputArgs( 12218 MachineFunction &MF, CCState &CCInfo, 12219 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 12220 RISCVCCAssignFn Fn) const { 12221 unsigned NumArgs = Ins.size(); 12222 FunctionType *FType = MF.getFunction().getFunctionType(); 12223 12224 std::optional<unsigned> FirstMaskArgument; 12225 if (Subtarget.hasVInstructions()) 12226 FirstMaskArgument = preAssignMask(Ins); 12227 12228 for (unsigned i = 0; i != NumArgs; ++i) { 12229 MVT ArgVT = Ins[i].VT; 12230 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 12231 12232 Type *ArgTy = nullptr; 12233 if (IsRet) 12234 ArgTy = FType->getReturnType(); 12235 else if (Ins[i].isOrigArg()) 12236 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 12237 12238 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 12239 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 12240 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 12241 FirstMaskArgument)) { 12242 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 12243 << EVT(ArgVT).getEVTString() << '\n'); 12244 llvm_unreachable(nullptr); 12245 } 12246 } 12247 } 12248 12249 void RISCVTargetLowering::analyzeOutputArgs( 12250 MachineFunction &MF, CCState &CCInfo, 12251 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 12252 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 12253 unsigned NumArgs = Outs.size(); 12254 12255 std::optional<unsigned> FirstMaskArgument; 12256 if (Subtarget.hasVInstructions()) 12257 FirstMaskArgument = preAssignMask(Outs); 12258 12259 for (unsigned i = 0; i != NumArgs; i++) { 12260 MVT ArgVT = Outs[i].VT; 12261 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 12262 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 12263 12264 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 12265 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 12266 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 12267 FirstMaskArgument)) { 12268 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 12269 << EVT(ArgVT).getEVTString() << "\n"); 12270 llvm_unreachable(nullptr); 12271 } 12272 } 12273 } 12274 12275 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 12276 // values. 12277 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 12278 const CCValAssign &VA, const SDLoc &DL, 12279 const RISCVSubtarget &Subtarget) { 12280 switch (VA.getLocInfo()) { 12281 default: 12282 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 12283 case CCValAssign::Full: 12284 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 12285 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 12286 break; 12287 case CCValAssign::BCvt: 12288 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 12289 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 12290 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 12291 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 12292 else 12293 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 12294 break; 12295 } 12296 return Val; 12297 } 12298 12299 // The caller is responsible for loading the full value if the argument is 12300 // passed with CCValAssign::Indirect. 12301 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 12302 const CCValAssign &VA, const SDLoc &DL, 12303 const ISD::InputArg &In, 12304 const RISCVTargetLowering &TLI) { 12305 MachineFunction &MF = DAG.getMachineFunction(); 12306 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 12307 EVT LocVT = VA.getLocVT(); 12308 SDValue Val; 12309 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 12310 Register VReg = RegInfo.createVirtualRegister(RC); 12311 RegInfo.addLiveIn(VA.getLocReg(), VReg); 12312 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 12313 12314 // If input is sign extended from 32 bits, note it for the SExtWRemoval pass. 12315 if (In.isOrigArg()) { 12316 Argument *OrigArg = MF.getFunction().getArg(In.getOrigArgIndex()); 12317 if (OrigArg->getType()->isIntegerTy()) { 12318 unsigned BitWidth = OrigArg->getType()->getIntegerBitWidth(); 12319 // An input zero extended from i31 can also be considered sign extended. 12320 if ((BitWidth <= 32 && In.Flags.isSExt()) || 12321 (BitWidth < 32 && In.Flags.isZExt())) { 12322 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 12323 RVFI->addSExt32Register(VReg); 12324 } 12325 } 12326 } 12327 12328 if (VA.getLocInfo() == CCValAssign::Indirect) 12329 return Val; 12330 12331 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 12332 } 12333 12334 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 12335 const CCValAssign &VA, const SDLoc &DL, 12336 const RISCVSubtarget &Subtarget) { 12337 EVT LocVT = VA.getLocVT(); 12338 12339 switch (VA.getLocInfo()) { 12340 default: 12341 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 12342 case CCValAssign::Full: 12343 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 12344 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 12345 break; 12346 case CCValAssign::BCvt: 12347 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 12348 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 12349 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 12350 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 12351 else 12352 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 12353 break; 12354 } 12355 return Val; 12356 } 12357 12358 // The caller is responsible for loading the full value if the argument is 12359 // passed with CCValAssign::Indirect. 12360 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 12361 const CCValAssign &VA, const SDLoc &DL) { 12362 MachineFunction &MF = DAG.getMachineFunction(); 12363 MachineFrameInfo &MFI = MF.getFrameInfo(); 12364 EVT LocVT = VA.getLocVT(); 12365 EVT ValVT = VA.getValVT(); 12366 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 12367 if (ValVT.isScalableVector()) { 12368 // When the value is a scalable vector, we save the pointer which points to 12369 // the scalable vector value in the stack. The ValVT will be the pointer 12370 // type, instead of the scalable vector type. 12371 ValVT = LocVT; 12372 } 12373 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 12374 /*IsImmutable=*/true); 12375 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 12376 SDValue Val; 12377 12378 ISD::LoadExtType ExtType; 12379 switch (VA.getLocInfo()) { 12380 default: 12381 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 12382 case CCValAssign::Full: 12383 case CCValAssign::Indirect: 12384 case CCValAssign::BCvt: 12385 ExtType = ISD::NON_EXTLOAD; 12386 break; 12387 } 12388 Val = DAG.getExtLoad( 12389 ExtType, DL, LocVT, Chain, FIN, 12390 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 12391 return Val; 12392 } 12393 12394 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 12395 const CCValAssign &VA, const SDLoc &DL) { 12396 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 12397 "Unexpected VA"); 12398 MachineFunction &MF = DAG.getMachineFunction(); 12399 MachineFrameInfo &MFI = MF.getFrameInfo(); 12400 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 12401 12402 if (VA.isMemLoc()) { 12403 // f64 is passed on the stack. 12404 int FI = 12405 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 12406 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 12407 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 12408 MachinePointerInfo::getFixedStack(MF, FI)); 12409 } 12410 12411 assert(VA.isRegLoc() && "Expected register VA assignment"); 12412 12413 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 12414 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 12415 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 12416 SDValue Hi; 12417 if (VA.getLocReg() == RISCV::X17) { 12418 // Second half of f64 is passed on the stack. 12419 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 12420 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 12421 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 12422 MachinePointerInfo::getFixedStack(MF, FI)); 12423 } else { 12424 // Second half of f64 is passed in another GPR. 12425 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 12426 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 12427 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 12428 } 12429 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 12430 } 12431 12432 // FastCC has less than 1% performance improvement for some particular 12433 // benchmark. But theoretically, it may has benenfit for some cases. 12434 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 12435 unsigned ValNo, MVT ValVT, MVT LocVT, 12436 CCValAssign::LocInfo LocInfo, 12437 ISD::ArgFlagsTy ArgFlags, CCState &State, 12438 bool IsFixed, bool IsRet, Type *OrigTy, 12439 const RISCVTargetLowering &TLI, 12440 std::optional<unsigned> FirstMaskArgument) { 12441 12442 // X5 and X6 might be used for save-restore libcall. 12443 static const MCPhysReg GPRList[] = { 12444 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 12445 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 12446 RISCV::X29, RISCV::X30, RISCV::X31}; 12447 12448 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 12449 if (unsigned Reg = State.AllocateReg(GPRList)) { 12450 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 12451 return false; 12452 } 12453 } 12454 12455 if (LocVT == MVT::f16) { 12456 static const MCPhysReg FPR16List[] = { 12457 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 12458 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 12459 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 12460 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 12461 if (unsigned Reg = State.AllocateReg(FPR16List)) { 12462 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 12463 return false; 12464 } 12465 } 12466 12467 if (LocVT == MVT::f32) { 12468 static const MCPhysReg FPR32List[] = { 12469 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 12470 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 12471 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 12472 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 12473 if (unsigned Reg = State.AllocateReg(FPR32List)) { 12474 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 12475 return false; 12476 } 12477 } 12478 12479 if (LocVT == MVT::f64) { 12480 static const MCPhysReg FPR64List[] = { 12481 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 12482 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 12483 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 12484 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 12485 if (unsigned Reg = State.AllocateReg(FPR64List)) { 12486 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 12487 return false; 12488 } 12489 } 12490 12491 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 12492 unsigned Offset4 = State.AllocateStack(4, Align(4)); 12493 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 12494 return false; 12495 } 12496 12497 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 12498 unsigned Offset5 = State.AllocateStack(8, Align(8)); 12499 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 12500 return false; 12501 } 12502 12503 if (LocVT.isVector()) { 12504 if (unsigned Reg = 12505 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 12506 // Fixed-length vectors are located in the corresponding scalable-vector 12507 // container types. 12508 if (ValVT.isFixedLengthVector()) 12509 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 12510 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 12511 } else { 12512 // Try and pass the address via a "fast" GPR. 12513 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 12514 LocInfo = CCValAssign::Indirect; 12515 LocVT = TLI.getSubtarget().getXLenVT(); 12516 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 12517 } else if (ValVT.isFixedLengthVector()) { 12518 auto StackAlign = 12519 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 12520 unsigned StackOffset = 12521 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 12522 State.addLoc( 12523 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 12524 } else { 12525 // Can't pass scalable vectors on the stack. 12526 return true; 12527 } 12528 } 12529 12530 return false; 12531 } 12532 12533 return true; // CC didn't match. 12534 } 12535 12536 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 12537 CCValAssign::LocInfo LocInfo, 12538 ISD::ArgFlagsTy ArgFlags, CCState &State) { 12539 12540 if (ArgFlags.isNest()) { 12541 report_fatal_error( 12542 "Attribute 'nest' is not supported in GHC calling convention"); 12543 } 12544 12545 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 12546 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 12547 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 12548 static const MCPhysReg GPRList[] = { 12549 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 12550 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 12551 if (unsigned Reg = State.AllocateReg(GPRList)) { 12552 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 12553 return false; 12554 } 12555 } 12556 12557 if (LocVT == MVT::f32) { 12558 // Pass in STG registers: F1, ..., F6 12559 // fs0 ... fs5 12560 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 12561 RISCV::F18_F, RISCV::F19_F, 12562 RISCV::F20_F, RISCV::F21_F}; 12563 if (unsigned Reg = State.AllocateReg(FPR32List)) { 12564 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 12565 return false; 12566 } 12567 } 12568 12569 if (LocVT == MVT::f64) { 12570 // Pass in STG registers: D1, ..., D6 12571 // fs6 ... fs11 12572 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 12573 RISCV::F24_D, RISCV::F25_D, 12574 RISCV::F26_D, RISCV::F27_D}; 12575 if (unsigned Reg = State.AllocateReg(FPR64List)) { 12576 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 12577 return false; 12578 } 12579 } 12580 12581 report_fatal_error("No registers left in GHC calling convention"); 12582 return true; 12583 } 12584 12585 // Transform physical registers into virtual registers. 12586 SDValue RISCVTargetLowering::LowerFormalArguments( 12587 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 12588 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 12589 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 12590 12591 MachineFunction &MF = DAG.getMachineFunction(); 12592 12593 switch (CallConv) { 12594 default: 12595 report_fatal_error("Unsupported calling convention"); 12596 case CallingConv::C: 12597 case CallingConv::Fast: 12598 break; 12599 case CallingConv::GHC: 12600 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 12601 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 12602 report_fatal_error( 12603 "GHC calling convention requires the F and D instruction set extensions"); 12604 } 12605 12606 const Function &Func = MF.getFunction(); 12607 if (Func.hasFnAttribute("interrupt")) { 12608 if (!Func.arg_empty()) 12609 report_fatal_error( 12610 "Functions with the interrupt attribute cannot have arguments!"); 12611 12612 StringRef Kind = 12613 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 12614 12615 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 12616 report_fatal_error( 12617 "Function interrupt attribute argument not supported!"); 12618 } 12619 12620 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 12621 MVT XLenVT = Subtarget.getXLenVT(); 12622 unsigned XLenInBytes = Subtarget.getXLen() / 8; 12623 // Used with vargs to acumulate store chains. 12624 std::vector<SDValue> OutChains; 12625 12626 // Assign locations to all of the incoming arguments. 12627 SmallVector<CCValAssign, 16> ArgLocs; 12628 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 12629 12630 if (CallConv == CallingConv::GHC) 12631 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 12632 else 12633 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 12634 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 12635 : CC_RISCV); 12636 12637 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 12638 CCValAssign &VA = ArgLocs[i]; 12639 SDValue ArgValue; 12640 // Passing f64 on RV32D with a soft float ABI must be handled as a special 12641 // case. 12642 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 12643 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 12644 else if (VA.isRegLoc()) 12645 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, Ins[i], *this); 12646 else 12647 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 12648 12649 if (VA.getLocInfo() == CCValAssign::Indirect) { 12650 // If the original argument was split and passed by reference (e.g. i128 12651 // on RV32), we need to load all parts of it here (using the same 12652 // address). Vectors may be partly split to registers and partly to the 12653 // stack, in which case the base address is partly offset and subsequent 12654 // stores are relative to that. 12655 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 12656 MachinePointerInfo())); 12657 unsigned ArgIndex = Ins[i].OrigArgIndex; 12658 unsigned ArgPartOffset = Ins[i].PartOffset; 12659 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 12660 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 12661 CCValAssign &PartVA = ArgLocs[i + 1]; 12662 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 12663 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 12664 if (PartVA.getValVT().isScalableVector()) 12665 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 12666 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 12667 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 12668 MachinePointerInfo())); 12669 ++i; 12670 } 12671 continue; 12672 } 12673 InVals.push_back(ArgValue); 12674 } 12675 12676 if (any_of(ArgLocs, 12677 [](CCValAssign &VA) { return VA.getLocVT().isScalableVector(); })) 12678 MF.getInfo<RISCVMachineFunctionInfo>()->setIsVectorCall(); 12679 12680 if (IsVarArg) { 12681 ArrayRef<MCPhysReg> ArgRegs = ArrayRef(ArgGPRs); 12682 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 12683 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 12684 MachineFrameInfo &MFI = MF.getFrameInfo(); 12685 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 12686 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 12687 12688 // Offset of the first variable argument from stack pointer, and size of 12689 // the vararg save area. For now, the varargs save area is either zero or 12690 // large enough to hold a0-a7. 12691 int VaArgOffset, VarArgsSaveSize; 12692 12693 // If all registers are allocated, then all varargs must be passed on the 12694 // stack and we don't need to save any argregs. 12695 if (ArgRegs.size() == Idx) { 12696 VaArgOffset = CCInfo.getNextStackOffset(); 12697 VarArgsSaveSize = 0; 12698 } else { 12699 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 12700 VaArgOffset = -VarArgsSaveSize; 12701 } 12702 12703 // Record the frame index of the first variable argument 12704 // which is a value necessary to VASTART. 12705 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 12706 RVFI->setVarArgsFrameIndex(FI); 12707 12708 // If saving an odd number of registers then create an extra stack slot to 12709 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 12710 // offsets to even-numbered registered remain 2*XLEN-aligned. 12711 if (Idx % 2) { 12712 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 12713 VarArgsSaveSize += XLenInBytes; 12714 } 12715 12716 // Copy the integer registers that may have been used for passing varargs 12717 // to the vararg save area. 12718 for (unsigned I = Idx; I < ArgRegs.size(); 12719 ++I, VaArgOffset += XLenInBytes) { 12720 const Register Reg = RegInfo.createVirtualRegister(RC); 12721 RegInfo.addLiveIn(ArgRegs[I], Reg); 12722 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 12723 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 12724 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 12725 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 12726 MachinePointerInfo::getFixedStack(MF, FI)); 12727 cast<StoreSDNode>(Store.getNode()) 12728 ->getMemOperand() 12729 ->setValue((Value *)nullptr); 12730 OutChains.push_back(Store); 12731 } 12732 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 12733 } 12734 12735 // All stores are grouped in one node to allow the matching between 12736 // the size of Ins and InVals. This only happens for vararg functions. 12737 if (!OutChains.empty()) { 12738 OutChains.push_back(Chain); 12739 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 12740 } 12741 12742 return Chain; 12743 } 12744 12745 /// isEligibleForTailCallOptimization - Check whether the call is eligible 12746 /// for tail call optimization. 12747 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 12748 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 12749 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 12750 const SmallVector<CCValAssign, 16> &ArgLocs) const { 12751 12752 auto &Callee = CLI.Callee; 12753 auto CalleeCC = CLI.CallConv; 12754 auto &Outs = CLI.Outs; 12755 auto &Caller = MF.getFunction(); 12756 auto CallerCC = Caller.getCallingConv(); 12757 12758 // Exception-handling functions need a special set of instructions to 12759 // indicate a return to the hardware. Tail-calling another function would 12760 // probably break this. 12761 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 12762 // should be expanded as new function attributes are introduced. 12763 if (Caller.hasFnAttribute("interrupt")) 12764 return false; 12765 12766 // Do not tail call opt if the stack is used to pass parameters. 12767 if (CCInfo.getNextStackOffset() != 0) 12768 return false; 12769 12770 // Do not tail call opt if any parameters need to be passed indirectly. 12771 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 12772 // passed indirectly. So the address of the value will be passed in a 12773 // register, or if not available, then the address is put on the stack. In 12774 // order to pass indirectly, space on the stack often needs to be allocated 12775 // in order to store the value. In this case the CCInfo.getNextStackOffset() 12776 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 12777 // are passed CCValAssign::Indirect. 12778 for (auto &VA : ArgLocs) 12779 if (VA.getLocInfo() == CCValAssign::Indirect) 12780 return false; 12781 12782 // Do not tail call opt if either caller or callee uses struct return 12783 // semantics. 12784 auto IsCallerStructRet = Caller.hasStructRetAttr(); 12785 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 12786 if (IsCallerStructRet || IsCalleeStructRet) 12787 return false; 12788 12789 // Externally-defined functions with weak linkage should not be 12790 // tail-called. The behaviour of branch instructions in this situation (as 12791 // used for tail calls) is implementation-defined, so we cannot rely on the 12792 // linker replacing the tail call with a return. 12793 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 12794 const GlobalValue *GV = G->getGlobal(); 12795 if (GV->hasExternalWeakLinkage()) 12796 return false; 12797 } 12798 12799 // The callee has to preserve all registers the caller needs to preserve. 12800 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 12801 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 12802 if (CalleeCC != CallerCC) { 12803 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 12804 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 12805 return false; 12806 } 12807 12808 // Byval parameters hand the function a pointer directly into the stack area 12809 // we want to reuse during a tail call. Working around this *is* possible 12810 // but less efficient and uglier in LowerCall. 12811 for (auto &Arg : Outs) 12812 if (Arg.Flags.isByVal()) 12813 return false; 12814 12815 return true; 12816 } 12817 12818 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 12819 return DAG.getDataLayout().getPrefTypeAlign( 12820 VT.getTypeForEVT(*DAG.getContext())); 12821 } 12822 12823 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 12824 // and output parameter nodes. 12825 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 12826 SmallVectorImpl<SDValue> &InVals) const { 12827 SelectionDAG &DAG = CLI.DAG; 12828 SDLoc &DL = CLI.DL; 12829 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 12830 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 12831 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 12832 SDValue Chain = CLI.Chain; 12833 SDValue Callee = CLI.Callee; 12834 bool &IsTailCall = CLI.IsTailCall; 12835 CallingConv::ID CallConv = CLI.CallConv; 12836 bool IsVarArg = CLI.IsVarArg; 12837 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 12838 MVT XLenVT = Subtarget.getXLenVT(); 12839 12840 MachineFunction &MF = DAG.getMachineFunction(); 12841 12842 // Analyze the operands of the call, assigning locations to each operand. 12843 SmallVector<CCValAssign, 16> ArgLocs; 12844 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 12845 12846 if (CallConv == CallingConv::GHC) 12847 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 12848 else 12849 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 12850 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 12851 : CC_RISCV); 12852 12853 // Check if it's really possible to do a tail call. 12854 if (IsTailCall) 12855 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 12856 12857 if (IsTailCall) 12858 ++NumTailCalls; 12859 else if (CLI.CB && CLI.CB->isMustTailCall()) 12860 report_fatal_error("failed to perform tail call elimination on a call " 12861 "site marked musttail"); 12862 12863 // Get a count of how many bytes are to be pushed on the stack. 12864 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 12865 12866 // Create local copies for byval args 12867 SmallVector<SDValue, 8> ByValArgs; 12868 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 12869 ISD::ArgFlagsTy Flags = Outs[i].Flags; 12870 if (!Flags.isByVal()) 12871 continue; 12872 12873 SDValue Arg = OutVals[i]; 12874 unsigned Size = Flags.getByValSize(); 12875 Align Alignment = Flags.getNonZeroByValAlign(); 12876 12877 int FI = 12878 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 12879 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 12880 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 12881 12882 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 12883 /*IsVolatile=*/false, 12884 /*AlwaysInline=*/false, IsTailCall, 12885 MachinePointerInfo(), MachinePointerInfo()); 12886 ByValArgs.push_back(FIPtr); 12887 } 12888 12889 if (!IsTailCall) 12890 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 12891 12892 // Copy argument values to their designated locations. 12893 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 12894 SmallVector<SDValue, 8> MemOpChains; 12895 SDValue StackPtr; 12896 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 12897 CCValAssign &VA = ArgLocs[i]; 12898 SDValue ArgValue = OutVals[i]; 12899 ISD::ArgFlagsTy Flags = Outs[i].Flags; 12900 12901 // Handle passing f64 on RV32D with a soft float ABI as a special case. 12902 bool IsF64OnRV32DSoftABI = 12903 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 12904 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 12905 SDValue SplitF64 = DAG.getNode( 12906 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 12907 SDValue Lo = SplitF64.getValue(0); 12908 SDValue Hi = SplitF64.getValue(1); 12909 12910 Register RegLo = VA.getLocReg(); 12911 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 12912 12913 if (RegLo == RISCV::X17) { 12914 // Second half of f64 is passed on the stack. 12915 // Work out the address of the stack slot. 12916 if (!StackPtr.getNode()) 12917 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 12918 // Emit the store. 12919 MemOpChains.push_back( 12920 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 12921 } else { 12922 // Second half of f64 is passed in another GPR. 12923 assert(RegLo < RISCV::X31 && "Invalid register pair"); 12924 Register RegHigh = RegLo + 1; 12925 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 12926 } 12927 continue; 12928 } 12929 12930 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 12931 // as any other MemLoc. 12932 12933 // Promote the value if needed. 12934 // For now, only handle fully promoted and indirect arguments. 12935 if (VA.getLocInfo() == CCValAssign::Indirect) { 12936 // Store the argument in a stack slot and pass its address. 12937 Align StackAlign = 12938 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 12939 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 12940 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 12941 // If the original argument was split (e.g. i128), we need 12942 // to store the required parts of it here (and pass just one address). 12943 // Vectors may be partly split to registers and partly to the stack, in 12944 // which case the base address is partly offset and subsequent stores are 12945 // relative to that. 12946 unsigned ArgIndex = Outs[i].OrigArgIndex; 12947 unsigned ArgPartOffset = Outs[i].PartOffset; 12948 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 12949 // Calculate the total size to store. We don't have access to what we're 12950 // actually storing other than performing the loop and collecting the 12951 // info. 12952 SmallVector<std::pair<SDValue, SDValue>> Parts; 12953 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 12954 SDValue PartValue = OutVals[i + 1]; 12955 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 12956 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 12957 EVT PartVT = PartValue.getValueType(); 12958 if (PartVT.isScalableVector()) 12959 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 12960 StoredSize += PartVT.getStoreSize(); 12961 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 12962 Parts.push_back(std::make_pair(PartValue, Offset)); 12963 ++i; 12964 } 12965 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 12966 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 12967 MemOpChains.push_back( 12968 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 12969 MachinePointerInfo::getFixedStack(MF, FI))); 12970 for (const auto &Part : Parts) { 12971 SDValue PartValue = Part.first; 12972 SDValue PartOffset = Part.second; 12973 SDValue Address = 12974 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 12975 MemOpChains.push_back( 12976 DAG.getStore(Chain, DL, PartValue, Address, 12977 MachinePointerInfo::getFixedStack(MF, FI))); 12978 } 12979 ArgValue = SpillSlot; 12980 } else { 12981 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 12982 } 12983 12984 // Use local copy if it is a byval arg. 12985 if (Flags.isByVal()) 12986 ArgValue = ByValArgs[j++]; 12987 12988 if (VA.isRegLoc()) { 12989 // Queue up the argument copies and emit them at the end. 12990 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 12991 } else { 12992 assert(VA.isMemLoc() && "Argument not register or memory"); 12993 assert(!IsTailCall && "Tail call not allowed if stack is used " 12994 "for passing parameters"); 12995 12996 // Work out the address of the stack slot. 12997 if (!StackPtr.getNode()) 12998 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 12999 SDValue Address = 13000 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 13001 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 13002 13003 // Emit the store. 13004 MemOpChains.push_back( 13005 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 13006 } 13007 } 13008 13009 // Join the stores, which are independent of one another. 13010 if (!MemOpChains.empty()) 13011 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 13012 13013 SDValue Glue; 13014 13015 // Build a sequence of copy-to-reg nodes, chained and glued together. 13016 for (auto &Reg : RegsToPass) { 13017 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 13018 Glue = Chain.getValue(1); 13019 } 13020 13021 // Validate that none of the argument registers have been marked as 13022 // reserved, if so report an error. Do the same for the return address if this 13023 // is not a tailcall. 13024 validateCCReservedRegs(RegsToPass, MF); 13025 if (!IsTailCall && 13026 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 13027 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 13028 MF.getFunction(), 13029 "Return address register required, but has been reserved."}); 13030 13031 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 13032 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 13033 // split it and then direct call can be matched by PseudoCALL. 13034 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 13035 const GlobalValue *GV = S->getGlobal(); 13036 13037 unsigned OpFlags = RISCVII::MO_CALL; 13038 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 13039 OpFlags = RISCVII::MO_PLT; 13040 13041 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 13042 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 13043 unsigned OpFlags = RISCVII::MO_CALL; 13044 13045 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 13046 nullptr)) 13047 OpFlags = RISCVII::MO_PLT; 13048 13049 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 13050 } 13051 13052 // The first call operand is the chain and the second is the target address. 13053 SmallVector<SDValue, 8> Ops; 13054 Ops.push_back(Chain); 13055 Ops.push_back(Callee); 13056 13057 // Add argument registers to the end of the list so that they are 13058 // known live into the call. 13059 for (auto &Reg : RegsToPass) 13060 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 13061 13062 if (!IsTailCall) { 13063 // Add a register mask operand representing the call-preserved registers. 13064 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 13065 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 13066 assert(Mask && "Missing call preserved mask for calling convention"); 13067 Ops.push_back(DAG.getRegisterMask(Mask)); 13068 } 13069 13070 // Glue the call to the argument copies, if any. 13071 if (Glue.getNode()) 13072 Ops.push_back(Glue); 13073 13074 // Emit the call. 13075 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 13076 13077 if (IsTailCall) { 13078 MF.getFrameInfo().setHasTailCall(); 13079 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 13080 } 13081 13082 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 13083 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 13084 Glue = Chain.getValue(1); 13085 13086 // Mark the end of the call, which is glued to the call itself. 13087 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL); 13088 Glue = Chain.getValue(1); 13089 13090 // Assign locations to each value returned by this call. 13091 SmallVector<CCValAssign, 16> RVLocs; 13092 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 13093 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 13094 13095 // Copy all of the result registers out of their specified physreg. 13096 for (auto &VA : RVLocs) { 13097 // Copy the value out 13098 SDValue RetValue = 13099 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 13100 // Glue the RetValue to the end of the call sequence 13101 Chain = RetValue.getValue(1); 13102 Glue = RetValue.getValue(2); 13103 13104 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 13105 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 13106 SDValue RetValue2 = 13107 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 13108 Chain = RetValue2.getValue(1); 13109 Glue = RetValue2.getValue(2); 13110 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 13111 RetValue2); 13112 } 13113 13114 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 13115 13116 InVals.push_back(RetValue); 13117 } 13118 13119 return Chain; 13120 } 13121 13122 bool RISCVTargetLowering::CanLowerReturn( 13123 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 13124 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 13125 SmallVector<CCValAssign, 16> RVLocs; 13126 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 13127 13128 std::optional<unsigned> FirstMaskArgument; 13129 if (Subtarget.hasVInstructions()) 13130 FirstMaskArgument = preAssignMask(Outs); 13131 13132 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 13133 MVT VT = Outs[i].VT; 13134 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 13135 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 13136 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 13137 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 13138 *this, FirstMaskArgument)) 13139 return false; 13140 } 13141 return true; 13142 } 13143 13144 SDValue 13145 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 13146 bool IsVarArg, 13147 const SmallVectorImpl<ISD::OutputArg> &Outs, 13148 const SmallVectorImpl<SDValue> &OutVals, 13149 const SDLoc &DL, SelectionDAG &DAG) const { 13150 MachineFunction &MF = DAG.getMachineFunction(); 13151 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 13152 13153 // Stores the assignment of the return value to a location. 13154 SmallVector<CCValAssign, 16> RVLocs; 13155 13156 // Info about the registers and stack slot. 13157 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 13158 *DAG.getContext()); 13159 13160 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 13161 nullptr, CC_RISCV); 13162 13163 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 13164 report_fatal_error("GHC functions return void only"); 13165 13166 SDValue Glue; 13167 SmallVector<SDValue, 4> RetOps(1, Chain); 13168 13169 // Copy the result values into the output registers. 13170 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 13171 SDValue Val = OutVals[i]; 13172 CCValAssign &VA = RVLocs[i]; 13173 assert(VA.isRegLoc() && "Can only return in registers!"); 13174 13175 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 13176 // Handle returning f64 on RV32D with a soft float ABI. 13177 assert(VA.isRegLoc() && "Expected return via registers"); 13178 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 13179 DAG.getVTList(MVT::i32, MVT::i32), Val); 13180 SDValue Lo = SplitF64.getValue(0); 13181 SDValue Hi = SplitF64.getValue(1); 13182 Register RegLo = VA.getLocReg(); 13183 assert(RegLo < RISCV::X31 && "Invalid register pair"); 13184 Register RegHi = RegLo + 1; 13185 13186 if (STI.isRegisterReservedByUser(RegLo) || 13187 STI.isRegisterReservedByUser(RegHi)) 13188 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 13189 MF.getFunction(), 13190 "Return value register required, but has been reserved."}); 13191 13192 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 13193 Glue = Chain.getValue(1); 13194 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 13195 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 13196 Glue = Chain.getValue(1); 13197 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 13198 } else { 13199 // Handle a 'normal' return. 13200 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 13201 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 13202 13203 if (STI.isRegisterReservedByUser(VA.getLocReg())) 13204 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 13205 MF.getFunction(), 13206 "Return value register required, but has been reserved."}); 13207 13208 // Guarantee that all emitted copies are stuck together. 13209 Glue = Chain.getValue(1); 13210 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 13211 } 13212 } 13213 13214 RetOps[0] = Chain; // Update chain. 13215 13216 // Add the glue node if we have it. 13217 if (Glue.getNode()) { 13218 RetOps.push_back(Glue); 13219 } 13220 13221 if (any_of(RVLocs, 13222 [](CCValAssign &VA) { return VA.getLocVT().isScalableVector(); })) 13223 MF.getInfo<RISCVMachineFunctionInfo>()->setIsVectorCall(); 13224 13225 unsigned RetOpc = RISCVISD::RET_FLAG; 13226 // Interrupt service routines use different return instructions. 13227 const Function &Func = DAG.getMachineFunction().getFunction(); 13228 if (Func.hasFnAttribute("interrupt")) { 13229 if (!Func.getReturnType()->isVoidTy()) 13230 report_fatal_error( 13231 "Functions with the interrupt attribute must have void return type!"); 13232 13233 MachineFunction &MF = DAG.getMachineFunction(); 13234 StringRef Kind = 13235 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 13236 13237 if (Kind == "user") 13238 RetOpc = RISCVISD::URET_FLAG; 13239 else if (Kind == "supervisor") 13240 RetOpc = RISCVISD::SRET_FLAG; 13241 else 13242 RetOpc = RISCVISD::MRET_FLAG; 13243 } 13244 13245 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 13246 } 13247 13248 void RISCVTargetLowering::validateCCReservedRegs( 13249 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 13250 MachineFunction &MF) const { 13251 const Function &F = MF.getFunction(); 13252 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 13253 13254 if (llvm::any_of(Regs, [&STI](auto Reg) { 13255 return STI.isRegisterReservedByUser(Reg.first); 13256 })) 13257 F.getContext().diagnose(DiagnosticInfoUnsupported{ 13258 F, "Argument register required, but has been reserved."}); 13259 } 13260 13261 // Check if the result of the node is only used as a return value, as 13262 // otherwise we can't perform a tail-call. 13263 bool RISCVTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 13264 if (N->getNumValues() != 1) 13265 return false; 13266 if (!N->hasNUsesOfValue(1, 0)) 13267 return false; 13268 13269 SDNode *Copy = *N->use_begin(); 13270 // TODO: Handle additional opcodes in order to support tail-calling libcalls 13271 // with soft float ABIs. 13272 if (Copy->getOpcode() != ISD::CopyToReg) { 13273 return false; 13274 } 13275 13276 // If the ISD::CopyToReg has a glue operand, we conservatively assume it 13277 // isn't safe to perform a tail call. 13278 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == MVT::Glue) 13279 return false; 13280 13281 // The copy must be used by a RISCVISD::RET_FLAG, and nothing else. 13282 bool HasRet = false; 13283 for (SDNode *Node : Copy->uses()) { 13284 if (Node->getOpcode() != RISCVISD::RET_FLAG) 13285 return false; 13286 HasRet = true; 13287 } 13288 if (!HasRet) 13289 return false; 13290 13291 Chain = Copy->getOperand(0); 13292 return true; 13293 } 13294 13295 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 13296 return CI->isTailCall(); 13297 } 13298 13299 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 13300 #define NODE_NAME_CASE(NODE) \ 13301 case RISCVISD::NODE: \ 13302 return "RISCVISD::" #NODE; 13303 // clang-format off 13304 switch ((RISCVISD::NodeType)Opcode) { 13305 case RISCVISD::FIRST_NUMBER: 13306 break; 13307 NODE_NAME_CASE(RET_FLAG) 13308 NODE_NAME_CASE(URET_FLAG) 13309 NODE_NAME_CASE(SRET_FLAG) 13310 NODE_NAME_CASE(MRET_FLAG) 13311 NODE_NAME_CASE(CALL) 13312 NODE_NAME_CASE(SELECT_CC) 13313 NODE_NAME_CASE(BR_CC) 13314 NODE_NAME_CASE(BuildPairF64) 13315 NODE_NAME_CASE(SplitF64) 13316 NODE_NAME_CASE(TAIL) 13317 NODE_NAME_CASE(ADD_LO) 13318 NODE_NAME_CASE(HI) 13319 NODE_NAME_CASE(LLA) 13320 NODE_NAME_CASE(ADD_TPREL) 13321 NODE_NAME_CASE(LA) 13322 NODE_NAME_CASE(LA_TLS_IE) 13323 NODE_NAME_CASE(LA_TLS_GD) 13324 NODE_NAME_CASE(MULHSU) 13325 NODE_NAME_CASE(SLLW) 13326 NODE_NAME_CASE(SRAW) 13327 NODE_NAME_CASE(SRLW) 13328 NODE_NAME_CASE(DIVW) 13329 NODE_NAME_CASE(DIVUW) 13330 NODE_NAME_CASE(REMUW) 13331 NODE_NAME_CASE(ROLW) 13332 NODE_NAME_CASE(RORW) 13333 NODE_NAME_CASE(CLZW) 13334 NODE_NAME_CASE(CTZW) 13335 NODE_NAME_CASE(ABSW) 13336 NODE_NAME_CASE(FMV_H_X) 13337 NODE_NAME_CASE(FMV_X_ANYEXTH) 13338 NODE_NAME_CASE(FMV_X_SIGNEXTH) 13339 NODE_NAME_CASE(FMV_W_X_RV64) 13340 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 13341 NODE_NAME_CASE(FCVT_X) 13342 NODE_NAME_CASE(FCVT_XU) 13343 NODE_NAME_CASE(FCVT_W_RV64) 13344 NODE_NAME_CASE(FCVT_WU_RV64) 13345 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 13346 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 13347 NODE_NAME_CASE(FROUND) 13348 NODE_NAME_CASE(READ_CYCLE_WIDE) 13349 NODE_NAME_CASE(BREV8) 13350 NODE_NAME_CASE(ORC_B) 13351 NODE_NAME_CASE(ZIP) 13352 NODE_NAME_CASE(UNZIP) 13353 NODE_NAME_CASE(VMV_V_X_VL) 13354 NODE_NAME_CASE(VFMV_V_F_VL) 13355 NODE_NAME_CASE(VMV_X_S) 13356 NODE_NAME_CASE(VMV_S_X_VL) 13357 NODE_NAME_CASE(VFMV_S_F_VL) 13358 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 13359 NODE_NAME_CASE(READ_VLENB) 13360 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 13361 NODE_NAME_CASE(VSLIDEUP_VL) 13362 NODE_NAME_CASE(VSLIDE1UP_VL) 13363 NODE_NAME_CASE(VSLIDEDOWN_VL) 13364 NODE_NAME_CASE(VSLIDE1DOWN_VL) 13365 NODE_NAME_CASE(VID_VL) 13366 NODE_NAME_CASE(VFNCVT_ROD_VL) 13367 NODE_NAME_CASE(VECREDUCE_ADD_VL) 13368 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 13369 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 13370 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 13371 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 13372 NODE_NAME_CASE(VECREDUCE_AND_VL) 13373 NODE_NAME_CASE(VECREDUCE_OR_VL) 13374 NODE_NAME_CASE(VECREDUCE_XOR_VL) 13375 NODE_NAME_CASE(VECREDUCE_FADD_VL) 13376 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 13377 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 13378 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 13379 NODE_NAME_CASE(ADD_VL) 13380 NODE_NAME_CASE(AND_VL) 13381 NODE_NAME_CASE(MUL_VL) 13382 NODE_NAME_CASE(OR_VL) 13383 NODE_NAME_CASE(SDIV_VL) 13384 NODE_NAME_CASE(SHL_VL) 13385 NODE_NAME_CASE(SREM_VL) 13386 NODE_NAME_CASE(SRA_VL) 13387 NODE_NAME_CASE(SRL_VL) 13388 NODE_NAME_CASE(SUB_VL) 13389 NODE_NAME_CASE(UDIV_VL) 13390 NODE_NAME_CASE(UREM_VL) 13391 NODE_NAME_CASE(XOR_VL) 13392 NODE_NAME_CASE(SADDSAT_VL) 13393 NODE_NAME_CASE(UADDSAT_VL) 13394 NODE_NAME_CASE(SSUBSAT_VL) 13395 NODE_NAME_CASE(USUBSAT_VL) 13396 NODE_NAME_CASE(FADD_VL) 13397 NODE_NAME_CASE(FSUB_VL) 13398 NODE_NAME_CASE(FMUL_VL) 13399 NODE_NAME_CASE(FDIV_VL) 13400 NODE_NAME_CASE(FNEG_VL) 13401 NODE_NAME_CASE(FABS_VL) 13402 NODE_NAME_CASE(FSQRT_VL) 13403 NODE_NAME_CASE(VFMADD_VL) 13404 NODE_NAME_CASE(VFNMADD_VL) 13405 NODE_NAME_CASE(VFMSUB_VL) 13406 NODE_NAME_CASE(VFNMSUB_VL) 13407 NODE_NAME_CASE(FCOPYSIGN_VL) 13408 NODE_NAME_CASE(SMIN_VL) 13409 NODE_NAME_CASE(SMAX_VL) 13410 NODE_NAME_CASE(UMIN_VL) 13411 NODE_NAME_CASE(UMAX_VL) 13412 NODE_NAME_CASE(FMINNUM_VL) 13413 NODE_NAME_CASE(FMAXNUM_VL) 13414 NODE_NAME_CASE(MULHS_VL) 13415 NODE_NAME_CASE(MULHU_VL) 13416 NODE_NAME_CASE(VFCVT_RTZ_X_F_VL) 13417 NODE_NAME_CASE(VFCVT_RTZ_XU_F_VL) 13418 NODE_NAME_CASE(VFCVT_RM_X_F_VL) 13419 NODE_NAME_CASE(VFCVT_RM_XU_F_VL) 13420 NODE_NAME_CASE(VFCVT_X_F_VL) 13421 NODE_NAME_CASE(VFCVT_XU_F_VL) 13422 NODE_NAME_CASE(VFROUND_NOEXCEPT_VL) 13423 NODE_NAME_CASE(SINT_TO_FP_VL) 13424 NODE_NAME_CASE(UINT_TO_FP_VL) 13425 NODE_NAME_CASE(VFCVT_RM_F_XU_VL) 13426 NODE_NAME_CASE(VFCVT_RM_F_X_VL) 13427 NODE_NAME_CASE(FP_EXTEND_VL) 13428 NODE_NAME_CASE(FP_ROUND_VL) 13429 NODE_NAME_CASE(VWMUL_VL) 13430 NODE_NAME_CASE(VWMULU_VL) 13431 NODE_NAME_CASE(VWMULSU_VL) 13432 NODE_NAME_CASE(VWADD_VL) 13433 NODE_NAME_CASE(VWADDU_VL) 13434 NODE_NAME_CASE(VWSUB_VL) 13435 NODE_NAME_CASE(VWSUBU_VL) 13436 NODE_NAME_CASE(VWADD_W_VL) 13437 NODE_NAME_CASE(VWADDU_W_VL) 13438 NODE_NAME_CASE(VWSUB_W_VL) 13439 NODE_NAME_CASE(VWSUBU_W_VL) 13440 NODE_NAME_CASE(VNSRL_VL) 13441 NODE_NAME_CASE(SETCC_VL) 13442 NODE_NAME_CASE(VSELECT_VL) 13443 NODE_NAME_CASE(VP_MERGE_VL) 13444 NODE_NAME_CASE(VMAND_VL) 13445 NODE_NAME_CASE(VMOR_VL) 13446 NODE_NAME_CASE(VMXOR_VL) 13447 NODE_NAME_CASE(VMCLR_VL) 13448 NODE_NAME_CASE(VMSET_VL) 13449 NODE_NAME_CASE(VRGATHER_VX_VL) 13450 NODE_NAME_CASE(VRGATHER_VV_VL) 13451 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 13452 NODE_NAME_CASE(VSEXT_VL) 13453 NODE_NAME_CASE(VZEXT_VL) 13454 NODE_NAME_CASE(VCPOP_VL) 13455 NODE_NAME_CASE(VFIRST_VL) 13456 NODE_NAME_CASE(READ_CSR) 13457 NODE_NAME_CASE(WRITE_CSR) 13458 NODE_NAME_CASE(SWAP_CSR) 13459 } 13460 // clang-format on 13461 return nullptr; 13462 #undef NODE_NAME_CASE 13463 } 13464 13465 /// getConstraintType - Given a constraint letter, return the type of 13466 /// constraint it is for this target. 13467 RISCVTargetLowering::ConstraintType 13468 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 13469 if (Constraint.size() == 1) { 13470 switch (Constraint[0]) { 13471 default: 13472 break; 13473 case 'f': 13474 return C_RegisterClass; 13475 case 'I': 13476 case 'J': 13477 case 'K': 13478 return C_Immediate; 13479 case 'A': 13480 return C_Memory; 13481 case 'S': // A symbolic address 13482 return C_Other; 13483 } 13484 } else { 13485 if (Constraint == "vr" || Constraint == "vm") 13486 return C_RegisterClass; 13487 } 13488 return TargetLowering::getConstraintType(Constraint); 13489 } 13490 13491 std::pair<unsigned, const TargetRegisterClass *> 13492 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 13493 StringRef Constraint, 13494 MVT VT) const { 13495 // First, see if this is a constraint that directly corresponds to a 13496 // RISCV register class. 13497 if (Constraint.size() == 1) { 13498 switch (Constraint[0]) { 13499 case 'r': 13500 // TODO: Support fixed vectors up to XLen for P extension? 13501 if (VT.isVector()) 13502 break; 13503 return std::make_pair(0U, &RISCV::GPRRegClass); 13504 case 'f': 13505 if (Subtarget.hasStdExtZfhOrZfhmin() && VT == MVT::f16) 13506 return std::make_pair(0U, &RISCV::FPR16RegClass); 13507 if (Subtarget.hasStdExtF() && VT == MVT::f32) 13508 return std::make_pair(0U, &RISCV::FPR32RegClass); 13509 if (Subtarget.hasStdExtD() && VT == MVT::f64) 13510 return std::make_pair(0U, &RISCV::FPR64RegClass); 13511 break; 13512 default: 13513 break; 13514 } 13515 } else if (Constraint == "vr") { 13516 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 13517 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 13518 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 13519 return std::make_pair(0U, RC); 13520 } 13521 } else if (Constraint == "vm") { 13522 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 13523 return std::make_pair(0U, &RISCV::VMV0RegClass); 13524 } 13525 13526 // Clang will correctly decode the usage of register name aliases into their 13527 // official names. However, other frontends like `rustc` do not. This allows 13528 // users of these frontends to use the ABI names for registers in LLVM-style 13529 // register constraints. 13530 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 13531 .Case("{zero}", RISCV::X0) 13532 .Case("{ra}", RISCV::X1) 13533 .Case("{sp}", RISCV::X2) 13534 .Case("{gp}", RISCV::X3) 13535 .Case("{tp}", RISCV::X4) 13536 .Case("{t0}", RISCV::X5) 13537 .Case("{t1}", RISCV::X6) 13538 .Case("{t2}", RISCV::X7) 13539 .Cases("{s0}", "{fp}", RISCV::X8) 13540 .Case("{s1}", RISCV::X9) 13541 .Case("{a0}", RISCV::X10) 13542 .Case("{a1}", RISCV::X11) 13543 .Case("{a2}", RISCV::X12) 13544 .Case("{a3}", RISCV::X13) 13545 .Case("{a4}", RISCV::X14) 13546 .Case("{a5}", RISCV::X15) 13547 .Case("{a6}", RISCV::X16) 13548 .Case("{a7}", RISCV::X17) 13549 .Case("{s2}", RISCV::X18) 13550 .Case("{s3}", RISCV::X19) 13551 .Case("{s4}", RISCV::X20) 13552 .Case("{s5}", RISCV::X21) 13553 .Case("{s6}", RISCV::X22) 13554 .Case("{s7}", RISCV::X23) 13555 .Case("{s8}", RISCV::X24) 13556 .Case("{s9}", RISCV::X25) 13557 .Case("{s10}", RISCV::X26) 13558 .Case("{s11}", RISCV::X27) 13559 .Case("{t3}", RISCV::X28) 13560 .Case("{t4}", RISCV::X29) 13561 .Case("{t5}", RISCV::X30) 13562 .Case("{t6}", RISCV::X31) 13563 .Default(RISCV::NoRegister); 13564 if (XRegFromAlias != RISCV::NoRegister) 13565 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 13566 13567 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 13568 // TableGen record rather than the AsmName to choose registers for InlineAsm 13569 // constraints, plus we want to match those names to the widest floating point 13570 // register type available, manually select floating point registers here. 13571 // 13572 // The second case is the ABI name of the register, so that frontends can also 13573 // use the ABI names in register constraint lists. 13574 if (Subtarget.hasStdExtF()) { 13575 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 13576 .Cases("{f0}", "{ft0}", RISCV::F0_F) 13577 .Cases("{f1}", "{ft1}", RISCV::F1_F) 13578 .Cases("{f2}", "{ft2}", RISCV::F2_F) 13579 .Cases("{f3}", "{ft3}", RISCV::F3_F) 13580 .Cases("{f4}", "{ft4}", RISCV::F4_F) 13581 .Cases("{f5}", "{ft5}", RISCV::F5_F) 13582 .Cases("{f6}", "{ft6}", RISCV::F6_F) 13583 .Cases("{f7}", "{ft7}", RISCV::F7_F) 13584 .Cases("{f8}", "{fs0}", RISCV::F8_F) 13585 .Cases("{f9}", "{fs1}", RISCV::F9_F) 13586 .Cases("{f10}", "{fa0}", RISCV::F10_F) 13587 .Cases("{f11}", "{fa1}", RISCV::F11_F) 13588 .Cases("{f12}", "{fa2}", RISCV::F12_F) 13589 .Cases("{f13}", "{fa3}", RISCV::F13_F) 13590 .Cases("{f14}", "{fa4}", RISCV::F14_F) 13591 .Cases("{f15}", "{fa5}", RISCV::F15_F) 13592 .Cases("{f16}", "{fa6}", RISCV::F16_F) 13593 .Cases("{f17}", "{fa7}", RISCV::F17_F) 13594 .Cases("{f18}", "{fs2}", RISCV::F18_F) 13595 .Cases("{f19}", "{fs3}", RISCV::F19_F) 13596 .Cases("{f20}", "{fs4}", RISCV::F20_F) 13597 .Cases("{f21}", "{fs5}", RISCV::F21_F) 13598 .Cases("{f22}", "{fs6}", RISCV::F22_F) 13599 .Cases("{f23}", "{fs7}", RISCV::F23_F) 13600 .Cases("{f24}", "{fs8}", RISCV::F24_F) 13601 .Cases("{f25}", "{fs9}", RISCV::F25_F) 13602 .Cases("{f26}", "{fs10}", RISCV::F26_F) 13603 .Cases("{f27}", "{fs11}", RISCV::F27_F) 13604 .Cases("{f28}", "{ft8}", RISCV::F28_F) 13605 .Cases("{f29}", "{ft9}", RISCV::F29_F) 13606 .Cases("{f30}", "{ft10}", RISCV::F30_F) 13607 .Cases("{f31}", "{ft11}", RISCV::F31_F) 13608 .Default(RISCV::NoRegister); 13609 if (FReg != RISCV::NoRegister) { 13610 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 13611 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 13612 unsigned RegNo = FReg - RISCV::F0_F; 13613 unsigned DReg = RISCV::F0_D + RegNo; 13614 return std::make_pair(DReg, &RISCV::FPR64RegClass); 13615 } 13616 if (VT == MVT::f32 || VT == MVT::Other) 13617 return std::make_pair(FReg, &RISCV::FPR32RegClass); 13618 if (Subtarget.hasStdExtZfhOrZfhmin() && VT == MVT::f16) { 13619 unsigned RegNo = FReg - RISCV::F0_F; 13620 unsigned HReg = RISCV::F0_H + RegNo; 13621 return std::make_pair(HReg, &RISCV::FPR16RegClass); 13622 } 13623 } 13624 } 13625 13626 if (Subtarget.hasVInstructions()) { 13627 Register VReg = StringSwitch<Register>(Constraint.lower()) 13628 .Case("{v0}", RISCV::V0) 13629 .Case("{v1}", RISCV::V1) 13630 .Case("{v2}", RISCV::V2) 13631 .Case("{v3}", RISCV::V3) 13632 .Case("{v4}", RISCV::V4) 13633 .Case("{v5}", RISCV::V5) 13634 .Case("{v6}", RISCV::V6) 13635 .Case("{v7}", RISCV::V7) 13636 .Case("{v8}", RISCV::V8) 13637 .Case("{v9}", RISCV::V9) 13638 .Case("{v10}", RISCV::V10) 13639 .Case("{v11}", RISCV::V11) 13640 .Case("{v12}", RISCV::V12) 13641 .Case("{v13}", RISCV::V13) 13642 .Case("{v14}", RISCV::V14) 13643 .Case("{v15}", RISCV::V15) 13644 .Case("{v16}", RISCV::V16) 13645 .Case("{v17}", RISCV::V17) 13646 .Case("{v18}", RISCV::V18) 13647 .Case("{v19}", RISCV::V19) 13648 .Case("{v20}", RISCV::V20) 13649 .Case("{v21}", RISCV::V21) 13650 .Case("{v22}", RISCV::V22) 13651 .Case("{v23}", RISCV::V23) 13652 .Case("{v24}", RISCV::V24) 13653 .Case("{v25}", RISCV::V25) 13654 .Case("{v26}", RISCV::V26) 13655 .Case("{v27}", RISCV::V27) 13656 .Case("{v28}", RISCV::V28) 13657 .Case("{v29}", RISCV::V29) 13658 .Case("{v30}", RISCV::V30) 13659 .Case("{v31}", RISCV::V31) 13660 .Default(RISCV::NoRegister); 13661 if (VReg != RISCV::NoRegister) { 13662 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 13663 return std::make_pair(VReg, &RISCV::VMRegClass); 13664 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 13665 return std::make_pair(VReg, &RISCV::VRRegClass); 13666 for (const auto *RC : 13667 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 13668 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 13669 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 13670 return std::make_pair(VReg, RC); 13671 } 13672 } 13673 } 13674 } 13675 13676 std::pair<Register, const TargetRegisterClass *> Res = 13677 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13678 13679 // If we picked one of the Zfinx register classes, remap it to the GPR class. 13680 // FIXME: When Zfinx is supported in CodeGen this will need to take the 13681 // Subtarget into account. 13682 if (Res.second == &RISCV::GPRF16RegClass || 13683 Res.second == &RISCV::GPRF32RegClass || 13684 Res.second == &RISCV::GPRF64RegClass) 13685 return std::make_pair(Res.first, &RISCV::GPRRegClass); 13686 13687 return Res; 13688 } 13689 13690 unsigned 13691 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 13692 // Currently only support length 1 constraints. 13693 if (ConstraintCode.size() == 1) { 13694 switch (ConstraintCode[0]) { 13695 case 'A': 13696 return InlineAsm::Constraint_A; 13697 default: 13698 break; 13699 } 13700 } 13701 13702 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 13703 } 13704 13705 void RISCVTargetLowering::LowerAsmOperandForConstraint( 13706 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 13707 SelectionDAG &DAG) const { 13708 // Currently only support length 1 constraints. 13709 if (Constraint.length() == 1) { 13710 switch (Constraint[0]) { 13711 case 'I': 13712 // Validate & create a 12-bit signed immediate operand. 13713 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 13714 uint64_t CVal = C->getSExtValue(); 13715 if (isInt<12>(CVal)) 13716 Ops.push_back( 13717 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 13718 } 13719 return; 13720 case 'J': 13721 // Validate & create an integer zero operand. 13722 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 13723 if (C->getZExtValue() == 0) 13724 Ops.push_back( 13725 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 13726 return; 13727 case 'K': 13728 // Validate & create a 5-bit unsigned immediate operand. 13729 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 13730 uint64_t CVal = C->getZExtValue(); 13731 if (isUInt<5>(CVal)) 13732 Ops.push_back( 13733 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 13734 } 13735 return; 13736 case 'S': 13737 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 13738 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 13739 GA->getValueType(0))); 13740 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 13741 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 13742 BA->getValueType(0))); 13743 } 13744 return; 13745 default: 13746 break; 13747 } 13748 } 13749 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13750 } 13751 13752 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 13753 Instruction *Inst, 13754 AtomicOrdering Ord) const { 13755 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 13756 return Builder.CreateFence(Ord); 13757 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 13758 return Builder.CreateFence(AtomicOrdering::Release); 13759 return nullptr; 13760 } 13761 13762 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 13763 Instruction *Inst, 13764 AtomicOrdering Ord) const { 13765 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 13766 return Builder.CreateFence(AtomicOrdering::Acquire); 13767 return nullptr; 13768 } 13769 13770 TargetLowering::AtomicExpansionKind 13771 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 13772 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 13773 // point operations can't be used in an lr/sc sequence without breaking the 13774 // forward-progress guarantee. 13775 if (AI->isFloatingPointOperation() || 13776 AI->getOperation() == AtomicRMWInst::UIncWrap || 13777 AI->getOperation() == AtomicRMWInst::UDecWrap) 13778 return AtomicExpansionKind::CmpXChg; 13779 13780 // Don't expand forced atomics, we want to have __sync libcalls instead. 13781 if (Subtarget.hasForcedAtomics()) 13782 return AtomicExpansionKind::None; 13783 13784 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 13785 if (Size == 8 || Size == 16) 13786 return AtomicExpansionKind::MaskedIntrinsic; 13787 return AtomicExpansionKind::None; 13788 } 13789 13790 static Intrinsic::ID 13791 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 13792 if (XLen == 32) { 13793 switch (BinOp) { 13794 default: 13795 llvm_unreachable("Unexpected AtomicRMW BinOp"); 13796 case AtomicRMWInst::Xchg: 13797 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 13798 case AtomicRMWInst::Add: 13799 return Intrinsic::riscv_masked_atomicrmw_add_i32; 13800 case AtomicRMWInst::Sub: 13801 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 13802 case AtomicRMWInst::Nand: 13803 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 13804 case AtomicRMWInst::Max: 13805 return Intrinsic::riscv_masked_atomicrmw_max_i32; 13806 case AtomicRMWInst::Min: 13807 return Intrinsic::riscv_masked_atomicrmw_min_i32; 13808 case AtomicRMWInst::UMax: 13809 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 13810 case AtomicRMWInst::UMin: 13811 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 13812 } 13813 } 13814 13815 if (XLen == 64) { 13816 switch (BinOp) { 13817 default: 13818 llvm_unreachable("Unexpected AtomicRMW BinOp"); 13819 case AtomicRMWInst::Xchg: 13820 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 13821 case AtomicRMWInst::Add: 13822 return Intrinsic::riscv_masked_atomicrmw_add_i64; 13823 case AtomicRMWInst::Sub: 13824 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 13825 case AtomicRMWInst::Nand: 13826 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 13827 case AtomicRMWInst::Max: 13828 return Intrinsic::riscv_masked_atomicrmw_max_i64; 13829 case AtomicRMWInst::Min: 13830 return Intrinsic::riscv_masked_atomicrmw_min_i64; 13831 case AtomicRMWInst::UMax: 13832 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 13833 case AtomicRMWInst::UMin: 13834 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 13835 } 13836 } 13837 13838 llvm_unreachable("Unexpected XLen\n"); 13839 } 13840 13841 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 13842 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 13843 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 13844 unsigned XLen = Subtarget.getXLen(); 13845 Value *Ordering = 13846 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 13847 Type *Tys[] = {AlignedAddr->getType()}; 13848 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 13849 AI->getModule(), 13850 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 13851 13852 if (XLen == 64) { 13853 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 13854 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 13855 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 13856 } 13857 13858 Value *Result; 13859 13860 // Must pass the shift amount needed to sign extend the loaded value prior 13861 // to performing a signed comparison for min/max. ShiftAmt is the number of 13862 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 13863 // is the number of bits to left+right shift the value in order to 13864 // sign-extend. 13865 if (AI->getOperation() == AtomicRMWInst::Min || 13866 AI->getOperation() == AtomicRMWInst::Max) { 13867 const DataLayout &DL = AI->getModule()->getDataLayout(); 13868 unsigned ValWidth = 13869 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 13870 Value *SextShamt = 13871 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 13872 Result = Builder.CreateCall(LrwOpScwLoop, 13873 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 13874 } else { 13875 Result = 13876 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 13877 } 13878 13879 if (XLen == 64) 13880 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 13881 return Result; 13882 } 13883 13884 TargetLowering::AtomicExpansionKind 13885 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 13886 AtomicCmpXchgInst *CI) const { 13887 // Don't expand forced atomics, we want to have __sync libcalls instead. 13888 if (Subtarget.hasForcedAtomics()) 13889 return AtomicExpansionKind::None; 13890 13891 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 13892 if (Size == 8 || Size == 16) 13893 return AtomicExpansionKind::MaskedIntrinsic; 13894 return AtomicExpansionKind::None; 13895 } 13896 13897 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 13898 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 13899 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 13900 unsigned XLen = Subtarget.getXLen(); 13901 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 13902 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 13903 if (XLen == 64) { 13904 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 13905 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 13906 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 13907 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 13908 } 13909 Type *Tys[] = {AlignedAddr->getType()}; 13910 Function *MaskedCmpXchg = 13911 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 13912 Value *Result = Builder.CreateCall( 13913 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 13914 if (XLen == 64) 13915 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 13916 return Result; 13917 } 13918 13919 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT, 13920 EVT DataVT) const { 13921 return false; 13922 } 13923 13924 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 13925 EVT VT) const { 13926 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 13927 return false; 13928 13929 switch (FPVT.getSimpleVT().SimpleTy) { 13930 case MVT::f16: 13931 return Subtarget.hasStdExtZfhOrZfhmin(); 13932 case MVT::f32: 13933 return Subtarget.hasStdExtF(); 13934 case MVT::f64: 13935 return Subtarget.hasStdExtD(); 13936 default: 13937 return false; 13938 } 13939 } 13940 13941 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 13942 // If we are using the small code model, we can reduce size of jump table 13943 // entry to 4 bytes. 13944 if (Subtarget.is64Bit() && !isPositionIndependent() && 13945 getTargetMachine().getCodeModel() == CodeModel::Small) { 13946 return MachineJumpTableInfo::EK_Custom32; 13947 } 13948 return TargetLowering::getJumpTableEncoding(); 13949 } 13950 13951 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 13952 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 13953 unsigned uid, MCContext &Ctx) const { 13954 assert(Subtarget.is64Bit() && !isPositionIndependent() && 13955 getTargetMachine().getCodeModel() == CodeModel::Small); 13956 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 13957 } 13958 13959 bool RISCVTargetLowering::isVScaleKnownToBeAPowerOfTwo() const { 13960 // We define vscale to be VLEN/RVVBitsPerBlock. VLEN is always a power 13961 // of two >= 64, and RVVBitsPerBlock is 64. Thus, vscale must be 13962 // a power of two as well. 13963 // FIXME: This doesn't work for zve32, but that's already broken 13964 // elsewhere for the same reason. 13965 assert(Subtarget.getRealMinVLen() >= 64 && "zve32* unsupported"); 13966 static_assert(RISCV::RVVBitsPerBlock == 64, 13967 "RVVBitsPerBlock changed, audit needed"); 13968 return true; 13969 } 13970 13971 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 13972 EVT VT) const { 13973 EVT SVT = VT.getScalarType(); 13974 13975 if (!SVT.isSimple()) 13976 return false; 13977 13978 switch (SVT.getSimpleVT().SimpleTy) { 13979 case MVT::f16: 13980 return VT.isVector() ? Subtarget.hasVInstructionsF16() 13981 : Subtarget.hasStdExtZfh(); 13982 case MVT::f32: 13983 return Subtarget.hasStdExtF(); 13984 case MVT::f64: 13985 return Subtarget.hasStdExtD(); 13986 default: 13987 break; 13988 } 13989 13990 return false; 13991 } 13992 13993 Register RISCVTargetLowering::getExceptionPointerRegister( 13994 const Constant *PersonalityFn) const { 13995 return RISCV::X10; 13996 } 13997 13998 Register RISCVTargetLowering::getExceptionSelectorRegister( 13999 const Constant *PersonalityFn) const { 14000 return RISCV::X11; 14001 } 14002 14003 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 14004 // Return false to suppress the unnecessary extensions if the LibCall 14005 // arguments or return value is f32 type for LP64 ABI. 14006 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 14007 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 14008 return false; 14009 14010 return true; 14011 } 14012 14013 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 14014 if (Subtarget.is64Bit() && Type == MVT::i32) 14015 return true; 14016 14017 return IsSigned; 14018 } 14019 14020 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 14021 SDValue C) const { 14022 // Check integral scalar types. 14023 const bool HasExtMOrZmmul = 14024 Subtarget.hasStdExtM() || Subtarget.hasStdExtZmmul(); 14025 if (VT.isScalarInteger()) { 14026 // Omit the optimization if the sub target has the M extension and the data 14027 // size exceeds XLen. 14028 if (HasExtMOrZmmul && VT.getSizeInBits() > Subtarget.getXLen()) 14029 return false; 14030 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 14031 // Break the MUL to a SLLI and an ADD/SUB. 14032 const APInt &Imm = ConstNode->getAPIntValue(); 14033 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 14034 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 14035 return true; 14036 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 14037 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 14038 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 14039 (Imm - 8).isPowerOf2())) 14040 return true; 14041 // Omit the following optimization if the sub target has the M extension 14042 // and the data size >= XLen. 14043 if (HasExtMOrZmmul && VT.getSizeInBits() >= Subtarget.getXLen()) 14044 return false; 14045 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 14046 // a pair of LUI/ADDI. 14047 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 14048 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 14049 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 14050 (1 - ImmS).isPowerOf2()) 14051 return true; 14052 } 14053 } 14054 } 14055 14056 return false; 14057 } 14058 14059 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 14060 SDValue ConstNode) const { 14061 // Let the DAGCombiner decide for vectors. 14062 EVT VT = AddNode.getValueType(); 14063 if (VT.isVector()) 14064 return true; 14065 14066 // Let the DAGCombiner decide for larger types. 14067 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 14068 return true; 14069 14070 // It is worse if c1 is simm12 while c1*c2 is not. 14071 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 14072 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 14073 const APInt &C1 = C1Node->getAPIntValue(); 14074 const APInt &C2 = C2Node->getAPIntValue(); 14075 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 14076 return false; 14077 14078 // Default to true and let the DAGCombiner decide. 14079 return true; 14080 } 14081 14082 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 14083 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 14084 unsigned *Fast) const { 14085 if (!VT.isVector()) { 14086 if (Fast) 14087 *Fast = 0; 14088 return Subtarget.enableUnalignedScalarMem(); 14089 } 14090 14091 // All vector implementations must support element alignment 14092 EVT ElemVT = VT.getVectorElementType(); 14093 if (Alignment >= ElemVT.getStoreSize()) { 14094 if (Fast) 14095 *Fast = 1; 14096 return true; 14097 } 14098 14099 return false; 14100 } 14101 14102 bool RISCVTargetLowering::splitValueIntoRegisterParts( 14103 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 14104 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const { 14105 bool IsABIRegCopy = CC.has_value(); 14106 EVT ValueVT = Val.getValueType(); 14107 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 14108 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 14109 // and cast to f32. 14110 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 14111 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 14112 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 14113 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 14114 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 14115 Parts[0] = Val; 14116 return true; 14117 } 14118 14119 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 14120 LLVMContext &Context = *DAG.getContext(); 14121 EVT ValueEltVT = ValueVT.getVectorElementType(); 14122 EVT PartEltVT = PartVT.getVectorElementType(); 14123 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinValue(); 14124 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinValue(); 14125 if (PartVTBitSize % ValueVTBitSize == 0) { 14126 assert(PartVTBitSize >= ValueVTBitSize); 14127 // If the element types are different, bitcast to the same element type of 14128 // PartVT first. 14129 // Give an example here, we want copy a <vscale x 1 x i8> value to 14130 // <vscale x 4 x i16>. 14131 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 14132 // subvector, then we can bitcast to <vscale x 4 x i16>. 14133 if (ValueEltVT != PartEltVT) { 14134 if (PartVTBitSize > ValueVTBitSize) { 14135 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 14136 assert(Count != 0 && "The number of element should not be zero."); 14137 EVT SameEltTypeVT = 14138 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 14139 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 14140 DAG.getUNDEF(SameEltTypeVT), Val, 14141 DAG.getVectorIdxConstant(0, DL)); 14142 } 14143 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 14144 } else { 14145 Val = 14146 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 14147 Val, DAG.getVectorIdxConstant(0, DL)); 14148 } 14149 Parts[0] = Val; 14150 return true; 14151 } 14152 } 14153 return false; 14154 } 14155 14156 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 14157 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 14158 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const { 14159 bool IsABIRegCopy = CC.has_value(); 14160 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 14161 SDValue Val = Parts[0]; 14162 14163 // Cast the f32 to i32, truncate to i16, and cast back to f16. 14164 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 14165 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 14166 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 14167 return Val; 14168 } 14169 14170 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 14171 LLVMContext &Context = *DAG.getContext(); 14172 SDValue Val = Parts[0]; 14173 EVT ValueEltVT = ValueVT.getVectorElementType(); 14174 EVT PartEltVT = PartVT.getVectorElementType(); 14175 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinValue(); 14176 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinValue(); 14177 if (PartVTBitSize % ValueVTBitSize == 0) { 14178 assert(PartVTBitSize >= ValueVTBitSize); 14179 EVT SameEltTypeVT = ValueVT; 14180 // If the element types are different, convert it to the same element type 14181 // of PartVT. 14182 // Give an example here, we want copy a <vscale x 1 x i8> value from 14183 // <vscale x 4 x i16>. 14184 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 14185 // then we can extract <vscale x 1 x i8>. 14186 if (ValueEltVT != PartEltVT) { 14187 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 14188 assert(Count != 0 && "The number of element should not be zero."); 14189 SameEltTypeVT = 14190 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 14191 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 14192 } 14193 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 14194 DAG.getVectorIdxConstant(0, DL)); 14195 return Val; 14196 } 14197 } 14198 return SDValue(); 14199 } 14200 14201 bool RISCVTargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const { 14202 // When aggressively optimizing for code size, we prefer to use a div 14203 // instruction, as it is usually smaller than the alternative sequence. 14204 // TODO: Add vector division? 14205 bool OptSize = Attr.hasFnAttr(Attribute::MinSize); 14206 return OptSize && !VT.isVector(); 14207 } 14208 14209 bool RISCVTargetLowering::preferScalarizeSplat(unsigned Opc) const { 14210 // Scalarize zero_ext and sign_ext might stop match to widening instruction in 14211 // some situation. 14212 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND) 14213 return false; 14214 return true; 14215 } 14216 14217 static Value *useTpOffset(IRBuilderBase &IRB, unsigned Offset) { 14218 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 14219 Function *ThreadPointerFunc = 14220 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 14221 return IRB.CreatePointerCast( 14222 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), 14223 IRB.CreateCall(ThreadPointerFunc), Offset), 14224 IRB.getInt8PtrTy()->getPointerTo(0)); 14225 } 14226 14227 Value *RISCVTargetLowering::getIRStackGuard(IRBuilderBase &IRB) const { 14228 // Fuchsia provides a fixed TLS slot for the stack cookie. 14229 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value. 14230 if (Subtarget.isTargetFuchsia()) 14231 return useTpOffset(IRB, -0x10); 14232 14233 return TargetLowering::getIRStackGuard(IRB); 14234 } 14235 14236 #define GET_REGISTER_MATCHER 14237 #include "RISCVGenAsmMatcher.inc" 14238 14239 Register 14240 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 14241 const MachineFunction &MF) const { 14242 Register Reg = MatchRegisterAltName(RegName); 14243 if (Reg == RISCV::NoRegister) 14244 Reg = MatchRegisterName(RegName); 14245 if (Reg == RISCV::NoRegister) 14246 report_fatal_error( 14247 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 14248 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 14249 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 14250 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 14251 StringRef(RegName) + "\".")); 14252 return Reg; 14253 } 14254 14255 namespace llvm::RISCVVIntrinsicsTable { 14256 14257 #define GET_RISCVVIntrinsicsTable_IMPL 14258 #include "RISCVGenSearchableTables.inc" 14259 14260 } // namespace llvm::RISCVVIntrinsicsTable 14261