1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 116 assert(Size <= 512 && isPowerOf2_32(Size)); 117 const TargetRegisterClass *RC; 118 if (Size <= 64) 119 RC = &RISCV::VRRegClass; 120 else if (Size == 128) 121 RC = &RISCV::VRM2RegClass; 122 else if (Size == 256) 123 RC = &RISCV::VRM4RegClass; 124 else 125 RC = &RISCV::VRM8RegClass; 126 127 addRegisterClass(VT, RC); 128 }; 129 130 for (MVT VT : BoolVecVTs) 131 addRegClassForRVV(VT); 132 for (MVT VT : IntVecVTs) { 133 if (VT.getVectorElementType() == MVT::i64 && 134 !Subtarget.hasVInstructionsI64()) 135 continue; 136 addRegClassForRVV(VT); 137 } 138 139 if (Subtarget.hasVInstructionsF16()) 140 for (MVT VT : F16VecVTs) 141 addRegClassForRVV(VT); 142 143 if (Subtarget.hasVInstructionsF32()) 144 for (MVT VT : F32VecVTs) 145 addRegClassForRVV(VT); 146 147 if (Subtarget.hasVInstructionsF64()) 148 for (MVT VT : F64VecVTs) 149 addRegClassForRVV(VT); 150 151 if (Subtarget.useRVVForFixedLengthVectors()) { 152 auto addRegClassForFixedVectors = [this](MVT VT) { 153 MVT ContainerVT = getContainerForFixedLengthVector(VT); 154 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 155 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 156 addRegisterClass(VT, TRI.getRegClass(RCID)); 157 }; 158 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 159 if (useRVVForFixedLengthVectorVT(VT)) 160 addRegClassForFixedVectors(VT); 161 162 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 163 if (useRVVForFixedLengthVectorVT(VT)) 164 addRegClassForFixedVectors(VT); 165 } 166 } 167 168 // Compute derived properties from the register classes. 169 computeRegisterProperties(STI.getRegisterInfo()); 170 171 setStackPointerRegisterToSaveRestore(RISCV::X2); 172 173 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 174 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 175 176 // TODO: add all necessary setOperationAction calls. 177 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 178 179 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 180 setOperationAction(ISD::BR_CC, XLenVT, Expand); 181 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 182 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 183 184 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 185 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 186 187 setOperationAction(ISD::VASTART, MVT::Other, Custom); 188 setOperationAction(ISD::VAARG, MVT::Other, Expand); 189 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 190 setOperationAction(ISD::VAEND, MVT::Other, Expand); 191 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 193 if (!Subtarget.hasStdExtZbb()) { 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 196 } 197 198 if (Subtarget.is64Bit()) { 199 setOperationAction(ISD::ADD, MVT::i32, Custom); 200 setOperationAction(ISD::SUB, MVT::i32, Custom); 201 setOperationAction(ISD::SHL, MVT::i32, Custom); 202 setOperationAction(ISD::SRA, MVT::i32, Custom); 203 setOperationAction(ISD::SRL, MVT::i32, Custom); 204 205 setOperationAction(ISD::UADDO, MVT::i32, Custom); 206 setOperationAction(ISD::USUBO, MVT::i32, Custom); 207 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 208 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 209 } else { 210 setLibcallName(RTLIB::SHL_I128, nullptr); 211 setLibcallName(RTLIB::SRL_I128, nullptr); 212 setLibcallName(RTLIB::SRA_I128, nullptr); 213 setLibcallName(RTLIB::MUL_I128, nullptr); 214 setLibcallName(RTLIB::MULO_I64, nullptr); 215 } 216 217 if (!Subtarget.hasStdExtM()) { 218 setOperationAction(ISD::MUL, XLenVT, Expand); 219 setOperationAction(ISD::MULHS, XLenVT, Expand); 220 setOperationAction(ISD::MULHU, XLenVT, Expand); 221 setOperationAction(ISD::SDIV, XLenVT, Expand); 222 setOperationAction(ISD::UDIV, XLenVT, Expand); 223 setOperationAction(ISD::SREM, XLenVT, Expand); 224 setOperationAction(ISD::UREM, XLenVT, Expand); 225 } else { 226 if (Subtarget.is64Bit()) { 227 setOperationAction(ISD::MUL, MVT::i32, Custom); 228 setOperationAction(ISD::MUL, MVT::i128, Custom); 229 230 setOperationAction(ISD::SDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UDIV, MVT::i8, Custom); 232 setOperationAction(ISD::UREM, MVT::i8, Custom); 233 setOperationAction(ISD::SDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UDIV, MVT::i16, Custom); 235 setOperationAction(ISD::UREM, MVT::i16, Custom); 236 setOperationAction(ISD::SDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UDIV, MVT::i32, Custom); 238 setOperationAction(ISD::UREM, MVT::i32, Custom); 239 } else { 240 setOperationAction(ISD::MUL, MVT::i64, Custom); 241 } 242 } 243 244 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 246 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 247 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 248 249 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 251 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 252 253 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 254 Subtarget.hasStdExtZbkb()) { 255 if (Subtarget.is64Bit()) { 256 setOperationAction(ISD::ROTL, MVT::i32, Custom); 257 setOperationAction(ISD::ROTR, MVT::i32, Custom); 258 } 259 } else { 260 setOperationAction(ISD::ROTL, XLenVT, Expand); 261 setOperationAction(ISD::ROTR, XLenVT, Expand); 262 } 263 264 if (Subtarget.hasStdExtZbp()) { 265 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 266 // more combining. 267 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 268 setOperationAction(ISD::BSWAP, XLenVT, Custom); 269 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 270 // BSWAP i8 doesn't exist. 271 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 272 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 273 274 if (Subtarget.is64Bit()) { 275 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 276 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 277 } 278 } else { 279 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 280 // pattern match it directly in isel. 281 setOperationAction(ISD::BSWAP, XLenVT, 282 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 283 ? Legal 284 : Expand); 285 // Zbkb can use rev8+brev8 to implement bitreverse. 286 setOperationAction(ISD::BITREVERSE, XLenVT, 287 Subtarget.hasStdExtZbkb() ? Custom : Expand); 288 } 289 290 if (Subtarget.hasStdExtZbb()) { 291 setOperationAction(ISD::SMIN, XLenVT, Legal); 292 setOperationAction(ISD::SMAX, XLenVT, Legal); 293 setOperationAction(ISD::UMIN, XLenVT, Legal); 294 setOperationAction(ISD::UMAX, XLenVT, Legal); 295 296 if (Subtarget.is64Bit()) { 297 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 298 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 299 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 300 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 301 } 302 } else { 303 setOperationAction(ISD::CTTZ, XLenVT, Expand); 304 setOperationAction(ISD::CTLZ, XLenVT, Expand); 305 setOperationAction(ISD::CTPOP, XLenVT, Expand); 306 307 if (Subtarget.is64Bit()) 308 setOperationAction(ISD::ABS, MVT::i32, Custom); 309 } 310 311 if (Subtarget.hasStdExtZbt()) { 312 setOperationAction(ISD::FSHL, XLenVT, Custom); 313 setOperationAction(ISD::FSHR, XLenVT, Custom); 314 setOperationAction(ISD::SELECT, XLenVT, Legal); 315 316 if (Subtarget.is64Bit()) { 317 setOperationAction(ISD::FSHL, MVT::i32, Custom); 318 setOperationAction(ISD::FSHR, MVT::i32, Custom); 319 } 320 } else { 321 setOperationAction(ISD::SELECT, XLenVT, Custom); 322 } 323 324 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 325 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 326 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 327 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 328 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 329 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 330 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 331 332 static const ISD::CondCode FPCCToExpand[] = { 333 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 334 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 335 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 336 337 static const ISD::NodeType FPOpToExpand[] = { 338 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 339 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 340 341 if (Subtarget.hasStdExtZfh()) 342 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 343 344 if (Subtarget.hasStdExtZfh()) { 345 for (auto NT : FPLegalNodeTypes) 346 setOperationAction(NT, MVT::f16, Legal); 347 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 348 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 349 for (auto CC : FPCCToExpand) 350 setCondCodeAction(CC, MVT::f16, Expand); 351 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 352 setOperationAction(ISD::SELECT, MVT::f16, Custom); 353 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 354 355 setOperationAction(ISD::FREM, MVT::f16, Promote); 356 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 357 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 358 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 359 setOperationAction(ISD::FRINT, MVT::f16, Promote); 360 setOperationAction(ISD::FROUND, MVT::f16, Promote); 361 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 362 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 363 setOperationAction(ISD::FPOW, MVT::f16, Promote); 364 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 365 setOperationAction(ISD::FCOS, MVT::f16, Promote); 366 setOperationAction(ISD::FSIN, MVT::f16, Promote); 367 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 368 setOperationAction(ISD::FEXP, MVT::f16, Promote); 369 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 370 setOperationAction(ISD::FLOG, MVT::f16, Promote); 371 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 372 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 373 374 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 375 // complete support for all operations in LegalizeDAG. 376 377 // We need to custom promote this. 378 if (Subtarget.is64Bit()) 379 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 380 } 381 382 if (Subtarget.hasStdExtF()) { 383 for (auto NT : FPLegalNodeTypes) 384 setOperationAction(NT, MVT::f32, Legal); 385 for (auto CC : FPCCToExpand) 386 setCondCodeAction(CC, MVT::f32, Expand); 387 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 388 setOperationAction(ISD::SELECT, MVT::f32, Custom); 389 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 390 for (auto Op : FPOpToExpand) 391 setOperationAction(Op, MVT::f32, Expand); 392 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 393 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 394 } 395 396 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 397 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 398 399 if (Subtarget.hasStdExtD()) { 400 for (auto NT : FPLegalNodeTypes) 401 setOperationAction(NT, MVT::f64, Legal); 402 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 403 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 404 for (auto CC : FPCCToExpand) 405 setCondCodeAction(CC, MVT::f64, Expand); 406 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 407 setOperationAction(ISD::SELECT, MVT::f64, Custom); 408 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 409 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 410 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 411 for (auto Op : FPOpToExpand) 412 setOperationAction(Op, MVT::f64, Expand); 413 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 414 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 415 } 416 417 if (Subtarget.is64Bit()) { 418 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 419 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 420 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 421 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 422 } 423 424 if (Subtarget.hasStdExtF()) { 425 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 426 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 427 428 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 429 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 430 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 431 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 432 433 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 434 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 435 } 436 437 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 438 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 439 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 440 setOperationAction(ISD::JumpTable, XLenVT, Custom); 441 442 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 443 444 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 445 // Unfortunately this can't be determined just from the ISA naming string. 446 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 447 Subtarget.is64Bit() ? Legal : Custom); 448 449 setOperationAction(ISD::TRAP, MVT::Other, Legal); 450 setOperationAction(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 { 459 setMaxAtomicSizeInBitsSupported(0); 460 } 461 462 setBooleanContents(ZeroOrOneBooleanContent); 463 464 if (Subtarget.hasVInstructions()) { 465 setBooleanVectorContents(ZeroOrOneBooleanContent); 466 467 setOperationAction(ISD::VSCALE, XLenVT, Custom); 468 469 // RVV intrinsics may have illegal operands. 470 // We also need to custom legalize vmv.x.s. 471 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 474 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 475 if (Subtarget.is64Bit()) { 476 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 477 } else { 478 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 479 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 480 } 481 482 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 483 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 484 485 static const unsigned IntegerVPOps[] = { 486 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 487 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 488 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 489 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 490 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 491 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 492 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 493 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FPTOSI, 494 ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_SEXT, 495 ISD::VP_ZEXT}; 496 497 static const unsigned FloatingPointVPOps[] = { 498 ISD::VP_FADD, ISD::VP_FSUB, 499 ISD::VP_FMUL, ISD::VP_FDIV, 500 ISD::VP_FNEG, ISD::VP_FMA, 501 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 502 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, 503 ISD::VP_MERGE, ISD::VP_SELECT, 504 ISD::VP_SITOFP, ISD::VP_UITOFP, 505 ISD::VP_SETCC}; 506 507 if (!Subtarget.is64Bit()) { 508 // We must custom-lower certain vXi64 operations on RV32 due to the vector 509 // element type being illegal. 510 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 511 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 512 513 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 514 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 515 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 516 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 517 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 518 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 519 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 520 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 521 522 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 523 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 524 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 525 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 526 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 527 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 528 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 529 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 530 } 531 532 for (MVT VT : BoolVecVTs) { 533 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 534 535 // Mask VTs are custom-expanded into a series of standard nodes 536 setOperationAction(ISD::TRUNCATE, VT, Custom); 537 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 538 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 539 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 540 541 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 542 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 543 544 setOperationAction(ISD::SELECT, VT, Custom); 545 setOperationAction(ISD::SELECT_CC, VT, Expand); 546 setOperationAction(ISD::VSELECT, VT, Expand); 547 setOperationAction(ISD::VP_MERGE, VT, Expand); 548 setOperationAction(ISD::VP_SELECT, VT, Expand); 549 550 setOperationAction(ISD::VP_AND, VT, Custom); 551 setOperationAction(ISD::VP_OR, VT, Custom); 552 setOperationAction(ISD::VP_XOR, VT, Custom); 553 554 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 555 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 556 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 557 558 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 559 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 560 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 561 562 // RVV has native int->float & float->int conversions where the 563 // element type sizes are within one power-of-two of each other. Any 564 // wider distances between type sizes have to be lowered as sequences 565 // which progressively narrow the gap in stages. 566 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 567 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 568 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 569 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 570 571 // Expand all extending loads to types larger than this, and truncating 572 // stores from types larger than this. 573 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 574 setTruncStoreAction(OtherVT, VT, Expand); 575 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 576 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 577 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 578 } 579 580 setOperationAction(ISD::VP_FPTOSI, VT, Custom); 581 setOperationAction(ISD::VP_FPTOUI, VT, Custom); 582 } 583 584 for (MVT VT : IntVecVTs) { 585 if (VT.getVectorElementType() == MVT::i64 && 586 !Subtarget.hasVInstructionsI64()) 587 continue; 588 589 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 590 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 591 592 // Vectors implement MULHS/MULHU. 593 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 594 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 595 596 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 597 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 598 setOperationAction(ISD::MULHU, VT, Expand); 599 setOperationAction(ISD::MULHS, VT, Expand); 600 } 601 602 setOperationAction(ISD::SMIN, VT, Legal); 603 setOperationAction(ISD::SMAX, VT, Legal); 604 setOperationAction(ISD::UMIN, VT, Legal); 605 setOperationAction(ISD::UMAX, VT, Legal); 606 607 setOperationAction(ISD::ROTL, VT, Expand); 608 setOperationAction(ISD::ROTR, VT, Expand); 609 610 setOperationAction(ISD::CTTZ, VT, Expand); 611 setOperationAction(ISD::CTLZ, VT, Expand); 612 setOperationAction(ISD::CTPOP, VT, Expand); 613 614 setOperationAction(ISD::BSWAP, VT, Expand); 615 616 // Custom-lower extensions and truncations from/to mask types. 617 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 618 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 619 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 620 621 // RVV has native int->float & float->int conversions where the 622 // element type sizes are within one power-of-two of each other. Any 623 // wider distances between type sizes have to be lowered as sequences 624 // which progressively narrow the gap in stages. 625 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 626 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 627 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 628 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 629 630 setOperationAction(ISD::SADDSAT, VT, Legal); 631 setOperationAction(ISD::UADDSAT, VT, Legal); 632 setOperationAction(ISD::SSUBSAT, VT, Legal); 633 setOperationAction(ISD::USUBSAT, VT, Legal); 634 635 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 636 // nodes which truncate by one power of two at a time. 637 setOperationAction(ISD::TRUNCATE, VT, Custom); 638 639 // Custom-lower insert/extract operations to simplify patterns. 640 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 641 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 642 643 // Custom-lower reduction operations to set up the corresponding custom 644 // nodes' operands. 645 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 646 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 647 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 648 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 649 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 650 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 651 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 652 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 653 654 for (unsigned VPOpc : IntegerVPOps) 655 setOperationAction(VPOpc, VT, Custom); 656 657 setOperationAction(ISD::LOAD, VT, Custom); 658 setOperationAction(ISD::STORE, VT, Custom); 659 660 setOperationAction(ISD::MLOAD, VT, Custom); 661 setOperationAction(ISD::MSTORE, VT, Custom); 662 setOperationAction(ISD::MGATHER, VT, Custom); 663 setOperationAction(ISD::MSCATTER, VT, Custom); 664 665 setOperationAction(ISD::VP_LOAD, VT, Custom); 666 setOperationAction(ISD::VP_STORE, VT, Custom); 667 setOperationAction(ISD::VP_GATHER, VT, Custom); 668 setOperationAction(ISD::VP_SCATTER, VT, Custom); 669 670 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 671 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 672 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 673 674 setOperationAction(ISD::SELECT, VT, Custom); 675 setOperationAction(ISD::SELECT_CC, VT, Expand); 676 677 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 678 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 679 680 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 681 setTruncStoreAction(VT, OtherVT, Expand); 682 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 683 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 684 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 685 } 686 687 // Splice 688 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 689 690 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 691 // type that can represent the value exactly. 692 if (VT.getVectorElementType() != MVT::i64) { 693 MVT FloatEltVT = 694 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 695 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 696 if (isTypeLegal(FloatVT)) { 697 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 698 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 699 } 700 } 701 } 702 703 // Expand various CCs to best match the RVV ISA, which natively supports UNE 704 // but no other unordered comparisons, and supports all ordered comparisons 705 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 706 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 707 // and we pattern-match those back to the "original", swapping operands once 708 // more. This way we catch both operations and both "vf" and "fv" forms with 709 // fewer patterns. 710 static const ISD::CondCode VFPCCToExpand[] = { 711 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 712 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 713 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 714 }; 715 716 // Sets common operation actions on RVV floating-point vector types. 717 const auto SetCommonVFPActions = [&](MVT VT) { 718 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 719 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 720 // sizes are within one power-of-two of each other. Therefore conversions 721 // between vXf16 and vXf64 must be lowered as sequences which convert via 722 // vXf32. 723 setOperationAction(ISD::FP_ROUND, VT, Custom); 724 setOperationAction(ISD::FP_EXTEND, VT, Custom); 725 // Custom-lower insert/extract operations to simplify patterns. 726 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 727 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 728 // Expand various condition codes (explained above). 729 for (auto CC : VFPCCToExpand) 730 setCondCodeAction(CC, VT, Expand); 731 732 setOperationAction(ISD::FMINNUM, VT, Legal); 733 setOperationAction(ISD::FMAXNUM, VT, Legal); 734 735 setOperationAction(ISD::FTRUNC, VT, Custom); 736 setOperationAction(ISD::FCEIL, VT, Custom); 737 setOperationAction(ISD::FFLOOR, VT, Custom); 738 setOperationAction(ISD::FROUND, VT, Custom); 739 740 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 741 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 742 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 743 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 744 745 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 746 747 setOperationAction(ISD::LOAD, VT, Custom); 748 setOperationAction(ISD::STORE, VT, Custom); 749 750 setOperationAction(ISD::MLOAD, VT, Custom); 751 setOperationAction(ISD::MSTORE, VT, Custom); 752 setOperationAction(ISD::MGATHER, VT, Custom); 753 setOperationAction(ISD::MSCATTER, VT, Custom); 754 755 setOperationAction(ISD::VP_LOAD, VT, Custom); 756 setOperationAction(ISD::VP_STORE, VT, Custom); 757 setOperationAction(ISD::VP_GATHER, VT, Custom); 758 setOperationAction(ISD::VP_SCATTER, VT, Custom); 759 760 setOperationAction(ISD::SELECT, VT, Custom); 761 setOperationAction(ISD::SELECT_CC, VT, Expand); 762 763 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 764 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 765 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 766 767 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 768 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 769 770 for (unsigned VPOpc : FloatingPointVPOps) 771 setOperationAction(VPOpc, VT, Custom); 772 }; 773 774 // Sets common extload/truncstore actions on RVV floating-point vector 775 // types. 776 const auto SetCommonVFPExtLoadTruncStoreActions = 777 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 778 for (auto SmallVT : SmallerVTs) { 779 setTruncStoreAction(VT, SmallVT, Expand); 780 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 781 } 782 }; 783 784 if (Subtarget.hasVInstructionsF16()) 785 for (MVT VT : F16VecVTs) 786 SetCommonVFPActions(VT); 787 788 for (MVT VT : F32VecVTs) { 789 if (Subtarget.hasVInstructionsF32()) 790 SetCommonVFPActions(VT); 791 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 792 } 793 794 for (MVT VT : F64VecVTs) { 795 if (Subtarget.hasVInstructionsF64()) 796 SetCommonVFPActions(VT); 797 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 798 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 799 } 800 801 if (Subtarget.useRVVForFixedLengthVectors()) { 802 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 803 if (!useRVVForFixedLengthVectorVT(VT)) 804 continue; 805 806 // By default everything must be expanded. 807 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 808 setOperationAction(Op, VT, Expand); 809 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 810 setTruncStoreAction(VT, OtherVT, Expand); 811 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 812 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 813 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 814 } 815 816 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 817 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 818 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 819 820 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 821 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 822 823 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 824 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 825 826 setOperationAction(ISD::LOAD, VT, Custom); 827 setOperationAction(ISD::STORE, VT, Custom); 828 829 setOperationAction(ISD::SETCC, VT, Custom); 830 831 setOperationAction(ISD::SELECT, VT, Custom); 832 833 setOperationAction(ISD::TRUNCATE, VT, Custom); 834 835 setOperationAction(ISD::BITCAST, VT, Custom); 836 837 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 838 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 839 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 840 841 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 842 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 843 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 844 845 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 846 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 847 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 848 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 849 850 // Operations below are different for between masks and other vectors. 851 if (VT.getVectorElementType() == MVT::i1) { 852 setOperationAction(ISD::VP_AND, VT, Custom); 853 setOperationAction(ISD::VP_OR, VT, Custom); 854 setOperationAction(ISD::VP_XOR, VT, Custom); 855 setOperationAction(ISD::AND, VT, Custom); 856 setOperationAction(ISD::OR, VT, Custom); 857 setOperationAction(ISD::XOR, VT, Custom); 858 859 setOperationAction(ISD::VP_FPTOSI, VT, Custom); 860 setOperationAction(ISD::VP_FPTOUI, VT, Custom); 861 setOperationAction(ISD::VP_SETCC, VT, Custom); 862 continue; 863 } 864 865 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 866 // it before type legalization for i64 vectors on RV32. It will then be 867 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 868 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 869 // improvements first. 870 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 871 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 872 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 873 } 874 875 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 876 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 877 878 setOperationAction(ISD::MLOAD, VT, Custom); 879 setOperationAction(ISD::MSTORE, VT, Custom); 880 setOperationAction(ISD::MGATHER, VT, Custom); 881 setOperationAction(ISD::MSCATTER, VT, Custom); 882 883 setOperationAction(ISD::VP_LOAD, VT, Custom); 884 setOperationAction(ISD::VP_STORE, VT, Custom); 885 setOperationAction(ISD::VP_GATHER, VT, Custom); 886 setOperationAction(ISD::VP_SCATTER, VT, Custom); 887 888 setOperationAction(ISD::ADD, VT, Custom); 889 setOperationAction(ISD::MUL, VT, Custom); 890 setOperationAction(ISD::SUB, VT, Custom); 891 setOperationAction(ISD::AND, VT, Custom); 892 setOperationAction(ISD::OR, VT, Custom); 893 setOperationAction(ISD::XOR, VT, Custom); 894 setOperationAction(ISD::SDIV, VT, Custom); 895 setOperationAction(ISD::SREM, VT, Custom); 896 setOperationAction(ISD::UDIV, VT, Custom); 897 setOperationAction(ISD::UREM, VT, Custom); 898 setOperationAction(ISD::SHL, VT, Custom); 899 setOperationAction(ISD::SRA, VT, Custom); 900 setOperationAction(ISD::SRL, VT, Custom); 901 902 setOperationAction(ISD::SMIN, VT, Custom); 903 setOperationAction(ISD::SMAX, VT, Custom); 904 setOperationAction(ISD::UMIN, VT, Custom); 905 setOperationAction(ISD::UMAX, VT, Custom); 906 setOperationAction(ISD::ABS, VT, Custom); 907 908 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 909 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 910 setOperationAction(ISD::MULHS, VT, Custom); 911 setOperationAction(ISD::MULHU, VT, Custom); 912 } 913 914 setOperationAction(ISD::SADDSAT, VT, Custom); 915 setOperationAction(ISD::UADDSAT, VT, Custom); 916 setOperationAction(ISD::SSUBSAT, VT, Custom); 917 setOperationAction(ISD::USUBSAT, VT, Custom); 918 919 setOperationAction(ISD::VSELECT, VT, Custom); 920 setOperationAction(ISD::SELECT_CC, VT, Expand); 921 922 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 923 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 924 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 925 926 // Custom-lower reduction operations to set up the corresponding custom 927 // nodes' operands. 928 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 929 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 930 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 931 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 932 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 933 934 for (unsigned VPOpc : IntegerVPOps) 935 setOperationAction(VPOpc, VT, Custom); 936 937 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 938 // type that can represent the value exactly. 939 if (VT.getVectorElementType() != MVT::i64) { 940 MVT FloatEltVT = 941 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 942 EVT FloatVT = 943 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 944 if (isTypeLegal(FloatVT)) { 945 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 946 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 947 } 948 } 949 } 950 951 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 952 if (!useRVVForFixedLengthVectorVT(VT)) 953 continue; 954 955 // By default everything must be expanded. 956 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 957 setOperationAction(Op, VT, Expand); 958 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 959 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 960 setTruncStoreAction(VT, OtherVT, Expand); 961 } 962 963 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 964 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 965 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 966 967 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 968 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 969 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 970 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 971 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 972 973 setOperationAction(ISD::LOAD, VT, Custom); 974 setOperationAction(ISD::STORE, VT, Custom); 975 setOperationAction(ISD::MLOAD, VT, Custom); 976 setOperationAction(ISD::MSTORE, VT, Custom); 977 setOperationAction(ISD::MGATHER, VT, Custom); 978 setOperationAction(ISD::MSCATTER, VT, Custom); 979 980 setOperationAction(ISD::VP_LOAD, VT, Custom); 981 setOperationAction(ISD::VP_STORE, VT, Custom); 982 setOperationAction(ISD::VP_GATHER, VT, Custom); 983 setOperationAction(ISD::VP_SCATTER, VT, Custom); 984 985 setOperationAction(ISD::FADD, VT, Custom); 986 setOperationAction(ISD::FSUB, VT, Custom); 987 setOperationAction(ISD::FMUL, VT, Custom); 988 setOperationAction(ISD::FDIV, VT, Custom); 989 setOperationAction(ISD::FNEG, VT, Custom); 990 setOperationAction(ISD::FABS, VT, Custom); 991 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 992 setOperationAction(ISD::FSQRT, VT, Custom); 993 setOperationAction(ISD::FMA, VT, Custom); 994 setOperationAction(ISD::FMINNUM, VT, Custom); 995 setOperationAction(ISD::FMAXNUM, VT, Custom); 996 997 setOperationAction(ISD::FP_ROUND, VT, Custom); 998 setOperationAction(ISD::FP_EXTEND, VT, Custom); 999 1000 setOperationAction(ISD::FTRUNC, VT, Custom); 1001 setOperationAction(ISD::FCEIL, VT, Custom); 1002 setOperationAction(ISD::FFLOOR, VT, Custom); 1003 setOperationAction(ISD::FROUND, VT, Custom); 1004 1005 for (auto CC : VFPCCToExpand) 1006 setCondCodeAction(CC, VT, Expand); 1007 1008 setOperationAction(ISD::VSELECT, VT, Custom); 1009 setOperationAction(ISD::SELECT, VT, Custom); 1010 setOperationAction(ISD::SELECT_CC, VT, Expand); 1011 1012 setOperationAction(ISD::BITCAST, VT, Custom); 1013 1014 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1015 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1016 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1017 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1018 1019 for (unsigned VPOpc : FloatingPointVPOps) 1020 setOperationAction(VPOpc, VT, Custom); 1021 } 1022 1023 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1024 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1025 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1026 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1027 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1028 if (Subtarget.hasStdExtZfh()) 1029 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1030 if (Subtarget.hasStdExtF()) 1031 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1032 if (Subtarget.hasStdExtD()) 1033 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1034 } 1035 } 1036 1037 // Function alignments. 1038 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1039 setMinFunctionAlignment(FunctionAlignment); 1040 setPrefFunctionAlignment(FunctionAlignment); 1041 1042 setMinimumJumpTableEntries(5); 1043 1044 // Jumps are expensive, compared to logic 1045 setJumpIsExpensive(); 1046 1047 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 1048 ISD::OR, ISD::XOR}); 1049 1050 if (Subtarget.hasStdExtZbp()) 1051 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 1052 if (Subtarget.hasStdExtZbkb()) 1053 setTargetDAGCombine(ISD::BITREVERSE); 1054 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 1055 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 1056 if (Subtarget.hasStdExtF()) 1057 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 1058 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 1059 if (Subtarget.hasVInstructions()) 1060 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 1061 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 1062 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 1063 1064 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1065 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1066 } 1067 1068 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1069 LLVMContext &Context, 1070 EVT VT) const { 1071 if (!VT.isVector()) 1072 return getPointerTy(DL); 1073 if (Subtarget.hasVInstructions() && 1074 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1075 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1076 return VT.changeVectorElementTypeToInteger(); 1077 } 1078 1079 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1080 return Subtarget.getXLenVT(); 1081 } 1082 1083 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1084 const CallInst &I, 1085 MachineFunction &MF, 1086 unsigned Intrinsic) const { 1087 auto &DL = I.getModule()->getDataLayout(); 1088 switch (Intrinsic) { 1089 default: 1090 return false; 1091 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1092 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1093 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1094 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1095 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1096 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1097 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1098 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1099 case Intrinsic::riscv_masked_cmpxchg_i32: 1100 Info.opc = ISD::INTRINSIC_W_CHAIN; 1101 Info.memVT = MVT::i32; 1102 Info.ptrVal = I.getArgOperand(0); 1103 Info.offset = 0; 1104 Info.align = Align(4); 1105 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1106 MachineMemOperand::MOVolatile; 1107 return true; 1108 case Intrinsic::riscv_masked_strided_load: 1109 Info.opc = ISD::INTRINSIC_W_CHAIN; 1110 Info.ptrVal = I.getArgOperand(1); 1111 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1112 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1113 Info.size = MemoryLocation::UnknownSize; 1114 Info.flags |= MachineMemOperand::MOLoad; 1115 return true; 1116 case Intrinsic::riscv_masked_strided_store: 1117 Info.opc = ISD::INTRINSIC_VOID; 1118 Info.ptrVal = I.getArgOperand(1); 1119 Info.memVT = 1120 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1121 Info.align = Align( 1122 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1123 8); 1124 Info.size = MemoryLocation::UnknownSize; 1125 Info.flags |= MachineMemOperand::MOStore; 1126 return true; 1127 case Intrinsic::riscv_seg2_load: 1128 case Intrinsic::riscv_seg3_load: 1129 case Intrinsic::riscv_seg4_load: 1130 case Intrinsic::riscv_seg5_load: 1131 case Intrinsic::riscv_seg6_load: 1132 case Intrinsic::riscv_seg7_load: 1133 case Intrinsic::riscv_seg8_load: 1134 Info.opc = ISD::INTRINSIC_W_CHAIN; 1135 Info.ptrVal = I.getArgOperand(0); 1136 Info.memVT = 1137 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1138 Info.align = 1139 Align(DL.getTypeSizeInBits( 1140 I.getType()->getStructElementType(0)->getScalarType()) / 1141 8); 1142 Info.size = MemoryLocation::UnknownSize; 1143 Info.flags |= MachineMemOperand::MOLoad; 1144 return true; 1145 } 1146 } 1147 1148 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1149 const AddrMode &AM, Type *Ty, 1150 unsigned AS, 1151 Instruction *I) const { 1152 // No global is ever allowed as a base. 1153 if (AM.BaseGV) 1154 return false; 1155 1156 // Require a 12-bit signed offset. 1157 if (!isInt<12>(AM.BaseOffs)) 1158 return false; 1159 1160 switch (AM.Scale) { 1161 case 0: // "r+i" or just "i", depending on HasBaseReg. 1162 break; 1163 case 1: 1164 if (!AM.HasBaseReg) // allow "r+i". 1165 break; 1166 return false; // disallow "r+r" or "r+r+i". 1167 default: 1168 return false; 1169 } 1170 1171 return true; 1172 } 1173 1174 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1175 return isInt<12>(Imm); 1176 } 1177 1178 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1179 return isInt<12>(Imm); 1180 } 1181 1182 // On RV32, 64-bit integers are split into their high and low parts and held 1183 // in two different registers, so the trunc is free since the low register can 1184 // just be used. 1185 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1186 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1187 return false; 1188 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1189 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1190 return (SrcBits == 64 && DestBits == 32); 1191 } 1192 1193 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1194 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1195 !SrcVT.isInteger() || !DstVT.isInteger()) 1196 return false; 1197 unsigned SrcBits = SrcVT.getSizeInBits(); 1198 unsigned DestBits = DstVT.getSizeInBits(); 1199 return (SrcBits == 64 && DestBits == 32); 1200 } 1201 1202 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1203 // Zexts are free if they can be combined with a load. 1204 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1205 // poorly with type legalization of compares preferring sext. 1206 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1207 EVT MemVT = LD->getMemoryVT(); 1208 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1209 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1210 LD->getExtensionType() == ISD::ZEXTLOAD)) 1211 return true; 1212 } 1213 1214 return TargetLowering::isZExtFree(Val, VT2); 1215 } 1216 1217 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1218 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1219 } 1220 1221 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1222 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1223 } 1224 1225 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1226 return Subtarget.hasStdExtZbb(); 1227 } 1228 1229 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1230 return Subtarget.hasStdExtZbb(); 1231 } 1232 1233 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1234 EVT VT = Y.getValueType(); 1235 1236 // FIXME: Support vectors once we have tests. 1237 if (VT.isVector()) 1238 return false; 1239 1240 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1241 Subtarget.hasStdExtZbkb()) && 1242 !isa<ConstantSDNode>(Y); 1243 } 1244 1245 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1246 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1247 auto *C = dyn_cast<ConstantSDNode>(Y); 1248 return C && C->getAPIntValue().ule(10); 1249 } 1250 1251 /// Check if sinking \p I's operands to I's basic block is profitable, because 1252 /// the operands can be folded into a target instruction, e.g. 1253 /// splats of scalars can fold into vector instructions. 1254 bool RISCVTargetLowering::shouldSinkOperands( 1255 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1256 using namespace llvm::PatternMatch; 1257 1258 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1259 return false; 1260 1261 auto IsSinker = [&](Instruction *I, int Operand) { 1262 switch (I->getOpcode()) { 1263 case Instruction::Add: 1264 case Instruction::Sub: 1265 case Instruction::Mul: 1266 case Instruction::And: 1267 case Instruction::Or: 1268 case Instruction::Xor: 1269 case Instruction::FAdd: 1270 case Instruction::FSub: 1271 case Instruction::FMul: 1272 case Instruction::FDiv: 1273 case Instruction::ICmp: 1274 case Instruction::FCmp: 1275 return true; 1276 case Instruction::Shl: 1277 case Instruction::LShr: 1278 case Instruction::AShr: 1279 case Instruction::UDiv: 1280 case Instruction::SDiv: 1281 case Instruction::URem: 1282 case Instruction::SRem: 1283 return Operand == 1; 1284 case Instruction::Call: 1285 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1286 switch (II->getIntrinsicID()) { 1287 case Intrinsic::fma: 1288 case Intrinsic::vp_fma: 1289 return Operand == 0 || Operand == 1; 1290 // FIXME: Our patterns can only match vx/vf instructions when the splat 1291 // it on the RHS, because TableGen doesn't recognize our VP operations 1292 // as commutative. 1293 case Intrinsic::vp_add: 1294 case Intrinsic::vp_mul: 1295 case Intrinsic::vp_and: 1296 case Intrinsic::vp_or: 1297 case Intrinsic::vp_xor: 1298 case Intrinsic::vp_fadd: 1299 case Intrinsic::vp_fmul: 1300 case Intrinsic::vp_shl: 1301 case Intrinsic::vp_lshr: 1302 case Intrinsic::vp_ashr: 1303 case Intrinsic::vp_udiv: 1304 case Intrinsic::vp_sdiv: 1305 case Intrinsic::vp_urem: 1306 case Intrinsic::vp_srem: 1307 return Operand == 1; 1308 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1309 // explicit patterns for both LHS and RHS (as 'vr' versions). 1310 case Intrinsic::vp_sub: 1311 case Intrinsic::vp_fsub: 1312 case Intrinsic::vp_fdiv: 1313 return Operand == 0 || Operand == 1; 1314 default: 1315 return false; 1316 } 1317 } 1318 return false; 1319 default: 1320 return false; 1321 } 1322 }; 1323 1324 for (auto OpIdx : enumerate(I->operands())) { 1325 if (!IsSinker(I, OpIdx.index())) 1326 continue; 1327 1328 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1329 // Make sure we are not already sinking this operand 1330 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1331 continue; 1332 1333 // We are looking for a splat that can be sunk. 1334 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1335 m_Undef(), m_ZeroMask()))) 1336 continue; 1337 1338 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1339 // and vector registers 1340 for (Use &U : Op->uses()) { 1341 Instruction *Insn = cast<Instruction>(U.getUser()); 1342 if (!IsSinker(Insn, U.getOperandNo())) 1343 return false; 1344 } 1345 1346 Ops.push_back(&Op->getOperandUse(0)); 1347 Ops.push_back(&OpIdx.value()); 1348 } 1349 return true; 1350 } 1351 1352 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1353 bool ForCodeSize) const { 1354 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1355 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1356 return false; 1357 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1358 return false; 1359 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1360 return false; 1361 return Imm.isZero(); 1362 } 1363 1364 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1365 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1366 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1367 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1368 } 1369 1370 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1371 CallingConv::ID CC, 1372 EVT VT) const { 1373 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1374 // We might still end up using a GPR but that will be decided based on ABI. 1375 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1376 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1377 return MVT::f32; 1378 1379 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1380 } 1381 1382 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1383 CallingConv::ID CC, 1384 EVT VT) const { 1385 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1386 // We might still end up using a GPR but that will be decided based on ABI. 1387 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1388 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1389 return 1; 1390 1391 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1392 } 1393 1394 // Changes the condition code and swaps operands if necessary, so the SetCC 1395 // operation matches one of the comparisons supported directly by branches 1396 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1397 // with 1/-1. 1398 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1399 ISD::CondCode &CC, SelectionDAG &DAG) { 1400 // Convert X > -1 to X >= 0. 1401 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1402 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1403 CC = ISD::SETGE; 1404 return; 1405 } 1406 // Convert X < 1 to 0 >= X. 1407 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1408 RHS = LHS; 1409 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1410 CC = ISD::SETGE; 1411 return; 1412 } 1413 1414 switch (CC) { 1415 default: 1416 break; 1417 case ISD::SETGT: 1418 case ISD::SETLE: 1419 case ISD::SETUGT: 1420 case ISD::SETULE: 1421 CC = ISD::getSetCCSwappedOperands(CC); 1422 std::swap(LHS, RHS); 1423 break; 1424 } 1425 } 1426 1427 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1428 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1429 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1430 if (VT.getVectorElementType() == MVT::i1) 1431 KnownSize *= 8; 1432 1433 switch (KnownSize) { 1434 default: 1435 llvm_unreachable("Invalid LMUL."); 1436 case 8: 1437 return RISCVII::VLMUL::LMUL_F8; 1438 case 16: 1439 return RISCVII::VLMUL::LMUL_F4; 1440 case 32: 1441 return RISCVII::VLMUL::LMUL_F2; 1442 case 64: 1443 return RISCVII::VLMUL::LMUL_1; 1444 case 128: 1445 return RISCVII::VLMUL::LMUL_2; 1446 case 256: 1447 return RISCVII::VLMUL::LMUL_4; 1448 case 512: 1449 return RISCVII::VLMUL::LMUL_8; 1450 } 1451 } 1452 1453 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1454 switch (LMul) { 1455 default: 1456 llvm_unreachable("Invalid LMUL."); 1457 case RISCVII::VLMUL::LMUL_F8: 1458 case RISCVII::VLMUL::LMUL_F4: 1459 case RISCVII::VLMUL::LMUL_F2: 1460 case RISCVII::VLMUL::LMUL_1: 1461 return RISCV::VRRegClassID; 1462 case RISCVII::VLMUL::LMUL_2: 1463 return RISCV::VRM2RegClassID; 1464 case RISCVII::VLMUL::LMUL_4: 1465 return RISCV::VRM4RegClassID; 1466 case RISCVII::VLMUL::LMUL_8: 1467 return RISCV::VRM8RegClassID; 1468 } 1469 } 1470 1471 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1472 RISCVII::VLMUL LMUL = getLMUL(VT); 1473 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1474 LMUL == RISCVII::VLMUL::LMUL_F4 || 1475 LMUL == RISCVII::VLMUL::LMUL_F2 || 1476 LMUL == RISCVII::VLMUL::LMUL_1) { 1477 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1478 "Unexpected subreg numbering"); 1479 return RISCV::sub_vrm1_0 + Index; 1480 } 1481 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1482 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1483 "Unexpected subreg numbering"); 1484 return RISCV::sub_vrm2_0 + Index; 1485 } 1486 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1487 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1488 "Unexpected subreg numbering"); 1489 return RISCV::sub_vrm4_0 + Index; 1490 } 1491 llvm_unreachable("Invalid vector type."); 1492 } 1493 1494 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1495 if (VT.getVectorElementType() == MVT::i1) 1496 return RISCV::VRRegClassID; 1497 return getRegClassIDForLMUL(getLMUL(VT)); 1498 } 1499 1500 // Attempt to decompose a subvector insert/extract between VecVT and 1501 // SubVecVT via subregister indices. Returns the subregister index that 1502 // can perform the subvector insert/extract with the given element index, as 1503 // well as the index corresponding to any leftover subvectors that must be 1504 // further inserted/extracted within the register class for SubVecVT. 1505 std::pair<unsigned, unsigned> 1506 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1507 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1508 const RISCVRegisterInfo *TRI) { 1509 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1510 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1511 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1512 "Register classes not ordered"); 1513 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1514 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1515 // Try to compose a subregister index that takes us from the incoming 1516 // LMUL>1 register class down to the outgoing one. At each step we half 1517 // the LMUL: 1518 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1519 // Note that this is not guaranteed to find a subregister index, such as 1520 // when we are extracting from one VR type to another. 1521 unsigned SubRegIdx = RISCV::NoSubRegister; 1522 for (const unsigned RCID : 1523 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1524 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1525 VecVT = VecVT.getHalfNumVectorElementsVT(); 1526 bool IsHi = 1527 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1528 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1529 getSubregIndexByMVT(VecVT, IsHi)); 1530 if (IsHi) 1531 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1532 } 1533 return {SubRegIdx, InsertExtractIdx}; 1534 } 1535 1536 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1537 // stores for those types. 1538 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1539 return !Subtarget.useRVVForFixedLengthVectors() || 1540 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1541 } 1542 1543 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1544 if (ScalarTy->isPointerTy()) 1545 return true; 1546 1547 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1548 ScalarTy->isIntegerTy(32)) 1549 return true; 1550 1551 if (ScalarTy->isIntegerTy(64)) 1552 return Subtarget.hasVInstructionsI64(); 1553 1554 if (ScalarTy->isHalfTy()) 1555 return Subtarget.hasVInstructionsF16(); 1556 if (ScalarTy->isFloatTy()) 1557 return Subtarget.hasVInstructionsF32(); 1558 if (ScalarTy->isDoubleTy()) 1559 return Subtarget.hasVInstructionsF64(); 1560 1561 return false; 1562 } 1563 1564 static SDValue getVLOperand(SDValue Op) { 1565 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1566 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1567 "Unexpected opcode"); 1568 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1569 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1570 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1571 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1572 if (!II) 1573 return SDValue(); 1574 return Op.getOperand(II->VLOperand + 1 + HasChain); 1575 } 1576 1577 static bool useRVVForFixedLengthVectorVT(MVT VT, 1578 const RISCVSubtarget &Subtarget) { 1579 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1580 if (!Subtarget.useRVVForFixedLengthVectors()) 1581 return false; 1582 1583 // We only support a set of vector types with a consistent maximum fixed size 1584 // across all supported vector element types to avoid legalization issues. 1585 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1586 // fixed-length vector type we support is 1024 bytes. 1587 if (VT.getFixedSizeInBits() > 1024 * 8) 1588 return false; 1589 1590 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1591 1592 MVT EltVT = VT.getVectorElementType(); 1593 1594 // Don't use RVV for vectors we cannot scalarize if required. 1595 switch (EltVT.SimpleTy) { 1596 // i1 is supported but has different rules. 1597 default: 1598 return false; 1599 case MVT::i1: 1600 // Masks can only use a single register. 1601 if (VT.getVectorNumElements() > MinVLen) 1602 return false; 1603 MinVLen /= 8; 1604 break; 1605 case MVT::i8: 1606 case MVT::i16: 1607 case MVT::i32: 1608 break; 1609 case MVT::i64: 1610 if (!Subtarget.hasVInstructionsI64()) 1611 return false; 1612 break; 1613 case MVT::f16: 1614 if (!Subtarget.hasVInstructionsF16()) 1615 return false; 1616 break; 1617 case MVT::f32: 1618 if (!Subtarget.hasVInstructionsF32()) 1619 return false; 1620 break; 1621 case MVT::f64: 1622 if (!Subtarget.hasVInstructionsF64()) 1623 return false; 1624 break; 1625 } 1626 1627 // Reject elements larger than ELEN. 1628 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1629 return false; 1630 1631 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1632 // Don't use RVV for types that don't fit. 1633 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1634 return false; 1635 1636 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1637 // the base fixed length RVV support in place. 1638 if (!VT.isPow2VectorType()) 1639 return false; 1640 1641 return true; 1642 } 1643 1644 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1645 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1646 } 1647 1648 // Return the largest legal scalable vector type that matches VT's element type. 1649 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1650 const RISCVSubtarget &Subtarget) { 1651 // This may be called before legal types are setup. 1652 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1653 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1654 "Expected legal fixed length vector!"); 1655 1656 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1657 unsigned MaxELen = Subtarget.getELEN(); 1658 1659 MVT EltVT = VT.getVectorElementType(); 1660 switch (EltVT.SimpleTy) { 1661 default: 1662 llvm_unreachable("unexpected element type for RVV container"); 1663 case MVT::i1: 1664 case MVT::i8: 1665 case MVT::i16: 1666 case MVT::i32: 1667 case MVT::i64: 1668 case MVT::f16: 1669 case MVT::f32: 1670 case MVT::f64: { 1671 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1672 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1673 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1674 unsigned NumElts = 1675 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1676 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1677 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1678 return MVT::getScalableVectorVT(EltVT, NumElts); 1679 } 1680 } 1681 } 1682 1683 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1684 const RISCVSubtarget &Subtarget) { 1685 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1686 Subtarget); 1687 } 1688 1689 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1690 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1691 } 1692 1693 // Grow V to consume an entire RVV register. 1694 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1695 const RISCVSubtarget &Subtarget) { 1696 assert(VT.isScalableVector() && 1697 "Expected to convert into a scalable vector!"); 1698 assert(V.getValueType().isFixedLengthVector() && 1699 "Expected a fixed length vector operand!"); 1700 SDLoc DL(V); 1701 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1702 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1703 } 1704 1705 // Shrink V so it's just big enough to maintain a VT's worth of data. 1706 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1707 const RISCVSubtarget &Subtarget) { 1708 assert(VT.isFixedLengthVector() && 1709 "Expected to convert into a fixed length vector!"); 1710 assert(V.getValueType().isScalableVector() && 1711 "Expected a scalable vector operand!"); 1712 SDLoc DL(V); 1713 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1714 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1715 } 1716 1717 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1718 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1719 // the vector type that it is contained in. 1720 static std::pair<SDValue, SDValue> 1721 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1722 const RISCVSubtarget &Subtarget) { 1723 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1724 MVT XLenVT = Subtarget.getXLenVT(); 1725 SDValue VL = VecVT.isFixedLengthVector() 1726 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1727 : DAG.getRegister(RISCV::X0, XLenVT); 1728 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1729 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1730 return {Mask, VL}; 1731 } 1732 1733 // As above but assuming the given type is a scalable vector type. 1734 static std::pair<SDValue, SDValue> 1735 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1736 const RISCVSubtarget &Subtarget) { 1737 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1738 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1739 } 1740 1741 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1742 // of either is (currently) supported. This can get us into an infinite loop 1743 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1744 // as a ..., etc. 1745 // Until either (or both) of these can reliably lower any node, reporting that 1746 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1747 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1748 // which is not desirable. 1749 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1750 EVT VT, unsigned DefinedValues) const { 1751 return false; 1752 } 1753 1754 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1755 const RISCVSubtarget &Subtarget) { 1756 // RISCV FP-to-int conversions saturate to the destination register size, but 1757 // don't produce 0 for nan. We can use a conversion instruction and fix the 1758 // nan case with a compare and a select. 1759 SDValue Src = Op.getOperand(0); 1760 1761 EVT DstVT = Op.getValueType(); 1762 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1763 1764 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1765 unsigned Opc; 1766 if (SatVT == DstVT) 1767 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1768 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1769 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1770 else 1771 return SDValue(); 1772 // FIXME: Support other SatVTs by clamping before or after the conversion. 1773 1774 SDLoc DL(Op); 1775 SDValue FpToInt = DAG.getNode( 1776 Opc, DL, DstVT, Src, 1777 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1778 1779 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1780 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1781 } 1782 1783 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1784 // and back. Taking care to avoid converting values that are nan or already 1785 // correct. 1786 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1787 // have FRM dependencies modeled yet. 1788 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1789 MVT VT = Op.getSimpleValueType(); 1790 assert(VT.isVector() && "Unexpected type"); 1791 1792 SDLoc DL(Op); 1793 1794 // Freeze the source since we are increasing the number of uses. 1795 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1796 1797 // Truncate to integer and convert back to FP. 1798 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1799 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1800 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1801 1802 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1803 1804 if (Op.getOpcode() == ISD::FCEIL) { 1805 // If the truncated value is the greater than or equal to the original 1806 // value, we've computed the ceil. Otherwise, we went the wrong way and 1807 // need to increase by 1. 1808 // FIXME: This should use a masked operation. Handle here or in isel? 1809 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1810 DAG.getConstantFP(1.0, DL, VT)); 1811 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1812 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1813 } else if (Op.getOpcode() == ISD::FFLOOR) { 1814 // If the truncated value is the less than or equal to the original value, 1815 // we've computed the floor. Otherwise, we went the wrong way and need to 1816 // decrease by 1. 1817 // FIXME: This should use a masked operation. Handle here or in isel? 1818 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1819 DAG.getConstantFP(1.0, DL, VT)); 1820 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1821 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1822 } 1823 1824 // Restore the original sign so that -0.0 is preserved. 1825 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1826 1827 // Determine the largest integer that can be represented exactly. This and 1828 // values larger than it don't have any fractional bits so don't need to 1829 // be converted. 1830 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1831 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1832 APFloat MaxVal = APFloat(FltSem); 1833 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1834 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1835 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1836 1837 // If abs(Src) was larger than MaxVal or nan, keep it. 1838 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1839 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1840 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1841 } 1842 1843 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1844 // This mode isn't supported in vector hardware on RISCV. But as long as we 1845 // aren't compiling with trapping math, we can emulate this with 1846 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1847 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1848 // dependencies modeled yet. 1849 // FIXME: Use masked operations to avoid final merge. 1850 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1851 MVT VT = Op.getSimpleValueType(); 1852 assert(VT.isVector() && "Unexpected type"); 1853 1854 SDLoc DL(Op); 1855 1856 // Freeze the source since we are increasing the number of uses. 1857 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1858 1859 // We do the conversion on the absolute value and fix the sign at the end. 1860 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1861 1862 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1863 bool Ignored; 1864 APFloat Point5Pred = APFloat(0.5f); 1865 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1866 Point5Pred.next(/*nextDown*/ true); 1867 1868 // Add the adjustment. 1869 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1870 DAG.getConstantFP(Point5Pred, DL, VT)); 1871 1872 // Truncate to integer and convert back to fp. 1873 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1874 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1875 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1876 1877 // Restore the original sign. 1878 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1879 1880 // Determine the largest integer that can be represented exactly. This and 1881 // values larger than it don't have any fractional bits so don't need to 1882 // be converted. 1883 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1884 APFloat MaxVal = APFloat(FltSem); 1885 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1886 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1887 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1888 1889 // If abs(Src) was larger than MaxVal or nan, keep it. 1890 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1891 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1892 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1893 } 1894 1895 struct VIDSequence { 1896 int64_t StepNumerator; 1897 unsigned StepDenominator; 1898 int64_t Addend; 1899 }; 1900 1901 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1902 // to the (non-zero) step S and start value X. This can be then lowered as the 1903 // RVV sequence (VID * S) + X, for example. 1904 // The step S is represented as an integer numerator divided by a positive 1905 // denominator. Note that the implementation currently only identifies 1906 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1907 // cannot detect 2/3, for example. 1908 // Note that this method will also match potentially unappealing index 1909 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1910 // determine whether this is worth generating code for. 1911 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1912 unsigned NumElts = Op.getNumOperands(); 1913 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1914 if (!Op.getValueType().isInteger()) 1915 return None; 1916 1917 Optional<unsigned> SeqStepDenom; 1918 Optional<int64_t> SeqStepNum, SeqAddend; 1919 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1920 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1921 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1922 // Assume undef elements match the sequence; we just have to be careful 1923 // when interpolating across them. 1924 if (Op.getOperand(Idx).isUndef()) 1925 continue; 1926 // The BUILD_VECTOR must be all constants. 1927 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1928 return None; 1929 1930 uint64_t Val = Op.getConstantOperandVal(Idx) & 1931 maskTrailingOnes<uint64_t>(EltSizeInBits); 1932 1933 if (PrevElt) { 1934 // Calculate the step since the last non-undef element, and ensure 1935 // it's consistent across the entire sequence. 1936 unsigned IdxDiff = Idx - PrevElt->second; 1937 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1938 1939 // A zero-value value difference means that we're somewhere in the middle 1940 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1941 // step change before evaluating the sequence. 1942 if (ValDiff != 0) { 1943 int64_t Remainder = ValDiff % IdxDiff; 1944 // Normalize the step if it's greater than 1. 1945 if (Remainder != ValDiff) { 1946 // The difference must cleanly divide the element span. 1947 if (Remainder != 0) 1948 return None; 1949 ValDiff /= IdxDiff; 1950 IdxDiff = 1; 1951 } 1952 1953 if (!SeqStepNum) 1954 SeqStepNum = ValDiff; 1955 else if (ValDiff != SeqStepNum) 1956 return None; 1957 1958 if (!SeqStepDenom) 1959 SeqStepDenom = IdxDiff; 1960 else if (IdxDiff != *SeqStepDenom) 1961 return None; 1962 } 1963 } 1964 1965 // Record and/or check any addend. 1966 if (SeqStepNum && SeqStepDenom) { 1967 uint64_t ExpectedVal = 1968 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1969 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1970 if (!SeqAddend) 1971 SeqAddend = Addend; 1972 else if (SeqAddend != Addend) 1973 return None; 1974 } 1975 1976 // Record this non-undef element for later. 1977 if (!PrevElt || PrevElt->first != Val) 1978 PrevElt = std::make_pair(Val, Idx); 1979 } 1980 // We need to have logged both a step and an addend for this to count as 1981 // a legal index sequence. 1982 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1983 return None; 1984 1985 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1986 } 1987 1988 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1989 // and lower it as a VRGATHER_VX_VL from the source vector. 1990 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1991 SelectionDAG &DAG, 1992 const RISCVSubtarget &Subtarget) { 1993 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1994 return SDValue(); 1995 SDValue Vec = SplatVal.getOperand(0); 1996 // Only perform this optimization on vectors of the same size for simplicity. 1997 if (Vec.getValueType() != VT) 1998 return SDValue(); 1999 SDValue Idx = SplatVal.getOperand(1); 2000 // The index must be a legal type. 2001 if (Idx.getValueType() != Subtarget.getXLenVT()) 2002 return SDValue(); 2003 2004 MVT ContainerVT = VT; 2005 if (VT.isFixedLengthVector()) { 2006 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2007 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2008 } 2009 2010 SDValue Mask, VL; 2011 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2012 2013 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2014 Idx, Mask, VL); 2015 2016 if (!VT.isFixedLengthVector()) 2017 return Gather; 2018 2019 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2020 } 2021 2022 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2023 const RISCVSubtarget &Subtarget) { 2024 MVT VT = Op.getSimpleValueType(); 2025 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2026 2027 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2028 2029 SDLoc DL(Op); 2030 SDValue Mask, VL; 2031 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2032 2033 MVT XLenVT = Subtarget.getXLenVT(); 2034 unsigned NumElts = Op.getNumOperands(); 2035 2036 if (VT.getVectorElementType() == MVT::i1) { 2037 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2038 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2039 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2040 } 2041 2042 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2043 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2044 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2045 } 2046 2047 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2048 // scalar integer chunks whose bit-width depends on the number of mask 2049 // bits and XLEN. 2050 // First, determine the most appropriate scalar integer type to use. This 2051 // is at most XLenVT, but may be shrunk to a smaller vector element type 2052 // according to the size of the final vector - use i8 chunks rather than 2053 // XLenVT if we're producing a v8i1. This results in more consistent 2054 // codegen across RV32 and RV64. 2055 unsigned NumViaIntegerBits = 2056 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2057 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 2058 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2059 // If we have to use more than one INSERT_VECTOR_ELT then this 2060 // optimization is likely to increase code size; avoid peforming it in 2061 // such a case. We can use a load from a constant pool in this case. 2062 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2063 return SDValue(); 2064 // Now we can create our integer vector type. Note that it may be larger 2065 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2066 MVT IntegerViaVecVT = 2067 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2068 divideCeil(NumElts, NumViaIntegerBits)); 2069 2070 uint64_t Bits = 0; 2071 unsigned BitPos = 0, IntegerEltIdx = 0; 2072 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2073 2074 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2075 // Once we accumulate enough bits to fill our scalar type, insert into 2076 // our vector and clear our accumulated data. 2077 if (I != 0 && I % NumViaIntegerBits == 0) { 2078 if (NumViaIntegerBits <= 32) 2079 Bits = SignExtend64(Bits, 32); 2080 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2081 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2082 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2083 Bits = 0; 2084 BitPos = 0; 2085 IntegerEltIdx++; 2086 } 2087 SDValue V = Op.getOperand(I); 2088 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2089 Bits |= ((uint64_t)BitValue << BitPos); 2090 } 2091 2092 // Insert the (remaining) scalar value into position in our integer 2093 // vector type. 2094 if (NumViaIntegerBits <= 32) 2095 Bits = SignExtend64(Bits, 32); 2096 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2097 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2098 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2099 2100 if (NumElts < NumViaIntegerBits) { 2101 // If we're producing a smaller vector than our minimum legal integer 2102 // type, bitcast to the equivalent (known-legal) mask type, and extract 2103 // our final mask. 2104 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2105 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2106 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2107 DAG.getConstant(0, DL, XLenVT)); 2108 } else { 2109 // Else we must have produced an integer type with the same size as the 2110 // mask type; bitcast for the final result. 2111 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2112 Vec = DAG.getBitcast(VT, Vec); 2113 } 2114 2115 return Vec; 2116 } 2117 2118 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2119 // vector type, we have a legal equivalently-sized i8 type, so we can use 2120 // that. 2121 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2122 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2123 2124 SDValue WideVec; 2125 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2126 // For a splat, perform a scalar truncate before creating the wider 2127 // vector. 2128 assert(Splat.getValueType() == XLenVT && 2129 "Unexpected type for i1 splat value"); 2130 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2131 DAG.getConstant(1, DL, XLenVT)); 2132 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2133 } else { 2134 SmallVector<SDValue, 8> Ops(Op->op_values()); 2135 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2136 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2137 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2138 } 2139 2140 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2141 } 2142 2143 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2144 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2145 return Gather; 2146 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2147 : RISCVISD::VMV_V_X_VL; 2148 Splat = 2149 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2150 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2151 } 2152 2153 // Try and match index sequences, which we can lower to the vid instruction 2154 // with optional modifications. An all-undef vector is matched by 2155 // getSplatValue, above. 2156 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2157 int64_t StepNumerator = SimpleVID->StepNumerator; 2158 unsigned StepDenominator = SimpleVID->StepDenominator; 2159 int64_t Addend = SimpleVID->Addend; 2160 2161 assert(StepNumerator != 0 && "Invalid step"); 2162 bool Negate = false; 2163 int64_t SplatStepVal = StepNumerator; 2164 unsigned StepOpcode = ISD::MUL; 2165 if (StepNumerator != 1) { 2166 if (isPowerOf2_64(std::abs(StepNumerator))) { 2167 Negate = StepNumerator < 0; 2168 StepOpcode = ISD::SHL; 2169 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2170 } 2171 } 2172 2173 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2174 // threshold since it's the immediate value many RVV instructions accept. 2175 // There is no vmul.vi instruction so ensure multiply constant can fit in 2176 // a single addi instruction. 2177 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2178 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2179 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2180 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2181 // Convert right out of the scalable type so we can use standard ISD 2182 // nodes for the rest of the computation. If we used scalable types with 2183 // these, we'd lose the fixed-length vector info and generate worse 2184 // vsetvli code. 2185 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2186 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2187 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2188 SDValue SplatStep = DAG.getSplatBuildVector( 2189 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2190 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2191 } 2192 if (StepDenominator != 1) { 2193 SDValue SplatStep = DAG.getSplatBuildVector( 2194 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2195 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2196 } 2197 if (Addend != 0 || Negate) { 2198 SDValue SplatAddend = DAG.getSplatBuildVector( 2199 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2200 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2201 } 2202 return VID; 2203 } 2204 } 2205 2206 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2207 // when re-interpreted as a vector with a larger element type. For example, 2208 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2209 // could be instead splat as 2210 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2211 // TODO: This optimization could also work on non-constant splats, but it 2212 // would require bit-manipulation instructions to construct the splat value. 2213 SmallVector<SDValue> Sequence; 2214 unsigned EltBitSize = VT.getScalarSizeInBits(); 2215 const auto *BV = cast<BuildVectorSDNode>(Op); 2216 if (VT.isInteger() && EltBitSize < 64 && 2217 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2218 BV->getRepeatedSequence(Sequence) && 2219 (Sequence.size() * EltBitSize) <= 64) { 2220 unsigned SeqLen = Sequence.size(); 2221 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2222 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2223 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2224 ViaIntVT == MVT::i64) && 2225 "Unexpected sequence type"); 2226 2227 unsigned EltIdx = 0; 2228 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2229 uint64_t SplatValue = 0; 2230 // Construct the amalgamated value which can be splatted as this larger 2231 // vector type. 2232 for (const auto &SeqV : Sequence) { 2233 if (!SeqV.isUndef()) 2234 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2235 << (EltIdx * EltBitSize)); 2236 EltIdx++; 2237 } 2238 2239 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2240 // achieve better constant materializion. 2241 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2242 SplatValue = SignExtend64(SplatValue, 32); 2243 2244 // Since we can't introduce illegal i64 types at this stage, we can only 2245 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2246 // way we can use RVV instructions to splat. 2247 assert((ViaIntVT.bitsLE(XLenVT) || 2248 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2249 "Unexpected bitcast sequence"); 2250 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2251 SDValue ViaVL = 2252 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2253 MVT ViaContainerVT = 2254 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2255 SDValue Splat = 2256 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2257 DAG.getUNDEF(ViaContainerVT), 2258 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2259 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2260 return DAG.getBitcast(VT, Splat); 2261 } 2262 } 2263 2264 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2265 // which constitute a large proportion of the elements. In such cases we can 2266 // splat a vector with the dominant element and make up the shortfall with 2267 // INSERT_VECTOR_ELTs. 2268 // Note that this includes vectors of 2 elements by association. The 2269 // upper-most element is the "dominant" one, allowing us to use a splat to 2270 // "insert" the upper element, and an insert of the lower element at position 2271 // 0, which improves codegen. 2272 SDValue DominantValue; 2273 unsigned MostCommonCount = 0; 2274 DenseMap<SDValue, unsigned> ValueCounts; 2275 unsigned NumUndefElts = 2276 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2277 2278 // Track the number of scalar loads we know we'd be inserting, estimated as 2279 // any non-zero floating-point constant. Other kinds of element are either 2280 // already in registers or are materialized on demand. The threshold at which 2281 // a vector load is more desirable than several scalar materializion and 2282 // vector-insertion instructions is not known. 2283 unsigned NumScalarLoads = 0; 2284 2285 for (SDValue V : Op->op_values()) { 2286 if (V.isUndef()) 2287 continue; 2288 2289 ValueCounts.insert(std::make_pair(V, 0)); 2290 unsigned &Count = ValueCounts[V]; 2291 2292 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2293 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2294 2295 // Is this value dominant? In case of a tie, prefer the highest element as 2296 // it's cheaper to insert near the beginning of a vector than it is at the 2297 // end. 2298 if (++Count >= MostCommonCount) { 2299 DominantValue = V; 2300 MostCommonCount = Count; 2301 } 2302 } 2303 2304 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2305 unsigned NumDefElts = NumElts - NumUndefElts; 2306 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2307 2308 // Don't perform this optimization when optimizing for size, since 2309 // materializing elements and inserting them tends to cause code bloat. 2310 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2311 ((MostCommonCount > DominantValueCountThreshold) || 2312 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2313 // Start by splatting the most common element. 2314 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2315 2316 DenseSet<SDValue> Processed{DominantValue}; 2317 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2318 for (const auto &OpIdx : enumerate(Op->ops())) { 2319 const SDValue &V = OpIdx.value(); 2320 if (V.isUndef() || !Processed.insert(V).second) 2321 continue; 2322 if (ValueCounts[V] == 1) { 2323 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2324 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2325 } else { 2326 // Blend in all instances of this value using a VSELECT, using a 2327 // mask where each bit signals whether that element is the one 2328 // we're after. 2329 SmallVector<SDValue> Ops; 2330 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2331 return DAG.getConstant(V == V1, DL, XLenVT); 2332 }); 2333 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2334 DAG.getBuildVector(SelMaskTy, DL, Ops), 2335 DAG.getSplatBuildVector(VT, DL, V), Vec); 2336 } 2337 } 2338 2339 return Vec; 2340 } 2341 2342 return SDValue(); 2343 } 2344 2345 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2346 SDValue Lo, SDValue Hi, SDValue VL, 2347 SelectionDAG &DAG) { 2348 if (!Passthru) 2349 Passthru = DAG.getUNDEF(VT); 2350 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2351 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2352 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2353 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2354 // node in order to try and match RVV vector/scalar instructions. 2355 if ((LoC >> 31) == HiC) 2356 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2357 2358 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2359 // vmv.v.x whose EEW = 32 to lower it. 2360 auto *Const = dyn_cast<ConstantSDNode>(VL); 2361 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2362 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2363 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2364 // access the subtarget here now. 2365 auto InterVec = DAG.getNode( 2366 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2367 DAG.getRegister(RISCV::X0, MVT::i32)); 2368 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2369 } 2370 } 2371 2372 // Fall back to a stack store and stride x0 vector load. 2373 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2374 Hi, VL); 2375 } 2376 2377 // Called by type legalization to handle splat of i64 on RV32. 2378 // FIXME: We can optimize this when the type has sign or zero bits in one 2379 // of the halves. 2380 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2381 SDValue Scalar, SDValue VL, 2382 SelectionDAG &DAG) { 2383 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2384 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2385 DAG.getConstant(0, DL, MVT::i32)); 2386 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2387 DAG.getConstant(1, DL, MVT::i32)); 2388 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2389 } 2390 2391 // This function lowers a splat of a scalar operand Splat with the vector 2392 // length VL. It ensures the final sequence is type legal, which is useful when 2393 // lowering a splat after type legalization. 2394 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2395 MVT VT, SDLoc DL, SelectionDAG &DAG, 2396 const RISCVSubtarget &Subtarget) { 2397 bool HasPassthru = Passthru && !Passthru.isUndef(); 2398 if (!HasPassthru && !Passthru) 2399 Passthru = DAG.getUNDEF(VT); 2400 if (VT.isFloatingPoint()) { 2401 // If VL is 1, we could use vfmv.s.f. 2402 if (isOneConstant(VL)) 2403 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2404 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2405 } 2406 2407 MVT XLenVT = Subtarget.getXLenVT(); 2408 2409 // Simplest case is that the operand needs to be promoted to XLenVT. 2410 if (Scalar.getValueType().bitsLE(XLenVT)) { 2411 // If the operand is a constant, sign extend to increase our chances 2412 // of being able to use a .vi instruction. ANY_EXTEND would become a 2413 // a zero extend and the simm5 check in isel would fail. 2414 // FIXME: Should we ignore the upper bits in isel instead? 2415 unsigned ExtOpc = 2416 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2417 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2418 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2419 // If VL is 1 and the scalar value won't benefit from immediate, we could 2420 // use vmv.s.x. 2421 if (isOneConstant(VL) && 2422 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2423 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2424 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2425 } 2426 2427 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2428 "Unexpected scalar for splat lowering!"); 2429 2430 if (isOneConstant(VL) && isNullConstant(Scalar)) 2431 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2432 DAG.getConstant(0, DL, XLenVT), VL); 2433 2434 // Otherwise use the more complicated splatting algorithm. 2435 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2436 } 2437 2438 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2439 const RISCVSubtarget &Subtarget) { 2440 // We need to be able to widen elements to the next larger integer type. 2441 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2442 return false; 2443 2444 int Size = Mask.size(); 2445 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2446 2447 int Srcs[] = {-1, -1}; 2448 for (int i = 0; i != Size; ++i) { 2449 // Ignore undef elements. 2450 if (Mask[i] < 0) 2451 continue; 2452 2453 // Is this an even or odd element. 2454 int Pol = i % 2; 2455 2456 // Ensure we consistently use the same source for this element polarity. 2457 int Src = Mask[i] / Size; 2458 if (Srcs[Pol] < 0) 2459 Srcs[Pol] = Src; 2460 if (Srcs[Pol] != Src) 2461 return false; 2462 2463 // Make sure the element within the source is appropriate for this element 2464 // in the destination. 2465 int Elt = Mask[i] % Size; 2466 if (Elt != i / 2) 2467 return false; 2468 } 2469 2470 // We need to find a source for each polarity and they can't be the same. 2471 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2472 return false; 2473 2474 // Swap the sources if the second source was in the even polarity. 2475 SwapSources = Srcs[0] > Srcs[1]; 2476 2477 return true; 2478 } 2479 2480 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2481 /// and then extract the original number of elements from the rotated result. 2482 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2483 /// returned rotation amount is for a rotate right, where elements move from 2484 /// higher elements to lower elements. \p LoSrc indicates the first source 2485 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2486 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2487 /// 0 or 1 if a rotation is found. 2488 /// 2489 /// NOTE: We talk about rotate to the right which matches how bit shift and 2490 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2491 /// and the table below write vectors with the lowest elements on the left. 2492 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2493 int Size = Mask.size(); 2494 2495 // We need to detect various ways of spelling a rotation: 2496 // [11, 12, 13, 14, 15, 0, 1, 2] 2497 // [-1, 12, 13, 14, -1, -1, 1, -1] 2498 // [-1, -1, -1, -1, -1, -1, 1, 2] 2499 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2500 // [-1, 4, 5, 6, -1, -1, 9, -1] 2501 // [-1, 4, 5, 6, -1, -1, -1, -1] 2502 int Rotation = 0; 2503 LoSrc = -1; 2504 HiSrc = -1; 2505 for (int i = 0; i != Size; ++i) { 2506 int M = Mask[i]; 2507 if (M < 0) 2508 continue; 2509 2510 // Determine where a rotate vector would have started. 2511 int StartIdx = i - (M % Size); 2512 // The identity rotation isn't interesting, stop. 2513 if (StartIdx == 0) 2514 return -1; 2515 2516 // If we found the tail of a vector the rotation must be the missing 2517 // front. If we found the head of a vector, it must be how much of the 2518 // head. 2519 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2520 2521 if (Rotation == 0) 2522 Rotation = CandidateRotation; 2523 else if (Rotation != CandidateRotation) 2524 // The rotations don't match, so we can't match this mask. 2525 return -1; 2526 2527 // Compute which value this mask is pointing at. 2528 int MaskSrc = M < Size ? 0 : 1; 2529 2530 // Compute which of the two target values this index should be assigned to. 2531 // This reflects whether the high elements are remaining or the low elemnts 2532 // are remaining. 2533 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2534 2535 // Either set up this value if we've not encountered it before, or check 2536 // that it remains consistent. 2537 if (TargetSrc < 0) 2538 TargetSrc = MaskSrc; 2539 else if (TargetSrc != MaskSrc) 2540 // This may be a rotation, but it pulls from the inputs in some 2541 // unsupported interleaving. 2542 return -1; 2543 } 2544 2545 // Check that we successfully analyzed the mask, and normalize the results. 2546 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2547 assert((LoSrc >= 0 || HiSrc >= 0) && 2548 "Failed to find a rotated input vector!"); 2549 2550 return Rotation; 2551 } 2552 2553 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2554 const RISCVSubtarget &Subtarget) { 2555 SDValue V1 = Op.getOperand(0); 2556 SDValue V2 = Op.getOperand(1); 2557 SDLoc DL(Op); 2558 MVT XLenVT = Subtarget.getXLenVT(); 2559 MVT VT = Op.getSimpleValueType(); 2560 unsigned NumElts = VT.getVectorNumElements(); 2561 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2562 2563 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2564 2565 SDValue TrueMask, VL; 2566 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2567 2568 if (SVN->isSplat()) { 2569 const int Lane = SVN->getSplatIndex(); 2570 if (Lane >= 0) { 2571 MVT SVT = VT.getVectorElementType(); 2572 2573 // Turn splatted vector load into a strided load with an X0 stride. 2574 SDValue V = V1; 2575 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2576 // with undef. 2577 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2578 int Offset = Lane; 2579 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2580 int OpElements = 2581 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2582 V = V.getOperand(Offset / OpElements); 2583 Offset %= OpElements; 2584 } 2585 2586 // We need to ensure the load isn't atomic or volatile. 2587 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2588 auto *Ld = cast<LoadSDNode>(V); 2589 Offset *= SVT.getStoreSize(); 2590 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2591 TypeSize::Fixed(Offset), DL); 2592 2593 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2594 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2595 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2596 SDValue IntID = 2597 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2598 SDValue Ops[] = {Ld->getChain(), 2599 IntID, 2600 DAG.getUNDEF(ContainerVT), 2601 NewAddr, 2602 DAG.getRegister(RISCV::X0, XLenVT), 2603 VL}; 2604 SDValue NewLoad = DAG.getMemIntrinsicNode( 2605 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2606 DAG.getMachineFunction().getMachineMemOperand( 2607 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2608 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2609 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2610 } 2611 2612 // Otherwise use a scalar load and splat. This will give the best 2613 // opportunity to fold a splat into the operation. ISel can turn it into 2614 // the x0 strided load if we aren't able to fold away the select. 2615 if (SVT.isFloatingPoint()) 2616 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2617 Ld->getPointerInfo().getWithOffset(Offset), 2618 Ld->getOriginalAlign(), 2619 Ld->getMemOperand()->getFlags()); 2620 else 2621 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2622 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2623 Ld->getOriginalAlign(), 2624 Ld->getMemOperand()->getFlags()); 2625 DAG.makeEquivalentMemoryOrdering(Ld, V); 2626 2627 unsigned Opc = 2628 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2629 SDValue Splat = 2630 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2631 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2632 } 2633 2634 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2635 assert(Lane < (int)NumElts && "Unexpected lane!"); 2636 SDValue Gather = 2637 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2638 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2639 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2640 } 2641 } 2642 2643 ArrayRef<int> Mask = SVN->getMask(); 2644 2645 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2646 // be undef which can be handled with a single SLIDEDOWN/UP. 2647 int LoSrc, HiSrc; 2648 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2649 if (Rotation > 0) { 2650 SDValue LoV, HiV; 2651 if (LoSrc >= 0) { 2652 LoV = LoSrc == 0 ? V1 : V2; 2653 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2654 } 2655 if (HiSrc >= 0) { 2656 HiV = HiSrc == 0 ? V1 : V2; 2657 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2658 } 2659 2660 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2661 // to slide LoV up by (NumElts - Rotation). 2662 unsigned InvRotate = NumElts - Rotation; 2663 2664 SDValue Res = DAG.getUNDEF(ContainerVT); 2665 if (HiV) { 2666 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2667 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2668 // causes multiple vsetvlis in some test cases such as lowering 2669 // reduce.mul 2670 SDValue DownVL = VL; 2671 if (LoV) 2672 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2673 Res = 2674 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2675 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2676 } 2677 if (LoV) 2678 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2679 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2680 2681 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2682 } 2683 2684 // Detect an interleave shuffle and lower to 2685 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2686 bool SwapSources; 2687 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2688 // Swap sources if needed. 2689 if (SwapSources) 2690 std::swap(V1, V2); 2691 2692 // Extract the lower half of the vectors. 2693 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2694 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2695 DAG.getConstant(0, DL, XLenVT)); 2696 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2697 DAG.getConstant(0, DL, XLenVT)); 2698 2699 // Double the element width and halve the number of elements in an int type. 2700 unsigned EltBits = VT.getScalarSizeInBits(); 2701 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2702 MVT WideIntVT = 2703 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2704 // Convert this to a scalable vector. We need to base this on the 2705 // destination size to ensure there's always a type with a smaller LMUL. 2706 MVT WideIntContainerVT = 2707 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2708 2709 // Convert sources to scalable vectors with the same element count as the 2710 // larger type. 2711 MVT HalfContainerVT = MVT::getVectorVT( 2712 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2713 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2714 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2715 2716 // Cast sources to integer. 2717 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2718 MVT IntHalfVT = 2719 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2720 V1 = DAG.getBitcast(IntHalfVT, V1); 2721 V2 = DAG.getBitcast(IntHalfVT, V2); 2722 2723 // Freeze V2 since we use it twice and we need to be sure that the add and 2724 // multiply see the same value. 2725 V2 = DAG.getFreeze(V2); 2726 2727 // Recreate TrueMask using the widened type's element count. 2728 MVT MaskVT = 2729 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2730 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2731 2732 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2733 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2734 V2, TrueMask, VL); 2735 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2736 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2737 DAG.getUNDEF(IntHalfVT), 2738 DAG.getAllOnesConstant(DL, XLenVT)); 2739 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2740 V2, Multiplier, TrueMask, VL); 2741 // Add the new copies to our previous addition giving us 2^eltbits copies of 2742 // V2. This is equivalent to shifting V2 left by eltbits. This should 2743 // combine with the vwmulu.vv above to form vwmaccu.vv. 2744 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2745 TrueMask, VL); 2746 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2747 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2748 // vector VT. 2749 ContainerVT = 2750 MVT::getVectorVT(VT.getVectorElementType(), 2751 WideIntContainerVT.getVectorElementCount() * 2); 2752 Add = DAG.getBitcast(ContainerVT, Add); 2753 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2754 } 2755 2756 // Detect shuffles which can be re-expressed as vector selects; these are 2757 // shuffles in which each element in the destination is taken from an element 2758 // at the corresponding index in either source vectors. 2759 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2760 int MaskIndex = MaskIdx.value(); 2761 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2762 }); 2763 2764 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2765 2766 SmallVector<SDValue> MaskVals; 2767 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2768 // merged with a second vrgather. 2769 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2770 2771 // By default we preserve the original operand order, and use a mask to 2772 // select LHS as true and RHS as false. However, since RVV vector selects may 2773 // feature splats but only on the LHS, we may choose to invert our mask and 2774 // instead select between RHS and LHS. 2775 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2776 bool InvertMask = IsSelect == SwapOps; 2777 2778 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2779 // half. 2780 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2781 2782 // Now construct the mask that will be used by the vselect or blended 2783 // vrgather operation. For vrgathers, construct the appropriate indices into 2784 // each vector. 2785 for (int MaskIndex : Mask) { 2786 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2787 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2788 if (!IsSelect) { 2789 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2790 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2791 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2792 : DAG.getUNDEF(XLenVT)); 2793 GatherIndicesRHS.push_back( 2794 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2795 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2796 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2797 ++LHSIndexCounts[MaskIndex]; 2798 if (!IsLHSOrUndefIndex) 2799 ++RHSIndexCounts[MaskIndex - NumElts]; 2800 } 2801 } 2802 2803 if (SwapOps) { 2804 std::swap(V1, V2); 2805 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2806 } 2807 2808 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2809 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2810 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2811 2812 if (IsSelect) 2813 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2814 2815 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2816 // On such a large vector we're unable to use i8 as the index type. 2817 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2818 // may involve vector splitting if we're already at LMUL=8, or our 2819 // user-supplied maximum fixed-length LMUL. 2820 return SDValue(); 2821 } 2822 2823 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2824 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2825 MVT IndexVT = VT.changeTypeToInteger(); 2826 // Since we can't introduce illegal index types at this stage, use i16 and 2827 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2828 // than XLenVT. 2829 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2830 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2831 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2832 } 2833 2834 MVT IndexContainerVT = 2835 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2836 2837 SDValue Gather; 2838 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2839 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2840 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2841 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2842 Subtarget); 2843 } else { 2844 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2845 // If only one index is used, we can use a "splat" vrgather. 2846 // TODO: We can splat the most-common index and fix-up any stragglers, if 2847 // that's beneficial. 2848 if (LHSIndexCounts.size() == 1) { 2849 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2850 Gather = 2851 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2852 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2853 } else { 2854 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2855 LHSIndices = 2856 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2857 2858 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2859 TrueMask, VL); 2860 } 2861 } 2862 2863 // If a second vector operand is used by this shuffle, blend it in with an 2864 // additional vrgather. 2865 if (!V2.isUndef()) { 2866 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2867 // If only one index is used, we can use a "splat" vrgather. 2868 // TODO: We can splat the most-common index and fix-up any stragglers, if 2869 // that's beneficial. 2870 if (RHSIndexCounts.size() == 1) { 2871 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2872 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2873 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2874 } else { 2875 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2876 RHSIndices = 2877 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2878 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2879 VL); 2880 } 2881 2882 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2883 SelectMask = 2884 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2885 2886 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2887 Gather, VL); 2888 } 2889 2890 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2891 } 2892 2893 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2894 // Support splats for any type. These should type legalize well. 2895 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2896 return true; 2897 2898 // Only support legal VTs for other shuffles for now. 2899 if (!isTypeLegal(VT)) 2900 return false; 2901 2902 MVT SVT = VT.getSimpleVT(); 2903 2904 bool SwapSources; 2905 int LoSrc, HiSrc; 2906 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2907 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2908 } 2909 2910 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2911 SDLoc DL, SelectionDAG &DAG, 2912 const RISCVSubtarget &Subtarget) { 2913 if (VT.isScalableVector()) 2914 return DAG.getFPExtendOrRound(Op, DL, VT); 2915 assert(VT.isFixedLengthVector() && 2916 "Unexpected value type for RVV FP extend/round lowering"); 2917 SDValue Mask, VL; 2918 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2919 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2920 ? RISCVISD::FP_EXTEND_VL 2921 : RISCVISD::FP_ROUND_VL; 2922 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2923 } 2924 2925 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2926 // the exponent. 2927 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2928 MVT VT = Op.getSimpleValueType(); 2929 unsigned EltSize = VT.getScalarSizeInBits(); 2930 SDValue Src = Op.getOperand(0); 2931 SDLoc DL(Op); 2932 2933 // We need a FP type that can represent the value. 2934 // TODO: Use f16 for i8 when possible? 2935 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2936 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2937 2938 // Legal types should have been checked in the RISCVTargetLowering 2939 // constructor. 2940 // TODO: Splitting may make sense in some cases. 2941 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2942 "Expected legal float type!"); 2943 2944 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2945 // The trailing zero count is equal to log2 of this single bit value. 2946 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2947 SDValue Neg = 2948 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2949 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2950 } 2951 2952 // We have a legal FP type, convert to it. 2953 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2954 // Bitcast to integer and shift the exponent to the LSB. 2955 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2956 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2957 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2958 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2959 DAG.getConstant(ShiftAmt, DL, IntVT)); 2960 // Truncate back to original type to allow vnsrl. 2961 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2962 // The exponent contains log2 of the value in biased form. 2963 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2964 2965 // For trailing zeros, we just need to subtract the bias. 2966 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2967 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2968 DAG.getConstant(ExponentBias, DL, VT)); 2969 2970 // For leading zeros, we need to remove the bias and convert from log2 to 2971 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2972 unsigned Adjust = ExponentBias + (EltSize - 1); 2973 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2974 } 2975 2976 // While RVV has alignment restrictions, we should always be able to load as a 2977 // legal equivalently-sized byte-typed vector instead. This method is 2978 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2979 // the load is already correctly-aligned, it returns SDValue(). 2980 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2981 SelectionDAG &DAG) const { 2982 auto *Load = cast<LoadSDNode>(Op); 2983 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2984 2985 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2986 Load->getMemoryVT(), 2987 *Load->getMemOperand())) 2988 return SDValue(); 2989 2990 SDLoc DL(Op); 2991 MVT VT = Op.getSimpleValueType(); 2992 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2993 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2994 "Unexpected unaligned RVV load type"); 2995 MVT NewVT = 2996 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2997 assert(NewVT.isValid() && 2998 "Expecting equally-sized RVV vector types to be legal"); 2999 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 3000 Load->getPointerInfo(), Load->getOriginalAlign(), 3001 Load->getMemOperand()->getFlags()); 3002 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 3003 } 3004 3005 // While RVV has alignment restrictions, we should always be able to store as a 3006 // legal equivalently-sized byte-typed vector instead. This method is 3007 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 3008 // returns SDValue() if the store is already correctly aligned. 3009 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 3010 SelectionDAG &DAG) const { 3011 auto *Store = cast<StoreSDNode>(Op); 3012 assert(Store && Store->getValue().getValueType().isVector() && 3013 "Expected vector store"); 3014 3015 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3016 Store->getMemoryVT(), 3017 *Store->getMemOperand())) 3018 return SDValue(); 3019 3020 SDLoc DL(Op); 3021 SDValue StoredVal = Store->getValue(); 3022 MVT VT = StoredVal.getSimpleValueType(); 3023 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3024 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3025 "Unexpected unaligned RVV store type"); 3026 MVT NewVT = 3027 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3028 assert(NewVT.isValid() && 3029 "Expecting equally-sized RVV vector types to be legal"); 3030 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3031 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3032 Store->getPointerInfo(), Store->getOriginalAlign(), 3033 Store->getMemOperand()->getFlags()); 3034 } 3035 3036 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3037 SelectionDAG &DAG) const { 3038 switch (Op.getOpcode()) { 3039 default: 3040 report_fatal_error("unimplemented operand"); 3041 case ISD::GlobalAddress: 3042 return lowerGlobalAddress(Op, DAG); 3043 case ISD::BlockAddress: 3044 return lowerBlockAddress(Op, DAG); 3045 case ISD::ConstantPool: 3046 return lowerConstantPool(Op, DAG); 3047 case ISD::JumpTable: 3048 return lowerJumpTable(Op, DAG); 3049 case ISD::GlobalTLSAddress: 3050 return lowerGlobalTLSAddress(Op, DAG); 3051 case ISD::SELECT: 3052 return lowerSELECT(Op, DAG); 3053 case ISD::BRCOND: 3054 return lowerBRCOND(Op, DAG); 3055 case ISD::VASTART: 3056 return lowerVASTART(Op, DAG); 3057 case ISD::FRAMEADDR: 3058 return lowerFRAMEADDR(Op, DAG); 3059 case ISD::RETURNADDR: 3060 return lowerRETURNADDR(Op, DAG); 3061 case ISD::SHL_PARTS: 3062 return lowerShiftLeftParts(Op, DAG); 3063 case ISD::SRA_PARTS: 3064 return lowerShiftRightParts(Op, DAG, true); 3065 case ISD::SRL_PARTS: 3066 return lowerShiftRightParts(Op, DAG, false); 3067 case ISD::BITCAST: { 3068 SDLoc DL(Op); 3069 EVT VT = Op.getValueType(); 3070 SDValue Op0 = Op.getOperand(0); 3071 EVT Op0VT = Op0.getValueType(); 3072 MVT XLenVT = Subtarget.getXLenVT(); 3073 if (VT.isFixedLengthVector()) { 3074 // We can handle fixed length vector bitcasts with a simple replacement 3075 // in isel. 3076 if (Op0VT.isFixedLengthVector()) 3077 return Op; 3078 // When bitcasting from scalar to fixed-length vector, insert the scalar 3079 // into a one-element vector of the result type, and perform a vector 3080 // bitcast. 3081 if (!Op0VT.isVector()) { 3082 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3083 if (!isTypeLegal(BVT)) 3084 return SDValue(); 3085 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3086 DAG.getUNDEF(BVT), Op0, 3087 DAG.getConstant(0, DL, XLenVT))); 3088 } 3089 return SDValue(); 3090 } 3091 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3092 // thus: bitcast the vector to a one-element vector type whose element type 3093 // is the same as the result type, and extract the first element. 3094 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3095 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3096 if (!isTypeLegal(BVT)) 3097 return SDValue(); 3098 SDValue BVec = DAG.getBitcast(BVT, Op0); 3099 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3100 DAG.getConstant(0, DL, XLenVT)); 3101 } 3102 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3103 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3104 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3105 return FPConv; 3106 } 3107 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3108 Subtarget.hasStdExtF()) { 3109 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3110 SDValue FPConv = 3111 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3112 return FPConv; 3113 } 3114 return SDValue(); 3115 } 3116 case ISD::INTRINSIC_WO_CHAIN: 3117 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3118 case ISD::INTRINSIC_W_CHAIN: 3119 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3120 case ISD::INTRINSIC_VOID: 3121 return LowerINTRINSIC_VOID(Op, DAG); 3122 case ISD::BSWAP: 3123 case ISD::BITREVERSE: { 3124 MVT VT = Op.getSimpleValueType(); 3125 SDLoc DL(Op); 3126 if (Subtarget.hasStdExtZbp()) { 3127 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3128 // Start with the maximum immediate value which is the bitwidth - 1. 3129 unsigned Imm = VT.getSizeInBits() - 1; 3130 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3131 if (Op.getOpcode() == ISD::BSWAP) 3132 Imm &= ~0x7U; 3133 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3134 DAG.getConstant(Imm, DL, VT)); 3135 } 3136 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3137 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3138 // Expand bitreverse to a bswap(rev8) followed by brev8. 3139 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3140 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3141 // as brev8 by an isel pattern. 3142 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3143 DAG.getConstant(7, DL, VT)); 3144 } 3145 case ISD::FSHL: 3146 case ISD::FSHR: { 3147 MVT VT = Op.getSimpleValueType(); 3148 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3149 SDLoc DL(Op); 3150 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3151 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3152 // accidentally setting the extra bit. 3153 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3154 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3155 DAG.getConstant(ShAmtWidth, DL, VT)); 3156 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3157 // instruction use different orders. fshl will return its first operand for 3158 // shift of zero, fshr will return its second operand. fsl and fsr both 3159 // return rs1 so the ISD nodes need to have different operand orders. 3160 // Shift amount is in rs2. 3161 SDValue Op0 = Op.getOperand(0); 3162 SDValue Op1 = Op.getOperand(1); 3163 unsigned Opc = RISCVISD::FSL; 3164 if (Op.getOpcode() == ISD::FSHR) { 3165 std::swap(Op0, Op1); 3166 Opc = RISCVISD::FSR; 3167 } 3168 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3169 } 3170 case ISD::TRUNCATE: { 3171 SDLoc DL(Op); 3172 MVT VT = Op.getSimpleValueType(); 3173 // Only custom-lower vector truncates 3174 if (!VT.isVector()) 3175 return Op; 3176 3177 // Truncates to mask types are handled differently 3178 if (VT.getVectorElementType() == MVT::i1) 3179 return lowerVectorMaskTrunc(Op, DAG); 3180 3181 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3182 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3183 // truncate by one power of two at a time. 3184 MVT DstEltVT = VT.getVectorElementType(); 3185 3186 SDValue Src = Op.getOperand(0); 3187 MVT SrcVT = Src.getSimpleValueType(); 3188 MVT SrcEltVT = SrcVT.getVectorElementType(); 3189 3190 assert(DstEltVT.bitsLT(SrcEltVT) && 3191 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3192 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3193 "Unexpected vector truncate lowering"); 3194 3195 MVT ContainerVT = SrcVT; 3196 if (SrcVT.isFixedLengthVector()) { 3197 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3198 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3199 } 3200 3201 SDValue Result = Src; 3202 SDValue Mask, VL; 3203 std::tie(Mask, VL) = 3204 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3205 LLVMContext &Context = *DAG.getContext(); 3206 const ElementCount Count = ContainerVT.getVectorElementCount(); 3207 do { 3208 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3209 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3210 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3211 Mask, VL); 3212 } while (SrcEltVT != DstEltVT); 3213 3214 if (SrcVT.isFixedLengthVector()) 3215 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3216 3217 return Result; 3218 } 3219 case ISD::ANY_EXTEND: 3220 case ISD::ZERO_EXTEND: 3221 if (Op.getOperand(0).getValueType().isVector() && 3222 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3223 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3224 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3225 case ISD::SIGN_EXTEND: 3226 if (Op.getOperand(0).getValueType().isVector() && 3227 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3228 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3229 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3230 case ISD::SPLAT_VECTOR_PARTS: 3231 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3232 case ISD::INSERT_VECTOR_ELT: 3233 return lowerINSERT_VECTOR_ELT(Op, DAG); 3234 case ISD::EXTRACT_VECTOR_ELT: 3235 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3236 case ISD::VSCALE: { 3237 MVT VT = Op.getSimpleValueType(); 3238 SDLoc DL(Op); 3239 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3240 // We define our scalable vector types for lmul=1 to use a 64 bit known 3241 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3242 // vscale as VLENB / 8. 3243 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3244 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3245 report_fatal_error("Support for VLEN==32 is incomplete."); 3246 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3247 // We assume VLENB is a multiple of 8. We manually choose the best shift 3248 // here because SimplifyDemandedBits isn't always able to simplify it. 3249 uint64_t Val = Op.getConstantOperandVal(0); 3250 if (isPowerOf2_64(Val)) { 3251 uint64_t Log2 = Log2_64(Val); 3252 if (Log2 < 3) 3253 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3254 DAG.getConstant(3 - Log2, DL, VT)); 3255 if (Log2 > 3) 3256 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3257 DAG.getConstant(Log2 - 3, DL, VT)); 3258 return VLENB; 3259 } 3260 // If the multiplier is a multiple of 8, scale it down to avoid needing 3261 // to shift the VLENB value. 3262 if ((Val % 8) == 0) 3263 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3264 DAG.getConstant(Val / 8, DL, VT)); 3265 } 3266 3267 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3268 DAG.getConstant(3, DL, VT)); 3269 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3270 } 3271 case ISD::FPOWI: { 3272 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3273 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3274 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3275 Op.getOperand(1).getValueType() == MVT::i32) { 3276 SDLoc DL(Op); 3277 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3278 SDValue Powi = 3279 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3280 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3281 DAG.getIntPtrConstant(0, DL)); 3282 } 3283 return SDValue(); 3284 } 3285 case ISD::FP_EXTEND: { 3286 // RVV can only do fp_extend to types double the size as the source. We 3287 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3288 // via f32. 3289 SDLoc DL(Op); 3290 MVT VT = Op.getSimpleValueType(); 3291 SDValue Src = Op.getOperand(0); 3292 MVT SrcVT = Src.getSimpleValueType(); 3293 3294 // Prepare any fixed-length vector operands. 3295 MVT ContainerVT = VT; 3296 if (SrcVT.isFixedLengthVector()) { 3297 ContainerVT = getContainerForFixedLengthVector(VT); 3298 MVT SrcContainerVT = 3299 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3300 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3301 } 3302 3303 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3304 SrcVT.getVectorElementType() != MVT::f16) { 3305 // For scalable vectors, we only need to close the gap between 3306 // vXf16->vXf64. 3307 if (!VT.isFixedLengthVector()) 3308 return Op; 3309 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3310 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3311 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3312 } 3313 3314 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3315 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3316 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3317 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3318 3319 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3320 DL, DAG, Subtarget); 3321 if (VT.isFixedLengthVector()) 3322 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3323 return Extend; 3324 } 3325 case ISD::FP_ROUND: { 3326 // RVV can only do fp_round to types half the size as the source. We 3327 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3328 // conversion instruction. 3329 SDLoc DL(Op); 3330 MVT VT = Op.getSimpleValueType(); 3331 SDValue Src = Op.getOperand(0); 3332 MVT SrcVT = Src.getSimpleValueType(); 3333 3334 // Prepare any fixed-length vector operands. 3335 MVT ContainerVT = VT; 3336 if (VT.isFixedLengthVector()) { 3337 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3338 ContainerVT = 3339 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3340 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3341 } 3342 3343 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3344 SrcVT.getVectorElementType() != MVT::f64) { 3345 // For scalable vectors, we only need to close the gap between 3346 // vXf64<->vXf16. 3347 if (!VT.isFixedLengthVector()) 3348 return Op; 3349 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3350 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3351 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3352 } 3353 3354 SDValue Mask, VL; 3355 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3356 3357 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3358 SDValue IntermediateRound = 3359 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3360 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3361 DL, DAG, Subtarget); 3362 3363 if (VT.isFixedLengthVector()) 3364 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3365 return Round; 3366 } 3367 case ISD::FP_TO_SINT: 3368 case ISD::FP_TO_UINT: 3369 case ISD::SINT_TO_FP: 3370 case ISD::UINT_TO_FP: { 3371 // RVV can only do fp<->int conversions to types half/double the size as 3372 // the source. We custom-lower any conversions that do two hops into 3373 // sequences. 3374 MVT VT = Op.getSimpleValueType(); 3375 if (!VT.isVector()) 3376 return Op; 3377 SDLoc DL(Op); 3378 SDValue Src = Op.getOperand(0); 3379 MVT EltVT = VT.getVectorElementType(); 3380 MVT SrcVT = Src.getSimpleValueType(); 3381 MVT SrcEltVT = SrcVT.getVectorElementType(); 3382 unsigned EltSize = EltVT.getSizeInBits(); 3383 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3384 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3385 "Unexpected vector element types"); 3386 3387 bool IsInt2FP = SrcEltVT.isInteger(); 3388 // Widening conversions 3389 if (EltSize > (2 * SrcEltSize)) { 3390 if (IsInt2FP) { 3391 // Do a regular integer sign/zero extension then convert to float. 3392 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3393 VT.getVectorElementCount()); 3394 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3395 ? ISD::ZERO_EXTEND 3396 : ISD::SIGN_EXTEND; 3397 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3398 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3399 } 3400 // FP2Int 3401 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3402 // Do one doubling fp_extend then complete the operation by converting 3403 // to int. 3404 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3405 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3406 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3407 } 3408 3409 // Narrowing conversions 3410 if (SrcEltSize > (2 * EltSize)) { 3411 if (IsInt2FP) { 3412 // One narrowing int_to_fp, then an fp_round. 3413 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3414 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3415 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3416 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3417 } 3418 // FP2Int 3419 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3420 // representable by the integer, the result is poison. 3421 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3422 VT.getVectorElementCount()); 3423 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3424 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3425 } 3426 3427 // Scalable vectors can exit here. Patterns will handle equally-sized 3428 // conversions halving/doubling ones. 3429 if (!VT.isFixedLengthVector()) 3430 return Op; 3431 3432 // For fixed-length vectors we lower to a custom "VL" node. 3433 unsigned RVVOpc = 0; 3434 switch (Op.getOpcode()) { 3435 default: 3436 llvm_unreachable("Impossible opcode"); 3437 case ISD::FP_TO_SINT: 3438 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3439 break; 3440 case ISD::FP_TO_UINT: 3441 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3442 break; 3443 case ISD::SINT_TO_FP: 3444 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3445 break; 3446 case ISD::UINT_TO_FP: 3447 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3448 break; 3449 } 3450 3451 MVT ContainerVT, SrcContainerVT; 3452 // Derive the reference container type from the larger vector type. 3453 if (SrcEltSize > EltSize) { 3454 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3455 ContainerVT = 3456 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3457 } else { 3458 ContainerVT = getContainerForFixedLengthVector(VT); 3459 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3460 } 3461 3462 SDValue Mask, VL; 3463 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3464 3465 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3466 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3467 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3468 } 3469 case ISD::FP_TO_SINT_SAT: 3470 case ISD::FP_TO_UINT_SAT: 3471 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3472 case ISD::FTRUNC: 3473 case ISD::FCEIL: 3474 case ISD::FFLOOR: 3475 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3476 case ISD::FROUND: 3477 return lowerFROUND(Op, DAG); 3478 case ISD::VECREDUCE_ADD: 3479 case ISD::VECREDUCE_UMAX: 3480 case ISD::VECREDUCE_SMAX: 3481 case ISD::VECREDUCE_UMIN: 3482 case ISD::VECREDUCE_SMIN: 3483 return lowerVECREDUCE(Op, DAG); 3484 case ISD::VECREDUCE_AND: 3485 case ISD::VECREDUCE_OR: 3486 case ISD::VECREDUCE_XOR: 3487 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3488 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3489 return lowerVECREDUCE(Op, DAG); 3490 case ISD::VECREDUCE_FADD: 3491 case ISD::VECREDUCE_SEQ_FADD: 3492 case ISD::VECREDUCE_FMIN: 3493 case ISD::VECREDUCE_FMAX: 3494 return lowerFPVECREDUCE(Op, DAG); 3495 case ISD::VP_REDUCE_ADD: 3496 case ISD::VP_REDUCE_UMAX: 3497 case ISD::VP_REDUCE_SMAX: 3498 case ISD::VP_REDUCE_UMIN: 3499 case ISD::VP_REDUCE_SMIN: 3500 case ISD::VP_REDUCE_FADD: 3501 case ISD::VP_REDUCE_SEQ_FADD: 3502 case ISD::VP_REDUCE_FMIN: 3503 case ISD::VP_REDUCE_FMAX: 3504 return lowerVPREDUCE(Op, DAG); 3505 case ISD::VP_REDUCE_AND: 3506 case ISD::VP_REDUCE_OR: 3507 case ISD::VP_REDUCE_XOR: 3508 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3509 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3510 return lowerVPREDUCE(Op, DAG); 3511 case ISD::INSERT_SUBVECTOR: 3512 return lowerINSERT_SUBVECTOR(Op, DAG); 3513 case ISD::EXTRACT_SUBVECTOR: 3514 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3515 case ISD::STEP_VECTOR: 3516 return lowerSTEP_VECTOR(Op, DAG); 3517 case ISD::VECTOR_REVERSE: 3518 return lowerVECTOR_REVERSE(Op, DAG); 3519 case ISD::VECTOR_SPLICE: 3520 return lowerVECTOR_SPLICE(Op, DAG); 3521 case ISD::BUILD_VECTOR: 3522 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3523 case ISD::SPLAT_VECTOR: 3524 if (Op.getValueType().getVectorElementType() == MVT::i1) 3525 return lowerVectorMaskSplat(Op, DAG); 3526 return SDValue(); 3527 case ISD::VECTOR_SHUFFLE: 3528 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3529 case ISD::CONCAT_VECTORS: { 3530 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3531 // better than going through the stack, as the default expansion does. 3532 SDLoc DL(Op); 3533 MVT VT = Op.getSimpleValueType(); 3534 unsigned NumOpElts = 3535 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3536 SDValue Vec = DAG.getUNDEF(VT); 3537 for (const auto &OpIdx : enumerate(Op->ops())) { 3538 SDValue SubVec = OpIdx.value(); 3539 // Don't insert undef subvectors. 3540 if (SubVec.isUndef()) 3541 continue; 3542 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3543 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3544 } 3545 return Vec; 3546 } 3547 case ISD::LOAD: 3548 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3549 return V; 3550 if (Op.getValueType().isFixedLengthVector()) 3551 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3552 return Op; 3553 case ISD::STORE: 3554 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3555 return V; 3556 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3557 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3558 return Op; 3559 case ISD::MLOAD: 3560 case ISD::VP_LOAD: 3561 return lowerMaskedLoad(Op, DAG); 3562 case ISD::MSTORE: 3563 case ISD::VP_STORE: 3564 return lowerMaskedStore(Op, DAG); 3565 case ISD::SETCC: 3566 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3567 case ISD::ADD: 3568 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3569 case ISD::SUB: 3570 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3571 case ISD::MUL: 3572 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3573 case ISD::MULHS: 3574 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3575 case ISD::MULHU: 3576 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3577 case ISD::AND: 3578 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3579 RISCVISD::AND_VL); 3580 case ISD::OR: 3581 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3582 RISCVISD::OR_VL); 3583 case ISD::XOR: 3584 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3585 RISCVISD::XOR_VL); 3586 case ISD::SDIV: 3587 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3588 case ISD::SREM: 3589 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3590 case ISD::UDIV: 3591 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3592 case ISD::UREM: 3593 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3594 case ISD::SHL: 3595 case ISD::SRA: 3596 case ISD::SRL: 3597 if (Op.getSimpleValueType().isFixedLengthVector()) 3598 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3599 // This can be called for an i32 shift amount that needs to be promoted. 3600 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3601 "Unexpected custom legalisation"); 3602 return SDValue(); 3603 case ISD::SADDSAT: 3604 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3605 case ISD::UADDSAT: 3606 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3607 case ISD::SSUBSAT: 3608 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3609 case ISD::USUBSAT: 3610 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3611 case ISD::FADD: 3612 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3613 case ISD::FSUB: 3614 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3615 case ISD::FMUL: 3616 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3617 case ISD::FDIV: 3618 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3619 case ISD::FNEG: 3620 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3621 case ISD::FABS: 3622 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3623 case ISD::FSQRT: 3624 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3625 case ISD::FMA: 3626 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3627 case ISD::SMIN: 3628 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3629 case ISD::SMAX: 3630 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3631 case ISD::UMIN: 3632 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3633 case ISD::UMAX: 3634 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3635 case ISD::FMINNUM: 3636 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3637 case ISD::FMAXNUM: 3638 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3639 case ISD::ABS: 3640 return lowerABS(Op, DAG); 3641 case ISD::CTLZ_ZERO_UNDEF: 3642 case ISD::CTTZ_ZERO_UNDEF: 3643 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3644 case ISD::VSELECT: 3645 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3646 case ISD::FCOPYSIGN: 3647 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3648 case ISD::MGATHER: 3649 case ISD::VP_GATHER: 3650 return lowerMaskedGather(Op, DAG); 3651 case ISD::MSCATTER: 3652 case ISD::VP_SCATTER: 3653 return lowerMaskedScatter(Op, DAG); 3654 case ISD::FLT_ROUNDS_: 3655 return lowerGET_ROUNDING(Op, DAG); 3656 case ISD::SET_ROUNDING: 3657 return lowerSET_ROUNDING(Op, DAG); 3658 case ISD::VP_SELECT: 3659 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3660 case ISD::VP_MERGE: 3661 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3662 case ISD::VP_ADD: 3663 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3664 case ISD::VP_SUB: 3665 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3666 case ISD::VP_MUL: 3667 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3668 case ISD::VP_SDIV: 3669 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3670 case ISD::VP_UDIV: 3671 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3672 case ISD::VP_SREM: 3673 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3674 case ISD::VP_UREM: 3675 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3676 case ISD::VP_AND: 3677 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3678 case ISD::VP_OR: 3679 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3680 case ISD::VP_XOR: 3681 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3682 case ISD::VP_ASHR: 3683 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3684 case ISD::VP_LSHR: 3685 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3686 case ISD::VP_SHL: 3687 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3688 case ISD::VP_FADD: 3689 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3690 case ISD::VP_FSUB: 3691 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3692 case ISD::VP_FMUL: 3693 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3694 case ISD::VP_FDIV: 3695 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3696 case ISD::VP_FNEG: 3697 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3698 case ISD::VP_FMA: 3699 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3700 case ISD::VP_SEXT: 3701 case ISD::VP_ZEXT: 3702 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3703 return lowerVPExtMaskOp(Op, DAG); 3704 return lowerVPOp(Op, DAG, 3705 Op.getOpcode() == ISD::VP_SEXT ? RISCVISD::VSEXT_VL 3706 : RISCVISD::VZEXT_VL); 3707 case ISD::VP_FPTOSI: 3708 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3709 case ISD::VP_FPTOUI: 3710 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3711 case ISD::VP_SITOFP: 3712 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3713 case ISD::VP_UITOFP: 3714 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3715 case ISD::VP_SETCC: 3716 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3717 } 3718 } 3719 3720 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3721 SelectionDAG &DAG, unsigned Flags) { 3722 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3723 } 3724 3725 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3726 SelectionDAG &DAG, unsigned Flags) { 3727 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3728 Flags); 3729 } 3730 3731 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3732 SelectionDAG &DAG, unsigned Flags) { 3733 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3734 N->getOffset(), Flags); 3735 } 3736 3737 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3738 SelectionDAG &DAG, unsigned Flags) { 3739 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3740 } 3741 3742 template <class NodeTy> 3743 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3744 bool IsLocal) const { 3745 SDLoc DL(N); 3746 EVT Ty = getPointerTy(DAG.getDataLayout()); 3747 3748 if (isPositionIndependent()) { 3749 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3750 if (IsLocal) 3751 // Use PC-relative addressing to access the symbol. This generates the 3752 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3753 // %pcrel_lo(auipc)). 3754 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3755 3756 // Use PC-relative addressing to access the GOT for this symbol, then load 3757 // the address from the GOT. This generates the pattern (PseudoLA sym), 3758 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3759 SDValue Load = 3760 SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3761 MachineFunction &MF = DAG.getMachineFunction(); 3762 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3763 MachinePointerInfo::getGOT(MF), 3764 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3765 MachineMemOperand::MOInvariant, 3766 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3767 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3768 return Load; 3769 } 3770 3771 switch (getTargetMachine().getCodeModel()) { 3772 default: 3773 report_fatal_error("Unsupported code model for lowering"); 3774 case CodeModel::Small: { 3775 // Generate a sequence for accessing addresses within the first 2 GiB of 3776 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3777 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3778 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3779 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3780 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3781 } 3782 case CodeModel::Medium: { 3783 // Generate a sequence for accessing addresses within any 2GiB range within 3784 // the address space. This generates the pattern (PseudoLLA sym), which 3785 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3786 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3787 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3788 } 3789 } 3790 } 3791 3792 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>( 3793 GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3794 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>( 3795 BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3796 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>( 3797 ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3798 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>( 3799 JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3800 3801 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3802 SelectionDAG &DAG) const { 3803 SDLoc DL(Op); 3804 EVT Ty = Op.getValueType(); 3805 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3806 int64_t Offset = N->getOffset(); 3807 MVT XLenVT = Subtarget.getXLenVT(); 3808 3809 const GlobalValue *GV = N->getGlobal(); 3810 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3811 SDValue Addr = getAddr(N, DAG, IsLocal); 3812 3813 // In order to maximise the opportunity for common subexpression elimination, 3814 // emit a separate ADD node for the global address offset instead of folding 3815 // it in the global address node. Later peephole optimisations may choose to 3816 // fold it back in when profitable. 3817 if (Offset != 0) 3818 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3819 DAG.getConstant(Offset, DL, XLenVT)); 3820 return Addr; 3821 } 3822 3823 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3824 SelectionDAG &DAG) const { 3825 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3826 3827 return getAddr(N, DAG); 3828 } 3829 3830 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3831 SelectionDAG &DAG) const { 3832 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3833 3834 return getAddr(N, DAG); 3835 } 3836 3837 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3838 SelectionDAG &DAG) const { 3839 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3840 3841 return getAddr(N, DAG); 3842 } 3843 3844 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3845 SelectionDAG &DAG, 3846 bool UseGOT) const { 3847 SDLoc DL(N); 3848 EVT Ty = getPointerTy(DAG.getDataLayout()); 3849 const GlobalValue *GV = N->getGlobal(); 3850 MVT XLenVT = Subtarget.getXLenVT(); 3851 3852 if (UseGOT) { 3853 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3854 // load the address from the GOT and add the thread pointer. This generates 3855 // the pattern (PseudoLA_TLS_IE sym), which expands to 3856 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3857 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3858 SDValue Load = 3859 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3860 MachineFunction &MF = DAG.getMachineFunction(); 3861 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3862 MachinePointerInfo::getGOT(MF), 3863 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3864 MachineMemOperand::MOInvariant, 3865 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3866 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3867 3868 // Add the thread pointer. 3869 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3870 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3871 } 3872 3873 // Generate a sequence for accessing the address relative to the thread 3874 // pointer, with the appropriate adjustment for the thread pointer offset. 3875 // This generates the pattern 3876 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3877 SDValue AddrHi = 3878 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3879 SDValue AddrAdd = 3880 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3881 SDValue AddrLo = 3882 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3883 3884 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3885 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3886 SDValue MNAdd = SDValue( 3887 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3888 0); 3889 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3890 } 3891 3892 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3893 SelectionDAG &DAG) const { 3894 SDLoc DL(N); 3895 EVT Ty = getPointerTy(DAG.getDataLayout()); 3896 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3897 const GlobalValue *GV = N->getGlobal(); 3898 3899 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3900 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3901 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3902 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3903 SDValue Load = 3904 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3905 3906 // Prepare argument list to generate call. 3907 ArgListTy Args; 3908 ArgListEntry Entry; 3909 Entry.Node = Load; 3910 Entry.Ty = CallTy; 3911 Args.push_back(Entry); 3912 3913 // Setup call to __tls_get_addr. 3914 TargetLowering::CallLoweringInfo CLI(DAG); 3915 CLI.setDebugLoc(DL) 3916 .setChain(DAG.getEntryNode()) 3917 .setLibCallee(CallingConv::C, CallTy, 3918 DAG.getExternalSymbol("__tls_get_addr", Ty), 3919 std::move(Args)); 3920 3921 return LowerCallTo(CLI).first; 3922 } 3923 3924 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3925 SelectionDAG &DAG) const { 3926 SDLoc DL(Op); 3927 EVT Ty = Op.getValueType(); 3928 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3929 int64_t Offset = N->getOffset(); 3930 MVT XLenVT = Subtarget.getXLenVT(); 3931 3932 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3933 3934 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3935 CallingConv::GHC) 3936 report_fatal_error("In GHC calling convention TLS is not supported"); 3937 3938 SDValue Addr; 3939 switch (Model) { 3940 case TLSModel::LocalExec: 3941 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3942 break; 3943 case TLSModel::InitialExec: 3944 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3945 break; 3946 case TLSModel::LocalDynamic: 3947 case TLSModel::GeneralDynamic: 3948 Addr = getDynamicTLSAddr(N, DAG); 3949 break; 3950 } 3951 3952 // In order to maximise the opportunity for common subexpression elimination, 3953 // emit a separate ADD node for the global address offset instead of folding 3954 // it in the global address node. Later peephole optimisations may choose to 3955 // fold it back in when profitable. 3956 if (Offset != 0) 3957 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3958 DAG.getConstant(Offset, DL, XLenVT)); 3959 return Addr; 3960 } 3961 3962 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3963 SDValue CondV = Op.getOperand(0); 3964 SDValue TrueV = Op.getOperand(1); 3965 SDValue FalseV = Op.getOperand(2); 3966 SDLoc DL(Op); 3967 MVT VT = Op.getSimpleValueType(); 3968 MVT XLenVT = Subtarget.getXLenVT(); 3969 3970 // Lower vector SELECTs to VSELECTs by splatting the condition. 3971 if (VT.isVector()) { 3972 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3973 SDValue CondSplat = VT.isScalableVector() 3974 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3975 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3976 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3977 } 3978 3979 // If the result type is XLenVT and CondV is the output of a SETCC node 3980 // which also operated on XLenVT inputs, then merge the SETCC node into the 3981 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3982 // compare+branch instructions. i.e.: 3983 // (select (setcc lhs, rhs, cc), truev, falsev) 3984 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3985 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3986 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3987 SDValue LHS = CondV.getOperand(0); 3988 SDValue RHS = CondV.getOperand(1); 3989 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3990 ISD::CondCode CCVal = CC->get(); 3991 3992 // Special case for a select of 2 constants that have a diffence of 1. 3993 // Normally this is done by DAGCombine, but if the select is introduced by 3994 // type legalization or op legalization, we miss it. Restricting to SETLT 3995 // case for now because that is what signed saturating add/sub need. 3996 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3997 // but we would probably want to swap the true/false values if the condition 3998 // is SETGE/SETLE to avoid an XORI. 3999 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 4000 CCVal == ISD::SETLT) { 4001 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 4002 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 4003 if (TrueVal - 1 == FalseVal) 4004 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 4005 if (TrueVal + 1 == FalseVal) 4006 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 4007 } 4008 4009 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 4010 4011 SDValue TargetCC = DAG.getCondCode(CCVal); 4012 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 4013 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 4014 } 4015 4016 // Otherwise: 4017 // (select condv, truev, falsev) 4018 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 4019 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4020 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 4021 4022 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 4023 4024 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 4025 } 4026 4027 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4028 SDValue CondV = Op.getOperand(1); 4029 SDLoc DL(Op); 4030 MVT XLenVT = Subtarget.getXLenVT(); 4031 4032 if (CondV.getOpcode() == ISD::SETCC && 4033 CondV.getOperand(0).getValueType() == XLenVT) { 4034 SDValue LHS = CondV.getOperand(0); 4035 SDValue RHS = CondV.getOperand(1); 4036 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 4037 4038 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 4039 4040 SDValue TargetCC = DAG.getCondCode(CCVal); 4041 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 4042 LHS, RHS, TargetCC, Op.getOperand(2)); 4043 } 4044 4045 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 4046 CondV, DAG.getConstant(0, DL, XLenVT), 4047 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 4048 } 4049 4050 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 4051 MachineFunction &MF = DAG.getMachineFunction(); 4052 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 4053 4054 SDLoc DL(Op); 4055 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 4056 getPointerTy(MF.getDataLayout())); 4057 4058 // vastart just stores the address of the VarArgsFrameIndex slot into the 4059 // memory location argument. 4060 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4061 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 4062 MachinePointerInfo(SV)); 4063 } 4064 4065 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 4066 SelectionDAG &DAG) const { 4067 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4068 MachineFunction &MF = DAG.getMachineFunction(); 4069 MachineFrameInfo &MFI = MF.getFrameInfo(); 4070 MFI.setFrameAddressIsTaken(true); 4071 Register FrameReg = RI.getFrameRegister(MF); 4072 int XLenInBytes = Subtarget.getXLen() / 8; 4073 4074 EVT VT = Op.getValueType(); 4075 SDLoc DL(Op); 4076 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 4077 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4078 while (Depth--) { 4079 int Offset = -(XLenInBytes * 2); 4080 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 4081 DAG.getIntPtrConstant(Offset, DL)); 4082 FrameAddr = 4083 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 4084 } 4085 return FrameAddr; 4086 } 4087 4088 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 4089 SelectionDAG &DAG) const { 4090 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4091 MachineFunction &MF = DAG.getMachineFunction(); 4092 MachineFrameInfo &MFI = MF.getFrameInfo(); 4093 MFI.setReturnAddressIsTaken(true); 4094 MVT XLenVT = Subtarget.getXLenVT(); 4095 int XLenInBytes = Subtarget.getXLen() / 8; 4096 4097 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4098 return SDValue(); 4099 4100 EVT VT = Op.getValueType(); 4101 SDLoc DL(Op); 4102 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4103 if (Depth) { 4104 int Off = -XLenInBytes; 4105 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 4106 SDValue Offset = DAG.getConstant(Off, DL, VT); 4107 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4108 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4109 MachinePointerInfo()); 4110 } 4111 4112 // Return the value of the return address register, marking it an implicit 4113 // live-in. 4114 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 4115 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 4116 } 4117 4118 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4119 SelectionDAG &DAG) const { 4120 SDLoc DL(Op); 4121 SDValue Lo = Op.getOperand(0); 4122 SDValue Hi = Op.getOperand(1); 4123 SDValue Shamt = Op.getOperand(2); 4124 EVT VT = Lo.getValueType(); 4125 4126 // if Shamt-XLEN < 0: // Shamt < XLEN 4127 // Lo = Lo << Shamt 4128 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4129 // else: 4130 // Lo = 0 4131 // Hi = Lo << (Shamt-XLEN) 4132 4133 SDValue Zero = DAG.getConstant(0, DL, VT); 4134 SDValue One = DAG.getConstant(1, DL, VT); 4135 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4136 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4137 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4138 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4139 4140 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4141 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4142 SDValue ShiftRightLo = 4143 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4144 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4145 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4146 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4147 4148 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4149 4150 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4151 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4152 4153 SDValue Parts[2] = {Lo, Hi}; 4154 return DAG.getMergeValues(Parts, DL); 4155 } 4156 4157 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4158 bool IsSRA) const { 4159 SDLoc DL(Op); 4160 SDValue Lo = Op.getOperand(0); 4161 SDValue Hi = Op.getOperand(1); 4162 SDValue Shamt = Op.getOperand(2); 4163 EVT VT = Lo.getValueType(); 4164 4165 // SRA expansion: 4166 // if Shamt-XLEN < 0: // Shamt < XLEN 4167 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4168 // Hi = Hi >>s Shamt 4169 // else: 4170 // Lo = Hi >>s (Shamt-XLEN); 4171 // Hi = Hi >>s (XLEN-1) 4172 // 4173 // SRL expansion: 4174 // if Shamt-XLEN < 0: // Shamt < XLEN 4175 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4176 // Hi = Hi >>u Shamt 4177 // else: 4178 // Lo = Hi >>u (Shamt-XLEN); 4179 // Hi = 0; 4180 4181 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4182 4183 SDValue Zero = DAG.getConstant(0, DL, VT); 4184 SDValue One = DAG.getConstant(1, DL, VT); 4185 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4186 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4187 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4188 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4189 4190 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4191 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4192 SDValue ShiftLeftHi = 4193 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4194 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4195 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4196 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4197 SDValue HiFalse = 4198 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4199 4200 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4201 4202 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4203 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4204 4205 SDValue Parts[2] = {Lo, Hi}; 4206 return DAG.getMergeValues(Parts, DL); 4207 } 4208 4209 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4210 // legal equivalently-sized i8 type, so we can use that as a go-between. 4211 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4212 SelectionDAG &DAG) const { 4213 SDLoc DL(Op); 4214 MVT VT = Op.getSimpleValueType(); 4215 SDValue SplatVal = Op.getOperand(0); 4216 // All-zeros or all-ones splats are handled specially. 4217 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4218 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4219 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4220 } 4221 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4222 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4223 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4224 } 4225 MVT XLenVT = Subtarget.getXLenVT(); 4226 assert(SplatVal.getValueType() == XLenVT && 4227 "Unexpected type for i1 splat value"); 4228 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4229 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4230 DAG.getConstant(1, DL, XLenVT)); 4231 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4232 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4233 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4234 } 4235 4236 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4237 // illegal (currently only vXi64 RV32). 4238 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4239 // them to VMV_V_X_VL. 4240 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4241 SelectionDAG &DAG) const { 4242 SDLoc DL(Op); 4243 MVT VecVT = Op.getSimpleValueType(); 4244 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4245 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4246 4247 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4248 SDValue Lo = Op.getOperand(0); 4249 SDValue Hi = Op.getOperand(1); 4250 4251 if (VecVT.isFixedLengthVector()) { 4252 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4253 SDLoc DL(Op); 4254 SDValue Mask, VL; 4255 std::tie(Mask, VL) = 4256 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4257 4258 SDValue Res = 4259 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4260 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4261 } 4262 4263 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4264 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4265 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4266 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4267 // node in order to try and match RVV vector/scalar instructions. 4268 if ((LoC >> 31) == HiC) 4269 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4270 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4271 } 4272 4273 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4274 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4275 isa<ConstantSDNode>(Hi.getOperand(1)) && 4276 Hi.getConstantOperandVal(1) == 31) 4277 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4278 DAG.getRegister(RISCV::X0, MVT::i32)); 4279 4280 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4281 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4282 DAG.getUNDEF(VecVT), Lo, Hi, 4283 DAG.getRegister(RISCV::X0, MVT::i32)); 4284 } 4285 4286 // Custom-lower extensions from mask vectors by using a vselect either with 1 4287 // for zero/any-extension or -1 for sign-extension: 4288 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4289 // Note that any-extension is lowered identically to zero-extension. 4290 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4291 int64_t ExtTrueVal) const { 4292 SDLoc DL(Op); 4293 MVT VecVT = Op.getSimpleValueType(); 4294 SDValue Src = Op.getOperand(0); 4295 // Only custom-lower extensions from mask types 4296 assert(Src.getValueType().isVector() && 4297 Src.getValueType().getVectorElementType() == MVT::i1); 4298 4299 if (VecVT.isScalableVector()) { 4300 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4301 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4302 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4303 } 4304 4305 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4306 MVT I1ContainerVT = 4307 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4308 4309 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4310 4311 SDValue Mask, VL; 4312 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4313 4314 MVT XLenVT = Subtarget.getXLenVT(); 4315 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4316 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4317 4318 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4319 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4320 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4321 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4322 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4323 SplatTrueVal, SplatZero, VL); 4324 4325 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4326 } 4327 4328 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4329 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4330 MVT ExtVT = Op.getSimpleValueType(); 4331 // Only custom-lower extensions from fixed-length vector types. 4332 if (!ExtVT.isFixedLengthVector()) 4333 return Op; 4334 MVT VT = Op.getOperand(0).getSimpleValueType(); 4335 // Grab the canonical container type for the extended type. Infer the smaller 4336 // type from that to ensure the same number of vector elements, as we know 4337 // the LMUL will be sufficient to hold the smaller type. 4338 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4339 // Get the extended container type manually to ensure the same number of 4340 // vector elements between source and dest. 4341 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4342 ContainerExtVT.getVectorElementCount()); 4343 4344 SDValue Op1 = 4345 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4346 4347 SDLoc DL(Op); 4348 SDValue Mask, VL; 4349 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4350 4351 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4352 4353 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4354 } 4355 4356 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4357 // setcc operation: 4358 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4359 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 4360 SelectionDAG &DAG) const { 4361 SDLoc DL(Op); 4362 EVT MaskVT = Op.getValueType(); 4363 // Only expect to custom-lower truncations to mask types 4364 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4365 "Unexpected type for vector mask lowering"); 4366 SDValue Src = Op.getOperand(0); 4367 MVT VecVT = Src.getSimpleValueType(); 4368 4369 // If this is a fixed vector, we need to convert it to a scalable vector. 4370 MVT ContainerVT = VecVT; 4371 if (VecVT.isFixedLengthVector()) { 4372 ContainerVT = getContainerForFixedLengthVector(VecVT); 4373 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4374 } 4375 4376 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4377 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4378 4379 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4380 DAG.getUNDEF(ContainerVT), SplatOne); 4381 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4382 DAG.getUNDEF(ContainerVT), SplatZero); 4383 4384 if (VecVT.isScalableVector()) { 4385 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 4386 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 4387 } 4388 4389 SDValue Mask, VL; 4390 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4391 4392 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4393 SDValue Trunc = 4394 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4395 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4396 DAG.getCondCode(ISD::SETNE), Mask, VL); 4397 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4398 } 4399 4400 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4401 // first position of a vector, and that vector is slid up to the insert index. 4402 // By limiting the active vector length to index+1 and merging with the 4403 // original vector (with an undisturbed tail policy for elements >= VL), we 4404 // achieve the desired result of leaving all elements untouched except the one 4405 // at VL-1, which is replaced with the desired value. 4406 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4407 SelectionDAG &DAG) const { 4408 SDLoc DL(Op); 4409 MVT VecVT = Op.getSimpleValueType(); 4410 SDValue Vec = Op.getOperand(0); 4411 SDValue Val = Op.getOperand(1); 4412 SDValue Idx = Op.getOperand(2); 4413 4414 if (VecVT.getVectorElementType() == MVT::i1) { 4415 // FIXME: For now we just promote to an i8 vector and insert into that, 4416 // but this is probably not optimal. 4417 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4418 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4419 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4420 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4421 } 4422 4423 MVT ContainerVT = VecVT; 4424 // If the operand is a fixed-length vector, convert to a scalable one. 4425 if (VecVT.isFixedLengthVector()) { 4426 ContainerVT = getContainerForFixedLengthVector(VecVT); 4427 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4428 } 4429 4430 MVT XLenVT = Subtarget.getXLenVT(); 4431 4432 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4433 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4434 // Even i64-element vectors on RV32 can be lowered without scalar 4435 // legalization if the most-significant 32 bits of the value are not affected 4436 // by the sign-extension of the lower 32 bits. 4437 // TODO: We could also catch sign extensions of a 32-bit value. 4438 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4439 const auto *CVal = cast<ConstantSDNode>(Val); 4440 if (isInt<32>(CVal->getSExtValue())) { 4441 IsLegalInsert = true; 4442 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4443 } 4444 } 4445 4446 SDValue Mask, VL; 4447 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4448 4449 SDValue ValInVec; 4450 4451 if (IsLegalInsert) { 4452 unsigned Opc = 4453 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4454 if (isNullConstant(Idx)) { 4455 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4456 if (!VecVT.isFixedLengthVector()) 4457 return Vec; 4458 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4459 } 4460 ValInVec = 4461 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4462 } else { 4463 // On RV32, i64-element vectors must be specially handled to place the 4464 // value at element 0, by using two vslide1up instructions in sequence on 4465 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4466 // this. 4467 SDValue One = DAG.getConstant(1, DL, XLenVT); 4468 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4469 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4470 MVT I32ContainerVT = 4471 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4472 SDValue I32Mask = 4473 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4474 // Limit the active VL to two. 4475 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4476 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4477 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4478 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4479 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4480 // First slide in the hi value, then the lo in underneath it. 4481 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4482 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4483 I32Mask, InsertI64VL); 4484 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4485 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4486 I32Mask, InsertI64VL); 4487 // Bitcast back to the right container type. 4488 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4489 } 4490 4491 // Now that the value is in a vector, slide it into position. 4492 SDValue InsertVL = 4493 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4494 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4495 ValInVec, Idx, Mask, InsertVL); 4496 if (!VecVT.isFixedLengthVector()) 4497 return Slideup; 4498 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4499 } 4500 4501 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4502 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4503 // types this is done using VMV_X_S to allow us to glean information about the 4504 // sign bits of the result. 4505 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4506 SelectionDAG &DAG) const { 4507 SDLoc DL(Op); 4508 SDValue Idx = Op.getOperand(1); 4509 SDValue Vec = Op.getOperand(0); 4510 EVT EltVT = Op.getValueType(); 4511 MVT VecVT = Vec.getSimpleValueType(); 4512 MVT XLenVT = Subtarget.getXLenVT(); 4513 4514 if (VecVT.getVectorElementType() == MVT::i1) { 4515 if (VecVT.isFixedLengthVector()) { 4516 unsigned NumElts = VecVT.getVectorNumElements(); 4517 if (NumElts >= 8) { 4518 MVT WideEltVT; 4519 unsigned WidenVecLen; 4520 SDValue ExtractElementIdx; 4521 SDValue ExtractBitIdx; 4522 unsigned MaxEEW = Subtarget.getELEN(); 4523 MVT LargestEltVT = MVT::getIntegerVT( 4524 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4525 if (NumElts <= LargestEltVT.getSizeInBits()) { 4526 assert(isPowerOf2_32(NumElts) && 4527 "the number of elements should be power of 2"); 4528 WideEltVT = MVT::getIntegerVT(NumElts); 4529 WidenVecLen = 1; 4530 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4531 ExtractBitIdx = Idx; 4532 } else { 4533 WideEltVT = LargestEltVT; 4534 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4535 // extract element index = index / element width 4536 ExtractElementIdx = DAG.getNode( 4537 ISD::SRL, DL, XLenVT, Idx, 4538 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4539 // mask bit index = index % element width 4540 ExtractBitIdx = DAG.getNode( 4541 ISD::AND, DL, XLenVT, Idx, 4542 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4543 } 4544 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4545 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4546 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4547 Vec, ExtractElementIdx); 4548 // Extract the bit from GPR. 4549 SDValue ShiftRight = 4550 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4551 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4552 DAG.getConstant(1, DL, XLenVT)); 4553 } 4554 } 4555 // Otherwise, promote to an i8 vector and extract from that. 4556 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4557 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4558 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4559 } 4560 4561 // If this is a fixed vector, we need to convert it to a scalable vector. 4562 MVT ContainerVT = VecVT; 4563 if (VecVT.isFixedLengthVector()) { 4564 ContainerVT = getContainerForFixedLengthVector(VecVT); 4565 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4566 } 4567 4568 // If the index is 0, the vector is already in the right position. 4569 if (!isNullConstant(Idx)) { 4570 // Use a VL of 1 to avoid processing more elements than we need. 4571 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4572 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4573 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4574 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4575 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4576 } 4577 4578 if (!EltVT.isInteger()) { 4579 // Floating-point extracts are handled in TableGen. 4580 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4581 DAG.getConstant(0, DL, XLenVT)); 4582 } 4583 4584 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4585 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4586 } 4587 4588 // Some RVV intrinsics may claim that they want an integer operand to be 4589 // promoted or expanded. 4590 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4591 const RISCVSubtarget &Subtarget) { 4592 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4593 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4594 "Unexpected opcode"); 4595 4596 if (!Subtarget.hasVInstructions()) 4597 return SDValue(); 4598 4599 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4600 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4601 SDLoc DL(Op); 4602 4603 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4604 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4605 if (!II || !II->hasScalarOperand()) 4606 return SDValue(); 4607 4608 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4609 assert(SplatOp < Op.getNumOperands()); 4610 4611 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4612 SDValue &ScalarOp = Operands[SplatOp]; 4613 MVT OpVT = ScalarOp.getSimpleValueType(); 4614 MVT XLenVT = Subtarget.getXLenVT(); 4615 4616 // If this isn't a scalar, or its type is XLenVT we're done. 4617 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4618 return SDValue(); 4619 4620 // Simplest case is that the operand needs to be promoted to XLenVT. 4621 if (OpVT.bitsLT(XLenVT)) { 4622 // If the operand is a constant, sign extend to increase our chances 4623 // of being able to use a .vi instruction. ANY_EXTEND would become a 4624 // a zero extend and the simm5 check in isel would fail. 4625 // FIXME: Should we ignore the upper bits in isel instead? 4626 unsigned ExtOpc = 4627 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4628 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4629 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4630 } 4631 4632 // Use the previous operand to get the vXi64 VT. The result might be a mask 4633 // VT for compares. Using the previous operand assumes that the previous 4634 // operand will never have a smaller element size than a scalar operand and 4635 // that a widening operation never uses SEW=64. 4636 // NOTE: If this fails the below assert, we can probably just find the 4637 // element count from any operand or result and use it to construct the VT. 4638 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4639 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4640 4641 // The more complex case is when the scalar is larger than XLenVT. 4642 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4643 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4644 4645 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4646 // instruction to sign-extend since SEW>XLEN. 4647 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4648 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4649 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4650 } 4651 4652 switch (IntNo) { 4653 case Intrinsic::riscv_vslide1up: 4654 case Intrinsic::riscv_vslide1down: 4655 case Intrinsic::riscv_vslide1up_mask: 4656 case Intrinsic::riscv_vslide1down_mask: { 4657 // We need to special case these when the scalar is larger than XLen. 4658 unsigned NumOps = Op.getNumOperands(); 4659 bool IsMasked = NumOps == 7; 4660 4661 // Convert the vector source to the equivalent nxvXi32 vector. 4662 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4663 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4664 4665 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4666 DAG.getConstant(0, DL, XLenVT)); 4667 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4668 DAG.getConstant(1, DL, XLenVT)); 4669 4670 // Double the VL since we halved SEW. 4671 SDValue AVL = getVLOperand(Op); 4672 SDValue I32VL; 4673 4674 // Optimize for constant AVL 4675 if (isa<ConstantSDNode>(AVL)) { 4676 unsigned EltSize = VT.getScalarSizeInBits(); 4677 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4678 4679 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4680 unsigned MaxVLMAX = 4681 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4682 4683 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4684 unsigned MinVLMAX = 4685 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4686 4687 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4688 if (AVLInt <= MinVLMAX) { 4689 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4690 } else if (AVLInt >= 2 * MaxVLMAX) { 4691 // Just set vl to VLMAX in this situation 4692 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4693 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4694 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4695 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4696 SDValue SETVLMAX = DAG.getTargetConstant( 4697 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4698 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4699 LMUL); 4700 } else { 4701 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4702 // is related to the hardware implementation. 4703 // So let the following code handle 4704 } 4705 } 4706 if (!I32VL) { 4707 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4708 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4709 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4710 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4711 SDValue SETVL = 4712 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4713 // Using vsetvli instruction to get actually used length which related to 4714 // the hardware implementation 4715 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4716 SEW, LMUL); 4717 I32VL = 4718 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4719 } 4720 4721 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4722 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL); 4723 4724 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4725 // instructions. 4726 SDValue Passthru; 4727 if (IsMasked) 4728 Passthru = DAG.getUNDEF(I32VT); 4729 else 4730 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4731 4732 if (IntNo == Intrinsic::riscv_vslide1up || 4733 IntNo == Intrinsic::riscv_vslide1up_mask) { 4734 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4735 ScalarHi, I32Mask, I32VL); 4736 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4737 ScalarLo, I32Mask, I32VL); 4738 } else { 4739 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4740 ScalarLo, I32Mask, I32VL); 4741 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4742 ScalarHi, I32Mask, I32VL); 4743 } 4744 4745 // Convert back to nxvXi64. 4746 Vec = DAG.getBitcast(VT, Vec); 4747 4748 if (!IsMasked) 4749 return Vec; 4750 // Apply mask after the operation. 4751 SDValue Mask = Operands[NumOps - 3]; 4752 SDValue MaskedOff = Operands[1]; 4753 // Assume Policy operand is the last operand. 4754 uint64_t Policy = 4755 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4756 // We don't need to select maskedoff if it's undef. 4757 if (MaskedOff.isUndef()) 4758 return Vec; 4759 // TAMU 4760 if (Policy == RISCVII::TAIL_AGNOSTIC) 4761 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4762 AVL); 4763 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4764 // It's fine because vmerge does not care mask policy. 4765 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4766 AVL); 4767 } 4768 } 4769 4770 // We need to convert the scalar to a splat vector. 4771 SDValue VL = getVLOperand(Op); 4772 assert(VL.getValueType() == XLenVT); 4773 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4774 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4775 } 4776 4777 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4778 SelectionDAG &DAG) const { 4779 unsigned IntNo = Op.getConstantOperandVal(0); 4780 SDLoc DL(Op); 4781 MVT XLenVT = Subtarget.getXLenVT(); 4782 4783 switch (IntNo) { 4784 default: 4785 break; // Don't custom lower most intrinsics. 4786 case Intrinsic::thread_pointer: { 4787 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4788 return DAG.getRegister(RISCV::X4, PtrVT); 4789 } 4790 case Intrinsic::riscv_orc_b: 4791 case Intrinsic::riscv_brev8: { 4792 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4793 unsigned Opc = 4794 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4795 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4796 DAG.getConstant(7, DL, XLenVT)); 4797 } 4798 case Intrinsic::riscv_grev: 4799 case Intrinsic::riscv_gorc: { 4800 unsigned Opc = 4801 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4802 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4803 } 4804 case Intrinsic::riscv_zip: 4805 case Intrinsic::riscv_unzip: { 4806 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4807 // For i32 the immediate is 15. For i64 the immediate is 31. 4808 unsigned Opc = 4809 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4810 unsigned BitWidth = Op.getValueSizeInBits(); 4811 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4812 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4813 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4814 } 4815 case Intrinsic::riscv_shfl: 4816 case Intrinsic::riscv_unshfl: { 4817 unsigned Opc = 4818 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4819 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4820 } 4821 case Intrinsic::riscv_bcompress: 4822 case Intrinsic::riscv_bdecompress: { 4823 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4824 : RISCVISD::BDECOMPRESS; 4825 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4826 } 4827 case Intrinsic::riscv_bfp: 4828 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4829 Op.getOperand(2)); 4830 case Intrinsic::riscv_fsl: 4831 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4832 Op.getOperand(2), Op.getOperand(3)); 4833 case Intrinsic::riscv_fsr: 4834 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4835 Op.getOperand(2), Op.getOperand(3)); 4836 case Intrinsic::riscv_vmv_x_s: 4837 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4838 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4839 Op.getOperand(1)); 4840 case Intrinsic::riscv_vmv_v_x: 4841 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4842 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4843 Subtarget); 4844 case Intrinsic::riscv_vfmv_v_f: 4845 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4846 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4847 case Intrinsic::riscv_vmv_s_x: { 4848 SDValue Scalar = Op.getOperand(2); 4849 4850 if (Scalar.getValueType().bitsLE(XLenVT)) { 4851 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4852 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4853 Op.getOperand(1), Scalar, Op.getOperand(3)); 4854 } 4855 4856 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4857 4858 // This is an i64 value that lives in two scalar registers. We have to 4859 // insert this in a convoluted way. First we build vXi64 splat containing 4860 // the two values that we assemble using some bit math. Next we'll use 4861 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4862 // to merge element 0 from our splat into the source vector. 4863 // FIXME: This is probably not the best way to do this, but it is 4864 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4865 // point. 4866 // sw lo, (a0) 4867 // sw hi, 4(a0) 4868 // vlse vX, (a0) 4869 // 4870 // vid.v vVid 4871 // vmseq.vx mMask, vVid, 0 4872 // vmerge.vvm vDest, vSrc, vVal, mMask 4873 MVT VT = Op.getSimpleValueType(); 4874 SDValue Vec = Op.getOperand(1); 4875 SDValue VL = getVLOperand(Op); 4876 4877 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4878 if (Op.getOperand(1).isUndef()) 4879 return SplattedVal; 4880 SDValue SplattedIdx = 4881 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4882 DAG.getConstant(0, DL, MVT::i32), VL); 4883 4884 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4885 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4886 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4887 SDValue SelectCond = 4888 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4889 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4890 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4891 Vec, VL); 4892 } 4893 } 4894 4895 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4896 } 4897 4898 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4899 SelectionDAG &DAG) const { 4900 unsigned IntNo = Op.getConstantOperandVal(1); 4901 switch (IntNo) { 4902 default: 4903 break; 4904 case Intrinsic::riscv_masked_strided_load: { 4905 SDLoc DL(Op); 4906 MVT XLenVT = Subtarget.getXLenVT(); 4907 4908 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4909 // the selection of the masked intrinsics doesn't do this for us. 4910 SDValue Mask = Op.getOperand(5); 4911 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4912 4913 MVT VT = Op->getSimpleValueType(0); 4914 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4915 4916 SDValue PassThru = Op.getOperand(2); 4917 if (!IsUnmasked) { 4918 MVT MaskVT = 4919 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4920 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4921 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4922 } 4923 4924 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4925 4926 SDValue IntID = DAG.getTargetConstant( 4927 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4928 XLenVT); 4929 4930 auto *Load = cast<MemIntrinsicSDNode>(Op); 4931 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4932 if (IsUnmasked) 4933 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4934 else 4935 Ops.push_back(PassThru); 4936 Ops.push_back(Op.getOperand(3)); // Ptr 4937 Ops.push_back(Op.getOperand(4)); // Stride 4938 if (!IsUnmasked) 4939 Ops.push_back(Mask); 4940 Ops.push_back(VL); 4941 if (!IsUnmasked) { 4942 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4943 Ops.push_back(Policy); 4944 } 4945 4946 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4947 SDValue Result = 4948 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4949 Load->getMemoryVT(), Load->getMemOperand()); 4950 SDValue Chain = Result.getValue(1); 4951 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4952 return DAG.getMergeValues({Result, Chain}, DL); 4953 } 4954 case Intrinsic::riscv_seg2_load: 4955 case Intrinsic::riscv_seg3_load: 4956 case Intrinsic::riscv_seg4_load: 4957 case Intrinsic::riscv_seg5_load: 4958 case Intrinsic::riscv_seg6_load: 4959 case Intrinsic::riscv_seg7_load: 4960 case Intrinsic::riscv_seg8_load: { 4961 SDLoc DL(Op); 4962 static const Intrinsic::ID VlsegInts[7] = { 4963 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4964 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4965 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4966 Intrinsic::riscv_vlseg8}; 4967 unsigned NF = Op->getNumValues() - 1; 4968 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4969 MVT XLenVT = Subtarget.getXLenVT(); 4970 MVT VT = Op->getSimpleValueType(0); 4971 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4972 4973 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4974 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4975 auto *Load = cast<MemIntrinsicSDNode>(Op); 4976 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4977 ContainerVTs.push_back(MVT::Other); 4978 SDVTList VTs = DAG.getVTList(ContainerVTs); 4979 SDValue Result = 4980 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, 4981 {Load->getChain(), IntID, Op.getOperand(2), VL}, 4982 Load->getMemoryVT(), Load->getMemOperand()); 4983 SmallVector<SDValue, 9> Results; 4984 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4985 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4986 DAG, Subtarget)); 4987 Results.push_back(Result.getValue(NF)); 4988 return DAG.getMergeValues(Results, DL); 4989 } 4990 } 4991 4992 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4993 } 4994 4995 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4996 SelectionDAG &DAG) const { 4997 unsigned IntNo = Op.getConstantOperandVal(1); 4998 switch (IntNo) { 4999 default: 5000 break; 5001 case Intrinsic::riscv_masked_strided_store: { 5002 SDLoc DL(Op); 5003 MVT XLenVT = Subtarget.getXLenVT(); 5004 5005 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5006 // the selection of the masked intrinsics doesn't do this for us. 5007 SDValue Mask = Op.getOperand(5); 5008 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5009 5010 SDValue Val = Op.getOperand(2); 5011 MVT VT = Val.getSimpleValueType(); 5012 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5013 5014 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5015 if (!IsUnmasked) { 5016 MVT MaskVT = 5017 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5018 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5019 } 5020 5021 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5022 5023 SDValue IntID = DAG.getTargetConstant( 5024 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5025 XLenVT); 5026 5027 auto *Store = cast<MemIntrinsicSDNode>(Op); 5028 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5029 Ops.push_back(Val); 5030 Ops.push_back(Op.getOperand(3)); // Ptr 5031 Ops.push_back(Op.getOperand(4)); // Stride 5032 if (!IsUnmasked) 5033 Ops.push_back(Mask); 5034 Ops.push_back(VL); 5035 5036 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5037 Ops, Store->getMemoryVT(), 5038 Store->getMemOperand()); 5039 } 5040 } 5041 5042 return SDValue(); 5043 } 5044 5045 static MVT getLMUL1VT(MVT VT) { 5046 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5047 "Unexpected vector MVT"); 5048 return MVT::getScalableVectorVT( 5049 VT.getVectorElementType(), 5050 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5051 } 5052 5053 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5054 switch (ISDOpcode) { 5055 default: 5056 llvm_unreachable("Unhandled reduction"); 5057 case ISD::VECREDUCE_ADD: 5058 return RISCVISD::VECREDUCE_ADD_VL; 5059 case ISD::VECREDUCE_UMAX: 5060 return RISCVISD::VECREDUCE_UMAX_VL; 5061 case ISD::VECREDUCE_SMAX: 5062 return RISCVISD::VECREDUCE_SMAX_VL; 5063 case ISD::VECREDUCE_UMIN: 5064 return RISCVISD::VECREDUCE_UMIN_VL; 5065 case ISD::VECREDUCE_SMIN: 5066 return RISCVISD::VECREDUCE_SMIN_VL; 5067 case ISD::VECREDUCE_AND: 5068 return RISCVISD::VECREDUCE_AND_VL; 5069 case ISD::VECREDUCE_OR: 5070 return RISCVISD::VECREDUCE_OR_VL; 5071 case ISD::VECREDUCE_XOR: 5072 return RISCVISD::VECREDUCE_XOR_VL; 5073 } 5074 } 5075 5076 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5077 SelectionDAG &DAG, 5078 bool IsVP) const { 5079 SDLoc DL(Op); 5080 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5081 MVT VecVT = Vec.getSimpleValueType(); 5082 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5083 Op.getOpcode() == ISD::VECREDUCE_OR || 5084 Op.getOpcode() == ISD::VECREDUCE_XOR || 5085 Op.getOpcode() == ISD::VP_REDUCE_AND || 5086 Op.getOpcode() == ISD::VP_REDUCE_OR || 5087 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5088 "Unexpected reduction lowering"); 5089 5090 MVT XLenVT = Subtarget.getXLenVT(); 5091 assert(Op.getValueType() == XLenVT && 5092 "Expected reduction output to be legalized to XLenVT"); 5093 5094 MVT ContainerVT = VecVT; 5095 if (VecVT.isFixedLengthVector()) { 5096 ContainerVT = getContainerForFixedLengthVector(VecVT); 5097 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5098 } 5099 5100 SDValue Mask, VL; 5101 if (IsVP) { 5102 Mask = Op.getOperand(2); 5103 VL = Op.getOperand(3); 5104 } else { 5105 std::tie(Mask, VL) = 5106 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5107 } 5108 5109 unsigned BaseOpc; 5110 ISD::CondCode CC; 5111 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5112 5113 switch (Op.getOpcode()) { 5114 default: 5115 llvm_unreachable("Unhandled reduction"); 5116 case ISD::VECREDUCE_AND: 5117 case ISD::VP_REDUCE_AND: { 5118 // vcpop ~x == 0 5119 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5120 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5121 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5122 CC = ISD::SETEQ; 5123 BaseOpc = ISD::AND; 5124 break; 5125 } 5126 case ISD::VECREDUCE_OR: 5127 case ISD::VP_REDUCE_OR: 5128 // vcpop x != 0 5129 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5130 CC = ISD::SETNE; 5131 BaseOpc = ISD::OR; 5132 break; 5133 case ISD::VECREDUCE_XOR: 5134 case ISD::VP_REDUCE_XOR: { 5135 // ((vcpop x) & 1) != 0 5136 SDValue One = DAG.getConstant(1, DL, XLenVT); 5137 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5138 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5139 CC = ISD::SETNE; 5140 BaseOpc = ISD::XOR; 5141 break; 5142 } 5143 } 5144 5145 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5146 5147 if (!IsVP) 5148 return SetCC; 5149 5150 // Now include the start value in the operation. 5151 // Note that we must return the start value when no elements are operated 5152 // upon. The vcpop instructions we've emitted in each case above will return 5153 // 0 for an inactive vector, and so we've already received the neutral value: 5154 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5155 // can simply include the start value. 5156 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5157 } 5158 5159 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5160 SelectionDAG &DAG) const { 5161 SDLoc DL(Op); 5162 SDValue Vec = Op.getOperand(0); 5163 EVT VecEVT = Vec.getValueType(); 5164 5165 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5166 5167 // Due to ordering in legalize types we may have a vector type that needs to 5168 // be split. Do that manually so we can get down to a legal type. 5169 while (getTypeAction(*DAG.getContext(), VecEVT) == 5170 TargetLowering::TypeSplitVector) { 5171 SDValue Lo, Hi; 5172 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5173 VecEVT = Lo.getValueType(); 5174 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5175 } 5176 5177 // TODO: The type may need to be widened rather than split. Or widened before 5178 // it can be split. 5179 if (!isTypeLegal(VecEVT)) 5180 return SDValue(); 5181 5182 MVT VecVT = VecEVT.getSimpleVT(); 5183 MVT VecEltVT = VecVT.getVectorElementType(); 5184 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5185 5186 MVT ContainerVT = VecVT; 5187 if (VecVT.isFixedLengthVector()) { 5188 ContainerVT = getContainerForFixedLengthVector(VecVT); 5189 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5190 } 5191 5192 MVT M1VT = getLMUL1VT(ContainerVT); 5193 MVT XLenVT = Subtarget.getXLenVT(); 5194 5195 SDValue Mask, VL; 5196 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5197 5198 SDValue NeutralElem = 5199 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5200 SDValue IdentitySplat = 5201 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5202 M1VT, DL, DAG, Subtarget); 5203 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5204 IdentitySplat, Mask, VL); 5205 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5206 DAG.getConstant(0, DL, XLenVT)); 5207 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5208 } 5209 5210 // Given a reduction op, this function returns the matching reduction opcode, 5211 // the vector SDValue and the scalar SDValue required to lower this to a 5212 // RISCVISD node. 5213 static std::tuple<unsigned, SDValue, SDValue> 5214 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5215 SDLoc DL(Op); 5216 auto Flags = Op->getFlags(); 5217 unsigned Opcode = Op.getOpcode(); 5218 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5219 switch (Opcode) { 5220 default: 5221 llvm_unreachable("Unhandled reduction"); 5222 case ISD::VECREDUCE_FADD: { 5223 // Use positive zero if we can. It is cheaper to materialize. 5224 SDValue Zero = 5225 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5226 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5227 } 5228 case ISD::VECREDUCE_SEQ_FADD: 5229 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5230 Op.getOperand(0)); 5231 case ISD::VECREDUCE_FMIN: 5232 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5233 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5234 case ISD::VECREDUCE_FMAX: 5235 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5236 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5237 } 5238 } 5239 5240 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5241 SelectionDAG &DAG) const { 5242 SDLoc DL(Op); 5243 MVT VecEltVT = Op.getSimpleValueType(); 5244 5245 unsigned RVVOpcode; 5246 SDValue VectorVal, ScalarVal; 5247 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5248 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5249 MVT VecVT = VectorVal.getSimpleValueType(); 5250 5251 MVT ContainerVT = VecVT; 5252 if (VecVT.isFixedLengthVector()) { 5253 ContainerVT = getContainerForFixedLengthVector(VecVT); 5254 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5255 } 5256 5257 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5258 MVT XLenVT = Subtarget.getXLenVT(); 5259 5260 SDValue Mask, VL; 5261 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5262 5263 SDValue ScalarSplat = 5264 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5265 M1VT, DL, DAG, Subtarget); 5266 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5267 VectorVal, ScalarSplat, Mask, VL); 5268 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5269 DAG.getConstant(0, DL, XLenVT)); 5270 } 5271 5272 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5273 switch (ISDOpcode) { 5274 default: 5275 llvm_unreachable("Unhandled reduction"); 5276 case ISD::VP_REDUCE_ADD: 5277 return RISCVISD::VECREDUCE_ADD_VL; 5278 case ISD::VP_REDUCE_UMAX: 5279 return RISCVISD::VECREDUCE_UMAX_VL; 5280 case ISD::VP_REDUCE_SMAX: 5281 return RISCVISD::VECREDUCE_SMAX_VL; 5282 case ISD::VP_REDUCE_UMIN: 5283 return RISCVISD::VECREDUCE_UMIN_VL; 5284 case ISD::VP_REDUCE_SMIN: 5285 return RISCVISD::VECREDUCE_SMIN_VL; 5286 case ISD::VP_REDUCE_AND: 5287 return RISCVISD::VECREDUCE_AND_VL; 5288 case ISD::VP_REDUCE_OR: 5289 return RISCVISD::VECREDUCE_OR_VL; 5290 case ISD::VP_REDUCE_XOR: 5291 return RISCVISD::VECREDUCE_XOR_VL; 5292 case ISD::VP_REDUCE_FADD: 5293 return RISCVISD::VECREDUCE_FADD_VL; 5294 case ISD::VP_REDUCE_SEQ_FADD: 5295 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5296 case ISD::VP_REDUCE_FMAX: 5297 return RISCVISD::VECREDUCE_FMAX_VL; 5298 case ISD::VP_REDUCE_FMIN: 5299 return RISCVISD::VECREDUCE_FMIN_VL; 5300 } 5301 } 5302 5303 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5304 SelectionDAG &DAG) const { 5305 SDLoc DL(Op); 5306 SDValue Vec = Op.getOperand(1); 5307 EVT VecEVT = Vec.getValueType(); 5308 5309 // TODO: The type may need to be widened rather than split. Or widened before 5310 // it can be split. 5311 if (!isTypeLegal(VecEVT)) 5312 return SDValue(); 5313 5314 MVT VecVT = VecEVT.getSimpleVT(); 5315 MVT VecEltVT = VecVT.getVectorElementType(); 5316 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5317 5318 MVT ContainerVT = VecVT; 5319 if (VecVT.isFixedLengthVector()) { 5320 ContainerVT = getContainerForFixedLengthVector(VecVT); 5321 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5322 } 5323 5324 SDValue VL = Op.getOperand(3); 5325 SDValue Mask = Op.getOperand(2); 5326 5327 MVT M1VT = getLMUL1VT(ContainerVT); 5328 MVT XLenVT = Subtarget.getXLenVT(); 5329 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5330 5331 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5332 DAG.getConstant(1, DL, XLenVT), M1VT, 5333 DL, DAG, Subtarget); 5334 SDValue Reduction = 5335 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5336 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5337 DAG.getConstant(0, DL, XLenVT)); 5338 if (!VecVT.isInteger()) 5339 return Elt0; 5340 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5341 } 5342 5343 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5344 SelectionDAG &DAG) const { 5345 SDValue Vec = Op.getOperand(0); 5346 SDValue SubVec = Op.getOperand(1); 5347 MVT VecVT = Vec.getSimpleValueType(); 5348 MVT SubVecVT = SubVec.getSimpleValueType(); 5349 5350 SDLoc DL(Op); 5351 MVT XLenVT = Subtarget.getXLenVT(); 5352 unsigned OrigIdx = Op.getConstantOperandVal(2); 5353 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5354 5355 // We don't have the ability to slide mask vectors up indexed by their i1 5356 // elements; the smallest we can do is i8. Often we are able to bitcast to 5357 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5358 // into a scalable one, we might not necessarily have enough scalable 5359 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5360 if (SubVecVT.getVectorElementType() == MVT::i1 && 5361 (OrigIdx != 0 || !Vec.isUndef())) { 5362 if (VecVT.getVectorMinNumElements() >= 8 && 5363 SubVecVT.getVectorMinNumElements() >= 8) { 5364 assert(OrigIdx % 8 == 0 && "Invalid index"); 5365 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5366 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5367 "Unexpected mask vector lowering"); 5368 OrigIdx /= 8; 5369 SubVecVT = 5370 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5371 SubVecVT.isScalableVector()); 5372 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5373 VecVT.isScalableVector()); 5374 Vec = DAG.getBitcast(VecVT, Vec); 5375 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5376 } else { 5377 // We can't slide this mask vector up indexed by its i1 elements. 5378 // This poses a problem when we wish to insert a scalable vector which 5379 // can't be re-expressed as a larger type. Just choose the slow path and 5380 // extend to a larger type, then truncate back down. 5381 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5382 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5383 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5384 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5385 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5386 Op.getOperand(2)); 5387 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5388 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5389 } 5390 } 5391 5392 // If the subvector vector is a fixed-length type, we cannot use subregister 5393 // manipulation to simplify the codegen; we don't know which register of a 5394 // LMUL group contains the specific subvector as we only know the minimum 5395 // register size. Therefore we must slide the vector group up the full 5396 // amount. 5397 if (SubVecVT.isFixedLengthVector()) { 5398 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5399 return Op; 5400 MVT ContainerVT = VecVT; 5401 if (VecVT.isFixedLengthVector()) { 5402 ContainerVT = getContainerForFixedLengthVector(VecVT); 5403 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5404 } 5405 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5406 DAG.getUNDEF(ContainerVT), SubVec, 5407 DAG.getConstant(0, DL, XLenVT)); 5408 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5409 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5410 return DAG.getBitcast(Op.getValueType(), SubVec); 5411 } 5412 SDValue Mask = 5413 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5414 // Set the vector length to only the number of elements we care about. Note 5415 // that for slideup this includes the offset. 5416 SDValue VL = 5417 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5418 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5419 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5420 SubVec, SlideupAmt, Mask, VL); 5421 if (VecVT.isFixedLengthVector()) 5422 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5423 return DAG.getBitcast(Op.getValueType(), Slideup); 5424 } 5425 5426 unsigned SubRegIdx, RemIdx; 5427 std::tie(SubRegIdx, RemIdx) = 5428 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5429 VecVT, SubVecVT, OrigIdx, TRI); 5430 5431 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5432 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5433 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5434 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5435 5436 // 1. If the Idx has been completely eliminated and this subvector's size is 5437 // a vector register or a multiple thereof, or the surrounding elements are 5438 // undef, then this is a subvector insert which naturally aligns to a vector 5439 // register. These can easily be handled using subregister manipulation. 5440 // 2. If the subvector is smaller than a vector register, then the insertion 5441 // must preserve the undisturbed elements of the register. We do this by 5442 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5443 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5444 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5445 // LMUL=1 type back into the larger vector (resolving to another subregister 5446 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5447 // to avoid allocating a large register group to hold our subvector. 5448 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5449 return Op; 5450 5451 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5452 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5453 // (in our case undisturbed). This means we can set up a subvector insertion 5454 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5455 // size of the subvector. 5456 MVT InterSubVT = VecVT; 5457 SDValue AlignedExtract = Vec; 5458 unsigned AlignedIdx = OrigIdx - RemIdx; 5459 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5460 InterSubVT = getLMUL1VT(VecVT); 5461 // Extract a subvector equal to the nearest full vector register type. This 5462 // should resolve to a EXTRACT_SUBREG instruction. 5463 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5464 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5465 } 5466 5467 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5468 // For scalable vectors this must be further multiplied by vscale. 5469 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5470 5471 SDValue Mask, VL; 5472 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5473 5474 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5475 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5476 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5477 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5478 5479 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5480 DAG.getUNDEF(InterSubVT), SubVec, 5481 DAG.getConstant(0, DL, XLenVT)); 5482 5483 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5484 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5485 5486 // If required, insert this subvector back into the correct vector register. 5487 // This should resolve to an INSERT_SUBREG instruction. 5488 if (VecVT.bitsGT(InterSubVT)) 5489 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5490 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5491 5492 // We might have bitcast from a mask type: cast back to the original type if 5493 // required. 5494 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5495 } 5496 5497 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5498 SelectionDAG &DAG) const { 5499 SDValue Vec = Op.getOperand(0); 5500 MVT SubVecVT = Op.getSimpleValueType(); 5501 MVT VecVT = Vec.getSimpleValueType(); 5502 5503 SDLoc DL(Op); 5504 MVT XLenVT = Subtarget.getXLenVT(); 5505 unsigned OrigIdx = Op.getConstantOperandVal(1); 5506 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5507 5508 // We don't have the ability to slide mask vectors down indexed by their i1 5509 // elements; the smallest we can do is i8. Often we are able to bitcast to 5510 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5511 // from a scalable one, we might not necessarily have enough scalable 5512 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5513 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5514 if (VecVT.getVectorMinNumElements() >= 8 && 5515 SubVecVT.getVectorMinNumElements() >= 8) { 5516 assert(OrigIdx % 8 == 0 && "Invalid index"); 5517 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5518 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5519 "Unexpected mask vector lowering"); 5520 OrigIdx /= 8; 5521 SubVecVT = 5522 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5523 SubVecVT.isScalableVector()); 5524 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5525 VecVT.isScalableVector()); 5526 Vec = DAG.getBitcast(VecVT, Vec); 5527 } else { 5528 // We can't slide this mask vector down, indexed by its i1 elements. 5529 // This poses a problem when we wish to extract a scalable vector which 5530 // can't be re-expressed as a larger type. Just choose the slow path and 5531 // extend to a larger type, then truncate back down. 5532 // TODO: We could probably improve this when extracting certain fixed 5533 // from fixed, where we can extract as i8 and shift the correct element 5534 // right to reach the desired subvector? 5535 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5536 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5537 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5538 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5539 Op.getOperand(1)); 5540 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5541 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5542 } 5543 } 5544 5545 // If the subvector vector is a fixed-length type, we cannot use subregister 5546 // manipulation to simplify the codegen; we don't know which register of a 5547 // LMUL group contains the specific subvector as we only know the minimum 5548 // register size. Therefore we must slide the vector group down the full 5549 // amount. 5550 if (SubVecVT.isFixedLengthVector()) { 5551 // With an index of 0 this is a cast-like subvector, which can be performed 5552 // with subregister operations. 5553 if (OrigIdx == 0) 5554 return Op; 5555 MVT ContainerVT = VecVT; 5556 if (VecVT.isFixedLengthVector()) { 5557 ContainerVT = getContainerForFixedLengthVector(VecVT); 5558 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5559 } 5560 SDValue Mask = 5561 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5562 // Set the vector length to only the number of elements we care about. This 5563 // avoids sliding down elements we're going to discard straight away. 5564 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5565 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5566 SDValue Slidedown = 5567 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5568 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5569 // Now we can use a cast-like subvector extract to get the result. 5570 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5571 DAG.getConstant(0, DL, XLenVT)); 5572 return DAG.getBitcast(Op.getValueType(), Slidedown); 5573 } 5574 5575 unsigned SubRegIdx, RemIdx; 5576 std::tie(SubRegIdx, RemIdx) = 5577 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5578 VecVT, SubVecVT, OrigIdx, TRI); 5579 5580 // If the Idx has been completely eliminated then this is a subvector extract 5581 // which naturally aligns to a vector register. These can easily be handled 5582 // using subregister manipulation. 5583 if (RemIdx == 0) 5584 return Op; 5585 5586 // Else we must shift our vector register directly to extract the subvector. 5587 // Do this using VSLIDEDOWN. 5588 5589 // If the vector type is an LMUL-group type, extract a subvector equal to the 5590 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5591 // instruction. 5592 MVT InterSubVT = VecVT; 5593 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5594 InterSubVT = getLMUL1VT(VecVT); 5595 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5596 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5597 } 5598 5599 // Slide this vector register down by the desired number of elements in order 5600 // to place the desired subvector starting at element 0. 5601 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5602 // For scalable vectors this must be further multiplied by vscale. 5603 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5604 5605 SDValue Mask, VL; 5606 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5607 SDValue Slidedown = 5608 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5609 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5610 5611 // Now the vector is in the right position, extract our final subvector. This 5612 // should resolve to a COPY. 5613 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5614 DAG.getConstant(0, DL, XLenVT)); 5615 5616 // We might have bitcast from a mask type: cast back to the original type if 5617 // required. 5618 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5619 } 5620 5621 // Lower step_vector to the vid instruction. Any non-identity step value must 5622 // be accounted for my manual expansion. 5623 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5624 SelectionDAG &DAG) const { 5625 SDLoc DL(Op); 5626 MVT VT = Op.getSimpleValueType(); 5627 MVT XLenVT = Subtarget.getXLenVT(); 5628 SDValue Mask, VL; 5629 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5630 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5631 uint64_t StepValImm = Op.getConstantOperandVal(0); 5632 if (StepValImm != 1) { 5633 if (isPowerOf2_64(StepValImm)) { 5634 SDValue StepVal = 5635 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5636 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5637 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5638 } else { 5639 SDValue StepVal = lowerScalarSplat( 5640 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5641 VL, VT, DL, DAG, Subtarget); 5642 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5643 } 5644 } 5645 return StepVec; 5646 } 5647 5648 // Implement vector_reverse using vrgather.vv with indices determined by 5649 // subtracting the id of each element from (VLMAX-1). This will convert 5650 // the indices like so: 5651 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5652 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5653 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5654 SelectionDAG &DAG) const { 5655 SDLoc DL(Op); 5656 MVT VecVT = Op.getSimpleValueType(); 5657 unsigned EltSize = VecVT.getScalarSizeInBits(); 5658 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5659 5660 unsigned MaxVLMAX = 0; 5661 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5662 if (VectorBitsMax != 0) 5663 MaxVLMAX = 5664 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5665 5666 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5667 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5668 5669 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5670 // to use vrgatherei16.vv. 5671 // TODO: It's also possible to use vrgatherei16.vv for other types to 5672 // decrease register width for the index calculation. 5673 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5674 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5675 // Reverse each half, then reassemble them in reverse order. 5676 // NOTE: It's also possible that after splitting that VLMAX no longer 5677 // requires vrgatherei16.vv. 5678 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5679 SDValue Lo, Hi; 5680 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5681 EVT LoVT, HiVT; 5682 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5683 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5684 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5685 // Reassemble the low and high pieces reversed. 5686 // FIXME: This is a CONCAT_VECTORS. 5687 SDValue Res = 5688 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5689 DAG.getIntPtrConstant(0, DL)); 5690 return DAG.getNode( 5691 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5692 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5693 } 5694 5695 // Just promote the int type to i16 which will double the LMUL. 5696 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5697 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5698 } 5699 5700 MVT XLenVT = Subtarget.getXLenVT(); 5701 SDValue Mask, VL; 5702 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5703 5704 // Calculate VLMAX-1 for the desired SEW. 5705 unsigned MinElts = VecVT.getVectorMinNumElements(); 5706 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5707 DAG.getConstant(MinElts, DL, XLenVT)); 5708 SDValue VLMinus1 = 5709 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5710 5711 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5712 bool IsRV32E64 = 5713 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5714 SDValue SplatVL; 5715 if (!IsRV32E64) 5716 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5717 else 5718 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5719 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5720 5721 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5722 SDValue Indices = 5723 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5724 5725 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5726 } 5727 5728 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5729 SelectionDAG &DAG) const { 5730 SDLoc DL(Op); 5731 SDValue V1 = Op.getOperand(0); 5732 SDValue V2 = Op.getOperand(1); 5733 MVT XLenVT = Subtarget.getXLenVT(); 5734 MVT VecVT = Op.getSimpleValueType(); 5735 5736 unsigned MinElts = VecVT.getVectorMinNumElements(); 5737 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5738 DAG.getConstant(MinElts, DL, XLenVT)); 5739 5740 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5741 SDValue DownOffset, UpOffset; 5742 if (ImmValue >= 0) { 5743 // The operand is a TargetConstant, we need to rebuild it as a regular 5744 // constant. 5745 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5746 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5747 } else { 5748 // The operand is a TargetConstant, we need to rebuild it as a regular 5749 // constant rather than negating the original operand. 5750 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5751 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5752 } 5753 5754 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5755 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax); 5756 5757 SDValue SlideDown = 5758 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5759 DownOffset, TrueMask, UpOffset); 5760 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5761 TrueMask, 5762 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5763 } 5764 5765 SDValue 5766 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5767 SelectionDAG &DAG) const { 5768 SDLoc DL(Op); 5769 auto *Load = cast<LoadSDNode>(Op); 5770 5771 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5772 Load->getMemoryVT(), 5773 *Load->getMemOperand()) && 5774 "Expecting a correctly-aligned load"); 5775 5776 MVT VT = Op.getSimpleValueType(); 5777 MVT XLenVT = Subtarget.getXLenVT(); 5778 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5779 5780 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5781 5782 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5783 SDValue IntID = DAG.getTargetConstant( 5784 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5785 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5786 if (!IsMaskOp) 5787 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5788 Ops.push_back(Load->getBasePtr()); 5789 Ops.push_back(VL); 5790 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5791 SDValue NewLoad = 5792 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5793 Load->getMemoryVT(), Load->getMemOperand()); 5794 5795 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5796 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5797 } 5798 5799 SDValue 5800 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5801 SelectionDAG &DAG) const { 5802 SDLoc DL(Op); 5803 auto *Store = cast<StoreSDNode>(Op); 5804 5805 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5806 Store->getMemoryVT(), 5807 *Store->getMemOperand()) && 5808 "Expecting a correctly-aligned store"); 5809 5810 SDValue StoreVal = Store->getValue(); 5811 MVT VT = StoreVal.getSimpleValueType(); 5812 MVT XLenVT = Subtarget.getXLenVT(); 5813 5814 // If the size less than a byte, we need to pad with zeros to make a byte. 5815 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5816 VT = MVT::v8i1; 5817 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5818 DAG.getConstant(0, DL, VT), StoreVal, 5819 DAG.getIntPtrConstant(0, DL)); 5820 } 5821 5822 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5823 5824 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5825 5826 SDValue NewValue = 5827 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5828 5829 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5830 SDValue IntID = DAG.getTargetConstant( 5831 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5832 return DAG.getMemIntrinsicNode( 5833 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5834 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5835 Store->getMemoryVT(), Store->getMemOperand()); 5836 } 5837 5838 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5839 SelectionDAG &DAG) const { 5840 SDLoc DL(Op); 5841 MVT VT = Op.getSimpleValueType(); 5842 5843 const auto *MemSD = cast<MemSDNode>(Op); 5844 EVT MemVT = MemSD->getMemoryVT(); 5845 MachineMemOperand *MMO = MemSD->getMemOperand(); 5846 SDValue Chain = MemSD->getChain(); 5847 SDValue BasePtr = MemSD->getBasePtr(); 5848 5849 SDValue Mask, PassThru, VL; 5850 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5851 Mask = VPLoad->getMask(); 5852 PassThru = DAG.getUNDEF(VT); 5853 VL = VPLoad->getVectorLength(); 5854 } else { 5855 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5856 Mask = MLoad->getMask(); 5857 PassThru = MLoad->getPassThru(); 5858 } 5859 5860 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5861 5862 MVT XLenVT = Subtarget.getXLenVT(); 5863 5864 MVT ContainerVT = VT; 5865 if (VT.isFixedLengthVector()) { 5866 ContainerVT = getContainerForFixedLengthVector(VT); 5867 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5868 if (!IsUnmasked) { 5869 MVT MaskVT = 5870 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5871 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5872 } 5873 } 5874 5875 if (!VL) 5876 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5877 5878 unsigned IntID = 5879 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5880 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5881 if (IsUnmasked) 5882 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5883 else 5884 Ops.push_back(PassThru); 5885 Ops.push_back(BasePtr); 5886 if (!IsUnmasked) 5887 Ops.push_back(Mask); 5888 Ops.push_back(VL); 5889 if (!IsUnmasked) 5890 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5891 5892 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5893 5894 SDValue Result = 5895 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5896 Chain = Result.getValue(1); 5897 5898 if (VT.isFixedLengthVector()) 5899 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5900 5901 return DAG.getMergeValues({Result, Chain}, DL); 5902 } 5903 5904 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5905 SelectionDAG &DAG) const { 5906 SDLoc DL(Op); 5907 5908 const auto *MemSD = cast<MemSDNode>(Op); 5909 EVT MemVT = MemSD->getMemoryVT(); 5910 MachineMemOperand *MMO = MemSD->getMemOperand(); 5911 SDValue Chain = MemSD->getChain(); 5912 SDValue BasePtr = MemSD->getBasePtr(); 5913 SDValue Val, Mask, VL; 5914 5915 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5916 Val = VPStore->getValue(); 5917 Mask = VPStore->getMask(); 5918 VL = VPStore->getVectorLength(); 5919 } else { 5920 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5921 Val = MStore->getValue(); 5922 Mask = MStore->getMask(); 5923 } 5924 5925 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5926 5927 MVT VT = Val.getSimpleValueType(); 5928 MVT XLenVT = Subtarget.getXLenVT(); 5929 5930 MVT ContainerVT = VT; 5931 if (VT.isFixedLengthVector()) { 5932 ContainerVT = getContainerForFixedLengthVector(VT); 5933 5934 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5935 if (!IsUnmasked) { 5936 MVT MaskVT = 5937 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5938 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5939 } 5940 } 5941 5942 if (!VL) 5943 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5944 5945 unsigned IntID = 5946 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5947 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5948 Ops.push_back(Val); 5949 Ops.push_back(BasePtr); 5950 if (!IsUnmasked) 5951 Ops.push_back(Mask); 5952 Ops.push_back(VL); 5953 5954 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5955 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5956 } 5957 5958 SDValue 5959 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5960 SelectionDAG &DAG) const { 5961 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5962 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5963 5964 MVT VT = Op.getSimpleValueType(); 5965 5966 SDValue Op1 = 5967 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5968 SDValue Op2 = 5969 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5970 5971 SDLoc DL(Op); 5972 SDValue VL = 5973 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5974 5975 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5976 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5977 5978 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5979 Op.getOperand(2), Mask, VL); 5980 5981 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5982 } 5983 5984 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5985 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5986 MVT VT = Op.getSimpleValueType(); 5987 5988 if (VT.getVectorElementType() == MVT::i1) 5989 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5990 5991 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5992 } 5993 5994 SDValue 5995 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5996 SelectionDAG &DAG) const { 5997 unsigned Opc; 5998 switch (Op.getOpcode()) { 5999 default: llvm_unreachable("Unexpected opcode!"); 6000 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 6001 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 6002 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 6003 } 6004 6005 return lowerToScalableOp(Op, DAG, Opc); 6006 } 6007 6008 // Lower vector ABS to smax(X, sub(0, X)). 6009 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 6010 SDLoc DL(Op); 6011 MVT VT = Op.getSimpleValueType(); 6012 SDValue X = Op.getOperand(0); 6013 6014 assert(VT.isFixedLengthVector() && "Unexpected type"); 6015 6016 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6017 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6018 6019 SDValue Mask, VL; 6020 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6021 6022 SDValue SplatZero = DAG.getNode( 6023 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6024 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6025 SDValue NegX = 6026 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6027 SDValue Max = 6028 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6029 6030 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6031 } 6032 6033 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6034 SDValue Op, SelectionDAG &DAG) const { 6035 SDLoc DL(Op); 6036 MVT VT = Op.getSimpleValueType(); 6037 SDValue Mag = Op.getOperand(0); 6038 SDValue Sign = Op.getOperand(1); 6039 assert(Mag.getValueType() == Sign.getValueType() && 6040 "Can only handle COPYSIGN with matching types."); 6041 6042 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6043 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6044 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6045 6046 SDValue Mask, VL; 6047 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6048 6049 SDValue CopySign = 6050 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6051 6052 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6053 } 6054 6055 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6056 SDValue Op, SelectionDAG &DAG) const { 6057 MVT VT = Op.getSimpleValueType(); 6058 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6059 6060 MVT I1ContainerVT = 6061 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6062 6063 SDValue CC = 6064 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6065 SDValue Op1 = 6066 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6067 SDValue Op2 = 6068 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6069 6070 SDLoc DL(Op); 6071 SDValue Mask, VL; 6072 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6073 6074 SDValue Select = 6075 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6076 6077 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6078 } 6079 6080 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6081 unsigned NewOpc, 6082 bool HasMask) const { 6083 MVT VT = Op.getSimpleValueType(); 6084 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6085 6086 // Create list of operands by converting existing ones to scalable types. 6087 SmallVector<SDValue, 6> Ops; 6088 for (const SDValue &V : Op->op_values()) { 6089 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6090 6091 // Pass through non-vector operands. 6092 if (!V.getValueType().isVector()) { 6093 Ops.push_back(V); 6094 continue; 6095 } 6096 6097 // "cast" fixed length vector to a scalable vector. 6098 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6099 "Only fixed length vectors are supported!"); 6100 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6101 } 6102 6103 SDLoc DL(Op); 6104 SDValue Mask, VL; 6105 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6106 if (HasMask) 6107 Ops.push_back(Mask); 6108 Ops.push_back(VL); 6109 6110 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6111 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6112 } 6113 6114 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6115 // * Operands of each node are assumed to be in the same order. 6116 // * The EVL operand is promoted from i32 to i64 on RV64. 6117 // * Fixed-length vectors are converted to their scalable-vector container 6118 // types. 6119 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6120 unsigned RISCVISDOpc) const { 6121 SDLoc DL(Op); 6122 MVT VT = Op.getSimpleValueType(); 6123 SmallVector<SDValue, 4> Ops; 6124 6125 for (const auto &OpIdx : enumerate(Op->ops())) { 6126 SDValue V = OpIdx.value(); 6127 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6128 // Pass through operands which aren't fixed-length vectors. 6129 if (!V.getValueType().isFixedLengthVector()) { 6130 Ops.push_back(V); 6131 continue; 6132 } 6133 // "cast" fixed length vector to a scalable vector. 6134 MVT OpVT = V.getSimpleValueType(); 6135 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6136 assert(useRVVForFixedLengthVectorVT(OpVT) && 6137 "Only fixed length vectors are supported!"); 6138 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6139 } 6140 6141 if (!VT.isFixedLengthVector()) 6142 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6143 6144 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6145 6146 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6147 6148 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6149 } 6150 6151 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6152 SelectionDAG &DAG) const { 6153 SDLoc DL(Op); 6154 MVT VT = Op.getSimpleValueType(); 6155 6156 SDValue Src = Op.getOperand(0); 6157 // NOTE: Mask is dropped. 6158 SDValue VL = Op.getOperand(2); 6159 6160 MVT ContainerVT = VT; 6161 if (VT.isFixedLengthVector()) { 6162 ContainerVT = getContainerForFixedLengthVector(VT); 6163 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6164 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6165 } 6166 6167 MVT XLenVT = Subtarget.getXLenVT(); 6168 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6169 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6170 DAG.getUNDEF(ContainerVT), Zero, VL); 6171 6172 SDValue SplatValue = 6173 DAG.getConstant(Op.getOpcode() == ISD::VP_ZEXT ? 1 : -1, DL, XLenVT); 6174 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6175 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6176 6177 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6178 Splat, ZeroSplat, VL); 6179 if (!VT.isFixedLengthVector()) 6180 return Result; 6181 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6182 } 6183 6184 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6185 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6186 unsigned RISCVISDOpc) const { 6187 SDLoc DL(Op); 6188 6189 SDValue Src = Op.getOperand(0); 6190 SDValue Mask = Op.getOperand(1); 6191 SDValue VL = Op.getOperand(2); 6192 6193 MVT DstVT = Op.getSimpleValueType(); 6194 MVT SrcVT = Src.getSimpleValueType(); 6195 if (DstVT.isFixedLengthVector()) { 6196 DstVT = getContainerForFixedLengthVector(DstVT); 6197 SrcVT = getContainerForFixedLengthVector(SrcVT); 6198 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6199 MVT MaskVT = MVT::getVectorVT(MVT::i1, DstVT.getVectorElementCount()); 6200 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6201 } 6202 6203 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6204 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6205 ? RISCVISD::VSEXT_VL 6206 : RISCVISD::VZEXT_VL; 6207 6208 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6209 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6210 6211 SDValue Result; 6212 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6213 if (SrcVT.isInteger()) { 6214 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6215 6216 // Do we need to do any pre-widening before converting? 6217 if (SrcEltSize == 1) { 6218 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6219 MVT XLenVT = Subtarget.getXLenVT(); 6220 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6221 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6222 DAG.getUNDEF(IntVT), Zero, VL); 6223 SDValue One = DAG.getConstant( 6224 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6225 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6226 DAG.getUNDEF(IntVT), One, VL); 6227 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6228 ZeroSplat, VL); 6229 } else if (DstEltSize > (2 * SrcEltSize)) { 6230 // Widen before converting. 6231 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6232 DstVT.getVectorElementCount()); 6233 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6234 } 6235 6236 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6237 } else { 6238 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6239 "Wrong input/output vector types"); 6240 6241 // Convert f16 to f32 then convert f32 to i64. 6242 if (DstEltSize > (2 * SrcEltSize)) { 6243 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6244 MVT InterimFVT = 6245 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6246 Src = 6247 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6248 } 6249 6250 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6251 } 6252 } else { // Narrowing + Conversion 6253 if (SrcVT.isInteger()) { 6254 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6255 // First do a narrowing convert to an FP type half the size, then round 6256 // the FP type to a small FP type if needed. 6257 6258 MVT InterimFVT = DstVT; 6259 if (SrcEltSize > (2 * DstEltSize)) { 6260 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6261 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6262 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6263 } 6264 6265 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6266 6267 if (InterimFVT != DstVT) { 6268 Src = Result; 6269 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6270 } 6271 } else { 6272 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6273 "Wrong input/output vector types"); 6274 // First do a narrowing conversion to an integer half the size, then 6275 // truncate if needed. 6276 6277 if (DstEltSize == 1) { 6278 // First convert to the same size integer, then convert to mask using 6279 // setcc. 6280 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6281 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6282 DstVT.getVectorElementCount()); 6283 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6284 6285 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6286 // otherwise the conversion was undefined. 6287 MVT XLenVT = Subtarget.getXLenVT(); 6288 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6289 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6290 DAG.getUNDEF(InterimIVT), SplatZero); 6291 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6292 DAG.getCondCode(ISD::SETNE), Mask, VL); 6293 } else { 6294 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6295 DstVT.getVectorElementCount()); 6296 6297 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6298 6299 while (InterimIVT != DstVT) { 6300 SrcEltSize /= 2; 6301 Src = Result; 6302 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6303 DstVT.getVectorElementCount()); 6304 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6305 Src, Mask, VL); 6306 } 6307 } 6308 } 6309 } 6310 6311 MVT VT = Op.getSimpleValueType(); 6312 if (!VT.isFixedLengthVector()) 6313 return Result; 6314 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6315 } 6316 6317 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6318 unsigned MaskOpc, 6319 unsigned VecOpc) const { 6320 MVT VT = Op.getSimpleValueType(); 6321 if (VT.getVectorElementType() != MVT::i1) 6322 return lowerVPOp(Op, DAG, VecOpc); 6323 6324 // It is safe to drop mask parameter as masked-off elements are undef. 6325 SDValue Op1 = Op->getOperand(0); 6326 SDValue Op2 = Op->getOperand(1); 6327 SDValue VL = Op->getOperand(3); 6328 6329 MVT ContainerVT = VT; 6330 const bool IsFixed = VT.isFixedLengthVector(); 6331 if (IsFixed) { 6332 ContainerVT = getContainerForFixedLengthVector(VT); 6333 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6334 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6335 } 6336 6337 SDLoc DL(Op); 6338 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6339 if (!IsFixed) 6340 return Val; 6341 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6342 } 6343 6344 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6345 // matched to a RVV indexed load. The RVV indexed load instructions only 6346 // support the "unsigned unscaled" addressing mode; indices are implicitly 6347 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6348 // signed or scaled indexing is extended to the XLEN value type and scaled 6349 // accordingly. 6350 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6351 SelectionDAG &DAG) const { 6352 SDLoc DL(Op); 6353 MVT VT = Op.getSimpleValueType(); 6354 6355 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6356 EVT MemVT = MemSD->getMemoryVT(); 6357 MachineMemOperand *MMO = MemSD->getMemOperand(); 6358 SDValue Chain = MemSD->getChain(); 6359 SDValue BasePtr = MemSD->getBasePtr(); 6360 6361 ISD::LoadExtType LoadExtType; 6362 SDValue Index, Mask, PassThru, VL; 6363 6364 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6365 Index = VPGN->getIndex(); 6366 Mask = VPGN->getMask(); 6367 PassThru = DAG.getUNDEF(VT); 6368 VL = VPGN->getVectorLength(); 6369 // VP doesn't support extending loads. 6370 LoadExtType = ISD::NON_EXTLOAD; 6371 } else { 6372 // Else it must be a MGATHER. 6373 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6374 Index = MGN->getIndex(); 6375 Mask = MGN->getMask(); 6376 PassThru = MGN->getPassThru(); 6377 LoadExtType = MGN->getExtensionType(); 6378 } 6379 6380 MVT IndexVT = Index.getSimpleValueType(); 6381 MVT XLenVT = Subtarget.getXLenVT(); 6382 6383 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6384 "Unexpected VTs!"); 6385 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6386 // Targets have to explicitly opt-in for extending vector loads. 6387 assert(LoadExtType == ISD::NON_EXTLOAD && 6388 "Unexpected extending MGATHER/VP_GATHER"); 6389 (void)LoadExtType; 6390 6391 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6392 // the selection of the masked intrinsics doesn't do this for us. 6393 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6394 6395 MVT ContainerVT = VT; 6396 if (VT.isFixedLengthVector()) { 6397 // We need to use the larger of the result and index type to determine the 6398 // scalable type to use so we don't increase LMUL for any operand/result. 6399 if (VT.bitsGE(IndexVT)) { 6400 ContainerVT = getContainerForFixedLengthVector(VT); 6401 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6402 ContainerVT.getVectorElementCount()); 6403 } else { 6404 IndexVT = getContainerForFixedLengthVector(IndexVT); 6405 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6406 IndexVT.getVectorElementCount()); 6407 } 6408 6409 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6410 6411 if (!IsUnmasked) { 6412 MVT MaskVT = 6413 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6414 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6415 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6416 } 6417 } 6418 6419 if (!VL) 6420 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6421 6422 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6423 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6424 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6425 VL); 6426 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6427 TrueMask, VL); 6428 } 6429 6430 unsigned IntID = 6431 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6432 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6433 if (IsUnmasked) 6434 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6435 else 6436 Ops.push_back(PassThru); 6437 Ops.push_back(BasePtr); 6438 Ops.push_back(Index); 6439 if (!IsUnmasked) 6440 Ops.push_back(Mask); 6441 Ops.push_back(VL); 6442 if (!IsUnmasked) 6443 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6444 6445 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6446 SDValue Result = 6447 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6448 Chain = Result.getValue(1); 6449 6450 if (VT.isFixedLengthVector()) 6451 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6452 6453 return DAG.getMergeValues({Result, Chain}, DL); 6454 } 6455 6456 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6457 // matched to a RVV indexed store. The RVV indexed store instructions only 6458 // support the "unsigned unscaled" addressing mode; indices are implicitly 6459 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6460 // signed or scaled indexing is extended to the XLEN value type and scaled 6461 // accordingly. 6462 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6463 SelectionDAG &DAG) const { 6464 SDLoc DL(Op); 6465 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6466 EVT MemVT = MemSD->getMemoryVT(); 6467 MachineMemOperand *MMO = MemSD->getMemOperand(); 6468 SDValue Chain = MemSD->getChain(); 6469 SDValue BasePtr = MemSD->getBasePtr(); 6470 6471 bool IsTruncatingStore = false; 6472 SDValue Index, Mask, Val, VL; 6473 6474 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6475 Index = VPSN->getIndex(); 6476 Mask = VPSN->getMask(); 6477 Val = VPSN->getValue(); 6478 VL = VPSN->getVectorLength(); 6479 // VP doesn't support truncating stores. 6480 IsTruncatingStore = false; 6481 } else { 6482 // Else it must be a MSCATTER. 6483 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6484 Index = MSN->getIndex(); 6485 Mask = MSN->getMask(); 6486 Val = MSN->getValue(); 6487 IsTruncatingStore = MSN->isTruncatingStore(); 6488 } 6489 6490 MVT VT = Val.getSimpleValueType(); 6491 MVT IndexVT = Index.getSimpleValueType(); 6492 MVT XLenVT = Subtarget.getXLenVT(); 6493 6494 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6495 "Unexpected VTs!"); 6496 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6497 // Targets have to explicitly opt-in for extending vector loads and 6498 // truncating vector stores. 6499 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6500 (void)IsTruncatingStore; 6501 6502 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6503 // the selection of the masked intrinsics doesn't do this for us. 6504 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6505 6506 MVT ContainerVT = VT; 6507 if (VT.isFixedLengthVector()) { 6508 // We need to use the larger of the value and index type to determine the 6509 // scalable type to use so we don't increase LMUL for any operand/result. 6510 if (VT.bitsGE(IndexVT)) { 6511 ContainerVT = getContainerForFixedLengthVector(VT); 6512 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6513 ContainerVT.getVectorElementCount()); 6514 } else { 6515 IndexVT = getContainerForFixedLengthVector(IndexVT); 6516 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6517 IndexVT.getVectorElementCount()); 6518 } 6519 6520 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6521 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6522 6523 if (!IsUnmasked) { 6524 MVT MaskVT = 6525 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6526 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6527 } 6528 } 6529 6530 if (!VL) 6531 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6532 6533 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6534 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6535 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6536 VL); 6537 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6538 TrueMask, VL); 6539 } 6540 6541 unsigned IntID = 6542 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6543 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6544 Ops.push_back(Val); 6545 Ops.push_back(BasePtr); 6546 Ops.push_back(Index); 6547 if (!IsUnmasked) 6548 Ops.push_back(Mask); 6549 Ops.push_back(VL); 6550 6551 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6552 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6553 } 6554 6555 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6556 SelectionDAG &DAG) const { 6557 const MVT XLenVT = Subtarget.getXLenVT(); 6558 SDLoc DL(Op); 6559 SDValue Chain = Op->getOperand(0); 6560 SDValue SysRegNo = DAG.getTargetConstant( 6561 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6562 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6563 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6564 6565 // Encoding used for rounding mode in RISCV differs from that used in 6566 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6567 // table, which consists of a sequence of 4-bit fields, each representing 6568 // corresponding FLT_ROUNDS mode. 6569 static const int Table = 6570 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6571 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6572 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6573 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6574 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6575 6576 SDValue Shift = 6577 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6578 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6579 DAG.getConstant(Table, DL, XLenVT), Shift); 6580 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6581 DAG.getConstant(7, DL, XLenVT)); 6582 6583 return DAG.getMergeValues({Masked, Chain}, DL); 6584 } 6585 6586 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6587 SelectionDAG &DAG) const { 6588 const MVT XLenVT = Subtarget.getXLenVT(); 6589 SDLoc DL(Op); 6590 SDValue Chain = Op->getOperand(0); 6591 SDValue RMValue = Op->getOperand(1); 6592 SDValue SysRegNo = DAG.getTargetConstant( 6593 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6594 6595 // Encoding used for rounding mode in RISCV differs from that used in 6596 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6597 // a table, which consists of a sequence of 4-bit fields, each representing 6598 // corresponding RISCV mode. 6599 static const unsigned Table = 6600 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6601 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6602 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6603 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6604 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6605 6606 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6607 DAG.getConstant(2, DL, XLenVT)); 6608 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6609 DAG.getConstant(Table, DL, XLenVT), Shift); 6610 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6611 DAG.getConstant(0x7, DL, XLenVT)); 6612 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6613 RMValue); 6614 } 6615 6616 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6617 switch (IntNo) { 6618 default: 6619 llvm_unreachable("Unexpected Intrinsic"); 6620 case Intrinsic::riscv_bcompress: 6621 return RISCVISD::BCOMPRESSW; 6622 case Intrinsic::riscv_bdecompress: 6623 return RISCVISD::BDECOMPRESSW; 6624 case Intrinsic::riscv_bfp: 6625 return RISCVISD::BFPW; 6626 case Intrinsic::riscv_fsl: 6627 return RISCVISD::FSLW; 6628 case Intrinsic::riscv_fsr: 6629 return RISCVISD::FSRW; 6630 } 6631 } 6632 6633 // Converts the given intrinsic to a i64 operation with any extension. 6634 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6635 unsigned IntNo) { 6636 SDLoc DL(N); 6637 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6638 // Deal with the Instruction Operands 6639 SmallVector<SDValue, 3> NewOps; 6640 for (SDValue Op : drop_begin(N->ops())) 6641 // Promote the operand to i64 type 6642 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6643 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6644 // ReplaceNodeResults requires we maintain the same type for the return value. 6645 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6646 } 6647 6648 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6649 // form of the given Opcode. 6650 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6651 switch (Opcode) { 6652 default: 6653 llvm_unreachable("Unexpected opcode"); 6654 case ISD::SHL: 6655 return RISCVISD::SLLW; 6656 case ISD::SRA: 6657 return RISCVISD::SRAW; 6658 case ISD::SRL: 6659 return RISCVISD::SRLW; 6660 case ISD::SDIV: 6661 return RISCVISD::DIVW; 6662 case ISD::UDIV: 6663 return RISCVISD::DIVUW; 6664 case ISD::UREM: 6665 return RISCVISD::REMUW; 6666 case ISD::ROTL: 6667 return RISCVISD::ROLW; 6668 case ISD::ROTR: 6669 return RISCVISD::RORW; 6670 } 6671 } 6672 6673 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6674 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6675 // otherwise be promoted to i64, making it difficult to select the 6676 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6677 // type i8/i16/i32 is lost. 6678 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6679 unsigned ExtOpc = ISD::ANY_EXTEND) { 6680 SDLoc DL(N); 6681 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6682 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6683 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6684 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6685 // ReplaceNodeResults requires we maintain the same type for the return value. 6686 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6687 } 6688 6689 // Converts the given 32-bit operation to a i64 operation with signed extension 6690 // semantic to reduce the signed extension instructions. 6691 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6692 SDLoc DL(N); 6693 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6694 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6695 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6696 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6697 DAG.getValueType(MVT::i32)); 6698 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6699 } 6700 6701 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6702 SmallVectorImpl<SDValue> &Results, 6703 SelectionDAG &DAG) const { 6704 SDLoc DL(N); 6705 switch (N->getOpcode()) { 6706 default: 6707 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6708 case ISD::STRICT_FP_TO_SINT: 6709 case ISD::STRICT_FP_TO_UINT: 6710 case ISD::FP_TO_SINT: 6711 case ISD::FP_TO_UINT: { 6712 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6713 "Unexpected custom legalisation"); 6714 bool IsStrict = N->isStrictFPOpcode(); 6715 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6716 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6717 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6718 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6719 TargetLowering::TypeSoftenFloat) { 6720 if (!isTypeLegal(Op0.getValueType())) 6721 return; 6722 if (IsStrict) { 6723 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6724 : RISCVISD::STRICT_FCVT_WU_RV64; 6725 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6726 SDValue Res = DAG.getNode( 6727 Opc, DL, VTs, N->getOperand(0), Op0, 6728 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6729 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6730 Results.push_back(Res.getValue(1)); 6731 return; 6732 } 6733 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6734 SDValue Res = 6735 DAG.getNode(Opc, DL, MVT::i64, Op0, 6736 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6737 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6738 return; 6739 } 6740 // If the FP type needs to be softened, emit a library call using the 'si' 6741 // version. If we left it to default legalization we'd end up with 'di'. If 6742 // the FP type doesn't need to be softened just let generic type 6743 // legalization promote the result type. 6744 RTLIB::Libcall LC; 6745 if (IsSigned) 6746 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6747 else 6748 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6749 MakeLibCallOptions CallOptions; 6750 EVT OpVT = Op0.getValueType(); 6751 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6752 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6753 SDValue Result; 6754 std::tie(Result, Chain) = 6755 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6756 Results.push_back(Result); 6757 if (IsStrict) 6758 Results.push_back(Chain); 6759 break; 6760 } 6761 case ISD::READCYCLECOUNTER: { 6762 assert(!Subtarget.is64Bit() && 6763 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6764 6765 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6766 SDValue RCW = 6767 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6768 6769 Results.push_back( 6770 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6771 Results.push_back(RCW.getValue(2)); 6772 break; 6773 } 6774 case ISD::MUL: { 6775 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6776 unsigned XLen = Subtarget.getXLen(); 6777 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6778 if (Size > XLen) { 6779 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6780 SDValue LHS = N->getOperand(0); 6781 SDValue RHS = N->getOperand(1); 6782 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6783 6784 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6785 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6786 // We need exactly one side to be unsigned. 6787 if (LHSIsU == RHSIsU) 6788 return; 6789 6790 auto MakeMULPair = [&](SDValue S, SDValue U) { 6791 MVT XLenVT = Subtarget.getXLenVT(); 6792 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6793 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6794 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6795 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6796 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6797 }; 6798 6799 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6800 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6801 6802 // The other operand should be signed, but still prefer MULH when 6803 // possible. 6804 if (RHSIsU && LHSIsS && !RHSIsS) 6805 Results.push_back(MakeMULPair(LHS, RHS)); 6806 else if (LHSIsU && RHSIsS && !LHSIsS) 6807 Results.push_back(MakeMULPair(RHS, LHS)); 6808 6809 return; 6810 } 6811 LLVM_FALLTHROUGH; 6812 } 6813 case ISD::ADD: 6814 case ISD::SUB: 6815 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6816 "Unexpected custom legalisation"); 6817 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6818 break; 6819 case ISD::SHL: 6820 case ISD::SRA: 6821 case ISD::SRL: 6822 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6823 "Unexpected custom legalisation"); 6824 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6825 Results.push_back(customLegalizeToWOp(N, DAG)); 6826 break; 6827 } 6828 6829 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6830 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6831 // shift amount. 6832 if (N->getOpcode() == ISD::SHL) { 6833 SDLoc DL(N); 6834 SDValue NewOp0 = 6835 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6836 SDValue NewOp1 = 6837 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6838 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6839 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6840 DAG.getValueType(MVT::i32)); 6841 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6842 } 6843 6844 break; 6845 case ISD::ROTL: 6846 case ISD::ROTR: 6847 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6848 "Unexpected custom legalisation"); 6849 Results.push_back(customLegalizeToWOp(N, DAG)); 6850 break; 6851 case ISD::CTTZ: 6852 case ISD::CTTZ_ZERO_UNDEF: 6853 case ISD::CTLZ: 6854 case ISD::CTLZ_ZERO_UNDEF: { 6855 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6856 "Unexpected custom legalisation"); 6857 6858 SDValue NewOp0 = 6859 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6860 bool IsCTZ = 6861 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6862 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6863 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6864 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6865 return; 6866 } 6867 case ISD::SDIV: 6868 case ISD::UDIV: 6869 case ISD::UREM: { 6870 MVT VT = N->getSimpleValueType(0); 6871 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6872 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6873 "Unexpected custom legalisation"); 6874 // Don't promote division/remainder by constant since we should expand those 6875 // to multiply by magic constant. 6876 // FIXME: What if the expansion is disabled for minsize. 6877 if (N->getOperand(1).getOpcode() == ISD::Constant) 6878 return; 6879 6880 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6881 // the upper 32 bits. For other types we need to sign or zero extend 6882 // based on the opcode. 6883 unsigned ExtOpc = ISD::ANY_EXTEND; 6884 if (VT != MVT::i32) 6885 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6886 : ISD::ZERO_EXTEND; 6887 6888 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6889 break; 6890 } 6891 case ISD::UADDO: 6892 case ISD::USUBO: { 6893 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6894 "Unexpected custom legalisation"); 6895 bool IsAdd = N->getOpcode() == ISD::UADDO; 6896 // Create an ADDW or SUBW. 6897 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6898 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6899 SDValue Res = 6900 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6901 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6902 DAG.getValueType(MVT::i32)); 6903 6904 SDValue Overflow; 6905 if (IsAdd && isOneConstant(RHS)) { 6906 // Special case uaddo X, 1 overflowed if the addition result is 0. 6907 // FIXME: We can do this for any constant RHS by using (X + C) < C. 6908 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6909 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6910 } else { 6911 // Sign extend the LHS and perform an unsigned compare with the ADDW 6912 // result. Since the inputs are sign extended from i32, this is equivalent 6913 // to comparing the lower 32 bits. 6914 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6915 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6916 IsAdd ? ISD::SETULT : ISD::SETUGT); 6917 } 6918 6919 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6920 Results.push_back(Overflow); 6921 return; 6922 } 6923 case ISD::UADDSAT: 6924 case ISD::USUBSAT: { 6925 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6926 "Unexpected custom legalisation"); 6927 if (Subtarget.hasStdExtZbb()) { 6928 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6929 // sign extend allows overflow of the lower 32 bits to be detected on 6930 // the promoted size. 6931 SDValue LHS = 6932 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6933 SDValue RHS = 6934 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6935 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6936 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6937 return; 6938 } 6939 6940 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6941 // promotion for UADDO/USUBO. 6942 Results.push_back(expandAddSubSat(N, DAG)); 6943 return; 6944 } 6945 case ISD::ABS: { 6946 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6947 "Unexpected custom legalisation"); 6948 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6949 6950 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6951 6952 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6953 6954 // Freeze the source so we can increase it's use count. 6955 Src = DAG.getFreeze(Src); 6956 6957 // Copy sign bit to all bits using the sraiw pattern. 6958 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6959 DAG.getValueType(MVT::i32)); 6960 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6961 DAG.getConstant(31, DL, MVT::i64)); 6962 6963 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6964 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6965 6966 // NOTE: The result is only required to be anyextended, but sext is 6967 // consistent with type legalization of sub. 6968 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6969 DAG.getValueType(MVT::i32)); 6970 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6971 return; 6972 } 6973 case ISD::BITCAST: { 6974 EVT VT = N->getValueType(0); 6975 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6976 SDValue Op0 = N->getOperand(0); 6977 EVT Op0VT = Op0.getValueType(); 6978 MVT XLenVT = Subtarget.getXLenVT(); 6979 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6980 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6981 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6982 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6983 Subtarget.hasStdExtF()) { 6984 SDValue FPConv = 6985 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6986 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6987 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6988 isTypeLegal(Op0VT)) { 6989 // Custom-legalize bitcasts from fixed-length vector types to illegal 6990 // scalar types in order to improve codegen. Bitcast the vector to a 6991 // one-element vector type whose element type is the same as the result 6992 // type, and extract the first element. 6993 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6994 if (isTypeLegal(BVT)) { 6995 SDValue BVec = DAG.getBitcast(BVT, Op0); 6996 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6997 DAG.getConstant(0, DL, XLenVT))); 6998 } 6999 } 7000 break; 7001 } 7002 case RISCVISD::GREV: 7003 case RISCVISD::GORC: 7004 case RISCVISD::SHFL: { 7005 MVT VT = N->getSimpleValueType(0); 7006 MVT XLenVT = Subtarget.getXLenVT(); 7007 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7008 "Unexpected custom legalisation"); 7009 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7010 assert((Subtarget.hasStdExtZbp() || 7011 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7012 N->getConstantOperandVal(1) == 7)) && 7013 "Unexpected extension"); 7014 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7015 SDValue NewOp1 = 7016 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7017 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7018 // ReplaceNodeResults requires we maintain the same type for the return 7019 // value. 7020 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7021 break; 7022 } 7023 case ISD::BSWAP: 7024 case ISD::BITREVERSE: { 7025 MVT VT = N->getSimpleValueType(0); 7026 MVT XLenVT = Subtarget.getXLenVT(); 7027 assert((VT == MVT::i8 || VT == MVT::i16 || 7028 (VT == MVT::i32 && Subtarget.is64Bit())) && 7029 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7030 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7031 unsigned Imm = VT.getSizeInBits() - 1; 7032 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7033 if (N->getOpcode() == ISD::BSWAP) 7034 Imm &= ~0x7U; 7035 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7036 DAG.getConstant(Imm, DL, XLenVT)); 7037 // ReplaceNodeResults requires we maintain the same type for the return 7038 // value. 7039 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7040 break; 7041 } 7042 case ISD::FSHL: 7043 case ISD::FSHR: { 7044 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7045 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7046 SDValue NewOp0 = 7047 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7048 SDValue NewOp1 = 7049 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7050 SDValue NewShAmt = 7051 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7052 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7053 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7054 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7055 DAG.getConstant(0x1f, DL, MVT::i64)); 7056 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7057 // instruction use different orders. fshl will return its first operand for 7058 // shift of zero, fshr will return its second operand. fsl and fsr both 7059 // return rs1 so the ISD nodes need to have different operand orders. 7060 // Shift amount is in rs2. 7061 unsigned Opc = RISCVISD::FSLW; 7062 if (N->getOpcode() == ISD::FSHR) { 7063 std::swap(NewOp0, NewOp1); 7064 Opc = RISCVISD::FSRW; 7065 } 7066 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7067 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7068 break; 7069 } 7070 case ISD::EXTRACT_VECTOR_ELT: { 7071 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7072 // type is illegal (currently only vXi64 RV32). 7073 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7074 // transferred to the destination register. We issue two of these from the 7075 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7076 // first element. 7077 SDValue Vec = N->getOperand(0); 7078 SDValue Idx = N->getOperand(1); 7079 7080 // The vector type hasn't been legalized yet so we can't issue target 7081 // specific nodes if it needs legalization. 7082 // FIXME: We would manually legalize if it's important. 7083 if (!isTypeLegal(Vec.getValueType())) 7084 return; 7085 7086 MVT VecVT = Vec.getSimpleValueType(); 7087 7088 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7089 VecVT.getVectorElementType() == MVT::i64 && 7090 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7091 7092 // If this is a fixed vector, we need to convert it to a scalable vector. 7093 MVT ContainerVT = VecVT; 7094 if (VecVT.isFixedLengthVector()) { 7095 ContainerVT = getContainerForFixedLengthVector(VecVT); 7096 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7097 } 7098 7099 MVT XLenVT = Subtarget.getXLenVT(); 7100 7101 // Use a VL of 1 to avoid processing more elements than we need. 7102 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 7103 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7104 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 7105 7106 // Unless the index is known to be 0, we must slide the vector down to get 7107 // the desired element into index 0. 7108 if (!isNullConstant(Idx)) { 7109 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7110 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7111 } 7112 7113 // Extract the lower XLEN bits of the correct vector element. 7114 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7115 7116 // To extract the upper XLEN bits of the vector element, shift the first 7117 // element right by 32 bits and re-extract the lower XLEN bits. 7118 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7119 DAG.getUNDEF(ContainerVT), 7120 DAG.getConstant(32, DL, XLenVT), VL); 7121 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7122 ThirtyTwoV, Mask, VL); 7123 7124 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7125 7126 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7127 break; 7128 } 7129 case ISD::INTRINSIC_WO_CHAIN: { 7130 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7131 switch (IntNo) { 7132 default: 7133 llvm_unreachable( 7134 "Don't know how to custom type legalize this intrinsic!"); 7135 case Intrinsic::riscv_grev: 7136 case Intrinsic::riscv_gorc: { 7137 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7138 "Unexpected custom legalisation"); 7139 SDValue NewOp1 = 7140 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7141 SDValue NewOp2 = 7142 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7143 unsigned Opc = 7144 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7145 // If the control is a constant, promote the node by clearing any extra 7146 // bits bits in the control. isel will form greviw/gorciw if the result is 7147 // sign extended. 7148 if (isa<ConstantSDNode>(NewOp2)) { 7149 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7150 DAG.getConstant(0x1f, DL, MVT::i64)); 7151 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7152 } 7153 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7154 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7155 break; 7156 } 7157 case Intrinsic::riscv_bcompress: 7158 case Intrinsic::riscv_bdecompress: 7159 case Intrinsic::riscv_bfp: 7160 case Intrinsic::riscv_fsl: 7161 case Intrinsic::riscv_fsr: { 7162 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7163 "Unexpected custom legalisation"); 7164 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7165 break; 7166 } 7167 case Intrinsic::riscv_orc_b: { 7168 // Lower to the GORCI encoding for orc.b with the operand extended. 7169 SDValue NewOp = 7170 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7171 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7172 DAG.getConstant(7, DL, MVT::i64)); 7173 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7174 return; 7175 } 7176 case Intrinsic::riscv_shfl: 7177 case Intrinsic::riscv_unshfl: { 7178 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7179 "Unexpected custom legalisation"); 7180 SDValue NewOp1 = 7181 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7182 SDValue NewOp2 = 7183 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7184 unsigned Opc = 7185 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7186 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7187 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7188 // will be shuffled the same way as the lower 32 bit half, but the two 7189 // halves won't cross. 7190 if (isa<ConstantSDNode>(NewOp2)) { 7191 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7192 DAG.getConstant(0xf, DL, MVT::i64)); 7193 Opc = 7194 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7195 } 7196 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7197 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7198 break; 7199 } 7200 case Intrinsic::riscv_vmv_x_s: { 7201 EVT VT = N->getValueType(0); 7202 MVT XLenVT = Subtarget.getXLenVT(); 7203 if (VT.bitsLT(XLenVT)) { 7204 // Simple case just extract using vmv.x.s and truncate. 7205 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7206 Subtarget.getXLenVT(), N->getOperand(1)); 7207 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7208 return; 7209 } 7210 7211 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7212 "Unexpected custom legalization"); 7213 7214 // We need to do the move in two steps. 7215 SDValue Vec = N->getOperand(1); 7216 MVT VecVT = Vec.getSimpleValueType(); 7217 7218 // First extract the lower XLEN bits of the element. 7219 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7220 7221 // To extract the upper XLEN bits of the vector element, shift the first 7222 // element right by 32 bits and re-extract the lower XLEN bits. 7223 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7224 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7225 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 7226 SDValue ThirtyTwoV = 7227 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7228 DAG.getConstant(32, DL, XLenVT), VL); 7229 SDValue LShr32 = 7230 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7231 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7232 7233 Results.push_back( 7234 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7235 break; 7236 } 7237 } 7238 break; 7239 } 7240 case ISD::VECREDUCE_ADD: 7241 case ISD::VECREDUCE_AND: 7242 case ISD::VECREDUCE_OR: 7243 case ISD::VECREDUCE_XOR: 7244 case ISD::VECREDUCE_SMAX: 7245 case ISD::VECREDUCE_UMAX: 7246 case ISD::VECREDUCE_SMIN: 7247 case ISD::VECREDUCE_UMIN: 7248 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7249 Results.push_back(V); 7250 break; 7251 case ISD::VP_REDUCE_ADD: 7252 case ISD::VP_REDUCE_AND: 7253 case ISD::VP_REDUCE_OR: 7254 case ISD::VP_REDUCE_XOR: 7255 case ISD::VP_REDUCE_SMAX: 7256 case ISD::VP_REDUCE_UMAX: 7257 case ISD::VP_REDUCE_SMIN: 7258 case ISD::VP_REDUCE_UMIN: 7259 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7260 Results.push_back(V); 7261 break; 7262 case ISD::FLT_ROUNDS_: { 7263 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7264 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7265 Results.push_back(Res.getValue(0)); 7266 Results.push_back(Res.getValue(1)); 7267 break; 7268 } 7269 } 7270 } 7271 7272 // A structure to hold one of the bit-manipulation patterns below. Together, a 7273 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7274 // (or (and (shl x, 1), 0xAAAAAAAA), 7275 // (and (srl x, 1), 0x55555555)) 7276 struct RISCVBitmanipPat { 7277 SDValue Op; 7278 unsigned ShAmt; 7279 bool IsSHL; 7280 7281 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7282 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7283 } 7284 }; 7285 7286 // Matches patterns of the form 7287 // (and (shl x, C2), (C1 << C2)) 7288 // (and (srl x, C2), C1) 7289 // (shl (and x, C1), C2) 7290 // (srl (and x, (C1 << C2)), C2) 7291 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7292 // The expected masks for each shift amount are specified in BitmanipMasks where 7293 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7294 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7295 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7296 // XLen is 64. 7297 static Optional<RISCVBitmanipPat> 7298 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7299 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7300 "Unexpected number of masks"); 7301 Optional<uint64_t> Mask; 7302 // Optionally consume a mask around the shift operation. 7303 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7304 Mask = Op.getConstantOperandVal(1); 7305 Op = Op.getOperand(0); 7306 } 7307 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7308 return None; 7309 bool IsSHL = Op.getOpcode() == ISD::SHL; 7310 7311 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7312 return None; 7313 uint64_t ShAmt = Op.getConstantOperandVal(1); 7314 7315 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7316 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7317 return None; 7318 // If we don't have enough masks for 64 bit, then we must be trying to 7319 // match SHFL so we're only allowed to shift 1/4 of the width. 7320 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7321 return None; 7322 7323 SDValue Src = Op.getOperand(0); 7324 7325 // The expected mask is shifted left when the AND is found around SHL 7326 // patterns. 7327 // ((x >> 1) & 0x55555555) 7328 // ((x << 1) & 0xAAAAAAAA) 7329 bool SHLExpMask = IsSHL; 7330 7331 if (!Mask) { 7332 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7333 // the mask is all ones: consume that now. 7334 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7335 Mask = Src.getConstantOperandVal(1); 7336 Src = Src.getOperand(0); 7337 // The expected mask is now in fact shifted left for SRL, so reverse the 7338 // decision. 7339 // ((x & 0xAAAAAAAA) >> 1) 7340 // ((x & 0x55555555) << 1) 7341 SHLExpMask = !SHLExpMask; 7342 } else { 7343 // Use a default shifted mask of all-ones if there's no AND, truncated 7344 // down to the expected width. This simplifies the logic later on. 7345 Mask = maskTrailingOnes<uint64_t>(Width); 7346 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7347 } 7348 } 7349 7350 unsigned MaskIdx = Log2_32(ShAmt); 7351 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7352 7353 if (SHLExpMask) 7354 ExpMask <<= ShAmt; 7355 7356 if (Mask != ExpMask) 7357 return None; 7358 7359 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7360 } 7361 7362 // Matches any of the following bit-manipulation patterns: 7363 // (and (shl x, 1), (0x55555555 << 1)) 7364 // (and (srl x, 1), 0x55555555) 7365 // (shl (and x, 0x55555555), 1) 7366 // (srl (and x, (0x55555555 << 1)), 1) 7367 // where the shift amount and mask may vary thus: 7368 // [1] = 0x55555555 / 0xAAAAAAAA 7369 // [2] = 0x33333333 / 0xCCCCCCCC 7370 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7371 // [8] = 0x00FF00FF / 0xFF00FF00 7372 // [16] = 0x0000FFFF / 0xFFFFFFFF 7373 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7374 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7375 // These are the unshifted masks which we use to match bit-manipulation 7376 // patterns. They may be shifted left in certain circumstances. 7377 static const uint64_t BitmanipMasks[] = { 7378 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7379 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7380 7381 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7382 } 7383 7384 // Match the following pattern as a GREVI(W) operation 7385 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7386 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7387 const RISCVSubtarget &Subtarget) { 7388 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7389 EVT VT = Op.getValueType(); 7390 7391 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7392 auto LHS = matchGREVIPat(Op.getOperand(0)); 7393 auto RHS = matchGREVIPat(Op.getOperand(1)); 7394 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7395 SDLoc DL(Op); 7396 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7397 DAG.getConstant(LHS->ShAmt, DL, VT)); 7398 } 7399 } 7400 return SDValue(); 7401 } 7402 7403 // Matches any the following pattern as a GORCI(W) operation 7404 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7405 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7406 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7407 // Note that with the variant of 3., 7408 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7409 // the inner pattern will first be matched as GREVI and then the outer 7410 // pattern will be matched to GORC via the first rule above. 7411 // 4. (or (rotl/rotr x, bitwidth/2), x) 7412 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7413 const RISCVSubtarget &Subtarget) { 7414 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7415 EVT VT = Op.getValueType(); 7416 7417 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7418 SDLoc DL(Op); 7419 SDValue Op0 = Op.getOperand(0); 7420 SDValue Op1 = Op.getOperand(1); 7421 7422 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7423 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7424 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7425 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7426 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7427 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7428 if ((Reverse.getOpcode() == ISD::ROTL || 7429 Reverse.getOpcode() == ISD::ROTR) && 7430 Reverse.getOperand(0) == X && 7431 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7432 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7433 if (RotAmt == (VT.getSizeInBits() / 2)) 7434 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7435 DAG.getConstant(RotAmt, DL, VT)); 7436 } 7437 return SDValue(); 7438 }; 7439 7440 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7441 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7442 return V; 7443 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7444 return V; 7445 7446 // OR is commutable so canonicalize its OR operand to the left 7447 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7448 std::swap(Op0, Op1); 7449 if (Op0.getOpcode() != ISD::OR) 7450 return SDValue(); 7451 SDValue OrOp0 = Op0.getOperand(0); 7452 SDValue OrOp1 = Op0.getOperand(1); 7453 auto LHS = matchGREVIPat(OrOp0); 7454 // OR is commutable so swap the operands and try again: x might have been 7455 // on the left 7456 if (!LHS) { 7457 std::swap(OrOp0, OrOp1); 7458 LHS = matchGREVIPat(OrOp0); 7459 } 7460 auto RHS = matchGREVIPat(Op1); 7461 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7462 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7463 DAG.getConstant(LHS->ShAmt, DL, VT)); 7464 } 7465 } 7466 return SDValue(); 7467 } 7468 7469 // Matches any of the following bit-manipulation patterns: 7470 // (and (shl x, 1), (0x22222222 << 1)) 7471 // (and (srl x, 1), 0x22222222) 7472 // (shl (and x, 0x22222222), 1) 7473 // (srl (and x, (0x22222222 << 1)), 1) 7474 // where the shift amount and mask may vary thus: 7475 // [1] = 0x22222222 / 0x44444444 7476 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7477 // [4] = 0x00F000F0 / 0x0F000F00 7478 // [8] = 0x0000FF00 / 0x00FF0000 7479 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7480 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7481 // These are the unshifted masks which we use to match bit-manipulation 7482 // patterns. They may be shifted left in certain circumstances. 7483 static const uint64_t BitmanipMasks[] = { 7484 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7485 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7486 7487 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7488 } 7489 7490 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7491 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7492 const RISCVSubtarget &Subtarget) { 7493 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7494 EVT VT = Op.getValueType(); 7495 7496 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7497 return SDValue(); 7498 7499 SDValue Op0 = Op.getOperand(0); 7500 SDValue Op1 = Op.getOperand(1); 7501 7502 // Or is commutable so canonicalize the second OR to the LHS. 7503 if (Op0.getOpcode() != ISD::OR) 7504 std::swap(Op0, Op1); 7505 if (Op0.getOpcode() != ISD::OR) 7506 return SDValue(); 7507 7508 // We found an inner OR, so our operands are the operands of the inner OR 7509 // and the other operand of the outer OR. 7510 SDValue A = Op0.getOperand(0); 7511 SDValue B = Op0.getOperand(1); 7512 SDValue C = Op1; 7513 7514 auto Match1 = matchSHFLPat(A); 7515 auto Match2 = matchSHFLPat(B); 7516 7517 // If neither matched, we failed. 7518 if (!Match1 && !Match2) 7519 return SDValue(); 7520 7521 // We had at least one match. if one failed, try the remaining C operand. 7522 if (!Match1) { 7523 std::swap(A, C); 7524 Match1 = matchSHFLPat(A); 7525 if (!Match1) 7526 return SDValue(); 7527 } else if (!Match2) { 7528 std::swap(B, C); 7529 Match2 = matchSHFLPat(B); 7530 if (!Match2) 7531 return SDValue(); 7532 } 7533 assert(Match1 && Match2); 7534 7535 // Make sure our matches pair up. 7536 if (!Match1->formsPairWith(*Match2)) 7537 return SDValue(); 7538 7539 // All the remains is to make sure C is an AND with the same input, that masks 7540 // out the bits that are being shuffled. 7541 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7542 C.getOperand(0) != Match1->Op) 7543 return SDValue(); 7544 7545 uint64_t Mask = C.getConstantOperandVal(1); 7546 7547 static const uint64_t BitmanipMasks[] = { 7548 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7549 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7550 }; 7551 7552 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7553 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7554 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7555 7556 if (Mask != ExpMask) 7557 return SDValue(); 7558 7559 SDLoc DL(Op); 7560 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7561 DAG.getConstant(Match1->ShAmt, DL, VT)); 7562 } 7563 7564 // Optimize (add (shl x, c0), (shl y, c1)) -> 7565 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7566 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7567 const RISCVSubtarget &Subtarget) { 7568 // Perform this optimization only in the zba extension. 7569 if (!Subtarget.hasStdExtZba()) 7570 return SDValue(); 7571 7572 // Skip for vector types and larger types. 7573 EVT VT = N->getValueType(0); 7574 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7575 return SDValue(); 7576 7577 // The two operand nodes must be SHL and have no other use. 7578 SDValue N0 = N->getOperand(0); 7579 SDValue N1 = N->getOperand(1); 7580 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7581 !N0->hasOneUse() || !N1->hasOneUse()) 7582 return SDValue(); 7583 7584 // Check c0 and c1. 7585 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7586 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7587 if (!N0C || !N1C) 7588 return SDValue(); 7589 int64_t C0 = N0C->getSExtValue(); 7590 int64_t C1 = N1C->getSExtValue(); 7591 if (C0 <= 0 || C1 <= 0) 7592 return SDValue(); 7593 7594 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7595 int64_t Bits = std::min(C0, C1); 7596 int64_t Diff = std::abs(C0 - C1); 7597 if (Diff != 1 && Diff != 2 && Diff != 3) 7598 return SDValue(); 7599 7600 // Build nodes. 7601 SDLoc DL(N); 7602 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7603 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7604 SDValue NA0 = 7605 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7606 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7607 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7608 } 7609 7610 // Combine 7611 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7612 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7613 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7614 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7615 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7616 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7617 // The grev patterns represents BSWAP. 7618 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7619 // off the grev. 7620 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7621 const RISCVSubtarget &Subtarget) { 7622 bool IsWInstruction = 7623 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7624 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7625 IsWInstruction) && 7626 "Unexpected opcode!"); 7627 SDValue Src = N->getOperand(0); 7628 EVT VT = N->getValueType(0); 7629 SDLoc DL(N); 7630 7631 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7632 return SDValue(); 7633 7634 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7635 !isa<ConstantSDNode>(Src.getOperand(1))) 7636 return SDValue(); 7637 7638 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7639 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7640 7641 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7642 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7643 unsigned ShAmt1 = N->getConstantOperandVal(1); 7644 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7645 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7646 return SDValue(); 7647 7648 Src = Src.getOperand(0); 7649 7650 // Toggle bit the MSB of the shift. 7651 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7652 if (CombinedShAmt == 0) 7653 return Src; 7654 7655 SDValue Res = DAG.getNode( 7656 RISCVISD::GREV, DL, VT, Src, 7657 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7658 if (!IsWInstruction) 7659 return Res; 7660 7661 // Sign extend the result to match the behavior of the rotate. This will be 7662 // selected to GREVIW in isel. 7663 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7664 DAG.getValueType(MVT::i32)); 7665 } 7666 7667 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7668 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7669 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7670 // not undo itself, but they are redundant. 7671 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7672 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7673 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7674 SDValue Src = N->getOperand(0); 7675 7676 if (Src.getOpcode() != N->getOpcode()) 7677 return SDValue(); 7678 7679 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7680 !isa<ConstantSDNode>(Src.getOperand(1))) 7681 return SDValue(); 7682 7683 unsigned ShAmt1 = N->getConstantOperandVal(1); 7684 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7685 Src = Src.getOperand(0); 7686 7687 unsigned CombinedShAmt; 7688 if (IsGORC) 7689 CombinedShAmt = ShAmt1 | ShAmt2; 7690 else 7691 CombinedShAmt = ShAmt1 ^ ShAmt2; 7692 7693 if (CombinedShAmt == 0) 7694 return Src; 7695 7696 SDLoc DL(N); 7697 return DAG.getNode( 7698 N->getOpcode(), DL, N->getValueType(0), Src, 7699 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7700 } 7701 7702 // Combine a constant select operand into its use: 7703 // 7704 // (and (select cond, -1, c), x) 7705 // -> (select cond, x, (and x, c)) [AllOnes=1] 7706 // (or (select cond, 0, c), x) 7707 // -> (select cond, x, (or x, c)) [AllOnes=0] 7708 // (xor (select cond, 0, c), x) 7709 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7710 // (add (select cond, 0, c), x) 7711 // -> (select cond, x, (add x, c)) [AllOnes=0] 7712 // (sub x, (select cond, 0, c)) 7713 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7714 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7715 SelectionDAG &DAG, bool AllOnes) { 7716 EVT VT = N->getValueType(0); 7717 7718 // Skip vectors. 7719 if (VT.isVector()) 7720 return SDValue(); 7721 7722 if ((Slct.getOpcode() != ISD::SELECT && 7723 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7724 !Slct.hasOneUse()) 7725 return SDValue(); 7726 7727 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7728 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7729 }; 7730 7731 bool SwapSelectOps; 7732 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7733 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7734 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7735 SDValue NonConstantVal; 7736 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7737 SwapSelectOps = false; 7738 NonConstantVal = FalseVal; 7739 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7740 SwapSelectOps = true; 7741 NonConstantVal = TrueVal; 7742 } else 7743 return SDValue(); 7744 7745 // Slct is now know to be the desired identity constant when CC is true. 7746 TrueVal = OtherOp; 7747 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7748 // Unless SwapSelectOps says the condition should be false. 7749 if (SwapSelectOps) 7750 std::swap(TrueVal, FalseVal); 7751 7752 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7753 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7754 {Slct.getOperand(0), Slct.getOperand(1), 7755 Slct.getOperand(2), TrueVal, FalseVal}); 7756 7757 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7758 {Slct.getOperand(0), TrueVal, FalseVal}); 7759 } 7760 7761 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7762 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7763 bool AllOnes) { 7764 SDValue N0 = N->getOperand(0); 7765 SDValue N1 = N->getOperand(1); 7766 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7767 return Result; 7768 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7769 return Result; 7770 return SDValue(); 7771 } 7772 7773 // Transform (add (mul x, c0), c1) -> 7774 // (add (mul (add x, c1/c0), c0), c1%c0). 7775 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7776 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7777 // to an infinite loop in DAGCombine if transformed. 7778 // Or transform (add (mul x, c0), c1) -> 7779 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7780 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7781 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7782 // lead to an infinite loop in DAGCombine if transformed. 7783 // Or transform (add (mul x, c0), c1) -> 7784 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7785 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7786 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7787 // lead to an infinite loop in DAGCombine if transformed. 7788 // Or transform (add (mul x, c0), c1) -> 7789 // (mul (add x, c1/c0), c0). 7790 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7791 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7792 const RISCVSubtarget &Subtarget) { 7793 // Skip for vector types and larger types. 7794 EVT VT = N->getValueType(0); 7795 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7796 return SDValue(); 7797 // The first operand node must be a MUL and has no other use. 7798 SDValue N0 = N->getOperand(0); 7799 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7800 return SDValue(); 7801 // Check if c0 and c1 match above conditions. 7802 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7803 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7804 if (!N0C || !N1C) 7805 return SDValue(); 7806 // If N0C has multiple uses it's possible one of the cases in 7807 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7808 // in an infinite loop. 7809 if (!N0C->hasOneUse()) 7810 return SDValue(); 7811 int64_t C0 = N0C->getSExtValue(); 7812 int64_t C1 = N1C->getSExtValue(); 7813 int64_t CA, CB; 7814 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7815 return SDValue(); 7816 // Search for proper CA (non-zero) and CB that both are simm12. 7817 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7818 !isInt<12>(C0 * (C1 / C0))) { 7819 CA = C1 / C0; 7820 CB = C1 % C0; 7821 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7822 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7823 CA = C1 / C0 + 1; 7824 CB = C1 % C0 - C0; 7825 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7826 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7827 CA = C1 / C0 - 1; 7828 CB = C1 % C0 + C0; 7829 } else 7830 return SDValue(); 7831 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7832 SDLoc DL(N); 7833 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7834 DAG.getConstant(CA, DL, VT)); 7835 SDValue New1 = 7836 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7837 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7838 } 7839 7840 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7841 const RISCVSubtarget &Subtarget) { 7842 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7843 return V; 7844 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7845 return V; 7846 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7847 // (select lhs, rhs, cc, x, (add x, y)) 7848 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7849 } 7850 7851 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7852 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7853 // (select lhs, rhs, cc, x, (sub x, y)) 7854 SDValue N0 = N->getOperand(0); 7855 SDValue N1 = N->getOperand(1); 7856 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7857 } 7858 7859 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7860 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7861 // (select lhs, rhs, cc, x, (and x, y)) 7862 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7863 } 7864 7865 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7866 const RISCVSubtarget &Subtarget) { 7867 if (Subtarget.hasStdExtZbp()) { 7868 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7869 return GREV; 7870 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7871 return GORC; 7872 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7873 return SHFL; 7874 } 7875 7876 // fold (or (select cond, 0, y), x) -> 7877 // (select cond, x, (or x, y)) 7878 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7879 } 7880 7881 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7882 // fold (xor (select cond, 0, y), x) -> 7883 // (select cond, x, (xor x, y)) 7884 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7885 } 7886 7887 static SDValue 7888 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 7889 const RISCVSubtarget &Subtarget) { 7890 SDValue Src = N->getOperand(0); 7891 EVT VT = N->getValueType(0); 7892 7893 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 7894 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7895 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 7896 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 7897 Src.getOperand(0)); 7898 7899 // Fold (i64 (sext_inreg (abs X), i32)) -> 7900 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 7901 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 7902 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 7903 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 7904 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 7905 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 7906 // may get combined into an earlier operation so we need to use 7907 // ComputeNumSignBits. 7908 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 7909 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 7910 // we can't assume that X has 33 sign bits. We must check. 7911 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 7912 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 7913 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 7914 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 7915 SDLoc DL(N); 7916 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 7917 SDValue Neg = 7918 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 7919 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 7920 DAG.getValueType(MVT::i32)); 7921 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 7922 } 7923 7924 return SDValue(); 7925 } 7926 7927 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7928 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7929 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7930 bool Commute = false) { 7931 assert((N->getOpcode() == RISCVISD::ADD_VL || 7932 N->getOpcode() == RISCVISD::SUB_VL) && 7933 "Unexpected opcode"); 7934 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7935 SDValue Op0 = N->getOperand(0); 7936 SDValue Op1 = N->getOperand(1); 7937 if (Commute) 7938 std::swap(Op0, Op1); 7939 7940 MVT VT = N->getSimpleValueType(0); 7941 7942 // Determine the narrow size for a widening add/sub. 7943 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7944 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7945 VT.getVectorElementCount()); 7946 7947 SDValue Mask = N->getOperand(2); 7948 SDValue VL = N->getOperand(3); 7949 7950 SDLoc DL(N); 7951 7952 // If the RHS is a sext or zext, we can form a widening op. 7953 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7954 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7955 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7956 unsigned ExtOpc = Op1.getOpcode(); 7957 Op1 = Op1.getOperand(0); 7958 // Re-introduce narrower extends if needed. 7959 if (Op1.getValueType() != NarrowVT) 7960 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7961 7962 unsigned WOpc; 7963 if (ExtOpc == RISCVISD::VSEXT_VL) 7964 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7965 else 7966 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7967 7968 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7969 } 7970 7971 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7972 // sext/zext? 7973 7974 return SDValue(); 7975 } 7976 7977 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7978 // vwsub(u).vv/vx. 7979 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7980 SDValue Op0 = N->getOperand(0); 7981 SDValue Op1 = N->getOperand(1); 7982 SDValue Mask = N->getOperand(2); 7983 SDValue VL = N->getOperand(3); 7984 7985 MVT VT = N->getSimpleValueType(0); 7986 MVT NarrowVT = Op1.getSimpleValueType(); 7987 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 7988 7989 unsigned VOpc; 7990 switch (N->getOpcode()) { 7991 default: llvm_unreachable("Unexpected opcode"); 7992 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 7993 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 7994 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 7995 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 7996 } 7997 7998 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 7999 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8000 8001 SDLoc DL(N); 8002 8003 // If the LHS is a sext or zext, we can narrow this op to the same size as 8004 // the RHS. 8005 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8006 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8007 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8008 unsigned ExtOpc = Op0.getOpcode(); 8009 Op0 = Op0.getOperand(0); 8010 // Re-introduce narrower extends if needed. 8011 if (Op0.getValueType() != NarrowVT) 8012 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8013 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8014 } 8015 8016 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8017 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8018 8019 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8020 // to commute and use a vwadd(u).vx instead. 8021 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8022 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8023 Op0 = Op0.getOperand(1); 8024 8025 // See if have enough sign bits or zero bits in the scalar to use a 8026 // widening add/sub by splatting to smaller element size. 8027 unsigned EltBits = VT.getScalarSizeInBits(); 8028 unsigned ScalarBits = Op0.getValueSizeInBits(); 8029 // Make sure we're getting all element bits from the scalar register. 8030 // FIXME: Support implicit sign extension of vmv.v.x? 8031 if (ScalarBits < EltBits) 8032 return SDValue(); 8033 8034 if (IsSigned) { 8035 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8036 return SDValue(); 8037 } else { 8038 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8039 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8040 return SDValue(); 8041 } 8042 8043 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8044 DAG.getUNDEF(NarrowVT), Op0, VL); 8045 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8046 } 8047 8048 return SDValue(); 8049 } 8050 8051 // Try to form VWMUL, VWMULU or VWMULSU. 8052 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8053 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8054 bool Commute) { 8055 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8056 SDValue Op0 = N->getOperand(0); 8057 SDValue Op1 = N->getOperand(1); 8058 if (Commute) 8059 std::swap(Op0, Op1); 8060 8061 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8062 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8063 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8064 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8065 return SDValue(); 8066 8067 SDValue Mask = N->getOperand(2); 8068 SDValue VL = N->getOperand(3); 8069 8070 // Make sure the mask and VL match. 8071 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8072 return SDValue(); 8073 8074 MVT VT = N->getSimpleValueType(0); 8075 8076 // Determine the narrow size for a widening multiply. 8077 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8078 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8079 VT.getVectorElementCount()); 8080 8081 SDLoc DL(N); 8082 8083 // See if the other operand is the same opcode. 8084 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8085 if (!Op1.hasOneUse()) 8086 return SDValue(); 8087 8088 // Make sure the mask and VL match. 8089 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8090 return SDValue(); 8091 8092 Op1 = Op1.getOperand(0); 8093 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8094 // The operand is a splat of a scalar. 8095 8096 // The pasthru must be undef for tail agnostic 8097 if (!Op1.getOperand(0).isUndef()) 8098 return SDValue(); 8099 // The VL must be the same. 8100 if (Op1.getOperand(2) != VL) 8101 return SDValue(); 8102 8103 // Get the scalar value. 8104 Op1 = Op1.getOperand(1); 8105 8106 // See if have enough sign bits or zero bits in the scalar to use a 8107 // widening multiply by splatting to smaller element size. 8108 unsigned EltBits = VT.getScalarSizeInBits(); 8109 unsigned ScalarBits = Op1.getValueSizeInBits(); 8110 // Make sure we're getting all element bits from the scalar register. 8111 // FIXME: Support implicit sign extension of vmv.v.x? 8112 if (ScalarBits < EltBits) 8113 return SDValue(); 8114 8115 // If the LHS is a sign extend, try to use vwmul. 8116 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8117 // Can use vwmul. 8118 } else { 8119 // Otherwise try to use vwmulu or vwmulsu. 8120 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8121 if (DAG.MaskedValueIsZero(Op1, Mask)) 8122 IsVWMULSU = IsSignExt; 8123 else 8124 return SDValue(); 8125 } 8126 8127 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8128 DAG.getUNDEF(NarrowVT), Op1, VL); 8129 } else 8130 return SDValue(); 8131 8132 Op0 = Op0.getOperand(0); 8133 8134 // Re-introduce narrower extends if needed. 8135 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8136 if (Op0.getValueType() != NarrowVT) 8137 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8138 // vwmulsu requires second operand to be zero extended. 8139 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8140 if (Op1.getValueType() != NarrowVT) 8141 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8142 8143 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8144 if (!IsVWMULSU) 8145 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8146 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8147 } 8148 8149 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8150 switch (Op.getOpcode()) { 8151 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8152 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8153 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8154 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8155 case ISD::FROUND: return RISCVFPRndMode::RMM; 8156 } 8157 8158 return RISCVFPRndMode::Invalid; 8159 } 8160 8161 // Fold 8162 // (fp_to_int (froundeven X)) -> fcvt X, rne 8163 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8164 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8165 // (fp_to_int (fceil X)) -> fcvt X, rup 8166 // (fp_to_int (fround X)) -> fcvt X, rmm 8167 static SDValue performFP_TO_INTCombine(SDNode *N, 8168 TargetLowering::DAGCombinerInfo &DCI, 8169 const RISCVSubtarget &Subtarget) { 8170 SelectionDAG &DAG = DCI.DAG; 8171 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8172 MVT XLenVT = Subtarget.getXLenVT(); 8173 8174 // Only handle XLen or i32 types. Other types narrower than XLen will 8175 // eventually be legalized to XLenVT. 8176 EVT VT = N->getValueType(0); 8177 if (VT != MVT::i32 && VT != XLenVT) 8178 return SDValue(); 8179 8180 SDValue Src = N->getOperand(0); 8181 8182 // Ensure the FP type is also legal. 8183 if (!TLI.isTypeLegal(Src.getValueType())) 8184 return SDValue(); 8185 8186 // Don't do this for f16 with Zfhmin and not Zfh. 8187 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8188 return SDValue(); 8189 8190 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8191 if (FRM == RISCVFPRndMode::Invalid) 8192 return SDValue(); 8193 8194 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8195 8196 unsigned Opc; 8197 if (VT == XLenVT) 8198 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8199 else 8200 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8201 8202 SDLoc DL(N); 8203 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8204 DAG.getTargetConstant(FRM, DL, XLenVT)); 8205 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8206 } 8207 8208 // Fold 8209 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8210 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8211 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8212 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8213 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8214 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8215 TargetLowering::DAGCombinerInfo &DCI, 8216 const RISCVSubtarget &Subtarget) { 8217 SelectionDAG &DAG = DCI.DAG; 8218 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8219 MVT XLenVT = Subtarget.getXLenVT(); 8220 8221 // Only handle XLen types. Other types narrower than XLen will eventually be 8222 // legalized to XLenVT. 8223 EVT DstVT = N->getValueType(0); 8224 if (DstVT != XLenVT) 8225 return SDValue(); 8226 8227 SDValue Src = N->getOperand(0); 8228 8229 // Ensure the FP type is also legal. 8230 if (!TLI.isTypeLegal(Src.getValueType())) 8231 return SDValue(); 8232 8233 // Don't do this for f16 with Zfhmin and not Zfh. 8234 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8235 return SDValue(); 8236 8237 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8238 8239 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8240 if (FRM == RISCVFPRndMode::Invalid) 8241 return SDValue(); 8242 8243 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8244 8245 unsigned Opc; 8246 if (SatVT == DstVT) 8247 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8248 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8249 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8250 else 8251 return SDValue(); 8252 // FIXME: Support other SatVTs by clamping before or after the conversion. 8253 8254 Src = Src.getOperand(0); 8255 8256 SDLoc DL(N); 8257 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8258 DAG.getTargetConstant(FRM, DL, XLenVT)); 8259 8260 // RISCV FP-to-int conversions saturate to the destination register size, but 8261 // don't produce 0 for nan. 8262 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8263 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8264 } 8265 8266 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8267 // smaller than XLenVT. 8268 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8269 const RISCVSubtarget &Subtarget) { 8270 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8271 8272 SDValue Src = N->getOperand(0); 8273 if (Src.getOpcode() != ISD::BSWAP) 8274 return SDValue(); 8275 8276 EVT VT = N->getValueType(0); 8277 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8278 !isPowerOf2_32(VT.getSizeInBits())) 8279 return SDValue(); 8280 8281 SDLoc DL(N); 8282 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8283 DAG.getConstant(7, DL, VT)); 8284 } 8285 8286 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8287 DAGCombinerInfo &DCI) const { 8288 SelectionDAG &DAG = DCI.DAG; 8289 8290 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8291 // bits are demanded. N will be added to the Worklist if it was not deleted. 8292 // Caller should return SDValue(N, 0) if this returns true. 8293 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8294 SDValue Op = N->getOperand(OpNo); 8295 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8296 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8297 return false; 8298 8299 if (N->getOpcode() != ISD::DELETED_NODE) 8300 DCI.AddToWorklist(N); 8301 return true; 8302 }; 8303 8304 switch (N->getOpcode()) { 8305 default: 8306 break; 8307 case RISCVISD::SplitF64: { 8308 SDValue Op0 = N->getOperand(0); 8309 // If the input to SplitF64 is just BuildPairF64 then the operation is 8310 // redundant. Instead, use BuildPairF64's operands directly. 8311 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8312 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8313 8314 if (Op0->isUndef()) { 8315 SDValue Lo = DAG.getUNDEF(MVT::i32); 8316 SDValue Hi = DAG.getUNDEF(MVT::i32); 8317 return DCI.CombineTo(N, Lo, Hi); 8318 } 8319 8320 SDLoc DL(N); 8321 8322 // It's cheaper to materialise two 32-bit integers than to load a double 8323 // from the constant pool and transfer it to integer registers through the 8324 // stack. 8325 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8326 APInt V = C->getValueAPF().bitcastToAPInt(); 8327 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8328 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8329 return DCI.CombineTo(N, Lo, Hi); 8330 } 8331 8332 // This is a target-specific version of a DAGCombine performed in 8333 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8334 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8335 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8336 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8337 !Op0.getNode()->hasOneUse()) 8338 break; 8339 SDValue NewSplitF64 = 8340 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8341 Op0.getOperand(0)); 8342 SDValue Lo = NewSplitF64.getValue(0); 8343 SDValue Hi = NewSplitF64.getValue(1); 8344 APInt SignBit = APInt::getSignMask(32); 8345 if (Op0.getOpcode() == ISD::FNEG) { 8346 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8347 DAG.getConstant(SignBit, DL, MVT::i32)); 8348 return DCI.CombineTo(N, Lo, NewHi); 8349 } 8350 assert(Op0.getOpcode() == ISD::FABS); 8351 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8352 DAG.getConstant(~SignBit, DL, MVT::i32)); 8353 return DCI.CombineTo(N, Lo, NewHi); 8354 } 8355 case RISCVISD::SLLW: 8356 case RISCVISD::SRAW: 8357 case RISCVISD::SRLW: { 8358 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8359 if (SimplifyDemandedLowBitsHelper(0, 32) || 8360 SimplifyDemandedLowBitsHelper(1, 5)) 8361 return SDValue(N, 0); 8362 8363 break; 8364 } 8365 case ISD::ROTR: 8366 case ISD::ROTL: 8367 case RISCVISD::RORW: 8368 case RISCVISD::ROLW: { 8369 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8370 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8371 if (SimplifyDemandedLowBitsHelper(0, 32) || 8372 SimplifyDemandedLowBitsHelper(1, 5)) 8373 return SDValue(N, 0); 8374 } 8375 8376 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8377 } 8378 case RISCVISD::CLZW: 8379 case RISCVISD::CTZW: { 8380 // Only the lower 32 bits of the first operand are read 8381 if (SimplifyDemandedLowBitsHelper(0, 32)) 8382 return SDValue(N, 0); 8383 break; 8384 } 8385 case RISCVISD::GREV: 8386 case RISCVISD::GORC: { 8387 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8388 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8389 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8390 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8391 return SDValue(N, 0); 8392 8393 return combineGREVI_GORCI(N, DAG); 8394 } 8395 case RISCVISD::GREVW: 8396 case RISCVISD::GORCW: { 8397 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8398 if (SimplifyDemandedLowBitsHelper(0, 32) || 8399 SimplifyDemandedLowBitsHelper(1, 5)) 8400 return SDValue(N, 0); 8401 8402 break; 8403 } 8404 case RISCVISD::SHFL: 8405 case RISCVISD::UNSHFL: { 8406 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8407 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8408 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8409 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8410 return SDValue(N, 0); 8411 8412 break; 8413 } 8414 case RISCVISD::SHFLW: 8415 case RISCVISD::UNSHFLW: { 8416 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8417 if (SimplifyDemandedLowBitsHelper(0, 32) || 8418 SimplifyDemandedLowBitsHelper(1, 4)) 8419 return SDValue(N, 0); 8420 8421 break; 8422 } 8423 case RISCVISD::BCOMPRESSW: 8424 case RISCVISD::BDECOMPRESSW: { 8425 // Only the lower 32 bits of LHS and RHS are read. 8426 if (SimplifyDemandedLowBitsHelper(0, 32) || 8427 SimplifyDemandedLowBitsHelper(1, 32)) 8428 return SDValue(N, 0); 8429 8430 break; 8431 } 8432 case RISCVISD::FSR: 8433 case RISCVISD::FSL: 8434 case RISCVISD::FSRW: 8435 case RISCVISD::FSLW: { 8436 bool IsWInstruction = 8437 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8438 unsigned BitWidth = 8439 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8440 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8441 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8442 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8443 return SDValue(N, 0); 8444 8445 break; 8446 } 8447 case RISCVISD::FMV_X_ANYEXTH: 8448 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8449 SDLoc DL(N); 8450 SDValue Op0 = N->getOperand(0); 8451 MVT VT = N->getSimpleValueType(0); 8452 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8453 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8454 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8455 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8456 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8457 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8458 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8459 assert(Op0.getOperand(0).getValueType() == VT && 8460 "Unexpected value type!"); 8461 return Op0.getOperand(0); 8462 } 8463 8464 // This is a target-specific version of a DAGCombine performed in 8465 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8466 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8467 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8468 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8469 !Op0.getNode()->hasOneUse()) 8470 break; 8471 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8472 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8473 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8474 if (Op0.getOpcode() == ISD::FNEG) 8475 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8476 DAG.getConstant(SignBit, DL, VT)); 8477 8478 assert(Op0.getOpcode() == ISD::FABS); 8479 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8480 DAG.getConstant(~SignBit, DL, VT)); 8481 } 8482 case ISD::ADD: 8483 return performADDCombine(N, DAG, Subtarget); 8484 case ISD::SUB: 8485 return performSUBCombine(N, DAG); 8486 case ISD::AND: 8487 return performANDCombine(N, DAG); 8488 case ISD::OR: 8489 return performORCombine(N, DAG, Subtarget); 8490 case ISD::XOR: 8491 return performXORCombine(N, DAG); 8492 case ISD::SIGN_EXTEND_INREG: 8493 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8494 case ISD::ZERO_EXTEND: 8495 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8496 // type legalization. This is safe because fp_to_uint produces poison if 8497 // it overflows. 8498 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8499 SDValue Src = N->getOperand(0); 8500 if (Src.getOpcode() == ISD::FP_TO_UINT && 8501 isTypeLegal(Src.getOperand(0).getValueType())) 8502 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8503 Src.getOperand(0)); 8504 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8505 isTypeLegal(Src.getOperand(1).getValueType())) { 8506 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8507 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8508 Src.getOperand(0), Src.getOperand(1)); 8509 DCI.CombineTo(N, Res); 8510 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8511 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8512 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8513 } 8514 } 8515 return SDValue(); 8516 case RISCVISD::SELECT_CC: { 8517 // Transform 8518 SDValue LHS = N->getOperand(0); 8519 SDValue RHS = N->getOperand(1); 8520 SDValue TrueV = N->getOperand(3); 8521 SDValue FalseV = N->getOperand(4); 8522 8523 // If the True and False values are the same, we don't need a select_cc. 8524 if (TrueV == FalseV) 8525 return TrueV; 8526 8527 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8528 if (!ISD::isIntEqualitySetCC(CCVal)) 8529 break; 8530 8531 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8532 // (select_cc X, Y, lt, trueV, falseV) 8533 // Sometimes the setcc is introduced after select_cc has been formed. 8534 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8535 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8536 // If we're looking for eq 0 instead of ne 0, we need to invert the 8537 // condition. 8538 bool Invert = CCVal == ISD::SETEQ; 8539 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8540 if (Invert) 8541 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8542 8543 SDLoc DL(N); 8544 RHS = LHS.getOperand(1); 8545 LHS = LHS.getOperand(0); 8546 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8547 8548 SDValue TargetCC = DAG.getCondCode(CCVal); 8549 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8550 {LHS, RHS, TargetCC, TrueV, FalseV}); 8551 } 8552 8553 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8554 // (select_cc X, Y, eq/ne, trueV, falseV) 8555 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8556 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8557 {LHS.getOperand(0), LHS.getOperand(1), 8558 N->getOperand(2), TrueV, FalseV}); 8559 // (select_cc X, 1, setne, trueV, falseV) -> 8560 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8561 // This can occur when legalizing some floating point comparisons. 8562 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8563 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8564 SDLoc DL(N); 8565 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8566 SDValue TargetCC = DAG.getCondCode(CCVal); 8567 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8568 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8569 {LHS, RHS, TargetCC, TrueV, FalseV}); 8570 } 8571 8572 break; 8573 } 8574 case RISCVISD::BR_CC: { 8575 SDValue LHS = N->getOperand(1); 8576 SDValue RHS = N->getOperand(2); 8577 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8578 if (!ISD::isIntEqualitySetCC(CCVal)) 8579 break; 8580 8581 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8582 // (br_cc X, Y, lt, dest) 8583 // Sometimes the setcc is introduced after br_cc has been formed. 8584 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8585 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8586 // If we're looking for eq 0 instead of ne 0, we need to invert the 8587 // condition. 8588 bool Invert = CCVal == ISD::SETEQ; 8589 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8590 if (Invert) 8591 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8592 8593 SDLoc DL(N); 8594 RHS = LHS.getOperand(1); 8595 LHS = LHS.getOperand(0); 8596 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8597 8598 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8599 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8600 N->getOperand(4)); 8601 } 8602 8603 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8604 // (br_cc X, Y, eq/ne, trueV, falseV) 8605 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8606 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8607 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8608 N->getOperand(3), N->getOperand(4)); 8609 8610 // (br_cc X, 1, setne, br_cc) -> 8611 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8612 // This can occur when legalizing some floating point comparisons. 8613 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8614 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8615 SDLoc DL(N); 8616 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8617 SDValue TargetCC = DAG.getCondCode(CCVal); 8618 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8619 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8620 N->getOperand(0), LHS, RHS, TargetCC, 8621 N->getOperand(4)); 8622 } 8623 break; 8624 } 8625 case ISD::BITREVERSE: 8626 return performBITREVERSECombine(N, DAG, Subtarget); 8627 case ISD::FP_TO_SINT: 8628 case ISD::FP_TO_UINT: 8629 return performFP_TO_INTCombine(N, DCI, Subtarget); 8630 case ISD::FP_TO_SINT_SAT: 8631 case ISD::FP_TO_UINT_SAT: 8632 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8633 case ISD::FCOPYSIGN: { 8634 EVT VT = N->getValueType(0); 8635 if (!VT.isVector()) 8636 break; 8637 // There is a form of VFSGNJ which injects the negated sign of its second 8638 // operand. Try and bubble any FNEG up after the extend/round to produce 8639 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8640 // TRUNC=1. 8641 SDValue In2 = N->getOperand(1); 8642 // Avoid cases where the extend/round has multiple uses, as duplicating 8643 // those is typically more expensive than removing a fneg. 8644 if (!In2.hasOneUse()) 8645 break; 8646 if (In2.getOpcode() != ISD::FP_EXTEND && 8647 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8648 break; 8649 In2 = In2.getOperand(0); 8650 if (In2.getOpcode() != ISD::FNEG) 8651 break; 8652 SDLoc DL(N); 8653 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8654 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8655 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8656 } 8657 case ISD::MGATHER: 8658 case ISD::MSCATTER: 8659 case ISD::VP_GATHER: 8660 case ISD::VP_SCATTER: { 8661 if (!DCI.isBeforeLegalize()) 8662 break; 8663 SDValue Index, ScaleOp; 8664 bool IsIndexScaled = false; 8665 bool IsIndexSigned = false; 8666 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8667 Index = VPGSN->getIndex(); 8668 ScaleOp = VPGSN->getScale(); 8669 IsIndexScaled = VPGSN->isIndexScaled(); 8670 IsIndexSigned = VPGSN->isIndexSigned(); 8671 } else { 8672 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8673 Index = MGSN->getIndex(); 8674 ScaleOp = MGSN->getScale(); 8675 IsIndexScaled = MGSN->isIndexScaled(); 8676 IsIndexSigned = MGSN->isIndexSigned(); 8677 } 8678 EVT IndexVT = Index.getValueType(); 8679 MVT XLenVT = Subtarget.getXLenVT(); 8680 // RISCV indexed loads only support the "unsigned unscaled" addressing 8681 // mode, so anything else must be manually legalized. 8682 bool NeedsIdxLegalization = 8683 IsIndexScaled || 8684 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8685 if (!NeedsIdxLegalization) 8686 break; 8687 8688 SDLoc DL(N); 8689 8690 // Any index legalization should first promote to XLenVT, so we don't lose 8691 // bits when scaling. This may create an illegal index type so we let 8692 // LLVM's legalization take care of the splitting. 8693 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8694 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8695 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8696 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8697 DL, IndexVT, Index); 8698 } 8699 8700 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8701 if (IsIndexScaled && Scale != 1) { 8702 // Manually scale the indices by the element size. 8703 // TODO: Sanitize the scale operand here? 8704 // TODO: For VP nodes, should we use VP_SHL here? 8705 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8706 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8707 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8708 } 8709 8710 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8711 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8712 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8713 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8714 VPGN->getScale(), VPGN->getMask(), 8715 VPGN->getVectorLength()}, 8716 VPGN->getMemOperand(), NewIndexTy); 8717 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8718 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8719 {VPSN->getChain(), VPSN->getValue(), 8720 VPSN->getBasePtr(), Index, VPSN->getScale(), 8721 VPSN->getMask(), VPSN->getVectorLength()}, 8722 VPSN->getMemOperand(), NewIndexTy); 8723 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8724 return DAG.getMaskedGather( 8725 N->getVTList(), MGN->getMemoryVT(), DL, 8726 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8727 MGN->getBasePtr(), Index, MGN->getScale()}, 8728 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8729 const auto *MSN = cast<MaskedScatterSDNode>(N); 8730 return DAG.getMaskedScatter( 8731 N->getVTList(), MSN->getMemoryVT(), DL, 8732 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8733 Index, MSN->getScale()}, 8734 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8735 } 8736 case RISCVISD::SRA_VL: 8737 case RISCVISD::SRL_VL: 8738 case RISCVISD::SHL_VL: { 8739 SDValue ShAmt = N->getOperand(1); 8740 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8741 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8742 SDLoc DL(N); 8743 SDValue VL = N->getOperand(3); 8744 EVT VT = N->getValueType(0); 8745 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8746 ShAmt.getOperand(1), VL); 8747 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8748 N->getOperand(2), N->getOperand(3)); 8749 } 8750 break; 8751 } 8752 case ISD::SRA: 8753 case ISD::SRL: 8754 case ISD::SHL: { 8755 SDValue ShAmt = N->getOperand(1); 8756 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8757 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8758 SDLoc DL(N); 8759 EVT VT = N->getValueType(0); 8760 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8761 ShAmt.getOperand(1), 8762 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8763 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8764 } 8765 break; 8766 } 8767 case RISCVISD::ADD_VL: 8768 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8769 return V; 8770 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8771 case RISCVISD::SUB_VL: 8772 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8773 case RISCVISD::VWADD_W_VL: 8774 case RISCVISD::VWADDU_W_VL: 8775 case RISCVISD::VWSUB_W_VL: 8776 case RISCVISD::VWSUBU_W_VL: 8777 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8778 case RISCVISD::MUL_VL: 8779 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8780 return V; 8781 // Mul is commutative. 8782 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8783 case ISD::STORE: { 8784 auto *Store = cast<StoreSDNode>(N); 8785 SDValue Val = Store->getValue(); 8786 // Combine store of vmv.x.s to vse with VL of 1. 8787 // FIXME: Support FP. 8788 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8789 SDValue Src = Val.getOperand(0); 8790 EVT VecVT = Src.getValueType(); 8791 EVT MemVT = Store->getMemoryVT(); 8792 // The memory VT and the element type must match. 8793 if (VecVT.getVectorElementType() == MemVT) { 8794 SDLoc DL(N); 8795 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8796 return DAG.getStoreVP( 8797 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8798 DAG.getConstant(1, DL, MaskVT), 8799 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8800 Store->getMemOperand(), Store->getAddressingMode(), 8801 Store->isTruncatingStore(), /*IsCompress*/ false); 8802 } 8803 } 8804 8805 break; 8806 } 8807 case ISD::SPLAT_VECTOR: { 8808 EVT VT = N->getValueType(0); 8809 // Only perform this combine on legal MVT types. 8810 if (!isTypeLegal(VT)) 8811 break; 8812 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8813 DAG, Subtarget)) 8814 return Gather; 8815 break; 8816 } 8817 case RISCVISD::VMV_V_X_VL: { 8818 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8819 // scalar input. 8820 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8821 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8822 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8823 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8824 return SDValue(N, 0); 8825 8826 break; 8827 } 8828 case ISD::INTRINSIC_WO_CHAIN: { 8829 unsigned IntNo = N->getConstantOperandVal(0); 8830 switch (IntNo) { 8831 // By default we do not combine any intrinsic. 8832 default: 8833 return SDValue(); 8834 case Intrinsic::riscv_vcpop: 8835 case Intrinsic::riscv_vcpop_mask: 8836 case Intrinsic::riscv_vfirst: 8837 case Intrinsic::riscv_vfirst_mask: { 8838 SDValue VL = N->getOperand(2); 8839 if (IntNo == Intrinsic::riscv_vcpop_mask || 8840 IntNo == Intrinsic::riscv_vfirst_mask) 8841 VL = N->getOperand(3); 8842 if (!isNullConstant(VL)) 8843 return SDValue(); 8844 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8845 SDLoc DL(N); 8846 EVT VT = N->getValueType(0); 8847 if (IntNo == Intrinsic::riscv_vfirst || 8848 IntNo == Intrinsic::riscv_vfirst_mask) 8849 return DAG.getConstant(-1, DL, VT); 8850 return DAG.getConstant(0, DL, VT); 8851 } 8852 } 8853 } 8854 } 8855 8856 return SDValue(); 8857 } 8858 8859 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8860 const SDNode *N, CombineLevel Level) const { 8861 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8862 // materialised in fewer instructions than `(OP _, c1)`: 8863 // 8864 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8865 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8866 SDValue N0 = N->getOperand(0); 8867 EVT Ty = N0.getValueType(); 8868 if (Ty.isScalarInteger() && 8869 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8870 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8871 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8872 if (C1 && C2) { 8873 const APInt &C1Int = C1->getAPIntValue(); 8874 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8875 8876 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8877 // and the combine should happen, to potentially allow further combines 8878 // later. 8879 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8880 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8881 return true; 8882 8883 // We can materialise `c1` in an add immediate, so it's "free", and the 8884 // combine should be prevented. 8885 if (C1Int.getMinSignedBits() <= 64 && 8886 isLegalAddImmediate(C1Int.getSExtValue())) 8887 return false; 8888 8889 // Neither constant will fit into an immediate, so find materialisation 8890 // costs. 8891 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8892 Subtarget.getFeatureBits(), 8893 /*CompressionCost*/true); 8894 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8895 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8896 /*CompressionCost*/true); 8897 8898 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8899 // combine should be prevented. 8900 if (C1Cost < ShiftedC1Cost) 8901 return false; 8902 } 8903 } 8904 return true; 8905 } 8906 8907 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8908 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8909 TargetLoweringOpt &TLO) const { 8910 // Delay this optimization as late as possible. 8911 if (!TLO.LegalOps) 8912 return false; 8913 8914 EVT VT = Op.getValueType(); 8915 if (VT.isVector()) 8916 return false; 8917 8918 // Only handle AND for now. 8919 if (Op.getOpcode() != ISD::AND) 8920 return false; 8921 8922 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8923 if (!C) 8924 return false; 8925 8926 const APInt &Mask = C->getAPIntValue(); 8927 8928 // Clear all non-demanded bits initially. 8929 APInt ShrunkMask = Mask & DemandedBits; 8930 8931 // Try to make a smaller immediate by setting undemanded bits. 8932 8933 APInt ExpandedMask = Mask | ~DemandedBits; 8934 8935 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8936 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8937 }; 8938 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8939 if (NewMask == Mask) 8940 return true; 8941 SDLoc DL(Op); 8942 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8943 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8944 return TLO.CombineTo(Op, NewOp); 8945 }; 8946 8947 // If the shrunk mask fits in sign extended 12 bits, let the target 8948 // independent code apply it. 8949 if (ShrunkMask.isSignedIntN(12)) 8950 return false; 8951 8952 // Preserve (and X, 0xffff) when zext.h is supported. 8953 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8954 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8955 if (IsLegalMask(NewMask)) 8956 return UseMask(NewMask); 8957 } 8958 8959 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8960 if (VT == MVT::i64) { 8961 APInt NewMask = APInt(64, 0xffffffff); 8962 if (IsLegalMask(NewMask)) 8963 return UseMask(NewMask); 8964 } 8965 8966 // For the remaining optimizations, we need to be able to make a negative 8967 // number through a combination of mask and undemanded bits. 8968 if (!ExpandedMask.isNegative()) 8969 return false; 8970 8971 // What is the fewest number of bits we need to represent the negative number. 8972 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8973 8974 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8975 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8976 APInt NewMask = ShrunkMask; 8977 if (MinSignedBits <= 12) 8978 NewMask.setBitsFrom(11); 8979 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8980 NewMask.setBitsFrom(31); 8981 else 8982 return false; 8983 8984 // Check that our new mask is a subset of the demanded mask. 8985 assert(IsLegalMask(NewMask)); 8986 return UseMask(NewMask); 8987 } 8988 8989 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 8990 static const uint64_t GREVMasks[] = { 8991 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 8992 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 8993 8994 for (unsigned Stage = 0; Stage != 6; ++Stage) { 8995 unsigned Shift = 1 << Stage; 8996 if (ShAmt & Shift) { 8997 uint64_t Mask = GREVMasks[Stage]; 8998 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 8999 if (IsGORC) 9000 Res |= x; 9001 x = Res; 9002 } 9003 } 9004 9005 return x; 9006 } 9007 9008 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9009 KnownBits &Known, 9010 const APInt &DemandedElts, 9011 const SelectionDAG &DAG, 9012 unsigned Depth) const { 9013 unsigned BitWidth = Known.getBitWidth(); 9014 unsigned Opc = Op.getOpcode(); 9015 assert((Opc >= ISD::BUILTIN_OP_END || 9016 Opc == ISD::INTRINSIC_WO_CHAIN || 9017 Opc == ISD::INTRINSIC_W_CHAIN || 9018 Opc == ISD::INTRINSIC_VOID) && 9019 "Should use MaskedValueIsZero if you don't know whether Op" 9020 " is a target node!"); 9021 9022 Known.resetAll(); 9023 switch (Opc) { 9024 default: break; 9025 case RISCVISD::SELECT_CC: { 9026 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9027 // If we don't know any bits, early out. 9028 if (Known.isUnknown()) 9029 break; 9030 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9031 9032 // Only known if known in both the LHS and RHS. 9033 Known = KnownBits::commonBits(Known, Known2); 9034 break; 9035 } 9036 case RISCVISD::REMUW: { 9037 KnownBits Known2; 9038 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9039 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9040 // We only care about the lower 32 bits. 9041 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9042 // Restore the original width by sign extending. 9043 Known = Known.sext(BitWidth); 9044 break; 9045 } 9046 case RISCVISD::DIVUW: { 9047 KnownBits Known2; 9048 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9049 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9050 // We only care about the lower 32 bits. 9051 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9052 // Restore the original width by sign extending. 9053 Known = Known.sext(BitWidth); 9054 break; 9055 } 9056 case RISCVISD::CTZW: { 9057 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9058 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9059 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9060 Known.Zero.setBitsFrom(LowBits); 9061 break; 9062 } 9063 case RISCVISD::CLZW: { 9064 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9065 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9066 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9067 Known.Zero.setBitsFrom(LowBits); 9068 break; 9069 } 9070 case RISCVISD::GREV: 9071 case RISCVISD::GORC: { 9072 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9073 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9074 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9075 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9076 // To compute zeros, we need to invert the value and invert it back after. 9077 Known.Zero = 9078 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9079 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9080 } 9081 break; 9082 } 9083 case RISCVISD::READ_VLENB: { 9084 // If we know the minimum VLen from Zvl extensions, we can use that to 9085 // determine the trailing zeros of VLENB. 9086 // FIXME: Limit to 128 bit vectors until we have more testing. 9087 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 9088 if (MinVLenB > 0) 9089 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9090 // We assume VLENB is no more than 65536 / 8 bytes. 9091 Known.Zero.setBitsFrom(14); 9092 break; 9093 } 9094 case ISD::INTRINSIC_W_CHAIN: 9095 case ISD::INTRINSIC_WO_CHAIN: { 9096 unsigned IntNo = 9097 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9098 switch (IntNo) { 9099 default: 9100 // We can't do anything for most intrinsics. 9101 break; 9102 case Intrinsic::riscv_vsetvli: 9103 case Intrinsic::riscv_vsetvlimax: 9104 case Intrinsic::riscv_vsetvli_opt: 9105 case Intrinsic::riscv_vsetvlimax_opt: 9106 // Assume that VL output is positive and would fit in an int32_t. 9107 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9108 if (BitWidth >= 32) 9109 Known.Zero.setBitsFrom(31); 9110 break; 9111 } 9112 break; 9113 } 9114 } 9115 } 9116 9117 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9118 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9119 unsigned Depth) const { 9120 switch (Op.getOpcode()) { 9121 default: 9122 break; 9123 case RISCVISD::SELECT_CC: { 9124 unsigned Tmp = 9125 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9126 if (Tmp == 1) return 1; // Early out. 9127 unsigned Tmp2 = 9128 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9129 return std::min(Tmp, Tmp2); 9130 } 9131 case RISCVISD::SLLW: 9132 case RISCVISD::SRAW: 9133 case RISCVISD::SRLW: 9134 case RISCVISD::DIVW: 9135 case RISCVISD::DIVUW: 9136 case RISCVISD::REMUW: 9137 case RISCVISD::ROLW: 9138 case RISCVISD::RORW: 9139 case RISCVISD::GREVW: 9140 case RISCVISD::GORCW: 9141 case RISCVISD::FSLW: 9142 case RISCVISD::FSRW: 9143 case RISCVISD::SHFLW: 9144 case RISCVISD::UNSHFLW: 9145 case RISCVISD::BCOMPRESSW: 9146 case RISCVISD::BDECOMPRESSW: 9147 case RISCVISD::BFPW: 9148 case RISCVISD::FCVT_W_RV64: 9149 case RISCVISD::FCVT_WU_RV64: 9150 case RISCVISD::STRICT_FCVT_W_RV64: 9151 case RISCVISD::STRICT_FCVT_WU_RV64: 9152 // TODO: As the result is sign-extended, this is conservatively correct. A 9153 // more precise answer could be calculated for SRAW depending on known 9154 // bits in the shift amount. 9155 return 33; 9156 case RISCVISD::SHFL: 9157 case RISCVISD::UNSHFL: { 9158 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9159 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9160 // will stay within the upper 32 bits. If there were more than 32 sign bits 9161 // before there will be at least 33 sign bits after. 9162 if (Op.getValueType() == MVT::i64 && 9163 isa<ConstantSDNode>(Op.getOperand(1)) && 9164 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9165 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9166 if (Tmp > 32) 9167 return 33; 9168 } 9169 break; 9170 } 9171 case RISCVISD::VMV_X_S: { 9172 // The number of sign bits of the scalar result is computed by obtaining the 9173 // element type of the input vector operand, subtracting its width from the 9174 // XLEN, and then adding one (sign bit within the element type). If the 9175 // element type is wider than XLen, the least-significant XLEN bits are 9176 // taken. 9177 unsigned XLen = Subtarget.getXLen(); 9178 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9179 if (EltBits <= XLen) 9180 return XLen - EltBits + 1; 9181 break; 9182 } 9183 } 9184 9185 return 1; 9186 } 9187 9188 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9189 MachineBasicBlock *BB) { 9190 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9191 9192 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9193 // Should the count have wrapped while it was being read, we need to try 9194 // again. 9195 // ... 9196 // read: 9197 // rdcycleh x3 # load high word of cycle 9198 // rdcycle x2 # load low word of cycle 9199 // rdcycleh x4 # load high word of cycle 9200 // bne x3, x4, read # check if high word reads match, otherwise try again 9201 // ... 9202 9203 MachineFunction &MF = *BB->getParent(); 9204 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9205 MachineFunction::iterator It = ++BB->getIterator(); 9206 9207 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9208 MF.insert(It, LoopMBB); 9209 9210 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9211 MF.insert(It, DoneMBB); 9212 9213 // Transfer the remainder of BB and its successor edges to DoneMBB. 9214 DoneMBB->splice(DoneMBB->begin(), BB, 9215 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9216 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9217 9218 BB->addSuccessor(LoopMBB); 9219 9220 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9221 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9222 Register LoReg = MI.getOperand(0).getReg(); 9223 Register HiReg = MI.getOperand(1).getReg(); 9224 DebugLoc DL = MI.getDebugLoc(); 9225 9226 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9227 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9228 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9229 .addReg(RISCV::X0); 9230 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9231 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9232 .addReg(RISCV::X0); 9233 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9234 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9235 .addReg(RISCV::X0); 9236 9237 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9238 .addReg(HiReg) 9239 .addReg(ReadAgainReg) 9240 .addMBB(LoopMBB); 9241 9242 LoopMBB->addSuccessor(LoopMBB); 9243 LoopMBB->addSuccessor(DoneMBB); 9244 9245 MI.eraseFromParent(); 9246 9247 return DoneMBB; 9248 } 9249 9250 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9251 MachineBasicBlock *BB) { 9252 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9253 9254 MachineFunction &MF = *BB->getParent(); 9255 DebugLoc DL = MI.getDebugLoc(); 9256 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9257 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9258 Register LoReg = MI.getOperand(0).getReg(); 9259 Register HiReg = MI.getOperand(1).getReg(); 9260 Register SrcReg = MI.getOperand(2).getReg(); 9261 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9262 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9263 9264 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9265 RI); 9266 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9267 MachineMemOperand *MMOLo = 9268 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9269 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9270 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9271 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9272 .addFrameIndex(FI) 9273 .addImm(0) 9274 .addMemOperand(MMOLo); 9275 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9276 .addFrameIndex(FI) 9277 .addImm(4) 9278 .addMemOperand(MMOHi); 9279 MI.eraseFromParent(); // The pseudo instruction is gone now. 9280 return BB; 9281 } 9282 9283 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9284 MachineBasicBlock *BB) { 9285 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9286 "Unexpected instruction"); 9287 9288 MachineFunction &MF = *BB->getParent(); 9289 DebugLoc DL = MI.getDebugLoc(); 9290 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9291 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9292 Register DstReg = MI.getOperand(0).getReg(); 9293 Register LoReg = MI.getOperand(1).getReg(); 9294 Register HiReg = MI.getOperand(2).getReg(); 9295 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9296 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9297 9298 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9299 MachineMemOperand *MMOLo = 9300 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9301 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9302 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9303 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9304 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9305 .addFrameIndex(FI) 9306 .addImm(0) 9307 .addMemOperand(MMOLo); 9308 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9309 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9310 .addFrameIndex(FI) 9311 .addImm(4) 9312 .addMemOperand(MMOHi); 9313 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9314 MI.eraseFromParent(); // The pseudo instruction is gone now. 9315 return BB; 9316 } 9317 9318 static bool isSelectPseudo(MachineInstr &MI) { 9319 switch (MI.getOpcode()) { 9320 default: 9321 return false; 9322 case RISCV::Select_GPR_Using_CC_GPR: 9323 case RISCV::Select_FPR16_Using_CC_GPR: 9324 case RISCV::Select_FPR32_Using_CC_GPR: 9325 case RISCV::Select_FPR64_Using_CC_GPR: 9326 return true; 9327 } 9328 } 9329 9330 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9331 unsigned RelOpcode, unsigned EqOpcode, 9332 const RISCVSubtarget &Subtarget) { 9333 DebugLoc DL = MI.getDebugLoc(); 9334 Register DstReg = MI.getOperand(0).getReg(); 9335 Register Src1Reg = MI.getOperand(1).getReg(); 9336 Register Src2Reg = MI.getOperand(2).getReg(); 9337 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9338 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9339 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9340 9341 // Save the current FFLAGS. 9342 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9343 9344 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9345 .addReg(Src1Reg) 9346 .addReg(Src2Reg); 9347 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9348 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9349 9350 // Restore the FFLAGS. 9351 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9352 .addReg(SavedFFlags, RegState::Kill); 9353 9354 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9355 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9356 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9357 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9358 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9359 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9360 9361 // Erase the pseudoinstruction. 9362 MI.eraseFromParent(); 9363 return BB; 9364 } 9365 9366 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9367 MachineBasicBlock *BB, 9368 const RISCVSubtarget &Subtarget) { 9369 // To "insert" Select_* instructions, we actually have to insert the triangle 9370 // control-flow pattern. The incoming instructions know the destination vreg 9371 // to set, the condition code register to branch on, the true/false values to 9372 // select between, and the condcode to use to select the appropriate branch. 9373 // 9374 // We produce the following control flow: 9375 // HeadMBB 9376 // | \ 9377 // | IfFalseMBB 9378 // | / 9379 // TailMBB 9380 // 9381 // When we find a sequence of selects we attempt to optimize their emission 9382 // by sharing the control flow. Currently we only handle cases where we have 9383 // multiple selects with the exact same condition (same LHS, RHS and CC). 9384 // The selects may be interleaved with other instructions if the other 9385 // instructions meet some requirements we deem safe: 9386 // - They are debug instructions. Otherwise, 9387 // - They do not have side-effects, do not access memory and their inputs do 9388 // not depend on the results of the select pseudo-instructions. 9389 // The TrueV/FalseV operands of the selects cannot depend on the result of 9390 // previous selects in the sequence. 9391 // These conditions could be further relaxed. See the X86 target for a 9392 // related approach and more information. 9393 Register LHS = MI.getOperand(1).getReg(); 9394 Register RHS = MI.getOperand(2).getReg(); 9395 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9396 9397 SmallVector<MachineInstr *, 4> SelectDebugValues; 9398 SmallSet<Register, 4> SelectDests; 9399 SelectDests.insert(MI.getOperand(0).getReg()); 9400 9401 MachineInstr *LastSelectPseudo = &MI; 9402 9403 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9404 SequenceMBBI != E; ++SequenceMBBI) { 9405 if (SequenceMBBI->isDebugInstr()) 9406 continue; 9407 else if (isSelectPseudo(*SequenceMBBI)) { 9408 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9409 SequenceMBBI->getOperand(2).getReg() != RHS || 9410 SequenceMBBI->getOperand(3).getImm() != CC || 9411 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9412 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9413 break; 9414 LastSelectPseudo = &*SequenceMBBI; 9415 SequenceMBBI->collectDebugValues(SelectDebugValues); 9416 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9417 } else { 9418 if (SequenceMBBI->hasUnmodeledSideEffects() || 9419 SequenceMBBI->mayLoadOrStore()) 9420 break; 9421 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9422 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9423 })) 9424 break; 9425 } 9426 } 9427 9428 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9429 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9430 DebugLoc DL = MI.getDebugLoc(); 9431 MachineFunction::iterator I = ++BB->getIterator(); 9432 9433 MachineBasicBlock *HeadMBB = BB; 9434 MachineFunction *F = BB->getParent(); 9435 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9436 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9437 9438 F->insert(I, IfFalseMBB); 9439 F->insert(I, TailMBB); 9440 9441 // Transfer debug instructions associated with the selects to TailMBB. 9442 for (MachineInstr *DebugInstr : SelectDebugValues) { 9443 TailMBB->push_back(DebugInstr->removeFromParent()); 9444 } 9445 9446 // Move all instructions after the sequence to TailMBB. 9447 TailMBB->splice(TailMBB->end(), HeadMBB, 9448 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9449 // Update machine-CFG edges by transferring all successors of the current 9450 // block to the new block which will contain the Phi nodes for the selects. 9451 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9452 // Set the successors for HeadMBB. 9453 HeadMBB->addSuccessor(IfFalseMBB); 9454 HeadMBB->addSuccessor(TailMBB); 9455 9456 // Insert appropriate branch. 9457 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9458 .addReg(LHS) 9459 .addReg(RHS) 9460 .addMBB(TailMBB); 9461 9462 // IfFalseMBB just falls through to TailMBB. 9463 IfFalseMBB->addSuccessor(TailMBB); 9464 9465 // Create PHIs for all of the select pseudo-instructions. 9466 auto SelectMBBI = MI.getIterator(); 9467 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9468 auto InsertionPoint = TailMBB->begin(); 9469 while (SelectMBBI != SelectEnd) { 9470 auto Next = std::next(SelectMBBI); 9471 if (isSelectPseudo(*SelectMBBI)) { 9472 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9473 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9474 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9475 .addReg(SelectMBBI->getOperand(4).getReg()) 9476 .addMBB(HeadMBB) 9477 .addReg(SelectMBBI->getOperand(5).getReg()) 9478 .addMBB(IfFalseMBB); 9479 SelectMBBI->eraseFromParent(); 9480 } 9481 SelectMBBI = Next; 9482 } 9483 9484 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9485 return TailMBB; 9486 } 9487 9488 MachineBasicBlock * 9489 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9490 MachineBasicBlock *BB) const { 9491 switch (MI.getOpcode()) { 9492 default: 9493 llvm_unreachable("Unexpected instr type to insert"); 9494 case RISCV::ReadCycleWide: 9495 assert(!Subtarget.is64Bit() && 9496 "ReadCycleWrite is only to be used on riscv32"); 9497 return emitReadCycleWidePseudo(MI, BB); 9498 case RISCV::Select_GPR_Using_CC_GPR: 9499 case RISCV::Select_FPR16_Using_CC_GPR: 9500 case RISCV::Select_FPR32_Using_CC_GPR: 9501 case RISCV::Select_FPR64_Using_CC_GPR: 9502 return emitSelectPseudo(MI, BB, Subtarget); 9503 case RISCV::BuildPairF64Pseudo: 9504 return emitBuildPairF64Pseudo(MI, BB); 9505 case RISCV::SplitF64Pseudo: 9506 return emitSplitF64Pseudo(MI, BB); 9507 case RISCV::PseudoQuietFLE_H: 9508 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9509 case RISCV::PseudoQuietFLT_H: 9510 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9511 case RISCV::PseudoQuietFLE_S: 9512 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9513 case RISCV::PseudoQuietFLT_S: 9514 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9515 case RISCV::PseudoQuietFLE_D: 9516 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9517 case RISCV::PseudoQuietFLT_D: 9518 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9519 } 9520 } 9521 9522 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9523 SDNode *Node) const { 9524 // Add FRM dependency to any instructions with dynamic rounding mode. 9525 unsigned Opc = MI.getOpcode(); 9526 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9527 if (Idx < 0) 9528 return; 9529 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9530 return; 9531 // If the instruction already reads FRM, don't add another read. 9532 if (MI.readsRegister(RISCV::FRM)) 9533 return; 9534 MI.addOperand( 9535 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9536 } 9537 9538 // Calling Convention Implementation. 9539 // The expectations for frontend ABI lowering vary from target to target. 9540 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9541 // details, but this is a longer term goal. For now, we simply try to keep the 9542 // role of the frontend as simple and well-defined as possible. The rules can 9543 // be summarised as: 9544 // * Never split up large scalar arguments. We handle them here. 9545 // * If a hardfloat calling convention is being used, and the struct may be 9546 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9547 // available, then pass as two separate arguments. If either the GPRs or FPRs 9548 // are exhausted, then pass according to the rule below. 9549 // * If a struct could never be passed in registers or directly in a stack 9550 // slot (as it is larger than 2*XLEN and the floating point rules don't 9551 // apply), then pass it using a pointer with the byval attribute. 9552 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9553 // word-sized array or a 2*XLEN scalar (depending on alignment). 9554 // * The frontend can determine whether a struct is returned by reference or 9555 // not based on its size and fields. If it will be returned by reference, the 9556 // frontend must modify the prototype so a pointer with the sret annotation is 9557 // passed as the first argument. This is not necessary for large scalar 9558 // returns. 9559 // * Struct return values and varargs should be coerced to structs containing 9560 // register-size fields in the same situations they would be for fixed 9561 // arguments. 9562 9563 static const MCPhysReg ArgGPRs[] = { 9564 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9565 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9566 }; 9567 static const MCPhysReg ArgFPR16s[] = { 9568 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9569 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9570 }; 9571 static const MCPhysReg ArgFPR32s[] = { 9572 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9573 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9574 }; 9575 static const MCPhysReg ArgFPR64s[] = { 9576 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9577 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9578 }; 9579 // This is an interim calling convention and it may be changed in the future. 9580 static const MCPhysReg ArgVRs[] = { 9581 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9582 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9583 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9584 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9585 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9586 RISCV::V20M2, RISCV::V22M2}; 9587 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9588 RISCV::V20M4}; 9589 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9590 9591 // Pass a 2*XLEN argument that has been split into two XLEN values through 9592 // registers or the stack as necessary. 9593 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9594 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9595 MVT ValVT2, MVT LocVT2, 9596 ISD::ArgFlagsTy ArgFlags2) { 9597 unsigned XLenInBytes = XLen / 8; 9598 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9599 // At least one half can be passed via register. 9600 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9601 VA1.getLocVT(), CCValAssign::Full)); 9602 } else { 9603 // Both halves must be passed on the stack, with proper alignment. 9604 Align StackAlign = 9605 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9606 State.addLoc( 9607 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9608 State.AllocateStack(XLenInBytes, StackAlign), 9609 VA1.getLocVT(), CCValAssign::Full)); 9610 State.addLoc(CCValAssign::getMem( 9611 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9612 LocVT2, CCValAssign::Full)); 9613 return false; 9614 } 9615 9616 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9617 // The second half can also be passed via register. 9618 State.addLoc( 9619 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9620 } else { 9621 // The second half is passed via the stack, without additional alignment. 9622 State.addLoc(CCValAssign::getMem( 9623 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9624 LocVT2, CCValAssign::Full)); 9625 } 9626 9627 return false; 9628 } 9629 9630 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9631 Optional<unsigned> FirstMaskArgument, 9632 CCState &State, const RISCVTargetLowering &TLI) { 9633 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9634 if (RC == &RISCV::VRRegClass) { 9635 // Assign the first mask argument to V0. 9636 // This is an interim calling convention and it may be changed in the 9637 // future. 9638 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9639 return State.AllocateReg(RISCV::V0); 9640 return State.AllocateReg(ArgVRs); 9641 } 9642 if (RC == &RISCV::VRM2RegClass) 9643 return State.AllocateReg(ArgVRM2s); 9644 if (RC == &RISCV::VRM4RegClass) 9645 return State.AllocateReg(ArgVRM4s); 9646 if (RC == &RISCV::VRM8RegClass) 9647 return State.AllocateReg(ArgVRM8s); 9648 llvm_unreachable("Unhandled register class for ValueType"); 9649 } 9650 9651 // Implements the RISC-V calling convention. Returns true upon failure. 9652 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9653 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9654 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9655 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9656 Optional<unsigned> FirstMaskArgument) { 9657 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9658 assert(XLen == 32 || XLen == 64); 9659 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9660 9661 // Any return value split in to more than two values can't be returned 9662 // directly. Vectors are returned via the available vector registers. 9663 if (!LocVT.isVector() && IsRet && ValNo > 1) 9664 return true; 9665 9666 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9667 // variadic argument, or if no F16/F32 argument registers are available. 9668 bool UseGPRForF16_F32 = true; 9669 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9670 // variadic argument, or if no F64 argument registers are available. 9671 bool UseGPRForF64 = true; 9672 9673 switch (ABI) { 9674 default: 9675 llvm_unreachable("Unexpected ABI"); 9676 case RISCVABI::ABI_ILP32: 9677 case RISCVABI::ABI_LP64: 9678 break; 9679 case RISCVABI::ABI_ILP32F: 9680 case RISCVABI::ABI_LP64F: 9681 UseGPRForF16_F32 = !IsFixed; 9682 break; 9683 case RISCVABI::ABI_ILP32D: 9684 case RISCVABI::ABI_LP64D: 9685 UseGPRForF16_F32 = !IsFixed; 9686 UseGPRForF64 = !IsFixed; 9687 break; 9688 } 9689 9690 // FPR16, FPR32, and FPR64 alias each other. 9691 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9692 UseGPRForF16_F32 = true; 9693 UseGPRForF64 = true; 9694 } 9695 9696 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9697 // similar local variables rather than directly checking against the target 9698 // ABI. 9699 9700 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9701 LocVT = XLenVT; 9702 LocInfo = CCValAssign::BCvt; 9703 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9704 LocVT = MVT::i64; 9705 LocInfo = CCValAssign::BCvt; 9706 } 9707 9708 // If this is a variadic argument, the RISC-V calling convention requires 9709 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9710 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9711 // be used regardless of whether the original argument was split during 9712 // legalisation or not. The argument will not be passed by registers if the 9713 // original type is larger than 2*XLEN, so the register alignment rule does 9714 // not apply. 9715 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9716 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9717 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9718 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9719 // Skip 'odd' register if necessary. 9720 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9721 State.AllocateReg(ArgGPRs); 9722 } 9723 9724 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9725 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9726 State.getPendingArgFlags(); 9727 9728 assert(PendingLocs.size() == PendingArgFlags.size() && 9729 "PendingLocs and PendingArgFlags out of sync"); 9730 9731 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9732 // registers are exhausted. 9733 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9734 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9735 "Can't lower f64 if it is split"); 9736 // Depending on available argument GPRS, f64 may be passed in a pair of 9737 // GPRs, split between a GPR and the stack, or passed completely on the 9738 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9739 // cases. 9740 Register Reg = State.AllocateReg(ArgGPRs); 9741 LocVT = MVT::i32; 9742 if (!Reg) { 9743 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9744 State.addLoc( 9745 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9746 return false; 9747 } 9748 if (!State.AllocateReg(ArgGPRs)) 9749 State.AllocateStack(4, Align(4)); 9750 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9751 return false; 9752 } 9753 9754 // Fixed-length vectors are located in the corresponding scalable-vector 9755 // container types. 9756 if (ValVT.isFixedLengthVector()) 9757 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9758 9759 // Split arguments might be passed indirectly, so keep track of the pending 9760 // values. Split vectors are passed via a mix of registers and indirectly, so 9761 // treat them as we would any other argument. 9762 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9763 LocVT = XLenVT; 9764 LocInfo = CCValAssign::Indirect; 9765 PendingLocs.push_back( 9766 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9767 PendingArgFlags.push_back(ArgFlags); 9768 if (!ArgFlags.isSplitEnd()) { 9769 return false; 9770 } 9771 } 9772 9773 // If the split argument only had two elements, it should be passed directly 9774 // in registers or on the stack. 9775 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9776 PendingLocs.size() <= 2) { 9777 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9778 // Apply the normal calling convention rules to the first half of the 9779 // split argument. 9780 CCValAssign VA = PendingLocs[0]; 9781 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9782 PendingLocs.clear(); 9783 PendingArgFlags.clear(); 9784 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9785 ArgFlags); 9786 } 9787 9788 // Allocate to a register if possible, or else a stack slot. 9789 Register Reg; 9790 unsigned StoreSizeBytes = XLen / 8; 9791 Align StackAlign = Align(XLen / 8); 9792 9793 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9794 Reg = State.AllocateReg(ArgFPR16s); 9795 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9796 Reg = State.AllocateReg(ArgFPR32s); 9797 else if (ValVT == MVT::f64 && !UseGPRForF64) 9798 Reg = State.AllocateReg(ArgFPR64s); 9799 else if (ValVT.isVector()) { 9800 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9801 if (!Reg) { 9802 // For return values, the vector must be passed fully via registers or 9803 // via the stack. 9804 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9805 // but we're using all of them. 9806 if (IsRet) 9807 return true; 9808 // Try using a GPR to pass the address 9809 if ((Reg = State.AllocateReg(ArgGPRs))) { 9810 LocVT = XLenVT; 9811 LocInfo = CCValAssign::Indirect; 9812 } else if (ValVT.isScalableVector()) { 9813 LocVT = XLenVT; 9814 LocInfo = CCValAssign::Indirect; 9815 } else { 9816 // Pass fixed-length vectors on the stack. 9817 LocVT = ValVT; 9818 StoreSizeBytes = ValVT.getStoreSize(); 9819 // Align vectors to their element sizes, being careful for vXi1 9820 // vectors. 9821 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9822 } 9823 } 9824 } else { 9825 Reg = State.AllocateReg(ArgGPRs); 9826 } 9827 9828 unsigned StackOffset = 9829 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9830 9831 // If we reach this point and PendingLocs is non-empty, we must be at the 9832 // end of a split argument that must be passed indirectly. 9833 if (!PendingLocs.empty()) { 9834 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9835 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9836 9837 for (auto &It : PendingLocs) { 9838 if (Reg) 9839 It.convertToReg(Reg); 9840 else 9841 It.convertToMem(StackOffset); 9842 State.addLoc(It); 9843 } 9844 PendingLocs.clear(); 9845 PendingArgFlags.clear(); 9846 return false; 9847 } 9848 9849 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9850 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9851 "Expected an XLenVT or vector types at this stage"); 9852 9853 if (Reg) { 9854 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9855 return false; 9856 } 9857 9858 // When a floating-point value is passed on the stack, no bit-conversion is 9859 // needed. 9860 if (ValVT.isFloatingPoint()) { 9861 LocVT = ValVT; 9862 LocInfo = CCValAssign::Full; 9863 } 9864 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9865 return false; 9866 } 9867 9868 template <typename ArgTy> 9869 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9870 for (const auto &ArgIdx : enumerate(Args)) { 9871 MVT ArgVT = ArgIdx.value().VT; 9872 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9873 return ArgIdx.index(); 9874 } 9875 return None; 9876 } 9877 9878 void RISCVTargetLowering::analyzeInputArgs( 9879 MachineFunction &MF, CCState &CCInfo, 9880 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9881 RISCVCCAssignFn Fn) const { 9882 unsigned NumArgs = Ins.size(); 9883 FunctionType *FType = MF.getFunction().getFunctionType(); 9884 9885 Optional<unsigned> FirstMaskArgument; 9886 if (Subtarget.hasVInstructions()) 9887 FirstMaskArgument = preAssignMask(Ins); 9888 9889 for (unsigned i = 0; i != NumArgs; ++i) { 9890 MVT ArgVT = Ins[i].VT; 9891 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9892 9893 Type *ArgTy = nullptr; 9894 if (IsRet) 9895 ArgTy = FType->getReturnType(); 9896 else if (Ins[i].isOrigArg()) 9897 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9898 9899 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9900 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9901 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9902 FirstMaskArgument)) { 9903 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9904 << EVT(ArgVT).getEVTString() << '\n'); 9905 llvm_unreachable(nullptr); 9906 } 9907 } 9908 } 9909 9910 void RISCVTargetLowering::analyzeOutputArgs( 9911 MachineFunction &MF, CCState &CCInfo, 9912 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9913 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9914 unsigned NumArgs = Outs.size(); 9915 9916 Optional<unsigned> FirstMaskArgument; 9917 if (Subtarget.hasVInstructions()) 9918 FirstMaskArgument = preAssignMask(Outs); 9919 9920 for (unsigned i = 0; i != NumArgs; i++) { 9921 MVT ArgVT = Outs[i].VT; 9922 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9923 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9924 9925 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9926 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9927 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9928 FirstMaskArgument)) { 9929 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9930 << EVT(ArgVT).getEVTString() << "\n"); 9931 llvm_unreachable(nullptr); 9932 } 9933 } 9934 } 9935 9936 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9937 // values. 9938 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9939 const CCValAssign &VA, const SDLoc &DL, 9940 const RISCVSubtarget &Subtarget) { 9941 switch (VA.getLocInfo()) { 9942 default: 9943 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9944 case CCValAssign::Full: 9945 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9946 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9947 break; 9948 case CCValAssign::BCvt: 9949 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9950 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9951 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9952 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9953 else 9954 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9955 break; 9956 } 9957 return Val; 9958 } 9959 9960 // The caller is responsible for loading the full value if the argument is 9961 // passed with CCValAssign::Indirect. 9962 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9963 const CCValAssign &VA, const SDLoc &DL, 9964 const RISCVTargetLowering &TLI) { 9965 MachineFunction &MF = DAG.getMachineFunction(); 9966 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9967 EVT LocVT = VA.getLocVT(); 9968 SDValue Val; 9969 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9970 Register VReg = RegInfo.createVirtualRegister(RC); 9971 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9972 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9973 9974 if (VA.getLocInfo() == CCValAssign::Indirect) 9975 return Val; 9976 9977 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9978 } 9979 9980 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9981 const CCValAssign &VA, const SDLoc &DL, 9982 const RISCVSubtarget &Subtarget) { 9983 EVT LocVT = VA.getLocVT(); 9984 9985 switch (VA.getLocInfo()) { 9986 default: 9987 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9988 case CCValAssign::Full: 9989 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9990 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9991 break; 9992 case CCValAssign::BCvt: 9993 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9994 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9995 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9996 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9997 else 9998 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9999 break; 10000 } 10001 return Val; 10002 } 10003 10004 // The caller is responsible for loading the full value if the argument is 10005 // passed with CCValAssign::Indirect. 10006 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10007 const CCValAssign &VA, const SDLoc &DL) { 10008 MachineFunction &MF = DAG.getMachineFunction(); 10009 MachineFrameInfo &MFI = MF.getFrameInfo(); 10010 EVT LocVT = VA.getLocVT(); 10011 EVT ValVT = VA.getValVT(); 10012 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10013 if (ValVT.isScalableVector()) { 10014 // When the value is a scalable vector, we save the pointer which points to 10015 // the scalable vector value in the stack. The ValVT will be the pointer 10016 // type, instead of the scalable vector type. 10017 ValVT = LocVT; 10018 } 10019 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10020 /*IsImmutable=*/true); 10021 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10022 SDValue Val; 10023 10024 ISD::LoadExtType ExtType; 10025 switch (VA.getLocInfo()) { 10026 default: 10027 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10028 case CCValAssign::Full: 10029 case CCValAssign::Indirect: 10030 case CCValAssign::BCvt: 10031 ExtType = ISD::NON_EXTLOAD; 10032 break; 10033 } 10034 Val = DAG.getExtLoad( 10035 ExtType, DL, LocVT, Chain, FIN, 10036 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10037 return Val; 10038 } 10039 10040 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10041 const CCValAssign &VA, const SDLoc &DL) { 10042 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10043 "Unexpected VA"); 10044 MachineFunction &MF = DAG.getMachineFunction(); 10045 MachineFrameInfo &MFI = MF.getFrameInfo(); 10046 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10047 10048 if (VA.isMemLoc()) { 10049 // f64 is passed on the stack. 10050 int FI = 10051 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10052 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10053 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10054 MachinePointerInfo::getFixedStack(MF, FI)); 10055 } 10056 10057 assert(VA.isRegLoc() && "Expected register VA assignment"); 10058 10059 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10060 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10061 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10062 SDValue Hi; 10063 if (VA.getLocReg() == RISCV::X17) { 10064 // Second half of f64 is passed on the stack. 10065 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10066 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10067 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10068 MachinePointerInfo::getFixedStack(MF, FI)); 10069 } else { 10070 // Second half of f64 is passed in another GPR. 10071 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10072 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10073 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10074 } 10075 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10076 } 10077 10078 // FastCC has less than 1% performance improvement for some particular 10079 // benchmark. But theoretically, it may has benenfit for some cases. 10080 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10081 unsigned ValNo, MVT ValVT, MVT LocVT, 10082 CCValAssign::LocInfo LocInfo, 10083 ISD::ArgFlagsTy ArgFlags, CCState &State, 10084 bool IsFixed, bool IsRet, Type *OrigTy, 10085 const RISCVTargetLowering &TLI, 10086 Optional<unsigned> FirstMaskArgument) { 10087 10088 // X5 and X6 might be used for save-restore libcall. 10089 static const MCPhysReg GPRList[] = { 10090 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10091 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10092 RISCV::X29, RISCV::X30, RISCV::X31}; 10093 10094 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10095 if (unsigned Reg = State.AllocateReg(GPRList)) { 10096 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10097 return false; 10098 } 10099 } 10100 10101 if (LocVT == MVT::f16) { 10102 static const MCPhysReg FPR16List[] = { 10103 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10104 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10105 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10106 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10107 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10108 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10109 return false; 10110 } 10111 } 10112 10113 if (LocVT == MVT::f32) { 10114 static const MCPhysReg FPR32List[] = { 10115 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10116 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10117 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10118 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10119 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10120 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10121 return false; 10122 } 10123 } 10124 10125 if (LocVT == MVT::f64) { 10126 static const MCPhysReg FPR64List[] = { 10127 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10128 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10129 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10130 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10131 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10132 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10133 return false; 10134 } 10135 } 10136 10137 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10138 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10139 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10140 return false; 10141 } 10142 10143 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10144 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10145 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10146 return false; 10147 } 10148 10149 if (LocVT.isVector()) { 10150 if (unsigned Reg = 10151 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10152 // Fixed-length vectors are located in the corresponding scalable-vector 10153 // container types. 10154 if (ValVT.isFixedLengthVector()) 10155 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10156 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10157 } else { 10158 // Try and pass the address via a "fast" GPR. 10159 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10160 LocInfo = CCValAssign::Indirect; 10161 LocVT = TLI.getSubtarget().getXLenVT(); 10162 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10163 } else if (ValVT.isFixedLengthVector()) { 10164 auto StackAlign = 10165 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10166 unsigned StackOffset = 10167 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10168 State.addLoc( 10169 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10170 } else { 10171 // Can't pass scalable vectors on the stack. 10172 return true; 10173 } 10174 } 10175 10176 return false; 10177 } 10178 10179 return true; // CC didn't match. 10180 } 10181 10182 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10183 CCValAssign::LocInfo LocInfo, 10184 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10185 10186 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10187 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10188 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10189 static const MCPhysReg GPRList[] = { 10190 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10191 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10192 if (unsigned Reg = State.AllocateReg(GPRList)) { 10193 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10194 return false; 10195 } 10196 } 10197 10198 if (LocVT == MVT::f32) { 10199 // Pass in STG registers: F1, ..., F6 10200 // fs0 ... fs5 10201 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10202 RISCV::F18_F, RISCV::F19_F, 10203 RISCV::F20_F, RISCV::F21_F}; 10204 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10205 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10206 return false; 10207 } 10208 } 10209 10210 if (LocVT == MVT::f64) { 10211 // Pass in STG registers: D1, ..., D6 10212 // fs6 ... fs11 10213 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10214 RISCV::F24_D, RISCV::F25_D, 10215 RISCV::F26_D, RISCV::F27_D}; 10216 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10217 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10218 return false; 10219 } 10220 } 10221 10222 report_fatal_error("No registers left in GHC calling convention"); 10223 return true; 10224 } 10225 10226 // Transform physical registers into virtual registers. 10227 SDValue RISCVTargetLowering::LowerFormalArguments( 10228 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10229 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10230 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10231 10232 MachineFunction &MF = DAG.getMachineFunction(); 10233 10234 switch (CallConv) { 10235 default: 10236 report_fatal_error("Unsupported calling convention"); 10237 case CallingConv::C: 10238 case CallingConv::Fast: 10239 break; 10240 case CallingConv::GHC: 10241 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10242 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10243 report_fatal_error( 10244 "GHC calling convention requires the F and D instruction set extensions"); 10245 } 10246 10247 const Function &Func = MF.getFunction(); 10248 if (Func.hasFnAttribute("interrupt")) { 10249 if (!Func.arg_empty()) 10250 report_fatal_error( 10251 "Functions with the interrupt attribute cannot have arguments!"); 10252 10253 StringRef Kind = 10254 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10255 10256 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10257 report_fatal_error( 10258 "Function interrupt attribute argument not supported!"); 10259 } 10260 10261 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10262 MVT XLenVT = Subtarget.getXLenVT(); 10263 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10264 // Used with vargs to acumulate store chains. 10265 std::vector<SDValue> OutChains; 10266 10267 // Assign locations to all of the incoming arguments. 10268 SmallVector<CCValAssign, 16> ArgLocs; 10269 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10270 10271 if (CallConv == CallingConv::GHC) 10272 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10273 else 10274 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10275 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10276 : CC_RISCV); 10277 10278 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10279 CCValAssign &VA = ArgLocs[i]; 10280 SDValue ArgValue; 10281 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10282 // case. 10283 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10284 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10285 else if (VA.isRegLoc()) 10286 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10287 else 10288 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10289 10290 if (VA.getLocInfo() == CCValAssign::Indirect) { 10291 // If the original argument was split and passed by reference (e.g. i128 10292 // on RV32), we need to load all parts of it here (using the same 10293 // address). Vectors may be partly split to registers and partly to the 10294 // stack, in which case the base address is partly offset and subsequent 10295 // stores are relative to that. 10296 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10297 MachinePointerInfo())); 10298 unsigned ArgIndex = Ins[i].OrigArgIndex; 10299 unsigned ArgPartOffset = Ins[i].PartOffset; 10300 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10301 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10302 CCValAssign &PartVA = ArgLocs[i + 1]; 10303 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10304 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10305 if (PartVA.getValVT().isScalableVector()) 10306 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10307 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10308 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10309 MachinePointerInfo())); 10310 ++i; 10311 } 10312 continue; 10313 } 10314 InVals.push_back(ArgValue); 10315 } 10316 10317 if (IsVarArg) { 10318 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10319 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10320 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10321 MachineFrameInfo &MFI = MF.getFrameInfo(); 10322 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10323 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10324 10325 // Offset of the first variable argument from stack pointer, and size of 10326 // the vararg save area. For now, the varargs save area is either zero or 10327 // large enough to hold a0-a7. 10328 int VaArgOffset, VarArgsSaveSize; 10329 10330 // If all registers are allocated, then all varargs must be passed on the 10331 // stack and we don't need to save any argregs. 10332 if (ArgRegs.size() == Idx) { 10333 VaArgOffset = CCInfo.getNextStackOffset(); 10334 VarArgsSaveSize = 0; 10335 } else { 10336 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10337 VaArgOffset = -VarArgsSaveSize; 10338 } 10339 10340 // Record the frame index of the first variable argument 10341 // which is a value necessary to VASTART. 10342 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10343 RVFI->setVarArgsFrameIndex(FI); 10344 10345 // If saving an odd number of registers then create an extra stack slot to 10346 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10347 // offsets to even-numbered registered remain 2*XLEN-aligned. 10348 if (Idx % 2) { 10349 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10350 VarArgsSaveSize += XLenInBytes; 10351 } 10352 10353 // Copy the integer registers that may have been used for passing varargs 10354 // to the vararg save area. 10355 for (unsigned I = Idx; I < ArgRegs.size(); 10356 ++I, VaArgOffset += XLenInBytes) { 10357 const Register Reg = RegInfo.createVirtualRegister(RC); 10358 RegInfo.addLiveIn(ArgRegs[I], Reg); 10359 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10360 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10361 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10362 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10363 MachinePointerInfo::getFixedStack(MF, FI)); 10364 cast<StoreSDNode>(Store.getNode()) 10365 ->getMemOperand() 10366 ->setValue((Value *)nullptr); 10367 OutChains.push_back(Store); 10368 } 10369 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10370 } 10371 10372 // All stores are grouped in one node to allow the matching between 10373 // the size of Ins and InVals. This only happens for vararg functions. 10374 if (!OutChains.empty()) { 10375 OutChains.push_back(Chain); 10376 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10377 } 10378 10379 return Chain; 10380 } 10381 10382 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10383 /// for tail call optimization. 10384 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10385 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10386 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10387 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10388 10389 auto &Callee = CLI.Callee; 10390 auto CalleeCC = CLI.CallConv; 10391 auto &Outs = CLI.Outs; 10392 auto &Caller = MF.getFunction(); 10393 auto CallerCC = Caller.getCallingConv(); 10394 10395 // Exception-handling functions need a special set of instructions to 10396 // indicate a return to the hardware. Tail-calling another function would 10397 // probably break this. 10398 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10399 // should be expanded as new function attributes are introduced. 10400 if (Caller.hasFnAttribute("interrupt")) 10401 return false; 10402 10403 // Do not tail call opt if the stack is used to pass parameters. 10404 if (CCInfo.getNextStackOffset() != 0) 10405 return false; 10406 10407 // Do not tail call opt if any parameters need to be passed indirectly. 10408 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10409 // passed indirectly. So the address of the value will be passed in a 10410 // register, or if not available, then the address is put on the stack. In 10411 // order to pass indirectly, space on the stack often needs to be allocated 10412 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10413 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10414 // are passed CCValAssign::Indirect. 10415 for (auto &VA : ArgLocs) 10416 if (VA.getLocInfo() == CCValAssign::Indirect) 10417 return false; 10418 10419 // Do not tail call opt if either caller or callee uses struct return 10420 // semantics. 10421 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10422 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10423 if (IsCallerStructRet || IsCalleeStructRet) 10424 return false; 10425 10426 // Externally-defined functions with weak linkage should not be 10427 // tail-called. The behaviour of branch instructions in this situation (as 10428 // used for tail calls) is implementation-defined, so we cannot rely on the 10429 // linker replacing the tail call with a return. 10430 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10431 const GlobalValue *GV = G->getGlobal(); 10432 if (GV->hasExternalWeakLinkage()) 10433 return false; 10434 } 10435 10436 // The callee has to preserve all registers the caller needs to preserve. 10437 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10438 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10439 if (CalleeCC != CallerCC) { 10440 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10441 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10442 return false; 10443 } 10444 10445 // Byval parameters hand the function a pointer directly into the stack area 10446 // we want to reuse during a tail call. Working around this *is* possible 10447 // but less efficient and uglier in LowerCall. 10448 for (auto &Arg : Outs) 10449 if (Arg.Flags.isByVal()) 10450 return false; 10451 10452 return true; 10453 } 10454 10455 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10456 return DAG.getDataLayout().getPrefTypeAlign( 10457 VT.getTypeForEVT(*DAG.getContext())); 10458 } 10459 10460 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10461 // and output parameter nodes. 10462 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10463 SmallVectorImpl<SDValue> &InVals) const { 10464 SelectionDAG &DAG = CLI.DAG; 10465 SDLoc &DL = CLI.DL; 10466 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10467 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10468 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10469 SDValue Chain = CLI.Chain; 10470 SDValue Callee = CLI.Callee; 10471 bool &IsTailCall = CLI.IsTailCall; 10472 CallingConv::ID CallConv = CLI.CallConv; 10473 bool IsVarArg = CLI.IsVarArg; 10474 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10475 MVT XLenVT = Subtarget.getXLenVT(); 10476 10477 MachineFunction &MF = DAG.getMachineFunction(); 10478 10479 // Analyze the operands of the call, assigning locations to each operand. 10480 SmallVector<CCValAssign, 16> ArgLocs; 10481 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10482 10483 if (CallConv == CallingConv::GHC) 10484 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10485 else 10486 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10487 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10488 : CC_RISCV); 10489 10490 // Check if it's really possible to do a tail call. 10491 if (IsTailCall) 10492 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10493 10494 if (IsTailCall) 10495 ++NumTailCalls; 10496 else if (CLI.CB && CLI.CB->isMustTailCall()) 10497 report_fatal_error("failed to perform tail call elimination on a call " 10498 "site marked musttail"); 10499 10500 // Get a count of how many bytes are to be pushed on the stack. 10501 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10502 10503 // Create local copies for byval args 10504 SmallVector<SDValue, 8> ByValArgs; 10505 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10506 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10507 if (!Flags.isByVal()) 10508 continue; 10509 10510 SDValue Arg = OutVals[i]; 10511 unsigned Size = Flags.getByValSize(); 10512 Align Alignment = Flags.getNonZeroByValAlign(); 10513 10514 int FI = 10515 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10516 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10517 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10518 10519 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10520 /*IsVolatile=*/false, 10521 /*AlwaysInline=*/false, IsTailCall, 10522 MachinePointerInfo(), MachinePointerInfo()); 10523 ByValArgs.push_back(FIPtr); 10524 } 10525 10526 if (!IsTailCall) 10527 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10528 10529 // Copy argument values to their designated locations. 10530 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10531 SmallVector<SDValue, 8> MemOpChains; 10532 SDValue StackPtr; 10533 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10534 CCValAssign &VA = ArgLocs[i]; 10535 SDValue ArgValue = OutVals[i]; 10536 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10537 10538 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10539 bool IsF64OnRV32DSoftABI = 10540 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10541 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10542 SDValue SplitF64 = DAG.getNode( 10543 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10544 SDValue Lo = SplitF64.getValue(0); 10545 SDValue Hi = SplitF64.getValue(1); 10546 10547 Register RegLo = VA.getLocReg(); 10548 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10549 10550 if (RegLo == RISCV::X17) { 10551 // Second half of f64 is passed on the stack. 10552 // Work out the address of the stack slot. 10553 if (!StackPtr.getNode()) 10554 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10555 // Emit the store. 10556 MemOpChains.push_back( 10557 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10558 } else { 10559 // Second half of f64 is passed in another GPR. 10560 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10561 Register RegHigh = RegLo + 1; 10562 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10563 } 10564 continue; 10565 } 10566 10567 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10568 // as any other MemLoc. 10569 10570 // Promote the value if needed. 10571 // For now, only handle fully promoted and indirect arguments. 10572 if (VA.getLocInfo() == CCValAssign::Indirect) { 10573 // Store the argument in a stack slot and pass its address. 10574 Align StackAlign = 10575 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10576 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10577 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10578 // If the original argument was split (e.g. i128), we need 10579 // to store the required parts of it here (and pass just one address). 10580 // Vectors may be partly split to registers and partly to the stack, in 10581 // which case the base address is partly offset and subsequent stores are 10582 // relative to that. 10583 unsigned ArgIndex = Outs[i].OrigArgIndex; 10584 unsigned ArgPartOffset = Outs[i].PartOffset; 10585 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10586 // Calculate the total size to store. We don't have access to what we're 10587 // actually storing other than performing the loop and collecting the 10588 // info. 10589 SmallVector<std::pair<SDValue, SDValue>> Parts; 10590 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10591 SDValue PartValue = OutVals[i + 1]; 10592 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10593 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10594 EVT PartVT = PartValue.getValueType(); 10595 if (PartVT.isScalableVector()) 10596 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10597 StoredSize += PartVT.getStoreSize(); 10598 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10599 Parts.push_back(std::make_pair(PartValue, Offset)); 10600 ++i; 10601 } 10602 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10603 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10604 MemOpChains.push_back( 10605 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10606 MachinePointerInfo::getFixedStack(MF, FI))); 10607 for (const auto &Part : Parts) { 10608 SDValue PartValue = Part.first; 10609 SDValue PartOffset = Part.second; 10610 SDValue Address = 10611 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10612 MemOpChains.push_back( 10613 DAG.getStore(Chain, DL, PartValue, Address, 10614 MachinePointerInfo::getFixedStack(MF, FI))); 10615 } 10616 ArgValue = SpillSlot; 10617 } else { 10618 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10619 } 10620 10621 // Use local copy if it is a byval arg. 10622 if (Flags.isByVal()) 10623 ArgValue = ByValArgs[j++]; 10624 10625 if (VA.isRegLoc()) { 10626 // Queue up the argument copies and emit them at the end. 10627 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10628 } else { 10629 assert(VA.isMemLoc() && "Argument not register or memory"); 10630 assert(!IsTailCall && "Tail call not allowed if stack is used " 10631 "for passing parameters"); 10632 10633 // Work out the address of the stack slot. 10634 if (!StackPtr.getNode()) 10635 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10636 SDValue Address = 10637 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10638 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10639 10640 // Emit the store. 10641 MemOpChains.push_back( 10642 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10643 } 10644 } 10645 10646 // Join the stores, which are independent of one another. 10647 if (!MemOpChains.empty()) 10648 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10649 10650 SDValue Glue; 10651 10652 // Build a sequence of copy-to-reg nodes, chained and glued together. 10653 for (auto &Reg : RegsToPass) { 10654 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10655 Glue = Chain.getValue(1); 10656 } 10657 10658 // Validate that none of the argument registers have been marked as 10659 // reserved, if so report an error. Do the same for the return address if this 10660 // is not a tailcall. 10661 validateCCReservedRegs(RegsToPass, MF); 10662 if (!IsTailCall && 10663 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10664 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10665 MF.getFunction(), 10666 "Return address register required, but has been reserved."}); 10667 10668 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10669 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10670 // split it and then direct call can be matched by PseudoCALL. 10671 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10672 const GlobalValue *GV = S->getGlobal(); 10673 10674 unsigned OpFlags = RISCVII::MO_CALL; 10675 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10676 OpFlags = RISCVII::MO_PLT; 10677 10678 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10679 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10680 unsigned OpFlags = RISCVII::MO_CALL; 10681 10682 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10683 nullptr)) 10684 OpFlags = RISCVII::MO_PLT; 10685 10686 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10687 } 10688 10689 // The first call operand is the chain and the second is the target address. 10690 SmallVector<SDValue, 8> Ops; 10691 Ops.push_back(Chain); 10692 Ops.push_back(Callee); 10693 10694 // Add argument registers to the end of the list so that they are 10695 // known live into the call. 10696 for (auto &Reg : RegsToPass) 10697 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10698 10699 if (!IsTailCall) { 10700 // Add a register mask operand representing the call-preserved registers. 10701 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10702 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10703 assert(Mask && "Missing call preserved mask for calling convention"); 10704 Ops.push_back(DAG.getRegisterMask(Mask)); 10705 } 10706 10707 // Glue the call to the argument copies, if any. 10708 if (Glue.getNode()) 10709 Ops.push_back(Glue); 10710 10711 // Emit the call. 10712 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10713 10714 if (IsTailCall) { 10715 MF.getFrameInfo().setHasTailCall(); 10716 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10717 } 10718 10719 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10720 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10721 Glue = Chain.getValue(1); 10722 10723 // Mark the end of the call, which is glued to the call itself. 10724 Chain = DAG.getCALLSEQ_END(Chain, 10725 DAG.getConstant(NumBytes, DL, PtrVT, true), 10726 DAG.getConstant(0, DL, PtrVT, true), 10727 Glue, DL); 10728 Glue = Chain.getValue(1); 10729 10730 // Assign locations to each value returned by this call. 10731 SmallVector<CCValAssign, 16> RVLocs; 10732 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10733 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10734 10735 // Copy all of the result registers out of their specified physreg. 10736 for (auto &VA : RVLocs) { 10737 // Copy the value out 10738 SDValue RetValue = 10739 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10740 // Glue the RetValue to the end of the call sequence 10741 Chain = RetValue.getValue(1); 10742 Glue = RetValue.getValue(2); 10743 10744 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10745 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10746 SDValue RetValue2 = 10747 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10748 Chain = RetValue2.getValue(1); 10749 Glue = RetValue2.getValue(2); 10750 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10751 RetValue2); 10752 } 10753 10754 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10755 10756 InVals.push_back(RetValue); 10757 } 10758 10759 return Chain; 10760 } 10761 10762 bool RISCVTargetLowering::CanLowerReturn( 10763 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10764 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10765 SmallVector<CCValAssign, 16> RVLocs; 10766 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10767 10768 Optional<unsigned> FirstMaskArgument; 10769 if (Subtarget.hasVInstructions()) 10770 FirstMaskArgument = preAssignMask(Outs); 10771 10772 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10773 MVT VT = Outs[i].VT; 10774 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10775 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10776 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10777 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10778 *this, FirstMaskArgument)) 10779 return false; 10780 } 10781 return true; 10782 } 10783 10784 SDValue 10785 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10786 bool IsVarArg, 10787 const SmallVectorImpl<ISD::OutputArg> &Outs, 10788 const SmallVectorImpl<SDValue> &OutVals, 10789 const SDLoc &DL, SelectionDAG &DAG) const { 10790 const MachineFunction &MF = DAG.getMachineFunction(); 10791 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10792 10793 // Stores the assignment of the return value to a location. 10794 SmallVector<CCValAssign, 16> RVLocs; 10795 10796 // Info about the registers and stack slot. 10797 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10798 *DAG.getContext()); 10799 10800 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10801 nullptr, CC_RISCV); 10802 10803 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10804 report_fatal_error("GHC functions return void only"); 10805 10806 SDValue Glue; 10807 SmallVector<SDValue, 4> RetOps(1, Chain); 10808 10809 // Copy the result values into the output registers. 10810 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10811 SDValue Val = OutVals[i]; 10812 CCValAssign &VA = RVLocs[i]; 10813 assert(VA.isRegLoc() && "Can only return in registers!"); 10814 10815 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10816 // Handle returning f64 on RV32D with a soft float ABI. 10817 assert(VA.isRegLoc() && "Expected return via registers"); 10818 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10819 DAG.getVTList(MVT::i32, MVT::i32), Val); 10820 SDValue Lo = SplitF64.getValue(0); 10821 SDValue Hi = SplitF64.getValue(1); 10822 Register RegLo = VA.getLocReg(); 10823 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10824 Register RegHi = RegLo + 1; 10825 10826 if (STI.isRegisterReservedByUser(RegLo) || 10827 STI.isRegisterReservedByUser(RegHi)) 10828 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10829 MF.getFunction(), 10830 "Return value register required, but has been reserved."}); 10831 10832 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10833 Glue = Chain.getValue(1); 10834 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10835 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10836 Glue = Chain.getValue(1); 10837 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10838 } else { 10839 // Handle a 'normal' return. 10840 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10841 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10842 10843 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10844 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10845 MF.getFunction(), 10846 "Return value register required, but has been reserved."}); 10847 10848 // Guarantee that all emitted copies are stuck together. 10849 Glue = Chain.getValue(1); 10850 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10851 } 10852 } 10853 10854 RetOps[0] = Chain; // Update chain. 10855 10856 // Add the glue node if we have it. 10857 if (Glue.getNode()) { 10858 RetOps.push_back(Glue); 10859 } 10860 10861 unsigned RetOpc = RISCVISD::RET_FLAG; 10862 // Interrupt service routines use different return instructions. 10863 const Function &Func = DAG.getMachineFunction().getFunction(); 10864 if (Func.hasFnAttribute("interrupt")) { 10865 if (!Func.getReturnType()->isVoidTy()) 10866 report_fatal_error( 10867 "Functions with the interrupt attribute must have void return type!"); 10868 10869 MachineFunction &MF = DAG.getMachineFunction(); 10870 StringRef Kind = 10871 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10872 10873 if (Kind == "user") 10874 RetOpc = RISCVISD::URET_FLAG; 10875 else if (Kind == "supervisor") 10876 RetOpc = RISCVISD::SRET_FLAG; 10877 else 10878 RetOpc = RISCVISD::MRET_FLAG; 10879 } 10880 10881 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10882 } 10883 10884 void RISCVTargetLowering::validateCCReservedRegs( 10885 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10886 MachineFunction &MF) const { 10887 const Function &F = MF.getFunction(); 10888 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10889 10890 if (llvm::any_of(Regs, [&STI](auto Reg) { 10891 return STI.isRegisterReservedByUser(Reg.first); 10892 })) 10893 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10894 F, "Argument register required, but has been reserved."}); 10895 } 10896 10897 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10898 return CI->isTailCall(); 10899 } 10900 10901 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10902 #define NODE_NAME_CASE(NODE) \ 10903 case RISCVISD::NODE: \ 10904 return "RISCVISD::" #NODE; 10905 // clang-format off 10906 switch ((RISCVISD::NodeType)Opcode) { 10907 case RISCVISD::FIRST_NUMBER: 10908 break; 10909 NODE_NAME_CASE(RET_FLAG) 10910 NODE_NAME_CASE(URET_FLAG) 10911 NODE_NAME_CASE(SRET_FLAG) 10912 NODE_NAME_CASE(MRET_FLAG) 10913 NODE_NAME_CASE(CALL) 10914 NODE_NAME_CASE(SELECT_CC) 10915 NODE_NAME_CASE(BR_CC) 10916 NODE_NAME_CASE(BuildPairF64) 10917 NODE_NAME_CASE(SplitF64) 10918 NODE_NAME_CASE(TAIL) 10919 NODE_NAME_CASE(MULHSU) 10920 NODE_NAME_CASE(SLLW) 10921 NODE_NAME_CASE(SRAW) 10922 NODE_NAME_CASE(SRLW) 10923 NODE_NAME_CASE(DIVW) 10924 NODE_NAME_CASE(DIVUW) 10925 NODE_NAME_CASE(REMUW) 10926 NODE_NAME_CASE(ROLW) 10927 NODE_NAME_CASE(RORW) 10928 NODE_NAME_CASE(CLZW) 10929 NODE_NAME_CASE(CTZW) 10930 NODE_NAME_CASE(FSLW) 10931 NODE_NAME_CASE(FSRW) 10932 NODE_NAME_CASE(FSL) 10933 NODE_NAME_CASE(FSR) 10934 NODE_NAME_CASE(FMV_H_X) 10935 NODE_NAME_CASE(FMV_X_ANYEXTH) 10936 NODE_NAME_CASE(FMV_X_SIGNEXTH) 10937 NODE_NAME_CASE(FMV_W_X_RV64) 10938 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10939 NODE_NAME_CASE(FCVT_X) 10940 NODE_NAME_CASE(FCVT_XU) 10941 NODE_NAME_CASE(FCVT_W_RV64) 10942 NODE_NAME_CASE(FCVT_WU_RV64) 10943 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10944 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10945 NODE_NAME_CASE(READ_CYCLE_WIDE) 10946 NODE_NAME_CASE(GREV) 10947 NODE_NAME_CASE(GREVW) 10948 NODE_NAME_CASE(GORC) 10949 NODE_NAME_CASE(GORCW) 10950 NODE_NAME_CASE(SHFL) 10951 NODE_NAME_CASE(SHFLW) 10952 NODE_NAME_CASE(UNSHFL) 10953 NODE_NAME_CASE(UNSHFLW) 10954 NODE_NAME_CASE(BFP) 10955 NODE_NAME_CASE(BFPW) 10956 NODE_NAME_CASE(BCOMPRESS) 10957 NODE_NAME_CASE(BCOMPRESSW) 10958 NODE_NAME_CASE(BDECOMPRESS) 10959 NODE_NAME_CASE(BDECOMPRESSW) 10960 NODE_NAME_CASE(VMV_V_X_VL) 10961 NODE_NAME_CASE(VFMV_V_F_VL) 10962 NODE_NAME_CASE(VMV_X_S) 10963 NODE_NAME_CASE(VMV_S_X_VL) 10964 NODE_NAME_CASE(VFMV_S_F_VL) 10965 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10966 NODE_NAME_CASE(READ_VLENB) 10967 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10968 NODE_NAME_CASE(VSLIDEUP_VL) 10969 NODE_NAME_CASE(VSLIDE1UP_VL) 10970 NODE_NAME_CASE(VSLIDEDOWN_VL) 10971 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10972 NODE_NAME_CASE(VID_VL) 10973 NODE_NAME_CASE(VFNCVT_ROD_VL) 10974 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10975 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10976 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10977 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10978 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10979 NODE_NAME_CASE(VECREDUCE_AND_VL) 10980 NODE_NAME_CASE(VECREDUCE_OR_VL) 10981 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10982 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10983 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10984 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10985 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10986 NODE_NAME_CASE(ADD_VL) 10987 NODE_NAME_CASE(AND_VL) 10988 NODE_NAME_CASE(MUL_VL) 10989 NODE_NAME_CASE(OR_VL) 10990 NODE_NAME_CASE(SDIV_VL) 10991 NODE_NAME_CASE(SHL_VL) 10992 NODE_NAME_CASE(SREM_VL) 10993 NODE_NAME_CASE(SRA_VL) 10994 NODE_NAME_CASE(SRL_VL) 10995 NODE_NAME_CASE(SUB_VL) 10996 NODE_NAME_CASE(UDIV_VL) 10997 NODE_NAME_CASE(UREM_VL) 10998 NODE_NAME_CASE(XOR_VL) 10999 NODE_NAME_CASE(SADDSAT_VL) 11000 NODE_NAME_CASE(UADDSAT_VL) 11001 NODE_NAME_CASE(SSUBSAT_VL) 11002 NODE_NAME_CASE(USUBSAT_VL) 11003 NODE_NAME_CASE(FADD_VL) 11004 NODE_NAME_CASE(FSUB_VL) 11005 NODE_NAME_CASE(FMUL_VL) 11006 NODE_NAME_CASE(FDIV_VL) 11007 NODE_NAME_CASE(FNEG_VL) 11008 NODE_NAME_CASE(FABS_VL) 11009 NODE_NAME_CASE(FSQRT_VL) 11010 NODE_NAME_CASE(FMA_VL) 11011 NODE_NAME_CASE(FCOPYSIGN_VL) 11012 NODE_NAME_CASE(SMIN_VL) 11013 NODE_NAME_CASE(SMAX_VL) 11014 NODE_NAME_CASE(UMIN_VL) 11015 NODE_NAME_CASE(UMAX_VL) 11016 NODE_NAME_CASE(FMINNUM_VL) 11017 NODE_NAME_CASE(FMAXNUM_VL) 11018 NODE_NAME_CASE(MULHS_VL) 11019 NODE_NAME_CASE(MULHU_VL) 11020 NODE_NAME_CASE(FP_TO_SINT_VL) 11021 NODE_NAME_CASE(FP_TO_UINT_VL) 11022 NODE_NAME_CASE(SINT_TO_FP_VL) 11023 NODE_NAME_CASE(UINT_TO_FP_VL) 11024 NODE_NAME_CASE(FP_EXTEND_VL) 11025 NODE_NAME_CASE(FP_ROUND_VL) 11026 NODE_NAME_CASE(VWMUL_VL) 11027 NODE_NAME_CASE(VWMULU_VL) 11028 NODE_NAME_CASE(VWMULSU_VL) 11029 NODE_NAME_CASE(VWADD_VL) 11030 NODE_NAME_CASE(VWADDU_VL) 11031 NODE_NAME_CASE(VWSUB_VL) 11032 NODE_NAME_CASE(VWSUBU_VL) 11033 NODE_NAME_CASE(VWADD_W_VL) 11034 NODE_NAME_CASE(VWADDU_W_VL) 11035 NODE_NAME_CASE(VWSUB_W_VL) 11036 NODE_NAME_CASE(VWSUBU_W_VL) 11037 NODE_NAME_CASE(SETCC_VL) 11038 NODE_NAME_CASE(VSELECT_VL) 11039 NODE_NAME_CASE(VP_MERGE_VL) 11040 NODE_NAME_CASE(VMAND_VL) 11041 NODE_NAME_CASE(VMOR_VL) 11042 NODE_NAME_CASE(VMXOR_VL) 11043 NODE_NAME_CASE(VMCLR_VL) 11044 NODE_NAME_CASE(VMSET_VL) 11045 NODE_NAME_CASE(VRGATHER_VX_VL) 11046 NODE_NAME_CASE(VRGATHER_VV_VL) 11047 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11048 NODE_NAME_CASE(VSEXT_VL) 11049 NODE_NAME_CASE(VZEXT_VL) 11050 NODE_NAME_CASE(VCPOP_VL) 11051 NODE_NAME_CASE(READ_CSR) 11052 NODE_NAME_CASE(WRITE_CSR) 11053 NODE_NAME_CASE(SWAP_CSR) 11054 } 11055 // clang-format on 11056 return nullptr; 11057 #undef NODE_NAME_CASE 11058 } 11059 11060 /// getConstraintType - Given a constraint letter, return the type of 11061 /// constraint it is for this target. 11062 RISCVTargetLowering::ConstraintType 11063 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11064 if (Constraint.size() == 1) { 11065 switch (Constraint[0]) { 11066 default: 11067 break; 11068 case 'f': 11069 return C_RegisterClass; 11070 case 'I': 11071 case 'J': 11072 case 'K': 11073 return C_Immediate; 11074 case 'A': 11075 return C_Memory; 11076 case 'S': // A symbolic address 11077 return C_Other; 11078 } 11079 } else { 11080 if (Constraint == "vr" || Constraint == "vm") 11081 return C_RegisterClass; 11082 } 11083 return TargetLowering::getConstraintType(Constraint); 11084 } 11085 11086 std::pair<unsigned, const TargetRegisterClass *> 11087 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11088 StringRef Constraint, 11089 MVT VT) const { 11090 // First, see if this is a constraint that directly corresponds to a 11091 // RISCV register class. 11092 if (Constraint.size() == 1) { 11093 switch (Constraint[0]) { 11094 case 'r': 11095 // TODO: Support fixed vectors up to XLen for P extension? 11096 if (VT.isVector()) 11097 break; 11098 return std::make_pair(0U, &RISCV::GPRRegClass); 11099 case 'f': 11100 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11101 return std::make_pair(0U, &RISCV::FPR16RegClass); 11102 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11103 return std::make_pair(0U, &RISCV::FPR32RegClass); 11104 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11105 return std::make_pair(0U, &RISCV::FPR64RegClass); 11106 break; 11107 default: 11108 break; 11109 } 11110 } else if (Constraint == "vr") { 11111 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11112 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11113 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11114 return std::make_pair(0U, RC); 11115 } 11116 } else if (Constraint == "vm") { 11117 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11118 return std::make_pair(0U, &RISCV::VMV0RegClass); 11119 } 11120 11121 // Clang will correctly decode the usage of register name aliases into their 11122 // official names. However, other frontends like `rustc` do not. This allows 11123 // users of these frontends to use the ABI names for registers in LLVM-style 11124 // register constraints. 11125 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11126 .Case("{zero}", RISCV::X0) 11127 .Case("{ra}", RISCV::X1) 11128 .Case("{sp}", RISCV::X2) 11129 .Case("{gp}", RISCV::X3) 11130 .Case("{tp}", RISCV::X4) 11131 .Case("{t0}", RISCV::X5) 11132 .Case("{t1}", RISCV::X6) 11133 .Case("{t2}", RISCV::X7) 11134 .Cases("{s0}", "{fp}", RISCV::X8) 11135 .Case("{s1}", RISCV::X9) 11136 .Case("{a0}", RISCV::X10) 11137 .Case("{a1}", RISCV::X11) 11138 .Case("{a2}", RISCV::X12) 11139 .Case("{a3}", RISCV::X13) 11140 .Case("{a4}", RISCV::X14) 11141 .Case("{a5}", RISCV::X15) 11142 .Case("{a6}", RISCV::X16) 11143 .Case("{a7}", RISCV::X17) 11144 .Case("{s2}", RISCV::X18) 11145 .Case("{s3}", RISCV::X19) 11146 .Case("{s4}", RISCV::X20) 11147 .Case("{s5}", RISCV::X21) 11148 .Case("{s6}", RISCV::X22) 11149 .Case("{s7}", RISCV::X23) 11150 .Case("{s8}", RISCV::X24) 11151 .Case("{s9}", RISCV::X25) 11152 .Case("{s10}", RISCV::X26) 11153 .Case("{s11}", RISCV::X27) 11154 .Case("{t3}", RISCV::X28) 11155 .Case("{t4}", RISCV::X29) 11156 .Case("{t5}", RISCV::X30) 11157 .Case("{t6}", RISCV::X31) 11158 .Default(RISCV::NoRegister); 11159 if (XRegFromAlias != RISCV::NoRegister) 11160 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11161 11162 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11163 // TableGen record rather than the AsmName to choose registers for InlineAsm 11164 // constraints, plus we want to match those names to the widest floating point 11165 // register type available, manually select floating point registers here. 11166 // 11167 // The second case is the ABI name of the register, so that frontends can also 11168 // use the ABI names in register constraint lists. 11169 if (Subtarget.hasStdExtF()) { 11170 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11171 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11172 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11173 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11174 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11175 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11176 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11177 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11178 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11179 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11180 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11181 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11182 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11183 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11184 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11185 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11186 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11187 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11188 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11189 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11190 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11191 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11192 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11193 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11194 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11195 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11196 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11197 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11198 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11199 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11200 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11201 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11202 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11203 .Default(RISCV::NoRegister); 11204 if (FReg != RISCV::NoRegister) { 11205 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11206 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11207 unsigned RegNo = FReg - RISCV::F0_F; 11208 unsigned DReg = RISCV::F0_D + RegNo; 11209 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11210 } 11211 if (VT == MVT::f32 || VT == MVT::Other) 11212 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11213 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11214 unsigned RegNo = FReg - RISCV::F0_F; 11215 unsigned HReg = RISCV::F0_H + RegNo; 11216 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11217 } 11218 } 11219 } 11220 11221 if (Subtarget.hasVInstructions()) { 11222 Register VReg = StringSwitch<Register>(Constraint.lower()) 11223 .Case("{v0}", RISCV::V0) 11224 .Case("{v1}", RISCV::V1) 11225 .Case("{v2}", RISCV::V2) 11226 .Case("{v3}", RISCV::V3) 11227 .Case("{v4}", RISCV::V4) 11228 .Case("{v5}", RISCV::V5) 11229 .Case("{v6}", RISCV::V6) 11230 .Case("{v7}", RISCV::V7) 11231 .Case("{v8}", RISCV::V8) 11232 .Case("{v9}", RISCV::V9) 11233 .Case("{v10}", RISCV::V10) 11234 .Case("{v11}", RISCV::V11) 11235 .Case("{v12}", RISCV::V12) 11236 .Case("{v13}", RISCV::V13) 11237 .Case("{v14}", RISCV::V14) 11238 .Case("{v15}", RISCV::V15) 11239 .Case("{v16}", RISCV::V16) 11240 .Case("{v17}", RISCV::V17) 11241 .Case("{v18}", RISCV::V18) 11242 .Case("{v19}", RISCV::V19) 11243 .Case("{v20}", RISCV::V20) 11244 .Case("{v21}", RISCV::V21) 11245 .Case("{v22}", RISCV::V22) 11246 .Case("{v23}", RISCV::V23) 11247 .Case("{v24}", RISCV::V24) 11248 .Case("{v25}", RISCV::V25) 11249 .Case("{v26}", RISCV::V26) 11250 .Case("{v27}", RISCV::V27) 11251 .Case("{v28}", RISCV::V28) 11252 .Case("{v29}", RISCV::V29) 11253 .Case("{v30}", RISCV::V30) 11254 .Case("{v31}", RISCV::V31) 11255 .Default(RISCV::NoRegister); 11256 if (VReg != RISCV::NoRegister) { 11257 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11258 return std::make_pair(VReg, &RISCV::VMRegClass); 11259 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11260 return std::make_pair(VReg, &RISCV::VRRegClass); 11261 for (const auto *RC : 11262 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11263 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11264 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11265 return std::make_pair(VReg, RC); 11266 } 11267 } 11268 } 11269 } 11270 11271 std::pair<Register, const TargetRegisterClass *> Res = 11272 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11273 11274 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11275 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11276 // Subtarget into account. 11277 if (Res.second == &RISCV::GPRF16RegClass || 11278 Res.second == &RISCV::GPRF32RegClass || 11279 Res.second == &RISCV::GPRF64RegClass) 11280 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11281 11282 return Res; 11283 } 11284 11285 unsigned 11286 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11287 // Currently only support length 1 constraints. 11288 if (ConstraintCode.size() == 1) { 11289 switch (ConstraintCode[0]) { 11290 case 'A': 11291 return InlineAsm::Constraint_A; 11292 default: 11293 break; 11294 } 11295 } 11296 11297 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11298 } 11299 11300 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11301 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11302 SelectionDAG &DAG) const { 11303 // Currently only support length 1 constraints. 11304 if (Constraint.length() == 1) { 11305 switch (Constraint[0]) { 11306 case 'I': 11307 // Validate & create a 12-bit signed immediate operand. 11308 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11309 uint64_t CVal = C->getSExtValue(); 11310 if (isInt<12>(CVal)) 11311 Ops.push_back( 11312 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11313 } 11314 return; 11315 case 'J': 11316 // Validate & create an integer zero operand. 11317 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11318 if (C->getZExtValue() == 0) 11319 Ops.push_back( 11320 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11321 return; 11322 case 'K': 11323 // Validate & create a 5-bit unsigned immediate operand. 11324 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11325 uint64_t CVal = C->getZExtValue(); 11326 if (isUInt<5>(CVal)) 11327 Ops.push_back( 11328 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11329 } 11330 return; 11331 case 'S': 11332 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11333 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11334 GA->getValueType(0))); 11335 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11336 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11337 BA->getValueType(0))); 11338 } 11339 return; 11340 default: 11341 break; 11342 } 11343 } 11344 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11345 } 11346 11347 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11348 Instruction *Inst, 11349 AtomicOrdering Ord) const { 11350 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11351 return Builder.CreateFence(Ord); 11352 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11353 return Builder.CreateFence(AtomicOrdering::Release); 11354 return nullptr; 11355 } 11356 11357 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11358 Instruction *Inst, 11359 AtomicOrdering Ord) const { 11360 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11361 return Builder.CreateFence(AtomicOrdering::Acquire); 11362 return nullptr; 11363 } 11364 11365 TargetLowering::AtomicExpansionKind 11366 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11367 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11368 // point operations can't be used in an lr/sc sequence without breaking the 11369 // forward-progress guarantee. 11370 if (AI->isFloatingPointOperation()) 11371 return AtomicExpansionKind::CmpXChg; 11372 11373 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11374 if (Size == 8 || Size == 16) 11375 return AtomicExpansionKind::MaskedIntrinsic; 11376 return AtomicExpansionKind::None; 11377 } 11378 11379 static Intrinsic::ID 11380 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11381 if (XLen == 32) { 11382 switch (BinOp) { 11383 default: 11384 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11385 case AtomicRMWInst::Xchg: 11386 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11387 case AtomicRMWInst::Add: 11388 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11389 case AtomicRMWInst::Sub: 11390 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11391 case AtomicRMWInst::Nand: 11392 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11393 case AtomicRMWInst::Max: 11394 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11395 case AtomicRMWInst::Min: 11396 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11397 case AtomicRMWInst::UMax: 11398 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11399 case AtomicRMWInst::UMin: 11400 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11401 } 11402 } 11403 11404 if (XLen == 64) { 11405 switch (BinOp) { 11406 default: 11407 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11408 case AtomicRMWInst::Xchg: 11409 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11410 case AtomicRMWInst::Add: 11411 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11412 case AtomicRMWInst::Sub: 11413 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11414 case AtomicRMWInst::Nand: 11415 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11416 case AtomicRMWInst::Max: 11417 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11418 case AtomicRMWInst::Min: 11419 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11420 case AtomicRMWInst::UMax: 11421 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11422 case AtomicRMWInst::UMin: 11423 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11424 } 11425 } 11426 11427 llvm_unreachable("Unexpected XLen\n"); 11428 } 11429 11430 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11431 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11432 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11433 unsigned XLen = Subtarget.getXLen(); 11434 Value *Ordering = 11435 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11436 Type *Tys[] = {AlignedAddr->getType()}; 11437 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11438 AI->getModule(), 11439 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11440 11441 if (XLen == 64) { 11442 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11443 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11444 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11445 } 11446 11447 Value *Result; 11448 11449 // Must pass the shift amount needed to sign extend the loaded value prior 11450 // to performing a signed comparison for min/max. ShiftAmt is the number of 11451 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11452 // is the number of bits to left+right shift the value in order to 11453 // sign-extend. 11454 if (AI->getOperation() == AtomicRMWInst::Min || 11455 AI->getOperation() == AtomicRMWInst::Max) { 11456 const DataLayout &DL = AI->getModule()->getDataLayout(); 11457 unsigned ValWidth = 11458 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11459 Value *SextShamt = 11460 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11461 Result = Builder.CreateCall(LrwOpScwLoop, 11462 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11463 } else { 11464 Result = 11465 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11466 } 11467 11468 if (XLen == 64) 11469 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11470 return Result; 11471 } 11472 11473 TargetLowering::AtomicExpansionKind 11474 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11475 AtomicCmpXchgInst *CI) const { 11476 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11477 if (Size == 8 || Size == 16) 11478 return AtomicExpansionKind::MaskedIntrinsic; 11479 return AtomicExpansionKind::None; 11480 } 11481 11482 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11483 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11484 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11485 unsigned XLen = Subtarget.getXLen(); 11486 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11487 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11488 if (XLen == 64) { 11489 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11490 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11491 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11492 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11493 } 11494 Type *Tys[] = {AlignedAddr->getType()}; 11495 Function *MaskedCmpXchg = 11496 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11497 Value *Result = Builder.CreateCall( 11498 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11499 if (XLen == 64) 11500 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11501 return Result; 11502 } 11503 11504 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11505 return false; 11506 } 11507 11508 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11509 EVT VT) const { 11510 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11511 return false; 11512 11513 switch (FPVT.getSimpleVT().SimpleTy) { 11514 case MVT::f16: 11515 return Subtarget.hasStdExtZfh(); 11516 case MVT::f32: 11517 return Subtarget.hasStdExtF(); 11518 case MVT::f64: 11519 return Subtarget.hasStdExtD(); 11520 default: 11521 return false; 11522 } 11523 } 11524 11525 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11526 // If we are using the small code model, we can reduce size of jump table 11527 // entry to 4 bytes. 11528 if (Subtarget.is64Bit() && !isPositionIndependent() && 11529 getTargetMachine().getCodeModel() == CodeModel::Small) { 11530 return MachineJumpTableInfo::EK_Custom32; 11531 } 11532 return TargetLowering::getJumpTableEncoding(); 11533 } 11534 11535 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11536 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11537 unsigned uid, MCContext &Ctx) const { 11538 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11539 getTargetMachine().getCodeModel() == CodeModel::Small); 11540 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11541 } 11542 11543 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11544 EVT VT) const { 11545 VT = VT.getScalarType(); 11546 11547 if (!VT.isSimple()) 11548 return false; 11549 11550 switch (VT.getSimpleVT().SimpleTy) { 11551 case MVT::f16: 11552 return Subtarget.hasStdExtZfh(); 11553 case MVT::f32: 11554 return Subtarget.hasStdExtF(); 11555 case MVT::f64: 11556 return Subtarget.hasStdExtD(); 11557 default: 11558 break; 11559 } 11560 11561 return false; 11562 } 11563 11564 Register RISCVTargetLowering::getExceptionPointerRegister( 11565 const Constant *PersonalityFn) const { 11566 return RISCV::X10; 11567 } 11568 11569 Register RISCVTargetLowering::getExceptionSelectorRegister( 11570 const Constant *PersonalityFn) const { 11571 return RISCV::X11; 11572 } 11573 11574 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11575 // Return false to suppress the unnecessary extensions if the LibCall 11576 // arguments or return value is f32 type for LP64 ABI. 11577 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11578 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11579 return false; 11580 11581 return true; 11582 } 11583 11584 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11585 if (Subtarget.is64Bit() && Type == MVT::i32) 11586 return true; 11587 11588 return IsSigned; 11589 } 11590 11591 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11592 SDValue C) const { 11593 // Check integral scalar types. 11594 if (VT.isScalarInteger()) { 11595 // Omit the optimization if the sub target has the M extension and the data 11596 // size exceeds XLen. 11597 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11598 return false; 11599 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11600 // Break the MUL to a SLLI and an ADD/SUB. 11601 const APInt &Imm = ConstNode->getAPIntValue(); 11602 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11603 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11604 return true; 11605 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11606 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11607 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11608 (Imm - 8).isPowerOf2())) 11609 return true; 11610 // Omit the following optimization if the sub target has the M extension 11611 // and the data size >= XLen. 11612 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11613 return false; 11614 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11615 // a pair of LUI/ADDI. 11616 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11617 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11618 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11619 (1 - ImmS).isPowerOf2()) 11620 return true; 11621 } 11622 } 11623 } 11624 11625 return false; 11626 } 11627 11628 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11629 SDValue ConstNode) const { 11630 // Let the DAGCombiner decide for vectors. 11631 EVT VT = AddNode.getValueType(); 11632 if (VT.isVector()) 11633 return true; 11634 11635 // Let the DAGCombiner decide for larger types. 11636 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11637 return true; 11638 11639 // It is worse if c1 is simm12 while c1*c2 is not. 11640 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11641 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11642 const APInt &C1 = C1Node->getAPIntValue(); 11643 const APInt &C2 = C2Node->getAPIntValue(); 11644 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11645 return false; 11646 11647 // Default to true and let the DAGCombiner decide. 11648 return true; 11649 } 11650 11651 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11652 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11653 bool *Fast) const { 11654 if (!VT.isVector()) 11655 return false; 11656 11657 EVT ElemVT = VT.getVectorElementType(); 11658 if (Alignment >= ElemVT.getStoreSize()) { 11659 if (Fast) 11660 *Fast = true; 11661 return true; 11662 } 11663 11664 return false; 11665 } 11666 11667 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11668 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11669 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11670 bool IsABIRegCopy = CC.hasValue(); 11671 EVT ValueVT = Val.getValueType(); 11672 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11673 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11674 // and cast to f32. 11675 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11676 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11677 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11678 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11679 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11680 Parts[0] = Val; 11681 return true; 11682 } 11683 11684 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11685 LLVMContext &Context = *DAG.getContext(); 11686 EVT ValueEltVT = ValueVT.getVectorElementType(); 11687 EVT PartEltVT = PartVT.getVectorElementType(); 11688 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11689 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11690 if (PartVTBitSize % ValueVTBitSize == 0) { 11691 assert(PartVTBitSize >= ValueVTBitSize); 11692 // If the element types are different, bitcast to the same element type of 11693 // PartVT first. 11694 // Give an example here, we want copy a <vscale x 1 x i8> value to 11695 // <vscale x 4 x i16>. 11696 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11697 // subvector, then we can bitcast to <vscale x 4 x i16>. 11698 if (ValueEltVT != PartEltVT) { 11699 if (PartVTBitSize > ValueVTBitSize) { 11700 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11701 assert(Count != 0 && "The number of element should not be zero."); 11702 EVT SameEltTypeVT = 11703 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11704 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11705 DAG.getUNDEF(SameEltTypeVT), Val, 11706 DAG.getVectorIdxConstant(0, DL)); 11707 } 11708 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11709 } else { 11710 Val = 11711 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11712 Val, DAG.getVectorIdxConstant(0, DL)); 11713 } 11714 Parts[0] = Val; 11715 return true; 11716 } 11717 } 11718 return false; 11719 } 11720 11721 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11722 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11723 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11724 bool IsABIRegCopy = CC.hasValue(); 11725 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11726 SDValue Val = Parts[0]; 11727 11728 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11729 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11730 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11731 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11732 return Val; 11733 } 11734 11735 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11736 LLVMContext &Context = *DAG.getContext(); 11737 SDValue Val = Parts[0]; 11738 EVT ValueEltVT = ValueVT.getVectorElementType(); 11739 EVT PartEltVT = PartVT.getVectorElementType(); 11740 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11741 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11742 if (PartVTBitSize % ValueVTBitSize == 0) { 11743 assert(PartVTBitSize >= ValueVTBitSize); 11744 EVT SameEltTypeVT = ValueVT; 11745 // If the element types are different, convert it to the same element type 11746 // of PartVT. 11747 // Give an example here, we want copy a <vscale x 1 x i8> value from 11748 // <vscale x 4 x i16>. 11749 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11750 // then we can extract <vscale x 1 x i8>. 11751 if (ValueEltVT != PartEltVT) { 11752 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11753 assert(Count != 0 && "The number of element should not be zero."); 11754 SameEltTypeVT = 11755 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11756 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11757 } 11758 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11759 DAG.getVectorIdxConstant(0, DL)); 11760 return Val; 11761 } 11762 } 11763 return SDValue(); 11764 } 11765 11766 SDValue 11767 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11768 SelectionDAG &DAG, 11769 SmallVectorImpl<SDNode *> &Created) const { 11770 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11771 if (isIntDivCheap(N->getValueType(0), Attr)) 11772 return SDValue(N, 0); // Lower SDIV as SDIV 11773 11774 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11775 "Unexpected divisor!"); 11776 11777 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11778 if (!Subtarget.hasStdExtZbt()) 11779 return SDValue(); 11780 11781 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11782 // Besides, more critical path instructions will be generated when dividing 11783 // by 2. So we keep using the original DAGs for these cases. 11784 unsigned Lg2 = Divisor.countTrailingZeros(); 11785 if (Lg2 == 1 || Lg2 >= 12) 11786 return SDValue(); 11787 11788 // fold (sdiv X, pow2) 11789 EVT VT = N->getValueType(0); 11790 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11791 return SDValue(); 11792 11793 SDLoc DL(N); 11794 SDValue N0 = N->getOperand(0); 11795 SDValue Zero = DAG.getConstant(0, DL, VT); 11796 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11797 11798 // Add (N0 < 0) ? Pow2 - 1 : 0; 11799 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11800 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11801 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11802 11803 Created.push_back(Cmp.getNode()); 11804 Created.push_back(Add.getNode()); 11805 Created.push_back(Sel.getNode()); 11806 11807 // Divide by pow2. 11808 SDValue SRA = 11809 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11810 11811 // If we're dividing by a positive value, we're done. Otherwise, we must 11812 // negate the result. 11813 if (Divisor.isNonNegative()) 11814 return SRA; 11815 11816 Created.push_back(SRA.getNode()); 11817 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11818 } 11819 11820 #define GET_REGISTER_MATCHER 11821 #include "RISCVGenAsmMatcher.inc" 11822 11823 Register 11824 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11825 const MachineFunction &MF) const { 11826 Register Reg = MatchRegisterAltName(RegName); 11827 if (Reg == RISCV::NoRegister) 11828 Reg = MatchRegisterName(RegName); 11829 if (Reg == RISCV::NoRegister) 11830 report_fatal_error( 11831 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11832 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11833 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11834 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11835 StringRef(RegName) + "\".")); 11836 return Reg; 11837 } 11838 11839 namespace llvm { 11840 namespace RISCVVIntrinsicsTable { 11841 11842 #define GET_RISCVVIntrinsicsTable_IMPL 11843 #include "RISCVGenSearchableTables.inc" 11844 11845 } // namespace RISCVVIntrinsicsTable 11846 11847 } // namespace llvm 11848