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 308 if (Subtarget.hasStdExtZbt()) { 309 setOperationAction(ISD::FSHL, XLenVT, Custom); 310 setOperationAction(ISD::FSHR, XLenVT, Custom); 311 setOperationAction(ISD::SELECT, XLenVT, Legal); 312 313 if (Subtarget.is64Bit()) { 314 setOperationAction(ISD::FSHL, MVT::i32, Custom); 315 setOperationAction(ISD::FSHR, MVT::i32, Custom); 316 } 317 } else { 318 setOperationAction(ISD::SELECT, XLenVT, Custom); 319 } 320 321 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 322 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 323 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 324 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 325 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 326 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 327 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 328 329 static const ISD::CondCode FPCCToExpand[] = { 330 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 331 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 332 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 333 334 static const ISD::NodeType FPOpToExpand[] = { 335 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 336 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 337 338 if (Subtarget.hasStdExtZfh()) 339 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 340 341 if (Subtarget.hasStdExtZfh()) { 342 for (auto NT : FPLegalNodeTypes) 343 setOperationAction(NT, MVT::f16, Legal); 344 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 345 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 346 for (auto CC : FPCCToExpand) 347 setCondCodeAction(CC, MVT::f16, Expand); 348 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 349 setOperationAction(ISD::SELECT, MVT::f16, Custom); 350 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 351 352 setOperationAction(ISD::FREM, MVT::f16, Promote); 353 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 354 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 355 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 356 setOperationAction(ISD::FRINT, MVT::f16, Promote); 357 setOperationAction(ISD::FROUND, MVT::f16, Promote); 358 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 359 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 360 setOperationAction(ISD::FPOW, MVT::f16, Promote); 361 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 362 setOperationAction(ISD::FCOS, MVT::f16, Promote); 363 setOperationAction(ISD::FSIN, MVT::f16, Promote); 364 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 365 setOperationAction(ISD::FEXP, MVT::f16, Promote); 366 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 367 setOperationAction(ISD::FLOG, MVT::f16, Promote); 368 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 369 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 370 371 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 372 // complete support for all operations in LegalizeDAG. 373 374 // We need to custom promote this. 375 if (Subtarget.is64Bit()) 376 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 377 } 378 379 if (Subtarget.hasStdExtF()) { 380 for (auto NT : FPLegalNodeTypes) 381 setOperationAction(NT, MVT::f32, Legal); 382 for (auto CC : FPCCToExpand) 383 setCondCodeAction(CC, MVT::f32, Expand); 384 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 385 setOperationAction(ISD::SELECT, MVT::f32, Custom); 386 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 387 for (auto Op : FPOpToExpand) 388 setOperationAction(Op, MVT::f32, Expand); 389 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 390 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 391 } 392 393 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 394 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 395 396 if (Subtarget.hasStdExtD()) { 397 for (auto NT : FPLegalNodeTypes) 398 setOperationAction(NT, MVT::f64, Legal); 399 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 400 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 401 for (auto CC : FPCCToExpand) 402 setCondCodeAction(CC, MVT::f64, Expand); 403 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 404 setOperationAction(ISD::SELECT, MVT::f64, Custom); 405 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 406 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 407 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 408 for (auto Op : FPOpToExpand) 409 setOperationAction(Op, MVT::f64, Expand); 410 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 411 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 412 } 413 414 if (Subtarget.is64Bit()) { 415 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 416 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 417 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 418 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 419 } 420 421 if (Subtarget.hasStdExtF()) { 422 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 423 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 424 425 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 426 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 427 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 428 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 429 430 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 431 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 432 } 433 434 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 435 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 436 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 437 setOperationAction(ISD::JumpTable, XLenVT, Custom); 438 439 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 440 441 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 442 // Unfortunately this can't be determined just from the ISA naming string. 443 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 444 Subtarget.is64Bit() ? Legal : Custom); 445 446 setOperationAction(ISD::TRAP, MVT::Other, Legal); 447 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 448 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 449 if (Subtarget.is64Bit()) 450 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 451 452 if (Subtarget.hasStdExtA()) { 453 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 454 setMinCmpXchgSizeInBits(32); 455 } else { 456 setMaxAtomicSizeInBitsSupported(0); 457 } 458 459 setBooleanContents(ZeroOrOneBooleanContent); 460 461 if (Subtarget.hasVInstructions()) { 462 setBooleanVectorContents(ZeroOrOneBooleanContent); 463 464 setOperationAction(ISD::VSCALE, XLenVT, Custom); 465 466 // RVV intrinsics may have illegal operands. 467 // We also need to custom legalize vmv.x.s. 468 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 469 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 470 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 471 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 472 if (Subtarget.is64Bit()) { 473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 474 } else { 475 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 476 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 477 } 478 479 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 480 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 481 482 static const unsigned IntegerVPOps[] = { 483 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 484 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 485 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 486 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 487 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 488 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 489 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 490 ISD::VP_MERGE, ISD::VP_SELECT}; 491 492 static const unsigned FloatingPointVPOps[] = { 493 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 494 ISD::VP_FDIV, ISD::VP_FNEG, ISD::VP_FMA, 495 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN, 496 ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, ISD::VP_SELECT}; 497 498 if (!Subtarget.is64Bit()) { 499 // We must custom-lower certain vXi64 operations on RV32 due to the vector 500 // element type being illegal. 501 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 502 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 503 504 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 505 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 506 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 507 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 508 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 509 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 510 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 511 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 512 513 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 514 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 515 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 516 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 517 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 518 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 519 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 520 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 521 } 522 523 for (MVT VT : BoolVecVTs) { 524 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 525 526 // Mask VTs are custom-expanded into a series of standard nodes 527 setOperationAction(ISD::TRUNCATE, VT, Custom); 528 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 529 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 530 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 531 532 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 533 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 534 535 setOperationAction(ISD::SELECT, VT, Custom); 536 setOperationAction(ISD::SELECT_CC, VT, Expand); 537 setOperationAction(ISD::VSELECT, VT, Expand); 538 setOperationAction(ISD::VP_MERGE, VT, Expand); 539 setOperationAction(ISD::VP_SELECT, VT, Expand); 540 541 setOperationAction(ISD::VP_AND, VT, Custom); 542 setOperationAction(ISD::VP_OR, VT, Custom); 543 setOperationAction(ISD::VP_XOR, VT, Custom); 544 545 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 546 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 547 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 548 549 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 550 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 551 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 552 553 // RVV has native int->float & float->int conversions where the 554 // element type sizes are within one power-of-two of each other. Any 555 // wider distances between type sizes have to be lowered as sequences 556 // which progressively narrow the gap in stages. 557 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 558 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 559 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 560 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 561 562 // Expand all extending loads to types larger than this, and truncating 563 // stores from types larger than this. 564 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 565 setTruncStoreAction(OtherVT, VT, Expand); 566 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 567 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 568 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 569 } 570 } 571 572 for (MVT VT : IntVecVTs) { 573 if (VT.getVectorElementType() == MVT::i64 && 574 !Subtarget.hasVInstructionsI64()) 575 continue; 576 577 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 578 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 579 580 // Vectors implement MULHS/MULHU. 581 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 582 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 583 584 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 585 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 586 setOperationAction(ISD::MULHU, VT, Expand); 587 setOperationAction(ISD::MULHS, VT, Expand); 588 } 589 590 setOperationAction(ISD::SMIN, VT, Legal); 591 setOperationAction(ISD::SMAX, VT, Legal); 592 setOperationAction(ISD::UMIN, VT, Legal); 593 setOperationAction(ISD::UMAX, VT, Legal); 594 595 setOperationAction(ISD::ROTL, VT, Expand); 596 setOperationAction(ISD::ROTR, VT, Expand); 597 598 setOperationAction(ISD::CTTZ, VT, Expand); 599 setOperationAction(ISD::CTLZ, VT, Expand); 600 setOperationAction(ISD::CTPOP, VT, Expand); 601 602 setOperationAction(ISD::BSWAP, VT, Expand); 603 604 // Custom-lower extensions and truncations from/to mask types. 605 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 606 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 607 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 608 609 // RVV has native int->float & float->int conversions where the 610 // element type sizes are within one power-of-two of each other. Any 611 // wider distances between type sizes have to be lowered as sequences 612 // which progressively narrow the gap in stages. 613 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 614 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 615 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 616 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 617 618 setOperationAction(ISD::SADDSAT, VT, Legal); 619 setOperationAction(ISD::UADDSAT, VT, Legal); 620 setOperationAction(ISD::SSUBSAT, VT, Legal); 621 setOperationAction(ISD::USUBSAT, VT, Legal); 622 623 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 624 // nodes which truncate by one power of two at a time. 625 setOperationAction(ISD::TRUNCATE, VT, Custom); 626 627 // Custom-lower insert/extract operations to simplify patterns. 628 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 629 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 630 631 // Custom-lower reduction operations to set up the corresponding custom 632 // nodes' operands. 633 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 634 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 635 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 636 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 637 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 638 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 639 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 640 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 641 642 for (unsigned VPOpc : IntegerVPOps) 643 setOperationAction(VPOpc, VT, Custom); 644 645 setOperationAction(ISD::LOAD, VT, Custom); 646 setOperationAction(ISD::STORE, VT, Custom); 647 648 setOperationAction(ISD::MLOAD, VT, Custom); 649 setOperationAction(ISD::MSTORE, VT, Custom); 650 setOperationAction(ISD::MGATHER, VT, Custom); 651 setOperationAction(ISD::MSCATTER, VT, Custom); 652 653 setOperationAction(ISD::VP_LOAD, VT, Custom); 654 setOperationAction(ISD::VP_STORE, VT, Custom); 655 setOperationAction(ISD::VP_GATHER, VT, Custom); 656 setOperationAction(ISD::VP_SCATTER, VT, Custom); 657 658 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 659 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 660 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 661 662 setOperationAction(ISD::SELECT, VT, Custom); 663 setOperationAction(ISD::SELECT_CC, VT, Expand); 664 665 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 666 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 667 668 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 669 setTruncStoreAction(VT, OtherVT, Expand); 670 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 671 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 672 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 673 } 674 675 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 676 // type that can represent the value exactly. 677 if (VT.getVectorElementType() != MVT::i64) { 678 MVT FloatEltVT = 679 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 680 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 681 if (isTypeLegal(FloatVT)) { 682 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 683 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 684 } 685 } 686 } 687 688 // Expand various CCs to best match the RVV ISA, which natively supports UNE 689 // but no other unordered comparisons, and supports all ordered comparisons 690 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 691 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 692 // and we pattern-match those back to the "original", swapping operands once 693 // more. This way we catch both operations and both "vf" and "fv" forms with 694 // fewer patterns. 695 static const ISD::CondCode VFPCCToExpand[] = { 696 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 697 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 698 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 699 }; 700 701 // Sets common operation actions on RVV floating-point vector types. 702 const auto SetCommonVFPActions = [&](MVT VT) { 703 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 704 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 705 // sizes are within one power-of-two of each other. Therefore conversions 706 // between vXf16 and vXf64 must be lowered as sequences which convert via 707 // vXf32. 708 setOperationAction(ISD::FP_ROUND, VT, Custom); 709 setOperationAction(ISD::FP_EXTEND, VT, Custom); 710 // Custom-lower insert/extract operations to simplify patterns. 711 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 712 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 713 // Expand various condition codes (explained above). 714 for (auto CC : VFPCCToExpand) 715 setCondCodeAction(CC, VT, Expand); 716 717 setOperationAction(ISD::FMINNUM, VT, Legal); 718 setOperationAction(ISD::FMAXNUM, VT, Legal); 719 720 setOperationAction(ISD::FTRUNC, VT, Custom); 721 setOperationAction(ISD::FCEIL, VT, Custom); 722 setOperationAction(ISD::FFLOOR, VT, Custom); 723 setOperationAction(ISD::FROUND, VT, Custom); 724 725 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 726 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 727 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 728 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 729 730 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 731 732 setOperationAction(ISD::LOAD, VT, Custom); 733 setOperationAction(ISD::STORE, VT, Custom); 734 735 setOperationAction(ISD::MLOAD, VT, Custom); 736 setOperationAction(ISD::MSTORE, VT, Custom); 737 setOperationAction(ISD::MGATHER, VT, Custom); 738 setOperationAction(ISD::MSCATTER, VT, Custom); 739 740 setOperationAction(ISD::VP_LOAD, VT, Custom); 741 setOperationAction(ISD::VP_STORE, VT, Custom); 742 setOperationAction(ISD::VP_GATHER, VT, Custom); 743 setOperationAction(ISD::VP_SCATTER, VT, Custom); 744 745 setOperationAction(ISD::SELECT, VT, Custom); 746 setOperationAction(ISD::SELECT_CC, VT, Expand); 747 748 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 749 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 750 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 751 752 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 753 754 for (unsigned VPOpc : FloatingPointVPOps) 755 setOperationAction(VPOpc, VT, Custom); 756 }; 757 758 // Sets common extload/truncstore actions on RVV floating-point vector 759 // types. 760 const auto SetCommonVFPExtLoadTruncStoreActions = 761 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 762 for (auto SmallVT : SmallerVTs) { 763 setTruncStoreAction(VT, SmallVT, Expand); 764 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 765 } 766 }; 767 768 if (Subtarget.hasVInstructionsF16()) 769 for (MVT VT : F16VecVTs) 770 SetCommonVFPActions(VT); 771 772 for (MVT VT : F32VecVTs) { 773 if (Subtarget.hasVInstructionsF32()) 774 SetCommonVFPActions(VT); 775 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 776 } 777 778 for (MVT VT : F64VecVTs) { 779 if (Subtarget.hasVInstructionsF64()) 780 SetCommonVFPActions(VT); 781 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 782 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 783 } 784 785 if (Subtarget.useRVVForFixedLengthVectors()) { 786 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 787 if (!useRVVForFixedLengthVectorVT(VT)) 788 continue; 789 790 // By default everything must be expanded. 791 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 792 setOperationAction(Op, VT, Expand); 793 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 794 setTruncStoreAction(VT, OtherVT, Expand); 795 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 796 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 797 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 798 } 799 800 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 801 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 802 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 803 804 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 805 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 806 807 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 808 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 809 810 setOperationAction(ISD::LOAD, VT, Custom); 811 setOperationAction(ISD::STORE, VT, Custom); 812 813 setOperationAction(ISD::SETCC, VT, Custom); 814 815 setOperationAction(ISD::SELECT, VT, Custom); 816 817 setOperationAction(ISD::TRUNCATE, VT, Custom); 818 819 setOperationAction(ISD::BITCAST, VT, Custom); 820 821 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 822 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 823 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 824 825 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 826 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 827 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 828 829 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 830 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 831 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 832 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 833 834 // Operations below are different for between masks and other vectors. 835 if (VT.getVectorElementType() == MVT::i1) { 836 setOperationAction(ISD::VP_AND, VT, Custom); 837 setOperationAction(ISD::VP_OR, VT, Custom); 838 setOperationAction(ISD::VP_XOR, VT, Custom); 839 setOperationAction(ISD::AND, VT, Custom); 840 setOperationAction(ISD::OR, VT, Custom); 841 setOperationAction(ISD::XOR, VT, Custom); 842 continue; 843 } 844 845 // Use SPLAT_VECTOR to prevent type legalization from destroying the 846 // splats when type legalizing i64 scalar on RV32. 847 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 848 // improvements first. 849 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 850 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 851 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 852 } 853 854 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 855 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 856 857 setOperationAction(ISD::MLOAD, VT, Custom); 858 setOperationAction(ISD::MSTORE, VT, Custom); 859 setOperationAction(ISD::MGATHER, VT, Custom); 860 setOperationAction(ISD::MSCATTER, VT, Custom); 861 862 setOperationAction(ISD::VP_LOAD, VT, Custom); 863 setOperationAction(ISD::VP_STORE, VT, Custom); 864 setOperationAction(ISD::VP_GATHER, VT, Custom); 865 setOperationAction(ISD::VP_SCATTER, VT, Custom); 866 867 setOperationAction(ISD::ADD, VT, Custom); 868 setOperationAction(ISD::MUL, VT, Custom); 869 setOperationAction(ISD::SUB, VT, Custom); 870 setOperationAction(ISD::AND, VT, Custom); 871 setOperationAction(ISD::OR, VT, Custom); 872 setOperationAction(ISD::XOR, VT, Custom); 873 setOperationAction(ISD::SDIV, VT, Custom); 874 setOperationAction(ISD::SREM, VT, Custom); 875 setOperationAction(ISD::UDIV, VT, Custom); 876 setOperationAction(ISD::UREM, VT, Custom); 877 setOperationAction(ISD::SHL, VT, Custom); 878 setOperationAction(ISD::SRA, VT, Custom); 879 setOperationAction(ISD::SRL, VT, Custom); 880 881 setOperationAction(ISD::SMIN, VT, Custom); 882 setOperationAction(ISD::SMAX, VT, Custom); 883 setOperationAction(ISD::UMIN, VT, Custom); 884 setOperationAction(ISD::UMAX, VT, Custom); 885 setOperationAction(ISD::ABS, VT, Custom); 886 887 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 888 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 889 setOperationAction(ISD::MULHS, VT, Custom); 890 setOperationAction(ISD::MULHU, VT, Custom); 891 } 892 893 setOperationAction(ISD::SADDSAT, VT, Custom); 894 setOperationAction(ISD::UADDSAT, VT, Custom); 895 setOperationAction(ISD::SSUBSAT, VT, Custom); 896 setOperationAction(ISD::USUBSAT, VT, Custom); 897 898 setOperationAction(ISD::VSELECT, VT, Custom); 899 setOperationAction(ISD::SELECT_CC, VT, Expand); 900 901 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 902 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 903 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 904 905 // Custom-lower reduction operations to set up the corresponding custom 906 // nodes' operands. 907 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 908 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 909 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 910 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 911 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 912 913 for (unsigned VPOpc : IntegerVPOps) 914 setOperationAction(VPOpc, VT, Custom); 915 916 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 917 // type that can represent the value exactly. 918 if (VT.getVectorElementType() != MVT::i64) { 919 MVT FloatEltVT = 920 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 921 EVT FloatVT = 922 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 923 if (isTypeLegal(FloatVT)) { 924 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 925 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 926 } 927 } 928 } 929 930 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 931 if (!useRVVForFixedLengthVectorVT(VT)) 932 continue; 933 934 // By default everything must be expanded. 935 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 936 setOperationAction(Op, VT, Expand); 937 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 938 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 939 setTruncStoreAction(VT, OtherVT, Expand); 940 } 941 942 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 943 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 944 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 945 946 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 947 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 948 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 949 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 950 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 951 952 setOperationAction(ISD::LOAD, VT, Custom); 953 setOperationAction(ISD::STORE, VT, Custom); 954 setOperationAction(ISD::MLOAD, VT, Custom); 955 setOperationAction(ISD::MSTORE, VT, Custom); 956 setOperationAction(ISD::MGATHER, VT, Custom); 957 setOperationAction(ISD::MSCATTER, VT, Custom); 958 959 setOperationAction(ISD::VP_LOAD, VT, Custom); 960 setOperationAction(ISD::VP_STORE, VT, Custom); 961 setOperationAction(ISD::VP_GATHER, VT, Custom); 962 setOperationAction(ISD::VP_SCATTER, VT, Custom); 963 964 setOperationAction(ISD::FADD, VT, Custom); 965 setOperationAction(ISD::FSUB, VT, Custom); 966 setOperationAction(ISD::FMUL, VT, Custom); 967 setOperationAction(ISD::FDIV, VT, Custom); 968 setOperationAction(ISD::FNEG, VT, Custom); 969 setOperationAction(ISD::FABS, VT, Custom); 970 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 971 setOperationAction(ISD::FSQRT, VT, Custom); 972 setOperationAction(ISD::FMA, VT, Custom); 973 setOperationAction(ISD::FMINNUM, VT, Custom); 974 setOperationAction(ISD::FMAXNUM, VT, Custom); 975 976 setOperationAction(ISD::FP_ROUND, VT, Custom); 977 setOperationAction(ISD::FP_EXTEND, VT, Custom); 978 979 setOperationAction(ISD::FTRUNC, VT, Custom); 980 setOperationAction(ISD::FCEIL, VT, Custom); 981 setOperationAction(ISD::FFLOOR, VT, Custom); 982 setOperationAction(ISD::FROUND, VT, Custom); 983 984 for (auto CC : VFPCCToExpand) 985 setCondCodeAction(CC, VT, Expand); 986 987 setOperationAction(ISD::VSELECT, VT, Custom); 988 setOperationAction(ISD::SELECT, VT, Custom); 989 setOperationAction(ISD::SELECT_CC, VT, Expand); 990 991 setOperationAction(ISD::BITCAST, VT, Custom); 992 993 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 994 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 995 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 996 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 997 998 for (unsigned VPOpc : FloatingPointVPOps) 999 setOperationAction(VPOpc, VT, Custom); 1000 } 1001 1002 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1003 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1004 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1005 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1006 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1007 if (Subtarget.hasStdExtZfh()) 1008 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1009 if (Subtarget.hasStdExtF()) 1010 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1011 if (Subtarget.hasStdExtD()) 1012 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1013 } 1014 } 1015 1016 // Function alignments. 1017 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1018 setMinFunctionAlignment(FunctionAlignment); 1019 setPrefFunctionAlignment(FunctionAlignment); 1020 1021 setMinimumJumpTableEntries(5); 1022 1023 // Jumps are expensive, compared to logic 1024 setJumpIsExpensive(); 1025 1026 setTargetDAGCombine(ISD::ADD); 1027 setTargetDAGCombine(ISD::SUB); 1028 setTargetDAGCombine(ISD::AND); 1029 setTargetDAGCombine(ISD::OR); 1030 setTargetDAGCombine(ISD::XOR); 1031 setTargetDAGCombine(ISD::ROTL); 1032 setTargetDAGCombine(ISD::ROTR); 1033 setTargetDAGCombine(ISD::ANY_EXTEND); 1034 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1035 if (Subtarget.hasStdExtZfh()) 1036 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 1037 if (Subtarget.hasStdExtF()) { 1038 setTargetDAGCombine(ISD::ZERO_EXTEND); 1039 setTargetDAGCombine(ISD::FP_TO_SINT); 1040 setTargetDAGCombine(ISD::FP_TO_UINT); 1041 setTargetDAGCombine(ISD::FP_TO_SINT_SAT); 1042 setTargetDAGCombine(ISD::FP_TO_UINT_SAT); 1043 } 1044 if (Subtarget.hasVInstructions()) { 1045 setTargetDAGCombine(ISD::FCOPYSIGN); 1046 setTargetDAGCombine(ISD::MGATHER); 1047 setTargetDAGCombine(ISD::MSCATTER); 1048 setTargetDAGCombine(ISD::VP_GATHER); 1049 setTargetDAGCombine(ISD::VP_SCATTER); 1050 setTargetDAGCombine(ISD::SRA); 1051 setTargetDAGCombine(ISD::SRL); 1052 setTargetDAGCombine(ISD::SHL); 1053 setTargetDAGCombine(ISD::STORE); 1054 setTargetDAGCombine(ISD::SPLAT_VECTOR); 1055 } 1056 1057 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1058 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1059 } 1060 1061 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1062 LLVMContext &Context, 1063 EVT VT) const { 1064 if (!VT.isVector()) 1065 return getPointerTy(DL); 1066 if (Subtarget.hasVInstructions() && 1067 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1068 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1069 return VT.changeVectorElementTypeToInteger(); 1070 } 1071 1072 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1073 return Subtarget.getXLenVT(); 1074 } 1075 1076 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1077 const CallInst &I, 1078 MachineFunction &MF, 1079 unsigned Intrinsic) const { 1080 auto &DL = I.getModule()->getDataLayout(); 1081 switch (Intrinsic) { 1082 default: 1083 return false; 1084 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1085 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1086 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1087 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1088 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1089 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1090 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1091 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1092 case Intrinsic::riscv_masked_cmpxchg_i32: 1093 Info.opc = ISD::INTRINSIC_W_CHAIN; 1094 Info.memVT = MVT::i32; 1095 Info.ptrVal = I.getArgOperand(0); 1096 Info.offset = 0; 1097 Info.align = Align(4); 1098 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1099 MachineMemOperand::MOVolatile; 1100 return true; 1101 case Intrinsic::riscv_masked_strided_load: 1102 Info.opc = ISD::INTRINSIC_W_CHAIN; 1103 Info.ptrVal = I.getArgOperand(1); 1104 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1105 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1106 Info.size = MemoryLocation::UnknownSize; 1107 Info.flags |= MachineMemOperand::MOLoad; 1108 return true; 1109 case Intrinsic::riscv_masked_strided_store: 1110 Info.opc = ISD::INTRINSIC_VOID; 1111 Info.ptrVal = I.getArgOperand(1); 1112 Info.memVT = 1113 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1114 Info.align = Align( 1115 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1116 8); 1117 Info.size = MemoryLocation::UnknownSize; 1118 Info.flags |= MachineMemOperand::MOStore; 1119 return true; 1120 } 1121 } 1122 1123 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1124 const AddrMode &AM, Type *Ty, 1125 unsigned AS, 1126 Instruction *I) const { 1127 // No global is ever allowed as a base. 1128 if (AM.BaseGV) 1129 return false; 1130 1131 // Require a 12-bit signed offset. 1132 if (!isInt<12>(AM.BaseOffs)) 1133 return false; 1134 1135 switch (AM.Scale) { 1136 case 0: // "r+i" or just "i", depending on HasBaseReg. 1137 break; 1138 case 1: 1139 if (!AM.HasBaseReg) // allow "r+i". 1140 break; 1141 return false; // disallow "r+r" or "r+r+i". 1142 default: 1143 return false; 1144 } 1145 1146 return true; 1147 } 1148 1149 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1150 return isInt<12>(Imm); 1151 } 1152 1153 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1154 return isInt<12>(Imm); 1155 } 1156 1157 // On RV32, 64-bit integers are split into their high and low parts and held 1158 // in two different registers, so the trunc is free since the low register can 1159 // just be used. 1160 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1161 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1162 return false; 1163 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1164 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1165 return (SrcBits == 64 && DestBits == 32); 1166 } 1167 1168 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1169 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1170 !SrcVT.isInteger() || !DstVT.isInteger()) 1171 return false; 1172 unsigned SrcBits = SrcVT.getSizeInBits(); 1173 unsigned DestBits = DstVT.getSizeInBits(); 1174 return (SrcBits == 64 && DestBits == 32); 1175 } 1176 1177 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1178 // Zexts are free if they can be combined with a load. 1179 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1180 // poorly with type legalization of compares preferring sext. 1181 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1182 EVT MemVT = LD->getMemoryVT(); 1183 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1184 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1185 LD->getExtensionType() == ISD::ZEXTLOAD)) 1186 return true; 1187 } 1188 1189 return TargetLowering::isZExtFree(Val, VT2); 1190 } 1191 1192 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1193 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1194 } 1195 1196 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1197 return Subtarget.hasStdExtZbb(); 1198 } 1199 1200 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1201 return Subtarget.hasStdExtZbb(); 1202 } 1203 1204 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1205 EVT VT = Y.getValueType(); 1206 1207 // FIXME: Support vectors once we have tests. 1208 if (VT.isVector()) 1209 return false; 1210 1211 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1212 Subtarget.hasStdExtZbkb()) && 1213 !isa<ConstantSDNode>(Y); 1214 } 1215 1216 /// Check if sinking \p I's operands to I's basic block is profitable, because 1217 /// the operands can be folded into a target instruction, e.g. 1218 /// splats of scalars can fold into vector instructions. 1219 bool RISCVTargetLowering::shouldSinkOperands( 1220 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1221 using namespace llvm::PatternMatch; 1222 1223 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1224 return false; 1225 1226 auto IsSinker = [&](Instruction *I, int Operand) { 1227 switch (I->getOpcode()) { 1228 case Instruction::Add: 1229 case Instruction::Sub: 1230 case Instruction::Mul: 1231 case Instruction::And: 1232 case Instruction::Or: 1233 case Instruction::Xor: 1234 case Instruction::FAdd: 1235 case Instruction::FSub: 1236 case Instruction::FMul: 1237 case Instruction::FDiv: 1238 case Instruction::ICmp: 1239 case Instruction::FCmp: 1240 return true; 1241 case Instruction::Shl: 1242 case Instruction::LShr: 1243 case Instruction::AShr: 1244 case Instruction::UDiv: 1245 case Instruction::SDiv: 1246 case Instruction::URem: 1247 case Instruction::SRem: 1248 return Operand == 1; 1249 case Instruction::Call: 1250 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1251 switch (II->getIntrinsicID()) { 1252 case Intrinsic::fma: 1253 case Intrinsic::vp_fma: 1254 return Operand == 0 || Operand == 1; 1255 // FIXME: Our patterns can only match vx/vf instructions when the splat 1256 // it on the RHS, because TableGen doesn't recognize our VP operations 1257 // as commutative. 1258 case Intrinsic::vp_add: 1259 case Intrinsic::vp_mul: 1260 case Intrinsic::vp_and: 1261 case Intrinsic::vp_or: 1262 case Intrinsic::vp_xor: 1263 case Intrinsic::vp_fadd: 1264 case Intrinsic::vp_fmul: 1265 case Intrinsic::vp_shl: 1266 case Intrinsic::vp_lshr: 1267 case Intrinsic::vp_ashr: 1268 case Intrinsic::vp_udiv: 1269 case Intrinsic::vp_sdiv: 1270 case Intrinsic::vp_urem: 1271 case Intrinsic::vp_srem: 1272 return Operand == 1; 1273 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1274 // explicit patterns for both LHS and RHS (as 'vr' versions). 1275 case Intrinsic::vp_sub: 1276 case Intrinsic::vp_fsub: 1277 case Intrinsic::vp_fdiv: 1278 return Operand == 0 || Operand == 1; 1279 default: 1280 return false; 1281 } 1282 } 1283 return false; 1284 default: 1285 return false; 1286 } 1287 }; 1288 1289 for (auto OpIdx : enumerate(I->operands())) { 1290 if (!IsSinker(I, OpIdx.index())) 1291 continue; 1292 1293 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1294 // Make sure we are not already sinking this operand 1295 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1296 continue; 1297 1298 // We are looking for a splat that can be sunk. 1299 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1300 m_Undef(), m_ZeroMask()))) 1301 continue; 1302 1303 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1304 // and vector registers 1305 for (Use &U : Op->uses()) { 1306 Instruction *Insn = cast<Instruction>(U.getUser()); 1307 if (!IsSinker(Insn, U.getOperandNo())) 1308 return false; 1309 } 1310 1311 Ops.push_back(&Op->getOperandUse(0)); 1312 Ops.push_back(&OpIdx.value()); 1313 } 1314 return true; 1315 } 1316 1317 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1318 bool ForCodeSize) const { 1319 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1320 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1321 return false; 1322 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1323 return false; 1324 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1325 return false; 1326 return Imm.isZero(); 1327 } 1328 1329 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1330 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1331 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1332 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1333 } 1334 1335 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1336 CallingConv::ID CC, 1337 EVT VT) const { 1338 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1339 // We might still end up using a GPR but that will be decided based on ABI. 1340 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1341 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1342 return MVT::f32; 1343 1344 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1345 } 1346 1347 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1348 CallingConv::ID CC, 1349 EVT VT) const { 1350 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1351 // We might still end up using a GPR but that will be decided based on ABI. 1352 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1353 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1354 return 1; 1355 1356 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1357 } 1358 1359 // Changes the condition code and swaps operands if necessary, so the SetCC 1360 // operation matches one of the comparisons supported directly by branches 1361 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1362 // with 1/-1. 1363 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1364 ISD::CondCode &CC, SelectionDAG &DAG) { 1365 // Convert X > -1 to X >= 0. 1366 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1367 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1368 CC = ISD::SETGE; 1369 return; 1370 } 1371 // Convert X < 1 to 0 >= X. 1372 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1373 RHS = LHS; 1374 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1375 CC = ISD::SETGE; 1376 return; 1377 } 1378 1379 switch (CC) { 1380 default: 1381 break; 1382 case ISD::SETGT: 1383 case ISD::SETLE: 1384 case ISD::SETUGT: 1385 case ISD::SETULE: 1386 CC = ISD::getSetCCSwappedOperands(CC); 1387 std::swap(LHS, RHS); 1388 break; 1389 } 1390 } 1391 1392 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1393 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1394 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1395 if (VT.getVectorElementType() == MVT::i1) 1396 KnownSize *= 8; 1397 1398 switch (KnownSize) { 1399 default: 1400 llvm_unreachable("Invalid LMUL."); 1401 case 8: 1402 return RISCVII::VLMUL::LMUL_F8; 1403 case 16: 1404 return RISCVII::VLMUL::LMUL_F4; 1405 case 32: 1406 return RISCVII::VLMUL::LMUL_F2; 1407 case 64: 1408 return RISCVII::VLMUL::LMUL_1; 1409 case 128: 1410 return RISCVII::VLMUL::LMUL_2; 1411 case 256: 1412 return RISCVII::VLMUL::LMUL_4; 1413 case 512: 1414 return RISCVII::VLMUL::LMUL_8; 1415 } 1416 } 1417 1418 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1419 switch (LMul) { 1420 default: 1421 llvm_unreachable("Invalid LMUL."); 1422 case RISCVII::VLMUL::LMUL_F8: 1423 case RISCVII::VLMUL::LMUL_F4: 1424 case RISCVII::VLMUL::LMUL_F2: 1425 case RISCVII::VLMUL::LMUL_1: 1426 return RISCV::VRRegClassID; 1427 case RISCVII::VLMUL::LMUL_2: 1428 return RISCV::VRM2RegClassID; 1429 case RISCVII::VLMUL::LMUL_4: 1430 return RISCV::VRM4RegClassID; 1431 case RISCVII::VLMUL::LMUL_8: 1432 return RISCV::VRM8RegClassID; 1433 } 1434 } 1435 1436 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1437 RISCVII::VLMUL LMUL = getLMUL(VT); 1438 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1439 LMUL == RISCVII::VLMUL::LMUL_F4 || 1440 LMUL == RISCVII::VLMUL::LMUL_F2 || 1441 LMUL == RISCVII::VLMUL::LMUL_1) { 1442 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1443 "Unexpected subreg numbering"); 1444 return RISCV::sub_vrm1_0 + Index; 1445 } 1446 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1447 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1448 "Unexpected subreg numbering"); 1449 return RISCV::sub_vrm2_0 + Index; 1450 } 1451 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1452 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1453 "Unexpected subreg numbering"); 1454 return RISCV::sub_vrm4_0 + Index; 1455 } 1456 llvm_unreachable("Invalid vector type."); 1457 } 1458 1459 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1460 if (VT.getVectorElementType() == MVT::i1) 1461 return RISCV::VRRegClassID; 1462 return getRegClassIDForLMUL(getLMUL(VT)); 1463 } 1464 1465 // Attempt to decompose a subvector insert/extract between VecVT and 1466 // SubVecVT via subregister indices. Returns the subregister index that 1467 // can perform the subvector insert/extract with the given element index, as 1468 // well as the index corresponding to any leftover subvectors that must be 1469 // further inserted/extracted within the register class for SubVecVT. 1470 std::pair<unsigned, unsigned> 1471 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1472 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1473 const RISCVRegisterInfo *TRI) { 1474 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1475 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1476 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1477 "Register classes not ordered"); 1478 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1479 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1480 // Try to compose a subregister index that takes us from the incoming 1481 // LMUL>1 register class down to the outgoing one. At each step we half 1482 // the LMUL: 1483 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1484 // Note that this is not guaranteed to find a subregister index, such as 1485 // when we are extracting from one VR type to another. 1486 unsigned SubRegIdx = RISCV::NoSubRegister; 1487 for (const unsigned RCID : 1488 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1489 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1490 VecVT = VecVT.getHalfNumVectorElementsVT(); 1491 bool IsHi = 1492 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1493 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1494 getSubregIndexByMVT(VecVT, IsHi)); 1495 if (IsHi) 1496 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1497 } 1498 return {SubRegIdx, InsertExtractIdx}; 1499 } 1500 1501 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1502 // stores for those types. 1503 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1504 return !Subtarget.useRVVForFixedLengthVectors() || 1505 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1506 } 1507 1508 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1509 if (ScalarTy->isPointerTy()) 1510 return true; 1511 1512 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1513 ScalarTy->isIntegerTy(32)) 1514 return true; 1515 1516 if (ScalarTy->isIntegerTy(64)) 1517 return Subtarget.hasVInstructionsI64(); 1518 1519 if (ScalarTy->isHalfTy()) 1520 return Subtarget.hasVInstructionsF16(); 1521 if (ScalarTy->isFloatTy()) 1522 return Subtarget.hasVInstructionsF32(); 1523 if (ScalarTy->isDoubleTy()) 1524 return Subtarget.hasVInstructionsF64(); 1525 1526 return false; 1527 } 1528 1529 static SDValue getVLOperand(SDValue Op) { 1530 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1531 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1532 "Unexpected opcode"); 1533 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1534 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1535 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1536 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1537 if (!II) 1538 return SDValue(); 1539 return Op.getOperand(II->VLOperand + 1 + HasChain); 1540 } 1541 1542 static bool useRVVForFixedLengthVectorVT(MVT VT, 1543 const RISCVSubtarget &Subtarget) { 1544 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1545 if (!Subtarget.useRVVForFixedLengthVectors()) 1546 return false; 1547 1548 // We only support a set of vector types with a consistent maximum fixed size 1549 // across all supported vector element types to avoid legalization issues. 1550 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1551 // fixed-length vector type we support is 1024 bytes. 1552 if (VT.getFixedSizeInBits() > 1024 * 8) 1553 return false; 1554 1555 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1556 1557 MVT EltVT = VT.getVectorElementType(); 1558 1559 // Don't use RVV for vectors we cannot scalarize if required. 1560 switch (EltVT.SimpleTy) { 1561 // i1 is supported but has different rules. 1562 default: 1563 return false; 1564 case MVT::i1: 1565 // Masks can only use a single register. 1566 if (VT.getVectorNumElements() > MinVLen) 1567 return false; 1568 MinVLen /= 8; 1569 break; 1570 case MVT::i8: 1571 case MVT::i16: 1572 case MVT::i32: 1573 break; 1574 case MVT::i64: 1575 if (!Subtarget.hasVInstructionsI64()) 1576 return false; 1577 break; 1578 case MVT::f16: 1579 if (!Subtarget.hasVInstructionsF16()) 1580 return false; 1581 break; 1582 case MVT::f32: 1583 if (!Subtarget.hasVInstructionsF32()) 1584 return false; 1585 break; 1586 case MVT::f64: 1587 if (!Subtarget.hasVInstructionsF64()) 1588 return false; 1589 break; 1590 } 1591 1592 // Reject elements larger than ELEN. 1593 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1594 return false; 1595 1596 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1597 // Don't use RVV for types that don't fit. 1598 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1599 return false; 1600 1601 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1602 // the base fixed length RVV support in place. 1603 if (!VT.isPow2VectorType()) 1604 return false; 1605 1606 return true; 1607 } 1608 1609 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1610 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1611 } 1612 1613 // Return the largest legal scalable vector type that matches VT's element type. 1614 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1615 const RISCVSubtarget &Subtarget) { 1616 // This may be called before legal types are setup. 1617 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1618 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1619 "Expected legal fixed length vector!"); 1620 1621 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1622 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1623 1624 MVT EltVT = VT.getVectorElementType(); 1625 switch (EltVT.SimpleTy) { 1626 default: 1627 llvm_unreachable("unexpected element type for RVV container"); 1628 case MVT::i1: 1629 case MVT::i8: 1630 case MVT::i16: 1631 case MVT::i32: 1632 case MVT::i64: 1633 case MVT::f16: 1634 case MVT::f32: 1635 case MVT::f64: { 1636 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1637 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1638 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1639 unsigned NumElts = 1640 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1641 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1642 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1643 return MVT::getScalableVectorVT(EltVT, NumElts); 1644 } 1645 } 1646 } 1647 1648 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1649 const RISCVSubtarget &Subtarget) { 1650 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1651 Subtarget); 1652 } 1653 1654 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1655 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1656 } 1657 1658 // Grow V to consume an entire RVV register. 1659 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1660 const RISCVSubtarget &Subtarget) { 1661 assert(VT.isScalableVector() && 1662 "Expected to convert into a scalable vector!"); 1663 assert(V.getValueType().isFixedLengthVector() && 1664 "Expected a fixed length vector operand!"); 1665 SDLoc DL(V); 1666 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1667 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1668 } 1669 1670 // Shrink V so it's just big enough to maintain a VT's worth of data. 1671 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1672 const RISCVSubtarget &Subtarget) { 1673 assert(VT.isFixedLengthVector() && 1674 "Expected to convert into a fixed length vector!"); 1675 assert(V.getValueType().isScalableVector() && 1676 "Expected a scalable vector operand!"); 1677 SDLoc DL(V); 1678 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1679 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1680 } 1681 1682 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1683 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1684 // the vector type that it is contained in. 1685 static std::pair<SDValue, SDValue> 1686 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1687 const RISCVSubtarget &Subtarget) { 1688 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1689 MVT XLenVT = Subtarget.getXLenVT(); 1690 SDValue VL = VecVT.isFixedLengthVector() 1691 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1692 : DAG.getRegister(RISCV::X0, XLenVT); 1693 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1694 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1695 return {Mask, VL}; 1696 } 1697 1698 // As above but assuming the given type is a scalable vector type. 1699 static std::pair<SDValue, SDValue> 1700 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1701 const RISCVSubtarget &Subtarget) { 1702 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1703 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1704 } 1705 1706 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1707 // of either is (currently) supported. This can get us into an infinite loop 1708 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1709 // as a ..., etc. 1710 // Until either (or both) of these can reliably lower any node, reporting that 1711 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1712 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1713 // which is not desirable. 1714 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1715 EVT VT, unsigned DefinedValues) const { 1716 return false; 1717 } 1718 1719 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1720 const RISCVSubtarget &Subtarget) { 1721 // RISCV FP-to-int conversions saturate to the destination register size, but 1722 // don't produce 0 for nan. We can use a conversion instruction and fix the 1723 // nan case with a compare and a select. 1724 SDValue Src = Op.getOperand(0); 1725 1726 EVT DstVT = Op.getValueType(); 1727 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1728 1729 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1730 unsigned Opc; 1731 if (SatVT == DstVT) 1732 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1733 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1734 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1735 else 1736 return SDValue(); 1737 // FIXME: Support other SatVTs by clamping before or after the conversion. 1738 1739 SDLoc DL(Op); 1740 SDValue FpToInt = DAG.getNode( 1741 Opc, DL, DstVT, Src, 1742 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1743 1744 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1745 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1746 } 1747 1748 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1749 // and back. Taking care to avoid converting values that are nan or already 1750 // correct. 1751 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1752 // have FRM dependencies modeled yet. 1753 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1754 MVT VT = Op.getSimpleValueType(); 1755 assert(VT.isVector() && "Unexpected type"); 1756 1757 SDLoc DL(Op); 1758 1759 // Freeze the source since we are increasing the number of uses. 1760 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1761 1762 // Truncate to integer and convert back to FP. 1763 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1764 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1765 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1766 1767 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1768 1769 if (Op.getOpcode() == ISD::FCEIL) { 1770 // If the truncated value is the greater than or equal to the original 1771 // value, we've computed the ceil. Otherwise, we went the wrong way and 1772 // need to increase by 1. 1773 // FIXME: This should use a masked operation. Handle here or in isel? 1774 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1775 DAG.getConstantFP(1.0, DL, VT)); 1776 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1777 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1778 } else if (Op.getOpcode() == ISD::FFLOOR) { 1779 // If the truncated value is the less than or equal to the original value, 1780 // we've computed the floor. Otherwise, we went the wrong way and need to 1781 // decrease by 1. 1782 // FIXME: This should use a masked operation. Handle here or in isel? 1783 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1784 DAG.getConstantFP(1.0, DL, VT)); 1785 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1786 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1787 } 1788 1789 // Restore the original sign so that -0.0 is preserved. 1790 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1791 1792 // Determine the largest integer that can be represented exactly. This and 1793 // values larger than it don't have any fractional bits so don't need to 1794 // be converted. 1795 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1796 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1797 APFloat MaxVal = APFloat(FltSem); 1798 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1799 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1800 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1801 1802 // If abs(Src) was larger than MaxVal or nan, keep it. 1803 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1804 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1805 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1806 } 1807 1808 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1809 // This mode isn't supported in vector hardware on RISCV. But as long as we 1810 // aren't compiling with trapping math, we can emulate this with 1811 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1812 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1813 // dependencies modeled yet. 1814 // FIXME: Use masked operations to avoid final merge. 1815 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1816 MVT VT = Op.getSimpleValueType(); 1817 assert(VT.isVector() && "Unexpected type"); 1818 1819 SDLoc DL(Op); 1820 1821 // Freeze the source since we are increasing the number of uses. 1822 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1823 1824 // We do the conversion on the absolute value and fix the sign at the end. 1825 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1826 1827 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1828 bool Ignored; 1829 APFloat Point5Pred = APFloat(0.5f); 1830 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1831 Point5Pred.next(/*nextDown*/ true); 1832 1833 // Add the adjustment. 1834 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1835 DAG.getConstantFP(Point5Pred, DL, VT)); 1836 1837 // Truncate to integer and convert back to fp. 1838 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1839 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1840 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1841 1842 // Restore the original sign. 1843 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1844 1845 // Determine the largest integer that can be represented exactly. This and 1846 // values larger than it don't have any fractional bits so don't need to 1847 // be converted. 1848 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1849 APFloat MaxVal = APFloat(FltSem); 1850 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1851 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1852 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1853 1854 // If abs(Src) was larger than MaxVal or nan, keep it. 1855 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1856 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1857 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1858 } 1859 1860 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1861 const RISCVSubtarget &Subtarget) { 1862 MVT VT = Op.getSimpleValueType(); 1863 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1864 1865 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1866 1867 SDLoc DL(Op); 1868 SDValue Mask, VL; 1869 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1870 1871 unsigned Opc = 1872 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1873 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 1874 Op.getOperand(0), VL); 1875 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1876 } 1877 1878 struct VIDSequence { 1879 int64_t StepNumerator; 1880 unsigned StepDenominator; 1881 int64_t Addend; 1882 }; 1883 1884 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1885 // to the (non-zero) step S and start value X. This can be then lowered as the 1886 // RVV sequence (VID * S) + X, for example. 1887 // The step S is represented as an integer numerator divided by a positive 1888 // denominator. Note that the implementation currently only identifies 1889 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1890 // cannot detect 2/3, for example. 1891 // Note that this method will also match potentially unappealing index 1892 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1893 // determine whether this is worth generating code for. 1894 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1895 unsigned NumElts = Op.getNumOperands(); 1896 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1897 if (!Op.getValueType().isInteger()) 1898 return None; 1899 1900 Optional<unsigned> SeqStepDenom; 1901 Optional<int64_t> SeqStepNum, SeqAddend; 1902 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1903 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1904 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1905 // Assume undef elements match the sequence; we just have to be careful 1906 // when interpolating across them. 1907 if (Op.getOperand(Idx).isUndef()) 1908 continue; 1909 // The BUILD_VECTOR must be all constants. 1910 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1911 return None; 1912 1913 uint64_t Val = Op.getConstantOperandVal(Idx) & 1914 maskTrailingOnes<uint64_t>(EltSizeInBits); 1915 1916 if (PrevElt) { 1917 // Calculate the step since the last non-undef element, and ensure 1918 // it's consistent across the entire sequence. 1919 unsigned IdxDiff = Idx - PrevElt->second; 1920 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1921 1922 // A zero-value value difference means that we're somewhere in the middle 1923 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1924 // step change before evaluating the sequence. 1925 if (ValDiff != 0) { 1926 int64_t Remainder = ValDiff % IdxDiff; 1927 // Normalize the step if it's greater than 1. 1928 if (Remainder != ValDiff) { 1929 // The difference must cleanly divide the element span. 1930 if (Remainder != 0) 1931 return None; 1932 ValDiff /= IdxDiff; 1933 IdxDiff = 1; 1934 } 1935 1936 if (!SeqStepNum) 1937 SeqStepNum = ValDiff; 1938 else if (ValDiff != SeqStepNum) 1939 return None; 1940 1941 if (!SeqStepDenom) 1942 SeqStepDenom = IdxDiff; 1943 else if (IdxDiff != *SeqStepDenom) 1944 return None; 1945 } 1946 } 1947 1948 // Record and/or check any addend. 1949 if (SeqStepNum && SeqStepDenom) { 1950 uint64_t ExpectedVal = 1951 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1952 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1953 if (!SeqAddend) 1954 SeqAddend = Addend; 1955 else if (SeqAddend != Addend) 1956 return None; 1957 } 1958 1959 // Record this non-undef element for later. 1960 if (!PrevElt || PrevElt->first != Val) 1961 PrevElt = std::make_pair(Val, Idx); 1962 } 1963 // We need to have logged both a step and an addend for this to count as 1964 // a legal index sequence. 1965 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1966 return None; 1967 1968 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1969 } 1970 1971 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1972 // and lower it as a VRGATHER_VX_VL from the source vector. 1973 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1974 SelectionDAG &DAG, 1975 const RISCVSubtarget &Subtarget) { 1976 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1977 return SDValue(); 1978 SDValue Vec = SplatVal.getOperand(0); 1979 // Only perform this optimization on vectors of the same size for simplicity. 1980 if (Vec.getValueType() != VT) 1981 return SDValue(); 1982 SDValue Idx = SplatVal.getOperand(1); 1983 // The index must be a legal type. 1984 if (Idx.getValueType() != Subtarget.getXLenVT()) 1985 return SDValue(); 1986 1987 MVT ContainerVT = VT; 1988 if (VT.isFixedLengthVector()) { 1989 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1990 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1991 } 1992 1993 SDValue Mask, VL; 1994 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1995 1996 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 1997 Idx, Mask, VL); 1998 1999 if (!VT.isFixedLengthVector()) 2000 return Gather; 2001 2002 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2003 } 2004 2005 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2006 const RISCVSubtarget &Subtarget) { 2007 MVT VT = Op.getSimpleValueType(); 2008 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2009 2010 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2011 2012 SDLoc DL(Op); 2013 SDValue Mask, VL; 2014 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2015 2016 MVT XLenVT = Subtarget.getXLenVT(); 2017 unsigned NumElts = Op.getNumOperands(); 2018 2019 if (VT.getVectorElementType() == MVT::i1) { 2020 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2021 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2022 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2023 } 2024 2025 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2026 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2027 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2028 } 2029 2030 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2031 // scalar integer chunks whose bit-width depends on the number of mask 2032 // bits and XLEN. 2033 // First, determine the most appropriate scalar integer type to use. This 2034 // is at most XLenVT, but may be shrunk to a smaller vector element type 2035 // according to the size of the final vector - use i8 chunks rather than 2036 // XLenVT if we're producing a v8i1. This results in more consistent 2037 // codegen across RV32 and RV64. 2038 unsigned NumViaIntegerBits = 2039 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2040 NumViaIntegerBits = std::min(NumViaIntegerBits, 2041 Subtarget.getMaxELENForFixedLengthVectors()); 2042 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2043 // If we have to use more than one INSERT_VECTOR_ELT then this 2044 // optimization is likely to increase code size; avoid peforming it in 2045 // such a case. We can use a load from a constant pool in this case. 2046 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2047 return SDValue(); 2048 // Now we can create our integer vector type. Note that it may be larger 2049 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2050 MVT IntegerViaVecVT = 2051 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2052 divideCeil(NumElts, NumViaIntegerBits)); 2053 2054 uint64_t Bits = 0; 2055 unsigned BitPos = 0, IntegerEltIdx = 0; 2056 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2057 2058 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2059 // Once we accumulate enough bits to fill our scalar type, insert into 2060 // our vector and clear our accumulated data. 2061 if (I != 0 && I % NumViaIntegerBits == 0) { 2062 if (NumViaIntegerBits <= 32) 2063 Bits = SignExtend64(Bits, 32); 2064 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2065 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2066 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2067 Bits = 0; 2068 BitPos = 0; 2069 IntegerEltIdx++; 2070 } 2071 SDValue V = Op.getOperand(I); 2072 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2073 Bits |= ((uint64_t)BitValue << BitPos); 2074 } 2075 2076 // Insert the (remaining) scalar value into position in our integer 2077 // vector type. 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, Elt, 2082 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2083 2084 if (NumElts < NumViaIntegerBits) { 2085 // If we're producing a smaller vector than our minimum legal integer 2086 // type, bitcast to the equivalent (known-legal) mask type, and extract 2087 // our final mask. 2088 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2089 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2090 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2091 DAG.getConstant(0, DL, XLenVT)); 2092 } else { 2093 // Else we must have produced an integer type with the same size as the 2094 // mask type; bitcast for the final result. 2095 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2096 Vec = DAG.getBitcast(VT, Vec); 2097 } 2098 2099 return Vec; 2100 } 2101 2102 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2103 // vector type, we have a legal equivalently-sized i8 type, so we can use 2104 // that. 2105 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2106 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2107 2108 SDValue WideVec; 2109 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2110 // For a splat, perform a scalar truncate before creating the wider 2111 // vector. 2112 assert(Splat.getValueType() == XLenVT && 2113 "Unexpected type for i1 splat value"); 2114 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2115 DAG.getConstant(1, DL, XLenVT)); 2116 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2117 } else { 2118 SmallVector<SDValue, 8> Ops(Op->op_values()); 2119 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2120 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2121 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2122 } 2123 2124 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2125 } 2126 2127 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2128 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2129 return Gather; 2130 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2131 : RISCVISD::VMV_V_X_VL; 2132 Splat = 2133 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2134 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2135 } 2136 2137 // Try and match index sequences, which we can lower to the vid instruction 2138 // with optional modifications. An all-undef vector is matched by 2139 // getSplatValue, above. 2140 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2141 int64_t StepNumerator = SimpleVID->StepNumerator; 2142 unsigned StepDenominator = SimpleVID->StepDenominator; 2143 int64_t Addend = SimpleVID->Addend; 2144 2145 assert(StepNumerator != 0 && "Invalid step"); 2146 bool Negate = false; 2147 int64_t SplatStepVal = StepNumerator; 2148 unsigned StepOpcode = ISD::MUL; 2149 if (StepNumerator != 1) { 2150 if (isPowerOf2_64(std::abs(StepNumerator))) { 2151 Negate = StepNumerator < 0; 2152 StepOpcode = ISD::SHL; 2153 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2154 } 2155 } 2156 2157 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2158 // threshold since it's the immediate value many RVV instructions accept. 2159 // There is no vmul.vi instruction so ensure multiply constant can fit in 2160 // a single addi instruction. 2161 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2162 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2163 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2164 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2165 // Convert right out of the scalable type so we can use standard ISD 2166 // nodes for the rest of the computation. If we used scalable types with 2167 // these, we'd lose the fixed-length vector info and generate worse 2168 // vsetvli code. 2169 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2170 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2171 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2172 SDValue SplatStep = DAG.getSplatVector( 2173 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2174 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2175 } 2176 if (StepDenominator != 1) { 2177 SDValue SplatStep = DAG.getSplatVector( 2178 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2179 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2180 } 2181 if (Addend != 0 || Negate) { 2182 SDValue SplatAddend = 2183 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2184 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2185 } 2186 return VID; 2187 } 2188 } 2189 2190 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2191 // when re-interpreted as a vector with a larger element type. For example, 2192 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2193 // could be instead splat as 2194 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2195 // TODO: This optimization could also work on non-constant splats, but it 2196 // would require bit-manipulation instructions to construct the splat value. 2197 SmallVector<SDValue> Sequence; 2198 unsigned EltBitSize = VT.getScalarSizeInBits(); 2199 const auto *BV = cast<BuildVectorSDNode>(Op); 2200 if (VT.isInteger() && EltBitSize < 64 && 2201 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2202 BV->getRepeatedSequence(Sequence) && 2203 (Sequence.size() * EltBitSize) <= 64) { 2204 unsigned SeqLen = Sequence.size(); 2205 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2206 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2207 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2208 ViaIntVT == MVT::i64) && 2209 "Unexpected sequence type"); 2210 2211 unsigned EltIdx = 0; 2212 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2213 uint64_t SplatValue = 0; 2214 // Construct the amalgamated value which can be splatted as this larger 2215 // vector type. 2216 for (const auto &SeqV : Sequence) { 2217 if (!SeqV.isUndef()) 2218 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2219 << (EltIdx * EltBitSize)); 2220 EltIdx++; 2221 } 2222 2223 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2224 // achieve better constant materializion. 2225 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2226 SplatValue = SignExtend64(SplatValue, 32); 2227 2228 // Since we can't introduce illegal i64 types at this stage, we can only 2229 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2230 // way we can use RVV instructions to splat. 2231 assert((ViaIntVT.bitsLE(XLenVT) || 2232 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2233 "Unexpected bitcast sequence"); 2234 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2235 SDValue ViaVL = 2236 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2237 MVT ViaContainerVT = 2238 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2239 SDValue Splat = 2240 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2241 DAG.getUNDEF(ViaContainerVT), 2242 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2243 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2244 return DAG.getBitcast(VT, Splat); 2245 } 2246 } 2247 2248 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2249 // which constitute a large proportion of the elements. In such cases we can 2250 // splat a vector with the dominant element and make up the shortfall with 2251 // INSERT_VECTOR_ELTs. 2252 // Note that this includes vectors of 2 elements by association. The 2253 // upper-most element is the "dominant" one, allowing us to use a splat to 2254 // "insert" the upper element, and an insert of the lower element at position 2255 // 0, which improves codegen. 2256 SDValue DominantValue; 2257 unsigned MostCommonCount = 0; 2258 DenseMap<SDValue, unsigned> ValueCounts; 2259 unsigned NumUndefElts = 2260 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2261 2262 // Track the number of scalar loads we know we'd be inserting, estimated as 2263 // any non-zero floating-point constant. Other kinds of element are either 2264 // already in registers or are materialized on demand. The threshold at which 2265 // a vector load is more desirable than several scalar materializion and 2266 // vector-insertion instructions is not known. 2267 unsigned NumScalarLoads = 0; 2268 2269 for (SDValue V : Op->op_values()) { 2270 if (V.isUndef()) 2271 continue; 2272 2273 ValueCounts.insert(std::make_pair(V, 0)); 2274 unsigned &Count = ValueCounts[V]; 2275 2276 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2277 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2278 2279 // Is this value dominant? In case of a tie, prefer the highest element as 2280 // it's cheaper to insert near the beginning of a vector than it is at the 2281 // end. 2282 if (++Count >= MostCommonCount) { 2283 DominantValue = V; 2284 MostCommonCount = Count; 2285 } 2286 } 2287 2288 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2289 unsigned NumDefElts = NumElts - NumUndefElts; 2290 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2291 2292 // Don't perform this optimization when optimizing for size, since 2293 // materializing elements and inserting them tends to cause code bloat. 2294 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2295 ((MostCommonCount > DominantValueCountThreshold) || 2296 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2297 // Start by splatting the most common element. 2298 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2299 2300 DenseSet<SDValue> Processed{DominantValue}; 2301 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2302 for (const auto &OpIdx : enumerate(Op->ops())) { 2303 const SDValue &V = OpIdx.value(); 2304 if (V.isUndef() || !Processed.insert(V).second) 2305 continue; 2306 if (ValueCounts[V] == 1) { 2307 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2308 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2309 } else { 2310 // Blend in all instances of this value using a VSELECT, using a 2311 // mask where each bit signals whether that element is the one 2312 // we're after. 2313 SmallVector<SDValue> Ops; 2314 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2315 return DAG.getConstant(V == V1, DL, XLenVT); 2316 }); 2317 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2318 DAG.getBuildVector(SelMaskTy, DL, Ops), 2319 DAG.getSplatBuildVector(VT, DL, V), Vec); 2320 } 2321 } 2322 2323 return Vec; 2324 } 2325 2326 return SDValue(); 2327 } 2328 2329 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2330 SDValue Lo, SDValue Hi, SDValue VL, 2331 SelectionDAG &DAG) { 2332 bool HasPassthru = Passthru && !Passthru.isUndef(); 2333 if (!HasPassthru && !Passthru) 2334 Passthru = DAG.getUNDEF(VT); 2335 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2336 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2337 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2338 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2339 // node in order to try and match RVV vector/scalar instructions. 2340 if ((LoC >> 31) == HiC) 2341 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2342 2343 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2344 // vmv.v.x whose EEW = 32 to lower it. 2345 auto *Const = dyn_cast<ConstantSDNode>(VL); 2346 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2347 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2348 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2349 // access the subtarget here now. 2350 auto InterVec = DAG.getNode( 2351 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2352 DAG.getRegister(RISCV::X0, MVT::i32)); 2353 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2354 } 2355 } 2356 2357 // Fall back to a stack store and stride x0 vector load. 2358 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2359 Hi, VL); 2360 } 2361 2362 // Called by type legalization to handle splat of i64 on RV32. 2363 // FIXME: We can optimize this when the type has sign or zero bits in one 2364 // of the halves. 2365 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2366 SDValue Scalar, SDValue VL, 2367 SelectionDAG &DAG) { 2368 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2369 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2370 DAG.getConstant(0, DL, MVT::i32)); 2371 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2372 DAG.getConstant(1, DL, MVT::i32)); 2373 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2374 } 2375 2376 // This function lowers a splat of a scalar operand Splat with the vector 2377 // length VL. It ensures the final sequence is type legal, which is useful when 2378 // lowering a splat after type legalization. 2379 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2380 MVT VT, SDLoc DL, SelectionDAG &DAG, 2381 const RISCVSubtarget &Subtarget) { 2382 bool HasPassthru = Passthru && !Passthru.isUndef(); 2383 if (!HasPassthru && !Passthru) 2384 Passthru = DAG.getUNDEF(VT); 2385 if (VT.isFloatingPoint()) { 2386 // If VL is 1, we could use vfmv.s.f. 2387 if (isOneConstant(VL)) 2388 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2389 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2390 } 2391 2392 MVT XLenVT = Subtarget.getXLenVT(); 2393 2394 // Simplest case is that the operand needs to be promoted to XLenVT. 2395 if (Scalar.getValueType().bitsLE(XLenVT)) { 2396 // If the operand is a constant, sign extend to increase our chances 2397 // of being able to use a .vi instruction. ANY_EXTEND would become a 2398 // a zero extend and the simm5 check in isel would fail. 2399 // FIXME: Should we ignore the upper bits in isel instead? 2400 unsigned ExtOpc = 2401 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2402 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2403 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2404 // If VL is 1 and the scalar value won't benefit from immediate, we could 2405 // use vmv.s.x. 2406 if (isOneConstant(VL) && 2407 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2408 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2409 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2410 } 2411 2412 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2413 "Unexpected scalar for splat lowering!"); 2414 2415 if (isOneConstant(VL) && isNullConstant(Scalar)) 2416 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2417 DAG.getConstant(0, DL, XLenVT), VL); 2418 2419 // Otherwise use the more complicated splatting algorithm. 2420 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2421 } 2422 2423 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2424 const RISCVSubtarget &Subtarget) { 2425 // We need to be able to widen elements to the next larger integer type. 2426 if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors()) 2427 return false; 2428 2429 int Size = Mask.size(); 2430 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2431 2432 int Srcs[] = {-1, -1}; 2433 for (int i = 0; i != Size; ++i) { 2434 // Ignore undef elements. 2435 if (Mask[i] < 0) 2436 continue; 2437 2438 // Is this an even or odd element. 2439 int Pol = i % 2; 2440 2441 // Ensure we consistently use the same source for this element polarity. 2442 int Src = Mask[i] / Size; 2443 if (Srcs[Pol] < 0) 2444 Srcs[Pol] = Src; 2445 if (Srcs[Pol] != Src) 2446 return false; 2447 2448 // Make sure the element within the source is appropriate for this element 2449 // in the destination. 2450 int Elt = Mask[i] % Size; 2451 if (Elt != i / 2) 2452 return false; 2453 } 2454 2455 // We need to find a source for each polarity and they can't be the same. 2456 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2457 return false; 2458 2459 // Swap the sources if the second source was in the even polarity. 2460 SwapSources = Srcs[0] > Srcs[1]; 2461 2462 return true; 2463 } 2464 2465 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2466 /// and then extract the original number of elements from the rotated result. 2467 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2468 /// returned rotation amount is for a rotate right, where elements move from 2469 /// higher elements to lower elements. \p LoSrc indicates the first source 2470 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2471 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2472 /// 0 or 1 if a rotation is found. 2473 /// 2474 /// NOTE: We talk about rotate to the right which matches how bit shift and 2475 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2476 /// and the table below write vectors with the lowest elements on the left. 2477 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2478 int Size = Mask.size(); 2479 2480 // We need to detect various ways of spelling a rotation: 2481 // [11, 12, 13, 14, 15, 0, 1, 2] 2482 // [-1, 12, 13, 14, -1, -1, 1, -1] 2483 // [-1, -1, -1, -1, -1, -1, 1, 2] 2484 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2485 // [-1, 4, 5, 6, -1, -1, 9, -1] 2486 // [-1, 4, 5, 6, -1, -1, -1, -1] 2487 int Rotation = 0; 2488 LoSrc = -1; 2489 HiSrc = -1; 2490 for (int i = 0; i != Size; ++i) { 2491 int M = Mask[i]; 2492 if (M < 0) 2493 continue; 2494 2495 // Determine where a rotate vector would have started. 2496 int StartIdx = i - (M % Size); 2497 // The identity rotation isn't interesting, stop. 2498 if (StartIdx == 0) 2499 return -1; 2500 2501 // If we found the tail of a vector the rotation must be the missing 2502 // front. If we found the head of a vector, it must be how much of the 2503 // head. 2504 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2505 2506 if (Rotation == 0) 2507 Rotation = CandidateRotation; 2508 else if (Rotation != CandidateRotation) 2509 // The rotations don't match, so we can't match this mask. 2510 return -1; 2511 2512 // Compute which value this mask is pointing at. 2513 int MaskSrc = M < Size ? 0 : 1; 2514 2515 // Compute which of the two target values this index should be assigned to. 2516 // This reflects whether the high elements are remaining or the low elemnts 2517 // are remaining. 2518 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2519 2520 // Either set up this value if we've not encountered it before, or check 2521 // that it remains consistent. 2522 if (TargetSrc < 0) 2523 TargetSrc = MaskSrc; 2524 else if (TargetSrc != MaskSrc) 2525 // This may be a rotation, but it pulls from the inputs in some 2526 // unsupported interleaving. 2527 return -1; 2528 } 2529 2530 // Check that we successfully analyzed the mask, and normalize the results. 2531 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2532 assert((LoSrc >= 0 || HiSrc >= 0) && 2533 "Failed to find a rotated input vector!"); 2534 2535 return Rotation; 2536 } 2537 2538 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2539 const RISCVSubtarget &Subtarget) { 2540 SDValue V1 = Op.getOperand(0); 2541 SDValue V2 = Op.getOperand(1); 2542 SDLoc DL(Op); 2543 MVT XLenVT = Subtarget.getXLenVT(); 2544 MVT VT = Op.getSimpleValueType(); 2545 unsigned NumElts = VT.getVectorNumElements(); 2546 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2547 2548 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2549 2550 SDValue TrueMask, VL; 2551 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2552 2553 if (SVN->isSplat()) { 2554 const int Lane = SVN->getSplatIndex(); 2555 if (Lane >= 0) { 2556 MVT SVT = VT.getVectorElementType(); 2557 2558 // Turn splatted vector load into a strided load with an X0 stride. 2559 SDValue V = V1; 2560 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2561 // with undef. 2562 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2563 int Offset = Lane; 2564 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2565 int OpElements = 2566 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2567 V = V.getOperand(Offset / OpElements); 2568 Offset %= OpElements; 2569 } 2570 2571 // We need to ensure the load isn't atomic or volatile. 2572 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2573 auto *Ld = cast<LoadSDNode>(V); 2574 Offset *= SVT.getStoreSize(); 2575 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2576 TypeSize::Fixed(Offset), DL); 2577 2578 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2579 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2580 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2581 SDValue IntID = 2582 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2583 SDValue Ops[] = {Ld->getChain(), 2584 IntID, 2585 DAG.getUNDEF(ContainerVT), 2586 NewAddr, 2587 DAG.getRegister(RISCV::X0, XLenVT), 2588 VL}; 2589 SDValue NewLoad = DAG.getMemIntrinsicNode( 2590 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2591 DAG.getMachineFunction().getMachineMemOperand( 2592 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2593 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2594 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2595 } 2596 2597 // Otherwise use a scalar load and splat. This will give the best 2598 // opportunity to fold a splat into the operation. ISel can turn it into 2599 // the x0 strided load if we aren't able to fold away the select. 2600 if (SVT.isFloatingPoint()) 2601 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2602 Ld->getPointerInfo().getWithOffset(Offset), 2603 Ld->getOriginalAlign(), 2604 Ld->getMemOperand()->getFlags()); 2605 else 2606 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2607 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2608 Ld->getOriginalAlign(), 2609 Ld->getMemOperand()->getFlags()); 2610 DAG.makeEquivalentMemoryOrdering(Ld, V); 2611 2612 unsigned Opc = 2613 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2614 SDValue Splat = 2615 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2616 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2617 } 2618 2619 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2620 assert(Lane < (int)NumElts && "Unexpected lane!"); 2621 SDValue Gather = 2622 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2623 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2624 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2625 } 2626 } 2627 2628 ArrayRef<int> Mask = SVN->getMask(); 2629 2630 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2631 // be undef which can be handled with a single SLIDEDOWN/UP. 2632 int LoSrc, HiSrc; 2633 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2634 if (Rotation > 0) { 2635 SDValue LoV, HiV; 2636 if (LoSrc >= 0) { 2637 LoV = LoSrc == 0 ? V1 : V2; 2638 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2639 } 2640 if (HiSrc >= 0) { 2641 HiV = HiSrc == 0 ? V1 : V2; 2642 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2643 } 2644 2645 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2646 // to slide LoV up by (NumElts - Rotation). 2647 unsigned InvRotate = NumElts - Rotation; 2648 2649 SDValue Res = DAG.getUNDEF(ContainerVT); 2650 if (HiV) { 2651 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2652 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2653 // causes multiple vsetvlis in some test cases such as lowering 2654 // reduce.mul 2655 SDValue DownVL = VL; 2656 if (LoV) 2657 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2658 Res = 2659 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2660 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2661 } 2662 if (LoV) 2663 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2664 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2665 2666 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2667 } 2668 2669 // Detect an interleave shuffle and lower to 2670 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2671 bool SwapSources; 2672 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2673 // Swap sources if needed. 2674 if (SwapSources) 2675 std::swap(V1, V2); 2676 2677 // Extract the lower half of the vectors. 2678 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2679 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2680 DAG.getConstant(0, DL, XLenVT)); 2681 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2682 DAG.getConstant(0, DL, XLenVT)); 2683 2684 // Double the element width and halve the number of elements in an int type. 2685 unsigned EltBits = VT.getScalarSizeInBits(); 2686 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2687 MVT WideIntVT = 2688 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2689 // Convert this to a scalable vector. We need to base this on the 2690 // destination size to ensure there's always a type with a smaller LMUL. 2691 MVT WideIntContainerVT = 2692 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2693 2694 // Convert sources to scalable vectors with the same element count as the 2695 // larger type. 2696 MVT HalfContainerVT = MVT::getVectorVT( 2697 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2698 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2699 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2700 2701 // Cast sources to integer. 2702 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2703 MVT IntHalfVT = 2704 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2705 V1 = DAG.getBitcast(IntHalfVT, V1); 2706 V2 = DAG.getBitcast(IntHalfVT, V2); 2707 2708 // Freeze V2 since we use it twice and we need to be sure that the add and 2709 // multiply see the same value. 2710 V2 = DAG.getFreeze(V2); 2711 2712 // Recreate TrueMask using the widened type's element count. 2713 MVT MaskVT = 2714 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2715 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2716 2717 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2718 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2719 V2, TrueMask, VL); 2720 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2721 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2722 DAG.getUNDEF(IntHalfVT), 2723 DAG.getAllOnesConstant(DL, XLenVT)); 2724 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2725 V2, Multiplier, TrueMask, VL); 2726 // Add the new copies to our previous addition giving us 2^eltbits copies of 2727 // V2. This is equivalent to shifting V2 left by eltbits. This should 2728 // combine with the vwmulu.vv above to form vwmaccu.vv. 2729 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2730 TrueMask, VL); 2731 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2732 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2733 // vector VT. 2734 ContainerVT = 2735 MVT::getVectorVT(VT.getVectorElementType(), 2736 WideIntContainerVT.getVectorElementCount() * 2); 2737 Add = DAG.getBitcast(ContainerVT, Add); 2738 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2739 } 2740 2741 // Detect shuffles which can be re-expressed as vector selects; these are 2742 // shuffles in which each element in the destination is taken from an element 2743 // at the corresponding index in either source vectors. 2744 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2745 int MaskIndex = MaskIdx.value(); 2746 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2747 }); 2748 2749 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2750 2751 SmallVector<SDValue> MaskVals; 2752 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2753 // merged with a second vrgather. 2754 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2755 2756 // By default we preserve the original operand order, and use a mask to 2757 // select LHS as true and RHS as false. However, since RVV vector selects may 2758 // feature splats but only on the LHS, we may choose to invert our mask and 2759 // instead select between RHS and LHS. 2760 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2761 bool InvertMask = IsSelect == SwapOps; 2762 2763 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2764 // half. 2765 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2766 2767 // Now construct the mask that will be used by the vselect or blended 2768 // vrgather operation. For vrgathers, construct the appropriate indices into 2769 // each vector. 2770 for (int MaskIndex : Mask) { 2771 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2772 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2773 if (!IsSelect) { 2774 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2775 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2776 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2777 : DAG.getUNDEF(XLenVT)); 2778 GatherIndicesRHS.push_back( 2779 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2780 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2781 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2782 ++LHSIndexCounts[MaskIndex]; 2783 if (!IsLHSOrUndefIndex) 2784 ++RHSIndexCounts[MaskIndex - NumElts]; 2785 } 2786 } 2787 2788 if (SwapOps) { 2789 std::swap(V1, V2); 2790 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2791 } 2792 2793 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2794 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2795 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2796 2797 if (IsSelect) 2798 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2799 2800 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2801 // On such a large vector we're unable to use i8 as the index type. 2802 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2803 // may involve vector splitting if we're already at LMUL=8, or our 2804 // user-supplied maximum fixed-length LMUL. 2805 return SDValue(); 2806 } 2807 2808 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2809 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2810 MVT IndexVT = VT.changeTypeToInteger(); 2811 // Since we can't introduce illegal index types at this stage, use i16 and 2812 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2813 // than XLenVT. 2814 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2815 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2816 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2817 } 2818 2819 MVT IndexContainerVT = 2820 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2821 2822 SDValue Gather; 2823 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2824 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2825 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2826 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2827 Subtarget); 2828 } else { 2829 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2830 // If only one index is used, we can use a "splat" vrgather. 2831 // TODO: We can splat the most-common index and fix-up any stragglers, if 2832 // that's beneficial. 2833 if (LHSIndexCounts.size() == 1) { 2834 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2835 Gather = 2836 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2837 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2838 } else { 2839 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2840 LHSIndices = 2841 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2842 2843 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2844 TrueMask, VL); 2845 } 2846 } 2847 2848 // If a second vector operand is used by this shuffle, blend it in with an 2849 // additional vrgather. 2850 if (!V2.isUndef()) { 2851 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2852 // If only one index is used, we can use a "splat" vrgather. 2853 // TODO: We can splat the most-common index and fix-up any stragglers, if 2854 // that's beneficial. 2855 if (RHSIndexCounts.size() == 1) { 2856 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2857 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2858 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2859 } else { 2860 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2861 RHSIndices = 2862 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2863 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2864 VL); 2865 } 2866 2867 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2868 SelectMask = 2869 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2870 2871 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2872 Gather, VL); 2873 } 2874 2875 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2876 } 2877 2878 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2879 // Support splats for any type. These should type legalize well. 2880 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2881 return true; 2882 2883 // Only support legal VTs for other shuffles for now. 2884 if (!isTypeLegal(VT)) 2885 return false; 2886 2887 MVT SVT = VT.getSimpleVT(); 2888 2889 bool SwapSources; 2890 int LoSrc, HiSrc; 2891 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2892 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2893 } 2894 2895 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2896 SDLoc DL, SelectionDAG &DAG, 2897 const RISCVSubtarget &Subtarget) { 2898 if (VT.isScalableVector()) 2899 return DAG.getFPExtendOrRound(Op, DL, VT); 2900 assert(VT.isFixedLengthVector() && 2901 "Unexpected value type for RVV FP extend/round lowering"); 2902 SDValue Mask, VL; 2903 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2904 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2905 ? RISCVISD::FP_EXTEND_VL 2906 : RISCVISD::FP_ROUND_VL; 2907 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2908 } 2909 2910 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2911 // the exponent. 2912 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2913 MVT VT = Op.getSimpleValueType(); 2914 unsigned EltSize = VT.getScalarSizeInBits(); 2915 SDValue Src = Op.getOperand(0); 2916 SDLoc DL(Op); 2917 2918 // We need a FP type that can represent the value. 2919 // TODO: Use f16 for i8 when possible? 2920 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2921 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2922 2923 // Legal types should have been checked in the RISCVTargetLowering 2924 // constructor. 2925 // TODO: Splitting may make sense in some cases. 2926 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2927 "Expected legal float type!"); 2928 2929 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2930 // The trailing zero count is equal to log2 of this single bit value. 2931 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2932 SDValue Neg = 2933 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2934 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2935 } 2936 2937 // We have a legal FP type, convert to it. 2938 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2939 // Bitcast to integer and shift the exponent to the LSB. 2940 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2941 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2942 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2943 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2944 DAG.getConstant(ShiftAmt, DL, IntVT)); 2945 // Truncate back to original type to allow vnsrl. 2946 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2947 // The exponent contains log2 of the value in biased form. 2948 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2949 2950 // For trailing zeros, we just need to subtract the bias. 2951 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2952 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2953 DAG.getConstant(ExponentBias, DL, VT)); 2954 2955 // For leading zeros, we need to remove the bias and convert from log2 to 2956 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2957 unsigned Adjust = ExponentBias + (EltSize - 1); 2958 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2959 } 2960 2961 // While RVV has alignment restrictions, we should always be able to load as a 2962 // legal equivalently-sized byte-typed vector instead. This method is 2963 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2964 // the load is already correctly-aligned, it returns SDValue(). 2965 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2966 SelectionDAG &DAG) const { 2967 auto *Load = cast<LoadSDNode>(Op); 2968 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2969 2970 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2971 Load->getMemoryVT(), 2972 *Load->getMemOperand())) 2973 return SDValue(); 2974 2975 SDLoc DL(Op); 2976 MVT VT = Op.getSimpleValueType(); 2977 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2978 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2979 "Unexpected unaligned RVV load type"); 2980 MVT NewVT = 2981 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2982 assert(NewVT.isValid() && 2983 "Expecting equally-sized RVV vector types to be legal"); 2984 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2985 Load->getPointerInfo(), Load->getOriginalAlign(), 2986 Load->getMemOperand()->getFlags()); 2987 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2988 } 2989 2990 // While RVV has alignment restrictions, we should always be able to store as a 2991 // legal equivalently-sized byte-typed vector instead. This method is 2992 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2993 // returns SDValue() if the store is already correctly aligned. 2994 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2995 SelectionDAG &DAG) const { 2996 auto *Store = cast<StoreSDNode>(Op); 2997 assert(Store && Store->getValue().getValueType().isVector() && 2998 "Expected vector store"); 2999 3000 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3001 Store->getMemoryVT(), 3002 *Store->getMemOperand())) 3003 return SDValue(); 3004 3005 SDLoc DL(Op); 3006 SDValue StoredVal = Store->getValue(); 3007 MVT VT = StoredVal.getSimpleValueType(); 3008 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3009 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3010 "Unexpected unaligned RVV store type"); 3011 MVT NewVT = 3012 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3013 assert(NewVT.isValid() && 3014 "Expecting equally-sized RVV vector types to be legal"); 3015 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3016 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3017 Store->getPointerInfo(), Store->getOriginalAlign(), 3018 Store->getMemOperand()->getFlags()); 3019 } 3020 3021 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3022 SelectionDAG &DAG) const { 3023 switch (Op.getOpcode()) { 3024 default: 3025 report_fatal_error("unimplemented operand"); 3026 case ISD::GlobalAddress: 3027 return lowerGlobalAddress(Op, DAG); 3028 case ISD::BlockAddress: 3029 return lowerBlockAddress(Op, DAG); 3030 case ISD::ConstantPool: 3031 return lowerConstantPool(Op, DAG); 3032 case ISD::JumpTable: 3033 return lowerJumpTable(Op, DAG); 3034 case ISD::GlobalTLSAddress: 3035 return lowerGlobalTLSAddress(Op, DAG); 3036 case ISD::SELECT: 3037 return lowerSELECT(Op, DAG); 3038 case ISD::BRCOND: 3039 return lowerBRCOND(Op, DAG); 3040 case ISD::VASTART: 3041 return lowerVASTART(Op, DAG); 3042 case ISD::FRAMEADDR: 3043 return lowerFRAMEADDR(Op, DAG); 3044 case ISD::RETURNADDR: 3045 return lowerRETURNADDR(Op, DAG); 3046 case ISD::SHL_PARTS: 3047 return lowerShiftLeftParts(Op, DAG); 3048 case ISD::SRA_PARTS: 3049 return lowerShiftRightParts(Op, DAG, true); 3050 case ISD::SRL_PARTS: 3051 return lowerShiftRightParts(Op, DAG, false); 3052 case ISD::BITCAST: { 3053 SDLoc DL(Op); 3054 EVT VT = Op.getValueType(); 3055 SDValue Op0 = Op.getOperand(0); 3056 EVT Op0VT = Op0.getValueType(); 3057 MVT XLenVT = Subtarget.getXLenVT(); 3058 if (VT.isFixedLengthVector()) { 3059 // We can handle fixed length vector bitcasts with a simple replacement 3060 // in isel. 3061 if (Op0VT.isFixedLengthVector()) 3062 return Op; 3063 // When bitcasting from scalar to fixed-length vector, insert the scalar 3064 // into a one-element vector of the result type, and perform a vector 3065 // bitcast. 3066 if (!Op0VT.isVector()) { 3067 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3068 if (!isTypeLegal(BVT)) 3069 return SDValue(); 3070 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3071 DAG.getUNDEF(BVT), Op0, 3072 DAG.getConstant(0, DL, XLenVT))); 3073 } 3074 return SDValue(); 3075 } 3076 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3077 // thus: bitcast the vector to a one-element vector type whose element type 3078 // is the same as the result type, and extract the first element. 3079 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3080 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3081 if (!isTypeLegal(BVT)) 3082 return SDValue(); 3083 SDValue BVec = DAG.getBitcast(BVT, Op0); 3084 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3085 DAG.getConstant(0, DL, XLenVT)); 3086 } 3087 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3088 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3089 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3090 return FPConv; 3091 } 3092 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3093 Subtarget.hasStdExtF()) { 3094 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3095 SDValue FPConv = 3096 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3097 return FPConv; 3098 } 3099 return SDValue(); 3100 } 3101 case ISD::INTRINSIC_WO_CHAIN: 3102 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3103 case ISD::INTRINSIC_W_CHAIN: 3104 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3105 case ISD::INTRINSIC_VOID: 3106 return LowerINTRINSIC_VOID(Op, DAG); 3107 case ISD::BSWAP: 3108 case ISD::BITREVERSE: { 3109 MVT VT = Op.getSimpleValueType(); 3110 SDLoc DL(Op); 3111 if (Subtarget.hasStdExtZbp()) { 3112 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3113 // Start with the maximum immediate value which is the bitwidth - 1. 3114 unsigned Imm = VT.getSizeInBits() - 1; 3115 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3116 if (Op.getOpcode() == ISD::BSWAP) 3117 Imm &= ~0x7U; 3118 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3119 DAG.getConstant(Imm, DL, VT)); 3120 } 3121 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3122 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3123 // Expand bitreverse to a bswap(rev8) followed by brev8. 3124 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3125 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3126 // as brev8 by an isel pattern. 3127 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3128 DAG.getConstant(7, DL, VT)); 3129 } 3130 case ISD::FSHL: 3131 case ISD::FSHR: { 3132 MVT VT = Op.getSimpleValueType(); 3133 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3134 SDLoc DL(Op); 3135 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3136 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3137 // accidentally setting the extra bit. 3138 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3139 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3140 DAG.getConstant(ShAmtWidth, DL, VT)); 3141 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3142 // instruction use different orders. fshl will return its first operand for 3143 // shift of zero, fshr will return its second operand. fsl and fsr both 3144 // return rs1 so the ISD nodes need to have different operand orders. 3145 // Shift amount is in rs2. 3146 SDValue Op0 = Op.getOperand(0); 3147 SDValue Op1 = Op.getOperand(1); 3148 unsigned Opc = RISCVISD::FSL; 3149 if (Op.getOpcode() == ISD::FSHR) { 3150 std::swap(Op0, Op1); 3151 Opc = RISCVISD::FSR; 3152 } 3153 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3154 } 3155 case ISD::TRUNCATE: { 3156 SDLoc DL(Op); 3157 MVT VT = Op.getSimpleValueType(); 3158 // Only custom-lower vector truncates 3159 if (!VT.isVector()) 3160 return Op; 3161 3162 // Truncates to mask types are handled differently 3163 if (VT.getVectorElementType() == MVT::i1) 3164 return lowerVectorMaskTrunc(Op, DAG); 3165 3166 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3167 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3168 // truncate by one power of two at a time. 3169 MVT DstEltVT = VT.getVectorElementType(); 3170 3171 SDValue Src = Op.getOperand(0); 3172 MVT SrcVT = Src.getSimpleValueType(); 3173 MVT SrcEltVT = SrcVT.getVectorElementType(); 3174 3175 assert(DstEltVT.bitsLT(SrcEltVT) && 3176 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3177 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3178 "Unexpected vector truncate lowering"); 3179 3180 MVT ContainerVT = SrcVT; 3181 if (SrcVT.isFixedLengthVector()) { 3182 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3183 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3184 } 3185 3186 SDValue Result = Src; 3187 SDValue Mask, VL; 3188 std::tie(Mask, VL) = 3189 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3190 LLVMContext &Context = *DAG.getContext(); 3191 const ElementCount Count = ContainerVT.getVectorElementCount(); 3192 do { 3193 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3194 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3195 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3196 Mask, VL); 3197 } while (SrcEltVT != DstEltVT); 3198 3199 if (SrcVT.isFixedLengthVector()) 3200 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3201 3202 return Result; 3203 } 3204 case ISD::ANY_EXTEND: 3205 case ISD::ZERO_EXTEND: 3206 if (Op.getOperand(0).getValueType().isVector() && 3207 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3208 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3209 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3210 case ISD::SIGN_EXTEND: 3211 if (Op.getOperand(0).getValueType().isVector() && 3212 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3213 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3214 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3215 case ISD::SPLAT_VECTOR_PARTS: 3216 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3217 case ISD::INSERT_VECTOR_ELT: 3218 return lowerINSERT_VECTOR_ELT(Op, DAG); 3219 case ISD::EXTRACT_VECTOR_ELT: 3220 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3221 case ISD::VSCALE: { 3222 MVT VT = Op.getSimpleValueType(); 3223 SDLoc DL(Op); 3224 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3225 // We define our scalable vector types for lmul=1 to use a 64 bit known 3226 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3227 // vscale as VLENB / 8. 3228 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3229 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3230 report_fatal_error("Support for VLEN==32 is incomplete."); 3231 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3232 // We assume VLENB is a multiple of 8. We manually choose the best shift 3233 // here because SimplifyDemandedBits isn't always able to simplify it. 3234 uint64_t Val = Op.getConstantOperandVal(0); 3235 if (isPowerOf2_64(Val)) { 3236 uint64_t Log2 = Log2_64(Val); 3237 if (Log2 < 3) 3238 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3239 DAG.getConstant(3 - Log2, DL, VT)); 3240 if (Log2 > 3) 3241 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3242 DAG.getConstant(Log2 - 3, DL, VT)); 3243 return VLENB; 3244 } 3245 // If the multiplier is a multiple of 8, scale it down to avoid needing 3246 // to shift the VLENB value. 3247 if ((Val % 8) == 0) 3248 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3249 DAG.getConstant(Val / 8, DL, VT)); 3250 } 3251 3252 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3253 DAG.getConstant(3, DL, VT)); 3254 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3255 } 3256 case ISD::FPOWI: { 3257 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3258 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3259 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3260 Op.getOperand(1).getValueType() == MVT::i32) { 3261 SDLoc DL(Op); 3262 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3263 SDValue Powi = 3264 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3265 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3266 DAG.getIntPtrConstant(0, DL)); 3267 } 3268 return SDValue(); 3269 } 3270 case ISD::FP_EXTEND: { 3271 // RVV can only do fp_extend to types double the size as the source. We 3272 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3273 // via f32. 3274 SDLoc DL(Op); 3275 MVT VT = Op.getSimpleValueType(); 3276 SDValue Src = Op.getOperand(0); 3277 MVT SrcVT = Src.getSimpleValueType(); 3278 3279 // Prepare any fixed-length vector operands. 3280 MVT ContainerVT = VT; 3281 if (SrcVT.isFixedLengthVector()) { 3282 ContainerVT = getContainerForFixedLengthVector(VT); 3283 MVT SrcContainerVT = 3284 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3285 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3286 } 3287 3288 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3289 SrcVT.getVectorElementType() != MVT::f16) { 3290 // For scalable vectors, we only need to close the gap between 3291 // vXf16->vXf64. 3292 if (!VT.isFixedLengthVector()) 3293 return Op; 3294 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3295 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3296 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3297 } 3298 3299 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3300 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3301 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3302 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3303 3304 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3305 DL, DAG, Subtarget); 3306 if (VT.isFixedLengthVector()) 3307 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3308 return Extend; 3309 } 3310 case ISD::FP_ROUND: { 3311 // RVV can only do fp_round to types half the size as the source. We 3312 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3313 // conversion instruction. 3314 SDLoc DL(Op); 3315 MVT VT = Op.getSimpleValueType(); 3316 SDValue Src = Op.getOperand(0); 3317 MVT SrcVT = Src.getSimpleValueType(); 3318 3319 // Prepare any fixed-length vector operands. 3320 MVT ContainerVT = VT; 3321 if (VT.isFixedLengthVector()) { 3322 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3323 ContainerVT = 3324 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3325 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3326 } 3327 3328 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3329 SrcVT.getVectorElementType() != MVT::f64) { 3330 // For scalable vectors, we only need to close the gap between 3331 // vXf64<->vXf16. 3332 if (!VT.isFixedLengthVector()) 3333 return Op; 3334 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3335 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3336 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3337 } 3338 3339 SDValue Mask, VL; 3340 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3341 3342 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3343 SDValue IntermediateRound = 3344 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3345 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3346 DL, DAG, Subtarget); 3347 3348 if (VT.isFixedLengthVector()) 3349 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3350 return Round; 3351 } 3352 case ISD::FP_TO_SINT: 3353 case ISD::FP_TO_UINT: 3354 case ISD::SINT_TO_FP: 3355 case ISD::UINT_TO_FP: { 3356 // RVV can only do fp<->int conversions to types half/double the size as 3357 // the source. We custom-lower any conversions that do two hops into 3358 // sequences. 3359 MVT VT = Op.getSimpleValueType(); 3360 if (!VT.isVector()) 3361 return Op; 3362 SDLoc DL(Op); 3363 SDValue Src = Op.getOperand(0); 3364 MVT EltVT = VT.getVectorElementType(); 3365 MVT SrcVT = Src.getSimpleValueType(); 3366 MVT SrcEltVT = SrcVT.getVectorElementType(); 3367 unsigned EltSize = EltVT.getSizeInBits(); 3368 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3369 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3370 "Unexpected vector element types"); 3371 3372 bool IsInt2FP = SrcEltVT.isInteger(); 3373 // Widening conversions 3374 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 3375 if (IsInt2FP) { 3376 // Do a regular integer sign/zero extension then convert to float. 3377 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 3378 VT.getVectorElementCount()); 3379 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3380 ? ISD::ZERO_EXTEND 3381 : ISD::SIGN_EXTEND; 3382 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3383 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3384 } 3385 // FP2Int 3386 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3387 // Do one doubling fp_extend then complete the operation by converting 3388 // to int. 3389 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3390 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3391 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3392 } 3393 3394 // Narrowing conversions 3395 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 3396 if (IsInt2FP) { 3397 // One narrowing int_to_fp, then an fp_round. 3398 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3399 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3400 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3401 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3402 } 3403 // FP2Int 3404 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3405 // representable by the integer, the result is poison. 3406 MVT IVecVT = 3407 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3408 VT.getVectorElementCount()); 3409 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3410 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3411 } 3412 3413 // Scalable vectors can exit here. Patterns will handle equally-sized 3414 // conversions halving/doubling ones. 3415 if (!VT.isFixedLengthVector()) 3416 return Op; 3417 3418 // For fixed-length vectors we lower to a custom "VL" node. 3419 unsigned RVVOpc = 0; 3420 switch (Op.getOpcode()) { 3421 default: 3422 llvm_unreachable("Impossible opcode"); 3423 case ISD::FP_TO_SINT: 3424 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3425 break; 3426 case ISD::FP_TO_UINT: 3427 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3428 break; 3429 case ISD::SINT_TO_FP: 3430 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3431 break; 3432 case ISD::UINT_TO_FP: 3433 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3434 break; 3435 } 3436 3437 MVT ContainerVT, SrcContainerVT; 3438 // Derive the reference container type from the larger vector type. 3439 if (SrcEltSize > EltSize) { 3440 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3441 ContainerVT = 3442 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3443 } else { 3444 ContainerVT = getContainerForFixedLengthVector(VT); 3445 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3446 } 3447 3448 SDValue Mask, VL; 3449 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3450 3451 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3452 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3453 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3454 } 3455 case ISD::FP_TO_SINT_SAT: 3456 case ISD::FP_TO_UINT_SAT: 3457 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3458 case ISD::FTRUNC: 3459 case ISD::FCEIL: 3460 case ISD::FFLOOR: 3461 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3462 case ISD::FROUND: 3463 return lowerFROUND(Op, DAG); 3464 case ISD::VECREDUCE_ADD: 3465 case ISD::VECREDUCE_UMAX: 3466 case ISD::VECREDUCE_SMAX: 3467 case ISD::VECREDUCE_UMIN: 3468 case ISD::VECREDUCE_SMIN: 3469 return lowerVECREDUCE(Op, DAG); 3470 case ISD::VECREDUCE_AND: 3471 case ISD::VECREDUCE_OR: 3472 case ISD::VECREDUCE_XOR: 3473 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3474 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3475 return lowerVECREDUCE(Op, DAG); 3476 case ISD::VECREDUCE_FADD: 3477 case ISD::VECREDUCE_SEQ_FADD: 3478 case ISD::VECREDUCE_FMIN: 3479 case ISD::VECREDUCE_FMAX: 3480 return lowerFPVECREDUCE(Op, DAG); 3481 case ISD::VP_REDUCE_ADD: 3482 case ISD::VP_REDUCE_UMAX: 3483 case ISD::VP_REDUCE_SMAX: 3484 case ISD::VP_REDUCE_UMIN: 3485 case ISD::VP_REDUCE_SMIN: 3486 case ISD::VP_REDUCE_FADD: 3487 case ISD::VP_REDUCE_SEQ_FADD: 3488 case ISD::VP_REDUCE_FMIN: 3489 case ISD::VP_REDUCE_FMAX: 3490 return lowerVPREDUCE(Op, DAG); 3491 case ISD::VP_REDUCE_AND: 3492 case ISD::VP_REDUCE_OR: 3493 case ISD::VP_REDUCE_XOR: 3494 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3495 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3496 return lowerVPREDUCE(Op, DAG); 3497 case ISD::INSERT_SUBVECTOR: 3498 return lowerINSERT_SUBVECTOR(Op, DAG); 3499 case ISD::EXTRACT_SUBVECTOR: 3500 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3501 case ISD::STEP_VECTOR: 3502 return lowerSTEP_VECTOR(Op, DAG); 3503 case ISD::VECTOR_REVERSE: 3504 return lowerVECTOR_REVERSE(Op, DAG); 3505 case ISD::BUILD_VECTOR: 3506 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3507 case ISD::SPLAT_VECTOR: 3508 if (Op.getValueType().getVectorElementType() == MVT::i1) 3509 return lowerVectorMaskSplat(Op, DAG); 3510 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3511 case ISD::VECTOR_SHUFFLE: 3512 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3513 case ISD::CONCAT_VECTORS: { 3514 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3515 // better than going through the stack, as the default expansion does. 3516 SDLoc DL(Op); 3517 MVT VT = Op.getSimpleValueType(); 3518 unsigned NumOpElts = 3519 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3520 SDValue Vec = DAG.getUNDEF(VT); 3521 for (const auto &OpIdx : enumerate(Op->ops())) { 3522 SDValue SubVec = OpIdx.value(); 3523 // Don't insert undef subvectors. 3524 if (SubVec.isUndef()) 3525 continue; 3526 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3527 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3528 } 3529 return Vec; 3530 } 3531 case ISD::LOAD: 3532 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3533 return V; 3534 if (Op.getValueType().isFixedLengthVector()) 3535 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3536 return Op; 3537 case ISD::STORE: 3538 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3539 return V; 3540 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3541 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3542 return Op; 3543 case ISD::MLOAD: 3544 case ISD::VP_LOAD: 3545 return lowerMaskedLoad(Op, DAG); 3546 case ISD::MSTORE: 3547 case ISD::VP_STORE: 3548 return lowerMaskedStore(Op, DAG); 3549 case ISD::SETCC: 3550 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3551 case ISD::ADD: 3552 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3553 case ISD::SUB: 3554 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3555 case ISD::MUL: 3556 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3557 case ISD::MULHS: 3558 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3559 case ISD::MULHU: 3560 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3561 case ISD::AND: 3562 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3563 RISCVISD::AND_VL); 3564 case ISD::OR: 3565 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3566 RISCVISD::OR_VL); 3567 case ISD::XOR: 3568 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3569 RISCVISD::XOR_VL); 3570 case ISD::SDIV: 3571 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3572 case ISD::SREM: 3573 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3574 case ISD::UDIV: 3575 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3576 case ISD::UREM: 3577 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3578 case ISD::SHL: 3579 case ISD::SRA: 3580 case ISD::SRL: 3581 if (Op.getSimpleValueType().isFixedLengthVector()) 3582 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3583 // This can be called for an i32 shift amount that needs to be promoted. 3584 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3585 "Unexpected custom legalisation"); 3586 return SDValue(); 3587 case ISD::SADDSAT: 3588 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3589 case ISD::UADDSAT: 3590 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3591 case ISD::SSUBSAT: 3592 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3593 case ISD::USUBSAT: 3594 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3595 case ISD::FADD: 3596 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3597 case ISD::FSUB: 3598 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3599 case ISD::FMUL: 3600 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3601 case ISD::FDIV: 3602 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3603 case ISD::FNEG: 3604 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3605 case ISD::FABS: 3606 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3607 case ISD::FSQRT: 3608 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3609 case ISD::FMA: 3610 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3611 case ISD::SMIN: 3612 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3613 case ISD::SMAX: 3614 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3615 case ISD::UMIN: 3616 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3617 case ISD::UMAX: 3618 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3619 case ISD::FMINNUM: 3620 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3621 case ISD::FMAXNUM: 3622 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3623 case ISD::ABS: 3624 return lowerABS(Op, DAG); 3625 case ISD::CTLZ_ZERO_UNDEF: 3626 case ISD::CTTZ_ZERO_UNDEF: 3627 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3628 case ISD::VSELECT: 3629 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3630 case ISD::FCOPYSIGN: 3631 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3632 case ISD::MGATHER: 3633 case ISD::VP_GATHER: 3634 return lowerMaskedGather(Op, DAG); 3635 case ISD::MSCATTER: 3636 case ISD::VP_SCATTER: 3637 return lowerMaskedScatter(Op, DAG); 3638 case ISD::FLT_ROUNDS_: 3639 return lowerGET_ROUNDING(Op, DAG); 3640 case ISD::SET_ROUNDING: 3641 return lowerSET_ROUNDING(Op, DAG); 3642 case ISD::VP_SELECT: 3643 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3644 case ISD::VP_MERGE: 3645 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3646 case ISD::VP_ADD: 3647 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3648 case ISD::VP_SUB: 3649 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3650 case ISD::VP_MUL: 3651 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3652 case ISD::VP_SDIV: 3653 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3654 case ISD::VP_UDIV: 3655 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3656 case ISD::VP_SREM: 3657 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3658 case ISD::VP_UREM: 3659 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3660 case ISD::VP_AND: 3661 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3662 case ISD::VP_OR: 3663 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3664 case ISD::VP_XOR: 3665 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3666 case ISD::VP_ASHR: 3667 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3668 case ISD::VP_LSHR: 3669 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3670 case ISD::VP_SHL: 3671 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3672 case ISD::VP_FADD: 3673 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3674 case ISD::VP_FSUB: 3675 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3676 case ISD::VP_FMUL: 3677 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3678 case ISD::VP_FDIV: 3679 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3680 case ISD::VP_FNEG: 3681 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3682 case ISD::VP_FMA: 3683 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3684 } 3685 } 3686 3687 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3688 SelectionDAG &DAG, unsigned Flags) { 3689 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3690 } 3691 3692 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3693 SelectionDAG &DAG, unsigned Flags) { 3694 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3695 Flags); 3696 } 3697 3698 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3699 SelectionDAG &DAG, unsigned Flags) { 3700 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3701 N->getOffset(), Flags); 3702 } 3703 3704 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3705 SelectionDAG &DAG, unsigned Flags) { 3706 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3707 } 3708 3709 template <class NodeTy> 3710 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3711 bool IsLocal) const { 3712 SDLoc DL(N); 3713 EVT Ty = getPointerTy(DAG.getDataLayout()); 3714 3715 if (isPositionIndependent()) { 3716 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3717 if (IsLocal) 3718 // Use PC-relative addressing to access the symbol. This generates the 3719 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3720 // %pcrel_lo(auipc)). 3721 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3722 3723 // Use PC-relative addressing to access the GOT for this symbol, then load 3724 // the address from the GOT. This generates the pattern (PseudoLA sym), 3725 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3726 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3727 } 3728 3729 switch (getTargetMachine().getCodeModel()) { 3730 default: 3731 report_fatal_error("Unsupported code model for lowering"); 3732 case CodeModel::Small: { 3733 // Generate a sequence for accessing addresses within the first 2 GiB of 3734 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3735 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3736 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3737 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3738 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3739 } 3740 case CodeModel::Medium: { 3741 // Generate a sequence for accessing addresses within any 2GiB range within 3742 // the address space. This generates the pattern (PseudoLLA sym), which 3743 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3744 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3745 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3746 } 3747 } 3748 } 3749 3750 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3751 SelectionDAG &DAG) const { 3752 SDLoc DL(Op); 3753 EVT Ty = Op.getValueType(); 3754 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3755 int64_t Offset = N->getOffset(); 3756 MVT XLenVT = Subtarget.getXLenVT(); 3757 3758 const GlobalValue *GV = N->getGlobal(); 3759 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3760 SDValue Addr = getAddr(N, DAG, IsLocal); 3761 3762 // In order to maximise the opportunity for common subexpression elimination, 3763 // emit a separate ADD node for the global address offset instead of folding 3764 // it in the global address node. Later peephole optimisations may choose to 3765 // fold it back in when profitable. 3766 if (Offset != 0) 3767 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3768 DAG.getConstant(Offset, DL, XLenVT)); 3769 return Addr; 3770 } 3771 3772 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3773 SelectionDAG &DAG) const { 3774 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3775 3776 return getAddr(N, DAG); 3777 } 3778 3779 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3780 SelectionDAG &DAG) const { 3781 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3782 3783 return getAddr(N, DAG); 3784 } 3785 3786 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3787 SelectionDAG &DAG) const { 3788 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3789 3790 return getAddr(N, DAG); 3791 } 3792 3793 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3794 SelectionDAG &DAG, 3795 bool UseGOT) const { 3796 SDLoc DL(N); 3797 EVT Ty = getPointerTy(DAG.getDataLayout()); 3798 const GlobalValue *GV = N->getGlobal(); 3799 MVT XLenVT = Subtarget.getXLenVT(); 3800 3801 if (UseGOT) { 3802 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3803 // load the address from the GOT and add the thread pointer. This generates 3804 // the pattern (PseudoLA_TLS_IE sym), which expands to 3805 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3806 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3807 SDValue Load = 3808 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3809 3810 // Add the thread pointer. 3811 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3812 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3813 } 3814 3815 // Generate a sequence for accessing the address relative to the thread 3816 // pointer, with the appropriate adjustment for the thread pointer offset. 3817 // This generates the pattern 3818 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3819 SDValue AddrHi = 3820 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3821 SDValue AddrAdd = 3822 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3823 SDValue AddrLo = 3824 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3825 3826 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3827 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3828 SDValue MNAdd = SDValue( 3829 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3830 0); 3831 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3832 } 3833 3834 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3835 SelectionDAG &DAG) const { 3836 SDLoc DL(N); 3837 EVT Ty = getPointerTy(DAG.getDataLayout()); 3838 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3839 const GlobalValue *GV = N->getGlobal(); 3840 3841 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3842 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3843 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3844 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3845 SDValue Load = 3846 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3847 3848 // Prepare argument list to generate call. 3849 ArgListTy Args; 3850 ArgListEntry Entry; 3851 Entry.Node = Load; 3852 Entry.Ty = CallTy; 3853 Args.push_back(Entry); 3854 3855 // Setup call to __tls_get_addr. 3856 TargetLowering::CallLoweringInfo CLI(DAG); 3857 CLI.setDebugLoc(DL) 3858 .setChain(DAG.getEntryNode()) 3859 .setLibCallee(CallingConv::C, CallTy, 3860 DAG.getExternalSymbol("__tls_get_addr", Ty), 3861 std::move(Args)); 3862 3863 return LowerCallTo(CLI).first; 3864 } 3865 3866 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3867 SelectionDAG &DAG) const { 3868 SDLoc DL(Op); 3869 EVT Ty = Op.getValueType(); 3870 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3871 int64_t Offset = N->getOffset(); 3872 MVT XLenVT = Subtarget.getXLenVT(); 3873 3874 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3875 3876 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3877 CallingConv::GHC) 3878 report_fatal_error("In GHC calling convention TLS is not supported"); 3879 3880 SDValue Addr; 3881 switch (Model) { 3882 case TLSModel::LocalExec: 3883 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3884 break; 3885 case TLSModel::InitialExec: 3886 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3887 break; 3888 case TLSModel::LocalDynamic: 3889 case TLSModel::GeneralDynamic: 3890 Addr = getDynamicTLSAddr(N, DAG); 3891 break; 3892 } 3893 3894 // In order to maximise the opportunity for common subexpression elimination, 3895 // emit a separate ADD node for the global address offset instead of folding 3896 // it in the global address node. Later peephole optimisations may choose to 3897 // fold it back in when profitable. 3898 if (Offset != 0) 3899 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3900 DAG.getConstant(Offset, DL, XLenVT)); 3901 return Addr; 3902 } 3903 3904 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3905 SDValue CondV = Op.getOperand(0); 3906 SDValue TrueV = Op.getOperand(1); 3907 SDValue FalseV = Op.getOperand(2); 3908 SDLoc DL(Op); 3909 MVT VT = Op.getSimpleValueType(); 3910 MVT XLenVT = Subtarget.getXLenVT(); 3911 3912 // Lower vector SELECTs to VSELECTs by splatting the condition. 3913 if (VT.isVector()) { 3914 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3915 SDValue CondSplat = VT.isScalableVector() 3916 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3917 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3918 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3919 } 3920 3921 // If the result type is XLenVT and CondV is the output of a SETCC node 3922 // which also operated on XLenVT inputs, then merge the SETCC node into the 3923 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3924 // compare+branch instructions. i.e.: 3925 // (select (setcc lhs, rhs, cc), truev, falsev) 3926 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3927 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3928 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3929 SDValue LHS = CondV.getOperand(0); 3930 SDValue RHS = CondV.getOperand(1); 3931 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3932 ISD::CondCode CCVal = CC->get(); 3933 3934 // Special case for a select of 2 constants that have a diffence of 1. 3935 // Normally this is done by DAGCombine, but if the select is introduced by 3936 // type legalization or op legalization, we miss it. Restricting to SETLT 3937 // case for now because that is what signed saturating add/sub need. 3938 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3939 // but we would probably want to swap the true/false values if the condition 3940 // is SETGE/SETLE to avoid an XORI. 3941 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3942 CCVal == ISD::SETLT) { 3943 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3944 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3945 if (TrueVal - 1 == FalseVal) 3946 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3947 if (TrueVal + 1 == FalseVal) 3948 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3949 } 3950 3951 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3952 3953 SDValue TargetCC = DAG.getCondCode(CCVal); 3954 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3955 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3956 } 3957 3958 // Otherwise: 3959 // (select condv, truev, falsev) 3960 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3961 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3962 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3963 3964 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3965 3966 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3967 } 3968 3969 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3970 SDValue CondV = Op.getOperand(1); 3971 SDLoc DL(Op); 3972 MVT XLenVT = Subtarget.getXLenVT(); 3973 3974 if (CondV.getOpcode() == ISD::SETCC && 3975 CondV.getOperand(0).getValueType() == XLenVT) { 3976 SDValue LHS = CondV.getOperand(0); 3977 SDValue RHS = CondV.getOperand(1); 3978 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3979 3980 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3981 3982 SDValue TargetCC = DAG.getCondCode(CCVal); 3983 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3984 LHS, RHS, TargetCC, Op.getOperand(2)); 3985 } 3986 3987 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3988 CondV, DAG.getConstant(0, DL, XLenVT), 3989 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3990 } 3991 3992 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3993 MachineFunction &MF = DAG.getMachineFunction(); 3994 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3995 3996 SDLoc DL(Op); 3997 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3998 getPointerTy(MF.getDataLayout())); 3999 4000 // vastart just stores the address of the VarArgsFrameIndex slot into the 4001 // memory location argument. 4002 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4003 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 4004 MachinePointerInfo(SV)); 4005 } 4006 4007 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 4008 SelectionDAG &DAG) const { 4009 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4010 MachineFunction &MF = DAG.getMachineFunction(); 4011 MachineFrameInfo &MFI = MF.getFrameInfo(); 4012 MFI.setFrameAddressIsTaken(true); 4013 Register FrameReg = RI.getFrameRegister(MF); 4014 int XLenInBytes = Subtarget.getXLen() / 8; 4015 4016 EVT VT = Op.getValueType(); 4017 SDLoc DL(Op); 4018 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 4019 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4020 while (Depth--) { 4021 int Offset = -(XLenInBytes * 2); 4022 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 4023 DAG.getIntPtrConstant(Offset, DL)); 4024 FrameAddr = 4025 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 4026 } 4027 return FrameAddr; 4028 } 4029 4030 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 4031 SelectionDAG &DAG) const { 4032 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4033 MachineFunction &MF = DAG.getMachineFunction(); 4034 MachineFrameInfo &MFI = MF.getFrameInfo(); 4035 MFI.setReturnAddressIsTaken(true); 4036 MVT XLenVT = Subtarget.getXLenVT(); 4037 int XLenInBytes = Subtarget.getXLen() / 8; 4038 4039 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4040 return SDValue(); 4041 4042 EVT VT = Op.getValueType(); 4043 SDLoc DL(Op); 4044 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4045 if (Depth) { 4046 int Off = -XLenInBytes; 4047 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 4048 SDValue Offset = DAG.getConstant(Off, DL, VT); 4049 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4050 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4051 MachinePointerInfo()); 4052 } 4053 4054 // Return the value of the return address register, marking it an implicit 4055 // live-in. 4056 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 4057 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 4058 } 4059 4060 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4061 SelectionDAG &DAG) const { 4062 SDLoc DL(Op); 4063 SDValue Lo = Op.getOperand(0); 4064 SDValue Hi = Op.getOperand(1); 4065 SDValue Shamt = Op.getOperand(2); 4066 EVT VT = Lo.getValueType(); 4067 4068 // if Shamt-XLEN < 0: // Shamt < XLEN 4069 // Lo = Lo << Shamt 4070 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4071 // else: 4072 // Lo = 0 4073 // Hi = Lo << (Shamt-XLEN) 4074 4075 SDValue Zero = DAG.getConstant(0, DL, VT); 4076 SDValue One = DAG.getConstant(1, DL, VT); 4077 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4078 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4079 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4080 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4081 4082 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4083 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4084 SDValue ShiftRightLo = 4085 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4086 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4087 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4088 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4089 4090 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4091 4092 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4093 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4094 4095 SDValue Parts[2] = {Lo, Hi}; 4096 return DAG.getMergeValues(Parts, DL); 4097 } 4098 4099 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4100 bool IsSRA) const { 4101 SDLoc DL(Op); 4102 SDValue Lo = Op.getOperand(0); 4103 SDValue Hi = Op.getOperand(1); 4104 SDValue Shamt = Op.getOperand(2); 4105 EVT VT = Lo.getValueType(); 4106 4107 // SRA expansion: 4108 // if Shamt-XLEN < 0: // Shamt < XLEN 4109 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4110 // Hi = Hi >>s Shamt 4111 // else: 4112 // Lo = Hi >>s (Shamt-XLEN); 4113 // Hi = Hi >>s (XLEN-1) 4114 // 4115 // SRL expansion: 4116 // if Shamt-XLEN < 0: // Shamt < XLEN 4117 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4118 // Hi = Hi >>u Shamt 4119 // else: 4120 // Lo = Hi >>u (Shamt-XLEN); 4121 // Hi = 0; 4122 4123 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4124 4125 SDValue Zero = DAG.getConstant(0, DL, VT); 4126 SDValue One = DAG.getConstant(1, DL, VT); 4127 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4128 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4129 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4130 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4131 4132 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4133 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4134 SDValue ShiftLeftHi = 4135 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4136 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4137 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4138 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4139 SDValue HiFalse = 4140 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4141 4142 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4143 4144 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4145 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4146 4147 SDValue Parts[2] = {Lo, Hi}; 4148 return DAG.getMergeValues(Parts, DL); 4149 } 4150 4151 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4152 // legal equivalently-sized i8 type, so we can use that as a go-between. 4153 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4154 SelectionDAG &DAG) const { 4155 SDLoc DL(Op); 4156 MVT VT = Op.getSimpleValueType(); 4157 SDValue SplatVal = Op.getOperand(0); 4158 // All-zeros or all-ones splats are handled specially. 4159 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4160 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4161 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4162 } 4163 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4164 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4165 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4166 } 4167 MVT XLenVT = Subtarget.getXLenVT(); 4168 assert(SplatVal.getValueType() == XLenVT && 4169 "Unexpected type for i1 splat value"); 4170 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4171 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4172 DAG.getConstant(1, DL, XLenVT)); 4173 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4174 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4175 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4176 } 4177 4178 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4179 // illegal (currently only vXi64 RV32). 4180 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4181 // them to VMV_V_X_VL. 4182 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4183 SelectionDAG &DAG) const { 4184 SDLoc DL(Op); 4185 MVT VecVT = Op.getSimpleValueType(); 4186 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4187 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4188 4189 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4190 SDValue Lo = Op.getOperand(0); 4191 SDValue Hi = Op.getOperand(1); 4192 4193 if (VecVT.isFixedLengthVector()) { 4194 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4195 SDLoc DL(Op); 4196 SDValue Mask, VL; 4197 std::tie(Mask, VL) = 4198 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4199 4200 SDValue Res = 4201 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4202 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4203 } 4204 4205 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4206 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4207 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4208 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4209 // node in order to try and match RVV vector/scalar instructions. 4210 if ((LoC >> 31) == HiC) 4211 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4212 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4213 } 4214 4215 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4216 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4217 isa<ConstantSDNode>(Hi.getOperand(1)) && 4218 Hi.getConstantOperandVal(1) == 31) 4219 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4220 DAG.getRegister(RISCV::X0, MVT::i32)); 4221 4222 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4223 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4224 DAG.getUNDEF(VecVT), Lo, Hi, 4225 DAG.getRegister(RISCV::X0, MVT::i32)); 4226 } 4227 4228 // Custom-lower extensions from mask vectors by using a vselect either with 1 4229 // for zero/any-extension or -1 for sign-extension: 4230 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4231 // Note that any-extension is lowered identically to zero-extension. 4232 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4233 int64_t ExtTrueVal) const { 4234 SDLoc DL(Op); 4235 MVT VecVT = Op.getSimpleValueType(); 4236 SDValue Src = Op.getOperand(0); 4237 // Only custom-lower extensions from mask types 4238 assert(Src.getValueType().isVector() && 4239 Src.getValueType().getVectorElementType() == MVT::i1); 4240 4241 MVT XLenVT = Subtarget.getXLenVT(); 4242 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4243 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4244 4245 if (VecVT.isScalableVector()) { 4246 // Be careful not to introduce illegal scalar types at this stage, and be 4247 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 4248 // illegal and must be expanded. Since we know that the constants are 4249 // sign-extended 32-bit values, we use VMV_V_X_VL directly. 4250 bool IsRV32E64 = 4251 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 4252 4253 if (!IsRV32E64) { 4254 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 4255 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 4256 } else { 4257 SplatZero = 4258 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4259 SplatZero, DAG.getRegister(RISCV::X0, XLenVT)); 4260 SplatTrueVal = 4261 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4262 SplatTrueVal, DAG.getRegister(RISCV::X0, XLenVT)); 4263 } 4264 4265 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4266 } 4267 4268 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4269 MVT I1ContainerVT = 4270 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4271 4272 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4273 4274 SDValue Mask, VL; 4275 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4276 4277 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4278 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4279 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4280 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4281 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4282 SplatTrueVal, SplatZero, VL); 4283 4284 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4285 } 4286 4287 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4288 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4289 MVT ExtVT = Op.getSimpleValueType(); 4290 // Only custom-lower extensions from fixed-length vector types. 4291 if (!ExtVT.isFixedLengthVector()) 4292 return Op; 4293 MVT VT = Op.getOperand(0).getSimpleValueType(); 4294 // Grab the canonical container type for the extended type. Infer the smaller 4295 // type from that to ensure the same number of vector elements, as we know 4296 // the LMUL will be sufficient to hold the smaller type. 4297 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4298 // Get the extended container type manually to ensure the same number of 4299 // vector elements between source and dest. 4300 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4301 ContainerExtVT.getVectorElementCount()); 4302 4303 SDValue Op1 = 4304 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4305 4306 SDLoc DL(Op); 4307 SDValue Mask, VL; 4308 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4309 4310 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4311 4312 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4313 } 4314 4315 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4316 // setcc operation: 4317 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4318 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 4319 SelectionDAG &DAG) const { 4320 SDLoc DL(Op); 4321 EVT MaskVT = Op.getValueType(); 4322 // Only expect to custom-lower truncations to mask types 4323 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4324 "Unexpected type for vector mask lowering"); 4325 SDValue Src = Op.getOperand(0); 4326 MVT VecVT = Src.getSimpleValueType(); 4327 4328 // If this is a fixed vector, we need to convert it to a scalable vector. 4329 MVT ContainerVT = VecVT; 4330 if (VecVT.isFixedLengthVector()) { 4331 ContainerVT = getContainerForFixedLengthVector(VecVT); 4332 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4333 } 4334 4335 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4336 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4337 4338 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4339 DAG.getUNDEF(ContainerVT), SplatOne); 4340 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4341 DAG.getUNDEF(ContainerVT), SplatZero); 4342 4343 if (VecVT.isScalableVector()) { 4344 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 4345 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 4346 } 4347 4348 SDValue Mask, VL; 4349 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4350 4351 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4352 SDValue Trunc = 4353 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4354 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4355 DAG.getCondCode(ISD::SETNE), Mask, VL); 4356 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4357 } 4358 4359 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4360 // first position of a vector, and that vector is slid up to the insert index. 4361 // By limiting the active vector length to index+1 and merging with the 4362 // original vector (with an undisturbed tail policy for elements >= VL), we 4363 // achieve the desired result of leaving all elements untouched except the one 4364 // at VL-1, which is replaced with the desired value. 4365 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4366 SelectionDAG &DAG) const { 4367 SDLoc DL(Op); 4368 MVT VecVT = Op.getSimpleValueType(); 4369 SDValue Vec = Op.getOperand(0); 4370 SDValue Val = Op.getOperand(1); 4371 SDValue Idx = Op.getOperand(2); 4372 4373 if (VecVT.getVectorElementType() == MVT::i1) { 4374 // FIXME: For now we just promote to an i8 vector and insert into that, 4375 // but this is probably not optimal. 4376 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4377 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4378 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4379 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4380 } 4381 4382 MVT ContainerVT = VecVT; 4383 // If the operand is a fixed-length vector, convert to a scalable one. 4384 if (VecVT.isFixedLengthVector()) { 4385 ContainerVT = getContainerForFixedLengthVector(VecVT); 4386 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4387 } 4388 4389 MVT XLenVT = Subtarget.getXLenVT(); 4390 4391 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4392 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4393 // Even i64-element vectors on RV32 can be lowered without scalar 4394 // legalization if the most-significant 32 bits of the value are not affected 4395 // by the sign-extension of the lower 32 bits. 4396 // TODO: We could also catch sign extensions of a 32-bit value. 4397 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4398 const auto *CVal = cast<ConstantSDNode>(Val); 4399 if (isInt<32>(CVal->getSExtValue())) { 4400 IsLegalInsert = true; 4401 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4402 } 4403 } 4404 4405 SDValue Mask, VL; 4406 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4407 4408 SDValue ValInVec; 4409 4410 if (IsLegalInsert) { 4411 unsigned Opc = 4412 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4413 if (isNullConstant(Idx)) { 4414 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4415 if (!VecVT.isFixedLengthVector()) 4416 return Vec; 4417 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4418 } 4419 ValInVec = 4420 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4421 } else { 4422 // On RV32, i64-element vectors must be specially handled to place the 4423 // value at element 0, by using two vslide1up instructions in sequence on 4424 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4425 // this. 4426 SDValue One = DAG.getConstant(1, DL, XLenVT); 4427 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4428 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4429 MVT I32ContainerVT = 4430 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4431 SDValue I32Mask = 4432 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4433 // Limit the active VL to two. 4434 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4435 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4436 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4437 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4438 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4439 // First slide in the hi value, then the lo in underneath it. 4440 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4441 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4442 I32Mask, InsertI64VL); 4443 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4444 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4445 I32Mask, InsertI64VL); 4446 // Bitcast back to the right container type. 4447 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4448 } 4449 4450 // Now that the value is in a vector, slide it into position. 4451 SDValue InsertVL = 4452 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4453 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4454 ValInVec, Idx, Mask, InsertVL); 4455 if (!VecVT.isFixedLengthVector()) 4456 return Slideup; 4457 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4458 } 4459 4460 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4461 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4462 // types this is done using VMV_X_S to allow us to glean information about the 4463 // sign bits of the result. 4464 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4465 SelectionDAG &DAG) const { 4466 SDLoc DL(Op); 4467 SDValue Idx = Op.getOperand(1); 4468 SDValue Vec = Op.getOperand(0); 4469 EVT EltVT = Op.getValueType(); 4470 MVT VecVT = Vec.getSimpleValueType(); 4471 MVT XLenVT = Subtarget.getXLenVT(); 4472 4473 if (VecVT.getVectorElementType() == MVT::i1) { 4474 if (VecVT.isFixedLengthVector()) { 4475 unsigned NumElts = VecVT.getVectorNumElements(); 4476 if (NumElts >= 8) { 4477 MVT WideEltVT; 4478 unsigned WidenVecLen; 4479 SDValue ExtractElementIdx; 4480 SDValue ExtractBitIdx; 4481 unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors(); 4482 MVT LargestEltVT = MVT::getIntegerVT( 4483 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4484 if (NumElts <= LargestEltVT.getSizeInBits()) { 4485 assert(isPowerOf2_32(NumElts) && 4486 "the number of elements should be power of 2"); 4487 WideEltVT = MVT::getIntegerVT(NumElts); 4488 WidenVecLen = 1; 4489 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4490 ExtractBitIdx = Idx; 4491 } else { 4492 WideEltVT = LargestEltVT; 4493 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4494 // extract element index = index / element width 4495 ExtractElementIdx = DAG.getNode( 4496 ISD::SRL, DL, XLenVT, Idx, 4497 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4498 // mask bit index = index % element width 4499 ExtractBitIdx = DAG.getNode( 4500 ISD::AND, DL, XLenVT, Idx, 4501 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4502 } 4503 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4504 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4505 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4506 Vec, ExtractElementIdx); 4507 // Extract the bit from GPR. 4508 SDValue ShiftRight = 4509 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4510 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4511 DAG.getConstant(1, DL, XLenVT)); 4512 } 4513 } 4514 // Otherwise, promote to an i8 vector and extract from that. 4515 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4516 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4517 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4518 } 4519 4520 // If this is a fixed vector, we need to convert it to a scalable vector. 4521 MVT ContainerVT = VecVT; 4522 if (VecVT.isFixedLengthVector()) { 4523 ContainerVT = getContainerForFixedLengthVector(VecVT); 4524 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4525 } 4526 4527 // If the index is 0, the vector is already in the right position. 4528 if (!isNullConstant(Idx)) { 4529 // Use a VL of 1 to avoid processing more elements than we need. 4530 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4531 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4532 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4533 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4534 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4535 } 4536 4537 if (!EltVT.isInteger()) { 4538 // Floating-point extracts are handled in TableGen. 4539 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4540 DAG.getConstant(0, DL, XLenVT)); 4541 } 4542 4543 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4544 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4545 } 4546 4547 // Some RVV intrinsics may claim that they want an integer operand to be 4548 // promoted or expanded. 4549 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 4550 const RISCVSubtarget &Subtarget) { 4551 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4552 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4553 "Unexpected opcode"); 4554 4555 if (!Subtarget.hasVInstructions()) 4556 return SDValue(); 4557 4558 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4559 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4560 SDLoc DL(Op); 4561 4562 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4563 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4564 if (!II || !II->hasSplatOperand()) 4565 return SDValue(); 4566 4567 unsigned SplatOp = II->SplatOperand + 1 + HasChain; 4568 assert(SplatOp < Op.getNumOperands()); 4569 4570 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4571 SDValue &ScalarOp = Operands[SplatOp]; 4572 MVT OpVT = ScalarOp.getSimpleValueType(); 4573 MVT XLenVT = Subtarget.getXLenVT(); 4574 4575 // If this isn't a scalar, or its type is XLenVT we're done. 4576 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4577 return SDValue(); 4578 4579 // Simplest case is that the operand needs to be promoted to XLenVT. 4580 if (OpVT.bitsLT(XLenVT)) { 4581 // If the operand is a constant, sign extend to increase our chances 4582 // of being able to use a .vi instruction. ANY_EXTEND would become a 4583 // a zero extend and the simm5 check in isel would fail. 4584 // FIXME: Should we ignore the upper bits in isel instead? 4585 unsigned ExtOpc = 4586 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4587 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4588 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4589 } 4590 4591 // Use the previous operand to get the vXi64 VT. The result might be a mask 4592 // VT for compares. Using the previous operand assumes that the previous 4593 // operand will never have a smaller element size than a scalar operand and 4594 // that a widening operation never uses SEW=64. 4595 // NOTE: If this fails the below assert, we can probably just find the 4596 // element count from any operand or result and use it to construct the VT. 4597 assert(II->SplatOperand > 0 && "Unexpected splat operand!"); 4598 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4599 4600 // The more complex case is when the scalar is larger than XLenVT. 4601 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4602 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4603 4604 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4605 // on the instruction to sign-extend since SEW>XLEN. 4606 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4607 if (isInt<32>(CVal->getSExtValue())) { 4608 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4609 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4610 } 4611 } 4612 4613 // We need to convert the scalar to a splat vector. 4614 // FIXME: Can we implicitly truncate the scalar if it is known to 4615 // be sign extended? 4616 SDValue VL = getVLOperand(Op); 4617 assert(VL.getValueType() == XLenVT); 4618 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4619 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4620 } 4621 4622 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4623 SelectionDAG &DAG) const { 4624 unsigned IntNo = Op.getConstantOperandVal(0); 4625 SDLoc DL(Op); 4626 MVT XLenVT = Subtarget.getXLenVT(); 4627 4628 switch (IntNo) { 4629 default: 4630 break; // Don't custom lower most intrinsics. 4631 case Intrinsic::thread_pointer: { 4632 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4633 return DAG.getRegister(RISCV::X4, PtrVT); 4634 } 4635 case Intrinsic::riscv_orc_b: 4636 case Intrinsic::riscv_brev8: { 4637 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4638 unsigned Opc = 4639 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4640 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4641 DAG.getConstant(7, DL, XLenVT)); 4642 } 4643 case Intrinsic::riscv_grev: 4644 case Intrinsic::riscv_gorc: { 4645 unsigned Opc = 4646 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4647 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4648 } 4649 case Intrinsic::riscv_zip: 4650 case Intrinsic::riscv_unzip: { 4651 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4652 // For i32 the immdiate is 15. For i64 the immediate is 31. 4653 unsigned Opc = 4654 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4655 unsigned BitWidth = Op.getValueSizeInBits(); 4656 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4657 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4658 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4659 } 4660 case Intrinsic::riscv_shfl: 4661 case Intrinsic::riscv_unshfl: { 4662 unsigned Opc = 4663 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4664 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4665 } 4666 case Intrinsic::riscv_bcompress: 4667 case Intrinsic::riscv_bdecompress: { 4668 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4669 : RISCVISD::BDECOMPRESS; 4670 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4671 } 4672 case Intrinsic::riscv_bfp: 4673 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4674 Op.getOperand(2)); 4675 case Intrinsic::riscv_fsl: 4676 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4677 Op.getOperand(2), Op.getOperand(3)); 4678 case Intrinsic::riscv_fsr: 4679 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4680 Op.getOperand(2), Op.getOperand(3)); 4681 case Intrinsic::riscv_vmv_x_s: 4682 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4683 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4684 Op.getOperand(1)); 4685 case Intrinsic::riscv_vmv_v_x: 4686 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4687 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4688 Subtarget); 4689 case Intrinsic::riscv_vfmv_v_f: 4690 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4691 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4692 case Intrinsic::riscv_vmv_s_x: { 4693 SDValue Scalar = Op.getOperand(2); 4694 4695 if (Scalar.getValueType().bitsLE(XLenVT)) { 4696 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4697 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4698 Op.getOperand(1), Scalar, Op.getOperand(3)); 4699 } 4700 4701 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4702 4703 // This is an i64 value that lives in two scalar registers. We have to 4704 // insert this in a convoluted way. First we build vXi64 splat containing 4705 // the/ two values that we assemble using some bit math. Next we'll use 4706 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4707 // to merge element 0 from our splat into the source vector. 4708 // FIXME: This is probably not the best way to do this, but it is 4709 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4710 // point. 4711 // sw lo, (a0) 4712 // sw hi, 4(a0) 4713 // vlse vX, (a0) 4714 // 4715 // vid.v vVid 4716 // vmseq.vx mMask, vVid, 0 4717 // vmerge.vvm vDest, vSrc, vVal, mMask 4718 MVT VT = Op.getSimpleValueType(); 4719 SDValue Vec = Op.getOperand(1); 4720 SDValue VL = getVLOperand(Op); 4721 4722 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4723 if (Op.getOperand(1).isUndef()) 4724 return SplattedVal; 4725 SDValue SplattedIdx = 4726 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4727 DAG.getConstant(0, DL, MVT::i32), VL); 4728 4729 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4730 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4731 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4732 SDValue SelectCond = 4733 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4734 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4735 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4736 Vec, VL); 4737 } 4738 case Intrinsic::riscv_vslide1up: 4739 case Intrinsic::riscv_vslide1down: 4740 case Intrinsic::riscv_vslide1up_mask: 4741 case Intrinsic::riscv_vslide1down_mask: { 4742 // We need to special case these when the scalar is larger than XLen. 4743 unsigned NumOps = Op.getNumOperands(); 4744 bool IsMasked = NumOps == 7; 4745 SDValue Scalar = Op.getOperand(3); 4746 if (Scalar.getValueType().bitsLE(XLenVT)) 4747 break; 4748 4749 // Splatting a sign extended constant is fine. 4750 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4751 if (isInt<32>(CVal->getSExtValue())) 4752 break; 4753 4754 MVT VT = Op.getSimpleValueType(); 4755 assert(VT.getVectorElementType() == MVT::i64 && 4756 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4757 4758 // Convert the vector source to the equivalent nxvXi32 vector. 4759 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4760 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(2)); 4761 4762 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4763 DAG.getConstant(0, DL, XLenVT)); 4764 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4765 DAG.getConstant(1, DL, XLenVT)); 4766 4767 // Double the VL since we halved SEW. 4768 SDValue VL = getVLOperand(Op); 4769 SDValue I32VL = 4770 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4771 4772 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4773 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4774 4775 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4776 // instructions. 4777 SDValue Passthru = DAG.getBitcast(I32VT, Op.getOperand(1)); 4778 if (!IsMasked) { 4779 if (IntNo == Intrinsic::riscv_vslide1up) { 4780 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4781 ScalarHi, I32Mask, I32VL); 4782 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4783 ScalarLo, I32Mask, I32VL); 4784 } else { 4785 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4786 ScalarLo, I32Mask, I32VL); 4787 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4788 ScalarHi, I32Mask, I32VL); 4789 } 4790 } else { 4791 // TODO Those VSLIDE1 could be TAMA because we use vmerge to select 4792 // maskedoff 4793 SDValue Undef = DAG.getUNDEF(I32VT); 4794 if (IntNo == Intrinsic::riscv_vslide1up_mask) { 4795 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec, 4796 ScalarHi, I32Mask, I32VL); 4797 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec, 4798 ScalarLo, I32Mask, I32VL); 4799 } else { 4800 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec, 4801 ScalarLo, I32Mask, I32VL); 4802 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec, 4803 ScalarHi, I32Mask, I32VL); 4804 } 4805 } 4806 4807 // Convert back to nxvXi64. 4808 Vec = DAG.getBitcast(VT, Vec); 4809 4810 if (!IsMasked) 4811 return Vec; 4812 // Apply mask after the operation. 4813 SDValue Mask = Op.getOperand(NumOps - 3); 4814 SDValue MaskedOff = Op.getOperand(1); 4815 // Assume Policy operand is the last operand. 4816 uint64_t Policy = Op.getConstantOperandVal(NumOps - 1); 4817 // We don't need to select maskedoff if it's undef. 4818 if (MaskedOff.isUndef()) 4819 return Vec; 4820 // TAMU 4821 if (Policy == RISCVII::TAIL_AGNOSTIC) 4822 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4823 VL); 4824 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4825 // It's fine because vmerge does not care mask policy. 4826 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4827 } 4828 } 4829 4830 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4831 } 4832 4833 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4834 SelectionDAG &DAG) const { 4835 unsigned IntNo = Op.getConstantOperandVal(1); 4836 switch (IntNo) { 4837 default: 4838 break; 4839 case Intrinsic::riscv_masked_strided_load: { 4840 SDLoc DL(Op); 4841 MVT XLenVT = Subtarget.getXLenVT(); 4842 4843 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4844 // the selection of the masked intrinsics doesn't do this for us. 4845 SDValue Mask = Op.getOperand(5); 4846 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4847 4848 MVT VT = Op->getSimpleValueType(0); 4849 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4850 4851 SDValue PassThru = Op.getOperand(2); 4852 if (!IsUnmasked) { 4853 MVT MaskVT = 4854 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4855 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4856 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4857 } 4858 4859 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4860 4861 SDValue IntID = DAG.getTargetConstant( 4862 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4863 XLenVT); 4864 4865 auto *Load = cast<MemIntrinsicSDNode>(Op); 4866 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4867 if (IsUnmasked) 4868 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4869 else 4870 Ops.push_back(PassThru); 4871 Ops.push_back(Op.getOperand(3)); // Ptr 4872 Ops.push_back(Op.getOperand(4)); // Stride 4873 if (!IsUnmasked) 4874 Ops.push_back(Mask); 4875 Ops.push_back(VL); 4876 if (!IsUnmasked) { 4877 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4878 Ops.push_back(Policy); 4879 } 4880 4881 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4882 SDValue Result = 4883 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4884 Load->getMemoryVT(), Load->getMemOperand()); 4885 SDValue Chain = Result.getValue(1); 4886 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4887 return DAG.getMergeValues({Result, Chain}, DL); 4888 } 4889 } 4890 4891 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4892 } 4893 4894 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4895 SelectionDAG &DAG) const { 4896 unsigned IntNo = Op.getConstantOperandVal(1); 4897 switch (IntNo) { 4898 default: 4899 break; 4900 case Intrinsic::riscv_masked_strided_store: { 4901 SDLoc DL(Op); 4902 MVT XLenVT = Subtarget.getXLenVT(); 4903 4904 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4905 // the selection of the masked intrinsics doesn't do this for us. 4906 SDValue Mask = Op.getOperand(5); 4907 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4908 4909 SDValue Val = Op.getOperand(2); 4910 MVT VT = Val.getSimpleValueType(); 4911 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4912 4913 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4914 if (!IsUnmasked) { 4915 MVT MaskVT = 4916 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4917 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4918 } 4919 4920 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4921 4922 SDValue IntID = DAG.getTargetConstant( 4923 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4924 XLenVT); 4925 4926 auto *Store = cast<MemIntrinsicSDNode>(Op); 4927 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4928 Ops.push_back(Val); 4929 Ops.push_back(Op.getOperand(3)); // Ptr 4930 Ops.push_back(Op.getOperand(4)); // Stride 4931 if (!IsUnmasked) 4932 Ops.push_back(Mask); 4933 Ops.push_back(VL); 4934 4935 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4936 Ops, Store->getMemoryVT(), 4937 Store->getMemOperand()); 4938 } 4939 } 4940 4941 return SDValue(); 4942 } 4943 4944 static MVT getLMUL1VT(MVT VT) { 4945 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4946 "Unexpected vector MVT"); 4947 return MVT::getScalableVectorVT( 4948 VT.getVectorElementType(), 4949 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4950 } 4951 4952 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4953 switch (ISDOpcode) { 4954 default: 4955 llvm_unreachable("Unhandled reduction"); 4956 case ISD::VECREDUCE_ADD: 4957 return RISCVISD::VECREDUCE_ADD_VL; 4958 case ISD::VECREDUCE_UMAX: 4959 return RISCVISD::VECREDUCE_UMAX_VL; 4960 case ISD::VECREDUCE_SMAX: 4961 return RISCVISD::VECREDUCE_SMAX_VL; 4962 case ISD::VECREDUCE_UMIN: 4963 return RISCVISD::VECREDUCE_UMIN_VL; 4964 case ISD::VECREDUCE_SMIN: 4965 return RISCVISD::VECREDUCE_SMIN_VL; 4966 case ISD::VECREDUCE_AND: 4967 return RISCVISD::VECREDUCE_AND_VL; 4968 case ISD::VECREDUCE_OR: 4969 return RISCVISD::VECREDUCE_OR_VL; 4970 case ISD::VECREDUCE_XOR: 4971 return RISCVISD::VECREDUCE_XOR_VL; 4972 } 4973 } 4974 4975 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4976 SelectionDAG &DAG, 4977 bool IsVP) const { 4978 SDLoc DL(Op); 4979 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4980 MVT VecVT = Vec.getSimpleValueType(); 4981 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4982 Op.getOpcode() == ISD::VECREDUCE_OR || 4983 Op.getOpcode() == ISD::VECREDUCE_XOR || 4984 Op.getOpcode() == ISD::VP_REDUCE_AND || 4985 Op.getOpcode() == ISD::VP_REDUCE_OR || 4986 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4987 "Unexpected reduction lowering"); 4988 4989 MVT XLenVT = Subtarget.getXLenVT(); 4990 assert(Op.getValueType() == XLenVT && 4991 "Expected reduction output to be legalized to XLenVT"); 4992 4993 MVT ContainerVT = VecVT; 4994 if (VecVT.isFixedLengthVector()) { 4995 ContainerVT = getContainerForFixedLengthVector(VecVT); 4996 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4997 } 4998 4999 SDValue Mask, VL; 5000 if (IsVP) { 5001 Mask = Op.getOperand(2); 5002 VL = Op.getOperand(3); 5003 } else { 5004 std::tie(Mask, VL) = 5005 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5006 } 5007 5008 unsigned BaseOpc; 5009 ISD::CondCode CC; 5010 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5011 5012 switch (Op.getOpcode()) { 5013 default: 5014 llvm_unreachable("Unhandled reduction"); 5015 case ISD::VECREDUCE_AND: 5016 case ISD::VP_REDUCE_AND: { 5017 // vcpop ~x == 0 5018 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5019 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5020 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5021 CC = ISD::SETEQ; 5022 BaseOpc = ISD::AND; 5023 break; 5024 } 5025 case ISD::VECREDUCE_OR: 5026 case ISD::VP_REDUCE_OR: 5027 // vcpop x != 0 5028 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5029 CC = ISD::SETNE; 5030 BaseOpc = ISD::OR; 5031 break; 5032 case ISD::VECREDUCE_XOR: 5033 case ISD::VP_REDUCE_XOR: { 5034 // ((vcpop x) & 1) != 0 5035 SDValue One = DAG.getConstant(1, DL, XLenVT); 5036 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5037 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5038 CC = ISD::SETNE; 5039 BaseOpc = ISD::XOR; 5040 break; 5041 } 5042 } 5043 5044 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5045 5046 if (!IsVP) 5047 return SetCC; 5048 5049 // Now include the start value in the operation. 5050 // Note that we must return the start value when no elements are operated 5051 // upon. The vcpop instructions we've emitted in each case above will return 5052 // 0 for an inactive vector, and so we've already received the neutral value: 5053 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5054 // can simply include the start value. 5055 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5056 } 5057 5058 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5059 SelectionDAG &DAG) const { 5060 SDLoc DL(Op); 5061 SDValue Vec = Op.getOperand(0); 5062 EVT VecEVT = Vec.getValueType(); 5063 5064 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5065 5066 // Due to ordering in legalize types we may have a vector type that needs to 5067 // be split. Do that manually so we can get down to a legal type. 5068 while (getTypeAction(*DAG.getContext(), VecEVT) == 5069 TargetLowering::TypeSplitVector) { 5070 SDValue Lo, Hi; 5071 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5072 VecEVT = Lo.getValueType(); 5073 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5074 } 5075 5076 // TODO: The type may need to be widened rather than split. Or widened before 5077 // it can be split. 5078 if (!isTypeLegal(VecEVT)) 5079 return SDValue(); 5080 5081 MVT VecVT = VecEVT.getSimpleVT(); 5082 MVT VecEltVT = VecVT.getVectorElementType(); 5083 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5084 5085 MVT ContainerVT = VecVT; 5086 if (VecVT.isFixedLengthVector()) { 5087 ContainerVT = getContainerForFixedLengthVector(VecVT); 5088 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5089 } 5090 5091 MVT M1VT = getLMUL1VT(ContainerVT); 5092 MVT XLenVT = Subtarget.getXLenVT(); 5093 5094 SDValue Mask, VL; 5095 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5096 5097 SDValue NeutralElem = 5098 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5099 SDValue IdentitySplat = 5100 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5101 M1VT, DL, DAG, Subtarget); 5102 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5103 IdentitySplat, Mask, VL); 5104 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5105 DAG.getConstant(0, DL, XLenVT)); 5106 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5107 } 5108 5109 // Given a reduction op, this function returns the matching reduction opcode, 5110 // the vector SDValue and the scalar SDValue required to lower this to a 5111 // RISCVISD node. 5112 static std::tuple<unsigned, SDValue, SDValue> 5113 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5114 SDLoc DL(Op); 5115 auto Flags = Op->getFlags(); 5116 unsigned Opcode = Op.getOpcode(); 5117 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5118 switch (Opcode) { 5119 default: 5120 llvm_unreachable("Unhandled reduction"); 5121 case ISD::VECREDUCE_FADD: { 5122 // Use positive zero if we can. It is cheaper to materialize. 5123 SDValue Zero = 5124 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5125 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5126 } 5127 case ISD::VECREDUCE_SEQ_FADD: 5128 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5129 Op.getOperand(0)); 5130 case ISD::VECREDUCE_FMIN: 5131 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5132 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5133 case ISD::VECREDUCE_FMAX: 5134 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5135 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5136 } 5137 } 5138 5139 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5140 SelectionDAG &DAG) const { 5141 SDLoc DL(Op); 5142 MVT VecEltVT = Op.getSimpleValueType(); 5143 5144 unsigned RVVOpcode; 5145 SDValue VectorVal, ScalarVal; 5146 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5147 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5148 MVT VecVT = VectorVal.getSimpleValueType(); 5149 5150 MVT ContainerVT = VecVT; 5151 if (VecVT.isFixedLengthVector()) { 5152 ContainerVT = getContainerForFixedLengthVector(VecVT); 5153 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5154 } 5155 5156 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5157 MVT XLenVT = Subtarget.getXLenVT(); 5158 5159 SDValue Mask, VL; 5160 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5161 5162 SDValue ScalarSplat = 5163 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5164 M1VT, DL, DAG, Subtarget); 5165 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5166 VectorVal, ScalarSplat, Mask, VL); 5167 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5168 DAG.getConstant(0, DL, XLenVT)); 5169 } 5170 5171 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5172 switch (ISDOpcode) { 5173 default: 5174 llvm_unreachable("Unhandled reduction"); 5175 case ISD::VP_REDUCE_ADD: 5176 return RISCVISD::VECREDUCE_ADD_VL; 5177 case ISD::VP_REDUCE_UMAX: 5178 return RISCVISD::VECREDUCE_UMAX_VL; 5179 case ISD::VP_REDUCE_SMAX: 5180 return RISCVISD::VECREDUCE_SMAX_VL; 5181 case ISD::VP_REDUCE_UMIN: 5182 return RISCVISD::VECREDUCE_UMIN_VL; 5183 case ISD::VP_REDUCE_SMIN: 5184 return RISCVISD::VECREDUCE_SMIN_VL; 5185 case ISD::VP_REDUCE_AND: 5186 return RISCVISD::VECREDUCE_AND_VL; 5187 case ISD::VP_REDUCE_OR: 5188 return RISCVISD::VECREDUCE_OR_VL; 5189 case ISD::VP_REDUCE_XOR: 5190 return RISCVISD::VECREDUCE_XOR_VL; 5191 case ISD::VP_REDUCE_FADD: 5192 return RISCVISD::VECREDUCE_FADD_VL; 5193 case ISD::VP_REDUCE_SEQ_FADD: 5194 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5195 case ISD::VP_REDUCE_FMAX: 5196 return RISCVISD::VECREDUCE_FMAX_VL; 5197 case ISD::VP_REDUCE_FMIN: 5198 return RISCVISD::VECREDUCE_FMIN_VL; 5199 } 5200 } 5201 5202 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5203 SelectionDAG &DAG) const { 5204 SDLoc DL(Op); 5205 SDValue Vec = Op.getOperand(1); 5206 EVT VecEVT = Vec.getValueType(); 5207 5208 // TODO: The type may need to be widened rather than split. Or widened before 5209 // it can be split. 5210 if (!isTypeLegal(VecEVT)) 5211 return SDValue(); 5212 5213 MVT VecVT = VecEVT.getSimpleVT(); 5214 MVT VecEltVT = VecVT.getVectorElementType(); 5215 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5216 5217 MVT ContainerVT = VecVT; 5218 if (VecVT.isFixedLengthVector()) { 5219 ContainerVT = getContainerForFixedLengthVector(VecVT); 5220 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5221 } 5222 5223 SDValue VL = Op.getOperand(3); 5224 SDValue Mask = Op.getOperand(2); 5225 5226 MVT M1VT = getLMUL1VT(ContainerVT); 5227 MVT XLenVT = Subtarget.getXLenVT(); 5228 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5229 5230 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5231 DAG.getConstant(1, DL, XLenVT), M1VT, 5232 DL, DAG, Subtarget); 5233 SDValue Reduction = 5234 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5235 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5236 DAG.getConstant(0, DL, XLenVT)); 5237 if (!VecVT.isInteger()) 5238 return Elt0; 5239 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5240 } 5241 5242 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5243 SelectionDAG &DAG) const { 5244 SDValue Vec = Op.getOperand(0); 5245 SDValue SubVec = Op.getOperand(1); 5246 MVT VecVT = Vec.getSimpleValueType(); 5247 MVT SubVecVT = SubVec.getSimpleValueType(); 5248 5249 SDLoc DL(Op); 5250 MVT XLenVT = Subtarget.getXLenVT(); 5251 unsigned OrigIdx = Op.getConstantOperandVal(2); 5252 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5253 5254 // We don't have the ability to slide mask vectors up indexed by their i1 5255 // elements; the smallest we can do is i8. Often we are able to bitcast to 5256 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5257 // into a scalable one, we might not necessarily have enough scalable 5258 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5259 if (SubVecVT.getVectorElementType() == MVT::i1 && 5260 (OrigIdx != 0 || !Vec.isUndef())) { 5261 if (VecVT.getVectorMinNumElements() >= 8 && 5262 SubVecVT.getVectorMinNumElements() >= 8) { 5263 assert(OrigIdx % 8 == 0 && "Invalid index"); 5264 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5265 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5266 "Unexpected mask vector lowering"); 5267 OrigIdx /= 8; 5268 SubVecVT = 5269 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5270 SubVecVT.isScalableVector()); 5271 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5272 VecVT.isScalableVector()); 5273 Vec = DAG.getBitcast(VecVT, Vec); 5274 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5275 } else { 5276 // We can't slide this mask vector up indexed by its i1 elements. 5277 // This poses a problem when we wish to insert a scalable vector which 5278 // can't be re-expressed as a larger type. Just choose the slow path and 5279 // extend to a larger type, then truncate back down. 5280 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5281 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5282 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5283 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5284 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5285 Op.getOperand(2)); 5286 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5287 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5288 } 5289 } 5290 5291 // If the subvector vector is a fixed-length type, we cannot use subregister 5292 // manipulation to simplify the codegen; we don't know which register of a 5293 // LMUL group contains the specific subvector as we only know the minimum 5294 // register size. Therefore we must slide the vector group up the full 5295 // amount. 5296 if (SubVecVT.isFixedLengthVector()) { 5297 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5298 return Op; 5299 MVT ContainerVT = VecVT; 5300 if (VecVT.isFixedLengthVector()) { 5301 ContainerVT = getContainerForFixedLengthVector(VecVT); 5302 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5303 } 5304 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5305 DAG.getUNDEF(ContainerVT), SubVec, 5306 DAG.getConstant(0, DL, XLenVT)); 5307 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5308 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5309 return DAG.getBitcast(Op.getValueType(), SubVec); 5310 } 5311 SDValue Mask = 5312 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5313 // Set the vector length to only the number of elements we care about. Note 5314 // that for slideup this includes the offset. 5315 SDValue VL = 5316 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5317 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5318 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5319 SubVec, SlideupAmt, Mask, VL); 5320 if (VecVT.isFixedLengthVector()) 5321 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5322 return DAG.getBitcast(Op.getValueType(), Slideup); 5323 } 5324 5325 unsigned SubRegIdx, RemIdx; 5326 std::tie(SubRegIdx, RemIdx) = 5327 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5328 VecVT, SubVecVT, OrigIdx, TRI); 5329 5330 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5331 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5332 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5333 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5334 5335 // 1. If the Idx has been completely eliminated and this subvector's size is 5336 // a vector register or a multiple thereof, or the surrounding elements are 5337 // undef, then this is a subvector insert which naturally aligns to a vector 5338 // register. These can easily be handled using subregister manipulation. 5339 // 2. If the subvector is smaller than a vector register, then the insertion 5340 // must preserve the undisturbed elements of the register. We do this by 5341 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5342 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5343 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5344 // LMUL=1 type back into the larger vector (resolving to another subregister 5345 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5346 // to avoid allocating a large register group to hold our subvector. 5347 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5348 return Op; 5349 5350 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5351 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5352 // (in our case undisturbed). This means we can set up a subvector insertion 5353 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5354 // size of the subvector. 5355 MVT InterSubVT = VecVT; 5356 SDValue AlignedExtract = Vec; 5357 unsigned AlignedIdx = OrigIdx - RemIdx; 5358 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5359 InterSubVT = getLMUL1VT(VecVT); 5360 // Extract a subvector equal to the nearest full vector register type. This 5361 // should resolve to a EXTRACT_SUBREG instruction. 5362 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5363 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5364 } 5365 5366 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5367 // For scalable vectors this must be further multiplied by vscale. 5368 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5369 5370 SDValue Mask, VL; 5371 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5372 5373 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5374 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5375 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5376 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5377 5378 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5379 DAG.getUNDEF(InterSubVT), SubVec, 5380 DAG.getConstant(0, DL, XLenVT)); 5381 5382 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5383 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5384 5385 // If required, insert this subvector back into the correct vector register. 5386 // This should resolve to an INSERT_SUBREG instruction. 5387 if (VecVT.bitsGT(InterSubVT)) 5388 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5389 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5390 5391 // We might have bitcast from a mask type: cast back to the original type if 5392 // required. 5393 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5394 } 5395 5396 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5397 SelectionDAG &DAG) const { 5398 SDValue Vec = Op.getOperand(0); 5399 MVT SubVecVT = Op.getSimpleValueType(); 5400 MVT VecVT = Vec.getSimpleValueType(); 5401 5402 SDLoc DL(Op); 5403 MVT XLenVT = Subtarget.getXLenVT(); 5404 unsigned OrigIdx = Op.getConstantOperandVal(1); 5405 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5406 5407 // We don't have the ability to slide mask vectors down indexed by their i1 5408 // elements; the smallest we can do is i8. Often we are able to bitcast to 5409 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5410 // from a scalable one, we might not necessarily have enough scalable 5411 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5412 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5413 if (VecVT.getVectorMinNumElements() >= 8 && 5414 SubVecVT.getVectorMinNumElements() >= 8) { 5415 assert(OrigIdx % 8 == 0 && "Invalid index"); 5416 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5417 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5418 "Unexpected mask vector lowering"); 5419 OrigIdx /= 8; 5420 SubVecVT = 5421 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5422 SubVecVT.isScalableVector()); 5423 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5424 VecVT.isScalableVector()); 5425 Vec = DAG.getBitcast(VecVT, Vec); 5426 } else { 5427 // We can't slide this mask vector down, indexed by its i1 elements. 5428 // This poses a problem when we wish to extract a scalable vector which 5429 // can't be re-expressed as a larger type. Just choose the slow path and 5430 // extend to a larger type, then truncate back down. 5431 // TODO: We could probably improve this when extracting certain fixed 5432 // from fixed, where we can extract as i8 and shift the correct element 5433 // right to reach the desired subvector? 5434 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5435 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5436 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5437 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5438 Op.getOperand(1)); 5439 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5440 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5441 } 5442 } 5443 5444 // If the subvector vector is a fixed-length type, we cannot use subregister 5445 // manipulation to simplify the codegen; we don't know which register of a 5446 // LMUL group contains the specific subvector as we only know the minimum 5447 // register size. Therefore we must slide the vector group down the full 5448 // amount. 5449 if (SubVecVT.isFixedLengthVector()) { 5450 // With an index of 0 this is a cast-like subvector, which can be performed 5451 // with subregister operations. 5452 if (OrigIdx == 0) 5453 return Op; 5454 MVT ContainerVT = VecVT; 5455 if (VecVT.isFixedLengthVector()) { 5456 ContainerVT = getContainerForFixedLengthVector(VecVT); 5457 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5458 } 5459 SDValue Mask = 5460 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5461 // Set the vector length to only the number of elements we care about. This 5462 // avoids sliding down elements we're going to discard straight away. 5463 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5464 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5465 SDValue Slidedown = 5466 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5467 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5468 // Now we can use a cast-like subvector extract to get the result. 5469 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5470 DAG.getConstant(0, DL, XLenVT)); 5471 return DAG.getBitcast(Op.getValueType(), Slidedown); 5472 } 5473 5474 unsigned SubRegIdx, RemIdx; 5475 std::tie(SubRegIdx, RemIdx) = 5476 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5477 VecVT, SubVecVT, OrigIdx, TRI); 5478 5479 // If the Idx has been completely eliminated then this is a subvector extract 5480 // which naturally aligns to a vector register. These can easily be handled 5481 // using subregister manipulation. 5482 if (RemIdx == 0) 5483 return Op; 5484 5485 // Else we must shift our vector register directly to extract the subvector. 5486 // Do this using VSLIDEDOWN. 5487 5488 // If the vector type is an LMUL-group type, extract a subvector equal to the 5489 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5490 // instruction. 5491 MVT InterSubVT = VecVT; 5492 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5493 InterSubVT = getLMUL1VT(VecVT); 5494 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5495 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5496 } 5497 5498 // Slide this vector register down by the desired number of elements in order 5499 // to place the desired subvector starting at element 0. 5500 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5501 // For scalable vectors this must be further multiplied by vscale. 5502 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5503 5504 SDValue Mask, VL; 5505 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5506 SDValue Slidedown = 5507 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5508 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5509 5510 // Now the vector is in the right position, extract our final subvector. This 5511 // should resolve to a COPY. 5512 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5513 DAG.getConstant(0, DL, XLenVT)); 5514 5515 // We might have bitcast from a mask type: cast back to the original type if 5516 // required. 5517 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5518 } 5519 5520 // Lower step_vector to the vid instruction. Any non-identity step value must 5521 // be accounted for my manual expansion. 5522 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5523 SelectionDAG &DAG) const { 5524 SDLoc DL(Op); 5525 MVT VT = Op.getSimpleValueType(); 5526 MVT XLenVT = Subtarget.getXLenVT(); 5527 SDValue Mask, VL; 5528 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5529 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5530 uint64_t StepValImm = Op.getConstantOperandVal(0); 5531 if (StepValImm != 1) { 5532 if (isPowerOf2_64(StepValImm)) { 5533 SDValue StepVal = 5534 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5535 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5536 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5537 } else { 5538 SDValue StepVal = lowerScalarSplat( 5539 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5540 VL, VT, DL, DAG, Subtarget); 5541 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5542 } 5543 } 5544 return StepVec; 5545 } 5546 5547 // Implement vector_reverse using vrgather.vv with indices determined by 5548 // subtracting the id of each element from (VLMAX-1). This will convert 5549 // the indices like so: 5550 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5551 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5552 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5553 SelectionDAG &DAG) const { 5554 SDLoc DL(Op); 5555 MVT VecVT = Op.getSimpleValueType(); 5556 unsigned EltSize = VecVT.getScalarSizeInBits(); 5557 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5558 5559 unsigned MaxVLMAX = 0; 5560 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5561 if (VectorBitsMax != 0) 5562 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5563 5564 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5565 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5566 5567 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5568 // to use vrgatherei16.vv. 5569 // TODO: It's also possible to use vrgatherei16.vv for other types to 5570 // decrease register width for the index calculation. 5571 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5572 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5573 // Reverse each half, then reassemble them in reverse order. 5574 // NOTE: It's also possible that after splitting that VLMAX no longer 5575 // requires vrgatherei16.vv. 5576 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5577 SDValue Lo, Hi; 5578 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5579 EVT LoVT, HiVT; 5580 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5581 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5582 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5583 // Reassemble the low and high pieces reversed. 5584 // FIXME: This is a CONCAT_VECTORS. 5585 SDValue Res = 5586 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5587 DAG.getIntPtrConstant(0, DL)); 5588 return DAG.getNode( 5589 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5590 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5591 } 5592 5593 // Just promote the int type to i16 which will double the LMUL. 5594 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5595 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5596 } 5597 5598 MVT XLenVT = Subtarget.getXLenVT(); 5599 SDValue Mask, VL; 5600 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5601 5602 // Calculate VLMAX-1 for the desired SEW. 5603 unsigned MinElts = VecVT.getVectorMinNumElements(); 5604 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5605 DAG.getConstant(MinElts, DL, XLenVT)); 5606 SDValue VLMinus1 = 5607 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5608 5609 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5610 bool IsRV32E64 = 5611 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5612 SDValue SplatVL; 5613 if (!IsRV32E64) 5614 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5615 else 5616 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5617 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5618 5619 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5620 SDValue Indices = 5621 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5622 5623 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5624 } 5625 5626 SDValue 5627 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5628 SelectionDAG &DAG) const { 5629 SDLoc DL(Op); 5630 auto *Load = cast<LoadSDNode>(Op); 5631 5632 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5633 Load->getMemoryVT(), 5634 *Load->getMemOperand()) && 5635 "Expecting a correctly-aligned load"); 5636 5637 MVT VT = Op.getSimpleValueType(); 5638 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5639 5640 SDValue VL = 5641 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5642 5643 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5644 SDValue NewLoad = DAG.getMemIntrinsicNode( 5645 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5646 Load->getMemoryVT(), Load->getMemOperand()); 5647 5648 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5649 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5650 } 5651 5652 SDValue 5653 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5654 SelectionDAG &DAG) const { 5655 SDLoc DL(Op); 5656 auto *Store = cast<StoreSDNode>(Op); 5657 5658 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5659 Store->getMemoryVT(), 5660 *Store->getMemOperand()) && 5661 "Expecting a correctly-aligned store"); 5662 5663 SDValue StoreVal = Store->getValue(); 5664 MVT VT = StoreVal.getSimpleValueType(); 5665 5666 // If the size less than a byte, we need to pad with zeros to make a byte. 5667 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5668 VT = MVT::v8i1; 5669 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5670 DAG.getConstant(0, DL, VT), StoreVal, 5671 DAG.getIntPtrConstant(0, DL)); 5672 } 5673 5674 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5675 5676 SDValue VL = 5677 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5678 5679 SDValue NewValue = 5680 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5681 return DAG.getMemIntrinsicNode( 5682 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5683 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5684 Store->getMemoryVT(), Store->getMemOperand()); 5685 } 5686 5687 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5688 SelectionDAG &DAG) const { 5689 SDLoc DL(Op); 5690 MVT VT = Op.getSimpleValueType(); 5691 5692 const auto *MemSD = cast<MemSDNode>(Op); 5693 EVT MemVT = MemSD->getMemoryVT(); 5694 MachineMemOperand *MMO = MemSD->getMemOperand(); 5695 SDValue Chain = MemSD->getChain(); 5696 SDValue BasePtr = MemSD->getBasePtr(); 5697 5698 SDValue Mask, PassThru, VL; 5699 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5700 Mask = VPLoad->getMask(); 5701 PassThru = DAG.getUNDEF(VT); 5702 VL = VPLoad->getVectorLength(); 5703 } else { 5704 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5705 Mask = MLoad->getMask(); 5706 PassThru = MLoad->getPassThru(); 5707 } 5708 5709 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5710 5711 MVT XLenVT = Subtarget.getXLenVT(); 5712 5713 MVT ContainerVT = VT; 5714 if (VT.isFixedLengthVector()) { 5715 ContainerVT = getContainerForFixedLengthVector(VT); 5716 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5717 if (!IsUnmasked) { 5718 MVT MaskVT = 5719 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5720 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5721 } 5722 } 5723 5724 if (!VL) 5725 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5726 5727 unsigned IntID = 5728 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5729 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5730 if (IsUnmasked) 5731 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5732 else 5733 Ops.push_back(PassThru); 5734 Ops.push_back(BasePtr); 5735 if (!IsUnmasked) 5736 Ops.push_back(Mask); 5737 Ops.push_back(VL); 5738 if (!IsUnmasked) 5739 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5740 5741 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5742 5743 SDValue Result = 5744 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5745 Chain = Result.getValue(1); 5746 5747 if (VT.isFixedLengthVector()) 5748 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5749 5750 return DAG.getMergeValues({Result, Chain}, DL); 5751 } 5752 5753 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5754 SelectionDAG &DAG) const { 5755 SDLoc DL(Op); 5756 5757 const auto *MemSD = cast<MemSDNode>(Op); 5758 EVT MemVT = MemSD->getMemoryVT(); 5759 MachineMemOperand *MMO = MemSD->getMemOperand(); 5760 SDValue Chain = MemSD->getChain(); 5761 SDValue BasePtr = MemSD->getBasePtr(); 5762 SDValue Val, Mask, VL; 5763 5764 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5765 Val = VPStore->getValue(); 5766 Mask = VPStore->getMask(); 5767 VL = VPStore->getVectorLength(); 5768 } else { 5769 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5770 Val = MStore->getValue(); 5771 Mask = MStore->getMask(); 5772 } 5773 5774 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5775 5776 MVT VT = Val.getSimpleValueType(); 5777 MVT XLenVT = Subtarget.getXLenVT(); 5778 5779 MVT ContainerVT = VT; 5780 if (VT.isFixedLengthVector()) { 5781 ContainerVT = getContainerForFixedLengthVector(VT); 5782 5783 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5784 if (!IsUnmasked) { 5785 MVT MaskVT = 5786 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5787 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5788 } 5789 } 5790 5791 if (!VL) 5792 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5793 5794 unsigned IntID = 5795 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5796 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5797 Ops.push_back(Val); 5798 Ops.push_back(BasePtr); 5799 if (!IsUnmasked) 5800 Ops.push_back(Mask); 5801 Ops.push_back(VL); 5802 5803 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5804 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5805 } 5806 5807 SDValue 5808 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5809 SelectionDAG &DAG) const { 5810 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5811 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5812 5813 MVT VT = Op.getSimpleValueType(); 5814 5815 SDValue Op1 = 5816 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5817 SDValue Op2 = 5818 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5819 5820 SDLoc DL(Op); 5821 SDValue VL = 5822 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5823 5824 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5825 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5826 5827 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5828 Op.getOperand(2), Mask, VL); 5829 5830 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5831 } 5832 5833 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5834 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5835 MVT VT = Op.getSimpleValueType(); 5836 5837 if (VT.getVectorElementType() == MVT::i1) 5838 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5839 5840 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5841 } 5842 5843 SDValue 5844 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5845 SelectionDAG &DAG) const { 5846 unsigned Opc; 5847 switch (Op.getOpcode()) { 5848 default: llvm_unreachable("Unexpected opcode!"); 5849 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5850 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5851 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5852 } 5853 5854 return lowerToScalableOp(Op, DAG, Opc); 5855 } 5856 5857 // Lower vector ABS to smax(X, sub(0, X)). 5858 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5859 SDLoc DL(Op); 5860 MVT VT = Op.getSimpleValueType(); 5861 SDValue X = Op.getOperand(0); 5862 5863 assert(VT.isFixedLengthVector() && "Unexpected type"); 5864 5865 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5866 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5867 5868 SDValue Mask, VL; 5869 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5870 5871 SDValue SplatZero = DAG.getNode( 5872 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5873 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5874 SDValue NegX = 5875 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5876 SDValue Max = 5877 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5878 5879 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5880 } 5881 5882 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5883 SDValue Op, SelectionDAG &DAG) const { 5884 SDLoc DL(Op); 5885 MVT VT = Op.getSimpleValueType(); 5886 SDValue Mag = Op.getOperand(0); 5887 SDValue Sign = Op.getOperand(1); 5888 assert(Mag.getValueType() == Sign.getValueType() && 5889 "Can only handle COPYSIGN with matching types."); 5890 5891 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5892 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5893 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5894 5895 SDValue Mask, VL; 5896 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5897 5898 SDValue CopySign = 5899 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5900 5901 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5902 } 5903 5904 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5905 SDValue Op, SelectionDAG &DAG) const { 5906 MVT VT = Op.getSimpleValueType(); 5907 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5908 5909 MVT I1ContainerVT = 5910 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5911 5912 SDValue CC = 5913 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5914 SDValue Op1 = 5915 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5916 SDValue Op2 = 5917 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5918 5919 SDLoc DL(Op); 5920 SDValue Mask, VL; 5921 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5922 5923 SDValue Select = 5924 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5925 5926 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5927 } 5928 5929 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5930 unsigned NewOpc, 5931 bool HasMask) const { 5932 MVT VT = Op.getSimpleValueType(); 5933 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5934 5935 // Create list of operands by converting existing ones to scalable types. 5936 SmallVector<SDValue, 6> Ops; 5937 for (const SDValue &V : Op->op_values()) { 5938 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5939 5940 // Pass through non-vector operands. 5941 if (!V.getValueType().isVector()) { 5942 Ops.push_back(V); 5943 continue; 5944 } 5945 5946 // "cast" fixed length vector to a scalable vector. 5947 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5948 "Only fixed length vectors are supported!"); 5949 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5950 } 5951 5952 SDLoc DL(Op); 5953 SDValue Mask, VL; 5954 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5955 if (HasMask) 5956 Ops.push_back(Mask); 5957 Ops.push_back(VL); 5958 5959 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5960 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5961 } 5962 5963 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5964 // * Operands of each node are assumed to be in the same order. 5965 // * The EVL operand is promoted from i32 to i64 on RV64. 5966 // * Fixed-length vectors are converted to their scalable-vector container 5967 // types. 5968 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5969 unsigned RISCVISDOpc) const { 5970 SDLoc DL(Op); 5971 MVT VT = Op.getSimpleValueType(); 5972 SmallVector<SDValue, 4> Ops; 5973 5974 for (const auto &OpIdx : enumerate(Op->ops())) { 5975 SDValue V = OpIdx.value(); 5976 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5977 // Pass through operands which aren't fixed-length vectors. 5978 if (!V.getValueType().isFixedLengthVector()) { 5979 Ops.push_back(V); 5980 continue; 5981 } 5982 // "cast" fixed length vector to a scalable vector. 5983 MVT OpVT = V.getSimpleValueType(); 5984 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5985 assert(useRVVForFixedLengthVectorVT(OpVT) && 5986 "Only fixed length vectors are supported!"); 5987 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5988 } 5989 5990 if (!VT.isFixedLengthVector()) 5991 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5992 5993 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5994 5995 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5996 5997 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5998 } 5999 6000 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6001 unsigned MaskOpc, 6002 unsigned VecOpc) const { 6003 MVT VT = Op.getSimpleValueType(); 6004 if (VT.getVectorElementType() != MVT::i1) 6005 return lowerVPOp(Op, DAG, VecOpc); 6006 6007 // It is safe to drop mask parameter as masked-off elements are undef. 6008 SDValue Op1 = Op->getOperand(0); 6009 SDValue Op2 = Op->getOperand(1); 6010 SDValue VL = Op->getOperand(3); 6011 6012 MVT ContainerVT = VT; 6013 const bool IsFixed = VT.isFixedLengthVector(); 6014 if (IsFixed) { 6015 ContainerVT = getContainerForFixedLengthVector(VT); 6016 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6017 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6018 } 6019 6020 SDLoc DL(Op); 6021 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6022 if (!IsFixed) 6023 return Val; 6024 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6025 } 6026 6027 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6028 // matched to a RVV indexed load. The RVV indexed load instructions only 6029 // support the "unsigned unscaled" addressing mode; indices are implicitly 6030 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6031 // signed or scaled indexing is extended to the XLEN value type and scaled 6032 // accordingly. 6033 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6034 SelectionDAG &DAG) const { 6035 SDLoc DL(Op); 6036 MVT VT = Op.getSimpleValueType(); 6037 6038 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6039 EVT MemVT = MemSD->getMemoryVT(); 6040 MachineMemOperand *MMO = MemSD->getMemOperand(); 6041 SDValue Chain = MemSD->getChain(); 6042 SDValue BasePtr = MemSD->getBasePtr(); 6043 6044 ISD::LoadExtType LoadExtType; 6045 SDValue Index, Mask, PassThru, VL; 6046 6047 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6048 Index = VPGN->getIndex(); 6049 Mask = VPGN->getMask(); 6050 PassThru = DAG.getUNDEF(VT); 6051 VL = VPGN->getVectorLength(); 6052 // VP doesn't support extending loads. 6053 LoadExtType = ISD::NON_EXTLOAD; 6054 } else { 6055 // Else it must be a MGATHER. 6056 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6057 Index = MGN->getIndex(); 6058 Mask = MGN->getMask(); 6059 PassThru = MGN->getPassThru(); 6060 LoadExtType = MGN->getExtensionType(); 6061 } 6062 6063 MVT IndexVT = Index.getSimpleValueType(); 6064 MVT XLenVT = Subtarget.getXLenVT(); 6065 6066 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6067 "Unexpected VTs!"); 6068 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6069 // Targets have to explicitly opt-in for extending vector loads. 6070 assert(LoadExtType == ISD::NON_EXTLOAD && 6071 "Unexpected extending MGATHER/VP_GATHER"); 6072 (void)LoadExtType; 6073 6074 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6075 // the selection of the masked intrinsics doesn't do this for us. 6076 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6077 6078 MVT ContainerVT = VT; 6079 if (VT.isFixedLengthVector()) { 6080 // We need to use the larger of the result and index type to determine the 6081 // scalable type to use so we don't increase LMUL for any operand/result. 6082 if (VT.bitsGE(IndexVT)) { 6083 ContainerVT = getContainerForFixedLengthVector(VT); 6084 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6085 ContainerVT.getVectorElementCount()); 6086 } else { 6087 IndexVT = getContainerForFixedLengthVector(IndexVT); 6088 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6089 IndexVT.getVectorElementCount()); 6090 } 6091 6092 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6093 6094 if (!IsUnmasked) { 6095 MVT MaskVT = 6096 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6097 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6098 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6099 } 6100 } 6101 6102 if (!VL) 6103 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6104 6105 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6106 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6107 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6108 VL); 6109 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6110 TrueMask, VL); 6111 } 6112 6113 unsigned IntID = 6114 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6115 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6116 if (IsUnmasked) 6117 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6118 else 6119 Ops.push_back(PassThru); 6120 Ops.push_back(BasePtr); 6121 Ops.push_back(Index); 6122 if (!IsUnmasked) 6123 Ops.push_back(Mask); 6124 Ops.push_back(VL); 6125 if (!IsUnmasked) 6126 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6127 6128 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6129 SDValue Result = 6130 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6131 Chain = Result.getValue(1); 6132 6133 if (VT.isFixedLengthVector()) 6134 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6135 6136 return DAG.getMergeValues({Result, Chain}, DL); 6137 } 6138 6139 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6140 // matched to a RVV indexed store. The RVV indexed store instructions only 6141 // support the "unsigned unscaled" addressing mode; indices are implicitly 6142 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6143 // signed or scaled indexing is extended to the XLEN value type and scaled 6144 // accordingly. 6145 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6146 SelectionDAG &DAG) const { 6147 SDLoc DL(Op); 6148 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6149 EVT MemVT = MemSD->getMemoryVT(); 6150 MachineMemOperand *MMO = MemSD->getMemOperand(); 6151 SDValue Chain = MemSD->getChain(); 6152 SDValue BasePtr = MemSD->getBasePtr(); 6153 6154 bool IsTruncatingStore = false; 6155 SDValue Index, Mask, Val, VL; 6156 6157 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6158 Index = VPSN->getIndex(); 6159 Mask = VPSN->getMask(); 6160 Val = VPSN->getValue(); 6161 VL = VPSN->getVectorLength(); 6162 // VP doesn't support truncating stores. 6163 IsTruncatingStore = false; 6164 } else { 6165 // Else it must be a MSCATTER. 6166 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6167 Index = MSN->getIndex(); 6168 Mask = MSN->getMask(); 6169 Val = MSN->getValue(); 6170 IsTruncatingStore = MSN->isTruncatingStore(); 6171 } 6172 6173 MVT VT = Val.getSimpleValueType(); 6174 MVT IndexVT = Index.getSimpleValueType(); 6175 MVT XLenVT = Subtarget.getXLenVT(); 6176 6177 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6178 "Unexpected VTs!"); 6179 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6180 // Targets have to explicitly opt-in for extending vector loads and 6181 // truncating vector stores. 6182 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6183 (void)IsTruncatingStore; 6184 6185 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6186 // the selection of the masked intrinsics doesn't do this for us. 6187 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6188 6189 MVT ContainerVT = VT; 6190 if (VT.isFixedLengthVector()) { 6191 // We need to use the larger of the value and index type to determine the 6192 // scalable type to use so we don't increase LMUL for any operand/result. 6193 if (VT.bitsGE(IndexVT)) { 6194 ContainerVT = getContainerForFixedLengthVector(VT); 6195 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6196 ContainerVT.getVectorElementCount()); 6197 } else { 6198 IndexVT = getContainerForFixedLengthVector(IndexVT); 6199 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6200 IndexVT.getVectorElementCount()); 6201 } 6202 6203 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6204 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6205 6206 if (!IsUnmasked) { 6207 MVT MaskVT = 6208 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6209 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6210 } 6211 } 6212 6213 if (!VL) 6214 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6215 6216 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6217 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6218 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6219 VL); 6220 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6221 TrueMask, VL); 6222 } 6223 6224 unsigned IntID = 6225 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6226 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6227 Ops.push_back(Val); 6228 Ops.push_back(BasePtr); 6229 Ops.push_back(Index); 6230 if (!IsUnmasked) 6231 Ops.push_back(Mask); 6232 Ops.push_back(VL); 6233 6234 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6235 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6236 } 6237 6238 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6239 SelectionDAG &DAG) const { 6240 const MVT XLenVT = Subtarget.getXLenVT(); 6241 SDLoc DL(Op); 6242 SDValue Chain = Op->getOperand(0); 6243 SDValue SysRegNo = DAG.getTargetConstant( 6244 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6245 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6246 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6247 6248 // Encoding used for rounding mode in RISCV differs from that used in 6249 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6250 // table, which consists of a sequence of 4-bit fields, each representing 6251 // corresponding FLT_ROUNDS mode. 6252 static const int Table = 6253 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6254 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6255 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6256 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6257 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6258 6259 SDValue Shift = 6260 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6261 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6262 DAG.getConstant(Table, DL, XLenVT), Shift); 6263 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6264 DAG.getConstant(7, DL, XLenVT)); 6265 6266 return DAG.getMergeValues({Masked, Chain}, DL); 6267 } 6268 6269 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6270 SelectionDAG &DAG) const { 6271 const MVT XLenVT = Subtarget.getXLenVT(); 6272 SDLoc DL(Op); 6273 SDValue Chain = Op->getOperand(0); 6274 SDValue RMValue = Op->getOperand(1); 6275 SDValue SysRegNo = DAG.getTargetConstant( 6276 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6277 6278 // Encoding used for rounding mode in RISCV differs from that used in 6279 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6280 // a table, which consists of a sequence of 4-bit fields, each representing 6281 // corresponding RISCV mode. 6282 static const unsigned Table = 6283 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6284 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6285 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6286 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6287 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6288 6289 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6290 DAG.getConstant(2, DL, XLenVT)); 6291 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6292 DAG.getConstant(Table, DL, XLenVT), Shift); 6293 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6294 DAG.getConstant(0x7, DL, XLenVT)); 6295 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6296 RMValue); 6297 } 6298 6299 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6300 switch (IntNo) { 6301 default: 6302 llvm_unreachable("Unexpected Intrinsic"); 6303 case Intrinsic::riscv_grev: 6304 return RISCVISD::GREVW; 6305 case Intrinsic::riscv_gorc: 6306 return RISCVISD::GORCW; 6307 case Intrinsic::riscv_bcompress: 6308 return RISCVISD::BCOMPRESSW; 6309 case Intrinsic::riscv_bdecompress: 6310 return RISCVISD::BDECOMPRESSW; 6311 case Intrinsic::riscv_bfp: 6312 return RISCVISD::BFPW; 6313 case Intrinsic::riscv_fsl: 6314 return RISCVISD::FSLW; 6315 case Intrinsic::riscv_fsr: 6316 return RISCVISD::FSRW; 6317 } 6318 } 6319 6320 // Converts the given intrinsic to a i64 operation with any extension. 6321 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6322 unsigned IntNo) { 6323 SDLoc DL(N); 6324 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6325 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6326 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6327 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6328 // ReplaceNodeResults requires we maintain the same type for the return value. 6329 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6330 } 6331 6332 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6333 // form of the given Opcode. 6334 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6335 switch (Opcode) { 6336 default: 6337 llvm_unreachable("Unexpected opcode"); 6338 case ISD::SHL: 6339 return RISCVISD::SLLW; 6340 case ISD::SRA: 6341 return RISCVISD::SRAW; 6342 case ISD::SRL: 6343 return RISCVISD::SRLW; 6344 case ISD::SDIV: 6345 return RISCVISD::DIVW; 6346 case ISD::UDIV: 6347 return RISCVISD::DIVUW; 6348 case ISD::UREM: 6349 return RISCVISD::REMUW; 6350 case ISD::ROTL: 6351 return RISCVISD::ROLW; 6352 case ISD::ROTR: 6353 return RISCVISD::RORW; 6354 case RISCVISD::GREV: 6355 return RISCVISD::GREVW; 6356 case RISCVISD::GORC: 6357 return RISCVISD::GORCW; 6358 } 6359 } 6360 6361 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6362 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6363 // otherwise be promoted to i64, making it difficult to select the 6364 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6365 // type i8/i16/i32 is lost. 6366 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6367 unsigned ExtOpc = ISD::ANY_EXTEND) { 6368 SDLoc DL(N); 6369 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6370 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6371 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6372 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6373 // ReplaceNodeResults requires we maintain the same type for the return value. 6374 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6375 } 6376 6377 // Converts the given 32-bit operation to a i64 operation with signed extension 6378 // semantic to reduce the signed extension instructions. 6379 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6380 SDLoc DL(N); 6381 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6382 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6383 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6384 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6385 DAG.getValueType(MVT::i32)); 6386 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6387 } 6388 6389 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6390 SmallVectorImpl<SDValue> &Results, 6391 SelectionDAG &DAG) const { 6392 SDLoc DL(N); 6393 switch (N->getOpcode()) { 6394 default: 6395 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6396 case ISD::STRICT_FP_TO_SINT: 6397 case ISD::STRICT_FP_TO_UINT: 6398 case ISD::FP_TO_SINT: 6399 case ISD::FP_TO_UINT: { 6400 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6401 "Unexpected custom legalisation"); 6402 bool IsStrict = N->isStrictFPOpcode(); 6403 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6404 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6405 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6406 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6407 TargetLowering::TypeSoftenFloat) { 6408 if (!isTypeLegal(Op0.getValueType())) 6409 return; 6410 if (IsStrict) { 6411 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6412 : RISCVISD::STRICT_FCVT_WU_RV64; 6413 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6414 SDValue Res = DAG.getNode( 6415 Opc, DL, VTs, N->getOperand(0), Op0, 6416 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6417 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6418 Results.push_back(Res.getValue(1)); 6419 return; 6420 } 6421 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6422 SDValue Res = 6423 DAG.getNode(Opc, DL, MVT::i64, Op0, 6424 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6425 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6426 return; 6427 } 6428 // If the FP type needs to be softened, emit a library call using the 'si' 6429 // version. If we left it to default legalization we'd end up with 'di'. If 6430 // the FP type doesn't need to be softened just let generic type 6431 // legalization promote the result type. 6432 RTLIB::Libcall LC; 6433 if (IsSigned) 6434 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6435 else 6436 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6437 MakeLibCallOptions CallOptions; 6438 EVT OpVT = Op0.getValueType(); 6439 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6440 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6441 SDValue Result; 6442 std::tie(Result, Chain) = 6443 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6444 Results.push_back(Result); 6445 if (IsStrict) 6446 Results.push_back(Chain); 6447 break; 6448 } 6449 case ISD::READCYCLECOUNTER: { 6450 assert(!Subtarget.is64Bit() && 6451 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6452 6453 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6454 SDValue RCW = 6455 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6456 6457 Results.push_back( 6458 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6459 Results.push_back(RCW.getValue(2)); 6460 break; 6461 } 6462 case ISD::MUL: { 6463 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6464 unsigned XLen = Subtarget.getXLen(); 6465 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6466 if (Size > XLen) { 6467 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6468 SDValue LHS = N->getOperand(0); 6469 SDValue RHS = N->getOperand(1); 6470 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6471 6472 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6473 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6474 // We need exactly one side to be unsigned. 6475 if (LHSIsU == RHSIsU) 6476 return; 6477 6478 auto MakeMULPair = [&](SDValue S, SDValue U) { 6479 MVT XLenVT = Subtarget.getXLenVT(); 6480 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6481 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6482 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6483 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6484 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6485 }; 6486 6487 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6488 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6489 6490 // The other operand should be signed, but still prefer MULH when 6491 // possible. 6492 if (RHSIsU && LHSIsS && !RHSIsS) 6493 Results.push_back(MakeMULPair(LHS, RHS)); 6494 else if (LHSIsU && RHSIsS && !LHSIsS) 6495 Results.push_back(MakeMULPair(RHS, LHS)); 6496 6497 return; 6498 } 6499 LLVM_FALLTHROUGH; 6500 } 6501 case ISD::ADD: 6502 case ISD::SUB: 6503 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6504 "Unexpected custom legalisation"); 6505 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6506 break; 6507 case ISD::SHL: 6508 case ISD::SRA: 6509 case ISD::SRL: 6510 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6511 "Unexpected custom legalisation"); 6512 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6513 Results.push_back(customLegalizeToWOp(N, DAG)); 6514 break; 6515 } 6516 6517 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6518 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6519 // shift amount. 6520 if (N->getOpcode() == ISD::SHL) { 6521 SDLoc DL(N); 6522 SDValue NewOp0 = 6523 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6524 SDValue NewOp1 = 6525 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6526 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6527 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6528 DAG.getValueType(MVT::i32)); 6529 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6530 } 6531 6532 break; 6533 case ISD::ROTL: 6534 case ISD::ROTR: 6535 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6536 "Unexpected custom legalisation"); 6537 Results.push_back(customLegalizeToWOp(N, DAG)); 6538 break; 6539 case ISD::CTTZ: 6540 case ISD::CTTZ_ZERO_UNDEF: 6541 case ISD::CTLZ: 6542 case ISD::CTLZ_ZERO_UNDEF: { 6543 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6544 "Unexpected custom legalisation"); 6545 6546 SDValue NewOp0 = 6547 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6548 bool IsCTZ = 6549 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6550 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6551 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6552 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6553 return; 6554 } 6555 case ISD::SDIV: 6556 case ISD::UDIV: 6557 case ISD::UREM: { 6558 MVT VT = N->getSimpleValueType(0); 6559 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6560 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6561 "Unexpected custom legalisation"); 6562 // Don't promote division/remainder by constant since we should expand those 6563 // to multiply by magic constant. 6564 // FIXME: What if the expansion is disabled for minsize. 6565 if (N->getOperand(1).getOpcode() == ISD::Constant) 6566 return; 6567 6568 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6569 // the upper 32 bits. For other types we need to sign or zero extend 6570 // based on the opcode. 6571 unsigned ExtOpc = ISD::ANY_EXTEND; 6572 if (VT != MVT::i32) 6573 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6574 : ISD::ZERO_EXTEND; 6575 6576 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6577 break; 6578 } 6579 case ISD::UADDO: 6580 case ISD::USUBO: { 6581 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6582 "Unexpected custom legalisation"); 6583 bool IsAdd = N->getOpcode() == ISD::UADDO; 6584 // Create an ADDW or SUBW. 6585 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6586 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6587 SDValue Res = 6588 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6589 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6590 DAG.getValueType(MVT::i32)); 6591 6592 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6593 // Since the inputs are sign extended from i32, this is equivalent to 6594 // comparing the lower 32 bits. 6595 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6596 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6597 IsAdd ? ISD::SETULT : ISD::SETUGT); 6598 6599 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6600 Results.push_back(Overflow); 6601 return; 6602 } 6603 case ISD::UADDSAT: 6604 case ISD::USUBSAT: { 6605 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6606 "Unexpected custom legalisation"); 6607 if (Subtarget.hasStdExtZbb()) { 6608 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6609 // sign extend allows overflow of the lower 32 bits to be detected on 6610 // the promoted size. 6611 SDValue LHS = 6612 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6613 SDValue RHS = 6614 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6615 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6616 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6617 return; 6618 } 6619 6620 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6621 // promotion for UADDO/USUBO. 6622 Results.push_back(expandAddSubSat(N, DAG)); 6623 return; 6624 } 6625 case ISD::BITCAST: { 6626 EVT VT = N->getValueType(0); 6627 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6628 SDValue Op0 = N->getOperand(0); 6629 EVT Op0VT = Op0.getValueType(); 6630 MVT XLenVT = Subtarget.getXLenVT(); 6631 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6632 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6633 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6634 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6635 Subtarget.hasStdExtF()) { 6636 SDValue FPConv = 6637 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6638 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6639 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6640 isTypeLegal(Op0VT)) { 6641 // Custom-legalize bitcasts from fixed-length vector types to illegal 6642 // scalar types in order to improve codegen. Bitcast the vector to a 6643 // one-element vector type whose element type is the same as the result 6644 // type, and extract the first element. 6645 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6646 if (isTypeLegal(BVT)) { 6647 SDValue BVec = DAG.getBitcast(BVT, Op0); 6648 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6649 DAG.getConstant(0, DL, XLenVT))); 6650 } 6651 } 6652 break; 6653 } 6654 case RISCVISD::GREV: 6655 case RISCVISD::GORC: { 6656 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6657 "Unexpected custom legalisation"); 6658 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6659 // This is similar to customLegalizeToWOp, except that we pass the second 6660 // operand (a TargetConstant) straight through: it is already of type 6661 // XLenVT. 6662 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6663 SDValue NewOp0 = 6664 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6665 SDValue NewOp1 = 6666 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6667 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6668 // ReplaceNodeResults requires we maintain the same type for the return 6669 // value. 6670 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6671 break; 6672 } 6673 case RISCVISD::SHFL: { 6674 // There is no SHFLIW instruction, but we can just promote the operation. 6675 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6676 "Unexpected custom legalisation"); 6677 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6678 SDValue NewOp0 = 6679 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6680 SDValue NewOp1 = 6681 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6682 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6683 // ReplaceNodeResults requires we maintain the same type for the return 6684 // value. 6685 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6686 break; 6687 } 6688 case ISD::BSWAP: 6689 case ISD::BITREVERSE: { 6690 MVT VT = N->getSimpleValueType(0); 6691 MVT XLenVT = Subtarget.getXLenVT(); 6692 assert((VT == MVT::i8 || VT == MVT::i16 || 6693 (VT == MVT::i32 && Subtarget.is64Bit())) && 6694 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6695 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6696 unsigned Imm = VT.getSizeInBits() - 1; 6697 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6698 if (N->getOpcode() == ISD::BSWAP) 6699 Imm &= ~0x7U; 6700 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6701 SDValue GREVI = 6702 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6703 // ReplaceNodeResults requires we maintain the same type for the return 6704 // value. 6705 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6706 break; 6707 } 6708 case ISD::FSHL: 6709 case ISD::FSHR: { 6710 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6711 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6712 SDValue NewOp0 = 6713 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6714 SDValue NewOp1 = 6715 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6716 SDValue NewShAmt = 6717 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6718 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6719 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6720 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6721 DAG.getConstant(0x1f, DL, MVT::i64)); 6722 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6723 // instruction use different orders. fshl will return its first operand for 6724 // shift of zero, fshr will return its second operand. fsl and fsr both 6725 // return rs1 so the ISD nodes need to have different operand orders. 6726 // Shift amount is in rs2. 6727 unsigned Opc = RISCVISD::FSLW; 6728 if (N->getOpcode() == ISD::FSHR) { 6729 std::swap(NewOp0, NewOp1); 6730 Opc = RISCVISD::FSRW; 6731 } 6732 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6733 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6734 break; 6735 } 6736 case ISD::EXTRACT_VECTOR_ELT: { 6737 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6738 // type is illegal (currently only vXi64 RV32). 6739 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6740 // transferred to the destination register. We issue two of these from the 6741 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6742 // first element. 6743 SDValue Vec = N->getOperand(0); 6744 SDValue Idx = N->getOperand(1); 6745 6746 // The vector type hasn't been legalized yet so we can't issue target 6747 // specific nodes if it needs legalization. 6748 // FIXME: We would manually legalize if it's important. 6749 if (!isTypeLegal(Vec.getValueType())) 6750 return; 6751 6752 MVT VecVT = Vec.getSimpleValueType(); 6753 6754 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6755 VecVT.getVectorElementType() == MVT::i64 && 6756 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6757 6758 // If this is a fixed vector, we need to convert it to a scalable vector. 6759 MVT ContainerVT = VecVT; 6760 if (VecVT.isFixedLengthVector()) { 6761 ContainerVT = getContainerForFixedLengthVector(VecVT); 6762 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6763 } 6764 6765 MVT XLenVT = Subtarget.getXLenVT(); 6766 6767 // Use a VL of 1 to avoid processing more elements than we need. 6768 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6769 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6770 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6771 6772 // Unless the index is known to be 0, we must slide the vector down to get 6773 // the desired element into index 0. 6774 if (!isNullConstant(Idx)) { 6775 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6776 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6777 } 6778 6779 // Extract the lower XLEN bits of the correct vector element. 6780 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6781 6782 // To extract the upper XLEN bits of the vector element, shift the first 6783 // element right by 32 bits and re-extract the lower XLEN bits. 6784 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6785 DAG.getUNDEF(ContainerVT), 6786 DAG.getConstant(32, DL, XLenVT), VL); 6787 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6788 ThirtyTwoV, Mask, VL); 6789 6790 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6791 6792 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6793 break; 6794 } 6795 case ISD::INTRINSIC_WO_CHAIN: { 6796 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6797 switch (IntNo) { 6798 default: 6799 llvm_unreachable( 6800 "Don't know how to custom type legalize this intrinsic!"); 6801 case Intrinsic::riscv_grev: 6802 case Intrinsic::riscv_gorc: 6803 case Intrinsic::riscv_bcompress: 6804 case Intrinsic::riscv_bdecompress: 6805 case Intrinsic::riscv_bfp: { 6806 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6807 "Unexpected custom legalisation"); 6808 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6809 break; 6810 } 6811 case Intrinsic::riscv_fsl: 6812 case Intrinsic::riscv_fsr: { 6813 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6814 "Unexpected custom legalisation"); 6815 SDValue NewOp1 = 6816 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6817 SDValue NewOp2 = 6818 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6819 SDValue NewOp3 = 6820 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 6821 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 6822 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 6823 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6824 break; 6825 } 6826 case Intrinsic::riscv_orc_b: { 6827 // Lower to the GORCI encoding for orc.b with the operand extended. 6828 SDValue NewOp = 6829 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6830 // If Zbp is enabled, use GORCIW which will sign extend the result. 6831 unsigned Opc = 6832 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6833 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6834 DAG.getConstant(7, DL, MVT::i64)); 6835 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6836 return; 6837 } 6838 case Intrinsic::riscv_shfl: 6839 case Intrinsic::riscv_unshfl: { 6840 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6841 "Unexpected custom legalisation"); 6842 SDValue NewOp1 = 6843 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6844 SDValue NewOp2 = 6845 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6846 unsigned Opc = 6847 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6848 // There is no (UN)SHFLIW. If the control word is a constant, we can use 6849 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 6850 // will be shuffled the same way as the lower 32 bit half, but the two 6851 // halves won't cross. 6852 if (isa<ConstantSDNode>(NewOp2)) { 6853 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6854 DAG.getConstant(0xf, DL, MVT::i64)); 6855 Opc = 6856 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6857 } 6858 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6859 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6860 break; 6861 } 6862 case Intrinsic::riscv_vmv_x_s: { 6863 EVT VT = N->getValueType(0); 6864 MVT XLenVT = Subtarget.getXLenVT(); 6865 if (VT.bitsLT(XLenVT)) { 6866 // Simple case just extract using vmv.x.s and truncate. 6867 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6868 Subtarget.getXLenVT(), N->getOperand(1)); 6869 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6870 return; 6871 } 6872 6873 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6874 "Unexpected custom legalization"); 6875 6876 // We need to do the move in two steps. 6877 SDValue Vec = N->getOperand(1); 6878 MVT VecVT = Vec.getSimpleValueType(); 6879 6880 // First extract the lower XLEN bits of the element. 6881 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6882 6883 // To extract the upper XLEN bits of the vector element, shift the first 6884 // element right by 32 bits and re-extract the lower XLEN bits. 6885 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6886 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6887 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6888 SDValue ThirtyTwoV = 6889 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 6890 DAG.getConstant(32, DL, XLenVT), VL); 6891 SDValue LShr32 = 6892 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6893 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6894 6895 Results.push_back( 6896 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6897 break; 6898 } 6899 } 6900 break; 6901 } 6902 case ISD::VECREDUCE_ADD: 6903 case ISD::VECREDUCE_AND: 6904 case ISD::VECREDUCE_OR: 6905 case ISD::VECREDUCE_XOR: 6906 case ISD::VECREDUCE_SMAX: 6907 case ISD::VECREDUCE_UMAX: 6908 case ISD::VECREDUCE_SMIN: 6909 case ISD::VECREDUCE_UMIN: 6910 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6911 Results.push_back(V); 6912 break; 6913 case ISD::VP_REDUCE_ADD: 6914 case ISD::VP_REDUCE_AND: 6915 case ISD::VP_REDUCE_OR: 6916 case ISD::VP_REDUCE_XOR: 6917 case ISD::VP_REDUCE_SMAX: 6918 case ISD::VP_REDUCE_UMAX: 6919 case ISD::VP_REDUCE_SMIN: 6920 case ISD::VP_REDUCE_UMIN: 6921 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6922 Results.push_back(V); 6923 break; 6924 case ISD::FLT_ROUNDS_: { 6925 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6926 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6927 Results.push_back(Res.getValue(0)); 6928 Results.push_back(Res.getValue(1)); 6929 break; 6930 } 6931 } 6932 } 6933 6934 // A structure to hold one of the bit-manipulation patterns below. Together, a 6935 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6936 // (or (and (shl x, 1), 0xAAAAAAAA), 6937 // (and (srl x, 1), 0x55555555)) 6938 struct RISCVBitmanipPat { 6939 SDValue Op; 6940 unsigned ShAmt; 6941 bool IsSHL; 6942 6943 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6944 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6945 } 6946 }; 6947 6948 // Matches patterns of the form 6949 // (and (shl x, C2), (C1 << C2)) 6950 // (and (srl x, C2), C1) 6951 // (shl (and x, C1), C2) 6952 // (srl (and x, (C1 << C2)), C2) 6953 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6954 // The expected masks for each shift amount are specified in BitmanipMasks where 6955 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6956 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6957 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6958 // XLen is 64. 6959 static Optional<RISCVBitmanipPat> 6960 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6961 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6962 "Unexpected number of masks"); 6963 Optional<uint64_t> Mask; 6964 // Optionally consume a mask around the shift operation. 6965 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6966 Mask = Op.getConstantOperandVal(1); 6967 Op = Op.getOperand(0); 6968 } 6969 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6970 return None; 6971 bool IsSHL = Op.getOpcode() == ISD::SHL; 6972 6973 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6974 return None; 6975 uint64_t ShAmt = Op.getConstantOperandVal(1); 6976 6977 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6978 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6979 return None; 6980 // If we don't have enough masks for 64 bit, then we must be trying to 6981 // match SHFL so we're only allowed to shift 1/4 of the width. 6982 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6983 return None; 6984 6985 SDValue Src = Op.getOperand(0); 6986 6987 // The expected mask is shifted left when the AND is found around SHL 6988 // patterns. 6989 // ((x >> 1) & 0x55555555) 6990 // ((x << 1) & 0xAAAAAAAA) 6991 bool SHLExpMask = IsSHL; 6992 6993 if (!Mask) { 6994 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6995 // the mask is all ones: consume that now. 6996 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6997 Mask = Src.getConstantOperandVal(1); 6998 Src = Src.getOperand(0); 6999 // The expected mask is now in fact shifted left for SRL, so reverse the 7000 // decision. 7001 // ((x & 0xAAAAAAAA) >> 1) 7002 // ((x & 0x55555555) << 1) 7003 SHLExpMask = !SHLExpMask; 7004 } else { 7005 // Use a default shifted mask of all-ones if there's no AND, truncated 7006 // down to the expected width. This simplifies the logic later on. 7007 Mask = maskTrailingOnes<uint64_t>(Width); 7008 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7009 } 7010 } 7011 7012 unsigned MaskIdx = Log2_32(ShAmt); 7013 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7014 7015 if (SHLExpMask) 7016 ExpMask <<= ShAmt; 7017 7018 if (Mask != ExpMask) 7019 return None; 7020 7021 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7022 } 7023 7024 // Matches any of the following bit-manipulation patterns: 7025 // (and (shl x, 1), (0x55555555 << 1)) 7026 // (and (srl x, 1), 0x55555555) 7027 // (shl (and x, 0x55555555), 1) 7028 // (srl (and x, (0x55555555 << 1)), 1) 7029 // where the shift amount and mask may vary thus: 7030 // [1] = 0x55555555 / 0xAAAAAAAA 7031 // [2] = 0x33333333 / 0xCCCCCCCC 7032 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7033 // [8] = 0x00FF00FF / 0xFF00FF00 7034 // [16] = 0x0000FFFF / 0xFFFFFFFF 7035 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7036 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7037 // These are the unshifted masks which we use to match bit-manipulation 7038 // patterns. They may be shifted left in certain circumstances. 7039 static const uint64_t BitmanipMasks[] = { 7040 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7041 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7042 7043 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7044 } 7045 7046 // Match the following pattern as a GREVI(W) operation 7047 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7048 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7049 const RISCVSubtarget &Subtarget) { 7050 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7051 EVT VT = Op.getValueType(); 7052 7053 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7054 auto LHS = matchGREVIPat(Op.getOperand(0)); 7055 auto RHS = matchGREVIPat(Op.getOperand(1)); 7056 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7057 SDLoc DL(Op); 7058 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7059 DAG.getConstant(LHS->ShAmt, DL, VT)); 7060 } 7061 } 7062 return SDValue(); 7063 } 7064 7065 // Matches any the following pattern as a GORCI(W) operation 7066 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7067 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7068 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7069 // Note that with the variant of 3., 7070 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7071 // the inner pattern will first be matched as GREVI and then the outer 7072 // pattern will be matched to GORC via the first rule above. 7073 // 4. (or (rotl/rotr x, bitwidth/2), x) 7074 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7075 const RISCVSubtarget &Subtarget) { 7076 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7077 EVT VT = Op.getValueType(); 7078 7079 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7080 SDLoc DL(Op); 7081 SDValue Op0 = Op.getOperand(0); 7082 SDValue Op1 = Op.getOperand(1); 7083 7084 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7085 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7086 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7087 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7088 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7089 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7090 if ((Reverse.getOpcode() == ISD::ROTL || 7091 Reverse.getOpcode() == ISD::ROTR) && 7092 Reverse.getOperand(0) == X && 7093 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7094 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7095 if (RotAmt == (VT.getSizeInBits() / 2)) 7096 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7097 DAG.getConstant(RotAmt, DL, VT)); 7098 } 7099 return SDValue(); 7100 }; 7101 7102 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7103 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7104 return V; 7105 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7106 return V; 7107 7108 // OR is commutable so canonicalize its OR operand to the left 7109 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7110 std::swap(Op0, Op1); 7111 if (Op0.getOpcode() != ISD::OR) 7112 return SDValue(); 7113 SDValue OrOp0 = Op0.getOperand(0); 7114 SDValue OrOp1 = Op0.getOperand(1); 7115 auto LHS = matchGREVIPat(OrOp0); 7116 // OR is commutable so swap the operands and try again: x might have been 7117 // on the left 7118 if (!LHS) { 7119 std::swap(OrOp0, OrOp1); 7120 LHS = matchGREVIPat(OrOp0); 7121 } 7122 auto RHS = matchGREVIPat(Op1); 7123 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7124 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7125 DAG.getConstant(LHS->ShAmt, DL, VT)); 7126 } 7127 } 7128 return SDValue(); 7129 } 7130 7131 // Matches any of the following bit-manipulation patterns: 7132 // (and (shl x, 1), (0x22222222 << 1)) 7133 // (and (srl x, 1), 0x22222222) 7134 // (shl (and x, 0x22222222), 1) 7135 // (srl (and x, (0x22222222 << 1)), 1) 7136 // where the shift amount and mask may vary thus: 7137 // [1] = 0x22222222 / 0x44444444 7138 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7139 // [4] = 0x00F000F0 / 0x0F000F00 7140 // [8] = 0x0000FF00 / 0x00FF0000 7141 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7142 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7143 // These are the unshifted masks which we use to match bit-manipulation 7144 // patterns. They may be shifted left in certain circumstances. 7145 static const uint64_t BitmanipMasks[] = { 7146 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7147 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7148 7149 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7150 } 7151 7152 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7153 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7154 const RISCVSubtarget &Subtarget) { 7155 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7156 EVT VT = Op.getValueType(); 7157 7158 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7159 return SDValue(); 7160 7161 SDValue Op0 = Op.getOperand(0); 7162 SDValue Op1 = Op.getOperand(1); 7163 7164 // Or is commutable so canonicalize the second OR to the LHS. 7165 if (Op0.getOpcode() != ISD::OR) 7166 std::swap(Op0, Op1); 7167 if (Op0.getOpcode() != ISD::OR) 7168 return SDValue(); 7169 7170 // We found an inner OR, so our operands are the operands of the inner OR 7171 // and the other operand of the outer OR. 7172 SDValue A = Op0.getOperand(0); 7173 SDValue B = Op0.getOperand(1); 7174 SDValue C = Op1; 7175 7176 auto Match1 = matchSHFLPat(A); 7177 auto Match2 = matchSHFLPat(B); 7178 7179 // If neither matched, we failed. 7180 if (!Match1 && !Match2) 7181 return SDValue(); 7182 7183 // We had at least one match. if one failed, try the remaining C operand. 7184 if (!Match1) { 7185 std::swap(A, C); 7186 Match1 = matchSHFLPat(A); 7187 if (!Match1) 7188 return SDValue(); 7189 } else if (!Match2) { 7190 std::swap(B, C); 7191 Match2 = matchSHFLPat(B); 7192 if (!Match2) 7193 return SDValue(); 7194 } 7195 assert(Match1 && Match2); 7196 7197 // Make sure our matches pair up. 7198 if (!Match1->formsPairWith(*Match2)) 7199 return SDValue(); 7200 7201 // All the remains is to make sure C is an AND with the same input, that masks 7202 // out the bits that are being shuffled. 7203 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7204 C.getOperand(0) != Match1->Op) 7205 return SDValue(); 7206 7207 uint64_t Mask = C.getConstantOperandVal(1); 7208 7209 static const uint64_t BitmanipMasks[] = { 7210 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7211 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7212 }; 7213 7214 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7215 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7216 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7217 7218 if (Mask != ExpMask) 7219 return SDValue(); 7220 7221 SDLoc DL(Op); 7222 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7223 DAG.getConstant(Match1->ShAmt, DL, VT)); 7224 } 7225 7226 // Optimize (add (shl x, c0), (shl y, c1)) -> 7227 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7228 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7229 const RISCVSubtarget &Subtarget) { 7230 // Perform this optimization only in the zba extension. 7231 if (!Subtarget.hasStdExtZba()) 7232 return SDValue(); 7233 7234 // Skip for vector types and larger types. 7235 EVT VT = N->getValueType(0); 7236 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7237 return SDValue(); 7238 7239 // The two operand nodes must be SHL and have no other use. 7240 SDValue N0 = N->getOperand(0); 7241 SDValue N1 = N->getOperand(1); 7242 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7243 !N0->hasOneUse() || !N1->hasOneUse()) 7244 return SDValue(); 7245 7246 // Check c0 and c1. 7247 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7248 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7249 if (!N0C || !N1C) 7250 return SDValue(); 7251 int64_t C0 = N0C->getSExtValue(); 7252 int64_t C1 = N1C->getSExtValue(); 7253 if (C0 <= 0 || C1 <= 0) 7254 return SDValue(); 7255 7256 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7257 int64_t Bits = std::min(C0, C1); 7258 int64_t Diff = std::abs(C0 - C1); 7259 if (Diff != 1 && Diff != 2 && Diff != 3) 7260 return SDValue(); 7261 7262 // Build nodes. 7263 SDLoc DL(N); 7264 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7265 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7266 SDValue NA0 = 7267 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7268 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7269 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7270 } 7271 7272 // Combine 7273 // ROTR ((GREV x, 24), 16) -> (GREVI x, 8) 7274 // ROTL ((GREV x, 24), 16) -> (GREVI x, 8) 7275 // RORW ((GREVW x, 24), 16) -> (GREVIW x, 8) 7276 // ROLW ((GREVW x, 24), 16) -> (GREVIW x, 8) 7277 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG) { 7278 SDValue Src = N->getOperand(0); 7279 SDLoc DL(N); 7280 unsigned Opc; 7281 7282 if ((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL) && 7283 Src.getOpcode() == RISCVISD::GREV) 7284 Opc = RISCVISD::GREV; 7285 else if ((N->getOpcode() == RISCVISD::RORW || 7286 N->getOpcode() == RISCVISD::ROLW) && 7287 Src.getOpcode() == RISCVISD::GREVW) 7288 Opc = RISCVISD::GREVW; 7289 else 7290 return SDValue(); 7291 7292 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7293 !isa<ConstantSDNode>(Src.getOperand(1))) 7294 return SDValue(); 7295 7296 unsigned ShAmt1 = N->getConstantOperandVal(1); 7297 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7298 if (ShAmt1 != 16 && ShAmt2 != 24) 7299 return SDValue(); 7300 7301 Src = Src.getOperand(0); 7302 return DAG.getNode(Opc, DL, N->getValueType(0), Src, 7303 DAG.getConstant(8, DL, N->getOperand(1).getValueType())); 7304 } 7305 7306 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7307 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7308 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7309 // not undo itself, but they are redundant. 7310 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7311 SDValue Src = N->getOperand(0); 7312 7313 if (Src.getOpcode() != N->getOpcode()) 7314 return SDValue(); 7315 7316 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7317 !isa<ConstantSDNode>(Src.getOperand(1))) 7318 return SDValue(); 7319 7320 unsigned ShAmt1 = N->getConstantOperandVal(1); 7321 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7322 Src = Src.getOperand(0); 7323 7324 unsigned CombinedShAmt; 7325 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 7326 CombinedShAmt = ShAmt1 | ShAmt2; 7327 else 7328 CombinedShAmt = ShAmt1 ^ ShAmt2; 7329 7330 if (CombinedShAmt == 0) 7331 return Src; 7332 7333 SDLoc DL(N); 7334 return DAG.getNode( 7335 N->getOpcode(), DL, N->getValueType(0), Src, 7336 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7337 } 7338 7339 // Combine a constant select operand into its use: 7340 // 7341 // (and (select cond, -1, c), x) 7342 // -> (select cond, x, (and x, c)) [AllOnes=1] 7343 // (or (select cond, 0, c), x) 7344 // -> (select cond, x, (or x, c)) [AllOnes=0] 7345 // (xor (select cond, 0, c), x) 7346 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7347 // (add (select cond, 0, c), x) 7348 // -> (select cond, x, (add x, c)) [AllOnes=0] 7349 // (sub x, (select cond, 0, c)) 7350 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7351 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7352 SelectionDAG &DAG, bool AllOnes) { 7353 EVT VT = N->getValueType(0); 7354 7355 // Skip vectors. 7356 if (VT.isVector()) 7357 return SDValue(); 7358 7359 if ((Slct.getOpcode() != ISD::SELECT && 7360 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7361 !Slct.hasOneUse()) 7362 return SDValue(); 7363 7364 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7365 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7366 }; 7367 7368 bool SwapSelectOps; 7369 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7370 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7371 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7372 SDValue NonConstantVal; 7373 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7374 SwapSelectOps = false; 7375 NonConstantVal = FalseVal; 7376 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7377 SwapSelectOps = true; 7378 NonConstantVal = TrueVal; 7379 } else 7380 return SDValue(); 7381 7382 // Slct is now know to be the desired identity constant when CC is true. 7383 TrueVal = OtherOp; 7384 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7385 // Unless SwapSelectOps says the condition should be false. 7386 if (SwapSelectOps) 7387 std::swap(TrueVal, FalseVal); 7388 7389 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7390 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7391 {Slct.getOperand(0), Slct.getOperand(1), 7392 Slct.getOperand(2), TrueVal, FalseVal}); 7393 7394 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7395 {Slct.getOperand(0), TrueVal, FalseVal}); 7396 } 7397 7398 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7399 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7400 bool AllOnes) { 7401 SDValue N0 = N->getOperand(0); 7402 SDValue N1 = N->getOperand(1); 7403 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7404 return Result; 7405 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7406 return Result; 7407 return SDValue(); 7408 } 7409 7410 // Transform (add (mul x, c0), c1) -> 7411 // (add (mul (add x, c1/c0), c0), c1%c0). 7412 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7413 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7414 // to an infinite loop in DAGCombine if transformed. 7415 // Or transform (add (mul x, c0), c1) -> 7416 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7417 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7418 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7419 // lead to an infinite loop in DAGCombine if transformed. 7420 // Or transform (add (mul x, c0), c1) -> 7421 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7422 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7423 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7424 // lead to an infinite loop in DAGCombine if transformed. 7425 // Or transform (add (mul x, c0), c1) -> 7426 // (mul (add x, c1/c0), c0). 7427 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7428 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7429 const RISCVSubtarget &Subtarget) { 7430 // Skip for vector types and larger types. 7431 EVT VT = N->getValueType(0); 7432 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7433 return SDValue(); 7434 // The first operand node must be a MUL and has no other use. 7435 SDValue N0 = N->getOperand(0); 7436 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7437 return SDValue(); 7438 // Check if c0 and c1 match above conditions. 7439 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7440 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7441 if (!N0C || !N1C) 7442 return SDValue(); 7443 // If N0C has multiple uses it's possible one of the cases in 7444 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7445 // in an infinite loop. 7446 if (!N0C->hasOneUse()) 7447 return SDValue(); 7448 int64_t C0 = N0C->getSExtValue(); 7449 int64_t C1 = N1C->getSExtValue(); 7450 int64_t CA, CB; 7451 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7452 return SDValue(); 7453 // Search for proper CA (non-zero) and CB that both are simm12. 7454 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7455 !isInt<12>(C0 * (C1 / C0))) { 7456 CA = C1 / C0; 7457 CB = C1 % C0; 7458 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7459 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7460 CA = C1 / C0 + 1; 7461 CB = C1 % C0 - C0; 7462 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7463 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7464 CA = C1 / C0 - 1; 7465 CB = C1 % C0 + C0; 7466 } else 7467 return SDValue(); 7468 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7469 SDLoc DL(N); 7470 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7471 DAG.getConstant(CA, DL, VT)); 7472 SDValue New1 = 7473 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7474 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7475 } 7476 7477 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7478 const RISCVSubtarget &Subtarget) { 7479 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7480 return V; 7481 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7482 return V; 7483 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7484 // (select lhs, rhs, cc, x, (add x, y)) 7485 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7486 } 7487 7488 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7489 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7490 // (select lhs, rhs, cc, x, (sub x, y)) 7491 SDValue N0 = N->getOperand(0); 7492 SDValue N1 = N->getOperand(1); 7493 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7494 } 7495 7496 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7497 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7498 // (select lhs, rhs, cc, x, (and x, y)) 7499 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7500 } 7501 7502 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7503 const RISCVSubtarget &Subtarget) { 7504 if (Subtarget.hasStdExtZbp()) { 7505 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7506 return GREV; 7507 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7508 return GORC; 7509 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7510 return SHFL; 7511 } 7512 7513 // fold (or (select cond, 0, y), x) -> 7514 // (select cond, x, (or x, y)) 7515 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7516 } 7517 7518 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7519 // fold (xor (select cond, 0, y), x) -> 7520 // (select cond, x, (xor x, y)) 7521 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7522 } 7523 7524 static SDValue performSIGN_EXTEND_INREG(SDNode *N, SelectionDAG &DAG) { 7525 SDValue Src = N->getOperand(0); 7526 7527 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 7528 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7529 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 7530 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), N->getValueType(0), 7531 Src.getOperand(0)); 7532 7533 return SDValue(); 7534 } 7535 7536 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 7537 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 7538 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 7539 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 7540 // ADDW/SUBW/MULW. 7541 static SDValue performANY_EXTENDCombine(SDNode *N, 7542 TargetLowering::DAGCombinerInfo &DCI, 7543 const RISCVSubtarget &Subtarget) { 7544 if (!Subtarget.is64Bit()) 7545 return SDValue(); 7546 7547 SelectionDAG &DAG = DCI.DAG; 7548 7549 SDValue Src = N->getOperand(0); 7550 EVT VT = N->getValueType(0); 7551 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 7552 return SDValue(); 7553 7554 // The opcode must be one that can implicitly sign_extend. 7555 // FIXME: Additional opcodes. 7556 switch (Src.getOpcode()) { 7557 default: 7558 return SDValue(); 7559 case ISD::MUL: 7560 if (!Subtarget.hasStdExtM()) 7561 return SDValue(); 7562 LLVM_FALLTHROUGH; 7563 case ISD::ADD: 7564 case ISD::SUB: 7565 break; 7566 } 7567 7568 // Only handle cases where the result is used by a CopyToReg. That likely 7569 // means the value is a liveout of the basic block. This helps prevent 7570 // infinite combine loops like PR51206. 7571 if (none_of(N->uses(), 7572 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 7573 return SDValue(); 7574 7575 SmallVector<SDNode *, 4> SetCCs; 7576 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 7577 UE = Src.getNode()->use_end(); 7578 UI != UE; ++UI) { 7579 SDNode *User = *UI; 7580 if (User == N) 7581 continue; 7582 if (UI.getUse().getResNo() != Src.getResNo()) 7583 continue; 7584 // All i32 setccs are legalized by sign extending operands. 7585 if (User->getOpcode() == ISD::SETCC) { 7586 SetCCs.push_back(User); 7587 continue; 7588 } 7589 // We don't know if we can extend this user. 7590 break; 7591 } 7592 7593 // If we don't have any SetCCs, this isn't worthwhile. 7594 if (SetCCs.empty()) 7595 return SDValue(); 7596 7597 SDLoc DL(N); 7598 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 7599 DCI.CombineTo(N, SExt); 7600 7601 // Promote all the setccs. 7602 for (SDNode *SetCC : SetCCs) { 7603 SmallVector<SDValue, 4> Ops; 7604 7605 for (unsigned j = 0; j != 2; ++j) { 7606 SDValue SOp = SetCC->getOperand(j); 7607 if (SOp == Src) 7608 Ops.push_back(SExt); 7609 else 7610 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 7611 } 7612 7613 Ops.push_back(SetCC->getOperand(2)); 7614 DCI.CombineTo(SetCC, 7615 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7616 } 7617 return SDValue(N, 0); 7618 } 7619 7620 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7621 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7622 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7623 bool Commute = false) { 7624 assert((N->getOpcode() == RISCVISD::ADD_VL || 7625 N->getOpcode() == RISCVISD::SUB_VL) && 7626 "Unexpected opcode"); 7627 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7628 SDValue Op0 = N->getOperand(0); 7629 SDValue Op1 = N->getOperand(1); 7630 if (Commute) 7631 std::swap(Op0, Op1); 7632 7633 MVT VT = N->getSimpleValueType(0); 7634 7635 // Determine the narrow size for a widening add/sub. 7636 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7637 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7638 VT.getVectorElementCount()); 7639 7640 SDValue Mask = N->getOperand(2); 7641 SDValue VL = N->getOperand(3); 7642 7643 SDLoc DL(N); 7644 7645 // If the RHS is a sext or zext, we can form a widening op. 7646 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7647 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7648 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7649 unsigned ExtOpc = Op1.getOpcode(); 7650 Op1 = Op1.getOperand(0); 7651 // Re-introduce narrower extends if needed. 7652 if (Op1.getValueType() != NarrowVT) 7653 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7654 7655 unsigned WOpc; 7656 if (ExtOpc == RISCVISD::VSEXT_VL) 7657 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7658 else 7659 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7660 7661 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7662 } 7663 7664 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7665 // sext/zext? 7666 7667 return SDValue(); 7668 } 7669 7670 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7671 // vwsub(u).vv/vx. 7672 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7673 SDValue Op0 = N->getOperand(0); 7674 SDValue Op1 = N->getOperand(1); 7675 SDValue Mask = N->getOperand(2); 7676 SDValue VL = N->getOperand(3); 7677 7678 MVT VT = N->getSimpleValueType(0); 7679 MVT NarrowVT = Op1.getSimpleValueType(); 7680 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 7681 7682 unsigned VOpc; 7683 switch (N->getOpcode()) { 7684 default: llvm_unreachable("Unexpected opcode"); 7685 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 7686 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 7687 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 7688 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 7689 } 7690 7691 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 7692 N->getOpcode() == RISCVISD::VWSUB_W_VL; 7693 7694 SDLoc DL(N); 7695 7696 // If the LHS is a sext or zext, we can narrow this op to the same size as 7697 // the RHS. 7698 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 7699 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 7700 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 7701 unsigned ExtOpc = Op0.getOpcode(); 7702 Op0 = Op0.getOperand(0); 7703 // Re-introduce narrower extends if needed. 7704 if (Op0.getValueType() != NarrowVT) 7705 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7706 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 7707 } 7708 7709 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 7710 N->getOpcode() == RISCVISD::VWADDU_W_VL; 7711 7712 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 7713 // to commute and use a vwadd(u).vx instead. 7714 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 7715 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 7716 Op0 = Op0.getOperand(1); 7717 7718 // See if have enough sign bits or zero bits in the scalar to use a 7719 // widening add/sub by splatting to smaller element size. 7720 unsigned EltBits = VT.getScalarSizeInBits(); 7721 unsigned ScalarBits = Op0.getValueSizeInBits(); 7722 // Make sure we're getting all element bits from the scalar register. 7723 // FIXME: Support implicit sign extension of vmv.v.x? 7724 if (ScalarBits < EltBits) 7725 return SDValue(); 7726 7727 if (IsSigned) { 7728 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 7729 return SDValue(); 7730 } else { 7731 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7732 if (!DAG.MaskedValueIsZero(Op0, Mask)) 7733 return SDValue(); 7734 } 7735 7736 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7737 DAG.getUNDEF(NarrowVT), Op0, VL); 7738 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 7739 } 7740 7741 return SDValue(); 7742 } 7743 7744 // Try to form VWMUL, VWMULU or VWMULSU. 7745 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 7746 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 7747 bool Commute) { 7748 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7749 SDValue Op0 = N->getOperand(0); 7750 SDValue Op1 = N->getOperand(1); 7751 if (Commute) 7752 std::swap(Op0, Op1); 7753 7754 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7755 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7756 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 7757 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7758 return SDValue(); 7759 7760 SDValue Mask = N->getOperand(2); 7761 SDValue VL = N->getOperand(3); 7762 7763 // Make sure the mask and VL match. 7764 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7765 return SDValue(); 7766 7767 MVT VT = N->getSimpleValueType(0); 7768 7769 // Determine the narrow size for a widening multiply. 7770 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7771 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7772 VT.getVectorElementCount()); 7773 7774 SDLoc DL(N); 7775 7776 // See if the other operand is the same opcode. 7777 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 7778 if (!Op1.hasOneUse()) 7779 return SDValue(); 7780 7781 // Make sure the mask and VL match. 7782 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7783 return SDValue(); 7784 7785 Op1 = Op1.getOperand(0); 7786 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7787 // The operand is a splat of a scalar. 7788 7789 // The pasthru must be undef for tail agnostic 7790 if (!Op1.getOperand(0).isUndef()) 7791 return SDValue(); 7792 // The VL must be the same. 7793 if (Op1.getOperand(2) != VL) 7794 return SDValue(); 7795 7796 // Get the scalar value. 7797 Op1 = Op1.getOperand(1); 7798 7799 // See if have enough sign bits or zero bits in the scalar to use a 7800 // widening multiply by splatting to smaller element size. 7801 unsigned EltBits = VT.getScalarSizeInBits(); 7802 unsigned ScalarBits = Op1.getValueSizeInBits(); 7803 // Make sure we're getting all element bits from the scalar register. 7804 // FIXME: Support implicit sign extension of vmv.v.x? 7805 if (ScalarBits < EltBits) 7806 return SDValue(); 7807 7808 // If the LHS is a sign extend, try to use vwmul. 7809 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 7810 // Can use vwmul. 7811 } else { 7812 // Otherwise try to use vwmulu or vwmulsu. 7813 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7814 if (DAG.MaskedValueIsZero(Op1, Mask)) 7815 IsVWMULSU = IsSignExt; 7816 else 7817 return SDValue(); 7818 } 7819 7820 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7821 DAG.getUNDEF(NarrowVT), Op1, VL); 7822 } else 7823 return SDValue(); 7824 7825 Op0 = Op0.getOperand(0); 7826 7827 // Re-introduce narrower extends if needed. 7828 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7829 if (Op0.getValueType() != NarrowVT) 7830 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7831 // vwmulsu requires second operand to be zero extended. 7832 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 7833 if (Op1.getValueType() != NarrowVT) 7834 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7835 7836 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 7837 if (!IsVWMULSU) 7838 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7839 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7840 } 7841 7842 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 7843 switch (Op.getOpcode()) { 7844 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 7845 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 7846 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 7847 case ISD::FCEIL: return RISCVFPRndMode::RUP; 7848 case ISD::FROUND: return RISCVFPRndMode::RMM; 7849 } 7850 7851 return RISCVFPRndMode::Invalid; 7852 } 7853 7854 // Fold 7855 // (fp_to_int (froundeven X)) -> fcvt X, rne 7856 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7857 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7858 // (fp_to_int (fceil X)) -> fcvt X, rup 7859 // (fp_to_int (fround X)) -> fcvt X, rmm 7860 static SDValue performFP_TO_INTCombine(SDNode *N, 7861 TargetLowering::DAGCombinerInfo &DCI, 7862 const RISCVSubtarget &Subtarget) { 7863 SelectionDAG &DAG = DCI.DAG; 7864 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7865 MVT XLenVT = Subtarget.getXLenVT(); 7866 7867 // Only handle XLen or i32 types. Other types narrower than XLen will 7868 // eventually be legalized to XLenVT. 7869 EVT VT = N->getValueType(0); 7870 if (VT != MVT::i32 && VT != XLenVT) 7871 return SDValue(); 7872 7873 SDValue Src = N->getOperand(0); 7874 7875 // Ensure the FP type is also legal. 7876 if (!TLI.isTypeLegal(Src.getValueType())) 7877 return SDValue(); 7878 7879 // Don't do this for f16 with Zfhmin and not Zfh. 7880 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7881 return SDValue(); 7882 7883 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7884 if (FRM == RISCVFPRndMode::Invalid) 7885 return SDValue(); 7886 7887 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7888 7889 unsigned Opc; 7890 if (VT == XLenVT) 7891 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7892 else 7893 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7894 7895 SDLoc DL(N); 7896 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 7897 DAG.getTargetConstant(FRM, DL, XLenVT)); 7898 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 7899 } 7900 7901 // Fold 7902 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 7903 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 7904 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 7905 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 7906 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 7907 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 7908 TargetLowering::DAGCombinerInfo &DCI, 7909 const RISCVSubtarget &Subtarget) { 7910 SelectionDAG &DAG = DCI.DAG; 7911 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7912 MVT XLenVT = Subtarget.getXLenVT(); 7913 7914 // Only handle XLen types. Other types narrower than XLen will eventually be 7915 // legalized to XLenVT. 7916 EVT DstVT = N->getValueType(0); 7917 if (DstVT != XLenVT) 7918 return SDValue(); 7919 7920 SDValue Src = N->getOperand(0); 7921 7922 // Ensure the FP type is also legal. 7923 if (!TLI.isTypeLegal(Src.getValueType())) 7924 return SDValue(); 7925 7926 // Don't do this for f16 with Zfhmin and not Zfh. 7927 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7928 return SDValue(); 7929 7930 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7931 7932 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7933 if (FRM == RISCVFPRndMode::Invalid) 7934 return SDValue(); 7935 7936 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 7937 7938 unsigned Opc; 7939 if (SatVT == DstVT) 7940 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7941 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 7942 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7943 else 7944 return SDValue(); 7945 // FIXME: Support other SatVTs by clamping before or after the conversion. 7946 7947 Src = Src.getOperand(0); 7948 7949 SDLoc DL(N); 7950 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 7951 DAG.getTargetConstant(FRM, DL, XLenVT)); 7952 7953 // RISCV FP-to-int conversions saturate to the destination register size, but 7954 // don't produce 0 for nan. 7955 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 7956 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 7957 } 7958 7959 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 7960 DAGCombinerInfo &DCI) const { 7961 SelectionDAG &DAG = DCI.DAG; 7962 7963 // Helper to call SimplifyDemandedBits on an operand of N where only some low 7964 // bits are demanded. N will be added to the Worklist if it was not deleted. 7965 // Caller should return SDValue(N, 0) if this returns true. 7966 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 7967 SDValue Op = N->getOperand(OpNo); 7968 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 7969 if (!SimplifyDemandedBits(Op, Mask, DCI)) 7970 return false; 7971 7972 if (N->getOpcode() != ISD::DELETED_NODE) 7973 DCI.AddToWorklist(N); 7974 return true; 7975 }; 7976 7977 switch (N->getOpcode()) { 7978 default: 7979 break; 7980 case RISCVISD::SplitF64: { 7981 SDValue Op0 = N->getOperand(0); 7982 // If the input to SplitF64 is just BuildPairF64 then the operation is 7983 // redundant. Instead, use BuildPairF64's operands directly. 7984 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 7985 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 7986 7987 if (Op0->isUndef()) { 7988 SDValue Lo = DAG.getUNDEF(MVT::i32); 7989 SDValue Hi = DAG.getUNDEF(MVT::i32); 7990 return DCI.CombineTo(N, Lo, Hi); 7991 } 7992 7993 SDLoc DL(N); 7994 7995 // It's cheaper to materialise two 32-bit integers than to load a double 7996 // from the constant pool and transfer it to integer registers through the 7997 // stack. 7998 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 7999 APInt V = C->getValueAPF().bitcastToAPInt(); 8000 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8001 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8002 return DCI.CombineTo(N, Lo, Hi); 8003 } 8004 8005 // This is a target-specific version of a DAGCombine performed in 8006 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8007 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8008 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8009 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8010 !Op0.getNode()->hasOneUse()) 8011 break; 8012 SDValue NewSplitF64 = 8013 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8014 Op0.getOperand(0)); 8015 SDValue Lo = NewSplitF64.getValue(0); 8016 SDValue Hi = NewSplitF64.getValue(1); 8017 APInt SignBit = APInt::getSignMask(32); 8018 if (Op0.getOpcode() == ISD::FNEG) { 8019 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8020 DAG.getConstant(SignBit, DL, MVT::i32)); 8021 return DCI.CombineTo(N, Lo, NewHi); 8022 } 8023 assert(Op0.getOpcode() == ISD::FABS); 8024 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8025 DAG.getConstant(~SignBit, DL, MVT::i32)); 8026 return DCI.CombineTo(N, Lo, NewHi); 8027 } 8028 case RISCVISD::SLLW: 8029 case RISCVISD::SRAW: 8030 case RISCVISD::SRLW: 8031 case RISCVISD::ROLW: 8032 case RISCVISD::RORW: { 8033 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8034 if (SimplifyDemandedLowBitsHelper(0, 32) || 8035 SimplifyDemandedLowBitsHelper(1, 5)) 8036 return SDValue(N, 0); 8037 8038 return combineROTR_ROTL_RORW_ROLW(N, DAG); 8039 } 8040 case ISD::ROTR: 8041 case ISD::ROTL: 8042 return combineROTR_ROTL_RORW_ROLW(N, DAG); 8043 case RISCVISD::CLZW: 8044 case RISCVISD::CTZW: { 8045 // Only the lower 32 bits of the first operand are read 8046 if (SimplifyDemandedLowBitsHelper(0, 32)) 8047 return SDValue(N, 0); 8048 break; 8049 } 8050 case RISCVISD::GREV: 8051 case RISCVISD::GORC: { 8052 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8053 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8054 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8055 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8056 return SDValue(N, 0); 8057 8058 return combineGREVI_GORCI(N, DAG); 8059 } 8060 case RISCVISD::GREVW: 8061 case RISCVISD::GORCW: { 8062 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8063 if (SimplifyDemandedLowBitsHelper(0, 32) || 8064 SimplifyDemandedLowBitsHelper(1, 5)) 8065 return SDValue(N, 0); 8066 8067 return combineGREVI_GORCI(N, DAG); 8068 } 8069 case RISCVISD::SHFL: 8070 case RISCVISD::UNSHFL: { 8071 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8072 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8073 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8074 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8075 return SDValue(N, 0); 8076 8077 break; 8078 } 8079 case RISCVISD::SHFLW: 8080 case RISCVISD::UNSHFLW: { 8081 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8082 if (SimplifyDemandedLowBitsHelper(0, 32) || 8083 SimplifyDemandedLowBitsHelper(1, 4)) 8084 return SDValue(N, 0); 8085 8086 break; 8087 } 8088 case RISCVISD::BCOMPRESSW: 8089 case RISCVISD::BDECOMPRESSW: { 8090 // Only the lower 32 bits of LHS and RHS are read. 8091 if (SimplifyDemandedLowBitsHelper(0, 32) || 8092 SimplifyDemandedLowBitsHelper(1, 32)) 8093 return SDValue(N, 0); 8094 8095 break; 8096 } 8097 case RISCVISD::FMV_X_ANYEXTH: 8098 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8099 SDLoc DL(N); 8100 SDValue Op0 = N->getOperand(0); 8101 MVT VT = N->getSimpleValueType(0); 8102 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8103 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8104 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8105 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8106 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8107 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8108 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8109 assert(Op0.getOperand(0).getValueType() == VT && 8110 "Unexpected value type!"); 8111 return Op0.getOperand(0); 8112 } 8113 8114 // This is a target-specific version of a DAGCombine performed in 8115 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8116 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8117 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8118 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8119 !Op0.getNode()->hasOneUse()) 8120 break; 8121 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8122 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8123 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8124 if (Op0.getOpcode() == ISD::FNEG) 8125 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8126 DAG.getConstant(SignBit, DL, VT)); 8127 8128 assert(Op0.getOpcode() == ISD::FABS); 8129 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8130 DAG.getConstant(~SignBit, DL, VT)); 8131 } 8132 case ISD::ADD: 8133 return performADDCombine(N, DAG, Subtarget); 8134 case ISD::SUB: 8135 return performSUBCombine(N, DAG); 8136 case ISD::AND: 8137 return performANDCombine(N, DAG); 8138 case ISD::OR: 8139 return performORCombine(N, DAG, Subtarget); 8140 case ISD::XOR: 8141 return performXORCombine(N, DAG); 8142 case ISD::SIGN_EXTEND_INREG: 8143 return performSIGN_EXTEND_INREG(N, DAG); 8144 case ISD::ANY_EXTEND: 8145 return performANY_EXTENDCombine(N, DCI, Subtarget); 8146 case ISD::ZERO_EXTEND: 8147 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8148 // type legalization. This is safe because fp_to_uint produces poison if 8149 // it overflows. 8150 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8151 SDValue Src = N->getOperand(0); 8152 if (Src.getOpcode() == ISD::FP_TO_UINT && 8153 isTypeLegal(Src.getOperand(0).getValueType())) 8154 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8155 Src.getOperand(0)); 8156 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8157 isTypeLegal(Src.getOperand(1).getValueType())) { 8158 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8159 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8160 Src.getOperand(0), Src.getOperand(1)); 8161 DCI.CombineTo(N, Res); 8162 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8163 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8164 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8165 } 8166 } 8167 return SDValue(); 8168 case RISCVISD::SELECT_CC: { 8169 // Transform 8170 SDValue LHS = N->getOperand(0); 8171 SDValue RHS = N->getOperand(1); 8172 SDValue TrueV = N->getOperand(3); 8173 SDValue FalseV = N->getOperand(4); 8174 8175 // If the True and False values are the same, we don't need a select_cc. 8176 if (TrueV == FalseV) 8177 return TrueV; 8178 8179 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8180 if (!ISD::isIntEqualitySetCC(CCVal)) 8181 break; 8182 8183 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8184 // (select_cc X, Y, lt, trueV, falseV) 8185 // Sometimes the setcc is introduced after select_cc has been formed. 8186 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8187 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8188 // If we're looking for eq 0 instead of ne 0, we need to invert the 8189 // condition. 8190 bool Invert = CCVal == ISD::SETEQ; 8191 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8192 if (Invert) 8193 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8194 8195 SDLoc DL(N); 8196 RHS = LHS.getOperand(1); 8197 LHS = LHS.getOperand(0); 8198 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8199 8200 SDValue TargetCC = DAG.getCondCode(CCVal); 8201 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8202 {LHS, RHS, TargetCC, TrueV, FalseV}); 8203 } 8204 8205 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8206 // (select_cc X, Y, eq/ne, trueV, falseV) 8207 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8208 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8209 {LHS.getOperand(0), LHS.getOperand(1), 8210 N->getOperand(2), TrueV, FalseV}); 8211 // (select_cc X, 1, setne, trueV, falseV) -> 8212 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8213 // This can occur when legalizing some floating point comparisons. 8214 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8215 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8216 SDLoc DL(N); 8217 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8218 SDValue TargetCC = DAG.getCondCode(CCVal); 8219 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8220 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8221 {LHS, RHS, TargetCC, TrueV, FalseV}); 8222 } 8223 8224 break; 8225 } 8226 case RISCVISD::BR_CC: { 8227 SDValue LHS = N->getOperand(1); 8228 SDValue RHS = N->getOperand(2); 8229 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8230 if (!ISD::isIntEqualitySetCC(CCVal)) 8231 break; 8232 8233 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8234 // (br_cc X, Y, lt, dest) 8235 // Sometimes the setcc is introduced after br_cc has been formed. 8236 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8237 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8238 // If we're looking for eq 0 instead of ne 0, we need to invert the 8239 // condition. 8240 bool Invert = CCVal == ISD::SETEQ; 8241 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8242 if (Invert) 8243 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8244 8245 SDLoc DL(N); 8246 RHS = LHS.getOperand(1); 8247 LHS = LHS.getOperand(0); 8248 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8249 8250 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8251 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8252 N->getOperand(4)); 8253 } 8254 8255 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8256 // (br_cc X, Y, eq/ne, trueV, falseV) 8257 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8258 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8259 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8260 N->getOperand(3), N->getOperand(4)); 8261 8262 // (br_cc X, 1, setne, br_cc) -> 8263 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8264 // This can occur when legalizing some floating point comparisons. 8265 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8266 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8267 SDLoc DL(N); 8268 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8269 SDValue TargetCC = DAG.getCondCode(CCVal); 8270 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8271 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8272 N->getOperand(0), LHS, RHS, TargetCC, 8273 N->getOperand(4)); 8274 } 8275 break; 8276 } 8277 case ISD::FP_TO_SINT: 8278 case ISD::FP_TO_UINT: 8279 return performFP_TO_INTCombine(N, DCI, Subtarget); 8280 case ISD::FP_TO_SINT_SAT: 8281 case ISD::FP_TO_UINT_SAT: 8282 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8283 case ISD::FCOPYSIGN: { 8284 EVT VT = N->getValueType(0); 8285 if (!VT.isVector()) 8286 break; 8287 // There is a form of VFSGNJ which injects the negated sign of its second 8288 // operand. Try and bubble any FNEG up after the extend/round to produce 8289 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8290 // TRUNC=1. 8291 SDValue In2 = N->getOperand(1); 8292 // Avoid cases where the extend/round has multiple uses, as duplicating 8293 // those is typically more expensive than removing a fneg. 8294 if (!In2.hasOneUse()) 8295 break; 8296 if (In2.getOpcode() != ISD::FP_EXTEND && 8297 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8298 break; 8299 In2 = In2.getOperand(0); 8300 if (In2.getOpcode() != ISD::FNEG) 8301 break; 8302 SDLoc DL(N); 8303 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8304 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8305 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8306 } 8307 case ISD::MGATHER: 8308 case ISD::MSCATTER: 8309 case ISD::VP_GATHER: 8310 case ISD::VP_SCATTER: { 8311 if (!DCI.isBeforeLegalize()) 8312 break; 8313 SDValue Index, ScaleOp; 8314 bool IsIndexScaled = false; 8315 bool IsIndexSigned = false; 8316 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8317 Index = VPGSN->getIndex(); 8318 ScaleOp = VPGSN->getScale(); 8319 IsIndexScaled = VPGSN->isIndexScaled(); 8320 IsIndexSigned = VPGSN->isIndexSigned(); 8321 } else { 8322 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8323 Index = MGSN->getIndex(); 8324 ScaleOp = MGSN->getScale(); 8325 IsIndexScaled = MGSN->isIndexScaled(); 8326 IsIndexSigned = MGSN->isIndexSigned(); 8327 } 8328 EVT IndexVT = Index.getValueType(); 8329 MVT XLenVT = Subtarget.getXLenVT(); 8330 // RISCV indexed loads only support the "unsigned unscaled" addressing 8331 // mode, so anything else must be manually legalized. 8332 bool NeedsIdxLegalization = 8333 IsIndexScaled || 8334 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8335 if (!NeedsIdxLegalization) 8336 break; 8337 8338 SDLoc DL(N); 8339 8340 // Any index legalization should first promote to XLenVT, so we don't lose 8341 // bits when scaling. This may create an illegal index type so we let 8342 // LLVM's legalization take care of the splitting. 8343 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8344 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8345 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8346 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8347 DL, IndexVT, Index); 8348 } 8349 8350 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8351 if (IsIndexScaled && Scale != 1) { 8352 // Manually scale the indices by the element size. 8353 // TODO: Sanitize the scale operand here? 8354 // TODO: For VP nodes, should we use VP_SHL here? 8355 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8356 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8357 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8358 } 8359 8360 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8361 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8362 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8363 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8364 VPGN->getScale(), VPGN->getMask(), 8365 VPGN->getVectorLength()}, 8366 VPGN->getMemOperand(), NewIndexTy); 8367 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8368 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8369 {VPSN->getChain(), VPSN->getValue(), 8370 VPSN->getBasePtr(), Index, VPSN->getScale(), 8371 VPSN->getMask(), VPSN->getVectorLength()}, 8372 VPSN->getMemOperand(), NewIndexTy); 8373 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8374 return DAG.getMaskedGather( 8375 N->getVTList(), MGN->getMemoryVT(), DL, 8376 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8377 MGN->getBasePtr(), Index, MGN->getScale()}, 8378 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8379 const auto *MSN = cast<MaskedScatterSDNode>(N); 8380 return DAG.getMaskedScatter( 8381 N->getVTList(), MSN->getMemoryVT(), DL, 8382 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8383 Index, MSN->getScale()}, 8384 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8385 } 8386 case RISCVISD::SRA_VL: 8387 case RISCVISD::SRL_VL: 8388 case RISCVISD::SHL_VL: { 8389 SDValue ShAmt = N->getOperand(1); 8390 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8391 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8392 SDLoc DL(N); 8393 SDValue VL = N->getOperand(3); 8394 EVT VT = N->getValueType(0); 8395 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8396 ShAmt.getOperand(1), VL); 8397 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8398 N->getOperand(2), N->getOperand(3)); 8399 } 8400 break; 8401 } 8402 case ISD::SRA: 8403 case ISD::SRL: 8404 case ISD::SHL: { 8405 SDValue ShAmt = N->getOperand(1); 8406 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8407 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8408 SDLoc DL(N); 8409 EVT VT = N->getValueType(0); 8410 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8411 ShAmt.getOperand(1), 8412 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8413 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8414 } 8415 break; 8416 } 8417 case RISCVISD::ADD_VL: 8418 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8419 return V; 8420 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8421 case RISCVISD::SUB_VL: 8422 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8423 case RISCVISD::VWADD_W_VL: 8424 case RISCVISD::VWADDU_W_VL: 8425 case RISCVISD::VWSUB_W_VL: 8426 case RISCVISD::VWSUBU_W_VL: 8427 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8428 case RISCVISD::MUL_VL: 8429 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8430 return V; 8431 // Mul is commutative. 8432 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8433 case ISD::STORE: { 8434 auto *Store = cast<StoreSDNode>(N); 8435 SDValue Val = Store->getValue(); 8436 // Combine store of vmv.x.s to vse with VL of 1. 8437 // FIXME: Support FP. 8438 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8439 SDValue Src = Val.getOperand(0); 8440 EVT VecVT = Src.getValueType(); 8441 EVT MemVT = Store->getMemoryVT(); 8442 // The memory VT and the element type must match. 8443 if (VecVT.getVectorElementType() == MemVT) { 8444 SDLoc DL(N); 8445 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8446 return DAG.getStoreVP( 8447 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8448 DAG.getConstant(1, DL, MaskVT), 8449 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8450 Store->getMemOperand(), Store->getAddressingMode(), 8451 Store->isTruncatingStore(), /*IsCompress*/ false); 8452 } 8453 } 8454 8455 break; 8456 } 8457 case ISD::SPLAT_VECTOR: { 8458 EVT VT = N->getValueType(0); 8459 // Only perform this combine on legal MVT types. 8460 if (!isTypeLegal(VT)) 8461 break; 8462 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8463 DAG, Subtarget)) 8464 return Gather; 8465 break; 8466 } 8467 case RISCVISD::VMV_V_X_VL: { 8468 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8469 // scalar input. 8470 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8471 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8472 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8473 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8474 return SDValue(N, 0); 8475 8476 break; 8477 } 8478 case ISD::INTRINSIC_WO_CHAIN: { 8479 unsigned IntNo = N->getConstantOperandVal(0); 8480 switch (IntNo) { 8481 // By default we do not combine any intrinsic. 8482 default: 8483 return SDValue(); 8484 case Intrinsic::riscv_vcpop: 8485 case Intrinsic::riscv_vcpop_mask: 8486 case Intrinsic::riscv_vfirst: 8487 case Intrinsic::riscv_vfirst_mask: { 8488 SDValue VL = N->getOperand(2); 8489 if (IntNo == Intrinsic::riscv_vcpop_mask || 8490 IntNo == Intrinsic::riscv_vfirst_mask) 8491 VL = N->getOperand(3); 8492 if (!isNullConstant(VL)) 8493 return SDValue(); 8494 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8495 SDLoc DL(N); 8496 EVT VT = N->getValueType(0); 8497 if (IntNo == Intrinsic::riscv_vfirst || 8498 IntNo == Intrinsic::riscv_vfirst_mask) 8499 return DAG.getConstant(-1, DL, VT); 8500 return DAG.getConstant(0, DL, VT); 8501 } 8502 } 8503 } 8504 } 8505 8506 return SDValue(); 8507 } 8508 8509 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8510 const SDNode *N, CombineLevel Level) const { 8511 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8512 // materialised in fewer instructions than `(OP _, c1)`: 8513 // 8514 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8515 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8516 SDValue N0 = N->getOperand(0); 8517 EVT Ty = N0.getValueType(); 8518 if (Ty.isScalarInteger() && 8519 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8520 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8521 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8522 if (C1 && C2) { 8523 const APInt &C1Int = C1->getAPIntValue(); 8524 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8525 8526 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8527 // and the combine should happen, to potentially allow further combines 8528 // later. 8529 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8530 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8531 return true; 8532 8533 // We can materialise `c1` in an add immediate, so it's "free", and the 8534 // combine should be prevented. 8535 if (C1Int.getMinSignedBits() <= 64 && 8536 isLegalAddImmediate(C1Int.getSExtValue())) 8537 return false; 8538 8539 // Neither constant will fit into an immediate, so find materialisation 8540 // costs. 8541 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8542 Subtarget.getFeatureBits(), 8543 /*CompressionCost*/true); 8544 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8545 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8546 /*CompressionCost*/true); 8547 8548 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8549 // combine should be prevented. 8550 if (C1Cost < ShiftedC1Cost) 8551 return false; 8552 } 8553 } 8554 return true; 8555 } 8556 8557 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8558 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8559 TargetLoweringOpt &TLO) const { 8560 // Delay this optimization as late as possible. 8561 if (!TLO.LegalOps) 8562 return false; 8563 8564 EVT VT = Op.getValueType(); 8565 if (VT.isVector()) 8566 return false; 8567 8568 // Only handle AND for now. 8569 if (Op.getOpcode() != ISD::AND) 8570 return false; 8571 8572 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8573 if (!C) 8574 return false; 8575 8576 const APInt &Mask = C->getAPIntValue(); 8577 8578 // Clear all non-demanded bits initially. 8579 APInt ShrunkMask = Mask & DemandedBits; 8580 8581 // Try to make a smaller immediate by setting undemanded bits. 8582 8583 APInt ExpandedMask = Mask | ~DemandedBits; 8584 8585 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8586 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8587 }; 8588 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8589 if (NewMask == Mask) 8590 return true; 8591 SDLoc DL(Op); 8592 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8593 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8594 return TLO.CombineTo(Op, NewOp); 8595 }; 8596 8597 // If the shrunk mask fits in sign extended 12 bits, let the target 8598 // independent code apply it. 8599 if (ShrunkMask.isSignedIntN(12)) 8600 return false; 8601 8602 // Preserve (and X, 0xffff) when zext.h is supported. 8603 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8604 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8605 if (IsLegalMask(NewMask)) 8606 return UseMask(NewMask); 8607 } 8608 8609 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8610 if (VT == MVT::i64) { 8611 APInt NewMask = APInt(64, 0xffffffff); 8612 if (IsLegalMask(NewMask)) 8613 return UseMask(NewMask); 8614 } 8615 8616 // For the remaining optimizations, we need to be able to make a negative 8617 // number through a combination of mask and undemanded bits. 8618 if (!ExpandedMask.isNegative()) 8619 return false; 8620 8621 // What is the fewest number of bits we need to represent the negative number. 8622 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8623 8624 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8625 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8626 APInt NewMask = ShrunkMask; 8627 if (MinSignedBits <= 12) 8628 NewMask.setBitsFrom(11); 8629 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8630 NewMask.setBitsFrom(31); 8631 else 8632 return false; 8633 8634 // Check that our new mask is a subset of the demanded mask. 8635 assert(IsLegalMask(NewMask)); 8636 return UseMask(NewMask); 8637 } 8638 8639 static void computeGREV(APInt &Src, unsigned ShAmt) { 8640 ShAmt &= Src.getBitWidth() - 1; 8641 uint64_t x = Src.getZExtValue(); 8642 if (ShAmt & 1) 8643 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 8644 if (ShAmt & 2) 8645 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 8646 if (ShAmt & 4) 8647 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 8648 if (ShAmt & 8) 8649 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 8650 if (ShAmt & 16) 8651 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 8652 if (ShAmt & 32) 8653 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 8654 Src = x; 8655 } 8656 8657 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8658 KnownBits &Known, 8659 const APInt &DemandedElts, 8660 const SelectionDAG &DAG, 8661 unsigned Depth) const { 8662 unsigned BitWidth = Known.getBitWidth(); 8663 unsigned Opc = Op.getOpcode(); 8664 assert((Opc >= ISD::BUILTIN_OP_END || 8665 Opc == ISD::INTRINSIC_WO_CHAIN || 8666 Opc == ISD::INTRINSIC_W_CHAIN || 8667 Opc == ISD::INTRINSIC_VOID) && 8668 "Should use MaskedValueIsZero if you don't know whether Op" 8669 " is a target node!"); 8670 8671 Known.resetAll(); 8672 switch (Opc) { 8673 default: break; 8674 case RISCVISD::SELECT_CC: { 8675 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8676 // If we don't know any bits, early out. 8677 if (Known.isUnknown()) 8678 break; 8679 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8680 8681 // Only known if known in both the LHS and RHS. 8682 Known = KnownBits::commonBits(Known, Known2); 8683 break; 8684 } 8685 case RISCVISD::REMUW: { 8686 KnownBits Known2; 8687 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8688 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8689 // We only care about the lower 32 bits. 8690 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8691 // Restore the original width by sign extending. 8692 Known = Known.sext(BitWidth); 8693 break; 8694 } 8695 case RISCVISD::DIVUW: { 8696 KnownBits Known2; 8697 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8698 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8699 // We only care about the lower 32 bits. 8700 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8701 // Restore the original width by sign extending. 8702 Known = Known.sext(BitWidth); 8703 break; 8704 } 8705 case RISCVISD::CTZW: { 8706 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8707 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 8708 unsigned LowBits = Log2_32(PossibleTZ) + 1; 8709 Known.Zero.setBitsFrom(LowBits); 8710 break; 8711 } 8712 case RISCVISD::CLZW: { 8713 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8714 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 8715 unsigned LowBits = Log2_32(PossibleLZ) + 1; 8716 Known.Zero.setBitsFrom(LowBits); 8717 break; 8718 } 8719 case RISCVISD::GREV: 8720 case RISCVISD::GREVW: { 8721 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8722 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8723 if (Opc == RISCVISD::GREVW) 8724 Known = Known.trunc(32); 8725 unsigned ShAmt = C->getZExtValue(); 8726 computeGREV(Known.Zero, ShAmt); 8727 computeGREV(Known.One, ShAmt); 8728 if (Opc == RISCVISD::GREVW) 8729 Known = Known.sext(BitWidth); 8730 } 8731 break; 8732 } 8733 case RISCVISD::READ_VLENB: { 8734 // If we know the minimum VLen from Zvl extensions, we can use that to 8735 // determine the trailing zeros of VLENB. 8736 // FIXME: Limit to 128 bit vectors until we have more testing. 8737 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 8738 if (MinVLenB > 0) 8739 Known.Zero.setLowBits(Log2_32(MinVLenB)); 8740 // We assume VLENB is no more than 65536 / 8 bytes. 8741 Known.Zero.setBitsFrom(14); 8742 break; 8743 } 8744 case ISD::INTRINSIC_W_CHAIN: 8745 case ISD::INTRINSIC_WO_CHAIN: { 8746 unsigned IntNo = 8747 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 8748 switch (IntNo) { 8749 default: 8750 // We can't do anything for most intrinsics. 8751 break; 8752 case Intrinsic::riscv_vsetvli: 8753 case Intrinsic::riscv_vsetvlimax: 8754 case Intrinsic::riscv_vsetvli_opt: 8755 case Intrinsic::riscv_vsetvlimax_opt: 8756 // Assume that VL output is positive and would fit in an int32_t. 8757 // TODO: VLEN might be capped at 16 bits in a future V spec update. 8758 if (BitWidth >= 32) 8759 Known.Zero.setBitsFrom(31); 8760 break; 8761 } 8762 break; 8763 } 8764 } 8765 } 8766 8767 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 8768 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 8769 unsigned Depth) const { 8770 switch (Op.getOpcode()) { 8771 default: 8772 break; 8773 case RISCVISD::SELECT_CC: { 8774 unsigned Tmp = 8775 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 8776 if (Tmp == 1) return 1; // Early out. 8777 unsigned Tmp2 = 8778 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 8779 return std::min(Tmp, Tmp2); 8780 } 8781 case RISCVISD::SLLW: 8782 case RISCVISD::SRAW: 8783 case RISCVISD::SRLW: 8784 case RISCVISD::DIVW: 8785 case RISCVISD::DIVUW: 8786 case RISCVISD::REMUW: 8787 case RISCVISD::ROLW: 8788 case RISCVISD::RORW: 8789 case RISCVISD::GREVW: 8790 case RISCVISD::GORCW: 8791 case RISCVISD::FSLW: 8792 case RISCVISD::FSRW: 8793 case RISCVISD::SHFLW: 8794 case RISCVISD::UNSHFLW: 8795 case RISCVISD::BCOMPRESSW: 8796 case RISCVISD::BDECOMPRESSW: 8797 case RISCVISD::BFPW: 8798 case RISCVISD::FCVT_W_RV64: 8799 case RISCVISD::FCVT_WU_RV64: 8800 case RISCVISD::STRICT_FCVT_W_RV64: 8801 case RISCVISD::STRICT_FCVT_WU_RV64: 8802 // TODO: As the result is sign-extended, this is conservatively correct. A 8803 // more precise answer could be calculated for SRAW depending on known 8804 // bits in the shift amount. 8805 return 33; 8806 case RISCVISD::SHFL: 8807 case RISCVISD::UNSHFL: { 8808 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 8809 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 8810 // will stay within the upper 32 bits. If there were more than 32 sign bits 8811 // before there will be at least 33 sign bits after. 8812 if (Op.getValueType() == MVT::i64 && 8813 isa<ConstantSDNode>(Op.getOperand(1)) && 8814 (Op.getConstantOperandVal(1) & 0x10) == 0) { 8815 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 8816 if (Tmp > 32) 8817 return 33; 8818 } 8819 break; 8820 } 8821 case RISCVISD::VMV_X_S: { 8822 // The number of sign bits of the scalar result is computed by obtaining the 8823 // element type of the input vector operand, subtracting its width from the 8824 // XLEN, and then adding one (sign bit within the element type). If the 8825 // element type is wider than XLen, the least-significant XLEN bits are 8826 // taken. 8827 unsigned XLen = Subtarget.getXLen(); 8828 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 8829 if (EltBits <= XLen) 8830 return XLen - EltBits + 1; 8831 break; 8832 } 8833 } 8834 8835 return 1; 8836 } 8837 8838 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 8839 MachineBasicBlock *BB) { 8840 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 8841 8842 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 8843 // Should the count have wrapped while it was being read, we need to try 8844 // again. 8845 // ... 8846 // read: 8847 // rdcycleh x3 # load high word of cycle 8848 // rdcycle x2 # load low word of cycle 8849 // rdcycleh x4 # load high word of cycle 8850 // bne x3, x4, read # check if high word reads match, otherwise try again 8851 // ... 8852 8853 MachineFunction &MF = *BB->getParent(); 8854 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8855 MachineFunction::iterator It = ++BB->getIterator(); 8856 8857 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8858 MF.insert(It, LoopMBB); 8859 8860 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8861 MF.insert(It, DoneMBB); 8862 8863 // Transfer the remainder of BB and its successor edges to DoneMBB. 8864 DoneMBB->splice(DoneMBB->begin(), BB, 8865 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8866 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 8867 8868 BB->addSuccessor(LoopMBB); 8869 8870 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8871 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8872 Register LoReg = MI.getOperand(0).getReg(); 8873 Register HiReg = MI.getOperand(1).getReg(); 8874 DebugLoc DL = MI.getDebugLoc(); 8875 8876 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 8877 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 8878 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8879 .addReg(RISCV::X0); 8880 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 8881 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 8882 .addReg(RISCV::X0); 8883 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 8884 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8885 .addReg(RISCV::X0); 8886 8887 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 8888 .addReg(HiReg) 8889 .addReg(ReadAgainReg) 8890 .addMBB(LoopMBB); 8891 8892 LoopMBB->addSuccessor(LoopMBB); 8893 LoopMBB->addSuccessor(DoneMBB); 8894 8895 MI.eraseFromParent(); 8896 8897 return DoneMBB; 8898 } 8899 8900 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 8901 MachineBasicBlock *BB) { 8902 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 8903 8904 MachineFunction &MF = *BB->getParent(); 8905 DebugLoc DL = MI.getDebugLoc(); 8906 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8907 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8908 Register LoReg = MI.getOperand(0).getReg(); 8909 Register HiReg = MI.getOperand(1).getReg(); 8910 Register SrcReg = MI.getOperand(2).getReg(); 8911 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 8912 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8913 8914 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 8915 RI); 8916 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8917 MachineMemOperand *MMOLo = 8918 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 8919 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8920 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 8921 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 8922 .addFrameIndex(FI) 8923 .addImm(0) 8924 .addMemOperand(MMOLo); 8925 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 8926 .addFrameIndex(FI) 8927 .addImm(4) 8928 .addMemOperand(MMOHi); 8929 MI.eraseFromParent(); // The pseudo instruction is gone now. 8930 return BB; 8931 } 8932 8933 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 8934 MachineBasicBlock *BB) { 8935 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 8936 "Unexpected instruction"); 8937 8938 MachineFunction &MF = *BB->getParent(); 8939 DebugLoc DL = MI.getDebugLoc(); 8940 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8941 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8942 Register DstReg = MI.getOperand(0).getReg(); 8943 Register LoReg = MI.getOperand(1).getReg(); 8944 Register HiReg = MI.getOperand(2).getReg(); 8945 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 8946 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8947 8948 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8949 MachineMemOperand *MMOLo = 8950 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 8951 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8952 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 8953 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8954 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 8955 .addFrameIndex(FI) 8956 .addImm(0) 8957 .addMemOperand(MMOLo); 8958 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8959 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 8960 .addFrameIndex(FI) 8961 .addImm(4) 8962 .addMemOperand(MMOHi); 8963 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 8964 MI.eraseFromParent(); // The pseudo instruction is gone now. 8965 return BB; 8966 } 8967 8968 static bool isSelectPseudo(MachineInstr &MI) { 8969 switch (MI.getOpcode()) { 8970 default: 8971 return false; 8972 case RISCV::Select_GPR_Using_CC_GPR: 8973 case RISCV::Select_FPR16_Using_CC_GPR: 8974 case RISCV::Select_FPR32_Using_CC_GPR: 8975 case RISCV::Select_FPR64_Using_CC_GPR: 8976 return true; 8977 } 8978 } 8979 8980 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 8981 unsigned RelOpcode, unsigned EqOpcode, 8982 const RISCVSubtarget &Subtarget) { 8983 DebugLoc DL = MI.getDebugLoc(); 8984 Register DstReg = MI.getOperand(0).getReg(); 8985 Register Src1Reg = MI.getOperand(1).getReg(); 8986 Register Src2Reg = MI.getOperand(2).getReg(); 8987 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 8988 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 8989 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 8990 8991 // Save the current FFLAGS. 8992 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 8993 8994 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 8995 .addReg(Src1Reg) 8996 .addReg(Src2Reg); 8997 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8998 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 8999 9000 // Restore the FFLAGS. 9001 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9002 .addReg(SavedFFlags, RegState::Kill); 9003 9004 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9005 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9006 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9007 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9008 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9009 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9010 9011 // Erase the pseudoinstruction. 9012 MI.eraseFromParent(); 9013 return BB; 9014 } 9015 9016 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9017 MachineBasicBlock *BB, 9018 const RISCVSubtarget &Subtarget) { 9019 // To "insert" Select_* instructions, we actually have to insert the triangle 9020 // control-flow pattern. The incoming instructions know the destination vreg 9021 // to set, the condition code register to branch on, the true/false values to 9022 // select between, and the condcode to use to select the appropriate branch. 9023 // 9024 // We produce the following control flow: 9025 // HeadMBB 9026 // | \ 9027 // | IfFalseMBB 9028 // | / 9029 // TailMBB 9030 // 9031 // When we find a sequence of selects we attempt to optimize their emission 9032 // by sharing the control flow. Currently we only handle cases where we have 9033 // multiple selects with the exact same condition (same LHS, RHS and CC). 9034 // The selects may be interleaved with other instructions if the other 9035 // instructions meet some requirements we deem safe: 9036 // - They are debug instructions. Otherwise, 9037 // - They do not have side-effects, do not access memory and their inputs do 9038 // not depend on the results of the select pseudo-instructions. 9039 // The TrueV/FalseV operands of the selects cannot depend on the result of 9040 // previous selects in the sequence. 9041 // These conditions could be further relaxed. See the X86 target for a 9042 // related approach and more information. 9043 Register LHS = MI.getOperand(1).getReg(); 9044 Register RHS = MI.getOperand(2).getReg(); 9045 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9046 9047 SmallVector<MachineInstr *, 4> SelectDebugValues; 9048 SmallSet<Register, 4> SelectDests; 9049 SelectDests.insert(MI.getOperand(0).getReg()); 9050 9051 MachineInstr *LastSelectPseudo = &MI; 9052 9053 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9054 SequenceMBBI != E; ++SequenceMBBI) { 9055 if (SequenceMBBI->isDebugInstr()) 9056 continue; 9057 else if (isSelectPseudo(*SequenceMBBI)) { 9058 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9059 SequenceMBBI->getOperand(2).getReg() != RHS || 9060 SequenceMBBI->getOperand(3).getImm() != CC || 9061 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9062 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9063 break; 9064 LastSelectPseudo = &*SequenceMBBI; 9065 SequenceMBBI->collectDebugValues(SelectDebugValues); 9066 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9067 } else { 9068 if (SequenceMBBI->hasUnmodeledSideEffects() || 9069 SequenceMBBI->mayLoadOrStore()) 9070 break; 9071 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9072 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9073 })) 9074 break; 9075 } 9076 } 9077 9078 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9079 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9080 DebugLoc DL = MI.getDebugLoc(); 9081 MachineFunction::iterator I = ++BB->getIterator(); 9082 9083 MachineBasicBlock *HeadMBB = BB; 9084 MachineFunction *F = BB->getParent(); 9085 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9086 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9087 9088 F->insert(I, IfFalseMBB); 9089 F->insert(I, TailMBB); 9090 9091 // Transfer debug instructions associated with the selects to TailMBB. 9092 for (MachineInstr *DebugInstr : SelectDebugValues) { 9093 TailMBB->push_back(DebugInstr->removeFromParent()); 9094 } 9095 9096 // Move all instructions after the sequence to TailMBB. 9097 TailMBB->splice(TailMBB->end(), HeadMBB, 9098 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9099 // Update machine-CFG edges by transferring all successors of the current 9100 // block to the new block which will contain the Phi nodes for the selects. 9101 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9102 // Set the successors for HeadMBB. 9103 HeadMBB->addSuccessor(IfFalseMBB); 9104 HeadMBB->addSuccessor(TailMBB); 9105 9106 // Insert appropriate branch. 9107 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9108 .addReg(LHS) 9109 .addReg(RHS) 9110 .addMBB(TailMBB); 9111 9112 // IfFalseMBB just falls through to TailMBB. 9113 IfFalseMBB->addSuccessor(TailMBB); 9114 9115 // Create PHIs for all of the select pseudo-instructions. 9116 auto SelectMBBI = MI.getIterator(); 9117 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9118 auto InsertionPoint = TailMBB->begin(); 9119 while (SelectMBBI != SelectEnd) { 9120 auto Next = std::next(SelectMBBI); 9121 if (isSelectPseudo(*SelectMBBI)) { 9122 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9123 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9124 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9125 .addReg(SelectMBBI->getOperand(4).getReg()) 9126 .addMBB(HeadMBB) 9127 .addReg(SelectMBBI->getOperand(5).getReg()) 9128 .addMBB(IfFalseMBB); 9129 SelectMBBI->eraseFromParent(); 9130 } 9131 SelectMBBI = Next; 9132 } 9133 9134 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9135 return TailMBB; 9136 } 9137 9138 MachineBasicBlock * 9139 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9140 MachineBasicBlock *BB) const { 9141 switch (MI.getOpcode()) { 9142 default: 9143 llvm_unreachable("Unexpected instr type to insert"); 9144 case RISCV::ReadCycleWide: 9145 assert(!Subtarget.is64Bit() && 9146 "ReadCycleWrite is only to be used on riscv32"); 9147 return emitReadCycleWidePseudo(MI, BB); 9148 case RISCV::Select_GPR_Using_CC_GPR: 9149 case RISCV::Select_FPR16_Using_CC_GPR: 9150 case RISCV::Select_FPR32_Using_CC_GPR: 9151 case RISCV::Select_FPR64_Using_CC_GPR: 9152 return emitSelectPseudo(MI, BB, Subtarget); 9153 case RISCV::BuildPairF64Pseudo: 9154 return emitBuildPairF64Pseudo(MI, BB); 9155 case RISCV::SplitF64Pseudo: 9156 return emitSplitF64Pseudo(MI, BB); 9157 case RISCV::PseudoQuietFLE_H: 9158 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9159 case RISCV::PseudoQuietFLT_H: 9160 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9161 case RISCV::PseudoQuietFLE_S: 9162 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9163 case RISCV::PseudoQuietFLT_S: 9164 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9165 case RISCV::PseudoQuietFLE_D: 9166 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9167 case RISCV::PseudoQuietFLT_D: 9168 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9169 } 9170 } 9171 9172 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9173 SDNode *Node) const { 9174 // Add FRM dependency to any instructions with dynamic rounding mode. 9175 unsigned Opc = MI.getOpcode(); 9176 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9177 if (Idx < 0) 9178 return; 9179 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9180 return; 9181 // If the instruction already reads FRM, don't add another read. 9182 if (MI.readsRegister(RISCV::FRM)) 9183 return; 9184 MI.addOperand( 9185 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9186 } 9187 9188 // Calling Convention Implementation. 9189 // The expectations for frontend ABI lowering vary from target to target. 9190 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9191 // details, but this is a longer term goal. For now, we simply try to keep the 9192 // role of the frontend as simple and well-defined as possible. The rules can 9193 // be summarised as: 9194 // * Never split up large scalar arguments. We handle them here. 9195 // * If a hardfloat calling convention is being used, and the struct may be 9196 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9197 // available, then pass as two separate arguments. If either the GPRs or FPRs 9198 // are exhausted, then pass according to the rule below. 9199 // * If a struct could never be passed in registers or directly in a stack 9200 // slot (as it is larger than 2*XLEN and the floating point rules don't 9201 // apply), then pass it using a pointer with the byval attribute. 9202 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9203 // word-sized array or a 2*XLEN scalar (depending on alignment). 9204 // * The frontend can determine whether a struct is returned by reference or 9205 // not based on its size and fields. If it will be returned by reference, the 9206 // frontend must modify the prototype so a pointer with the sret annotation is 9207 // passed as the first argument. This is not necessary for large scalar 9208 // returns. 9209 // * Struct return values and varargs should be coerced to structs containing 9210 // register-size fields in the same situations they would be for fixed 9211 // arguments. 9212 9213 static const MCPhysReg ArgGPRs[] = { 9214 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9215 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9216 }; 9217 static const MCPhysReg ArgFPR16s[] = { 9218 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9219 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9220 }; 9221 static const MCPhysReg ArgFPR32s[] = { 9222 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9223 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9224 }; 9225 static const MCPhysReg ArgFPR64s[] = { 9226 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9227 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9228 }; 9229 // This is an interim calling convention and it may be changed in the future. 9230 static const MCPhysReg ArgVRs[] = { 9231 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9232 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9233 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9234 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9235 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9236 RISCV::V20M2, RISCV::V22M2}; 9237 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9238 RISCV::V20M4}; 9239 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9240 9241 // Pass a 2*XLEN argument that has been split into two XLEN values through 9242 // registers or the stack as necessary. 9243 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9244 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9245 MVT ValVT2, MVT LocVT2, 9246 ISD::ArgFlagsTy ArgFlags2) { 9247 unsigned XLenInBytes = XLen / 8; 9248 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9249 // At least one half can be passed via register. 9250 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9251 VA1.getLocVT(), CCValAssign::Full)); 9252 } else { 9253 // Both halves must be passed on the stack, with proper alignment. 9254 Align StackAlign = 9255 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9256 State.addLoc( 9257 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9258 State.AllocateStack(XLenInBytes, StackAlign), 9259 VA1.getLocVT(), CCValAssign::Full)); 9260 State.addLoc(CCValAssign::getMem( 9261 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9262 LocVT2, CCValAssign::Full)); 9263 return false; 9264 } 9265 9266 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9267 // The second half can also be passed via register. 9268 State.addLoc( 9269 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9270 } else { 9271 // The second half is passed via the stack, without additional alignment. 9272 State.addLoc(CCValAssign::getMem( 9273 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9274 LocVT2, CCValAssign::Full)); 9275 } 9276 9277 return false; 9278 } 9279 9280 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9281 Optional<unsigned> FirstMaskArgument, 9282 CCState &State, const RISCVTargetLowering &TLI) { 9283 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9284 if (RC == &RISCV::VRRegClass) { 9285 // Assign the first mask argument to V0. 9286 // This is an interim calling convention and it may be changed in the 9287 // future. 9288 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9289 return State.AllocateReg(RISCV::V0); 9290 return State.AllocateReg(ArgVRs); 9291 } 9292 if (RC == &RISCV::VRM2RegClass) 9293 return State.AllocateReg(ArgVRM2s); 9294 if (RC == &RISCV::VRM4RegClass) 9295 return State.AllocateReg(ArgVRM4s); 9296 if (RC == &RISCV::VRM8RegClass) 9297 return State.AllocateReg(ArgVRM8s); 9298 llvm_unreachable("Unhandled register class for ValueType"); 9299 } 9300 9301 // Implements the RISC-V calling convention. Returns true upon failure. 9302 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9303 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9304 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9305 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9306 Optional<unsigned> FirstMaskArgument) { 9307 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9308 assert(XLen == 32 || XLen == 64); 9309 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9310 9311 // Any return value split in to more than two values can't be returned 9312 // directly. Vectors are returned via the available vector registers. 9313 if (!LocVT.isVector() && IsRet && ValNo > 1) 9314 return true; 9315 9316 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9317 // variadic argument, or if no F16/F32 argument registers are available. 9318 bool UseGPRForF16_F32 = true; 9319 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9320 // variadic argument, or if no F64 argument registers are available. 9321 bool UseGPRForF64 = true; 9322 9323 switch (ABI) { 9324 default: 9325 llvm_unreachable("Unexpected ABI"); 9326 case RISCVABI::ABI_ILP32: 9327 case RISCVABI::ABI_LP64: 9328 break; 9329 case RISCVABI::ABI_ILP32F: 9330 case RISCVABI::ABI_LP64F: 9331 UseGPRForF16_F32 = !IsFixed; 9332 break; 9333 case RISCVABI::ABI_ILP32D: 9334 case RISCVABI::ABI_LP64D: 9335 UseGPRForF16_F32 = !IsFixed; 9336 UseGPRForF64 = !IsFixed; 9337 break; 9338 } 9339 9340 // FPR16, FPR32, and FPR64 alias each other. 9341 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9342 UseGPRForF16_F32 = true; 9343 UseGPRForF64 = true; 9344 } 9345 9346 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9347 // similar local variables rather than directly checking against the target 9348 // ABI. 9349 9350 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9351 LocVT = XLenVT; 9352 LocInfo = CCValAssign::BCvt; 9353 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9354 LocVT = MVT::i64; 9355 LocInfo = CCValAssign::BCvt; 9356 } 9357 9358 // If this is a variadic argument, the RISC-V calling convention requires 9359 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9360 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9361 // be used regardless of whether the original argument was split during 9362 // legalisation or not. The argument will not be passed by registers if the 9363 // original type is larger than 2*XLEN, so the register alignment rule does 9364 // not apply. 9365 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9366 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9367 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9368 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9369 // Skip 'odd' register if necessary. 9370 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9371 State.AllocateReg(ArgGPRs); 9372 } 9373 9374 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9375 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9376 State.getPendingArgFlags(); 9377 9378 assert(PendingLocs.size() == PendingArgFlags.size() && 9379 "PendingLocs and PendingArgFlags out of sync"); 9380 9381 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9382 // registers are exhausted. 9383 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9384 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9385 "Can't lower f64 if it is split"); 9386 // Depending on available argument GPRS, f64 may be passed in a pair of 9387 // GPRs, split between a GPR and the stack, or passed completely on the 9388 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9389 // cases. 9390 Register Reg = State.AllocateReg(ArgGPRs); 9391 LocVT = MVT::i32; 9392 if (!Reg) { 9393 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9394 State.addLoc( 9395 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9396 return false; 9397 } 9398 if (!State.AllocateReg(ArgGPRs)) 9399 State.AllocateStack(4, Align(4)); 9400 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9401 return false; 9402 } 9403 9404 // Fixed-length vectors are located in the corresponding scalable-vector 9405 // container types. 9406 if (ValVT.isFixedLengthVector()) 9407 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9408 9409 // Split arguments might be passed indirectly, so keep track of the pending 9410 // values. Split vectors are passed via a mix of registers and indirectly, so 9411 // treat them as we would any other argument. 9412 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9413 LocVT = XLenVT; 9414 LocInfo = CCValAssign::Indirect; 9415 PendingLocs.push_back( 9416 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9417 PendingArgFlags.push_back(ArgFlags); 9418 if (!ArgFlags.isSplitEnd()) { 9419 return false; 9420 } 9421 } 9422 9423 // If the split argument only had two elements, it should be passed directly 9424 // in registers or on the stack. 9425 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9426 PendingLocs.size() <= 2) { 9427 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9428 // Apply the normal calling convention rules to the first half of the 9429 // split argument. 9430 CCValAssign VA = PendingLocs[0]; 9431 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9432 PendingLocs.clear(); 9433 PendingArgFlags.clear(); 9434 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9435 ArgFlags); 9436 } 9437 9438 // Allocate to a register if possible, or else a stack slot. 9439 Register Reg; 9440 unsigned StoreSizeBytes = XLen / 8; 9441 Align StackAlign = Align(XLen / 8); 9442 9443 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9444 Reg = State.AllocateReg(ArgFPR16s); 9445 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9446 Reg = State.AllocateReg(ArgFPR32s); 9447 else if (ValVT == MVT::f64 && !UseGPRForF64) 9448 Reg = State.AllocateReg(ArgFPR64s); 9449 else if (ValVT.isVector()) { 9450 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9451 if (!Reg) { 9452 // For return values, the vector must be passed fully via registers or 9453 // via the stack. 9454 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9455 // but we're using all of them. 9456 if (IsRet) 9457 return true; 9458 // Try using a GPR to pass the address 9459 if ((Reg = State.AllocateReg(ArgGPRs))) { 9460 LocVT = XLenVT; 9461 LocInfo = CCValAssign::Indirect; 9462 } else if (ValVT.isScalableVector()) { 9463 LocVT = XLenVT; 9464 LocInfo = CCValAssign::Indirect; 9465 } else { 9466 // Pass fixed-length vectors on the stack. 9467 LocVT = ValVT; 9468 StoreSizeBytes = ValVT.getStoreSize(); 9469 // Align vectors to their element sizes, being careful for vXi1 9470 // vectors. 9471 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9472 } 9473 } 9474 } else { 9475 Reg = State.AllocateReg(ArgGPRs); 9476 } 9477 9478 unsigned StackOffset = 9479 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9480 9481 // If we reach this point and PendingLocs is non-empty, we must be at the 9482 // end of a split argument that must be passed indirectly. 9483 if (!PendingLocs.empty()) { 9484 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9485 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9486 9487 for (auto &It : PendingLocs) { 9488 if (Reg) 9489 It.convertToReg(Reg); 9490 else 9491 It.convertToMem(StackOffset); 9492 State.addLoc(It); 9493 } 9494 PendingLocs.clear(); 9495 PendingArgFlags.clear(); 9496 return false; 9497 } 9498 9499 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9500 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9501 "Expected an XLenVT or vector types at this stage"); 9502 9503 if (Reg) { 9504 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9505 return false; 9506 } 9507 9508 // When a floating-point value is passed on the stack, no bit-conversion is 9509 // needed. 9510 if (ValVT.isFloatingPoint()) { 9511 LocVT = ValVT; 9512 LocInfo = CCValAssign::Full; 9513 } 9514 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9515 return false; 9516 } 9517 9518 template <typename ArgTy> 9519 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9520 for (const auto &ArgIdx : enumerate(Args)) { 9521 MVT ArgVT = ArgIdx.value().VT; 9522 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9523 return ArgIdx.index(); 9524 } 9525 return None; 9526 } 9527 9528 void RISCVTargetLowering::analyzeInputArgs( 9529 MachineFunction &MF, CCState &CCInfo, 9530 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9531 RISCVCCAssignFn Fn) const { 9532 unsigned NumArgs = Ins.size(); 9533 FunctionType *FType = MF.getFunction().getFunctionType(); 9534 9535 Optional<unsigned> FirstMaskArgument; 9536 if (Subtarget.hasVInstructions()) 9537 FirstMaskArgument = preAssignMask(Ins); 9538 9539 for (unsigned i = 0; i != NumArgs; ++i) { 9540 MVT ArgVT = Ins[i].VT; 9541 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9542 9543 Type *ArgTy = nullptr; 9544 if (IsRet) 9545 ArgTy = FType->getReturnType(); 9546 else if (Ins[i].isOrigArg()) 9547 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9548 9549 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9550 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9551 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9552 FirstMaskArgument)) { 9553 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9554 << EVT(ArgVT).getEVTString() << '\n'); 9555 llvm_unreachable(nullptr); 9556 } 9557 } 9558 } 9559 9560 void RISCVTargetLowering::analyzeOutputArgs( 9561 MachineFunction &MF, CCState &CCInfo, 9562 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9563 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9564 unsigned NumArgs = Outs.size(); 9565 9566 Optional<unsigned> FirstMaskArgument; 9567 if (Subtarget.hasVInstructions()) 9568 FirstMaskArgument = preAssignMask(Outs); 9569 9570 for (unsigned i = 0; i != NumArgs; i++) { 9571 MVT ArgVT = Outs[i].VT; 9572 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9573 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9574 9575 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9576 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9577 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9578 FirstMaskArgument)) { 9579 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9580 << EVT(ArgVT).getEVTString() << "\n"); 9581 llvm_unreachable(nullptr); 9582 } 9583 } 9584 } 9585 9586 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9587 // values. 9588 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9589 const CCValAssign &VA, const SDLoc &DL, 9590 const RISCVSubtarget &Subtarget) { 9591 switch (VA.getLocInfo()) { 9592 default: 9593 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9594 case CCValAssign::Full: 9595 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9596 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9597 break; 9598 case CCValAssign::BCvt: 9599 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9600 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9601 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9602 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9603 else 9604 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9605 break; 9606 } 9607 return Val; 9608 } 9609 9610 // The caller is responsible for loading the full value if the argument is 9611 // passed with CCValAssign::Indirect. 9612 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9613 const CCValAssign &VA, const SDLoc &DL, 9614 const RISCVTargetLowering &TLI) { 9615 MachineFunction &MF = DAG.getMachineFunction(); 9616 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9617 EVT LocVT = VA.getLocVT(); 9618 SDValue Val; 9619 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9620 Register VReg = RegInfo.createVirtualRegister(RC); 9621 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9622 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9623 9624 if (VA.getLocInfo() == CCValAssign::Indirect) 9625 return Val; 9626 9627 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9628 } 9629 9630 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9631 const CCValAssign &VA, const SDLoc &DL, 9632 const RISCVSubtarget &Subtarget) { 9633 EVT LocVT = VA.getLocVT(); 9634 9635 switch (VA.getLocInfo()) { 9636 default: 9637 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9638 case CCValAssign::Full: 9639 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9640 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9641 break; 9642 case CCValAssign::BCvt: 9643 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9644 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9645 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9646 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9647 else 9648 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9649 break; 9650 } 9651 return Val; 9652 } 9653 9654 // The caller is responsible for loading the full value if the argument is 9655 // passed with CCValAssign::Indirect. 9656 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9657 const CCValAssign &VA, const SDLoc &DL) { 9658 MachineFunction &MF = DAG.getMachineFunction(); 9659 MachineFrameInfo &MFI = MF.getFrameInfo(); 9660 EVT LocVT = VA.getLocVT(); 9661 EVT ValVT = VA.getValVT(); 9662 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9663 if (ValVT.isScalableVector()) { 9664 // When the value is a scalable vector, we save the pointer which points to 9665 // the scalable vector value in the stack. The ValVT will be the pointer 9666 // type, instead of the scalable vector type. 9667 ValVT = LocVT; 9668 } 9669 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9670 /*IsImmutable=*/true); 9671 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9672 SDValue Val; 9673 9674 ISD::LoadExtType ExtType; 9675 switch (VA.getLocInfo()) { 9676 default: 9677 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9678 case CCValAssign::Full: 9679 case CCValAssign::Indirect: 9680 case CCValAssign::BCvt: 9681 ExtType = ISD::NON_EXTLOAD; 9682 break; 9683 } 9684 Val = DAG.getExtLoad( 9685 ExtType, DL, LocVT, Chain, FIN, 9686 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9687 return Val; 9688 } 9689 9690 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9691 const CCValAssign &VA, const SDLoc &DL) { 9692 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9693 "Unexpected VA"); 9694 MachineFunction &MF = DAG.getMachineFunction(); 9695 MachineFrameInfo &MFI = MF.getFrameInfo(); 9696 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9697 9698 if (VA.isMemLoc()) { 9699 // f64 is passed on the stack. 9700 int FI = 9701 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9702 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9703 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9704 MachinePointerInfo::getFixedStack(MF, FI)); 9705 } 9706 9707 assert(VA.isRegLoc() && "Expected register VA assignment"); 9708 9709 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9710 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 9711 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 9712 SDValue Hi; 9713 if (VA.getLocReg() == RISCV::X17) { 9714 // Second half of f64 is passed on the stack. 9715 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 9716 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9717 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 9718 MachinePointerInfo::getFixedStack(MF, FI)); 9719 } else { 9720 // Second half of f64 is passed in another GPR. 9721 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9722 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 9723 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 9724 } 9725 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 9726 } 9727 9728 // FastCC has less than 1% performance improvement for some particular 9729 // benchmark. But theoretically, it may has benenfit for some cases. 9730 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 9731 unsigned ValNo, MVT ValVT, MVT LocVT, 9732 CCValAssign::LocInfo LocInfo, 9733 ISD::ArgFlagsTy ArgFlags, CCState &State, 9734 bool IsFixed, bool IsRet, Type *OrigTy, 9735 const RISCVTargetLowering &TLI, 9736 Optional<unsigned> FirstMaskArgument) { 9737 9738 // X5 and X6 might be used for save-restore libcall. 9739 static const MCPhysReg GPRList[] = { 9740 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 9741 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 9742 RISCV::X29, RISCV::X30, RISCV::X31}; 9743 9744 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9745 if (unsigned Reg = State.AllocateReg(GPRList)) { 9746 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9747 return false; 9748 } 9749 } 9750 9751 if (LocVT == MVT::f16) { 9752 static const MCPhysReg FPR16List[] = { 9753 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 9754 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 9755 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 9756 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 9757 if (unsigned Reg = State.AllocateReg(FPR16List)) { 9758 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9759 return false; 9760 } 9761 } 9762 9763 if (LocVT == MVT::f32) { 9764 static const MCPhysReg FPR32List[] = { 9765 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 9766 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 9767 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 9768 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 9769 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9770 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9771 return false; 9772 } 9773 } 9774 9775 if (LocVT == MVT::f64) { 9776 static const MCPhysReg FPR64List[] = { 9777 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 9778 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 9779 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 9780 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 9781 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9782 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9783 return false; 9784 } 9785 } 9786 9787 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 9788 unsigned Offset4 = State.AllocateStack(4, Align(4)); 9789 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 9790 return false; 9791 } 9792 9793 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 9794 unsigned Offset5 = State.AllocateStack(8, Align(8)); 9795 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 9796 return false; 9797 } 9798 9799 if (LocVT.isVector()) { 9800 if (unsigned Reg = 9801 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 9802 // Fixed-length vectors are located in the corresponding scalable-vector 9803 // container types. 9804 if (ValVT.isFixedLengthVector()) 9805 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9806 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9807 } else { 9808 // Try and pass the address via a "fast" GPR. 9809 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 9810 LocInfo = CCValAssign::Indirect; 9811 LocVT = TLI.getSubtarget().getXLenVT(); 9812 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 9813 } else if (ValVT.isFixedLengthVector()) { 9814 auto StackAlign = 9815 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9816 unsigned StackOffset = 9817 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 9818 State.addLoc( 9819 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9820 } else { 9821 // Can't pass scalable vectors on the stack. 9822 return true; 9823 } 9824 } 9825 9826 return false; 9827 } 9828 9829 return true; // CC didn't match. 9830 } 9831 9832 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9833 CCValAssign::LocInfo LocInfo, 9834 ISD::ArgFlagsTy ArgFlags, CCState &State) { 9835 9836 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9837 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 9838 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 9839 static const MCPhysReg GPRList[] = { 9840 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 9841 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 9842 if (unsigned Reg = State.AllocateReg(GPRList)) { 9843 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9844 return false; 9845 } 9846 } 9847 9848 if (LocVT == MVT::f32) { 9849 // Pass in STG registers: F1, ..., F6 9850 // fs0 ... fs5 9851 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 9852 RISCV::F18_F, RISCV::F19_F, 9853 RISCV::F20_F, RISCV::F21_F}; 9854 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9855 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9856 return false; 9857 } 9858 } 9859 9860 if (LocVT == MVT::f64) { 9861 // Pass in STG registers: D1, ..., D6 9862 // fs6 ... fs11 9863 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 9864 RISCV::F24_D, RISCV::F25_D, 9865 RISCV::F26_D, RISCV::F27_D}; 9866 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9867 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9868 return false; 9869 } 9870 } 9871 9872 report_fatal_error("No registers left in GHC calling convention"); 9873 return true; 9874 } 9875 9876 // Transform physical registers into virtual registers. 9877 SDValue RISCVTargetLowering::LowerFormalArguments( 9878 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 9879 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 9880 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 9881 9882 MachineFunction &MF = DAG.getMachineFunction(); 9883 9884 switch (CallConv) { 9885 default: 9886 report_fatal_error("Unsupported calling convention"); 9887 case CallingConv::C: 9888 case CallingConv::Fast: 9889 break; 9890 case CallingConv::GHC: 9891 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 9892 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 9893 report_fatal_error( 9894 "GHC calling convention requires the F and D instruction set extensions"); 9895 } 9896 9897 const Function &Func = MF.getFunction(); 9898 if (Func.hasFnAttribute("interrupt")) { 9899 if (!Func.arg_empty()) 9900 report_fatal_error( 9901 "Functions with the interrupt attribute cannot have arguments!"); 9902 9903 StringRef Kind = 9904 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9905 9906 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 9907 report_fatal_error( 9908 "Function interrupt attribute argument not supported!"); 9909 } 9910 9911 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9912 MVT XLenVT = Subtarget.getXLenVT(); 9913 unsigned XLenInBytes = Subtarget.getXLen() / 8; 9914 // Used with vargs to acumulate store chains. 9915 std::vector<SDValue> OutChains; 9916 9917 // Assign locations to all of the incoming arguments. 9918 SmallVector<CCValAssign, 16> ArgLocs; 9919 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9920 9921 if (CallConv == CallingConv::GHC) 9922 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 9923 else 9924 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 9925 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9926 : CC_RISCV); 9927 9928 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 9929 CCValAssign &VA = ArgLocs[i]; 9930 SDValue ArgValue; 9931 // Passing f64 on RV32D with a soft float ABI must be handled as a special 9932 // case. 9933 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 9934 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 9935 else if (VA.isRegLoc()) 9936 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 9937 else 9938 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 9939 9940 if (VA.getLocInfo() == CCValAssign::Indirect) { 9941 // If the original argument was split and passed by reference (e.g. i128 9942 // on RV32), we need to load all parts of it here (using the same 9943 // address). Vectors may be partly split to registers and partly to the 9944 // stack, in which case the base address is partly offset and subsequent 9945 // stores are relative to that. 9946 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 9947 MachinePointerInfo())); 9948 unsigned ArgIndex = Ins[i].OrigArgIndex; 9949 unsigned ArgPartOffset = Ins[i].PartOffset; 9950 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9951 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 9952 CCValAssign &PartVA = ArgLocs[i + 1]; 9953 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 9954 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9955 if (PartVA.getValVT().isScalableVector()) 9956 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9957 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 9958 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 9959 MachinePointerInfo())); 9960 ++i; 9961 } 9962 continue; 9963 } 9964 InVals.push_back(ArgValue); 9965 } 9966 9967 if (IsVarArg) { 9968 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 9969 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 9970 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 9971 MachineFrameInfo &MFI = MF.getFrameInfo(); 9972 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9973 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 9974 9975 // Offset of the first variable argument from stack pointer, and size of 9976 // the vararg save area. For now, the varargs save area is either zero or 9977 // large enough to hold a0-a7. 9978 int VaArgOffset, VarArgsSaveSize; 9979 9980 // If all registers are allocated, then all varargs must be passed on the 9981 // stack and we don't need to save any argregs. 9982 if (ArgRegs.size() == Idx) { 9983 VaArgOffset = CCInfo.getNextStackOffset(); 9984 VarArgsSaveSize = 0; 9985 } else { 9986 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 9987 VaArgOffset = -VarArgsSaveSize; 9988 } 9989 9990 // Record the frame index of the first variable argument 9991 // which is a value necessary to VASTART. 9992 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9993 RVFI->setVarArgsFrameIndex(FI); 9994 9995 // If saving an odd number of registers then create an extra stack slot to 9996 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 9997 // offsets to even-numbered registered remain 2*XLEN-aligned. 9998 if (Idx % 2) { 9999 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10000 VarArgsSaveSize += XLenInBytes; 10001 } 10002 10003 // Copy the integer registers that may have been used for passing varargs 10004 // to the vararg save area. 10005 for (unsigned I = Idx; I < ArgRegs.size(); 10006 ++I, VaArgOffset += XLenInBytes) { 10007 const Register Reg = RegInfo.createVirtualRegister(RC); 10008 RegInfo.addLiveIn(ArgRegs[I], Reg); 10009 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10010 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10011 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10012 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10013 MachinePointerInfo::getFixedStack(MF, FI)); 10014 cast<StoreSDNode>(Store.getNode()) 10015 ->getMemOperand() 10016 ->setValue((Value *)nullptr); 10017 OutChains.push_back(Store); 10018 } 10019 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10020 } 10021 10022 // All stores are grouped in one node to allow the matching between 10023 // the size of Ins and InVals. This only happens for vararg functions. 10024 if (!OutChains.empty()) { 10025 OutChains.push_back(Chain); 10026 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10027 } 10028 10029 return Chain; 10030 } 10031 10032 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10033 /// for tail call optimization. 10034 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10035 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10036 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10037 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10038 10039 auto &Callee = CLI.Callee; 10040 auto CalleeCC = CLI.CallConv; 10041 auto &Outs = CLI.Outs; 10042 auto &Caller = MF.getFunction(); 10043 auto CallerCC = Caller.getCallingConv(); 10044 10045 // Exception-handling functions need a special set of instructions to 10046 // indicate a return to the hardware. Tail-calling another function would 10047 // probably break this. 10048 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10049 // should be expanded as new function attributes are introduced. 10050 if (Caller.hasFnAttribute("interrupt")) 10051 return false; 10052 10053 // Do not tail call opt if the stack is used to pass parameters. 10054 if (CCInfo.getNextStackOffset() != 0) 10055 return false; 10056 10057 // Do not tail call opt if any parameters need to be passed indirectly. 10058 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10059 // passed indirectly. So the address of the value will be passed in a 10060 // register, or if not available, then the address is put on the stack. In 10061 // order to pass indirectly, space on the stack often needs to be allocated 10062 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10063 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10064 // are passed CCValAssign::Indirect. 10065 for (auto &VA : ArgLocs) 10066 if (VA.getLocInfo() == CCValAssign::Indirect) 10067 return false; 10068 10069 // Do not tail call opt if either caller or callee uses struct return 10070 // semantics. 10071 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10072 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10073 if (IsCallerStructRet || IsCalleeStructRet) 10074 return false; 10075 10076 // Externally-defined functions with weak linkage should not be 10077 // tail-called. The behaviour of branch instructions in this situation (as 10078 // used for tail calls) is implementation-defined, so we cannot rely on the 10079 // linker replacing the tail call with a return. 10080 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10081 const GlobalValue *GV = G->getGlobal(); 10082 if (GV->hasExternalWeakLinkage()) 10083 return false; 10084 } 10085 10086 // The callee has to preserve all registers the caller needs to preserve. 10087 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10088 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10089 if (CalleeCC != CallerCC) { 10090 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10091 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10092 return false; 10093 } 10094 10095 // Byval parameters hand the function a pointer directly into the stack area 10096 // we want to reuse during a tail call. Working around this *is* possible 10097 // but less efficient and uglier in LowerCall. 10098 for (auto &Arg : Outs) 10099 if (Arg.Flags.isByVal()) 10100 return false; 10101 10102 return true; 10103 } 10104 10105 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10106 return DAG.getDataLayout().getPrefTypeAlign( 10107 VT.getTypeForEVT(*DAG.getContext())); 10108 } 10109 10110 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10111 // and output parameter nodes. 10112 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10113 SmallVectorImpl<SDValue> &InVals) const { 10114 SelectionDAG &DAG = CLI.DAG; 10115 SDLoc &DL = CLI.DL; 10116 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10117 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10118 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10119 SDValue Chain = CLI.Chain; 10120 SDValue Callee = CLI.Callee; 10121 bool &IsTailCall = CLI.IsTailCall; 10122 CallingConv::ID CallConv = CLI.CallConv; 10123 bool IsVarArg = CLI.IsVarArg; 10124 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10125 MVT XLenVT = Subtarget.getXLenVT(); 10126 10127 MachineFunction &MF = DAG.getMachineFunction(); 10128 10129 // Analyze the operands of the call, assigning locations to each operand. 10130 SmallVector<CCValAssign, 16> ArgLocs; 10131 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10132 10133 if (CallConv == CallingConv::GHC) 10134 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10135 else 10136 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10137 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10138 : CC_RISCV); 10139 10140 // Check if it's really possible to do a tail call. 10141 if (IsTailCall) 10142 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10143 10144 if (IsTailCall) 10145 ++NumTailCalls; 10146 else if (CLI.CB && CLI.CB->isMustTailCall()) 10147 report_fatal_error("failed to perform tail call elimination on a call " 10148 "site marked musttail"); 10149 10150 // Get a count of how many bytes are to be pushed on the stack. 10151 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10152 10153 // Create local copies for byval args 10154 SmallVector<SDValue, 8> ByValArgs; 10155 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10156 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10157 if (!Flags.isByVal()) 10158 continue; 10159 10160 SDValue Arg = OutVals[i]; 10161 unsigned Size = Flags.getByValSize(); 10162 Align Alignment = Flags.getNonZeroByValAlign(); 10163 10164 int FI = 10165 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10166 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10167 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10168 10169 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10170 /*IsVolatile=*/false, 10171 /*AlwaysInline=*/false, IsTailCall, 10172 MachinePointerInfo(), MachinePointerInfo()); 10173 ByValArgs.push_back(FIPtr); 10174 } 10175 10176 if (!IsTailCall) 10177 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10178 10179 // Copy argument values to their designated locations. 10180 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10181 SmallVector<SDValue, 8> MemOpChains; 10182 SDValue StackPtr; 10183 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10184 CCValAssign &VA = ArgLocs[i]; 10185 SDValue ArgValue = OutVals[i]; 10186 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10187 10188 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10189 bool IsF64OnRV32DSoftABI = 10190 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10191 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10192 SDValue SplitF64 = DAG.getNode( 10193 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10194 SDValue Lo = SplitF64.getValue(0); 10195 SDValue Hi = SplitF64.getValue(1); 10196 10197 Register RegLo = VA.getLocReg(); 10198 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10199 10200 if (RegLo == RISCV::X17) { 10201 // Second half of f64 is passed on the stack. 10202 // Work out the address of the stack slot. 10203 if (!StackPtr.getNode()) 10204 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10205 // Emit the store. 10206 MemOpChains.push_back( 10207 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10208 } else { 10209 // Second half of f64 is passed in another GPR. 10210 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10211 Register RegHigh = RegLo + 1; 10212 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10213 } 10214 continue; 10215 } 10216 10217 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10218 // as any other MemLoc. 10219 10220 // Promote the value if needed. 10221 // For now, only handle fully promoted and indirect arguments. 10222 if (VA.getLocInfo() == CCValAssign::Indirect) { 10223 // Store the argument in a stack slot and pass its address. 10224 Align StackAlign = 10225 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10226 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10227 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10228 // If the original argument was split (e.g. i128), we need 10229 // to store the required parts of it here (and pass just one address). 10230 // Vectors may be partly split to registers and partly to the stack, in 10231 // which case the base address is partly offset and subsequent stores are 10232 // relative to that. 10233 unsigned ArgIndex = Outs[i].OrigArgIndex; 10234 unsigned ArgPartOffset = Outs[i].PartOffset; 10235 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10236 // Calculate the total size to store. We don't have access to what we're 10237 // actually storing other than performing the loop and collecting the 10238 // info. 10239 SmallVector<std::pair<SDValue, SDValue>> Parts; 10240 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10241 SDValue PartValue = OutVals[i + 1]; 10242 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10243 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10244 EVT PartVT = PartValue.getValueType(); 10245 if (PartVT.isScalableVector()) 10246 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10247 StoredSize += PartVT.getStoreSize(); 10248 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10249 Parts.push_back(std::make_pair(PartValue, Offset)); 10250 ++i; 10251 } 10252 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10253 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10254 MemOpChains.push_back( 10255 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10256 MachinePointerInfo::getFixedStack(MF, FI))); 10257 for (const auto &Part : Parts) { 10258 SDValue PartValue = Part.first; 10259 SDValue PartOffset = Part.second; 10260 SDValue Address = 10261 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10262 MemOpChains.push_back( 10263 DAG.getStore(Chain, DL, PartValue, Address, 10264 MachinePointerInfo::getFixedStack(MF, FI))); 10265 } 10266 ArgValue = SpillSlot; 10267 } else { 10268 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10269 } 10270 10271 // Use local copy if it is a byval arg. 10272 if (Flags.isByVal()) 10273 ArgValue = ByValArgs[j++]; 10274 10275 if (VA.isRegLoc()) { 10276 // Queue up the argument copies and emit them at the end. 10277 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10278 } else { 10279 assert(VA.isMemLoc() && "Argument not register or memory"); 10280 assert(!IsTailCall && "Tail call not allowed if stack is used " 10281 "for passing parameters"); 10282 10283 // Work out the address of the stack slot. 10284 if (!StackPtr.getNode()) 10285 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10286 SDValue Address = 10287 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10288 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10289 10290 // Emit the store. 10291 MemOpChains.push_back( 10292 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10293 } 10294 } 10295 10296 // Join the stores, which are independent of one another. 10297 if (!MemOpChains.empty()) 10298 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10299 10300 SDValue Glue; 10301 10302 // Build a sequence of copy-to-reg nodes, chained and glued together. 10303 for (auto &Reg : RegsToPass) { 10304 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10305 Glue = Chain.getValue(1); 10306 } 10307 10308 // Validate that none of the argument registers have been marked as 10309 // reserved, if so report an error. Do the same for the return address if this 10310 // is not a tailcall. 10311 validateCCReservedRegs(RegsToPass, MF); 10312 if (!IsTailCall && 10313 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10314 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10315 MF.getFunction(), 10316 "Return address register required, but has been reserved."}); 10317 10318 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10319 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10320 // split it and then direct call can be matched by PseudoCALL. 10321 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10322 const GlobalValue *GV = S->getGlobal(); 10323 10324 unsigned OpFlags = RISCVII::MO_CALL; 10325 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10326 OpFlags = RISCVII::MO_PLT; 10327 10328 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10329 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10330 unsigned OpFlags = RISCVII::MO_CALL; 10331 10332 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10333 nullptr)) 10334 OpFlags = RISCVII::MO_PLT; 10335 10336 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10337 } 10338 10339 // The first call operand is the chain and the second is the target address. 10340 SmallVector<SDValue, 8> Ops; 10341 Ops.push_back(Chain); 10342 Ops.push_back(Callee); 10343 10344 // Add argument registers to the end of the list so that they are 10345 // known live into the call. 10346 for (auto &Reg : RegsToPass) 10347 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10348 10349 if (!IsTailCall) { 10350 // Add a register mask operand representing the call-preserved registers. 10351 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10352 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10353 assert(Mask && "Missing call preserved mask for calling convention"); 10354 Ops.push_back(DAG.getRegisterMask(Mask)); 10355 } 10356 10357 // Glue the call to the argument copies, if any. 10358 if (Glue.getNode()) 10359 Ops.push_back(Glue); 10360 10361 // Emit the call. 10362 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10363 10364 if (IsTailCall) { 10365 MF.getFrameInfo().setHasTailCall(); 10366 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10367 } 10368 10369 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10370 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10371 Glue = Chain.getValue(1); 10372 10373 // Mark the end of the call, which is glued to the call itself. 10374 Chain = DAG.getCALLSEQ_END(Chain, 10375 DAG.getConstant(NumBytes, DL, PtrVT, true), 10376 DAG.getConstant(0, DL, PtrVT, true), 10377 Glue, DL); 10378 Glue = Chain.getValue(1); 10379 10380 // Assign locations to each value returned by this call. 10381 SmallVector<CCValAssign, 16> RVLocs; 10382 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10383 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10384 10385 // Copy all of the result registers out of their specified physreg. 10386 for (auto &VA : RVLocs) { 10387 // Copy the value out 10388 SDValue RetValue = 10389 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10390 // Glue the RetValue to the end of the call sequence 10391 Chain = RetValue.getValue(1); 10392 Glue = RetValue.getValue(2); 10393 10394 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10395 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10396 SDValue RetValue2 = 10397 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10398 Chain = RetValue2.getValue(1); 10399 Glue = RetValue2.getValue(2); 10400 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10401 RetValue2); 10402 } 10403 10404 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10405 10406 InVals.push_back(RetValue); 10407 } 10408 10409 return Chain; 10410 } 10411 10412 bool RISCVTargetLowering::CanLowerReturn( 10413 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10414 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10415 SmallVector<CCValAssign, 16> RVLocs; 10416 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10417 10418 Optional<unsigned> FirstMaskArgument; 10419 if (Subtarget.hasVInstructions()) 10420 FirstMaskArgument = preAssignMask(Outs); 10421 10422 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10423 MVT VT = Outs[i].VT; 10424 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10425 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10426 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10427 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10428 *this, FirstMaskArgument)) 10429 return false; 10430 } 10431 return true; 10432 } 10433 10434 SDValue 10435 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10436 bool IsVarArg, 10437 const SmallVectorImpl<ISD::OutputArg> &Outs, 10438 const SmallVectorImpl<SDValue> &OutVals, 10439 const SDLoc &DL, SelectionDAG &DAG) const { 10440 const MachineFunction &MF = DAG.getMachineFunction(); 10441 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10442 10443 // Stores the assignment of the return value to a location. 10444 SmallVector<CCValAssign, 16> RVLocs; 10445 10446 // Info about the registers and stack slot. 10447 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10448 *DAG.getContext()); 10449 10450 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10451 nullptr, CC_RISCV); 10452 10453 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10454 report_fatal_error("GHC functions return void only"); 10455 10456 SDValue Glue; 10457 SmallVector<SDValue, 4> RetOps(1, Chain); 10458 10459 // Copy the result values into the output registers. 10460 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10461 SDValue Val = OutVals[i]; 10462 CCValAssign &VA = RVLocs[i]; 10463 assert(VA.isRegLoc() && "Can only return in registers!"); 10464 10465 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10466 // Handle returning f64 on RV32D with a soft float ABI. 10467 assert(VA.isRegLoc() && "Expected return via registers"); 10468 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10469 DAG.getVTList(MVT::i32, MVT::i32), Val); 10470 SDValue Lo = SplitF64.getValue(0); 10471 SDValue Hi = SplitF64.getValue(1); 10472 Register RegLo = VA.getLocReg(); 10473 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10474 Register RegHi = RegLo + 1; 10475 10476 if (STI.isRegisterReservedByUser(RegLo) || 10477 STI.isRegisterReservedByUser(RegHi)) 10478 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10479 MF.getFunction(), 10480 "Return value register required, but has been reserved."}); 10481 10482 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10483 Glue = Chain.getValue(1); 10484 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10485 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10486 Glue = Chain.getValue(1); 10487 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10488 } else { 10489 // Handle a 'normal' return. 10490 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10491 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10492 10493 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10494 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10495 MF.getFunction(), 10496 "Return value register required, but has been reserved."}); 10497 10498 // Guarantee that all emitted copies are stuck together. 10499 Glue = Chain.getValue(1); 10500 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10501 } 10502 } 10503 10504 RetOps[0] = Chain; // Update chain. 10505 10506 // Add the glue node if we have it. 10507 if (Glue.getNode()) { 10508 RetOps.push_back(Glue); 10509 } 10510 10511 unsigned RetOpc = RISCVISD::RET_FLAG; 10512 // Interrupt service routines use different return instructions. 10513 const Function &Func = DAG.getMachineFunction().getFunction(); 10514 if (Func.hasFnAttribute("interrupt")) { 10515 if (!Func.getReturnType()->isVoidTy()) 10516 report_fatal_error( 10517 "Functions with the interrupt attribute must have void return type!"); 10518 10519 MachineFunction &MF = DAG.getMachineFunction(); 10520 StringRef Kind = 10521 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10522 10523 if (Kind == "user") 10524 RetOpc = RISCVISD::URET_FLAG; 10525 else if (Kind == "supervisor") 10526 RetOpc = RISCVISD::SRET_FLAG; 10527 else 10528 RetOpc = RISCVISD::MRET_FLAG; 10529 } 10530 10531 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10532 } 10533 10534 void RISCVTargetLowering::validateCCReservedRegs( 10535 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10536 MachineFunction &MF) const { 10537 const Function &F = MF.getFunction(); 10538 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10539 10540 if (llvm::any_of(Regs, [&STI](auto Reg) { 10541 return STI.isRegisterReservedByUser(Reg.first); 10542 })) 10543 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10544 F, "Argument register required, but has been reserved."}); 10545 } 10546 10547 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10548 return CI->isTailCall(); 10549 } 10550 10551 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10552 #define NODE_NAME_CASE(NODE) \ 10553 case RISCVISD::NODE: \ 10554 return "RISCVISD::" #NODE; 10555 // clang-format off 10556 switch ((RISCVISD::NodeType)Opcode) { 10557 case RISCVISD::FIRST_NUMBER: 10558 break; 10559 NODE_NAME_CASE(RET_FLAG) 10560 NODE_NAME_CASE(URET_FLAG) 10561 NODE_NAME_CASE(SRET_FLAG) 10562 NODE_NAME_CASE(MRET_FLAG) 10563 NODE_NAME_CASE(CALL) 10564 NODE_NAME_CASE(SELECT_CC) 10565 NODE_NAME_CASE(BR_CC) 10566 NODE_NAME_CASE(BuildPairF64) 10567 NODE_NAME_CASE(SplitF64) 10568 NODE_NAME_CASE(TAIL) 10569 NODE_NAME_CASE(MULHSU) 10570 NODE_NAME_CASE(SLLW) 10571 NODE_NAME_CASE(SRAW) 10572 NODE_NAME_CASE(SRLW) 10573 NODE_NAME_CASE(DIVW) 10574 NODE_NAME_CASE(DIVUW) 10575 NODE_NAME_CASE(REMUW) 10576 NODE_NAME_CASE(ROLW) 10577 NODE_NAME_CASE(RORW) 10578 NODE_NAME_CASE(CLZW) 10579 NODE_NAME_CASE(CTZW) 10580 NODE_NAME_CASE(FSLW) 10581 NODE_NAME_CASE(FSRW) 10582 NODE_NAME_CASE(FSL) 10583 NODE_NAME_CASE(FSR) 10584 NODE_NAME_CASE(FMV_H_X) 10585 NODE_NAME_CASE(FMV_X_ANYEXTH) 10586 NODE_NAME_CASE(FMV_X_SIGNEXTH) 10587 NODE_NAME_CASE(FMV_W_X_RV64) 10588 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10589 NODE_NAME_CASE(FCVT_X) 10590 NODE_NAME_CASE(FCVT_XU) 10591 NODE_NAME_CASE(FCVT_W_RV64) 10592 NODE_NAME_CASE(FCVT_WU_RV64) 10593 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10594 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10595 NODE_NAME_CASE(READ_CYCLE_WIDE) 10596 NODE_NAME_CASE(GREV) 10597 NODE_NAME_CASE(GREVW) 10598 NODE_NAME_CASE(GORC) 10599 NODE_NAME_CASE(GORCW) 10600 NODE_NAME_CASE(SHFL) 10601 NODE_NAME_CASE(SHFLW) 10602 NODE_NAME_CASE(UNSHFL) 10603 NODE_NAME_CASE(UNSHFLW) 10604 NODE_NAME_CASE(BFP) 10605 NODE_NAME_CASE(BFPW) 10606 NODE_NAME_CASE(BCOMPRESS) 10607 NODE_NAME_CASE(BCOMPRESSW) 10608 NODE_NAME_CASE(BDECOMPRESS) 10609 NODE_NAME_CASE(BDECOMPRESSW) 10610 NODE_NAME_CASE(VMV_V_X_VL) 10611 NODE_NAME_CASE(VFMV_V_F_VL) 10612 NODE_NAME_CASE(VMV_X_S) 10613 NODE_NAME_CASE(VMV_S_X_VL) 10614 NODE_NAME_CASE(VFMV_S_F_VL) 10615 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10616 NODE_NAME_CASE(READ_VLENB) 10617 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10618 NODE_NAME_CASE(VSLIDEUP_VL) 10619 NODE_NAME_CASE(VSLIDE1UP_VL) 10620 NODE_NAME_CASE(VSLIDEDOWN_VL) 10621 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10622 NODE_NAME_CASE(VID_VL) 10623 NODE_NAME_CASE(VFNCVT_ROD_VL) 10624 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10625 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10626 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10627 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10628 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10629 NODE_NAME_CASE(VECREDUCE_AND_VL) 10630 NODE_NAME_CASE(VECREDUCE_OR_VL) 10631 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10632 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10633 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10634 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10635 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10636 NODE_NAME_CASE(ADD_VL) 10637 NODE_NAME_CASE(AND_VL) 10638 NODE_NAME_CASE(MUL_VL) 10639 NODE_NAME_CASE(OR_VL) 10640 NODE_NAME_CASE(SDIV_VL) 10641 NODE_NAME_CASE(SHL_VL) 10642 NODE_NAME_CASE(SREM_VL) 10643 NODE_NAME_CASE(SRA_VL) 10644 NODE_NAME_CASE(SRL_VL) 10645 NODE_NAME_CASE(SUB_VL) 10646 NODE_NAME_CASE(UDIV_VL) 10647 NODE_NAME_CASE(UREM_VL) 10648 NODE_NAME_CASE(XOR_VL) 10649 NODE_NAME_CASE(SADDSAT_VL) 10650 NODE_NAME_CASE(UADDSAT_VL) 10651 NODE_NAME_CASE(SSUBSAT_VL) 10652 NODE_NAME_CASE(USUBSAT_VL) 10653 NODE_NAME_CASE(FADD_VL) 10654 NODE_NAME_CASE(FSUB_VL) 10655 NODE_NAME_CASE(FMUL_VL) 10656 NODE_NAME_CASE(FDIV_VL) 10657 NODE_NAME_CASE(FNEG_VL) 10658 NODE_NAME_CASE(FABS_VL) 10659 NODE_NAME_CASE(FSQRT_VL) 10660 NODE_NAME_CASE(FMA_VL) 10661 NODE_NAME_CASE(FCOPYSIGN_VL) 10662 NODE_NAME_CASE(SMIN_VL) 10663 NODE_NAME_CASE(SMAX_VL) 10664 NODE_NAME_CASE(UMIN_VL) 10665 NODE_NAME_CASE(UMAX_VL) 10666 NODE_NAME_CASE(FMINNUM_VL) 10667 NODE_NAME_CASE(FMAXNUM_VL) 10668 NODE_NAME_CASE(MULHS_VL) 10669 NODE_NAME_CASE(MULHU_VL) 10670 NODE_NAME_CASE(FP_TO_SINT_VL) 10671 NODE_NAME_CASE(FP_TO_UINT_VL) 10672 NODE_NAME_CASE(SINT_TO_FP_VL) 10673 NODE_NAME_CASE(UINT_TO_FP_VL) 10674 NODE_NAME_CASE(FP_EXTEND_VL) 10675 NODE_NAME_CASE(FP_ROUND_VL) 10676 NODE_NAME_CASE(VWMUL_VL) 10677 NODE_NAME_CASE(VWMULU_VL) 10678 NODE_NAME_CASE(VWMULSU_VL) 10679 NODE_NAME_CASE(VWADD_VL) 10680 NODE_NAME_CASE(VWADDU_VL) 10681 NODE_NAME_CASE(VWSUB_VL) 10682 NODE_NAME_CASE(VWSUBU_VL) 10683 NODE_NAME_CASE(VWADD_W_VL) 10684 NODE_NAME_CASE(VWADDU_W_VL) 10685 NODE_NAME_CASE(VWSUB_W_VL) 10686 NODE_NAME_CASE(VWSUBU_W_VL) 10687 NODE_NAME_CASE(SETCC_VL) 10688 NODE_NAME_CASE(VSELECT_VL) 10689 NODE_NAME_CASE(VP_MERGE_VL) 10690 NODE_NAME_CASE(VMAND_VL) 10691 NODE_NAME_CASE(VMOR_VL) 10692 NODE_NAME_CASE(VMXOR_VL) 10693 NODE_NAME_CASE(VMCLR_VL) 10694 NODE_NAME_CASE(VMSET_VL) 10695 NODE_NAME_CASE(VRGATHER_VX_VL) 10696 NODE_NAME_CASE(VRGATHER_VV_VL) 10697 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10698 NODE_NAME_CASE(VSEXT_VL) 10699 NODE_NAME_CASE(VZEXT_VL) 10700 NODE_NAME_CASE(VCPOP_VL) 10701 NODE_NAME_CASE(VLE_VL) 10702 NODE_NAME_CASE(VSE_VL) 10703 NODE_NAME_CASE(READ_CSR) 10704 NODE_NAME_CASE(WRITE_CSR) 10705 NODE_NAME_CASE(SWAP_CSR) 10706 } 10707 // clang-format on 10708 return nullptr; 10709 #undef NODE_NAME_CASE 10710 } 10711 10712 /// getConstraintType - Given a constraint letter, return the type of 10713 /// constraint it is for this target. 10714 RISCVTargetLowering::ConstraintType 10715 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 10716 if (Constraint.size() == 1) { 10717 switch (Constraint[0]) { 10718 default: 10719 break; 10720 case 'f': 10721 return C_RegisterClass; 10722 case 'I': 10723 case 'J': 10724 case 'K': 10725 return C_Immediate; 10726 case 'A': 10727 return C_Memory; 10728 case 'S': // A symbolic address 10729 return C_Other; 10730 } 10731 } else { 10732 if (Constraint == "vr" || Constraint == "vm") 10733 return C_RegisterClass; 10734 } 10735 return TargetLowering::getConstraintType(Constraint); 10736 } 10737 10738 std::pair<unsigned, const TargetRegisterClass *> 10739 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10740 StringRef Constraint, 10741 MVT VT) const { 10742 // First, see if this is a constraint that directly corresponds to a 10743 // RISCV register class. 10744 if (Constraint.size() == 1) { 10745 switch (Constraint[0]) { 10746 case 'r': 10747 // TODO: Support fixed vectors up to XLen for P extension? 10748 if (VT.isVector()) 10749 break; 10750 return std::make_pair(0U, &RISCV::GPRRegClass); 10751 case 'f': 10752 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 10753 return std::make_pair(0U, &RISCV::FPR16RegClass); 10754 if (Subtarget.hasStdExtF() && VT == MVT::f32) 10755 return std::make_pair(0U, &RISCV::FPR32RegClass); 10756 if (Subtarget.hasStdExtD() && VT == MVT::f64) 10757 return std::make_pair(0U, &RISCV::FPR64RegClass); 10758 break; 10759 default: 10760 break; 10761 } 10762 } else if (Constraint == "vr") { 10763 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 10764 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10765 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 10766 return std::make_pair(0U, RC); 10767 } 10768 } else if (Constraint == "vm") { 10769 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 10770 return std::make_pair(0U, &RISCV::VMV0RegClass); 10771 } 10772 10773 // Clang will correctly decode the usage of register name aliases into their 10774 // official names. However, other frontends like `rustc` do not. This allows 10775 // users of these frontends to use the ABI names for registers in LLVM-style 10776 // register constraints. 10777 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 10778 .Case("{zero}", RISCV::X0) 10779 .Case("{ra}", RISCV::X1) 10780 .Case("{sp}", RISCV::X2) 10781 .Case("{gp}", RISCV::X3) 10782 .Case("{tp}", RISCV::X4) 10783 .Case("{t0}", RISCV::X5) 10784 .Case("{t1}", RISCV::X6) 10785 .Case("{t2}", RISCV::X7) 10786 .Cases("{s0}", "{fp}", RISCV::X8) 10787 .Case("{s1}", RISCV::X9) 10788 .Case("{a0}", RISCV::X10) 10789 .Case("{a1}", RISCV::X11) 10790 .Case("{a2}", RISCV::X12) 10791 .Case("{a3}", RISCV::X13) 10792 .Case("{a4}", RISCV::X14) 10793 .Case("{a5}", RISCV::X15) 10794 .Case("{a6}", RISCV::X16) 10795 .Case("{a7}", RISCV::X17) 10796 .Case("{s2}", RISCV::X18) 10797 .Case("{s3}", RISCV::X19) 10798 .Case("{s4}", RISCV::X20) 10799 .Case("{s5}", RISCV::X21) 10800 .Case("{s6}", RISCV::X22) 10801 .Case("{s7}", RISCV::X23) 10802 .Case("{s8}", RISCV::X24) 10803 .Case("{s9}", RISCV::X25) 10804 .Case("{s10}", RISCV::X26) 10805 .Case("{s11}", RISCV::X27) 10806 .Case("{t3}", RISCV::X28) 10807 .Case("{t4}", RISCV::X29) 10808 .Case("{t5}", RISCV::X30) 10809 .Case("{t6}", RISCV::X31) 10810 .Default(RISCV::NoRegister); 10811 if (XRegFromAlias != RISCV::NoRegister) 10812 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 10813 10814 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 10815 // TableGen record rather than the AsmName to choose registers for InlineAsm 10816 // constraints, plus we want to match those names to the widest floating point 10817 // register type available, manually select floating point registers here. 10818 // 10819 // The second case is the ABI name of the register, so that frontends can also 10820 // use the ABI names in register constraint lists. 10821 if (Subtarget.hasStdExtF()) { 10822 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 10823 .Cases("{f0}", "{ft0}", RISCV::F0_F) 10824 .Cases("{f1}", "{ft1}", RISCV::F1_F) 10825 .Cases("{f2}", "{ft2}", RISCV::F2_F) 10826 .Cases("{f3}", "{ft3}", RISCV::F3_F) 10827 .Cases("{f4}", "{ft4}", RISCV::F4_F) 10828 .Cases("{f5}", "{ft5}", RISCV::F5_F) 10829 .Cases("{f6}", "{ft6}", RISCV::F6_F) 10830 .Cases("{f7}", "{ft7}", RISCV::F7_F) 10831 .Cases("{f8}", "{fs0}", RISCV::F8_F) 10832 .Cases("{f9}", "{fs1}", RISCV::F9_F) 10833 .Cases("{f10}", "{fa0}", RISCV::F10_F) 10834 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10835 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10836 .Cases("{f13}", "{fa3}", RISCV::F13_F) 10837 .Cases("{f14}", "{fa4}", RISCV::F14_F) 10838 .Cases("{f15}", "{fa5}", RISCV::F15_F) 10839 .Cases("{f16}", "{fa6}", RISCV::F16_F) 10840 .Cases("{f17}", "{fa7}", RISCV::F17_F) 10841 .Cases("{f18}", "{fs2}", RISCV::F18_F) 10842 .Cases("{f19}", "{fs3}", RISCV::F19_F) 10843 .Cases("{f20}", "{fs4}", RISCV::F20_F) 10844 .Cases("{f21}", "{fs5}", RISCV::F21_F) 10845 .Cases("{f22}", "{fs6}", RISCV::F22_F) 10846 .Cases("{f23}", "{fs7}", RISCV::F23_F) 10847 .Cases("{f24}", "{fs8}", RISCV::F24_F) 10848 .Cases("{f25}", "{fs9}", RISCV::F25_F) 10849 .Cases("{f26}", "{fs10}", RISCV::F26_F) 10850 .Cases("{f27}", "{fs11}", RISCV::F27_F) 10851 .Cases("{f28}", "{ft8}", RISCV::F28_F) 10852 .Cases("{f29}", "{ft9}", RISCV::F29_F) 10853 .Cases("{f30}", "{ft10}", RISCV::F30_F) 10854 .Cases("{f31}", "{ft11}", RISCV::F31_F) 10855 .Default(RISCV::NoRegister); 10856 if (FReg != RISCV::NoRegister) { 10857 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 10858 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 10859 unsigned RegNo = FReg - RISCV::F0_F; 10860 unsigned DReg = RISCV::F0_D + RegNo; 10861 return std::make_pair(DReg, &RISCV::FPR64RegClass); 10862 } 10863 if (VT == MVT::f32 || VT == MVT::Other) 10864 return std::make_pair(FReg, &RISCV::FPR32RegClass); 10865 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 10866 unsigned RegNo = FReg - RISCV::F0_F; 10867 unsigned HReg = RISCV::F0_H + RegNo; 10868 return std::make_pair(HReg, &RISCV::FPR16RegClass); 10869 } 10870 } 10871 } 10872 10873 if (Subtarget.hasVInstructions()) { 10874 Register VReg = StringSwitch<Register>(Constraint.lower()) 10875 .Case("{v0}", RISCV::V0) 10876 .Case("{v1}", RISCV::V1) 10877 .Case("{v2}", RISCV::V2) 10878 .Case("{v3}", RISCV::V3) 10879 .Case("{v4}", RISCV::V4) 10880 .Case("{v5}", RISCV::V5) 10881 .Case("{v6}", RISCV::V6) 10882 .Case("{v7}", RISCV::V7) 10883 .Case("{v8}", RISCV::V8) 10884 .Case("{v9}", RISCV::V9) 10885 .Case("{v10}", RISCV::V10) 10886 .Case("{v11}", RISCV::V11) 10887 .Case("{v12}", RISCV::V12) 10888 .Case("{v13}", RISCV::V13) 10889 .Case("{v14}", RISCV::V14) 10890 .Case("{v15}", RISCV::V15) 10891 .Case("{v16}", RISCV::V16) 10892 .Case("{v17}", RISCV::V17) 10893 .Case("{v18}", RISCV::V18) 10894 .Case("{v19}", RISCV::V19) 10895 .Case("{v20}", RISCV::V20) 10896 .Case("{v21}", RISCV::V21) 10897 .Case("{v22}", RISCV::V22) 10898 .Case("{v23}", RISCV::V23) 10899 .Case("{v24}", RISCV::V24) 10900 .Case("{v25}", RISCV::V25) 10901 .Case("{v26}", RISCV::V26) 10902 .Case("{v27}", RISCV::V27) 10903 .Case("{v28}", RISCV::V28) 10904 .Case("{v29}", RISCV::V29) 10905 .Case("{v30}", RISCV::V30) 10906 .Case("{v31}", RISCV::V31) 10907 .Default(RISCV::NoRegister); 10908 if (VReg != RISCV::NoRegister) { 10909 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 10910 return std::make_pair(VReg, &RISCV::VMRegClass); 10911 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 10912 return std::make_pair(VReg, &RISCV::VRRegClass); 10913 for (const auto *RC : 10914 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10915 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 10916 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 10917 return std::make_pair(VReg, RC); 10918 } 10919 } 10920 } 10921 } 10922 10923 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10924 } 10925 10926 unsigned 10927 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 10928 // Currently only support length 1 constraints. 10929 if (ConstraintCode.size() == 1) { 10930 switch (ConstraintCode[0]) { 10931 case 'A': 10932 return InlineAsm::Constraint_A; 10933 default: 10934 break; 10935 } 10936 } 10937 10938 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 10939 } 10940 10941 void RISCVTargetLowering::LowerAsmOperandForConstraint( 10942 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 10943 SelectionDAG &DAG) const { 10944 // Currently only support length 1 constraints. 10945 if (Constraint.length() == 1) { 10946 switch (Constraint[0]) { 10947 case 'I': 10948 // Validate & create a 12-bit signed immediate operand. 10949 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10950 uint64_t CVal = C->getSExtValue(); 10951 if (isInt<12>(CVal)) 10952 Ops.push_back( 10953 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10954 } 10955 return; 10956 case 'J': 10957 // Validate & create an integer zero operand. 10958 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 10959 if (C->getZExtValue() == 0) 10960 Ops.push_back( 10961 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 10962 return; 10963 case 'K': 10964 // Validate & create a 5-bit unsigned immediate operand. 10965 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10966 uint64_t CVal = C->getZExtValue(); 10967 if (isUInt<5>(CVal)) 10968 Ops.push_back( 10969 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10970 } 10971 return; 10972 case 'S': 10973 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 10974 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 10975 GA->getValueType(0))); 10976 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 10977 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 10978 BA->getValueType(0))); 10979 } 10980 return; 10981 default: 10982 break; 10983 } 10984 } 10985 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 10986 } 10987 10988 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 10989 Instruction *Inst, 10990 AtomicOrdering Ord) const { 10991 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 10992 return Builder.CreateFence(Ord); 10993 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 10994 return Builder.CreateFence(AtomicOrdering::Release); 10995 return nullptr; 10996 } 10997 10998 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 10999 Instruction *Inst, 11000 AtomicOrdering Ord) const { 11001 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11002 return Builder.CreateFence(AtomicOrdering::Acquire); 11003 return nullptr; 11004 } 11005 11006 TargetLowering::AtomicExpansionKind 11007 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11008 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11009 // point operations can't be used in an lr/sc sequence without breaking the 11010 // forward-progress guarantee. 11011 if (AI->isFloatingPointOperation()) 11012 return AtomicExpansionKind::CmpXChg; 11013 11014 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11015 if (Size == 8 || Size == 16) 11016 return AtomicExpansionKind::MaskedIntrinsic; 11017 return AtomicExpansionKind::None; 11018 } 11019 11020 static Intrinsic::ID 11021 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11022 if (XLen == 32) { 11023 switch (BinOp) { 11024 default: 11025 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11026 case AtomicRMWInst::Xchg: 11027 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11028 case AtomicRMWInst::Add: 11029 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11030 case AtomicRMWInst::Sub: 11031 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11032 case AtomicRMWInst::Nand: 11033 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11034 case AtomicRMWInst::Max: 11035 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11036 case AtomicRMWInst::Min: 11037 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11038 case AtomicRMWInst::UMax: 11039 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11040 case AtomicRMWInst::UMin: 11041 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11042 } 11043 } 11044 11045 if (XLen == 64) { 11046 switch (BinOp) { 11047 default: 11048 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11049 case AtomicRMWInst::Xchg: 11050 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11051 case AtomicRMWInst::Add: 11052 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11053 case AtomicRMWInst::Sub: 11054 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11055 case AtomicRMWInst::Nand: 11056 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11057 case AtomicRMWInst::Max: 11058 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11059 case AtomicRMWInst::Min: 11060 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11061 case AtomicRMWInst::UMax: 11062 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11063 case AtomicRMWInst::UMin: 11064 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11065 } 11066 } 11067 11068 llvm_unreachable("Unexpected XLen\n"); 11069 } 11070 11071 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11072 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11073 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11074 unsigned XLen = Subtarget.getXLen(); 11075 Value *Ordering = 11076 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11077 Type *Tys[] = {AlignedAddr->getType()}; 11078 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11079 AI->getModule(), 11080 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11081 11082 if (XLen == 64) { 11083 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11084 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11085 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11086 } 11087 11088 Value *Result; 11089 11090 // Must pass the shift amount needed to sign extend the loaded value prior 11091 // to performing a signed comparison for min/max. ShiftAmt is the number of 11092 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11093 // is the number of bits to left+right shift the value in order to 11094 // sign-extend. 11095 if (AI->getOperation() == AtomicRMWInst::Min || 11096 AI->getOperation() == AtomicRMWInst::Max) { 11097 const DataLayout &DL = AI->getModule()->getDataLayout(); 11098 unsigned ValWidth = 11099 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11100 Value *SextShamt = 11101 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11102 Result = Builder.CreateCall(LrwOpScwLoop, 11103 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11104 } else { 11105 Result = 11106 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11107 } 11108 11109 if (XLen == 64) 11110 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11111 return Result; 11112 } 11113 11114 TargetLowering::AtomicExpansionKind 11115 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11116 AtomicCmpXchgInst *CI) const { 11117 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11118 if (Size == 8 || Size == 16) 11119 return AtomicExpansionKind::MaskedIntrinsic; 11120 return AtomicExpansionKind::None; 11121 } 11122 11123 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11124 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11125 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11126 unsigned XLen = Subtarget.getXLen(); 11127 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11128 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11129 if (XLen == 64) { 11130 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11131 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11132 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11133 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11134 } 11135 Type *Tys[] = {AlignedAddr->getType()}; 11136 Function *MaskedCmpXchg = 11137 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11138 Value *Result = Builder.CreateCall( 11139 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11140 if (XLen == 64) 11141 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11142 return Result; 11143 } 11144 11145 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11146 return false; 11147 } 11148 11149 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11150 EVT VT) const { 11151 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11152 return false; 11153 11154 switch (FPVT.getSimpleVT().SimpleTy) { 11155 case MVT::f16: 11156 return Subtarget.hasStdExtZfh(); 11157 case MVT::f32: 11158 return Subtarget.hasStdExtF(); 11159 case MVT::f64: 11160 return Subtarget.hasStdExtD(); 11161 default: 11162 return false; 11163 } 11164 } 11165 11166 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11167 // If we are using the small code model, we can reduce size of jump table 11168 // entry to 4 bytes. 11169 if (Subtarget.is64Bit() && !isPositionIndependent() && 11170 getTargetMachine().getCodeModel() == CodeModel::Small) { 11171 return MachineJumpTableInfo::EK_Custom32; 11172 } 11173 return TargetLowering::getJumpTableEncoding(); 11174 } 11175 11176 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11177 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11178 unsigned uid, MCContext &Ctx) const { 11179 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11180 getTargetMachine().getCodeModel() == CodeModel::Small); 11181 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11182 } 11183 11184 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11185 EVT VT) const { 11186 VT = VT.getScalarType(); 11187 11188 if (!VT.isSimple()) 11189 return false; 11190 11191 switch (VT.getSimpleVT().SimpleTy) { 11192 case MVT::f16: 11193 return Subtarget.hasStdExtZfh(); 11194 case MVT::f32: 11195 return Subtarget.hasStdExtF(); 11196 case MVT::f64: 11197 return Subtarget.hasStdExtD(); 11198 default: 11199 break; 11200 } 11201 11202 return false; 11203 } 11204 11205 Register RISCVTargetLowering::getExceptionPointerRegister( 11206 const Constant *PersonalityFn) const { 11207 return RISCV::X10; 11208 } 11209 11210 Register RISCVTargetLowering::getExceptionSelectorRegister( 11211 const Constant *PersonalityFn) const { 11212 return RISCV::X11; 11213 } 11214 11215 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11216 // Return false to suppress the unnecessary extensions if the LibCall 11217 // arguments or return value is f32 type for LP64 ABI. 11218 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11219 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11220 return false; 11221 11222 return true; 11223 } 11224 11225 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11226 if (Subtarget.is64Bit() && Type == MVT::i32) 11227 return true; 11228 11229 return IsSigned; 11230 } 11231 11232 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11233 SDValue C) const { 11234 // Check integral scalar types. 11235 if (VT.isScalarInteger()) { 11236 // Omit the optimization if the sub target has the M extension and the data 11237 // size exceeds XLen. 11238 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11239 return false; 11240 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11241 // Break the MUL to a SLLI and an ADD/SUB. 11242 const APInt &Imm = ConstNode->getAPIntValue(); 11243 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11244 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11245 return true; 11246 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11247 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11248 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11249 (Imm - 8).isPowerOf2())) 11250 return true; 11251 // Omit the following optimization if the sub target has the M extension 11252 // and the data size >= XLen. 11253 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11254 return false; 11255 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11256 // a pair of LUI/ADDI. 11257 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11258 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11259 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11260 (1 - ImmS).isPowerOf2()) 11261 return true; 11262 } 11263 } 11264 } 11265 11266 return false; 11267 } 11268 11269 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11270 SDValue ConstNode) const { 11271 // Let the DAGCombiner decide for vectors. 11272 EVT VT = AddNode.getValueType(); 11273 if (VT.isVector()) 11274 return true; 11275 11276 // Let the DAGCombiner decide for larger types. 11277 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11278 return true; 11279 11280 // It is worse if c1 is simm12 while c1*c2 is not. 11281 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11282 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11283 const APInt &C1 = C1Node->getAPIntValue(); 11284 const APInt &C2 = C2Node->getAPIntValue(); 11285 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11286 return false; 11287 11288 // Default to true and let the DAGCombiner decide. 11289 return true; 11290 } 11291 11292 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11293 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11294 bool *Fast) const { 11295 if (!VT.isVector()) 11296 return false; 11297 11298 EVT ElemVT = VT.getVectorElementType(); 11299 if (Alignment >= ElemVT.getStoreSize()) { 11300 if (Fast) 11301 *Fast = true; 11302 return true; 11303 } 11304 11305 return false; 11306 } 11307 11308 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11309 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11310 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11311 bool IsABIRegCopy = CC.hasValue(); 11312 EVT ValueVT = Val.getValueType(); 11313 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11314 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11315 // and cast to f32. 11316 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11317 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11318 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11319 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11320 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11321 Parts[0] = Val; 11322 return true; 11323 } 11324 11325 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11326 LLVMContext &Context = *DAG.getContext(); 11327 EVT ValueEltVT = ValueVT.getVectorElementType(); 11328 EVT PartEltVT = PartVT.getVectorElementType(); 11329 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11330 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11331 if (PartVTBitSize % ValueVTBitSize == 0) { 11332 assert(PartVTBitSize >= ValueVTBitSize); 11333 // If the element types are different, bitcast to the same element type of 11334 // PartVT first. 11335 // Give an example here, we want copy a <vscale x 1 x i8> value to 11336 // <vscale x 4 x i16>. 11337 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11338 // subvector, then we can bitcast to <vscale x 4 x i16>. 11339 if (ValueEltVT != PartEltVT) { 11340 if (PartVTBitSize > ValueVTBitSize) { 11341 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11342 assert(Count != 0 && "The number of element should not be zero."); 11343 EVT SameEltTypeVT = 11344 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11345 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11346 DAG.getUNDEF(SameEltTypeVT), Val, 11347 DAG.getVectorIdxConstant(0, DL)); 11348 } 11349 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11350 } else { 11351 Val = 11352 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11353 Val, DAG.getVectorIdxConstant(0, DL)); 11354 } 11355 Parts[0] = Val; 11356 return true; 11357 } 11358 } 11359 return false; 11360 } 11361 11362 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11363 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11364 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11365 bool IsABIRegCopy = CC.hasValue(); 11366 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11367 SDValue Val = Parts[0]; 11368 11369 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11370 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11371 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11372 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11373 return Val; 11374 } 11375 11376 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11377 LLVMContext &Context = *DAG.getContext(); 11378 SDValue Val = Parts[0]; 11379 EVT ValueEltVT = ValueVT.getVectorElementType(); 11380 EVT PartEltVT = PartVT.getVectorElementType(); 11381 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11382 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11383 if (PartVTBitSize % ValueVTBitSize == 0) { 11384 assert(PartVTBitSize >= ValueVTBitSize); 11385 EVT SameEltTypeVT = ValueVT; 11386 // If the element types are different, convert it to the same element type 11387 // of PartVT. 11388 // Give an example here, we want copy a <vscale x 1 x i8> value from 11389 // <vscale x 4 x i16>. 11390 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11391 // then we can extract <vscale x 1 x i8>. 11392 if (ValueEltVT != PartEltVT) { 11393 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11394 assert(Count != 0 && "The number of element should not be zero."); 11395 SameEltTypeVT = 11396 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11397 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11398 } 11399 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11400 DAG.getVectorIdxConstant(0, DL)); 11401 return Val; 11402 } 11403 } 11404 return SDValue(); 11405 } 11406 11407 SDValue 11408 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11409 SelectionDAG &DAG, 11410 SmallVectorImpl<SDNode *> &Created) const { 11411 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11412 if (isIntDivCheap(N->getValueType(0), Attr)) 11413 return SDValue(N, 0); // Lower SDIV as SDIV 11414 11415 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11416 "Unexpected divisor!"); 11417 11418 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11419 if (!Subtarget.hasStdExtZbt()) 11420 return SDValue(); 11421 11422 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11423 // Besides, more critical path instructions will be generated when dividing 11424 // by 2. So we keep using the original DAGs for these cases. 11425 unsigned Lg2 = Divisor.countTrailingZeros(); 11426 if (Lg2 == 1 || Lg2 >= 12) 11427 return SDValue(); 11428 11429 // fold (sdiv X, pow2) 11430 EVT VT = N->getValueType(0); 11431 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11432 return SDValue(); 11433 11434 SDLoc DL(N); 11435 SDValue N0 = N->getOperand(0); 11436 SDValue Zero = DAG.getConstant(0, DL, VT); 11437 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11438 11439 // Add (N0 < 0) ? Pow2 - 1 : 0; 11440 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11441 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11442 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11443 11444 Created.push_back(Cmp.getNode()); 11445 Created.push_back(Add.getNode()); 11446 Created.push_back(Sel.getNode()); 11447 11448 // Divide by pow2. 11449 SDValue SRA = 11450 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11451 11452 // If we're dividing by a positive value, we're done. Otherwise, we must 11453 // negate the result. 11454 if (Divisor.isNonNegative()) 11455 return SRA; 11456 11457 Created.push_back(SRA.getNode()); 11458 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11459 } 11460 11461 #define GET_REGISTER_MATCHER 11462 #include "RISCVGenAsmMatcher.inc" 11463 11464 Register 11465 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11466 const MachineFunction &MF) const { 11467 Register Reg = MatchRegisterAltName(RegName); 11468 if (Reg == RISCV::NoRegister) 11469 Reg = MatchRegisterName(RegName); 11470 if (Reg == RISCV::NoRegister) 11471 report_fatal_error( 11472 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11473 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11474 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11475 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11476 StringRef(RegName) + "\".")); 11477 return Reg; 11478 } 11479 11480 namespace llvm { 11481 namespace RISCVVIntrinsicsTable { 11482 11483 #define GET_RISCVVIntrinsicsTable_IMPL 11484 #include "RISCVGenSearchableTables.inc" 11485 11486 } // namespace RISCVVIntrinsicsTable 11487 11488 } // namespace llvm 11489