1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 116 assert(Size <= 512 && isPowerOf2_32(Size)); 117 const TargetRegisterClass *RC; 118 if (Size <= 64) 119 RC = &RISCV::VRRegClass; 120 else if (Size == 128) 121 RC = &RISCV::VRM2RegClass; 122 else if (Size == 256) 123 RC = &RISCV::VRM4RegClass; 124 else 125 RC = &RISCV::VRM8RegClass; 126 127 addRegisterClass(VT, RC); 128 }; 129 130 for (MVT VT : BoolVecVTs) 131 addRegClassForRVV(VT); 132 for (MVT VT : IntVecVTs) { 133 if (VT.getVectorElementType() == MVT::i64 && 134 !Subtarget.hasVInstructionsI64()) 135 continue; 136 addRegClassForRVV(VT); 137 } 138 139 if (Subtarget.hasVInstructionsF16()) 140 for (MVT VT : F16VecVTs) 141 addRegClassForRVV(VT); 142 143 if (Subtarget.hasVInstructionsF32()) 144 for (MVT VT : F32VecVTs) 145 addRegClassForRVV(VT); 146 147 if (Subtarget.hasVInstructionsF64()) 148 for (MVT VT : F64VecVTs) 149 addRegClassForRVV(VT); 150 151 if (Subtarget.useRVVForFixedLengthVectors()) { 152 auto addRegClassForFixedVectors = [this](MVT VT) { 153 MVT ContainerVT = getContainerForFixedLengthVector(VT); 154 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 155 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 156 addRegisterClass(VT, TRI.getRegClass(RCID)); 157 }; 158 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 159 if (useRVVForFixedLengthVectorVT(VT)) 160 addRegClassForFixedVectors(VT); 161 162 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 163 if (useRVVForFixedLengthVectorVT(VT)) 164 addRegClassForFixedVectors(VT); 165 } 166 } 167 168 // Compute derived properties from the register classes. 169 computeRegisterProperties(STI.getRegisterInfo()); 170 171 setStackPointerRegisterToSaveRestore(RISCV::X2); 172 173 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 174 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 175 176 // TODO: add all necessary setOperationAction calls. 177 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 178 179 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 180 setOperationAction(ISD::BR_CC, XLenVT, Expand); 181 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 182 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 183 184 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 185 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 186 187 setOperationAction(ISD::VASTART, MVT::Other, Custom); 188 setOperationAction(ISD::VAARG, MVT::Other, Expand); 189 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 190 setOperationAction(ISD::VAEND, MVT::Other, Expand); 191 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 193 if (!Subtarget.hasStdExtZbb()) { 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 196 } 197 198 if (Subtarget.is64Bit()) { 199 setOperationAction(ISD::ADD, MVT::i32, Custom); 200 setOperationAction(ISD::SUB, MVT::i32, Custom); 201 setOperationAction(ISD::SHL, MVT::i32, Custom); 202 setOperationAction(ISD::SRA, MVT::i32, Custom); 203 setOperationAction(ISD::SRL, MVT::i32, Custom); 204 205 setOperationAction(ISD::UADDO, MVT::i32, Custom); 206 setOperationAction(ISD::USUBO, MVT::i32, Custom); 207 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 208 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 209 } else { 210 setLibcallName(RTLIB::SHL_I128, nullptr); 211 setLibcallName(RTLIB::SRL_I128, nullptr); 212 setLibcallName(RTLIB::SRA_I128, nullptr); 213 setLibcallName(RTLIB::MUL_I128, nullptr); 214 setLibcallName(RTLIB::MULO_I64, nullptr); 215 } 216 217 if (!Subtarget.hasStdExtM()) { 218 setOperationAction(ISD::MUL, XLenVT, Expand); 219 setOperationAction(ISD::MULHS, XLenVT, Expand); 220 setOperationAction(ISD::MULHU, XLenVT, Expand); 221 setOperationAction(ISD::SDIV, XLenVT, Expand); 222 setOperationAction(ISD::UDIV, XLenVT, Expand); 223 setOperationAction(ISD::SREM, XLenVT, Expand); 224 setOperationAction(ISD::UREM, XLenVT, Expand); 225 } else { 226 if (Subtarget.is64Bit()) { 227 setOperationAction(ISD::MUL, MVT::i32, Custom); 228 setOperationAction(ISD::MUL, MVT::i128, Custom); 229 230 setOperationAction(ISD::SDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UDIV, MVT::i8, Custom); 232 setOperationAction(ISD::UREM, MVT::i8, Custom); 233 setOperationAction(ISD::SDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UDIV, MVT::i16, Custom); 235 setOperationAction(ISD::UREM, MVT::i16, Custom); 236 setOperationAction(ISD::SDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UDIV, MVT::i32, Custom); 238 setOperationAction(ISD::UREM, MVT::i32, Custom); 239 } else { 240 setOperationAction(ISD::MUL, MVT::i64, Custom); 241 } 242 } 243 244 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 246 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 247 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 248 249 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 251 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 252 253 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 254 Subtarget.hasStdExtZbkb()) { 255 if (Subtarget.is64Bit()) { 256 setOperationAction(ISD::ROTL, MVT::i32, Custom); 257 setOperationAction(ISD::ROTR, MVT::i32, Custom); 258 } 259 } else { 260 setOperationAction(ISD::ROTL, XLenVT, Expand); 261 setOperationAction(ISD::ROTR, XLenVT, Expand); 262 } 263 264 if (Subtarget.hasStdExtZbp()) { 265 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 266 // more combining. 267 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 268 setOperationAction(ISD::BSWAP, XLenVT, Custom); 269 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 270 // BSWAP i8 doesn't exist. 271 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 272 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 273 274 if (Subtarget.is64Bit()) { 275 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 276 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 277 } 278 } else { 279 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 280 // pattern match it directly in isel. 281 setOperationAction(ISD::BSWAP, XLenVT, 282 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 283 ? Legal 284 : Expand); 285 // Zbkb can use rev8+brev8 to implement bitreverse. 286 setOperationAction(ISD::BITREVERSE, XLenVT, 287 Subtarget.hasStdExtZbkb() ? Custom : Expand); 288 } 289 290 if (Subtarget.hasStdExtZbb()) { 291 setOperationAction(ISD::SMIN, XLenVT, Legal); 292 setOperationAction(ISD::SMAX, XLenVT, Legal); 293 setOperationAction(ISD::UMIN, XLenVT, Legal); 294 setOperationAction(ISD::UMAX, XLenVT, Legal); 295 296 if (Subtarget.is64Bit()) { 297 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 298 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 299 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 300 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 301 } 302 } else { 303 setOperationAction(ISD::CTTZ, XLenVT, Expand); 304 setOperationAction(ISD::CTLZ, XLenVT, Expand); 305 setOperationAction(ISD::CTPOP, XLenVT, Expand); 306 307 if (Subtarget.is64Bit()) 308 setOperationAction(ISD::ABS, MVT::i32, Custom); 309 } 310 311 if (Subtarget.hasStdExtZbt()) { 312 setOperationAction(ISD::FSHL, XLenVT, Custom); 313 setOperationAction(ISD::FSHR, XLenVT, Custom); 314 setOperationAction(ISD::SELECT, XLenVT, Legal); 315 316 if (Subtarget.is64Bit()) { 317 setOperationAction(ISD::FSHL, MVT::i32, Custom); 318 setOperationAction(ISD::FSHR, MVT::i32, Custom); 319 } 320 } else { 321 setOperationAction(ISD::SELECT, XLenVT, Custom); 322 } 323 324 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 325 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 326 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 327 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 328 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 329 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 330 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 331 332 static const ISD::CondCode FPCCToExpand[] = { 333 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 334 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 335 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 336 337 static const ISD::NodeType FPOpToExpand[] = { 338 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 339 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 340 341 if (Subtarget.hasStdExtZfh()) 342 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 343 344 if (Subtarget.hasStdExtZfh()) { 345 for (auto NT : FPLegalNodeTypes) 346 setOperationAction(NT, MVT::f16, Legal); 347 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 348 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 349 for (auto CC : FPCCToExpand) 350 setCondCodeAction(CC, MVT::f16, Expand); 351 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 352 setOperationAction(ISD::SELECT, MVT::f16, Custom); 353 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 354 355 setOperationAction(ISD::FREM, MVT::f16, Promote); 356 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 357 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 358 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 359 setOperationAction(ISD::FRINT, MVT::f16, Promote); 360 setOperationAction(ISD::FROUND, MVT::f16, Promote); 361 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 362 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 363 setOperationAction(ISD::FPOW, MVT::f16, Promote); 364 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 365 setOperationAction(ISD::FCOS, MVT::f16, Promote); 366 setOperationAction(ISD::FSIN, MVT::f16, Promote); 367 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 368 setOperationAction(ISD::FEXP, MVT::f16, Promote); 369 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 370 setOperationAction(ISD::FLOG, MVT::f16, Promote); 371 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 372 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 373 374 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 375 // complete support for all operations in LegalizeDAG. 376 377 // We need to custom promote this. 378 if (Subtarget.is64Bit()) 379 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 380 } 381 382 if (Subtarget.hasStdExtF()) { 383 for (auto NT : FPLegalNodeTypes) 384 setOperationAction(NT, MVT::f32, Legal); 385 for (auto CC : FPCCToExpand) 386 setCondCodeAction(CC, MVT::f32, Expand); 387 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 388 setOperationAction(ISD::SELECT, MVT::f32, Custom); 389 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 390 for (auto Op : FPOpToExpand) 391 setOperationAction(Op, MVT::f32, Expand); 392 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 393 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 394 } 395 396 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 397 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 398 399 if (Subtarget.hasStdExtD()) { 400 for (auto NT : FPLegalNodeTypes) 401 setOperationAction(NT, MVT::f64, Legal); 402 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 403 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 404 for (auto CC : FPCCToExpand) 405 setCondCodeAction(CC, MVT::f64, Expand); 406 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 407 setOperationAction(ISD::SELECT, MVT::f64, Custom); 408 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 409 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 410 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 411 for (auto Op : FPOpToExpand) 412 setOperationAction(Op, MVT::f64, Expand); 413 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 414 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 415 } 416 417 if (Subtarget.is64Bit()) { 418 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 419 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 420 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 421 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 422 } 423 424 if (Subtarget.hasStdExtF()) { 425 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 426 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 427 428 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 429 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 430 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 431 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 432 433 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 434 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 435 } 436 437 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 438 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 439 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 440 setOperationAction(ISD::JumpTable, XLenVT, Custom); 441 442 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 443 444 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 445 // Unfortunately this can't be determined just from the ISA naming string. 446 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 447 Subtarget.is64Bit() ? Legal : Custom); 448 449 setOperationAction(ISD::TRAP, MVT::Other, Legal); 450 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 451 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 452 if (Subtarget.is64Bit()) 453 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 454 455 if (Subtarget.hasStdExtA()) { 456 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 457 setMinCmpXchgSizeInBits(32); 458 } else { 459 setMaxAtomicSizeInBitsSupported(0); 460 } 461 462 setBooleanContents(ZeroOrOneBooleanContent); 463 464 if (Subtarget.hasVInstructions()) { 465 setBooleanVectorContents(ZeroOrOneBooleanContent); 466 467 setOperationAction(ISD::VSCALE, XLenVT, Custom); 468 469 // RVV intrinsics may have illegal operands. 470 // We also need to custom legalize vmv.x.s. 471 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 474 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 475 if (Subtarget.is64Bit()) { 476 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 477 } else { 478 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 479 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 480 } 481 482 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 483 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 484 485 static const unsigned IntegerVPOps[] = { 486 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 487 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 488 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 489 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 490 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 491 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 492 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 493 ISD::VP_MERGE, ISD::VP_SELECT}; 494 495 static const unsigned FloatingPointVPOps[] = { 496 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 497 ISD::VP_FDIV, ISD::VP_FNEG, ISD::VP_FMA, 498 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN, 499 ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, ISD::VP_SELECT}; 500 501 if (!Subtarget.is64Bit()) { 502 // We must custom-lower certain vXi64 operations on RV32 due to the vector 503 // element type being illegal. 504 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 505 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 506 507 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 508 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 509 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 510 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 511 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 512 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 513 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 514 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 515 516 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 517 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 518 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 519 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 520 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 521 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 522 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 523 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 524 } 525 526 for (MVT VT : BoolVecVTs) { 527 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 528 529 // Mask VTs are custom-expanded into a series of standard nodes 530 setOperationAction(ISD::TRUNCATE, VT, Custom); 531 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 532 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 533 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 534 535 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 536 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 537 538 setOperationAction(ISD::SELECT, VT, Custom); 539 setOperationAction(ISD::SELECT_CC, VT, Expand); 540 setOperationAction(ISD::VSELECT, VT, Expand); 541 setOperationAction(ISD::VP_MERGE, VT, Expand); 542 setOperationAction(ISD::VP_SELECT, VT, Expand); 543 544 setOperationAction(ISD::VP_AND, VT, Custom); 545 setOperationAction(ISD::VP_OR, VT, Custom); 546 setOperationAction(ISD::VP_XOR, VT, Custom); 547 548 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 549 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 550 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 551 552 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 553 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 554 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 555 556 // RVV has native int->float & float->int conversions where the 557 // element type sizes are within one power-of-two of each other. Any 558 // wider distances between type sizes have to be lowered as sequences 559 // which progressively narrow the gap in stages. 560 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 561 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 562 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 563 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 564 565 // Expand all extending loads to types larger than this, and truncating 566 // stores from types larger than this. 567 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 568 setTruncStoreAction(OtherVT, VT, Expand); 569 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 570 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 571 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 572 } 573 } 574 575 for (MVT VT : IntVecVTs) { 576 if (VT.getVectorElementType() == MVT::i64 && 577 !Subtarget.hasVInstructionsI64()) 578 continue; 579 580 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 581 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 582 583 // Vectors implement MULHS/MULHU. 584 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 585 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 586 587 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 588 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 589 setOperationAction(ISD::MULHU, VT, Expand); 590 setOperationAction(ISD::MULHS, VT, Expand); 591 } 592 593 setOperationAction(ISD::SMIN, VT, Legal); 594 setOperationAction(ISD::SMAX, VT, Legal); 595 setOperationAction(ISD::UMIN, VT, Legal); 596 setOperationAction(ISD::UMAX, VT, Legal); 597 598 setOperationAction(ISD::ROTL, VT, Expand); 599 setOperationAction(ISD::ROTR, VT, Expand); 600 601 setOperationAction(ISD::CTTZ, VT, Expand); 602 setOperationAction(ISD::CTLZ, VT, Expand); 603 setOperationAction(ISD::CTPOP, VT, Expand); 604 605 setOperationAction(ISD::BSWAP, VT, Expand); 606 607 // Custom-lower extensions and truncations from/to mask types. 608 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 609 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 610 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 611 612 // RVV has native int->float & float->int conversions where the 613 // element type sizes are within one power-of-two of each other. Any 614 // wider distances between type sizes have to be lowered as sequences 615 // which progressively narrow the gap in stages. 616 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 617 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 618 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 619 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 620 621 setOperationAction(ISD::SADDSAT, VT, Legal); 622 setOperationAction(ISD::UADDSAT, VT, Legal); 623 setOperationAction(ISD::SSUBSAT, VT, Legal); 624 setOperationAction(ISD::USUBSAT, VT, Legal); 625 626 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 627 // nodes which truncate by one power of two at a time. 628 setOperationAction(ISD::TRUNCATE, VT, Custom); 629 630 // Custom-lower insert/extract operations to simplify patterns. 631 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 632 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 633 634 // Custom-lower reduction operations to set up the corresponding custom 635 // nodes' operands. 636 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 637 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 638 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 639 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 640 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 641 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 642 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 643 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 644 645 for (unsigned VPOpc : IntegerVPOps) 646 setOperationAction(VPOpc, VT, Custom); 647 648 setOperationAction(ISD::LOAD, VT, Custom); 649 setOperationAction(ISD::STORE, VT, Custom); 650 651 setOperationAction(ISD::MLOAD, VT, Custom); 652 setOperationAction(ISD::MSTORE, VT, Custom); 653 setOperationAction(ISD::MGATHER, VT, Custom); 654 setOperationAction(ISD::MSCATTER, VT, Custom); 655 656 setOperationAction(ISD::VP_LOAD, VT, Custom); 657 setOperationAction(ISD::VP_STORE, VT, Custom); 658 setOperationAction(ISD::VP_GATHER, VT, Custom); 659 setOperationAction(ISD::VP_SCATTER, VT, Custom); 660 661 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 662 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 663 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 664 665 setOperationAction(ISD::SELECT, VT, Custom); 666 setOperationAction(ISD::SELECT_CC, VT, Expand); 667 668 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 669 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 670 671 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 672 setTruncStoreAction(VT, OtherVT, Expand); 673 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 674 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 675 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 676 } 677 678 // Splice 679 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 680 681 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 682 // type that can represent the value exactly. 683 if (VT.getVectorElementType() != MVT::i64) { 684 MVT FloatEltVT = 685 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 686 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 687 if (isTypeLegal(FloatVT)) { 688 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 689 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 690 } 691 } 692 } 693 694 // Expand various CCs to best match the RVV ISA, which natively supports UNE 695 // but no other unordered comparisons, and supports all ordered comparisons 696 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 697 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 698 // and we pattern-match those back to the "original", swapping operands once 699 // more. This way we catch both operations and both "vf" and "fv" forms with 700 // fewer patterns. 701 static const ISD::CondCode VFPCCToExpand[] = { 702 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 703 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 704 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 705 }; 706 707 // Sets common operation actions on RVV floating-point vector types. 708 const auto SetCommonVFPActions = [&](MVT VT) { 709 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 710 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 711 // sizes are within one power-of-two of each other. Therefore conversions 712 // between vXf16 and vXf64 must be lowered as sequences which convert via 713 // vXf32. 714 setOperationAction(ISD::FP_ROUND, VT, Custom); 715 setOperationAction(ISD::FP_EXTEND, VT, Custom); 716 // Custom-lower insert/extract operations to simplify patterns. 717 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 718 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 719 // Expand various condition codes (explained above). 720 for (auto CC : VFPCCToExpand) 721 setCondCodeAction(CC, VT, Expand); 722 723 setOperationAction(ISD::FMINNUM, VT, Legal); 724 setOperationAction(ISD::FMAXNUM, VT, Legal); 725 726 setOperationAction(ISD::FTRUNC, VT, Custom); 727 setOperationAction(ISD::FCEIL, VT, Custom); 728 setOperationAction(ISD::FFLOOR, VT, Custom); 729 setOperationAction(ISD::FROUND, VT, Custom); 730 731 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 732 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 733 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 734 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 735 736 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 737 738 setOperationAction(ISD::LOAD, VT, Custom); 739 setOperationAction(ISD::STORE, VT, Custom); 740 741 setOperationAction(ISD::MLOAD, VT, Custom); 742 setOperationAction(ISD::MSTORE, VT, Custom); 743 setOperationAction(ISD::MGATHER, VT, Custom); 744 setOperationAction(ISD::MSCATTER, VT, Custom); 745 746 setOperationAction(ISD::VP_LOAD, VT, Custom); 747 setOperationAction(ISD::VP_STORE, VT, Custom); 748 setOperationAction(ISD::VP_GATHER, VT, Custom); 749 setOperationAction(ISD::VP_SCATTER, VT, Custom); 750 751 setOperationAction(ISD::SELECT, VT, Custom); 752 setOperationAction(ISD::SELECT_CC, VT, Expand); 753 754 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 755 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 756 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 757 758 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 759 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 760 761 for (unsigned VPOpc : FloatingPointVPOps) 762 setOperationAction(VPOpc, VT, Custom); 763 }; 764 765 // Sets common extload/truncstore actions on RVV floating-point vector 766 // types. 767 const auto SetCommonVFPExtLoadTruncStoreActions = 768 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 769 for (auto SmallVT : SmallerVTs) { 770 setTruncStoreAction(VT, SmallVT, Expand); 771 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 772 } 773 }; 774 775 if (Subtarget.hasVInstructionsF16()) 776 for (MVT VT : F16VecVTs) 777 SetCommonVFPActions(VT); 778 779 for (MVT VT : F32VecVTs) { 780 if (Subtarget.hasVInstructionsF32()) 781 SetCommonVFPActions(VT); 782 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 783 } 784 785 for (MVT VT : F64VecVTs) { 786 if (Subtarget.hasVInstructionsF64()) 787 SetCommonVFPActions(VT); 788 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 789 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 790 } 791 792 if (Subtarget.useRVVForFixedLengthVectors()) { 793 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 794 if (!useRVVForFixedLengthVectorVT(VT)) 795 continue; 796 797 // By default everything must be expanded. 798 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 799 setOperationAction(Op, VT, Expand); 800 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 801 setTruncStoreAction(VT, OtherVT, Expand); 802 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 803 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 804 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 805 } 806 807 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 808 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 809 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 810 811 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 812 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 813 814 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 815 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 816 817 setOperationAction(ISD::LOAD, VT, Custom); 818 setOperationAction(ISD::STORE, VT, Custom); 819 820 setOperationAction(ISD::SETCC, VT, Custom); 821 822 setOperationAction(ISD::SELECT, VT, Custom); 823 824 setOperationAction(ISD::TRUNCATE, VT, Custom); 825 826 setOperationAction(ISD::BITCAST, VT, Custom); 827 828 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 829 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 830 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 831 832 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 833 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 834 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 835 836 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 837 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 838 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 839 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 840 841 // Operations below are different for between masks and other vectors. 842 if (VT.getVectorElementType() == MVT::i1) { 843 setOperationAction(ISD::VP_AND, VT, Custom); 844 setOperationAction(ISD::VP_OR, VT, Custom); 845 setOperationAction(ISD::VP_XOR, VT, Custom); 846 setOperationAction(ISD::AND, VT, Custom); 847 setOperationAction(ISD::OR, VT, Custom); 848 setOperationAction(ISD::XOR, VT, Custom); 849 continue; 850 } 851 852 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 853 // it before type legalization for i64 vectors on RV32. It will then be 854 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 855 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 856 // improvements first. 857 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 858 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 859 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 860 } 861 862 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 863 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 864 865 setOperationAction(ISD::MLOAD, VT, Custom); 866 setOperationAction(ISD::MSTORE, VT, Custom); 867 setOperationAction(ISD::MGATHER, VT, Custom); 868 setOperationAction(ISD::MSCATTER, VT, Custom); 869 870 setOperationAction(ISD::VP_LOAD, VT, Custom); 871 setOperationAction(ISD::VP_STORE, VT, Custom); 872 setOperationAction(ISD::VP_GATHER, VT, Custom); 873 setOperationAction(ISD::VP_SCATTER, VT, Custom); 874 875 setOperationAction(ISD::ADD, VT, Custom); 876 setOperationAction(ISD::MUL, VT, Custom); 877 setOperationAction(ISD::SUB, VT, Custom); 878 setOperationAction(ISD::AND, VT, Custom); 879 setOperationAction(ISD::OR, VT, Custom); 880 setOperationAction(ISD::XOR, VT, Custom); 881 setOperationAction(ISD::SDIV, VT, Custom); 882 setOperationAction(ISD::SREM, VT, Custom); 883 setOperationAction(ISD::UDIV, VT, Custom); 884 setOperationAction(ISD::UREM, VT, Custom); 885 setOperationAction(ISD::SHL, VT, Custom); 886 setOperationAction(ISD::SRA, VT, Custom); 887 setOperationAction(ISD::SRL, VT, Custom); 888 889 setOperationAction(ISD::SMIN, VT, Custom); 890 setOperationAction(ISD::SMAX, VT, Custom); 891 setOperationAction(ISD::UMIN, VT, Custom); 892 setOperationAction(ISD::UMAX, VT, Custom); 893 setOperationAction(ISD::ABS, VT, Custom); 894 895 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 896 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 897 setOperationAction(ISD::MULHS, VT, Custom); 898 setOperationAction(ISD::MULHU, VT, Custom); 899 } 900 901 setOperationAction(ISD::SADDSAT, VT, Custom); 902 setOperationAction(ISD::UADDSAT, VT, Custom); 903 setOperationAction(ISD::SSUBSAT, VT, Custom); 904 setOperationAction(ISD::USUBSAT, VT, Custom); 905 906 setOperationAction(ISD::VSELECT, VT, Custom); 907 setOperationAction(ISD::SELECT_CC, VT, Expand); 908 909 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 910 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 911 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 912 913 // Custom-lower reduction operations to set up the corresponding custom 914 // nodes' operands. 915 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 916 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 917 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 918 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 919 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 920 921 for (unsigned VPOpc : IntegerVPOps) 922 setOperationAction(VPOpc, VT, Custom); 923 924 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 925 // type that can represent the value exactly. 926 if (VT.getVectorElementType() != MVT::i64) { 927 MVT FloatEltVT = 928 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 929 EVT FloatVT = 930 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 931 if (isTypeLegal(FloatVT)) { 932 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 933 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 934 } 935 } 936 } 937 938 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 939 if (!useRVVForFixedLengthVectorVT(VT)) 940 continue; 941 942 // By default everything must be expanded. 943 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 944 setOperationAction(Op, VT, Expand); 945 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 946 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 947 setTruncStoreAction(VT, OtherVT, Expand); 948 } 949 950 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 951 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 952 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 953 954 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 955 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 956 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 957 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 958 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 959 960 setOperationAction(ISD::LOAD, VT, Custom); 961 setOperationAction(ISD::STORE, VT, Custom); 962 setOperationAction(ISD::MLOAD, VT, Custom); 963 setOperationAction(ISD::MSTORE, VT, Custom); 964 setOperationAction(ISD::MGATHER, VT, Custom); 965 setOperationAction(ISD::MSCATTER, VT, Custom); 966 967 setOperationAction(ISD::VP_LOAD, VT, Custom); 968 setOperationAction(ISD::VP_STORE, VT, Custom); 969 setOperationAction(ISD::VP_GATHER, VT, Custom); 970 setOperationAction(ISD::VP_SCATTER, VT, Custom); 971 972 setOperationAction(ISD::FADD, VT, Custom); 973 setOperationAction(ISD::FSUB, VT, Custom); 974 setOperationAction(ISD::FMUL, VT, Custom); 975 setOperationAction(ISD::FDIV, VT, Custom); 976 setOperationAction(ISD::FNEG, VT, Custom); 977 setOperationAction(ISD::FABS, VT, Custom); 978 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 979 setOperationAction(ISD::FSQRT, VT, Custom); 980 setOperationAction(ISD::FMA, VT, Custom); 981 setOperationAction(ISD::FMINNUM, VT, Custom); 982 setOperationAction(ISD::FMAXNUM, VT, Custom); 983 984 setOperationAction(ISD::FP_ROUND, VT, Custom); 985 setOperationAction(ISD::FP_EXTEND, VT, Custom); 986 987 setOperationAction(ISD::FTRUNC, VT, Custom); 988 setOperationAction(ISD::FCEIL, VT, Custom); 989 setOperationAction(ISD::FFLOOR, VT, Custom); 990 setOperationAction(ISD::FROUND, VT, Custom); 991 992 for (auto CC : VFPCCToExpand) 993 setCondCodeAction(CC, VT, Expand); 994 995 setOperationAction(ISD::VSELECT, VT, Custom); 996 setOperationAction(ISD::SELECT, VT, Custom); 997 setOperationAction(ISD::SELECT_CC, VT, Expand); 998 999 setOperationAction(ISD::BITCAST, VT, Custom); 1000 1001 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1002 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1003 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1004 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1005 1006 for (unsigned VPOpc : FloatingPointVPOps) 1007 setOperationAction(VPOpc, VT, Custom); 1008 } 1009 1010 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1011 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1012 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1013 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1014 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1015 if (Subtarget.hasStdExtZfh()) 1016 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1017 if (Subtarget.hasStdExtF()) 1018 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1019 if (Subtarget.hasStdExtD()) 1020 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1021 } 1022 } 1023 1024 // Function alignments. 1025 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1026 setMinFunctionAlignment(FunctionAlignment); 1027 setPrefFunctionAlignment(FunctionAlignment); 1028 1029 setMinimumJumpTableEntries(5); 1030 1031 // Jumps are expensive, compared to logic 1032 setJumpIsExpensive(); 1033 1034 setTargetDAGCombine(ISD::ADD); 1035 setTargetDAGCombine(ISD::SUB); 1036 setTargetDAGCombine(ISD::AND); 1037 setTargetDAGCombine(ISD::OR); 1038 setTargetDAGCombine(ISD::XOR); 1039 if (Subtarget.hasStdExtZbp()) { 1040 setTargetDAGCombine(ISD::ROTL); 1041 setTargetDAGCombine(ISD::ROTR); 1042 } 1043 if (Subtarget.hasStdExtZbkb()) 1044 setTargetDAGCombine(ISD::BITREVERSE); 1045 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1046 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 1047 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 1048 if (Subtarget.hasStdExtF()) { 1049 setTargetDAGCombine(ISD::ZERO_EXTEND); 1050 setTargetDAGCombine(ISD::FP_TO_SINT); 1051 setTargetDAGCombine(ISD::FP_TO_UINT); 1052 setTargetDAGCombine(ISD::FP_TO_SINT_SAT); 1053 setTargetDAGCombine(ISD::FP_TO_UINT_SAT); 1054 } 1055 if (Subtarget.hasVInstructions()) { 1056 setTargetDAGCombine(ISD::FCOPYSIGN); 1057 setTargetDAGCombine(ISD::MGATHER); 1058 setTargetDAGCombine(ISD::MSCATTER); 1059 setTargetDAGCombine(ISD::VP_GATHER); 1060 setTargetDAGCombine(ISD::VP_SCATTER); 1061 setTargetDAGCombine(ISD::SRA); 1062 setTargetDAGCombine(ISD::SRL); 1063 setTargetDAGCombine(ISD::SHL); 1064 setTargetDAGCombine(ISD::STORE); 1065 setTargetDAGCombine(ISD::SPLAT_VECTOR); 1066 } 1067 1068 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1069 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1070 } 1071 1072 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1073 LLVMContext &Context, 1074 EVT VT) const { 1075 if (!VT.isVector()) 1076 return getPointerTy(DL); 1077 if (Subtarget.hasVInstructions() && 1078 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1079 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1080 return VT.changeVectorElementTypeToInteger(); 1081 } 1082 1083 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1084 return Subtarget.getXLenVT(); 1085 } 1086 1087 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1088 const CallInst &I, 1089 MachineFunction &MF, 1090 unsigned Intrinsic) const { 1091 auto &DL = I.getModule()->getDataLayout(); 1092 switch (Intrinsic) { 1093 default: 1094 return false; 1095 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1096 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1097 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1098 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1099 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1100 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1101 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1102 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1103 case Intrinsic::riscv_masked_cmpxchg_i32: 1104 Info.opc = ISD::INTRINSIC_W_CHAIN; 1105 Info.memVT = MVT::i32; 1106 Info.ptrVal = I.getArgOperand(0); 1107 Info.offset = 0; 1108 Info.align = Align(4); 1109 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1110 MachineMemOperand::MOVolatile; 1111 return true; 1112 case Intrinsic::riscv_masked_strided_load: 1113 Info.opc = ISD::INTRINSIC_W_CHAIN; 1114 Info.ptrVal = I.getArgOperand(1); 1115 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1116 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1117 Info.size = MemoryLocation::UnknownSize; 1118 Info.flags |= MachineMemOperand::MOLoad; 1119 return true; 1120 case Intrinsic::riscv_masked_strided_store: 1121 Info.opc = ISD::INTRINSIC_VOID; 1122 Info.ptrVal = I.getArgOperand(1); 1123 Info.memVT = 1124 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1125 Info.align = Align( 1126 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1127 8); 1128 Info.size = MemoryLocation::UnknownSize; 1129 Info.flags |= MachineMemOperand::MOStore; 1130 return true; 1131 case Intrinsic::riscv_seg2_load: 1132 case Intrinsic::riscv_seg3_load: 1133 case Intrinsic::riscv_seg4_load: 1134 case Intrinsic::riscv_seg5_load: 1135 case Intrinsic::riscv_seg6_load: 1136 case Intrinsic::riscv_seg7_load: 1137 case Intrinsic::riscv_seg8_load: 1138 Info.opc = ISD::INTRINSIC_W_CHAIN; 1139 Info.ptrVal = I.getArgOperand(0); 1140 Info.memVT = 1141 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1142 Info.align = 1143 Align(DL.getTypeSizeInBits( 1144 I.getType()->getStructElementType(0)->getScalarType()) / 1145 8); 1146 Info.size = MemoryLocation::UnknownSize; 1147 Info.flags |= MachineMemOperand::MOLoad; 1148 return true; 1149 } 1150 } 1151 1152 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1153 const AddrMode &AM, Type *Ty, 1154 unsigned AS, 1155 Instruction *I) const { 1156 // No global is ever allowed as a base. 1157 if (AM.BaseGV) 1158 return false; 1159 1160 // Require a 12-bit signed offset. 1161 if (!isInt<12>(AM.BaseOffs)) 1162 return false; 1163 1164 switch (AM.Scale) { 1165 case 0: // "r+i" or just "i", depending on HasBaseReg. 1166 break; 1167 case 1: 1168 if (!AM.HasBaseReg) // allow "r+i". 1169 break; 1170 return false; // disallow "r+r" or "r+r+i". 1171 default: 1172 return false; 1173 } 1174 1175 return true; 1176 } 1177 1178 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1179 return isInt<12>(Imm); 1180 } 1181 1182 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1183 return isInt<12>(Imm); 1184 } 1185 1186 // On RV32, 64-bit integers are split into their high and low parts and held 1187 // in two different registers, so the trunc is free since the low register can 1188 // just be used. 1189 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1190 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1191 return false; 1192 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1193 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1194 return (SrcBits == 64 && DestBits == 32); 1195 } 1196 1197 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1198 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1199 !SrcVT.isInteger() || !DstVT.isInteger()) 1200 return false; 1201 unsigned SrcBits = SrcVT.getSizeInBits(); 1202 unsigned DestBits = DstVT.getSizeInBits(); 1203 return (SrcBits == 64 && DestBits == 32); 1204 } 1205 1206 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1207 // Zexts are free if they can be combined with a load. 1208 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1209 // poorly with type legalization of compares preferring sext. 1210 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1211 EVT MemVT = LD->getMemoryVT(); 1212 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1213 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1214 LD->getExtensionType() == ISD::ZEXTLOAD)) 1215 return true; 1216 } 1217 1218 return TargetLowering::isZExtFree(Val, VT2); 1219 } 1220 1221 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1222 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1223 } 1224 1225 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1226 return Subtarget.hasStdExtZbb(); 1227 } 1228 1229 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1230 return Subtarget.hasStdExtZbb(); 1231 } 1232 1233 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1234 EVT VT = Y.getValueType(); 1235 1236 // FIXME: Support vectors once we have tests. 1237 if (VT.isVector()) 1238 return false; 1239 1240 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1241 Subtarget.hasStdExtZbkb()) && 1242 !isa<ConstantSDNode>(Y); 1243 } 1244 1245 /// Check if sinking \p I's operands to I's basic block is profitable, because 1246 /// the operands can be folded into a target instruction, e.g. 1247 /// splats of scalars can fold into vector instructions. 1248 bool RISCVTargetLowering::shouldSinkOperands( 1249 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1250 using namespace llvm::PatternMatch; 1251 1252 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1253 return false; 1254 1255 auto IsSinker = [&](Instruction *I, int Operand) { 1256 switch (I->getOpcode()) { 1257 case Instruction::Add: 1258 case Instruction::Sub: 1259 case Instruction::Mul: 1260 case Instruction::And: 1261 case Instruction::Or: 1262 case Instruction::Xor: 1263 case Instruction::FAdd: 1264 case Instruction::FSub: 1265 case Instruction::FMul: 1266 case Instruction::FDiv: 1267 case Instruction::ICmp: 1268 case Instruction::FCmp: 1269 return true; 1270 case Instruction::Shl: 1271 case Instruction::LShr: 1272 case Instruction::AShr: 1273 case Instruction::UDiv: 1274 case Instruction::SDiv: 1275 case Instruction::URem: 1276 case Instruction::SRem: 1277 return Operand == 1; 1278 case Instruction::Call: 1279 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1280 switch (II->getIntrinsicID()) { 1281 case Intrinsic::fma: 1282 case Intrinsic::vp_fma: 1283 return Operand == 0 || Operand == 1; 1284 // FIXME: Our patterns can only match vx/vf instructions when the splat 1285 // it on the RHS, because TableGen doesn't recognize our VP operations 1286 // as commutative. 1287 case Intrinsic::vp_add: 1288 case Intrinsic::vp_mul: 1289 case Intrinsic::vp_and: 1290 case Intrinsic::vp_or: 1291 case Intrinsic::vp_xor: 1292 case Intrinsic::vp_fadd: 1293 case Intrinsic::vp_fmul: 1294 case Intrinsic::vp_shl: 1295 case Intrinsic::vp_lshr: 1296 case Intrinsic::vp_ashr: 1297 case Intrinsic::vp_udiv: 1298 case Intrinsic::vp_sdiv: 1299 case Intrinsic::vp_urem: 1300 case Intrinsic::vp_srem: 1301 return Operand == 1; 1302 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1303 // explicit patterns for both LHS and RHS (as 'vr' versions). 1304 case Intrinsic::vp_sub: 1305 case Intrinsic::vp_fsub: 1306 case Intrinsic::vp_fdiv: 1307 return Operand == 0 || Operand == 1; 1308 default: 1309 return false; 1310 } 1311 } 1312 return false; 1313 default: 1314 return false; 1315 } 1316 }; 1317 1318 for (auto OpIdx : enumerate(I->operands())) { 1319 if (!IsSinker(I, OpIdx.index())) 1320 continue; 1321 1322 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1323 // Make sure we are not already sinking this operand 1324 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1325 continue; 1326 1327 // We are looking for a splat that can be sunk. 1328 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1329 m_Undef(), m_ZeroMask()))) 1330 continue; 1331 1332 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1333 // and vector registers 1334 for (Use &U : Op->uses()) { 1335 Instruction *Insn = cast<Instruction>(U.getUser()); 1336 if (!IsSinker(Insn, U.getOperandNo())) 1337 return false; 1338 } 1339 1340 Ops.push_back(&Op->getOperandUse(0)); 1341 Ops.push_back(&OpIdx.value()); 1342 } 1343 return true; 1344 } 1345 1346 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1347 bool ForCodeSize) const { 1348 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1349 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1350 return false; 1351 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1352 return false; 1353 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1354 return false; 1355 return Imm.isZero(); 1356 } 1357 1358 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1359 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1360 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1361 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1362 } 1363 1364 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1365 CallingConv::ID CC, 1366 EVT VT) const { 1367 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1368 // We might still end up using a GPR but that will be decided based on ABI. 1369 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1370 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1371 return MVT::f32; 1372 1373 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1374 } 1375 1376 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1377 CallingConv::ID CC, 1378 EVT VT) const { 1379 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1380 // We might still end up using a GPR but that will be decided based on ABI. 1381 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1382 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1383 return 1; 1384 1385 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1386 } 1387 1388 // Changes the condition code and swaps operands if necessary, so the SetCC 1389 // operation matches one of the comparisons supported directly by branches 1390 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1391 // with 1/-1. 1392 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1393 ISD::CondCode &CC, SelectionDAG &DAG) { 1394 // Convert X > -1 to X >= 0. 1395 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1396 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1397 CC = ISD::SETGE; 1398 return; 1399 } 1400 // Convert X < 1 to 0 >= X. 1401 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1402 RHS = LHS; 1403 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1404 CC = ISD::SETGE; 1405 return; 1406 } 1407 1408 switch (CC) { 1409 default: 1410 break; 1411 case ISD::SETGT: 1412 case ISD::SETLE: 1413 case ISD::SETUGT: 1414 case ISD::SETULE: 1415 CC = ISD::getSetCCSwappedOperands(CC); 1416 std::swap(LHS, RHS); 1417 break; 1418 } 1419 } 1420 1421 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1422 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1423 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1424 if (VT.getVectorElementType() == MVT::i1) 1425 KnownSize *= 8; 1426 1427 switch (KnownSize) { 1428 default: 1429 llvm_unreachable("Invalid LMUL."); 1430 case 8: 1431 return RISCVII::VLMUL::LMUL_F8; 1432 case 16: 1433 return RISCVII::VLMUL::LMUL_F4; 1434 case 32: 1435 return RISCVII::VLMUL::LMUL_F2; 1436 case 64: 1437 return RISCVII::VLMUL::LMUL_1; 1438 case 128: 1439 return RISCVII::VLMUL::LMUL_2; 1440 case 256: 1441 return RISCVII::VLMUL::LMUL_4; 1442 case 512: 1443 return RISCVII::VLMUL::LMUL_8; 1444 } 1445 } 1446 1447 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1448 switch (LMul) { 1449 default: 1450 llvm_unreachable("Invalid LMUL."); 1451 case RISCVII::VLMUL::LMUL_F8: 1452 case RISCVII::VLMUL::LMUL_F4: 1453 case RISCVII::VLMUL::LMUL_F2: 1454 case RISCVII::VLMUL::LMUL_1: 1455 return RISCV::VRRegClassID; 1456 case RISCVII::VLMUL::LMUL_2: 1457 return RISCV::VRM2RegClassID; 1458 case RISCVII::VLMUL::LMUL_4: 1459 return RISCV::VRM4RegClassID; 1460 case RISCVII::VLMUL::LMUL_8: 1461 return RISCV::VRM8RegClassID; 1462 } 1463 } 1464 1465 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1466 RISCVII::VLMUL LMUL = getLMUL(VT); 1467 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1468 LMUL == RISCVII::VLMUL::LMUL_F4 || 1469 LMUL == RISCVII::VLMUL::LMUL_F2 || 1470 LMUL == RISCVII::VLMUL::LMUL_1) { 1471 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1472 "Unexpected subreg numbering"); 1473 return RISCV::sub_vrm1_0 + Index; 1474 } 1475 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1476 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1477 "Unexpected subreg numbering"); 1478 return RISCV::sub_vrm2_0 + Index; 1479 } 1480 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1481 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1482 "Unexpected subreg numbering"); 1483 return RISCV::sub_vrm4_0 + Index; 1484 } 1485 llvm_unreachable("Invalid vector type."); 1486 } 1487 1488 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1489 if (VT.getVectorElementType() == MVT::i1) 1490 return RISCV::VRRegClassID; 1491 return getRegClassIDForLMUL(getLMUL(VT)); 1492 } 1493 1494 // Attempt to decompose a subvector insert/extract between VecVT and 1495 // SubVecVT via subregister indices. Returns the subregister index that 1496 // can perform the subvector insert/extract with the given element index, as 1497 // well as the index corresponding to any leftover subvectors that must be 1498 // further inserted/extracted within the register class for SubVecVT. 1499 std::pair<unsigned, unsigned> 1500 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1501 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1502 const RISCVRegisterInfo *TRI) { 1503 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1504 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1505 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1506 "Register classes not ordered"); 1507 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1508 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1509 // Try to compose a subregister index that takes us from the incoming 1510 // LMUL>1 register class down to the outgoing one. At each step we half 1511 // the LMUL: 1512 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1513 // Note that this is not guaranteed to find a subregister index, such as 1514 // when we are extracting from one VR type to another. 1515 unsigned SubRegIdx = RISCV::NoSubRegister; 1516 for (const unsigned RCID : 1517 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1518 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1519 VecVT = VecVT.getHalfNumVectorElementsVT(); 1520 bool IsHi = 1521 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1522 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1523 getSubregIndexByMVT(VecVT, IsHi)); 1524 if (IsHi) 1525 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1526 } 1527 return {SubRegIdx, InsertExtractIdx}; 1528 } 1529 1530 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1531 // stores for those types. 1532 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1533 return !Subtarget.useRVVForFixedLengthVectors() || 1534 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1535 } 1536 1537 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1538 if (ScalarTy->isPointerTy()) 1539 return true; 1540 1541 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1542 ScalarTy->isIntegerTy(32)) 1543 return true; 1544 1545 if (ScalarTy->isIntegerTy(64)) 1546 return Subtarget.hasVInstructionsI64(); 1547 1548 if (ScalarTy->isHalfTy()) 1549 return Subtarget.hasVInstructionsF16(); 1550 if (ScalarTy->isFloatTy()) 1551 return Subtarget.hasVInstructionsF32(); 1552 if (ScalarTy->isDoubleTy()) 1553 return Subtarget.hasVInstructionsF64(); 1554 1555 return false; 1556 } 1557 1558 static SDValue getVLOperand(SDValue Op) { 1559 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1560 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1561 "Unexpected opcode"); 1562 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1563 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1564 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1565 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1566 if (!II) 1567 return SDValue(); 1568 return Op.getOperand(II->VLOperand + 1 + HasChain); 1569 } 1570 1571 static bool useRVVForFixedLengthVectorVT(MVT VT, 1572 const RISCVSubtarget &Subtarget) { 1573 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1574 if (!Subtarget.useRVVForFixedLengthVectors()) 1575 return false; 1576 1577 // We only support a set of vector types with a consistent maximum fixed size 1578 // across all supported vector element types to avoid legalization issues. 1579 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1580 // fixed-length vector type we support is 1024 bytes. 1581 if (VT.getFixedSizeInBits() > 1024 * 8) 1582 return false; 1583 1584 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1585 1586 MVT EltVT = VT.getVectorElementType(); 1587 1588 // Don't use RVV for vectors we cannot scalarize if required. 1589 switch (EltVT.SimpleTy) { 1590 // i1 is supported but has different rules. 1591 default: 1592 return false; 1593 case MVT::i1: 1594 // Masks can only use a single register. 1595 if (VT.getVectorNumElements() > MinVLen) 1596 return false; 1597 MinVLen /= 8; 1598 break; 1599 case MVT::i8: 1600 case MVT::i16: 1601 case MVT::i32: 1602 break; 1603 case MVT::i64: 1604 if (!Subtarget.hasVInstructionsI64()) 1605 return false; 1606 break; 1607 case MVT::f16: 1608 if (!Subtarget.hasVInstructionsF16()) 1609 return false; 1610 break; 1611 case MVT::f32: 1612 if (!Subtarget.hasVInstructionsF32()) 1613 return false; 1614 break; 1615 case MVT::f64: 1616 if (!Subtarget.hasVInstructionsF64()) 1617 return false; 1618 break; 1619 } 1620 1621 // Reject elements larger than ELEN. 1622 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1623 return false; 1624 1625 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1626 // Don't use RVV for types that don't fit. 1627 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1628 return false; 1629 1630 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1631 // the base fixed length RVV support in place. 1632 if (!VT.isPow2VectorType()) 1633 return false; 1634 1635 return true; 1636 } 1637 1638 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1639 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1640 } 1641 1642 // Return the largest legal scalable vector type that matches VT's element type. 1643 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1644 const RISCVSubtarget &Subtarget) { 1645 // This may be called before legal types are setup. 1646 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1647 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1648 "Expected legal fixed length vector!"); 1649 1650 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1651 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1652 1653 MVT EltVT = VT.getVectorElementType(); 1654 switch (EltVT.SimpleTy) { 1655 default: 1656 llvm_unreachable("unexpected element type for RVV container"); 1657 case MVT::i1: 1658 case MVT::i8: 1659 case MVT::i16: 1660 case MVT::i32: 1661 case MVT::i64: 1662 case MVT::f16: 1663 case MVT::f32: 1664 case MVT::f64: { 1665 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1666 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1667 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1668 unsigned NumElts = 1669 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1670 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1671 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1672 return MVT::getScalableVectorVT(EltVT, NumElts); 1673 } 1674 } 1675 } 1676 1677 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1678 const RISCVSubtarget &Subtarget) { 1679 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1680 Subtarget); 1681 } 1682 1683 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1684 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1685 } 1686 1687 // Grow V to consume an entire RVV register. 1688 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1689 const RISCVSubtarget &Subtarget) { 1690 assert(VT.isScalableVector() && 1691 "Expected to convert into a scalable vector!"); 1692 assert(V.getValueType().isFixedLengthVector() && 1693 "Expected a fixed length vector operand!"); 1694 SDLoc DL(V); 1695 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1696 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1697 } 1698 1699 // Shrink V so it's just big enough to maintain a VT's worth of data. 1700 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1701 const RISCVSubtarget &Subtarget) { 1702 assert(VT.isFixedLengthVector() && 1703 "Expected to convert into a fixed length vector!"); 1704 assert(V.getValueType().isScalableVector() && 1705 "Expected a scalable vector operand!"); 1706 SDLoc DL(V); 1707 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1708 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1709 } 1710 1711 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1712 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1713 // the vector type that it is contained in. 1714 static std::pair<SDValue, SDValue> 1715 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1716 const RISCVSubtarget &Subtarget) { 1717 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1718 MVT XLenVT = Subtarget.getXLenVT(); 1719 SDValue VL = VecVT.isFixedLengthVector() 1720 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1721 : DAG.getRegister(RISCV::X0, XLenVT); 1722 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1723 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1724 return {Mask, VL}; 1725 } 1726 1727 // As above but assuming the given type is a scalable vector type. 1728 static std::pair<SDValue, SDValue> 1729 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1730 const RISCVSubtarget &Subtarget) { 1731 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1732 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1733 } 1734 1735 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1736 // of either is (currently) supported. This can get us into an infinite loop 1737 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1738 // as a ..., etc. 1739 // Until either (or both) of these can reliably lower any node, reporting that 1740 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1741 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1742 // which is not desirable. 1743 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1744 EVT VT, unsigned DefinedValues) const { 1745 return false; 1746 } 1747 1748 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1749 const RISCVSubtarget &Subtarget) { 1750 // RISCV FP-to-int conversions saturate to the destination register size, but 1751 // don't produce 0 for nan. We can use a conversion instruction and fix the 1752 // nan case with a compare and a select. 1753 SDValue Src = Op.getOperand(0); 1754 1755 EVT DstVT = Op.getValueType(); 1756 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1757 1758 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1759 unsigned Opc; 1760 if (SatVT == DstVT) 1761 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1762 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1763 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1764 else 1765 return SDValue(); 1766 // FIXME: Support other SatVTs by clamping before or after the conversion. 1767 1768 SDLoc DL(Op); 1769 SDValue FpToInt = DAG.getNode( 1770 Opc, DL, DstVT, Src, 1771 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1772 1773 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1774 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1775 } 1776 1777 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1778 // and back. Taking care to avoid converting values that are nan or already 1779 // correct. 1780 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1781 // have FRM dependencies modeled yet. 1782 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1783 MVT VT = Op.getSimpleValueType(); 1784 assert(VT.isVector() && "Unexpected type"); 1785 1786 SDLoc DL(Op); 1787 1788 // Freeze the source since we are increasing the number of uses. 1789 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1790 1791 // Truncate to integer and convert back to FP. 1792 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1793 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1794 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1795 1796 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1797 1798 if (Op.getOpcode() == ISD::FCEIL) { 1799 // If the truncated value is the greater than or equal to the original 1800 // value, we've computed the ceil. Otherwise, we went the wrong way and 1801 // need to increase by 1. 1802 // FIXME: This should use a masked operation. Handle here or in isel? 1803 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1804 DAG.getConstantFP(1.0, DL, VT)); 1805 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1806 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1807 } else if (Op.getOpcode() == ISD::FFLOOR) { 1808 // If the truncated value is the less than or equal to the original value, 1809 // we've computed the floor. Otherwise, we went the wrong way and need to 1810 // decrease by 1. 1811 // FIXME: This should use a masked operation. Handle here or in isel? 1812 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1813 DAG.getConstantFP(1.0, DL, VT)); 1814 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1815 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1816 } 1817 1818 // Restore the original sign so that -0.0 is preserved. 1819 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1820 1821 // Determine the largest integer that can be represented exactly. This and 1822 // values larger than it don't have any fractional bits so don't need to 1823 // be converted. 1824 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1825 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1826 APFloat MaxVal = APFloat(FltSem); 1827 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1828 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1829 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1830 1831 // If abs(Src) was larger than MaxVal or nan, keep it. 1832 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1833 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1834 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1835 } 1836 1837 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1838 // This mode isn't supported in vector hardware on RISCV. But as long as we 1839 // aren't compiling with trapping math, we can emulate this with 1840 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1841 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1842 // dependencies modeled yet. 1843 // FIXME: Use masked operations to avoid final merge. 1844 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1845 MVT VT = Op.getSimpleValueType(); 1846 assert(VT.isVector() && "Unexpected type"); 1847 1848 SDLoc DL(Op); 1849 1850 // Freeze the source since we are increasing the number of uses. 1851 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1852 1853 // We do the conversion on the absolute value and fix the sign at the end. 1854 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1855 1856 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1857 bool Ignored; 1858 APFloat Point5Pred = APFloat(0.5f); 1859 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1860 Point5Pred.next(/*nextDown*/ true); 1861 1862 // Add the adjustment. 1863 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1864 DAG.getConstantFP(Point5Pred, DL, VT)); 1865 1866 // Truncate to integer and convert back to fp. 1867 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1868 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1869 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1870 1871 // Restore the original sign. 1872 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1873 1874 // Determine the largest integer that can be represented exactly. This and 1875 // values larger than it don't have any fractional bits so don't need to 1876 // be converted. 1877 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1878 APFloat MaxVal = APFloat(FltSem); 1879 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1880 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1881 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1882 1883 // If abs(Src) was larger than MaxVal or nan, keep it. 1884 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1885 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1886 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1887 } 1888 1889 struct VIDSequence { 1890 int64_t StepNumerator; 1891 unsigned StepDenominator; 1892 int64_t Addend; 1893 }; 1894 1895 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1896 // to the (non-zero) step S and start value X. This can be then lowered as the 1897 // RVV sequence (VID * S) + X, for example. 1898 // The step S is represented as an integer numerator divided by a positive 1899 // denominator. Note that the implementation currently only identifies 1900 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1901 // cannot detect 2/3, for example. 1902 // Note that this method will also match potentially unappealing index 1903 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1904 // determine whether this is worth generating code for. 1905 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1906 unsigned NumElts = Op.getNumOperands(); 1907 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1908 if (!Op.getValueType().isInteger()) 1909 return None; 1910 1911 Optional<unsigned> SeqStepDenom; 1912 Optional<int64_t> SeqStepNum, SeqAddend; 1913 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1914 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1915 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1916 // Assume undef elements match the sequence; we just have to be careful 1917 // when interpolating across them. 1918 if (Op.getOperand(Idx).isUndef()) 1919 continue; 1920 // The BUILD_VECTOR must be all constants. 1921 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1922 return None; 1923 1924 uint64_t Val = Op.getConstantOperandVal(Idx) & 1925 maskTrailingOnes<uint64_t>(EltSizeInBits); 1926 1927 if (PrevElt) { 1928 // Calculate the step since the last non-undef element, and ensure 1929 // it's consistent across the entire sequence. 1930 unsigned IdxDiff = Idx - PrevElt->second; 1931 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1932 1933 // A zero-value value difference means that we're somewhere in the middle 1934 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1935 // step change before evaluating the sequence. 1936 if (ValDiff != 0) { 1937 int64_t Remainder = ValDiff % IdxDiff; 1938 // Normalize the step if it's greater than 1. 1939 if (Remainder != ValDiff) { 1940 // The difference must cleanly divide the element span. 1941 if (Remainder != 0) 1942 return None; 1943 ValDiff /= IdxDiff; 1944 IdxDiff = 1; 1945 } 1946 1947 if (!SeqStepNum) 1948 SeqStepNum = ValDiff; 1949 else if (ValDiff != SeqStepNum) 1950 return None; 1951 1952 if (!SeqStepDenom) 1953 SeqStepDenom = IdxDiff; 1954 else if (IdxDiff != *SeqStepDenom) 1955 return None; 1956 } 1957 } 1958 1959 // Record and/or check any addend. 1960 if (SeqStepNum && SeqStepDenom) { 1961 uint64_t ExpectedVal = 1962 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1963 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1964 if (!SeqAddend) 1965 SeqAddend = Addend; 1966 else if (SeqAddend != Addend) 1967 return None; 1968 } 1969 1970 // Record this non-undef element for later. 1971 if (!PrevElt || PrevElt->first != Val) 1972 PrevElt = std::make_pair(Val, Idx); 1973 } 1974 // We need to have logged both a step and an addend for this to count as 1975 // a legal index sequence. 1976 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1977 return None; 1978 1979 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1980 } 1981 1982 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1983 // and lower it as a VRGATHER_VX_VL from the source vector. 1984 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1985 SelectionDAG &DAG, 1986 const RISCVSubtarget &Subtarget) { 1987 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1988 return SDValue(); 1989 SDValue Vec = SplatVal.getOperand(0); 1990 // Only perform this optimization on vectors of the same size for simplicity. 1991 if (Vec.getValueType() != VT) 1992 return SDValue(); 1993 SDValue Idx = SplatVal.getOperand(1); 1994 // The index must be a legal type. 1995 if (Idx.getValueType() != Subtarget.getXLenVT()) 1996 return SDValue(); 1997 1998 MVT ContainerVT = VT; 1999 if (VT.isFixedLengthVector()) { 2000 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2001 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2002 } 2003 2004 SDValue Mask, VL; 2005 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2006 2007 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2008 Idx, Mask, VL); 2009 2010 if (!VT.isFixedLengthVector()) 2011 return Gather; 2012 2013 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2014 } 2015 2016 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2017 const RISCVSubtarget &Subtarget) { 2018 MVT VT = Op.getSimpleValueType(); 2019 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2020 2021 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2022 2023 SDLoc DL(Op); 2024 SDValue Mask, VL; 2025 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2026 2027 MVT XLenVT = Subtarget.getXLenVT(); 2028 unsigned NumElts = Op.getNumOperands(); 2029 2030 if (VT.getVectorElementType() == MVT::i1) { 2031 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2032 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2033 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2034 } 2035 2036 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2037 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2038 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2039 } 2040 2041 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2042 // scalar integer chunks whose bit-width depends on the number of mask 2043 // bits and XLEN. 2044 // First, determine the most appropriate scalar integer type to use. This 2045 // is at most XLenVT, but may be shrunk to a smaller vector element type 2046 // according to the size of the final vector - use i8 chunks rather than 2047 // XLenVT if we're producing a v8i1. This results in more consistent 2048 // codegen across RV32 and RV64. 2049 unsigned NumViaIntegerBits = 2050 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2051 NumViaIntegerBits = std::min(NumViaIntegerBits, 2052 Subtarget.getMaxELENForFixedLengthVectors()); 2053 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2054 // If we have to use more than one INSERT_VECTOR_ELT then this 2055 // optimization is likely to increase code size; avoid peforming it in 2056 // such a case. We can use a load from a constant pool in this case. 2057 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2058 return SDValue(); 2059 // Now we can create our integer vector type. Note that it may be larger 2060 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2061 MVT IntegerViaVecVT = 2062 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2063 divideCeil(NumElts, NumViaIntegerBits)); 2064 2065 uint64_t Bits = 0; 2066 unsigned BitPos = 0, IntegerEltIdx = 0; 2067 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2068 2069 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2070 // Once we accumulate enough bits to fill our scalar type, insert into 2071 // our vector and clear our accumulated data. 2072 if (I != 0 && I % NumViaIntegerBits == 0) { 2073 if (NumViaIntegerBits <= 32) 2074 Bits = SignExtend64(Bits, 32); 2075 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2076 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2077 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2078 Bits = 0; 2079 BitPos = 0; 2080 IntegerEltIdx++; 2081 } 2082 SDValue V = Op.getOperand(I); 2083 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2084 Bits |= ((uint64_t)BitValue << BitPos); 2085 } 2086 2087 // Insert the (remaining) scalar value into position in our integer 2088 // vector type. 2089 if (NumViaIntegerBits <= 32) 2090 Bits = SignExtend64(Bits, 32); 2091 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2092 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2093 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2094 2095 if (NumElts < NumViaIntegerBits) { 2096 // If we're producing a smaller vector than our minimum legal integer 2097 // type, bitcast to the equivalent (known-legal) mask type, and extract 2098 // our final mask. 2099 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2100 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2101 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2102 DAG.getConstant(0, DL, XLenVT)); 2103 } else { 2104 // Else we must have produced an integer type with the same size as the 2105 // mask type; bitcast for the final result. 2106 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2107 Vec = DAG.getBitcast(VT, Vec); 2108 } 2109 2110 return Vec; 2111 } 2112 2113 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2114 // vector type, we have a legal equivalently-sized i8 type, so we can use 2115 // that. 2116 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2117 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2118 2119 SDValue WideVec; 2120 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2121 // For a splat, perform a scalar truncate before creating the wider 2122 // vector. 2123 assert(Splat.getValueType() == XLenVT && 2124 "Unexpected type for i1 splat value"); 2125 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2126 DAG.getConstant(1, DL, XLenVT)); 2127 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2128 } else { 2129 SmallVector<SDValue, 8> Ops(Op->op_values()); 2130 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2131 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2132 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2133 } 2134 2135 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2136 } 2137 2138 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2139 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2140 return Gather; 2141 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2142 : RISCVISD::VMV_V_X_VL; 2143 Splat = 2144 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2145 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2146 } 2147 2148 // Try and match index sequences, which we can lower to the vid instruction 2149 // with optional modifications. An all-undef vector is matched by 2150 // getSplatValue, above. 2151 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2152 int64_t StepNumerator = SimpleVID->StepNumerator; 2153 unsigned StepDenominator = SimpleVID->StepDenominator; 2154 int64_t Addend = SimpleVID->Addend; 2155 2156 assert(StepNumerator != 0 && "Invalid step"); 2157 bool Negate = false; 2158 int64_t SplatStepVal = StepNumerator; 2159 unsigned StepOpcode = ISD::MUL; 2160 if (StepNumerator != 1) { 2161 if (isPowerOf2_64(std::abs(StepNumerator))) { 2162 Negate = StepNumerator < 0; 2163 StepOpcode = ISD::SHL; 2164 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2165 } 2166 } 2167 2168 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2169 // threshold since it's the immediate value many RVV instructions accept. 2170 // There is no vmul.vi instruction so ensure multiply constant can fit in 2171 // a single addi instruction. 2172 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2173 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2174 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2175 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2176 // Convert right out of the scalable type so we can use standard ISD 2177 // nodes for the rest of the computation. If we used scalable types with 2178 // these, we'd lose the fixed-length vector info and generate worse 2179 // vsetvli code. 2180 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2181 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2182 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2183 SDValue SplatStep = DAG.getSplatVector( 2184 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2185 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2186 } 2187 if (StepDenominator != 1) { 2188 SDValue SplatStep = DAG.getSplatVector( 2189 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2190 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2191 } 2192 if (Addend != 0 || Negate) { 2193 SDValue SplatAddend = 2194 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2195 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2196 } 2197 return VID; 2198 } 2199 } 2200 2201 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2202 // when re-interpreted as a vector with a larger element type. For example, 2203 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2204 // could be instead splat as 2205 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2206 // TODO: This optimization could also work on non-constant splats, but it 2207 // would require bit-manipulation instructions to construct the splat value. 2208 SmallVector<SDValue> Sequence; 2209 unsigned EltBitSize = VT.getScalarSizeInBits(); 2210 const auto *BV = cast<BuildVectorSDNode>(Op); 2211 if (VT.isInteger() && EltBitSize < 64 && 2212 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2213 BV->getRepeatedSequence(Sequence) && 2214 (Sequence.size() * EltBitSize) <= 64) { 2215 unsigned SeqLen = Sequence.size(); 2216 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2217 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2218 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2219 ViaIntVT == MVT::i64) && 2220 "Unexpected sequence type"); 2221 2222 unsigned EltIdx = 0; 2223 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2224 uint64_t SplatValue = 0; 2225 // Construct the amalgamated value which can be splatted as this larger 2226 // vector type. 2227 for (const auto &SeqV : Sequence) { 2228 if (!SeqV.isUndef()) 2229 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2230 << (EltIdx * EltBitSize)); 2231 EltIdx++; 2232 } 2233 2234 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2235 // achieve better constant materializion. 2236 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2237 SplatValue = SignExtend64(SplatValue, 32); 2238 2239 // Since we can't introduce illegal i64 types at this stage, we can only 2240 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2241 // way we can use RVV instructions to splat. 2242 assert((ViaIntVT.bitsLE(XLenVT) || 2243 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2244 "Unexpected bitcast sequence"); 2245 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2246 SDValue ViaVL = 2247 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2248 MVT ViaContainerVT = 2249 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2250 SDValue Splat = 2251 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2252 DAG.getUNDEF(ViaContainerVT), 2253 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2254 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2255 return DAG.getBitcast(VT, Splat); 2256 } 2257 } 2258 2259 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2260 // which constitute a large proportion of the elements. In such cases we can 2261 // splat a vector with the dominant element and make up the shortfall with 2262 // INSERT_VECTOR_ELTs. 2263 // Note that this includes vectors of 2 elements by association. The 2264 // upper-most element is the "dominant" one, allowing us to use a splat to 2265 // "insert" the upper element, and an insert of the lower element at position 2266 // 0, which improves codegen. 2267 SDValue DominantValue; 2268 unsigned MostCommonCount = 0; 2269 DenseMap<SDValue, unsigned> ValueCounts; 2270 unsigned NumUndefElts = 2271 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2272 2273 // Track the number of scalar loads we know we'd be inserting, estimated as 2274 // any non-zero floating-point constant. Other kinds of element are either 2275 // already in registers or are materialized on demand. The threshold at which 2276 // a vector load is more desirable than several scalar materializion and 2277 // vector-insertion instructions is not known. 2278 unsigned NumScalarLoads = 0; 2279 2280 for (SDValue V : Op->op_values()) { 2281 if (V.isUndef()) 2282 continue; 2283 2284 ValueCounts.insert(std::make_pair(V, 0)); 2285 unsigned &Count = ValueCounts[V]; 2286 2287 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2288 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2289 2290 // Is this value dominant? In case of a tie, prefer the highest element as 2291 // it's cheaper to insert near the beginning of a vector than it is at the 2292 // end. 2293 if (++Count >= MostCommonCount) { 2294 DominantValue = V; 2295 MostCommonCount = Count; 2296 } 2297 } 2298 2299 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2300 unsigned NumDefElts = NumElts - NumUndefElts; 2301 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2302 2303 // Don't perform this optimization when optimizing for size, since 2304 // materializing elements and inserting them tends to cause code bloat. 2305 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2306 ((MostCommonCount > DominantValueCountThreshold) || 2307 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2308 // Start by splatting the most common element. 2309 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2310 2311 DenseSet<SDValue> Processed{DominantValue}; 2312 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2313 for (const auto &OpIdx : enumerate(Op->ops())) { 2314 const SDValue &V = OpIdx.value(); 2315 if (V.isUndef() || !Processed.insert(V).second) 2316 continue; 2317 if (ValueCounts[V] == 1) { 2318 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2319 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2320 } else { 2321 // Blend in all instances of this value using a VSELECT, using a 2322 // mask where each bit signals whether that element is the one 2323 // we're after. 2324 SmallVector<SDValue> Ops; 2325 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2326 return DAG.getConstant(V == V1, DL, XLenVT); 2327 }); 2328 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2329 DAG.getBuildVector(SelMaskTy, DL, Ops), 2330 DAG.getSplatBuildVector(VT, DL, V), Vec); 2331 } 2332 } 2333 2334 return Vec; 2335 } 2336 2337 return SDValue(); 2338 } 2339 2340 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2341 SDValue Lo, SDValue Hi, SDValue VL, 2342 SelectionDAG &DAG) { 2343 bool HasPassthru = Passthru && !Passthru.isUndef(); 2344 if (!HasPassthru && !Passthru) 2345 Passthru = DAG.getUNDEF(VT); 2346 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2347 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2348 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2349 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2350 // node in order to try and match RVV vector/scalar instructions. 2351 if ((LoC >> 31) == HiC) 2352 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2353 2354 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2355 // vmv.v.x whose EEW = 32 to lower it. 2356 auto *Const = dyn_cast<ConstantSDNode>(VL); 2357 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2358 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2359 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2360 // access the subtarget here now. 2361 auto InterVec = DAG.getNode( 2362 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2363 DAG.getRegister(RISCV::X0, MVT::i32)); 2364 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2365 } 2366 } 2367 2368 // Fall back to a stack store and stride x0 vector load. 2369 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2370 Hi, VL); 2371 } 2372 2373 // Called by type legalization to handle splat of i64 on RV32. 2374 // FIXME: We can optimize this when the type has sign or zero bits in one 2375 // of the halves. 2376 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2377 SDValue Scalar, SDValue VL, 2378 SelectionDAG &DAG) { 2379 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2380 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2381 DAG.getConstant(0, DL, MVT::i32)); 2382 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2383 DAG.getConstant(1, DL, MVT::i32)); 2384 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2385 } 2386 2387 // This function lowers a splat of a scalar operand Splat with the vector 2388 // length VL. It ensures the final sequence is type legal, which is useful when 2389 // lowering a splat after type legalization. 2390 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2391 MVT VT, SDLoc DL, SelectionDAG &DAG, 2392 const RISCVSubtarget &Subtarget) { 2393 bool HasPassthru = Passthru && !Passthru.isUndef(); 2394 if (!HasPassthru && !Passthru) 2395 Passthru = DAG.getUNDEF(VT); 2396 if (VT.isFloatingPoint()) { 2397 // If VL is 1, we could use vfmv.s.f. 2398 if (isOneConstant(VL)) 2399 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2400 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2401 } 2402 2403 MVT XLenVT = Subtarget.getXLenVT(); 2404 2405 // Simplest case is that the operand needs to be promoted to XLenVT. 2406 if (Scalar.getValueType().bitsLE(XLenVT)) { 2407 // If the operand is a constant, sign extend to increase our chances 2408 // of being able to use a .vi instruction. ANY_EXTEND would become a 2409 // a zero extend and the simm5 check in isel would fail. 2410 // FIXME: Should we ignore the upper bits in isel instead? 2411 unsigned ExtOpc = 2412 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2413 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2414 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2415 // If VL is 1 and the scalar value won't benefit from immediate, we could 2416 // use vmv.s.x. 2417 if (isOneConstant(VL) && 2418 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2419 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2420 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2421 } 2422 2423 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2424 "Unexpected scalar for splat lowering!"); 2425 2426 if (isOneConstant(VL) && isNullConstant(Scalar)) 2427 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2428 DAG.getConstant(0, DL, XLenVT), VL); 2429 2430 // Otherwise use the more complicated splatting algorithm. 2431 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2432 } 2433 2434 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2435 const RISCVSubtarget &Subtarget) { 2436 // We need to be able to widen elements to the next larger integer type. 2437 if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors()) 2438 return false; 2439 2440 int Size = Mask.size(); 2441 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2442 2443 int Srcs[] = {-1, -1}; 2444 for (int i = 0; i != Size; ++i) { 2445 // Ignore undef elements. 2446 if (Mask[i] < 0) 2447 continue; 2448 2449 // Is this an even or odd element. 2450 int Pol = i % 2; 2451 2452 // Ensure we consistently use the same source for this element polarity. 2453 int Src = Mask[i] / Size; 2454 if (Srcs[Pol] < 0) 2455 Srcs[Pol] = Src; 2456 if (Srcs[Pol] != Src) 2457 return false; 2458 2459 // Make sure the element within the source is appropriate for this element 2460 // in the destination. 2461 int Elt = Mask[i] % Size; 2462 if (Elt != i / 2) 2463 return false; 2464 } 2465 2466 // We need to find a source for each polarity and they can't be the same. 2467 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2468 return false; 2469 2470 // Swap the sources if the second source was in the even polarity. 2471 SwapSources = Srcs[0] > Srcs[1]; 2472 2473 return true; 2474 } 2475 2476 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2477 /// and then extract the original number of elements from the rotated result. 2478 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2479 /// returned rotation amount is for a rotate right, where elements move from 2480 /// higher elements to lower elements. \p LoSrc indicates the first source 2481 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2482 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2483 /// 0 or 1 if a rotation is found. 2484 /// 2485 /// NOTE: We talk about rotate to the right which matches how bit shift and 2486 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2487 /// and the table below write vectors with the lowest elements on the left. 2488 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2489 int Size = Mask.size(); 2490 2491 // We need to detect various ways of spelling a rotation: 2492 // [11, 12, 13, 14, 15, 0, 1, 2] 2493 // [-1, 12, 13, 14, -1, -1, 1, -1] 2494 // [-1, -1, -1, -1, -1, -1, 1, 2] 2495 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2496 // [-1, 4, 5, 6, -1, -1, 9, -1] 2497 // [-1, 4, 5, 6, -1, -1, -1, -1] 2498 int Rotation = 0; 2499 LoSrc = -1; 2500 HiSrc = -1; 2501 for (int i = 0; i != Size; ++i) { 2502 int M = Mask[i]; 2503 if (M < 0) 2504 continue; 2505 2506 // Determine where a rotate vector would have started. 2507 int StartIdx = i - (M % Size); 2508 // The identity rotation isn't interesting, stop. 2509 if (StartIdx == 0) 2510 return -1; 2511 2512 // If we found the tail of a vector the rotation must be the missing 2513 // front. If we found the head of a vector, it must be how much of the 2514 // head. 2515 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2516 2517 if (Rotation == 0) 2518 Rotation = CandidateRotation; 2519 else if (Rotation != CandidateRotation) 2520 // The rotations don't match, so we can't match this mask. 2521 return -1; 2522 2523 // Compute which value this mask is pointing at. 2524 int MaskSrc = M < Size ? 0 : 1; 2525 2526 // Compute which of the two target values this index should be assigned to. 2527 // This reflects whether the high elements are remaining or the low elemnts 2528 // are remaining. 2529 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2530 2531 // Either set up this value if we've not encountered it before, or check 2532 // that it remains consistent. 2533 if (TargetSrc < 0) 2534 TargetSrc = MaskSrc; 2535 else if (TargetSrc != MaskSrc) 2536 // This may be a rotation, but it pulls from the inputs in some 2537 // unsupported interleaving. 2538 return -1; 2539 } 2540 2541 // Check that we successfully analyzed the mask, and normalize the results. 2542 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2543 assert((LoSrc >= 0 || HiSrc >= 0) && 2544 "Failed to find a rotated input vector!"); 2545 2546 return Rotation; 2547 } 2548 2549 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2550 const RISCVSubtarget &Subtarget) { 2551 SDValue V1 = Op.getOperand(0); 2552 SDValue V2 = Op.getOperand(1); 2553 SDLoc DL(Op); 2554 MVT XLenVT = Subtarget.getXLenVT(); 2555 MVT VT = Op.getSimpleValueType(); 2556 unsigned NumElts = VT.getVectorNumElements(); 2557 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2558 2559 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2560 2561 SDValue TrueMask, VL; 2562 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2563 2564 if (SVN->isSplat()) { 2565 const int Lane = SVN->getSplatIndex(); 2566 if (Lane >= 0) { 2567 MVT SVT = VT.getVectorElementType(); 2568 2569 // Turn splatted vector load into a strided load with an X0 stride. 2570 SDValue V = V1; 2571 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2572 // with undef. 2573 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2574 int Offset = Lane; 2575 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2576 int OpElements = 2577 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2578 V = V.getOperand(Offset / OpElements); 2579 Offset %= OpElements; 2580 } 2581 2582 // We need to ensure the load isn't atomic or volatile. 2583 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2584 auto *Ld = cast<LoadSDNode>(V); 2585 Offset *= SVT.getStoreSize(); 2586 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2587 TypeSize::Fixed(Offset), DL); 2588 2589 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2590 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2591 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2592 SDValue IntID = 2593 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2594 SDValue Ops[] = {Ld->getChain(), 2595 IntID, 2596 DAG.getUNDEF(ContainerVT), 2597 NewAddr, 2598 DAG.getRegister(RISCV::X0, XLenVT), 2599 VL}; 2600 SDValue NewLoad = DAG.getMemIntrinsicNode( 2601 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2602 DAG.getMachineFunction().getMachineMemOperand( 2603 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2604 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2605 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2606 } 2607 2608 // Otherwise use a scalar load and splat. This will give the best 2609 // opportunity to fold a splat into the operation. ISel can turn it into 2610 // the x0 strided load if we aren't able to fold away the select. 2611 if (SVT.isFloatingPoint()) 2612 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2613 Ld->getPointerInfo().getWithOffset(Offset), 2614 Ld->getOriginalAlign(), 2615 Ld->getMemOperand()->getFlags()); 2616 else 2617 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2618 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2619 Ld->getOriginalAlign(), 2620 Ld->getMemOperand()->getFlags()); 2621 DAG.makeEquivalentMemoryOrdering(Ld, V); 2622 2623 unsigned Opc = 2624 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2625 SDValue Splat = 2626 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2627 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2628 } 2629 2630 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2631 assert(Lane < (int)NumElts && "Unexpected lane!"); 2632 SDValue Gather = 2633 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2634 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2635 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2636 } 2637 } 2638 2639 ArrayRef<int> Mask = SVN->getMask(); 2640 2641 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2642 // be undef which can be handled with a single SLIDEDOWN/UP. 2643 int LoSrc, HiSrc; 2644 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2645 if (Rotation > 0) { 2646 SDValue LoV, HiV; 2647 if (LoSrc >= 0) { 2648 LoV = LoSrc == 0 ? V1 : V2; 2649 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2650 } 2651 if (HiSrc >= 0) { 2652 HiV = HiSrc == 0 ? V1 : V2; 2653 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2654 } 2655 2656 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2657 // to slide LoV up by (NumElts - Rotation). 2658 unsigned InvRotate = NumElts - Rotation; 2659 2660 SDValue Res = DAG.getUNDEF(ContainerVT); 2661 if (HiV) { 2662 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2663 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2664 // causes multiple vsetvlis in some test cases such as lowering 2665 // reduce.mul 2666 SDValue DownVL = VL; 2667 if (LoV) 2668 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2669 Res = 2670 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2671 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2672 } 2673 if (LoV) 2674 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2675 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2676 2677 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2678 } 2679 2680 // Detect an interleave shuffle and lower to 2681 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2682 bool SwapSources; 2683 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2684 // Swap sources if needed. 2685 if (SwapSources) 2686 std::swap(V1, V2); 2687 2688 // Extract the lower half of the vectors. 2689 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2690 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2691 DAG.getConstant(0, DL, XLenVT)); 2692 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2693 DAG.getConstant(0, DL, XLenVT)); 2694 2695 // Double the element width and halve the number of elements in an int type. 2696 unsigned EltBits = VT.getScalarSizeInBits(); 2697 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2698 MVT WideIntVT = 2699 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2700 // Convert this to a scalable vector. We need to base this on the 2701 // destination size to ensure there's always a type with a smaller LMUL. 2702 MVT WideIntContainerVT = 2703 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2704 2705 // Convert sources to scalable vectors with the same element count as the 2706 // larger type. 2707 MVT HalfContainerVT = MVT::getVectorVT( 2708 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2709 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2710 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2711 2712 // Cast sources to integer. 2713 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2714 MVT IntHalfVT = 2715 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2716 V1 = DAG.getBitcast(IntHalfVT, V1); 2717 V2 = DAG.getBitcast(IntHalfVT, V2); 2718 2719 // Freeze V2 since we use it twice and we need to be sure that the add and 2720 // multiply see the same value. 2721 V2 = DAG.getFreeze(V2); 2722 2723 // Recreate TrueMask using the widened type's element count. 2724 MVT MaskVT = 2725 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2726 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2727 2728 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2729 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2730 V2, TrueMask, VL); 2731 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2732 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2733 DAG.getUNDEF(IntHalfVT), 2734 DAG.getAllOnesConstant(DL, XLenVT)); 2735 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2736 V2, Multiplier, TrueMask, VL); 2737 // Add the new copies to our previous addition giving us 2^eltbits copies of 2738 // V2. This is equivalent to shifting V2 left by eltbits. This should 2739 // combine with the vwmulu.vv above to form vwmaccu.vv. 2740 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2741 TrueMask, VL); 2742 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2743 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2744 // vector VT. 2745 ContainerVT = 2746 MVT::getVectorVT(VT.getVectorElementType(), 2747 WideIntContainerVT.getVectorElementCount() * 2); 2748 Add = DAG.getBitcast(ContainerVT, Add); 2749 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2750 } 2751 2752 // Detect shuffles which can be re-expressed as vector selects; these are 2753 // shuffles in which each element in the destination is taken from an element 2754 // at the corresponding index in either source vectors. 2755 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2756 int MaskIndex = MaskIdx.value(); 2757 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2758 }); 2759 2760 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2761 2762 SmallVector<SDValue> MaskVals; 2763 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2764 // merged with a second vrgather. 2765 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2766 2767 // By default we preserve the original operand order, and use a mask to 2768 // select LHS as true and RHS as false. However, since RVV vector selects may 2769 // feature splats but only on the LHS, we may choose to invert our mask and 2770 // instead select between RHS and LHS. 2771 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2772 bool InvertMask = IsSelect == SwapOps; 2773 2774 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2775 // half. 2776 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2777 2778 // Now construct the mask that will be used by the vselect or blended 2779 // vrgather operation. For vrgathers, construct the appropriate indices into 2780 // each vector. 2781 for (int MaskIndex : Mask) { 2782 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2783 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2784 if (!IsSelect) { 2785 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2786 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2787 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2788 : DAG.getUNDEF(XLenVT)); 2789 GatherIndicesRHS.push_back( 2790 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2791 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2792 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2793 ++LHSIndexCounts[MaskIndex]; 2794 if (!IsLHSOrUndefIndex) 2795 ++RHSIndexCounts[MaskIndex - NumElts]; 2796 } 2797 } 2798 2799 if (SwapOps) { 2800 std::swap(V1, V2); 2801 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2802 } 2803 2804 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2805 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2806 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2807 2808 if (IsSelect) 2809 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2810 2811 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2812 // On such a large vector we're unable to use i8 as the index type. 2813 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2814 // may involve vector splitting if we're already at LMUL=8, or our 2815 // user-supplied maximum fixed-length LMUL. 2816 return SDValue(); 2817 } 2818 2819 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2820 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2821 MVT IndexVT = VT.changeTypeToInteger(); 2822 // Since we can't introduce illegal index types at this stage, use i16 and 2823 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2824 // than XLenVT. 2825 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2826 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2827 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2828 } 2829 2830 MVT IndexContainerVT = 2831 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2832 2833 SDValue Gather; 2834 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2835 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2836 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2837 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2838 Subtarget); 2839 } else { 2840 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2841 // If only one index is used, we can use a "splat" vrgather. 2842 // TODO: We can splat the most-common index and fix-up any stragglers, if 2843 // that's beneficial. 2844 if (LHSIndexCounts.size() == 1) { 2845 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2846 Gather = 2847 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2848 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2849 } else { 2850 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2851 LHSIndices = 2852 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2853 2854 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2855 TrueMask, VL); 2856 } 2857 } 2858 2859 // If a second vector operand is used by this shuffle, blend it in with an 2860 // additional vrgather. 2861 if (!V2.isUndef()) { 2862 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2863 // If only one index is used, we can use a "splat" vrgather. 2864 // TODO: We can splat the most-common index and fix-up any stragglers, if 2865 // that's beneficial. 2866 if (RHSIndexCounts.size() == 1) { 2867 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2868 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2869 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2870 } else { 2871 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2872 RHSIndices = 2873 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2874 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2875 VL); 2876 } 2877 2878 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2879 SelectMask = 2880 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2881 2882 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2883 Gather, VL); 2884 } 2885 2886 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2887 } 2888 2889 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2890 // Support splats for any type. These should type legalize well. 2891 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2892 return true; 2893 2894 // Only support legal VTs for other shuffles for now. 2895 if (!isTypeLegal(VT)) 2896 return false; 2897 2898 MVT SVT = VT.getSimpleVT(); 2899 2900 bool SwapSources; 2901 int LoSrc, HiSrc; 2902 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2903 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2904 } 2905 2906 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2907 SDLoc DL, SelectionDAG &DAG, 2908 const RISCVSubtarget &Subtarget) { 2909 if (VT.isScalableVector()) 2910 return DAG.getFPExtendOrRound(Op, DL, VT); 2911 assert(VT.isFixedLengthVector() && 2912 "Unexpected value type for RVV FP extend/round lowering"); 2913 SDValue Mask, VL; 2914 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2915 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2916 ? RISCVISD::FP_EXTEND_VL 2917 : RISCVISD::FP_ROUND_VL; 2918 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2919 } 2920 2921 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2922 // the exponent. 2923 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2924 MVT VT = Op.getSimpleValueType(); 2925 unsigned EltSize = VT.getScalarSizeInBits(); 2926 SDValue Src = Op.getOperand(0); 2927 SDLoc DL(Op); 2928 2929 // We need a FP type that can represent the value. 2930 // TODO: Use f16 for i8 when possible? 2931 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2932 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2933 2934 // Legal types should have been checked in the RISCVTargetLowering 2935 // constructor. 2936 // TODO: Splitting may make sense in some cases. 2937 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2938 "Expected legal float type!"); 2939 2940 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2941 // The trailing zero count is equal to log2 of this single bit value. 2942 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2943 SDValue Neg = 2944 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2945 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2946 } 2947 2948 // We have a legal FP type, convert to it. 2949 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2950 // Bitcast to integer and shift the exponent to the LSB. 2951 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2952 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2953 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2954 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2955 DAG.getConstant(ShiftAmt, DL, IntVT)); 2956 // Truncate back to original type to allow vnsrl. 2957 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2958 // The exponent contains log2 of the value in biased form. 2959 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2960 2961 // For trailing zeros, we just need to subtract the bias. 2962 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2963 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2964 DAG.getConstant(ExponentBias, DL, VT)); 2965 2966 // For leading zeros, we need to remove the bias and convert from log2 to 2967 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2968 unsigned Adjust = ExponentBias + (EltSize - 1); 2969 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2970 } 2971 2972 // While RVV has alignment restrictions, we should always be able to load as a 2973 // legal equivalently-sized byte-typed vector instead. This method is 2974 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2975 // the load is already correctly-aligned, it returns SDValue(). 2976 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2977 SelectionDAG &DAG) const { 2978 auto *Load = cast<LoadSDNode>(Op); 2979 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2980 2981 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2982 Load->getMemoryVT(), 2983 *Load->getMemOperand())) 2984 return SDValue(); 2985 2986 SDLoc DL(Op); 2987 MVT VT = Op.getSimpleValueType(); 2988 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2989 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2990 "Unexpected unaligned RVV load type"); 2991 MVT NewVT = 2992 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2993 assert(NewVT.isValid() && 2994 "Expecting equally-sized RVV vector types to be legal"); 2995 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2996 Load->getPointerInfo(), Load->getOriginalAlign(), 2997 Load->getMemOperand()->getFlags()); 2998 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2999 } 3000 3001 // While RVV has alignment restrictions, we should always be able to store as a 3002 // legal equivalently-sized byte-typed vector instead. This method is 3003 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 3004 // returns SDValue() if the store is already correctly aligned. 3005 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 3006 SelectionDAG &DAG) const { 3007 auto *Store = cast<StoreSDNode>(Op); 3008 assert(Store && Store->getValue().getValueType().isVector() && 3009 "Expected vector store"); 3010 3011 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3012 Store->getMemoryVT(), 3013 *Store->getMemOperand())) 3014 return SDValue(); 3015 3016 SDLoc DL(Op); 3017 SDValue StoredVal = Store->getValue(); 3018 MVT VT = StoredVal.getSimpleValueType(); 3019 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3020 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3021 "Unexpected unaligned RVV store type"); 3022 MVT NewVT = 3023 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3024 assert(NewVT.isValid() && 3025 "Expecting equally-sized RVV vector types to be legal"); 3026 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3027 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3028 Store->getPointerInfo(), Store->getOriginalAlign(), 3029 Store->getMemOperand()->getFlags()); 3030 } 3031 3032 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3033 SelectionDAG &DAG) const { 3034 switch (Op.getOpcode()) { 3035 default: 3036 report_fatal_error("unimplemented operand"); 3037 case ISD::GlobalAddress: 3038 return lowerGlobalAddress(Op, DAG); 3039 case ISD::BlockAddress: 3040 return lowerBlockAddress(Op, DAG); 3041 case ISD::ConstantPool: 3042 return lowerConstantPool(Op, DAG); 3043 case ISD::JumpTable: 3044 return lowerJumpTable(Op, DAG); 3045 case ISD::GlobalTLSAddress: 3046 return lowerGlobalTLSAddress(Op, DAG); 3047 case ISD::SELECT: 3048 return lowerSELECT(Op, DAG); 3049 case ISD::BRCOND: 3050 return lowerBRCOND(Op, DAG); 3051 case ISD::VASTART: 3052 return lowerVASTART(Op, DAG); 3053 case ISD::FRAMEADDR: 3054 return lowerFRAMEADDR(Op, DAG); 3055 case ISD::RETURNADDR: 3056 return lowerRETURNADDR(Op, DAG); 3057 case ISD::SHL_PARTS: 3058 return lowerShiftLeftParts(Op, DAG); 3059 case ISD::SRA_PARTS: 3060 return lowerShiftRightParts(Op, DAG, true); 3061 case ISD::SRL_PARTS: 3062 return lowerShiftRightParts(Op, DAG, false); 3063 case ISD::BITCAST: { 3064 SDLoc DL(Op); 3065 EVT VT = Op.getValueType(); 3066 SDValue Op0 = Op.getOperand(0); 3067 EVT Op0VT = Op0.getValueType(); 3068 MVT XLenVT = Subtarget.getXLenVT(); 3069 if (VT.isFixedLengthVector()) { 3070 // We can handle fixed length vector bitcasts with a simple replacement 3071 // in isel. 3072 if (Op0VT.isFixedLengthVector()) 3073 return Op; 3074 // When bitcasting from scalar to fixed-length vector, insert the scalar 3075 // into a one-element vector of the result type, and perform a vector 3076 // bitcast. 3077 if (!Op0VT.isVector()) { 3078 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3079 if (!isTypeLegal(BVT)) 3080 return SDValue(); 3081 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3082 DAG.getUNDEF(BVT), Op0, 3083 DAG.getConstant(0, DL, XLenVT))); 3084 } 3085 return SDValue(); 3086 } 3087 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3088 // thus: bitcast the vector to a one-element vector type whose element type 3089 // is the same as the result type, and extract the first element. 3090 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3091 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3092 if (!isTypeLegal(BVT)) 3093 return SDValue(); 3094 SDValue BVec = DAG.getBitcast(BVT, Op0); 3095 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3096 DAG.getConstant(0, DL, XLenVT)); 3097 } 3098 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3099 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3100 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3101 return FPConv; 3102 } 3103 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3104 Subtarget.hasStdExtF()) { 3105 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3106 SDValue FPConv = 3107 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3108 return FPConv; 3109 } 3110 return SDValue(); 3111 } 3112 case ISD::INTRINSIC_WO_CHAIN: 3113 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3114 case ISD::INTRINSIC_W_CHAIN: 3115 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3116 case ISD::INTRINSIC_VOID: 3117 return LowerINTRINSIC_VOID(Op, DAG); 3118 case ISD::BSWAP: 3119 case ISD::BITREVERSE: { 3120 MVT VT = Op.getSimpleValueType(); 3121 SDLoc DL(Op); 3122 if (Subtarget.hasStdExtZbp()) { 3123 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3124 // Start with the maximum immediate value which is the bitwidth - 1. 3125 unsigned Imm = VT.getSizeInBits() - 1; 3126 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3127 if (Op.getOpcode() == ISD::BSWAP) 3128 Imm &= ~0x7U; 3129 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3130 DAG.getConstant(Imm, DL, VT)); 3131 } 3132 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3133 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3134 // Expand bitreverse to a bswap(rev8) followed by brev8. 3135 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3136 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3137 // as brev8 by an isel pattern. 3138 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3139 DAG.getConstant(7, DL, VT)); 3140 } 3141 case ISD::FSHL: 3142 case ISD::FSHR: { 3143 MVT VT = Op.getSimpleValueType(); 3144 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3145 SDLoc DL(Op); 3146 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3147 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3148 // accidentally setting the extra bit. 3149 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3150 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3151 DAG.getConstant(ShAmtWidth, DL, VT)); 3152 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3153 // instruction use different orders. fshl will return its first operand for 3154 // shift of zero, fshr will return its second operand. fsl and fsr both 3155 // return rs1 so the ISD nodes need to have different operand orders. 3156 // Shift amount is in rs2. 3157 SDValue Op0 = Op.getOperand(0); 3158 SDValue Op1 = Op.getOperand(1); 3159 unsigned Opc = RISCVISD::FSL; 3160 if (Op.getOpcode() == ISD::FSHR) { 3161 std::swap(Op0, Op1); 3162 Opc = RISCVISD::FSR; 3163 } 3164 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3165 } 3166 case ISD::TRUNCATE: { 3167 SDLoc DL(Op); 3168 MVT VT = Op.getSimpleValueType(); 3169 // Only custom-lower vector truncates 3170 if (!VT.isVector()) 3171 return Op; 3172 3173 // Truncates to mask types are handled differently 3174 if (VT.getVectorElementType() == MVT::i1) 3175 return lowerVectorMaskTrunc(Op, DAG); 3176 3177 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3178 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3179 // truncate by one power of two at a time. 3180 MVT DstEltVT = VT.getVectorElementType(); 3181 3182 SDValue Src = Op.getOperand(0); 3183 MVT SrcVT = Src.getSimpleValueType(); 3184 MVT SrcEltVT = SrcVT.getVectorElementType(); 3185 3186 assert(DstEltVT.bitsLT(SrcEltVT) && 3187 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3188 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3189 "Unexpected vector truncate lowering"); 3190 3191 MVT ContainerVT = SrcVT; 3192 if (SrcVT.isFixedLengthVector()) { 3193 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3194 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3195 } 3196 3197 SDValue Result = Src; 3198 SDValue Mask, VL; 3199 std::tie(Mask, VL) = 3200 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3201 LLVMContext &Context = *DAG.getContext(); 3202 const ElementCount Count = ContainerVT.getVectorElementCount(); 3203 do { 3204 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3205 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3206 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3207 Mask, VL); 3208 } while (SrcEltVT != DstEltVT); 3209 3210 if (SrcVT.isFixedLengthVector()) 3211 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3212 3213 return Result; 3214 } 3215 case ISD::ANY_EXTEND: 3216 case ISD::ZERO_EXTEND: 3217 if (Op.getOperand(0).getValueType().isVector() && 3218 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3219 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3220 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3221 case ISD::SIGN_EXTEND: 3222 if (Op.getOperand(0).getValueType().isVector() && 3223 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3224 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3225 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3226 case ISD::SPLAT_VECTOR_PARTS: 3227 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3228 case ISD::INSERT_VECTOR_ELT: 3229 return lowerINSERT_VECTOR_ELT(Op, DAG); 3230 case ISD::EXTRACT_VECTOR_ELT: 3231 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3232 case ISD::VSCALE: { 3233 MVT VT = Op.getSimpleValueType(); 3234 SDLoc DL(Op); 3235 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3236 // We define our scalable vector types for lmul=1 to use a 64 bit known 3237 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3238 // vscale as VLENB / 8. 3239 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3240 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3241 report_fatal_error("Support for VLEN==32 is incomplete."); 3242 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3243 // We assume VLENB is a multiple of 8. We manually choose the best shift 3244 // here because SimplifyDemandedBits isn't always able to simplify it. 3245 uint64_t Val = Op.getConstantOperandVal(0); 3246 if (isPowerOf2_64(Val)) { 3247 uint64_t Log2 = Log2_64(Val); 3248 if (Log2 < 3) 3249 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3250 DAG.getConstant(3 - Log2, DL, VT)); 3251 if (Log2 > 3) 3252 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3253 DAG.getConstant(Log2 - 3, DL, VT)); 3254 return VLENB; 3255 } 3256 // If the multiplier is a multiple of 8, scale it down to avoid needing 3257 // to shift the VLENB value. 3258 if ((Val % 8) == 0) 3259 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3260 DAG.getConstant(Val / 8, DL, VT)); 3261 } 3262 3263 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3264 DAG.getConstant(3, DL, VT)); 3265 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3266 } 3267 case ISD::FPOWI: { 3268 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3269 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3270 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3271 Op.getOperand(1).getValueType() == MVT::i32) { 3272 SDLoc DL(Op); 3273 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3274 SDValue Powi = 3275 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3276 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3277 DAG.getIntPtrConstant(0, DL)); 3278 } 3279 return SDValue(); 3280 } 3281 case ISD::FP_EXTEND: { 3282 // RVV can only do fp_extend to types double the size as the source. We 3283 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3284 // via f32. 3285 SDLoc DL(Op); 3286 MVT VT = Op.getSimpleValueType(); 3287 SDValue Src = Op.getOperand(0); 3288 MVT SrcVT = Src.getSimpleValueType(); 3289 3290 // Prepare any fixed-length vector operands. 3291 MVT ContainerVT = VT; 3292 if (SrcVT.isFixedLengthVector()) { 3293 ContainerVT = getContainerForFixedLengthVector(VT); 3294 MVT SrcContainerVT = 3295 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3296 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3297 } 3298 3299 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3300 SrcVT.getVectorElementType() != MVT::f16) { 3301 // For scalable vectors, we only need to close the gap between 3302 // vXf16->vXf64. 3303 if (!VT.isFixedLengthVector()) 3304 return Op; 3305 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3306 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3307 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3308 } 3309 3310 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3311 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3312 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3313 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3314 3315 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3316 DL, DAG, Subtarget); 3317 if (VT.isFixedLengthVector()) 3318 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3319 return Extend; 3320 } 3321 case ISD::FP_ROUND: { 3322 // RVV can only do fp_round to types half the size as the source. We 3323 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3324 // conversion instruction. 3325 SDLoc DL(Op); 3326 MVT VT = Op.getSimpleValueType(); 3327 SDValue Src = Op.getOperand(0); 3328 MVT SrcVT = Src.getSimpleValueType(); 3329 3330 // Prepare any fixed-length vector operands. 3331 MVT ContainerVT = VT; 3332 if (VT.isFixedLengthVector()) { 3333 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3334 ContainerVT = 3335 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3336 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3337 } 3338 3339 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3340 SrcVT.getVectorElementType() != MVT::f64) { 3341 // For scalable vectors, we only need to close the gap between 3342 // vXf64<->vXf16. 3343 if (!VT.isFixedLengthVector()) 3344 return Op; 3345 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3346 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3347 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3348 } 3349 3350 SDValue Mask, VL; 3351 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3352 3353 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3354 SDValue IntermediateRound = 3355 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3356 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3357 DL, DAG, Subtarget); 3358 3359 if (VT.isFixedLengthVector()) 3360 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3361 return Round; 3362 } 3363 case ISD::FP_TO_SINT: 3364 case ISD::FP_TO_UINT: 3365 case ISD::SINT_TO_FP: 3366 case ISD::UINT_TO_FP: { 3367 // RVV can only do fp<->int conversions to types half/double the size as 3368 // the source. We custom-lower any conversions that do two hops into 3369 // sequences. 3370 MVT VT = Op.getSimpleValueType(); 3371 if (!VT.isVector()) 3372 return Op; 3373 SDLoc DL(Op); 3374 SDValue Src = Op.getOperand(0); 3375 MVT EltVT = VT.getVectorElementType(); 3376 MVT SrcVT = Src.getSimpleValueType(); 3377 MVT SrcEltVT = SrcVT.getVectorElementType(); 3378 unsigned EltSize = EltVT.getSizeInBits(); 3379 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3380 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3381 "Unexpected vector element types"); 3382 3383 bool IsInt2FP = SrcEltVT.isInteger(); 3384 // Widening conversions 3385 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 3386 if (IsInt2FP) { 3387 // Do a regular integer sign/zero extension then convert to float. 3388 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 3389 VT.getVectorElementCount()); 3390 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3391 ? ISD::ZERO_EXTEND 3392 : ISD::SIGN_EXTEND; 3393 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3394 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3395 } 3396 // FP2Int 3397 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3398 // Do one doubling fp_extend then complete the operation by converting 3399 // to int. 3400 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3401 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3402 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3403 } 3404 3405 // Narrowing conversions 3406 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 3407 if (IsInt2FP) { 3408 // One narrowing int_to_fp, then an fp_round. 3409 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3410 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3411 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3412 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3413 } 3414 // FP2Int 3415 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3416 // representable by the integer, the result is poison. 3417 MVT IVecVT = 3418 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3419 VT.getVectorElementCount()); 3420 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3421 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3422 } 3423 3424 // Scalable vectors can exit here. Patterns will handle equally-sized 3425 // conversions halving/doubling ones. 3426 if (!VT.isFixedLengthVector()) 3427 return Op; 3428 3429 // For fixed-length vectors we lower to a custom "VL" node. 3430 unsigned RVVOpc = 0; 3431 switch (Op.getOpcode()) { 3432 default: 3433 llvm_unreachable("Impossible opcode"); 3434 case ISD::FP_TO_SINT: 3435 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3436 break; 3437 case ISD::FP_TO_UINT: 3438 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3439 break; 3440 case ISD::SINT_TO_FP: 3441 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3442 break; 3443 case ISD::UINT_TO_FP: 3444 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3445 break; 3446 } 3447 3448 MVT ContainerVT, SrcContainerVT; 3449 // Derive the reference container type from the larger vector type. 3450 if (SrcEltSize > EltSize) { 3451 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3452 ContainerVT = 3453 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3454 } else { 3455 ContainerVT = getContainerForFixedLengthVector(VT); 3456 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3457 } 3458 3459 SDValue Mask, VL; 3460 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3461 3462 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3463 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3464 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3465 } 3466 case ISD::FP_TO_SINT_SAT: 3467 case ISD::FP_TO_UINT_SAT: 3468 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3469 case ISD::FTRUNC: 3470 case ISD::FCEIL: 3471 case ISD::FFLOOR: 3472 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3473 case ISD::FROUND: 3474 return lowerFROUND(Op, DAG); 3475 case ISD::VECREDUCE_ADD: 3476 case ISD::VECREDUCE_UMAX: 3477 case ISD::VECREDUCE_SMAX: 3478 case ISD::VECREDUCE_UMIN: 3479 case ISD::VECREDUCE_SMIN: 3480 return lowerVECREDUCE(Op, DAG); 3481 case ISD::VECREDUCE_AND: 3482 case ISD::VECREDUCE_OR: 3483 case ISD::VECREDUCE_XOR: 3484 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3485 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3486 return lowerVECREDUCE(Op, DAG); 3487 case ISD::VECREDUCE_FADD: 3488 case ISD::VECREDUCE_SEQ_FADD: 3489 case ISD::VECREDUCE_FMIN: 3490 case ISD::VECREDUCE_FMAX: 3491 return lowerFPVECREDUCE(Op, DAG); 3492 case ISD::VP_REDUCE_ADD: 3493 case ISD::VP_REDUCE_UMAX: 3494 case ISD::VP_REDUCE_SMAX: 3495 case ISD::VP_REDUCE_UMIN: 3496 case ISD::VP_REDUCE_SMIN: 3497 case ISD::VP_REDUCE_FADD: 3498 case ISD::VP_REDUCE_SEQ_FADD: 3499 case ISD::VP_REDUCE_FMIN: 3500 case ISD::VP_REDUCE_FMAX: 3501 return lowerVPREDUCE(Op, DAG); 3502 case ISD::VP_REDUCE_AND: 3503 case ISD::VP_REDUCE_OR: 3504 case ISD::VP_REDUCE_XOR: 3505 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3506 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3507 return lowerVPREDUCE(Op, DAG); 3508 case ISD::INSERT_SUBVECTOR: 3509 return lowerINSERT_SUBVECTOR(Op, DAG); 3510 case ISD::EXTRACT_SUBVECTOR: 3511 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3512 case ISD::STEP_VECTOR: 3513 return lowerSTEP_VECTOR(Op, DAG); 3514 case ISD::VECTOR_REVERSE: 3515 return lowerVECTOR_REVERSE(Op, DAG); 3516 case ISD::VECTOR_SPLICE: 3517 return lowerVECTOR_SPLICE(Op, DAG); 3518 case ISD::BUILD_VECTOR: 3519 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3520 case ISD::SPLAT_VECTOR: 3521 if (Op.getValueType().getVectorElementType() == MVT::i1) 3522 return lowerVectorMaskSplat(Op, DAG); 3523 return SDValue(); 3524 case ISD::VECTOR_SHUFFLE: 3525 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3526 case ISD::CONCAT_VECTORS: { 3527 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3528 // better than going through the stack, as the default expansion does. 3529 SDLoc DL(Op); 3530 MVT VT = Op.getSimpleValueType(); 3531 unsigned NumOpElts = 3532 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3533 SDValue Vec = DAG.getUNDEF(VT); 3534 for (const auto &OpIdx : enumerate(Op->ops())) { 3535 SDValue SubVec = OpIdx.value(); 3536 // Don't insert undef subvectors. 3537 if (SubVec.isUndef()) 3538 continue; 3539 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3540 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3541 } 3542 return Vec; 3543 } 3544 case ISD::LOAD: 3545 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3546 return V; 3547 if (Op.getValueType().isFixedLengthVector()) 3548 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3549 return Op; 3550 case ISD::STORE: 3551 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3552 return V; 3553 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3554 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3555 return Op; 3556 case ISD::MLOAD: 3557 case ISD::VP_LOAD: 3558 return lowerMaskedLoad(Op, DAG); 3559 case ISD::MSTORE: 3560 case ISD::VP_STORE: 3561 return lowerMaskedStore(Op, DAG); 3562 case ISD::SETCC: 3563 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3564 case ISD::ADD: 3565 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3566 case ISD::SUB: 3567 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3568 case ISD::MUL: 3569 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3570 case ISD::MULHS: 3571 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3572 case ISD::MULHU: 3573 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3574 case ISD::AND: 3575 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3576 RISCVISD::AND_VL); 3577 case ISD::OR: 3578 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3579 RISCVISD::OR_VL); 3580 case ISD::XOR: 3581 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3582 RISCVISD::XOR_VL); 3583 case ISD::SDIV: 3584 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3585 case ISD::SREM: 3586 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3587 case ISD::UDIV: 3588 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3589 case ISD::UREM: 3590 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3591 case ISD::SHL: 3592 case ISD::SRA: 3593 case ISD::SRL: 3594 if (Op.getSimpleValueType().isFixedLengthVector()) 3595 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3596 // This can be called for an i32 shift amount that needs to be promoted. 3597 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3598 "Unexpected custom legalisation"); 3599 return SDValue(); 3600 case ISD::SADDSAT: 3601 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3602 case ISD::UADDSAT: 3603 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3604 case ISD::SSUBSAT: 3605 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3606 case ISD::USUBSAT: 3607 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3608 case ISD::FADD: 3609 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3610 case ISD::FSUB: 3611 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3612 case ISD::FMUL: 3613 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3614 case ISD::FDIV: 3615 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3616 case ISD::FNEG: 3617 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3618 case ISD::FABS: 3619 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3620 case ISD::FSQRT: 3621 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3622 case ISD::FMA: 3623 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3624 case ISD::SMIN: 3625 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3626 case ISD::SMAX: 3627 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3628 case ISD::UMIN: 3629 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3630 case ISD::UMAX: 3631 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3632 case ISD::FMINNUM: 3633 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3634 case ISD::FMAXNUM: 3635 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3636 case ISD::ABS: 3637 return lowerABS(Op, DAG); 3638 case ISD::CTLZ_ZERO_UNDEF: 3639 case ISD::CTTZ_ZERO_UNDEF: 3640 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3641 case ISD::VSELECT: 3642 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3643 case ISD::FCOPYSIGN: 3644 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3645 case ISD::MGATHER: 3646 case ISD::VP_GATHER: 3647 return lowerMaskedGather(Op, DAG); 3648 case ISD::MSCATTER: 3649 case ISD::VP_SCATTER: 3650 return lowerMaskedScatter(Op, DAG); 3651 case ISD::FLT_ROUNDS_: 3652 return lowerGET_ROUNDING(Op, DAG); 3653 case ISD::SET_ROUNDING: 3654 return lowerSET_ROUNDING(Op, DAG); 3655 case ISD::VP_SELECT: 3656 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3657 case ISD::VP_MERGE: 3658 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3659 case ISD::VP_ADD: 3660 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3661 case ISD::VP_SUB: 3662 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3663 case ISD::VP_MUL: 3664 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3665 case ISD::VP_SDIV: 3666 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3667 case ISD::VP_UDIV: 3668 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3669 case ISD::VP_SREM: 3670 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3671 case ISD::VP_UREM: 3672 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3673 case ISD::VP_AND: 3674 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3675 case ISD::VP_OR: 3676 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3677 case ISD::VP_XOR: 3678 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3679 case ISD::VP_ASHR: 3680 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3681 case ISD::VP_LSHR: 3682 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3683 case ISD::VP_SHL: 3684 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3685 case ISD::VP_FADD: 3686 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3687 case ISD::VP_FSUB: 3688 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3689 case ISD::VP_FMUL: 3690 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3691 case ISD::VP_FDIV: 3692 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3693 case ISD::VP_FNEG: 3694 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3695 case ISD::VP_FMA: 3696 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3697 } 3698 } 3699 3700 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3701 SelectionDAG &DAG, unsigned Flags) { 3702 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3703 } 3704 3705 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3706 SelectionDAG &DAG, unsigned Flags) { 3707 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3708 Flags); 3709 } 3710 3711 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3712 SelectionDAG &DAG, unsigned Flags) { 3713 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3714 N->getOffset(), Flags); 3715 } 3716 3717 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3718 SelectionDAG &DAG, unsigned Flags) { 3719 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3720 } 3721 3722 template <class NodeTy> 3723 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3724 bool IsLocal) const { 3725 SDLoc DL(N); 3726 EVT Ty = getPointerTy(DAG.getDataLayout()); 3727 3728 if (isPositionIndependent()) { 3729 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3730 if (IsLocal) 3731 // Use PC-relative addressing to access the symbol. This generates the 3732 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3733 // %pcrel_lo(auipc)). 3734 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3735 3736 // Use PC-relative addressing to access the GOT for this symbol, then load 3737 // the address from the GOT. This generates the pattern (PseudoLA sym), 3738 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3739 SDValue Load = 3740 SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3741 MachineFunction &MF = DAG.getMachineFunction(); 3742 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3743 MachinePointerInfo::getGOT(MF), 3744 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3745 MachineMemOperand::MOInvariant, 3746 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3747 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3748 return Load; 3749 } 3750 3751 switch (getTargetMachine().getCodeModel()) { 3752 default: 3753 report_fatal_error("Unsupported code model for lowering"); 3754 case CodeModel::Small: { 3755 // Generate a sequence for accessing addresses within the first 2 GiB of 3756 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3757 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3758 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3759 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3760 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3761 } 3762 case CodeModel::Medium: { 3763 // Generate a sequence for accessing addresses within any 2GiB range within 3764 // the address space. This generates the pattern (PseudoLLA sym), which 3765 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3766 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3767 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3768 } 3769 } 3770 } 3771 3772 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>( 3773 GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3774 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>( 3775 BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3776 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>( 3777 ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3778 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>( 3779 JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3780 3781 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3782 SelectionDAG &DAG) const { 3783 SDLoc DL(Op); 3784 EVT Ty = Op.getValueType(); 3785 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3786 int64_t Offset = N->getOffset(); 3787 MVT XLenVT = Subtarget.getXLenVT(); 3788 3789 const GlobalValue *GV = N->getGlobal(); 3790 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3791 SDValue Addr = getAddr(N, DAG, IsLocal); 3792 3793 // In order to maximise the opportunity for common subexpression elimination, 3794 // emit a separate ADD node for the global address offset instead of folding 3795 // it in the global address node. Later peephole optimisations may choose to 3796 // fold it back in when profitable. 3797 if (Offset != 0) 3798 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3799 DAG.getConstant(Offset, DL, XLenVT)); 3800 return Addr; 3801 } 3802 3803 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3804 SelectionDAG &DAG) const { 3805 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3806 3807 return getAddr(N, DAG); 3808 } 3809 3810 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3811 SelectionDAG &DAG) const { 3812 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3813 3814 return getAddr(N, DAG); 3815 } 3816 3817 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3818 SelectionDAG &DAG) const { 3819 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3820 3821 return getAddr(N, DAG); 3822 } 3823 3824 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3825 SelectionDAG &DAG, 3826 bool UseGOT) const { 3827 SDLoc DL(N); 3828 EVT Ty = getPointerTy(DAG.getDataLayout()); 3829 const GlobalValue *GV = N->getGlobal(); 3830 MVT XLenVT = Subtarget.getXLenVT(); 3831 3832 if (UseGOT) { 3833 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3834 // load the address from the GOT and add the thread pointer. This generates 3835 // the pattern (PseudoLA_TLS_IE sym), which expands to 3836 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3837 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3838 SDValue Load = 3839 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3840 MachineFunction &MF = DAG.getMachineFunction(); 3841 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3842 MachinePointerInfo::getGOT(MF), 3843 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3844 MachineMemOperand::MOInvariant, 3845 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3846 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3847 3848 // Add the thread pointer. 3849 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3850 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3851 } 3852 3853 // Generate a sequence for accessing the address relative to the thread 3854 // pointer, with the appropriate adjustment for the thread pointer offset. 3855 // This generates the pattern 3856 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3857 SDValue AddrHi = 3858 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3859 SDValue AddrAdd = 3860 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3861 SDValue AddrLo = 3862 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3863 3864 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3865 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3866 SDValue MNAdd = SDValue( 3867 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3868 0); 3869 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3870 } 3871 3872 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3873 SelectionDAG &DAG) const { 3874 SDLoc DL(N); 3875 EVT Ty = getPointerTy(DAG.getDataLayout()); 3876 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3877 const GlobalValue *GV = N->getGlobal(); 3878 3879 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3880 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3881 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3882 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3883 SDValue Load = 3884 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3885 3886 // Prepare argument list to generate call. 3887 ArgListTy Args; 3888 ArgListEntry Entry; 3889 Entry.Node = Load; 3890 Entry.Ty = CallTy; 3891 Args.push_back(Entry); 3892 3893 // Setup call to __tls_get_addr. 3894 TargetLowering::CallLoweringInfo CLI(DAG); 3895 CLI.setDebugLoc(DL) 3896 .setChain(DAG.getEntryNode()) 3897 .setLibCallee(CallingConv::C, CallTy, 3898 DAG.getExternalSymbol("__tls_get_addr", Ty), 3899 std::move(Args)); 3900 3901 return LowerCallTo(CLI).first; 3902 } 3903 3904 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3905 SelectionDAG &DAG) const { 3906 SDLoc DL(Op); 3907 EVT Ty = Op.getValueType(); 3908 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3909 int64_t Offset = N->getOffset(); 3910 MVT XLenVT = Subtarget.getXLenVT(); 3911 3912 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3913 3914 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3915 CallingConv::GHC) 3916 report_fatal_error("In GHC calling convention TLS is not supported"); 3917 3918 SDValue Addr; 3919 switch (Model) { 3920 case TLSModel::LocalExec: 3921 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3922 break; 3923 case TLSModel::InitialExec: 3924 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3925 break; 3926 case TLSModel::LocalDynamic: 3927 case TLSModel::GeneralDynamic: 3928 Addr = getDynamicTLSAddr(N, DAG); 3929 break; 3930 } 3931 3932 // In order to maximise the opportunity for common subexpression elimination, 3933 // emit a separate ADD node for the global address offset instead of folding 3934 // it in the global address node. Later peephole optimisations may choose to 3935 // fold it back in when profitable. 3936 if (Offset != 0) 3937 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3938 DAG.getConstant(Offset, DL, XLenVT)); 3939 return Addr; 3940 } 3941 3942 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3943 SDValue CondV = Op.getOperand(0); 3944 SDValue TrueV = Op.getOperand(1); 3945 SDValue FalseV = Op.getOperand(2); 3946 SDLoc DL(Op); 3947 MVT VT = Op.getSimpleValueType(); 3948 MVT XLenVT = Subtarget.getXLenVT(); 3949 3950 // Lower vector SELECTs to VSELECTs by splatting the condition. 3951 if (VT.isVector()) { 3952 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3953 SDValue CondSplat = VT.isScalableVector() 3954 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3955 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3956 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3957 } 3958 3959 // If the result type is XLenVT and CondV is the output of a SETCC node 3960 // which also operated on XLenVT inputs, then merge the SETCC node into the 3961 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3962 // compare+branch instructions. i.e.: 3963 // (select (setcc lhs, rhs, cc), truev, falsev) 3964 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3965 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3966 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3967 SDValue LHS = CondV.getOperand(0); 3968 SDValue RHS = CondV.getOperand(1); 3969 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3970 ISD::CondCode CCVal = CC->get(); 3971 3972 // Special case for a select of 2 constants that have a diffence of 1. 3973 // Normally this is done by DAGCombine, but if the select is introduced by 3974 // type legalization or op legalization, we miss it. Restricting to SETLT 3975 // case for now because that is what signed saturating add/sub need. 3976 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3977 // but we would probably want to swap the true/false values if the condition 3978 // is SETGE/SETLE to avoid an XORI. 3979 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3980 CCVal == ISD::SETLT) { 3981 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3982 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3983 if (TrueVal - 1 == FalseVal) 3984 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3985 if (TrueVal + 1 == FalseVal) 3986 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3987 } 3988 3989 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3990 3991 SDValue TargetCC = DAG.getCondCode(CCVal); 3992 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3993 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3994 } 3995 3996 // Otherwise: 3997 // (select condv, truev, falsev) 3998 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3999 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4000 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 4001 4002 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 4003 4004 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 4005 } 4006 4007 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4008 SDValue CondV = Op.getOperand(1); 4009 SDLoc DL(Op); 4010 MVT XLenVT = Subtarget.getXLenVT(); 4011 4012 if (CondV.getOpcode() == ISD::SETCC && 4013 CondV.getOperand(0).getValueType() == XLenVT) { 4014 SDValue LHS = CondV.getOperand(0); 4015 SDValue RHS = CondV.getOperand(1); 4016 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 4017 4018 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 4019 4020 SDValue TargetCC = DAG.getCondCode(CCVal); 4021 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 4022 LHS, RHS, TargetCC, Op.getOperand(2)); 4023 } 4024 4025 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 4026 CondV, DAG.getConstant(0, DL, XLenVT), 4027 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 4028 } 4029 4030 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 4031 MachineFunction &MF = DAG.getMachineFunction(); 4032 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 4033 4034 SDLoc DL(Op); 4035 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 4036 getPointerTy(MF.getDataLayout())); 4037 4038 // vastart just stores the address of the VarArgsFrameIndex slot into the 4039 // memory location argument. 4040 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4041 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 4042 MachinePointerInfo(SV)); 4043 } 4044 4045 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 4046 SelectionDAG &DAG) const { 4047 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4048 MachineFunction &MF = DAG.getMachineFunction(); 4049 MachineFrameInfo &MFI = MF.getFrameInfo(); 4050 MFI.setFrameAddressIsTaken(true); 4051 Register FrameReg = RI.getFrameRegister(MF); 4052 int XLenInBytes = Subtarget.getXLen() / 8; 4053 4054 EVT VT = Op.getValueType(); 4055 SDLoc DL(Op); 4056 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 4057 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4058 while (Depth--) { 4059 int Offset = -(XLenInBytes * 2); 4060 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 4061 DAG.getIntPtrConstant(Offset, DL)); 4062 FrameAddr = 4063 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 4064 } 4065 return FrameAddr; 4066 } 4067 4068 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 4069 SelectionDAG &DAG) const { 4070 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4071 MachineFunction &MF = DAG.getMachineFunction(); 4072 MachineFrameInfo &MFI = MF.getFrameInfo(); 4073 MFI.setReturnAddressIsTaken(true); 4074 MVT XLenVT = Subtarget.getXLenVT(); 4075 int XLenInBytes = Subtarget.getXLen() / 8; 4076 4077 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4078 return SDValue(); 4079 4080 EVT VT = Op.getValueType(); 4081 SDLoc DL(Op); 4082 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4083 if (Depth) { 4084 int Off = -XLenInBytes; 4085 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 4086 SDValue Offset = DAG.getConstant(Off, DL, VT); 4087 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4088 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4089 MachinePointerInfo()); 4090 } 4091 4092 // Return the value of the return address register, marking it an implicit 4093 // live-in. 4094 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 4095 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 4096 } 4097 4098 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4099 SelectionDAG &DAG) const { 4100 SDLoc DL(Op); 4101 SDValue Lo = Op.getOperand(0); 4102 SDValue Hi = Op.getOperand(1); 4103 SDValue Shamt = Op.getOperand(2); 4104 EVT VT = Lo.getValueType(); 4105 4106 // if Shamt-XLEN < 0: // Shamt < XLEN 4107 // Lo = Lo << Shamt 4108 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4109 // else: 4110 // Lo = 0 4111 // Hi = Lo << (Shamt-XLEN) 4112 4113 SDValue Zero = DAG.getConstant(0, DL, VT); 4114 SDValue One = DAG.getConstant(1, DL, VT); 4115 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4116 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4117 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4118 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4119 4120 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4121 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4122 SDValue ShiftRightLo = 4123 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4124 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4125 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4126 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4127 4128 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4129 4130 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4131 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4132 4133 SDValue Parts[2] = {Lo, Hi}; 4134 return DAG.getMergeValues(Parts, DL); 4135 } 4136 4137 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4138 bool IsSRA) const { 4139 SDLoc DL(Op); 4140 SDValue Lo = Op.getOperand(0); 4141 SDValue Hi = Op.getOperand(1); 4142 SDValue Shamt = Op.getOperand(2); 4143 EVT VT = Lo.getValueType(); 4144 4145 // SRA expansion: 4146 // if Shamt-XLEN < 0: // Shamt < XLEN 4147 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4148 // Hi = Hi >>s Shamt 4149 // else: 4150 // Lo = Hi >>s (Shamt-XLEN); 4151 // Hi = Hi >>s (XLEN-1) 4152 // 4153 // SRL expansion: 4154 // if Shamt-XLEN < 0: // Shamt < XLEN 4155 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4156 // Hi = Hi >>u Shamt 4157 // else: 4158 // Lo = Hi >>u (Shamt-XLEN); 4159 // Hi = 0; 4160 4161 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4162 4163 SDValue Zero = DAG.getConstant(0, DL, VT); 4164 SDValue One = DAG.getConstant(1, DL, VT); 4165 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4166 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4167 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4168 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4169 4170 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4171 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4172 SDValue ShiftLeftHi = 4173 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4174 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4175 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4176 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4177 SDValue HiFalse = 4178 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4179 4180 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4181 4182 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4183 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4184 4185 SDValue Parts[2] = {Lo, Hi}; 4186 return DAG.getMergeValues(Parts, DL); 4187 } 4188 4189 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4190 // legal equivalently-sized i8 type, so we can use that as a go-between. 4191 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4192 SelectionDAG &DAG) const { 4193 SDLoc DL(Op); 4194 MVT VT = Op.getSimpleValueType(); 4195 SDValue SplatVal = Op.getOperand(0); 4196 // All-zeros or all-ones splats are handled specially. 4197 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4198 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4199 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4200 } 4201 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4202 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4203 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4204 } 4205 MVT XLenVT = Subtarget.getXLenVT(); 4206 assert(SplatVal.getValueType() == XLenVT && 4207 "Unexpected type for i1 splat value"); 4208 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4209 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4210 DAG.getConstant(1, DL, XLenVT)); 4211 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4212 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4213 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4214 } 4215 4216 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4217 // illegal (currently only vXi64 RV32). 4218 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4219 // them to VMV_V_X_VL. 4220 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4221 SelectionDAG &DAG) const { 4222 SDLoc DL(Op); 4223 MVT VecVT = Op.getSimpleValueType(); 4224 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4225 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4226 4227 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4228 SDValue Lo = Op.getOperand(0); 4229 SDValue Hi = Op.getOperand(1); 4230 4231 if (VecVT.isFixedLengthVector()) { 4232 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4233 SDLoc DL(Op); 4234 SDValue Mask, VL; 4235 std::tie(Mask, VL) = 4236 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4237 4238 SDValue Res = 4239 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4240 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4241 } 4242 4243 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4244 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4245 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4246 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4247 // node in order to try and match RVV vector/scalar instructions. 4248 if ((LoC >> 31) == HiC) 4249 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4250 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4251 } 4252 4253 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4254 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4255 isa<ConstantSDNode>(Hi.getOperand(1)) && 4256 Hi.getConstantOperandVal(1) == 31) 4257 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4258 DAG.getRegister(RISCV::X0, MVT::i32)); 4259 4260 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4261 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4262 DAG.getUNDEF(VecVT), Lo, Hi, 4263 DAG.getRegister(RISCV::X0, MVT::i32)); 4264 } 4265 4266 // Custom-lower extensions from mask vectors by using a vselect either with 1 4267 // for zero/any-extension or -1 for sign-extension: 4268 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4269 // Note that any-extension is lowered identically to zero-extension. 4270 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4271 int64_t ExtTrueVal) const { 4272 SDLoc DL(Op); 4273 MVT VecVT = Op.getSimpleValueType(); 4274 SDValue Src = Op.getOperand(0); 4275 // Only custom-lower extensions from mask types 4276 assert(Src.getValueType().isVector() && 4277 Src.getValueType().getVectorElementType() == MVT::i1); 4278 4279 if (VecVT.isScalableVector()) { 4280 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4281 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4282 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4283 } 4284 4285 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4286 MVT I1ContainerVT = 4287 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4288 4289 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4290 4291 SDValue Mask, VL; 4292 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4293 4294 MVT XLenVT = Subtarget.getXLenVT(); 4295 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4296 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4297 4298 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4299 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4300 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4301 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4302 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4303 SplatTrueVal, SplatZero, VL); 4304 4305 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4306 } 4307 4308 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4309 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4310 MVT ExtVT = Op.getSimpleValueType(); 4311 // Only custom-lower extensions from fixed-length vector types. 4312 if (!ExtVT.isFixedLengthVector()) 4313 return Op; 4314 MVT VT = Op.getOperand(0).getSimpleValueType(); 4315 // Grab the canonical container type for the extended type. Infer the smaller 4316 // type from that to ensure the same number of vector elements, as we know 4317 // the LMUL will be sufficient to hold the smaller type. 4318 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4319 // Get the extended container type manually to ensure the same number of 4320 // vector elements between source and dest. 4321 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4322 ContainerExtVT.getVectorElementCount()); 4323 4324 SDValue Op1 = 4325 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4326 4327 SDLoc DL(Op); 4328 SDValue Mask, VL; 4329 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4330 4331 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4332 4333 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4334 } 4335 4336 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4337 // setcc operation: 4338 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4339 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 4340 SelectionDAG &DAG) const { 4341 SDLoc DL(Op); 4342 EVT MaskVT = Op.getValueType(); 4343 // Only expect to custom-lower truncations to mask types 4344 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4345 "Unexpected type for vector mask lowering"); 4346 SDValue Src = Op.getOperand(0); 4347 MVT VecVT = Src.getSimpleValueType(); 4348 4349 // If this is a fixed vector, we need to convert it to a scalable vector. 4350 MVT ContainerVT = VecVT; 4351 if (VecVT.isFixedLengthVector()) { 4352 ContainerVT = getContainerForFixedLengthVector(VecVT); 4353 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4354 } 4355 4356 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4357 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4358 4359 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4360 DAG.getUNDEF(ContainerVT), SplatOne); 4361 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4362 DAG.getUNDEF(ContainerVT), SplatZero); 4363 4364 if (VecVT.isScalableVector()) { 4365 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 4366 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 4367 } 4368 4369 SDValue Mask, VL; 4370 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4371 4372 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4373 SDValue Trunc = 4374 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4375 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4376 DAG.getCondCode(ISD::SETNE), Mask, VL); 4377 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4378 } 4379 4380 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4381 // first position of a vector, and that vector is slid up to the insert index. 4382 // By limiting the active vector length to index+1 and merging with the 4383 // original vector (with an undisturbed tail policy for elements >= VL), we 4384 // achieve the desired result of leaving all elements untouched except the one 4385 // at VL-1, which is replaced with the desired value. 4386 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4387 SelectionDAG &DAG) const { 4388 SDLoc DL(Op); 4389 MVT VecVT = Op.getSimpleValueType(); 4390 SDValue Vec = Op.getOperand(0); 4391 SDValue Val = Op.getOperand(1); 4392 SDValue Idx = Op.getOperand(2); 4393 4394 if (VecVT.getVectorElementType() == MVT::i1) { 4395 // FIXME: For now we just promote to an i8 vector and insert into that, 4396 // but this is probably not optimal. 4397 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4398 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4399 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4400 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4401 } 4402 4403 MVT ContainerVT = VecVT; 4404 // If the operand is a fixed-length vector, convert to a scalable one. 4405 if (VecVT.isFixedLengthVector()) { 4406 ContainerVT = getContainerForFixedLengthVector(VecVT); 4407 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4408 } 4409 4410 MVT XLenVT = Subtarget.getXLenVT(); 4411 4412 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4413 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4414 // Even i64-element vectors on RV32 can be lowered without scalar 4415 // legalization if the most-significant 32 bits of the value are not affected 4416 // by the sign-extension of the lower 32 bits. 4417 // TODO: We could also catch sign extensions of a 32-bit value. 4418 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4419 const auto *CVal = cast<ConstantSDNode>(Val); 4420 if (isInt<32>(CVal->getSExtValue())) { 4421 IsLegalInsert = true; 4422 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4423 } 4424 } 4425 4426 SDValue Mask, VL; 4427 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4428 4429 SDValue ValInVec; 4430 4431 if (IsLegalInsert) { 4432 unsigned Opc = 4433 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4434 if (isNullConstant(Idx)) { 4435 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4436 if (!VecVT.isFixedLengthVector()) 4437 return Vec; 4438 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4439 } 4440 ValInVec = 4441 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4442 } else { 4443 // On RV32, i64-element vectors must be specially handled to place the 4444 // value at element 0, by using two vslide1up instructions in sequence on 4445 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4446 // this. 4447 SDValue One = DAG.getConstant(1, DL, XLenVT); 4448 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4449 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4450 MVT I32ContainerVT = 4451 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4452 SDValue I32Mask = 4453 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4454 // Limit the active VL to two. 4455 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4456 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4457 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4458 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4459 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4460 // First slide in the hi value, then the lo in underneath it. 4461 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4462 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4463 I32Mask, InsertI64VL); 4464 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4465 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4466 I32Mask, InsertI64VL); 4467 // Bitcast back to the right container type. 4468 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4469 } 4470 4471 // Now that the value is in a vector, slide it into position. 4472 SDValue InsertVL = 4473 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4474 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4475 ValInVec, Idx, Mask, InsertVL); 4476 if (!VecVT.isFixedLengthVector()) 4477 return Slideup; 4478 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4479 } 4480 4481 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4482 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4483 // types this is done using VMV_X_S to allow us to glean information about the 4484 // sign bits of the result. 4485 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4486 SelectionDAG &DAG) const { 4487 SDLoc DL(Op); 4488 SDValue Idx = Op.getOperand(1); 4489 SDValue Vec = Op.getOperand(0); 4490 EVT EltVT = Op.getValueType(); 4491 MVT VecVT = Vec.getSimpleValueType(); 4492 MVT XLenVT = Subtarget.getXLenVT(); 4493 4494 if (VecVT.getVectorElementType() == MVT::i1) { 4495 if (VecVT.isFixedLengthVector()) { 4496 unsigned NumElts = VecVT.getVectorNumElements(); 4497 if (NumElts >= 8) { 4498 MVT WideEltVT; 4499 unsigned WidenVecLen; 4500 SDValue ExtractElementIdx; 4501 SDValue ExtractBitIdx; 4502 unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors(); 4503 MVT LargestEltVT = MVT::getIntegerVT( 4504 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4505 if (NumElts <= LargestEltVT.getSizeInBits()) { 4506 assert(isPowerOf2_32(NumElts) && 4507 "the number of elements should be power of 2"); 4508 WideEltVT = MVT::getIntegerVT(NumElts); 4509 WidenVecLen = 1; 4510 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4511 ExtractBitIdx = Idx; 4512 } else { 4513 WideEltVT = LargestEltVT; 4514 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4515 // extract element index = index / element width 4516 ExtractElementIdx = DAG.getNode( 4517 ISD::SRL, DL, XLenVT, Idx, 4518 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4519 // mask bit index = index % element width 4520 ExtractBitIdx = DAG.getNode( 4521 ISD::AND, DL, XLenVT, Idx, 4522 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4523 } 4524 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4525 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4526 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4527 Vec, ExtractElementIdx); 4528 // Extract the bit from GPR. 4529 SDValue ShiftRight = 4530 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4531 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4532 DAG.getConstant(1, DL, XLenVT)); 4533 } 4534 } 4535 // Otherwise, promote to an i8 vector and extract from that. 4536 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4537 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4538 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4539 } 4540 4541 // If this is a fixed vector, we need to convert it to a scalable vector. 4542 MVT ContainerVT = VecVT; 4543 if (VecVT.isFixedLengthVector()) { 4544 ContainerVT = getContainerForFixedLengthVector(VecVT); 4545 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4546 } 4547 4548 // If the index is 0, the vector is already in the right position. 4549 if (!isNullConstant(Idx)) { 4550 // Use a VL of 1 to avoid processing more elements than we need. 4551 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4552 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4553 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4554 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4555 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4556 } 4557 4558 if (!EltVT.isInteger()) { 4559 // Floating-point extracts are handled in TableGen. 4560 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4561 DAG.getConstant(0, DL, XLenVT)); 4562 } 4563 4564 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4565 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4566 } 4567 4568 // Some RVV intrinsics may claim that they want an integer operand to be 4569 // promoted or expanded. 4570 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4571 const RISCVSubtarget &Subtarget) { 4572 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4573 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4574 "Unexpected opcode"); 4575 4576 if (!Subtarget.hasVInstructions()) 4577 return SDValue(); 4578 4579 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4580 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4581 SDLoc DL(Op); 4582 4583 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4584 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4585 if (!II || !II->hasScalarOperand()) 4586 return SDValue(); 4587 4588 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4589 assert(SplatOp < Op.getNumOperands()); 4590 4591 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4592 SDValue &ScalarOp = Operands[SplatOp]; 4593 MVT OpVT = ScalarOp.getSimpleValueType(); 4594 MVT XLenVT = Subtarget.getXLenVT(); 4595 4596 // If this isn't a scalar, or its type is XLenVT we're done. 4597 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4598 return SDValue(); 4599 4600 // Simplest case is that the operand needs to be promoted to XLenVT. 4601 if (OpVT.bitsLT(XLenVT)) { 4602 // If the operand is a constant, sign extend to increase our chances 4603 // of being able to use a .vi instruction. ANY_EXTEND would become a 4604 // a zero extend and the simm5 check in isel would fail. 4605 // FIXME: Should we ignore the upper bits in isel instead? 4606 unsigned ExtOpc = 4607 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4608 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4609 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4610 } 4611 4612 // Use the previous operand to get the vXi64 VT. The result might be a mask 4613 // VT for compares. Using the previous operand assumes that the previous 4614 // operand will never have a smaller element size than a scalar operand and 4615 // that a widening operation never uses SEW=64. 4616 // NOTE: If this fails the below assert, we can probably just find the 4617 // element count from any operand or result and use it to construct the VT. 4618 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4619 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4620 4621 // The more complex case is when the scalar is larger than XLenVT. 4622 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4623 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4624 4625 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4626 // on the instruction to sign-extend since SEW>XLEN. 4627 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4628 if (isInt<32>(CVal->getSExtValue())) { 4629 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4630 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4631 } 4632 } 4633 4634 switch (IntNo) { 4635 case Intrinsic::riscv_vslide1up: 4636 case Intrinsic::riscv_vslide1down: 4637 case Intrinsic::riscv_vslide1up_mask: 4638 case Intrinsic::riscv_vslide1down_mask: { 4639 // We need to special case these when the scalar is larger than XLen. 4640 unsigned NumOps = Op.getNumOperands(); 4641 bool IsMasked = NumOps == 7; 4642 4643 // Convert the vector source to the equivalent nxvXi32 vector. 4644 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4645 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4646 4647 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4648 DAG.getConstant(0, DL, XLenVT)); 4649 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4650 DAG.getConstant(1, DL, XLenVT)); 4651 4652 // Double the VL since we halved SEW. 4653 SDValue AVL = getVLOperand(Op); 4654 SDValue I32VL; 4655 4656 // Optimize for constant AVL 4657 if (isa<ConstantSDNode>(AVL)) { 4658 unsigned EltSize = VT.getScalarSizeInBits(); 4659 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4660 4661 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4662 unsigned MaxVLMAX = 4663 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4664 4665 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4666 unsigned MinVLMAX = 4667 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4668 4669 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4670 if (AVLInt <= MinVLMAX) { 4671 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4672 } else if (AVLInt >= 2 * MaxVLMAX) { 4673 // Just set vl to VLMAX in this situation 4674 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4675 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4676 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4677 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4678 SDValue SETVLMAX = DAG.getTargetConstant( 4679 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4680 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4681 LMUL); 4682 } else { 4683 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4684 // is related to the hardware implementation. 4685 // So let the following code handle 4686 } 4687 } 4688 if (!I32VL) { 4689 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4690 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4691 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4692 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4693 SDValue SETVL = 4694 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4695 // Using vsetvli instruction to get actually used length which related to 4696 // the hardware implementation 4697 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4698 SEW, LMUL); 4699 I32VL = 4700 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4701 } 4702 4703 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4704 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL); 4705 4706 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4707 // instructions. 4708 SDValue Passthru; 4709 if (IsMasked) 4710 Passthru = DAG.getUNDEF(I32VT); 4711 else 4712 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4713 4714 if (IntNo == Intrinsic::riscv_vslide1up || 4715 IntNo == Intrinsic::riscv_vslide1up_mask) { 4716 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4717 ScalarHi, I32Mask, I32VL); 4718 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4719 ScalarLo, I32Mask, I32VL); 4720 } else { 4721 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4722 ScalarLo, I32Mask, I32VL); 4723 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4724 ScalarHi, I32Mask, I32VL); 4725 } 4726 4727 // Convert back to nxvXi64. 4728 Vec = DAG.getBitcast(VT, Vec); 4729 4730 if (!IsMasked) 4731 return Vec; 4732 // Apply mask after the operation. 4733 SDValue Mask = Operands[NumOps - 3]; 4734 SDValue MaskedOff = Operands[1]; 4735 // Assume Policy operand is the last operand. 4736 uint64_t Policy = 4737 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4738 // We don't need to select maskedoff if it's undef. 4739 if (MaskedOff.isUndef()) 4740 return Vec; 4741 // TAMU 4742 if (Policy == RISCVII::TAIL_AGNOSTIC) 4743 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4744 AVL); 4745 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4746 // It's fine because vmerge does not care mask policy. 4747 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4748 AVL); 4749 } 4750 } 4751 4752 // We need to convert the scalar to a splat vector. 4753 // FIXME: Can we implicitly truncate the scalar if it is known to 4754 // be sign extended? 4755 SDValue VL = getVLOperand(Op); 4756 assert(VL.getValueType() == XLenVT); 4757 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4758 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4759 } 4760 4761 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4762 SelectionDAG &DAG) const { 4763 unsigned IntNo = Op.getConstantOperandVal(0); 4764 SDLoc DL(Op); 4765 MVT XLenVT = Subtarget.getXLenVT(); 4766 4767 switch (IntNo) { 4768 default: 4769 break; // Don't custom lower most intrinsics. 4770 case Intrinsic::thread_pointer: { 4771 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4772 return DAG.getRegister(RISCV::X4, PtrVT); 4773 } 4774 case Intrinsic::riscv_orc_b: 4775 case Intrinsic::riscv_brev8: { 4776 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4777 unsigned Opc = 4778 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4779 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4780 DAG.getConstant(7, DL, XLenVT)); 4781 } 4782 case Intrinsic::riscv_grev: 4783 case Intrinsic::riscv_gorc: { 4784 unsigned Opc = 4785 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4786 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4787 } 4788 case Intrinsic::riscv_zip: 4789 case Intrinsic::riscv_unzip: { 4790 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4791 // For i32 the immediate is 15. For i64 the immediate is 31. 4792 unsigned Opc = 4793 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4794 unsigned BitWidth = Op.getValueSizeInBits(); 4795 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4796 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4797 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4798 } 4799 case Intrinsic::riscv_shfl: 4800 case Intrinsic::riscv_unshfl: { 4801 unsigned Opc = 4802 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4803 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4804 } 4805 case Intrinsic::riscv_bcompress: 4806 case Intrinsic::riscv_bdecompress: { 4807 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4808 : RISCVISD::BDECOMPRESS; 4809 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4810 } 4811 case Intrinsic::riscv_bfp: 4812 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4813 Op.getOperand(2)); 4814 case Intrinsic::riscv_fsl: 4815 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4816 Op.getOperand(2), Op.getOperand(3)); 4817 case Intrinsic::riscv_fsr: 4818 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4819 Op.getOperand(2), Op.getOperand(3)); 4820 case Intrinsic::riscv_vmv_x_s: 4821 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4822 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4823 Op.getOperand(1)); 4824 case Intrinsic::riscv_vmv_v_x: 4825 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4826 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4827 Subtarget); 4828 case Intrinsic::riscv_vfmv_v_f: 4829 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4830 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4831 case Intrinsic::riscv_vmv_s_x: { 4832 SDValue Scalar = Op.getOperand(2); 4833 4834 if (Scalar.getValueType().bitsLE(XLenVT)) { 4835 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4836 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4837 Op.getOperand(1), Scalar, Op.getOperand(3)); 4838 } 4839 4840 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4841 4842 // This is an i64 value that lives in two scalar registers. We have to 4843 // insert this in a convoluted way. First we build vXi64 splat containing 4844 // the/ two values that we assemble using some bit math. Next we'll use 4845 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4846 // to merge element 0 from our splat into the source vector. 4847 // FIXME: This is probably not the best way to do this, but it is 4848 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4849 // point. 4850 // sw lo, (a0) 4851 // sw hi, 4(a0) 4852 // vlse vX, (a0) 4853 // 4854 // vid.v vVid 4855 // vmseq.vx mMask, vVid, 0 4856 // vmerge.vvm vDest, vSrc, vVal, mMask 4857 MVT VT = Op.getSimpleValueType(); 4858 SDValue Vec = Op.getOperand(1); 4859 SDValue VL = getVLOperand(Op); 4860 4861 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4862 if (Op.getOperand(1).isUndef()) 4863 return SplattedVal; 4864 SDValue SplattedIdx = 4865 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4866 DAG.getConstant(0, DL, MVT::i32), VL); 4867 4868 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4869 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4870 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4871 SDValue SelectCond = 4872 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4873 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4874 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4875 Vec, VL); 4876 } 4877 } 4878 4879 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4880 } 4881 4882 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4883 SelectionDAG &DAG) const { 4884 unsigned IntNo = Op.getConstantOperandVal(1); 4885 switch (IntNo) { 4886 default: 4887 break; 4888 case Intrinsic::riscv_masked_strided_load: { 4889 SDLoc DL(Op); 4890 MVT XLenVT = Subtarget.getXLenVT(); 4891 4892 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4893 // the selection of the masked intrinsics doesn't do this for us. 4894 SDValue Mask = Op.getOperand(5); 4895 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4896 4897 MVT VT = Op->getSimpleValueType(0); 4898 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4899 4900 SDValue PassThru = Op.getOperand(2); 4901 if (!IsUnmasked) { 4902 MVT MaskVT = 4903 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4904 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4905 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4906 } 4907 4908 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4909 4910 SDValue IntID = DAG.getTargetConstant( 4911 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4912 XLenVT); 4913 4914 auto *Load = cast<MemIntrinsicSDNode>(Op); 4915 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4916 if (IsUnmasked) 4917 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4918 else 4919 Ops.push_back(PassThru); 4920 Ops.push_back(Op.getOperand(3)); // Ptr 4921 Ops.push_back(Op.getOperand(4)); // Stride 4922 if (!IsUnmasked) 4923 Ops.push_back(Mask); 4924 Ops.push_back(VL); 4925 if (!IsUnmasked) { 4926 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4927 Ops.push_back(Policy); 4928 } 4929 4930 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4931 SDValue Result = 4932 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4933 Load->getMemoryVT(), Load->getMemOperand()); 4934 SDValue Chain = Result.getValue(1); 4935 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4936 return DAG.getMergeValues({Result, Chain}, DL); 4937 } 4938 case Intrinsic::riscv_seg2_load: 4939 case Intrinsic::riscv_seg3_load: 4940 case Intrinsic::riscv_seg4_load: 4941 case Intrinsic::riscv_seg5_load: 4942 case Intrinsic::riscv_seg6_load: 4943 case Intrinsic::riscv_seg7_load: 4944 case Intrinsic::riscv_seg8_load: { 4945 SDLoc DL(Op); 4946 static const Intrinsic::ID VlsegInts[7] = { 4947 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4948 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4949 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4950 Intrinsic::riscv_vlseg8}; 4951 unsigned NF = Op->getNumValues() - 1; 4952 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4953 MVT XLenVT = Subtarget.getXLenVT(); 4954 MVT VT = Op->getSimpleValueType(0); 4955 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4956 4957 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4958 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4959 auto *Load = cast<MemIntrinsicSDNode>(Op); 4960 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4961 ContainerVTs.push_back(MVT::Other); 4962 SDVTList VTs = DAG.getVTList(ContainerVTs); 4963 SDValue Result = 4964 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, 4965 {Load->getChain(), IntID, Op.getOperand(2), VL}, 4966 Load->getMemoryVT(), Load->getMemOperand()); 4967 SmallVector<SDValue, 9> Results; 4968 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4969 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4970 DAG, Subtarget)); 4971 Results.push_back(Result.getValue(NF)); 4972 return DAG.getMergeValues(Results, DL); 4973 } 4974 } 4975 4976 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4977 } 4978 4979 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4980 SelectionDAG &DAG) const { 4981 unsigned IntNo = Op.getConstantOperandVal(1); 4982 switch (IntNo) { 4983 default: 4984 break; 4985 case Intrinsic::riscv_masked_strided_store: { 4986 SDLoc DL(Op); 4987 MVT XLenVT = Subtarget.getXLenVT(); 4988 4989 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4990 // the selection of the masked intrinsics doesn't do this for us. 4991 SDValue Mask = Op.getOperand(5); 4992 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4993 4994 SDValue Val = Op.getOperand(2); 4995 MVT VT = Val.getSimpleValueType(); 4996 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4997 4998 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4999 if (!IsUnmasked) { 5000 MVT MaskVT = 5001 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5002 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5003 } 5004 5005 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5006 5007 SDValue IntID = DAG.getTargetConstant( 5008 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5009 XLenVT); 5010 5011 auto *Store = cast<MemIntrinsicSDNode>(Op); 5012 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5013 Ops.push_back(Val); 5014 Ops.push_back(Op.getOperand(3)); // Ptr 5015 Ops.push_back(Op.getOperand(4)); // Stride 5016 if (!IsUnmasked) 5017 Ops.push_back(Mask); 5018 Ops.push_back(VL); 5019 5020 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5021 Ops, Store->getMemoryVT(), 5022 Store->getMemOperand()); 5023 } 5024 } 5025 5026 return SDValue(); 5027 } 5028 5029 static MVT getLMUL1VT(MVT VT) { 5030 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5031 "Unexpected vector MVT"); 5032 return MVT::getScalableVectorVT( 5033 VT.getVectorElementType(), 5034 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5035 } 5036 5037 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5038 switch (ISDOpcode) { 5039 default: 5040 llvm_unreachable("Unhandled reduction"); 5041 case ISD::VECREDUCE_ADD: 5042 return RISCVISD::VECREDUCE_ADD_VL; 5043 case ISD::VECREDUCE_UMAX: 5044 return RISCVISD::VECREDUCE_UMAX_VL; 5045 case ISD::VECREDUCE_SMAX: 5046 return RISCVISD::VECREDUCE_SMAX_VL; 5047 case ISD::VECREDUCE_UMIN: 5048 return RISCVISD::VECREDUCE_UMIN_VL; 5049 case ISD::VECREDUCE_SMIN: 5050 return RISCVISD::VECREDUCE_SMIN_VL; 5051 case ISD::VECREDUCE_AND: 5052 return RISCVISD::VECREDUCE_AND_VL; 5053 case ISD::VECREDUCE_OR: 5054 return RISCVISD::VECREDUCE_OR_VL; 5055 case ISD::VECREDUCE_XOR: 5056 return RISCVISD::VECREDUCE_XOR_VL; 5057 } 5058 } 5059 5060 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5061 SelectionDAG &DAG, 5062 bool IsVP) const { 5063 SDLoc DL(Op); 5064 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5065 MVT VecVT = Vec.getSimpleValueType(); 5066 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5067 Op.getOpcode() == ISD::VECREDUCE_OR || 5068 Op.getOpcode() == ISD::VECREDUCE_XOR || 5069 Op.getOpcode() == ISD::VP_REDUCE_AND || 5070 Op.getOpcode() == ISD::VP_REDUCE_OR || 5071 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5072 "Unexpected reduction lowering"); 5073 5074 MVT XLenVT = Subtarget.getXLenVT(); 5075 assert(Op.getValueType() == XLenVT && 5076 "Expected reduction output to be legalized to XLenVT"); 5077 5078 MVT ContainerVT = VecVT; 5079 if (VecVT.isFixedLengthVector()) { 5080 ContainerVT = getContainerForFixedLengthVector(VecVT); 5081 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5082 } 5083 5084 SDValue Mask, VL; 5085 if (IsVP) { 5086 Mask = Op.getOperand(2); 5087 VL = Op.getOperand(3); 5088 } else { 5089 std::tie(Mask, VL) = 5090 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5091 } 5092 5093 unsigned BaseOpc; 5094 ISD::CondCode CC; 5095 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5096 5097 switch (Op.getOpcode()) { 5098 default: 5099 llvm_unreachable("Unhandled reduction"); 5100 case ISD::VECREDUCE_AND: 5101 case ISD::VP_REDUCE_AND: { 5102 // vcpop ~x == 0 5103 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5104 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5105 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5106 CC = ISD::SETEQ; 5107 BaseOpc = ISD::AND; 5108 break; 5109 } 5110 case ISD::VECREDUCE_OR: 5111 case ISD::VP_REDUCE_OR: 5112 // vcpop x != 0 5113 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5114 CC = ISD::SETNE; 5115 BaseOpc = ISD::OR; 5116 break; 5117 case ISD::VECREDUCE_XOR: 5118 case ISD::VP_REDUCE_XOR: { 5119 // ((vcpop x) & 1) != 0 5120 SDValue One = DAG.getConstant(1, DL, XLenVT); 5121 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5122 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5123 CC = ISD::SETNE; 5124 BaseOpc = ISD::XOR; 5125 break; 5126 } 5127 } 5128 5129 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5130 5131 if (!IsVP) 5132 return SetCC; 5133 5134 // Now include the start value in the operation. 5135 // Note that we must return the start value when no elements are operated 5136 // upon. The vcpop instructions we've emitted in each case above will return 5137 // 0 for an inactive vector, and so we've already received the neutral value: 5138 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5139 // can simply include the start value. 5140 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5141 } 5142 5143 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5144 SelectionDAG &DAG) const { 5145 SDLoc DL(Op); 5146 SDValue Vec = Op.getOperand(0); 5147 EVT VecEVT = Vec.getValueType(); 5148 5149 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5150 5151 // Due to ordering in legalize types we may have a vector type that needs to 5152 // be split. Do that manually so we can get down to a legal type. 5153 while (getTypeAction(*DAG.getContext(), VecEVT) == 5154 TargetLowering::TypeSplitVector) { 5155 SDValue Lo, Hi; 5156 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5157 VecEVT = Lo.getValueType(); 5158 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5159 } 5160 5161 // TODO: The type may need to be widened rather than split. Or widened before 5162 // it can be split. 5163 if (!isTypeLegal(VecEVT)) 5164 return SDValue(); 5165 5166 MVT VecVT = VecEVT.getSimpleVT(); 5167 MVT VecEltVT = VecVT.getVectorElementType(); 5168 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5169 5170 MVT ContainerVT = VecVT; 5171 if (VecVT.isFixedLengthVector()) { 5172 ContainerVT = getContainerForFixedLengthVector(VecVT); 5173 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5174 } 5175 5176 MVT M1VT = getLMUL1VT(ContainerVT); 5177 MVT XLenVT = Subtarget.getXLenVT(); 5178 5179 SDValue Mask, VL; 5180 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5181 5182 SDValue NeutralElem = 5183 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5184 SDValue IdentitySplat = 5185 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5186 M1VT, DL, DAG, Subtarget); 5187 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5188 IdentitySplat, Mask, VL); 5189 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5190 DAG.getConstant(0, DL, XLenVT)); 5191 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5192 } 5193 5194 // Given a reduction op, this function returns the matching reduction opcode, 5195 // the vector SDValue and the scalar SDValue required to lower this to a 5196 // RISCVISD node. 5197 static std::tuple<unsigned, SDValue, SDValue> 5198 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5199 SDLoc DL(Op); 5200 auto Flags = Op->getFlags(); 5201 unsigned Opcode = Op.getOpcode(); 5202 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5203 switch (Opcode) { 5204 default: 5205 llvm_unreachable("Unhandled reduction"); 5206 case ISD::VECREDUCE_FADD: { 5207 // Use positive zero if we can. It is cheaper to materialize. 5208 SDValue Zero = 5209 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5210 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5211 } 5212 case ISD::VECREDUCE_SEQ_FADD: 5213 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5214 Op.getOperand(0)); 5215 case ISD::VECREDUCE_FMIN: 5216 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5217 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5218 case ISD::VECREDUCE_FMAX: 5219 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5220 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5221 } 5222 } 5223 5224 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5225 SelectionDAG &DAG) const { 5226 SDLoc DL(Op); 5227 MVT VecEltVT = Op.getSimpleValueType(); 5228 5229 unsigned RVVOpcode; 5230 SDValue VectorVal, ScalarVal; 5231 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5232 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5233 MVT VecVT = VectorVal.getSimpleValueType(); 5234 5235 MVT ContainerVT = VecVT; 5236 if (VecVT.isFixedLengthVector()) { 5237 ContainerVT = getContainerForFixedLengthVector(VecVT); 5238 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5239 } 5240 5241 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5242 MVT XLenVT = Subtarget.getXLenVT(); 5243 5244 SDValue Mask, VL; 5245 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5246 5247 SDValue ScalarSplat = 5248 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5249 M1VT, DL, DAG, Subtarget); 5250 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5251 VectorVal, ScalarSplat, Mask, VL); 5252 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5253 DAG.getConstant(0, DL, XLenVT)); 5254 } 5255 5256 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5257 switch (ISDOpcode) { 5258 default: 5259 llvm_unreachable("Unhandled reduction"); 5260 case ISD::VP_REDUCE_ADD: 5261 return RISCVISD::VECREDUCE_ADD_VL; 5262 case ISD::VP_REDUCE_UMAX: 5263 return RISCVISD::VECREDUCE_UMAX_VL; 5264 case ISD::VP_REDUCE_SMAX: 5265 return RISCVISD::VECREDUCE_SMAX_VL; 5266 case ISD::VP_REDUCE_UMIN: 5267 return RISCVISD::VECREDUCE_UMIN_VL; 5268 case ISD::VP_REDUCE_SMIN: 5269 return RISCVISD::VECREDUCE_SMIN_VL; 5270 case ISD::VP_REDUCE_AND: 5271 return RISCVISD::VECREDUCE_AND_VL; 5272 case ISD::VP_REDUCE_OR: 5273 return RISCVISD::VECREDUCE_OR_VL; 5274 case ISD::VP_REDUCE_XOR: 5275 return RISCVISD::VECREDUCE_XOR_VL; 5276 case ISD::VP_REDUCE_FADD: 5277 return RISCVISD::VECREDUCE_FADD_VL; 5278 case ISD::VP_REDUCE_SEQ_FADD: 5279 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5280 case ISD::VP_REDUCE_FMAX: 5281 return RISCVISD::VECREDUCE_FMAX_VL; 5282 case ISD::VP_REDUCE_FMIN: 5283 return RISCVISD::VECREDUCE_FMIN_VL; 5284 } 5285 } 5286 5287 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5288 SelectionDAG &DAG) const { 5289 SDLoc DL(Op); 5290 SDValue Vec = Op.getOperand(1); 5291 EVT VecEVT = Vec.getValueType(); 5292 5293 // TODO: The type may need to be widened rather than split. Or widened before 5294 // it can be split. 5295 if (!isTypeLegal(VecEVT)) 5296 return SDValue(); 5297 5298 MVT VecVT = VecEVT.getSimpleVT(); 5299 MVT VecEltVT = VecVT.getVectorElementType(); 5300 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5301 5302 MVT ContainerVT = VecVT; 5303 if (VecVT.isFixedLengthVector()) { 5304 ContainerVT = getContainerForFixedLengthVector(VecVT); 5305 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5306 } 5307 5308 SDValue VL = Op.getOperand(3); 5309 SDValue Mask = Op.getOperand(2); 5310 5311 MVT M1VT = getLMUL1VT(ContainerVT); 5312 MVT XLenVT = Subtarget.getXLenVT(); 5313 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5314 5315 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5316 DAG.getConstant(1, DL, XLenVT), M1VT, 5317 DL, DAG, Subtarget); 5318 SDValue Reduction = 5319 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5320 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5321 DAG.getConstant(0, DL, XLenVT)); 5322 if (!VecVT.isInteger()) 5323 return Elt0; 5324 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5325 } 5326 5327 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5328 SelectionDAG &DAG) const { 5329 SDValue Vec = Op.getOperand(0); 5330 SDValue SubVec = Op.getOperand(1); 5331 MVT VecVT = Vec.getSimpleValueType(); 5332 MVT SubVecVT = SubVec.getSimpleValueType(); 5333 5334 SDLoc DL(Op); 5335 MVT XLenVT = Subtarget.getXLenVT(); 5336 unsigned OrigIdx = Op.getConstantOperandVal(2); 5337 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5338 5339 // We don't have the ability to slide mask vectors up indexed by their i1 5340 // elements; the smallest we can do is i8. Often we are able to bitcast to 5341 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5342 // into a scalable one, we might not necessarily have enough scalable 5343 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5344 if (SubVecVT.getVectorElementType() == MVT::i1 && 5345 (OrigIdx != 0 || !Vec.isUndef())) { 5346 if (VecVT.getVectorMinNumElements() >= 8 && 5347 SubVecVT.getVectorMinNumElements() >= 8) { 5348 assert(OrigIdx % 8 == 0 && "Invalid index"); 5349 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5350 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5351 "Unexpected mask vector lowering"); 5352 OrigIdx /= 8; 5353 SubVecVT = 5354 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5355 SubVecVT.isScalableVector()); 5356 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5357 VecVT.isScalableVector()); 5358 Vec = DAG.getBitcast(VecVT, Vec); 5359 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5360 } else { 5361 // We can't slide this mask vector up indexed by its i1 elements. 5362 // This poses a problem when we wish to insert a scalable vector which 5363 // can't be re-expressed as a larger type. Just choose the slow path and 5364 // extend to a larger type, then truncate back down. 5365 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5366 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5367 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5368 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5369 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5370 Op.getOperand(2)); 5371 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5372 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5373 } 5374 } 5375 5376 // If the subvector vector is a fixed-length type, we cannot use subregister 5377 // manipulation to simplify the codegen; we don't know which register of a 5378 // LMUL group contains the specific subvector as we only know the minimum 5379 // register size. Therefore we must slide the vector group up the full 5380 // amount. 5381 if (SubVecVT.isFixedLengthVector()) { 5382 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5383 return Op; 5384 MVT ContainerVT = VecVT; 5385 if (VecVT.isFixedLengthVector()) { 5386 ContainerVT = getContainerForFixedLengthVector(VecVT); 5387 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5388 } 5389 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5390 DAG.getUNDEF(ContainerVT), SubVec, 5391 DAG.getConstant(0, DL, XLenVT)); 5392 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5393 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5394 return DAG.getBitcast(Op.getValueType(), SubVec); 5395 } 5396 SDValue Mask = 5397 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5398 // Set the vector length to only the number of elements we care about. Note 5399 // that for slideup this includes the offset. 5400 SDValue VL = 5401 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5402 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5403 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5404 SubVec, SlideupAmt, Mask, VL); 5405 if (VecVT.isFixedLengthVector()) 5406 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5407 return DAG.getBitcast(Op.getValueType(), Slideup); 5408 } 5409 5410 unsigned SubRegIdx, RemIdx; 5411 std::tie(SubRegIdx, RemIdx) = 5412 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5413 VecVT, SubVecVT, OrigIdx, TRI); 5414 5415 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5416 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5417 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5418 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5419 5420 // 1. If the Idx has been completely eliminated and this subvector's size is 5421 // a vector register or a multiple thereof, or the surrounding elements are 5422 // undef, then this is a subvector insert which naturally aligns to a vector 5423 // register. These can easily be handled using subregister manipulation. 5424 // 2. If the subvector is smaller than a vector register, then the insertion 5425 // must preserve the undisturbed elements of the register. We do this by 5426 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5427 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5428 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5429 // LMUL=1 type back into the larger vector (resolving to another subregister 5430 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5431 // to avoid allocating a large register group to hold our subvector. 5432 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5433 return Op; 5434 5435 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5436 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5437 // (in our case undisturbed). This means we can set up a subvector insertion 5438 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5439 // size of the subvector. 5440 MVT InterSubVT = VecVT; 5441 SDValue AlignedExtract = Vec; 5442 unsigned AlignedIdx = OrigIdx - RemIdx; 5443 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5444 InterSubVT = getLMUL1VT(VecVT); 5445 // Extract a subvector equal to the nearest full vector register type. This 5446 // should resolve to a EXTRACT_SUBREG instruction. 5447 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5448 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5449 } 5450 5451 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5452 // For scalable vectors this must be further multiplied by vscale. 5453 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5454 5455 SDValue Mask, VL; 5456 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5457 5458 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5459 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5460 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5461 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5462 5463 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5464 DAG.getUNDEF(InterSubVT), SubVec, 5465 DAG.getConstant(0, DL, XLenVT)); 5466 5467 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5468 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5469 5470 // If required, insert this subvector back into the correct vector register. 5471 // This should resolve to an INSERT_SUBREG instruction. 5472 if (VecVT.bitsGT(InterSubVT)) 5473 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5474 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5475 5476 // We might have bitcast from a mask type: cast back to the original type if 5477 // required. 5478 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5479 } 5480 5481 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5482 SelectionDAG &DAG) const { 5483 SDValue Vec = Op.getOperand(0); 5484 MVT SubVecVT = Op.getSimpleValueType(); 5485 MVT VecVT = Vec.getSimpleValueType(); 5486 5487 SDLoc DL(Op); 5488 MVT XLenVT = Subtarget.getXLenVT(); 5489 unsigned OrigIdx = Op.getConstantOperandVal(1); 5490 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5491 5492 // We don't have the ability to slide mask vectors down indexed by their i1 5493 // elements; the smallest we can do is i8. Often we are able to bitcast to 5494 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5495 // from a scalable one, we might not necessarily have enough scalable 5496 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5497 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5498 if (VecVT.getVectorMinNumElements() >= 8 && 5499 SubVecVT.getVectorMinNumElements() >= 8) { 5500 assert(OrigIdx % 8 == 0 && "Invalid index"); 5501 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5502 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5503 "Unexpected mask vector lowering"); 5504 OrigIdx /= 8; 5505 SubVecVT = 5506 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5507 SubVecVT.isScalableVector()); 5508 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5509 VecVT.isScalableVector()); 5510 Vec = DAG.getBitcast(VecVT, Vec); 5511 } else { 5512 // We can't slide this mask vector down, indexed by its i1 elements. 5513 // This poses a problem when we wish to extract a scalable vector which 5514 // can't be re-expressed as a larger type. Just choose the slow path and 5515 // extend to a larger type, then truncate back down. 5516 // TODO: We could probably improve this when extracting certain fixed 5517 // from fixed, where we can extract as i8 and shift the correct element 5518 // right to reach the desired subvector? 5519 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5520 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5521 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5522 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5523 Op.getOperand(1)); 5524 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5525 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5526 } 5527 } 5528 5529 // If the subvector vector is a fixed-length type, we cannot use subregister 5530 // manipulation to simplify the codegen; we don't know which register of a 5531 // LMUL group contains the specific subvector as we only know the minimum 5532 // register size. Therefore we must slide the vector group down the full 5533 // amount. 5534 if (SubVecVT.isFixedLengthVector()) { 5535 // With an index of 0 this is a cast-like subvector, which can be performed 5536 // with subregister operations. 5537 if (OrigIdx == 0) 5538 return Op; 5539 MVT ContainerVT = VecVT; 5540 if (VecVT.isFixedLengthVector()) { 5541 ContainerVT = getContainerForFixedLengthVector(VecVT); 5542 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5543 } 5544 SDValue Mask = 5545 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5546 // Set the vector length to only the number of elements we care about. This 5547 // avoids sliding down elements we're going to discard straight away. 5548 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5549 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5550 SDValue Slidedown = 5551 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5552 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5553 // Now we can use a cast-like subvector extract to get the result. 5554 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5555 DAG.getConstant(0, DL, XLenVT)); 5556 return DAG.getBitcast(Op.getValueType(), Slidedown); 5557 } 5558 5559 unsigned SubRegIdx, RemIdx; 5560 std::tie(SubRegIdx, RemIdx) = 5561 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5562 VecVT, SubVecVT, OrigIdx, TRI); 5563 5564 // If the Idx has been completely eliminated then this is a subvector extract 5565 // which naturally aligns to a vector register. These can easily be handled 5566 // using subregister manipulation. 5567 if (RemIdx == 0) 5568 return Op; 5569 5570 // Else we must shift our vector register directly to extract the subvector. 5571 // Do this using VSLIDEDOWN. 5572 5573 // If the vector type is an LMUL-group type, extract a subvector equal to the 5574 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5575 // instruction. 5576 MVT InterSubVT = VecVT; 5577 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5578 InterSubVT = getLMUL1VT(VecVT); 5579 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5580 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5581 } 5582 5583 // Slide this vector register down by the desired number of elements in order 5584 // to place the desired subvector starting at element 0. 5585 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5586 // For scalable vectors this must be further multiplied by vscale. 5587 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5588 5589 SDValue Mask, VL; 5590 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5591 SDValue Slidedown = 5592 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5593 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5594 5595 // Now the vector is in the right position, extract our final subvector. This 5596 // should resolve to a COPY. 5597 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5598 DAG.getConstant(0, DL, XLenVT)); 5599 5600 // We might have bitcast from a mask type: cast back to the original type if 5601 // required. 5602 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5603 } 5604 5605 // Lower step_vector to the vid instruction. Any non-identity step value must 5606 // be accounted for my manual expansion. 5607 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5608 SelectionDAG &DAG) const { 5609 SDLoc DL(Op); 5610 MVT VT = Op.getSimpleValueType(); 5611 MVT XLenVT = Subtarget.getXLenVT(); 5612 SDValue Mask, VL; 5613 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5614 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5615 uint64_t StepValImm = Op.getConstantOperandVal(0); 5616 if (StepValImm != 1) { 5617 if (isPowerOf2_64(StepValImm)) { 5618 SDValue StepVal = 5619 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5620 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5621 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5622 } else { 5623 SDValue StepVal = lowerScalarSplat( 5624 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5625 VL, VT, DL, DAG, Subtarget); 5626 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5627 } 5628 } 5629 return StepVec; 5630 } 5631 5632 // Implement vector_reverse using vrgather.vv with indices determined by 5633 // subtracting the id of each element from (VLMAX-1). This will convert 5634 // the indices like so: 5635 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5636 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5637 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5638 SelectionDAG &DAG) const { 5639 SDLoc DL(Op); 5640 MVT VecVT = Op.getSimpleValueType(); 5641 unsigned EltSize = VecVT.getScalarSizeInBits(); 5642 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5643 5644 unsigned MaxVLMAX = 0; 5645 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5646 if (VectorBitsMax != 0) 5647 MaxVLMAX = 5648 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5649 5650 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5651 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5652 5653 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5654 // to use vrgatherei16.vv. 5655 // TODO: It's also possible to use vrgatherei16.vv for other types to 5656 // decrease register width for the index calculation. 5657 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5658 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5659 // Reverse each half, then reassemble them in reverse order. 5660 // NOTE: It's also possible that after splitting that VLMAX no longer 5661 // requires vrgatherei16.vv. 5662 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5663 SDValue Lo, Hi; 5664 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5665 EVT LoVT, HiVT; 5666 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5667 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5668 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5669 // Reassemble the low and high pieces reversed. 5670 // FIXME: This is a CONCAT_VECTORS. 5671 SDValue Res = 5672 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5673 DAG.getIntPtrConstant(0, DL)); 5674 return DAG.getNode( 5675 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5676 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5677 } 5678 5679 // Just promote the int type to i16 which will double the LMUL. 5680 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5681 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5682 } 5683 5684 MVT XLenVT = Subtarget.getXLenVT(); 5685 SDValue Mask, VL; 5686 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5687 5688 // Calculate VLMAX-1 for the desired SEW. 5689 unsigned MinElts = VecVT.getVectorMinNumElements(); 5690 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5691 DAG.getConstant(MinElts, DL, XLenVT)); 5692 SDValue VLMinus1 = 5693 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5694 5695 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5696 bool IsRV32E64 = 5697 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5698 SDValue SplatVL; 5699 if (!IsRV32E64) 5700 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5701 else 5702 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5703 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5704 5705 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5706 SDValue Indices = 5707 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5708 5709 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5710 } 5711 5712 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5713 SelectionDAG &DAG) const { 5714 SDLoc DL(Op); 5715 SDValue V1 = Op.getOperand(0); 5716 SDValue V2 = Op.getOperand(1); 5717 MVT XLenVT = Subtarget.getXLenVT(); 5718 MVT VecVT = Op.getSimpleValueType(); 5719 5720 unsigned MinElts = VecVT.getVectorMinNumElements(); 5721 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5722 DAG.getConstant(MinElts, DL, XLenVT)); 5723 5724 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5725 SDValue DownOffset, UpOffset; 5726 if (ImmValue >= 0) { 5727 // The operand is a TargetConstant, we need to rebuild it as a regular 5728 // constant. 5729 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5730 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5731 } else { 5732 // The operand is a TargetConstant, we need to rebuild it as a regular 5733 // constant rather than negating the original operand. 5734 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5735 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5736 } 5737 5738 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5739 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax); 5740 5741 SDValue SlideDown = 5742 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5743 DownOffset, TrueMask, UpOffset); 5744 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5745 TrueMask, 5746 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5747 } 5748 5749 SDValue 5750 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5751 SelectionDAG &DAG) const { 5752 SDLoc DL(Op); 5753 auto *Load = cast<LoadSDNode>(Op); 5754 5755 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5756 Load->getMemoryVT(), 5757 *Load->getMemOperand()) && 5758 "Expecting a correctly-aligned load"); 5759 5760 MVT VT = Op.getSimpleValueType(); 5761 MVT XLenVT = Subtarget.getXLenVT(); 5762 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5763 5764 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5765 5766 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5767 SDValue IntID = DAG.getTargetConstant( 5768 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5769 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5770 if (!IsMaskOp) 5771 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5772 Ops.push_back(Load->getBasePtr()); 5773 Ops.push_back(VL); 5774 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5775 SDValue NewLoad = 5776 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5777 Load->getMemoryVT(), Load->getMemOperand()); 5778 5779 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5780 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5781 } 5782 5783 SDValue 5784 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5785 SelectionDAG &DAG) const { 5786 SDLoc DL(Op); 5787 auto *Store = cast<StoreSDNode>(Op); 5788 5789 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5790 Store->getMemoryVT(), 5791 *Store->getMemOperand()) && 5792 "Expecting a correctly-aligned store"); 5793 5794 SDValue StoreVal = Store->getValue(); 5795 MVT VT = StoreVal.getSimpleValueType(); 5796 MVT XLenVT = Subtarget.getXLenVT(); 5797 5798 // If the size less than a byte, we need to pad with zeros to make a byte. 5799 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5800 VT = MVT::v8i1; 5801 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5802 DAG.getConstant(0, DL, VT), StoreVal, 5803 DAG.getIntPtrConstant(0, DL)); 5804 } 5805 5806 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5807 5808 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5809 5810 SDValue NewValue = 5811 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5812 5813 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5814 SDValue IntID = DAG.getTargetConstant( 5815 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5816 return DAG.getMemIntrinsicNode( 5817 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5818 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5819 Store->getMemoryVT(), Store->getMemOperand()); 5820 } 5821 5822 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5823 SelectionDAG &DAG) const { 5824 SDLoc DL(Op); 5825 MVT VT = Op.getSimpleValueType(); 5826 5827 const auto *MemSD = cast<MemSDNode>(Op); 5828 EVT MemVT = MemSD->getMemoryVT(); 5829 MachineMemOperand *MMO = MemSD->getMemOperand(); 5830 SDValue Chain = MemSD->getChain(); 5831 SDValue BasePtr = MemSD->getBasePtr(); 5832 5833 SDValue Mask, PassThru, VL; 5834 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5835 Mask = VPLoad->getMask(); 5836 PassThru = DAG.getUNDEF(VT); 5837 VL = VPLoad->getVectorLength(); 5838 } else { 5839 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5840 Mask = MLoad->getMask(); 5841 PassThru = MLoad->getPassThru(); 5842 } 5843 5844 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5845 5846 MVT XLenVT = Subtarget.getXLenVT(); 5847 5848 MVT ContainerVT = VT; 5849 if (VT.isFixedLengthVector()) { 5850 ContainerVT = getContainerForFixedLengthVector(VT); 5851 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5852 if (!IsUnmasked) { 5853 MVT MaskVT = 5854 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5855 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5856 } 5857 } 5858 5859 if (!VL) 5860 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5861 5862 unsigned IntID = 5863 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5864 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5865 if (IsUnmasked) 5866 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5867 else 5868 Ops.push_back(PassThru); 5869 Ops.push_back(BasePtr); 5870 if (!IsUnmasked) 5871 Ops.push_back(Mask); 5872 Ops.push_back(VL); 5873 if (!IsUnmasked) 5874 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5875 5876 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5877 5878 SDValue Result = 5879 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5880 Chain = Result.getValue(1); 5881 5882 if (VT.isFixedLengthVector()) 5883 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5884 5885 return DAG.getMergeValues({Result, Chain}, DL); 5886 } 5887 5888 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5889 SelectionDAG &DAG) const { 5890 SDLoc DL(Op); 5891 5892 const auto *MemSD = cast<MemSDNode>(Op); 5893 EVT MemVT = MemSD->getMemoryVT(); 5894 MachineMemOperand *MMO = MemSD->getMemOperand(); 5895 SDValue Chain = MemSD->getChain(); 5896 SDValue BasePtr = MemSD->getBasePtr(); 5897 SDValue Val, Mask, VL; 5898 5899 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5900 Val = VPStore->getValue(); 5901 Mask = VPStore->getMask(); 5902 VL = VPStore->getVectorLength(); 5903 } else { 5904 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5905 Val = MStore->getValue(); 5906 Mask = MStore->getMask(); 5907 } 5908 5909 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5910 5911 MVT VT = Val.getSimpleValueType(); 5912 MVT XLenVT = Subtarget.getXLenVT(); 5913 5914 MVT ContainerVT = VT; 5915 if (VT.isFixedLengthVector()) { 5916 ContainerVT = getContainerForFixedLengthVector(VT); 5917 5918 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5919 if (!IsUnmasked) { 5920 MVT MaskVT = 5921 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5922 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5923 } 5924 } 5925 5926 if (!VL) 5927 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5928 5929 unsigned IntID = 5930 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5931 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5932 Ops.push_back(Val); 5933 Ops.push_back(BasePtr); 5934 if (!IsUnmasked) 5935 Ops.push_back(Mask); 5936 Ops.push_back(VL); 5937 5938 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5939 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5940 } 5941 5942 SDValue 5943 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5944 SelectionDAG &DAG) const { 5945 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5946 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5947 5948 MVT VT = Op.getSimpleValueType(); 5949 5950 SDValue Op1 = 5951 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5952 SDValue Op2 = 5953 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5954 5955 SDLoc DL(Op); 5956 SDValue VL = 5957 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5958 5959 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5960 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5961 5962 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5963 Op.getOperand(2), Mask, VL); 5964 5965 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5966 } 5967 5968 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5969 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5970 MVT VT = Op.getSimpleValueType(); 5971 5972 if (VT.getVectorElementType() == MVT::i1) 5973 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5974 5975 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5976 } 5977 5978 SDValue 5979 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5980 SelectionDAG &DAG) const { 5981 unsigned Opc; 5982 switch (Op.getOpcode()) { 5983 default: llvm_unreachable("Unexpected opcode!"); 5984 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5985 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5986 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5987 } 5988 5989 return lowerToScalableOp(Op, DAG, Opc); 5990 } 5991 5992 // Lower vector ABS to smax(X, sub(0, X)). 5993 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5994 SDLoc DL(Op); 5995 MVT VT = Op.getSimpleValueType(); 5996 SDValue X = Op.getOperand(0); 5997 5998 assert(VT.isFixedLengthVector() && "Unexpected type"); 5999 6000 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6001 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6002 6003 SDValue Mask, VL; 6004 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6005 6006 SDValue SplatZero = DAG.getNode( 6007 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6008 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6009 SDValue NegX = 6010 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6011 SDValue Max = 6012 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6013 6014 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6015 } 6016 6017 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6018 SDValue Op, SelectionDAG &DAG) const { 6019 SDLoc DL(Op); 6020 MVT VT = Op.getSimpleValueType(); 6021 SDValue Mag = Op.getOperand(0); 6022 SDValue Sign = Op.getOperand(1); 6023 assert(Mag.getValueType() == Sign.getValueType() && 6024 "Can only handle COPYSIGN with matching types."); 6025 6026 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6027 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6028 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6029 6030 SDValue Mask, VL; 6031 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6032 6033 SDValue CopySign = 6034 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6035 6036 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6037 } 6038 6039 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6040 SDValue Op, SelectionDAG &DAG) const { 6041 MVT VT = Op.getSimpleValueType(); 6042 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6043 6044 MVT I1ContainerVT = 6045 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6046 6047 SDValue CC = 6048 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6049 SDValue Op1 = 6050 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6051 SDValue Op2 = 6052 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6053 6054 SDLoc DL(Op); 6055 SDValue Mask, VL; 6056 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6057 6058 SDValue Select = 6059 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6060 6061 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6062 } 6063 6064 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6065 unsigned NewOpc, 6066 bool HasMask) const { 6067 MVT VT = Op.getSimpleValueType(); 6068 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6069 6070 // Create list of operands by converting existing ones to scalable types. 6071 SmallVector<SDValue, 6> Ops; 6072 for (const SDValue &V : Op->op_values()) { 6073 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6074 6075 // Pass through non-vector operands. 6076 if (!V.getValueType().isVector()) { 6077 Ops.push_back(V); 6078 continue; 6079 } 6080 6081 // "cast" fixed length vector to a scalable vector. 6082 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6083 "Only fixed length vectors are supported!"); 6084 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6085 } 6086 6087 SDLoc DL(Op); 6088 SDValue Mask, VL; 6089 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6090 if (HasMask) 6091 Ops.push_back(Mask); 6092 Ops.push_back(VL); 6093 6094 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6095 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6096 } 6097 6098 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6099 // * Operands of each node are assumed to be in the same order. 6100 // * The EVL operand is promoted from i32 to i64 on RV64. 6101 // * Fixed-length vectors are converted to their scalable-vector container 6102 // types. 6103 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6104 unsigned RISCVISDOpc) const { 6105 SDLoc DL(Op); 6106 MVT VT = Op.getSimpleValueType(); 6107 SmallVector<SDValue, 4> Ops; 6108 6109 for (const auto &OpIdx : enumerate(Op->ops())) { 6110 SDValue V = OpIdx.value(); 6111 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6112 // Pass through operands which aren't fixed-length vectors. 6113 if (!V.getValueType().isFixedLengthVector()) { 6114 Ops.push_back(V); 6115 continue; 6116 } 6117 // "cast" fixed length vector to a scalable vector. 6118 MVT OpVT = V.getSimpleValueType(); 6119 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6120 assert(useRVVForFixedLengthVectorVT(OpVT) && 6121 "Only fixed length vectors are supported!"); 6122 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6123 } 6124 6125 if (!VT.isFixedLengthVector()) 6126 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6127 6128 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6129 6130 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6131 6132 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6133 } 6134 6135 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6136 unsigned MaskOpc, 6137 unsigned VecOpc) const { 6138 MVT VT = Op.getSimpleValueType(); 6139 if (VT.getVectorElementType() != MVT::i1) 6140 return lowerVPOp(Op, DAG, VecOpc); 6141 6142 // It is safe to drop mask parameter as masked-off elements are undef. 6143 SDValue Op1 = Op->getOperand(0); 6144 SDValue Op2 = Op->getOperand(1); 6145 SDValue VL = Op->getOperand(3); 6146 6147 MVT ContainerVT = VT; 6148 const bool IsFixed = VT.isFixedLengthVector(); 6149 if (IsFixed) { 6150 ContainerVT = getContainerForFixedLengthVector(VT); 6151 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6152 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6153 } 6154 6155 SDLoc DL(Op); 6156 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6157 if (!IsFixed) 6158 return Val; 6159 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6160 } 6161 6162 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6163 // matched to a RVV indexed load. The RVV indexed load instructions only 6164 // support the "unsigned unscaled" addressing mode; indices are implicitly 6165 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6166 // signed or scaled indexing is extended to the XLEN value type and scaled 6167 // accordingly. 6168 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6169 SelectionDAG &DAG) const { 6170 SDLoc DL(Op); 6171 MVT VT = Op.getSimpleValueType(); 6172 6173 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6174 EVT MemVT = MemSD->getMemoryVT(); 6175 MachineMemOperand *MMO = MemSD->getMemOperand(); 6176 SDValue Chain = MemSD->getChain(); 6177 SDValue BasePtr = MemSD->getBasePtr(); 6178 6179 ISD::LoadExtType LoadExtType; 6180 SDValue Index, Mask, PassThru, VL; 6181 6182 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6183 Index = VPGN->getIndex(); 6184 Mask = VPGN->getMask(); 6185 PassThru = DAG.getUNDEF(VT); 6186 VL = VPGN->getVectorLength(); 6187 // VP doesn't support extending loads. 6188 LoadExtType = ISD::NON_EXTLOAD; 6189 } else { 6190 // Else it must be a MGATHER. 6191 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6192 Index = MGN->getIndex(); 6193 Mask = MGN->getMask(); 6194 PassThru = MGN->getPassThru(); 6195 LoadExtType = MGN->getExtensionType(); 6196 } 6197 6198 MVT IndexVT = Index.getSimpleValueType(); 6199 MVT XLenVT = Subtarget.getXLenVT(); 6200 6201 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6202 "Unexpected VTs!"); 6203 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6204 // Targets have to explicitly opt-in for extending vector loads. 6205 assert(LoadExtType == ISD::NON_EXTLOAD && 6206 "Unexpected extending MGATHER/VP_GATHER"); 6207 (void)LoadExtType; 6208 6209 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6210 // the selection of the masked intrinsics doesn't do this for us. 6211 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6212 6213 MVT ContainerVT = VT; 6214 if (VT.isFixedLengthVector()) { 6215 // We need to use the larger of the result and index type to determine the 6216 // scalable type to use so we don't increase LMUL for any operand/result. 6217 if (VT.bitsGE(IndexVT)) { 6218 ContainerVT = getContainerForFixedLengthVector(VT); 6219 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6220 ContainerVT.getVectorElementCount()); 6221 } else { 6222 IndexVT = getContainerForFixedLengthVector(IndexVT); 6223 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6224 IndexVT.getVectorElementCount()); 6225 } 6226 6227 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6228 6229 if (!IsUnmasked) { 6230 MVT MaskVT = 6231 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6232 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6233 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6234 } 6235 } 6236 6237 if (!VL) 6238 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6239 6240 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6241 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6242 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6243 VL); 6244 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6245 TrueMask, VL); 6246 } 6247 6248 unsigned IntID = 6249 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6250 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6251 if (IsUnmasked) 6252 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6253 else 6254 Ops.push_back(PassThru); 6255 Ops.push_back(BasePtr); 6256 Ops.push_back(Index); 6257 if (!IsUnmasked) 6258 Ops.push_back(Mask); 6259 Ops.push_back(VL); 6260 if (!IsUnmasked) 6261 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6262 6263 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6264 SDValue Result = 6265 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6266 Chain = Result.getValue(1); 6267 6268 if (VT.isFixedLengthVector()) 6269 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6270 6271 return DAG.getMergeValues({Result, Chain}, DL); 6272 } 6273 6274 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6275 // matched to a RVV indexed store. The RVV indexed store instructions only 6276 // support the "unsigned unscaled" addressing mode; indices are implicitly 6277 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6278 // signed or scaled indexing is extended to the XLEN value type and scaled 6279 // accordingly. 6280 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6281 SelectionDAG &DAG) const { 6282 SDLoc DL(Op); 6283 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6284 EVT MemVT = MemSD->getMemoryVT(); 6285 MachineMemOperand *MMO = MemSD->getMemOperand(); 6286 SDValue Chain = MemSD->getChain(); 6287 SDValue BasePtr = MemSD->getBasePtr(); 6288 6289 bool IsTruncatingStore = false; 6290 SDValue Index, Mask, Val, VL; 6291 6292 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6293 Index = VPSN->getIndex(); 6294 Mask = VPSN->getMask(); 6295 Val = VPSN->getValue(); 6296 VL = VPSN->getVectorLength(); 6297 // VP doesn't support truncating stores. 6298 IsTruncatingStore = false; 6299 } else { 6300 // Else it must be a MSCATTER. 6301 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6302 Index = MSN->getIndex(); 6303 Mask = MSN->getMask(); 6304 Val = MSN->getValue(); 6305 IsTruncatingStore = MSN->isTruncatingStore(); 6306 } 6307 6308 MVT VT = Val.getSimpleValueType(); 6309 MVT IndexVT = Index.getSimpleValueType(); 6310 MVT XLenVT = Subtarget.getXLenVT(); 6311 6312 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6313 "Unexpected VTs!"); 6314 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6315 // Targets have to explicitly opt-in for extending vector loads and 6316 // truncating vector stores. 6317 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6318 (void)IsTruncatingStore; 6319 6320 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6321 // the selection of the masked intrinsics doesn't do this for us. 6322 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6323 6324 MVT ContainerVT = VT; 6325 if (VT.isFixedLengthVector()) { 6326 // We need to use the larger of the value and index type to determine the 6327 // scalable type to use so we don't increase LMUL for any operand/result. 6328 if (VT.bitsGE(IndexVT)) { 6329 ContainerVT = getContainerForFixedLengthVector(VT); 6330 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6331 ContainerVT.getVectorElementCount()); 6332 } else { 6333 IndexVT = getContainerForFixedLengthVector(IndexVT); 6334 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6335 IndexVT.getVectorElementCount()); 6336 } 6337 6338 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6339 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6340 6341 if (!IsUnmasked) { 6342 MVT MaskVT = 6343 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6344 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6345 } 6346 } 6347 6348 if (!VL) 6349 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6350 6351 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6352 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6353 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6354 VL); 6355 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6356 TrueMask, VL); 6357 } 6358 6359 unsigned IntID = 6360 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6361 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6362 Ops.push_back(Val); 6363 Ops.push_back(BasePtr); 6364 Ops.push_back(Index); 6365 if (!IsUnmasked) 6366 Ops.push_back(Mask); 6367 Ops.push_back(VL); 6368 6369 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6370 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6371 } 6372 6373 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6374 SelectionDAG &DAG) const { 6375 const MVT XLenVT = Subtarget.getXLenVT(); 6376 SDLoc DL(Op); 6377 SDValue Chain = Op->getOperand(0); 6378 SDValue SysRegNo = DAG.getTargetConstant( 6379 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6380 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6381 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6382 6383 // Encoding used for rounding mode in RISCV differs from that used in 6384 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6385 // table, which consists of a sequence of 4-bit fields, each representing 6386 // corresponding FLT_ROUNDS mode. 6387 static const int Table = 6388 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6389 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6390 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6391 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6392 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6393 6394 SDValue Shift = 6395 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6396 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6397 DAG.getConstant(Table, DL, XLenVT), Shift); 6398 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6399 DAG.getConstant(7, DL, XLenVT)); 6400 6401 return DAG.getMergeValues({Masked, Chain}, DL); 6402 } 6403 6404 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6405 SelectionDAG &DAG) const { 6406 const MVT XLenVT = Subtarget.getXLenVT(); 6407 SDLoc DL(Op); 6408 SDValue Chain = Op->getOperand(0); 6409 SDValue RMValue = Op->getOperand(1); 6410 SDValue SysRegNo = DAG.getTargetConstant( 6411 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6412 6413 // Encoding used for rounding mode in RISCV differs from that used in 6414 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6415 // a table, which consists of a sequence of 4-bit fields, each representing 6416 // corresponding RISCV mode. 6417 static const unsigned Table = 6418 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6419 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6420 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6421 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6422 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6423 6424 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6425 DAG.getConstant(2, DL, XLenVT)); 6426 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6427 DAG.getConstant(Table, DL, XLenVT), Shift); 6428 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6429 DAG.getConstant(0x7, DL, XLenVT)); 6430 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6431 RMValue); 6432 } 6433 6434 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6435 switch (IntNo) { 6436 default: 6437 llvm_unreachable("Unexpected Intrinsic"); 6438 case Intrinsic::riscv_bcompress: 6439 return RISCVISD::BCOMPRESSW; 6440 case Intrinsic::riscv_bdecompress: 6441 return RISCVISD::BDECOMPRESSW; 6442 case Intrinsic::riscv_bfp: 6443 return RISCVISD::BFPW; 6444 case Intrinsic::riscv_fsl: 6445 return RISCVISD::FSLW; 6446 case Intrinsic::riscv_fsr: 6447 return RISCVISD::FSRW; 6448 } 6449 } 6450 6451 // Converts the given intrinsic to a i64 operation with any extension. 6452 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6453 unsigned IntNo) { 6454 SDLoc DL(N); 6455 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6456 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6457 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6458 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6459 // ReplaceNodeResults requires we maintain the same type for the return value. 6460 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6461 } 6462 6463 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6464 // form of the given Opcode. 6465 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6466 switch (Opcode) { 6467 default: 6468 llvm_unreachable("Unexpected opcode"); 6469 case ISD::SHL: 6470 return RISCVISD::SLLW; 6471 case ISD::SRA: 6472 return RISCVISD::SRAW; 6473 case ISD::SRL: 6474 return RISCVISD::SRLW; 6475 case ISD::SDIV: 6476 return RISCVISD::DIVW; 6477 case ISD::UDIV: 6478 return RISCVISD::DIVUW; 6479 case ISD::UREM: 6480 return RISCVISD::REMUW; 6481 case ISD::ROTL: 6482 return RISCVISD::ROLW; 6483 case ISD::ROTR: 6484 return RISCVISD::RORW; 6485 } 6486 } 6487 6488 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6489 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6490 // otherwise be promoted to i64, making it difficult to select the 6491 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6492 // type i8/i16/i32 is lost. 6493 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6494 unsigned ExtOpc = ISD::ANY_EXTEND) { 6495 SDLoc DL(N); 6496 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6497 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6498 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6499 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6500 // ReplaceNodeResults requires we maintain the same type for the return value. 6501 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6502 } 6503 6504 // Converts the given 32-bit operation to a i64 operation with signed extension 6505 // semantic to reduce the signed extension instructions. 6506 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6507 SDLoc DL(N); 6508 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6509 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6510 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6511 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6512 DAG.getValueType(MVT::i32)); 6513 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6514 } 6515 6516 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6517 SmallVectorImpl<SDValue> &Results, 6518 SelectionDAG &DAG) const { 6519 SDLoc DL(N); 6520 switch (N->getOpcode()) { 6521 default: 6522 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6523 case ISD::STRICT_FP_TO_SINT: 6524 case ISD::STRICT_FP_TO_UINT: 6525 case ISD::FP_TO_SINT: 6526 case ISD::FP_TO_UINT: { 6527 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6528 "Unexpected custom legalisation"); 6529 bool IsStrict = N->isStrictFPOpcode(); 6530 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6531 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6532 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6533 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6534 TargetLowering::TypeSoftenFloat) { 6535 if (!isTypeLegal(Op0.getValueType())) 6536 return; 6537 if (IsStrict) { 6538 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6539 : RISCVISD::STRICT_FCVT_WU_RV64; 6540 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6541 SDValue Res = DAG.getNode( 6542 Opc, DL, VTs, N->getOperand(0), Op0, 6543 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6544 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6545 Results.push_back(Res.getValue(1)); 6546 return; 6547 } 6548 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6549 SDValue Res = 6550 DAG.getNode(Opc, DL, MVT::i64, Op0, 6551 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6552 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6553 return; 6554 } 6555 // If the FP type needs to be softened, emit a library call using the 'si' 6556 // version. If we left it to default legalization we'd end up with 'di'. If 6557 // the FP type doesn't need to be softened just let generic type 6558 // legalization promote the result type. 6559 RTLIB::Libcall LC; 6560 if (IsSigned) 6561 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6562 else 6563 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6564 MakeLibCallOptions CallOptions; 6565 EVT OpVT = Op0.getValueType(); 6566 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6567 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6568 SDValue Result; 6569 std::tie(Result, Chain) = 6570 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6571 Results.push_back(Result); 6572 if (IsStrict) 6573 Results.push_back(Chain); 6574 break; 6575 } 6576 case ISD::READCYCLECOUNTER: { 6577 assert(!Subtarget.is64Bit() && 6578 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6579 6580 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6581 SDValue RCW = 6582 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6583 6584 Results.push_back( 6585 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6586 Results.push_back(RCW.getValue(2)); 6587 break; 6588 } 6589 case ISD::MUL: { 6590 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6591 unsigned XLen = Subtarget.getXLen(); 6592 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6593 if (Size > XLen) { 6594 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6595 SDValue LHS = N->getOperand(0); 6596 SDValue RHS = N->getOperand(1); 6597 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6598 6599 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6600 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6601 // We need exactly one side to be unsigned. 6602 if (LHSIsU == RHSIsU) 6603 return; 6604 6605 auto MakeMULPair = [&](SDValue S, SDValue U) { 6606 MVT XLenVT = Subtarget.getXLenVT(); 6607 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6608 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6609 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6610 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6611 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6612 }; 6613 6614 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6615 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6616 6617 // The other operand should be signed, but still prefer MULH when 6618 // possible. 6619 if (RHSIsU && LHSIsS && !RHSIsS) 6620 Results.push_back(MakeMULPair(LHS, RHS)); 6621 else if (LHSIsU && RHSIsS && !LHSIsS) 6622 Results.push_back(MakeMULPair(RHS, LHS)); 6623 6624 return; 6625 } 6626 LLVM_FALLTHROUGH; 6627 } 6628 case ISD::ADD: 6629 case ISD::SUB: 6630 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6631 "Unexpected custom legalisation"); 6632 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6633 break; 6634 case ISD::SHL: 6635 case ISD::SRA: 6636 case ISD::SRL: 6637 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6638 "Unexpected custom legalisation"); 6639 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6640 Results.push_back(customLegalizeToWOp(N, DAG)); 6641 break; 6642 } 6643 6644 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6645 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6646 // shift amount. 6647 if (N->getOpcode() == ISD::SHL) { 6648 SDLoc DL(N); 6649 SDValue NewOp0 = 6650 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6651 SDValue NewOp1 = 6652 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6653 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6654 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6655 DAG.getValueType(MVT::i32)); 6656 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6657 } 6658 6659 break; 6660 case ISD::ROTL: 6661 case ISD::ROTR: 6662 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6663 "Unexpected custom legalisation"); 6664 Results.push_back(customLegalizeToWOp(N, DAG)); 6665 break; 6666 case ISD::CTTZ: 6667 case ISD::CTTZ_ZERO_UNDEF: 6668 case ISD::CTLZ: 6669 case ISD::CTLZ_ZERO_UNDEF: { 6670 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6671 "Unexpected custom legalisation"); 6672 6673 SDValue NewOp0 = 6674 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6675 bool IsCTZ = 6676 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6677 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6678 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6679 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6680 return; 6681 } 6682 case ISD::SDIV: 6683 case ISD::UDIV: 6684 case ISD::UREM: { 6685 MVT VT = N->getSimpleValueType(0); 6686 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6687 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6688 "Unexpected custom legalisation"); 6689 // Don't promote division/remainder by constant since we should expand those 6690 // to multiply by magic constant. 6691 // FIXME: What if the expansion is disabled for minsize. 6692 if (N->getOperand(1).getOpcode() == ISD::Constant) 6693 return; 6694 6695 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6696 // the upper 32 bits. For other types we need to sign or zero extend 6697 // based on the opcode. 6698 unsigned ExtOpc = ISD::ANY_EXTEND; 6699 if (VT != MVT::i32) 6700 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6701 : ISD::ZERO_EXTEND; 6702 6703 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6704 break; 6705 } 6706 case ISD::UADDO: 6707 case ISD::USUBO: { 6708 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6709 "Unexpected custom legalisation"); 6710 bool IsAdd = N->getOpcode() == ISD::UADDO; 6711 // Create an ADDW or SUBW. 6712 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6713 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6714 SDValue Res = 6715 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6716 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6717 DAG.getValueType(MVT::i32)); 6718 6719 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6720 // Since the inputs are sign extended from i32, this is equivalent to 6721 // comparing the lower 32 bits. 6722 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6723 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6724 IsAdd ? ISD::SETULT : ISD::SETUGT); 6725 6726 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6727 Results.push_back(Overflow); 6728 return; 6729 } 6730 case ISD::UADDSAT: 6731 case ISD::USUBSAT: { 6732 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6733 "Unexpected custom legalisation"); 6734 if (Subtarget.hasStdExtZbb()) { 6735 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6736 // sign extend allows overflow of the lower 32 bits to be detected on 6737 // the promoted size. 6738 SDValue LHS = 6739 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6740 SDValue RHS = 6741 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6742 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6743 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6744 return; 6745 } 6746 6747 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6748 // promotion for UADDO/USUBO. 6749 Results.push_back(expandAddSubSat(N, DAG)); 6750 return; 6751 } 6752 case ISD::ABS: { 6753 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6754 "Unexpected custom legalisation"); 6755 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6756 6757 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6758 6759 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6760 6761 // Freeze the source so we can increase it's use count. 6762 Src = DAG.getFreeze(Src); 6763 6764 // Copy sign bit to all bits using the sraiw pattern. 6765 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6766 DAG.getValueType(MVT::i32)); 6767 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6768 DAG.getConstant(31, DL, MVT::i64)); 6769 6770 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6771 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6772 6773 // NOTE: The result is only required to be anyextended, but sext is 6774 // consistent with type legalization of sub. 6775 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6776 DAG.getValueType(MVT::i32)); 6777 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6778 return; 6779 } 6780 case ISD::BITCAST: { 6781 EVT VT = N->getValueType(0); 6782 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6783 SDValue Op0 = N->getOperand(0); 6784 EVT Op0VT = Op0.getValueType(); 6785 MVT XLenVT = Subtarget.getXLenVT(); 6786 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6787 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6788 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6789 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6790 Subtarget.hasStdExtF()) { 6791 SDValue FPConv = 6792 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6793 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6794 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6795 isTypeLegal(Op0VT)) { 6796 // Custom-legalize bitcasts from fixed-length vector types to illegal 6797 // scalar types in order to improve codegen. Bitcast the vector to a 6798 // one-element vector type whose element type is the same as the result 6799 // type, and extract the first element. 6800 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6801 if (isTypeLegal(BVT)) { 6802 SDValue BVec = DAG.getBitcast(BVT, Op0); 6803 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6804 DAG.getConstant(0, DL, XLenVT))); 6805 } 6806 } 6807 break; 6808 } 6809 case RISCVISD::GREV: 6810 case RISCVISD::GORC: 6811 case RISCVISD::SHFL: { 6812 MVT VT = N->getSimpleValueType(0); 6813 MVT XLenVT = Subtarget.getXLenVT(); 6814 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 6815 "Unexpected custom legalisation"); 6816 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6817 assert((Subtarget.hasStdExtZbp() || 6818 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 6819 N->getConstantOperandVal(1) == 7)) && 6820 "Unexpected extension"); 6821 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6822 SDValue NewOp1 = 6823 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 6824 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 6825 // ReplaceNodeResults requires we maintain the same type for the return 6826 // value. 6827 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 6828 break; 6829 } 6830 case ISD::BSWAP: 6831 case ISD::BITREVERSE: { 6832 MVT VT = N->getSimpleValueType(0); 6833 MVT XLenVT = Subtarget.getXLenVT(); 6834 assert((VT == MVT::i8 || VT == MVT::i16 || 6835 (VT == MVT::i32 && Subtarget.is64Bit())) && 6836 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6837 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6838 unsigned Imm = VT.getSizeInBits() - 1; 6839 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6840 if (N->getOpcode() == ISD::BSWAP) 6841 Imm &= ~0x7U; 6842 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 6843 DAG.getConstant(Imm, DL, XLenVT)); 6844 // ReplaceNodeResults requires we maintain the same type for the return 6845 // value. 6846 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6847 break; 6848 } 6849 case ISD::FSHL: 6850 case ISD::FSHR: { 6851 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6852 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6853 SDValue NewOp0 = 6854 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6855 SDValue NewOp1 = 6856 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6857 SDValue NewShAmt = 6858 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6859 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6860 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6861 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6862 DAG.getConstant(0x1f, DL, MVT::i64)); 6863 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6864 // instruction use different orders. fshl will return its first operand for 6865 // shift of zero, fshr will return its second operand. fsl and fsr both 6866 // return rs1 so the ISD nodes need to have different operand orders. 6867 // Shift amount is in rs2. 6868 unsigned Opc = RISCVISD::FSLW; 6869 if (N->getOpcode() == ISD::FSHR) { 6870 std::swap(NewOp0, NewOp1); 6871 Opc = RISCVISD::FSRW; 6872 } 6873 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6874 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6875 break; 6876 } 6877 case ISD::EXTRACT_VECTOR_ELT: { 6878 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6879 // type is illegal (currently only vXi64 RV32). 6880 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6881 // transferred to the destination register. We issue two of these from the 6882 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6883 // first element. 6884 SDValue Vec = N->getOperand(0); 6885 SDValue Idx = N->getOperand(1); 6886 6887 // The vector type hasn't been legalized yet so we can't issue target 6888 // specific nodes if it needs legalization. 6889 // FIXME: We would manually legalize if it's important. 6890 if (!isTypeLegal(Vec.getValueType())) 6891 return; 6892 6893 MVT VecVT = Vec.getSimpleValueType(); 6894 6895 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6896 VecVT.getVectorElementType() == MVT::i64 && 6897 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6898 6899 // If this is a fixed vector, we need to convert it to a scalable vector. 6900 MVT ContainerVT = VecVT; 6901 if (VecVT.isFixedLengthVector()) { 6902 ContainerVT = getContainerForFixedLengthVector(VecVT); 6903 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6904 } 6905 6906 MVT XLenVT = Subtarget.getXLenVT(); 6907 6908 // Use a VL of 1 to avoid processing more elements than we need. 6909 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6910 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6911 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6912 6913 // Unless the index is known to be 0, we must slide the vector down to get 6914 // the desired element into index 0. 6915 if (!isNullConstant(Idx)) { 6916 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6917 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6918 } 6919 6920 // Extract the lower XLEN bits of the correct vector element. 6921 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6922 6923 // To extract the upper XLEN bits of the vector element, shift the first 6924 // element right by 32 bits and re-extract the lower XLEN bits. 6925 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6926 DAG.getUNDEF(ContainerVT), 6927 DAG.getConstant(32, DL, XLenVT), VL); 6928 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6929 ThirtyTwoV, Mask, VL); 6930 6931 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6932 6933 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6934 break; 6935 } 6936 case ISD::INTRINSIC_WO_CHAIN: { 6937 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6938 switch (IntNo) { 6939 default: 6940 llvm_unreachable( 6941 "Don't know how to custom type legalize this intrinsic!"); 6942 case Intrinsic::riscv_grev: 6943 case Intrinsic::riscv_gorc: { 6944 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6945 "Unexpected custom legalisation"); 6946 SDValue NewOp1 = 6947 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6948 SDValue NewOp2 = 6949 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6950 unsigned Opc = 6951 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 6952 // If the control is a constant, promote the node by clearing any extra 6953 // bits bits in the control. isel will form greviw/gorciw if the result is 6954 // sign extended. 6955 if (isa<ConstantSDNode>(NewOp2)) { 6956 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6957 DAG.getConstant(0x1f, DL, MVT::i64)); 6958 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 6959 } 6960 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6961 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6962 break; 6963 } 6964 case Intrinsic::riscv_bcompress: 6965 case Intrinsic::riscv_bdecompress: 6966 case Intrinsic::riscv_bfp: { 6967 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6968 "Unexpected custom legalisation"); 6969 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6970 break; 6971 } 6972 case Intrinsic::riscv_fsl: 6973 case Intrinsic::riscv_fsr: { 6974 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6975 "Unexpected custom legalisation"); 6976 SDValue NewOp1 = 6977 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6978 SDValue NewOp2 = 6979 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6980 SDValue NewOp3 = 6981 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 6982 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 6983 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 6984 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6985 break; 6986 } 6987 case Intrinsic::riscv_orc_b: { 6988 // Lower to the GORCI encoding for orc.b with the operand extended. 6989 SDValue NewOp = 6990 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6991 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 6992 DAG.getConstant(7, DL, MVT::i64)); 6993 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6994 return; 6995 } 6996 case Intrinsic::riscv_shfl: 6997 case Intrinsic::riscv_unshfl: { 6998 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6999 "Unexpected custom legalisation"); 7000 SDValue NewOp1 = 7001 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7002 SDValue NewOp2 = 7003 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7004 unsigned Opc = 7005 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7006 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7007 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7008 // will be shuffled the same way as the lower 32 bit half, but the two 7009 // halves won't cross. 7010 if (isa<ConstantSDNode>(NewOp2)) { 7011 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7012 DAG.getConstant(0xf, DL, MVT::i64)); 7013 Opc = 7014 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7015 } 7016 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7017 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7018 break; 7019 } 7020 case Intrinsic::riscv_vmv_x_s: { 7021 EVT VT = N->getValueType(0); 7022 MVT XLenVT = Subtarget.getXLenVT(); 7023 if (VT.bitsLT(XLenVT)) { 7024 // Simple case just extract using vmv.x.s and truncate. 7025 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7026 Subtarget.getXLenVT(), N->getOperand(1)); 7027 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7028 return; 7029 } 7030 7031 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7032 "Unexpected custom legalization"); 7033 7034 // We need to do the move in two steps. 7035 SDValue Vec = N->getOperand(1); 7036 MVT VecVT = Vec.getSimpleValueType(); 7037 7038 // First extract the lower XLEN bits of the element. 7039 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7040 7041 // To extract the upper XLEN bits of the vector element, shift the first 7042 // element right by 32 bits and re-extract the lower XLEN bits. 7043 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7044 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7045 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 7046 SDValue ThirtyTwoV = 7047 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7048 DAG.getConstant(32, DL, XLenVT), VL); 7049 SDValue LShr32 = 7050 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7051 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7052 7053 Results.push_back( 7054 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7055 break; 7056 } 7057 } 7058 break; 7059 } 7060 case ISD::VECREDUCE_ADD: 7061 case ISD::VECREDUCE_AND: 7062 case ISD::VECREDUCE_OR: 7063 case ISD::VECREDUCE_XOR: 7064 case ISD::VECREDUCE_SMAX: 7065 case ISD::VECREDUCE_UMAX: 7066 case ISD::VECREDUCE_SMIN: 7067 case ISD::VECREDUCE_UMIN: 7068 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7069 Results.push_back(V); 7070 break; 7071 case ISD::VP_REDUCE_ADD: 7072 case ISD::VP_REDUCE_AND: 7073 case ISD::VP_REDUCE_OR: 7074 case ISD::VP_REDUCE_XOR: 7075 case ISD::VP_REDUCE_SMAX: 7076 case ISD::VP_REDUCE_UMAX: 7077 case ISD::VP_REDUCE_SMIN: 7078 case ISD::VP_REDUCE_UMIN: 7079 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7080 Results.push_back(V); 7081 break; 7082 case ISD::FLT_ROUNDS_: { 7083 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7084 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7085 Results.push_back(Res.getValue(0)); 7086 Results.push_back(Res.getValue(1)); 7087 break; 7088 } 7089 } 7090 } 7091 7092 // A structure to hold one of the bit-manipulation patterns below. Together, a 7093 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7094 // (or (and (shl x, 1), 0xAAAAAAAA), 7095 // (and (srl x, 1), 0x55555555)) 7096 struct RISCVBitmanipPat { 7097 SDValue Op; 7098 unsigned ShAmt; 7099 bool IsSHL; 7100 7101 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7102 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7103 } 7104 }; 7105 7106 // Matches patterns of the form 7107 // (and (shl x, C2), (C1 << C2)) 7108 // (and (srl x, C2), C1) 7109 // (shl (and x, C1), C2) 7110 // (srl (and x, (C1 << C2)), C2) 7111 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7112 // The expected masks for each shift amount are specified in BitmanipMasks where 7113 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7114 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7115 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7116 // XLen is 64. 7117 static Optional<RISCVBitmanipPat> 7118 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7119 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7120 "Unexpected number of masks"); 7121 Optional<uint64_t> Mask; 7122 // Optionally consume a mask around the shift operation. 7123 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7124 Mask = Op.getConstantOperandVal(1); 7125 Op = Op.getOperand(0); 7126 } 7127 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7128 return None; 7129 bool IsSHL = Op.getOpcode() == ISD::SHL; 7130 7131 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7132 return None; 7133 uint64_t ShAmt = Op.getConstantOperandVal(1); 7134 7135 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7136 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7137 return None; 7138 // If we don't have enough masks for 64 bit, then we must be trying to 7139 // match SHFL so we're only allowed to shift 1/4 of the width. 7140 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7141 return None; 7142 7143 SDValue Src = Op.getOperand(0); 7144 7145 // The expected mask is shifted left when the AND is found around SHL 7146 // patterns. 7147 // ((x >> 1) & 0x55555555) 7148 // ((x << 1) & 0xAAAAAAAA) 7149 bool SHLExpMask = IsSHL; 7150 7151 if (!Mask) { 7152 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7153 // the mask is all ones: consume that now. 7154 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7155 Mask = Src.getConstantOperandVal(1); 7156 Src = Src.getOperand(0); 7157 // The expected mask is now in fact shifted left for SRL, so reverse the 7158 // decision. 7159 // ((x & 0xAAAAAAAA) >> 1) 7160 // ((x & 0x55555555) << 1) 7161 SHLExpMask = !SHLExpMask; 7162 } else { 7163 // Use a default shifted mask of all-ones if there's no AND, truncated 7164 // down to the expected width. This simplifies the logic later on. 7165 Mask = maskTrailingOnes<uint64_t>(Width); 7166 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7167 } 7168 } 7169 7170 unsigned MaskIdx = Log2_32(ShAmt); 7171 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7172 7173 if (SHLExpMask) 7174 ExpMask <<= ShAmt; 7175 7176 if (Mask != ExpMask) 7177 return None; 7178 7179 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7180 } 7181 7182 // Matches any of the following bit-manipulation patterns: 7183 // (and (shl x, 1), (0x55555555 << 1)) 7184 // (and (srl x, 1), 0x55555555) 7185 // (shl (and x, 0x55555555), 1) 7186 // (srl (and x, (0x55555555 << 1)), 1) 7187 // where the shift amount and mask may vary thus: 7188 // [1] = 0x55555555 / 0xAAAAAAAA 7189 // [2] = 0x33333333 / 0xCCCCCCCC 7190 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7191 // [8] = 0x00FF00FF / 0xFF00FF00 7192 // [16] = 0x0000FFFF / 0xFFFFFFFF 7193 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7194 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7195 // These are the unshifted masks which we use to match bit-manipulation 7196 // patterns. They may be shifted left in certain circumstances. 7197 static const uint64_t BitmanipMasks[] = { 7198 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7199 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7200 7201 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7202 } 7203 7204 // Match the following pattern as a GREVI(W) operation 7205 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7206 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7207 const RISCVSubtarget &Subtarget) { 7208 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7209 EVT VT = Op.getValueType(); 7210 7211 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7212 auto LHS = matchGREVIPat(Op.getOperand(0)); 7213 auto RHS = matchGREVIPat(Op.getOperand(1)); 7214 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7215 SDLoc DL(Op); 7216 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7217 DAG.getConstant(LHS->ShAmt, DL, VT)); 7218 } 7219 } 7220 return SDValue(); 7221 } 7222 7223 // Matches any the following pattern as a GORCI(W) operation 7224 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7225 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7226 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7227 // Note that with the variant of 3., 7228 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7229 // the inner pattern will first be matched as GREVI and then the outer 7230 // pattern will be matched to GORC via the first rule above. 7231 // 4. (or (rotl/rotr x, bitwidth/2), x) 7232 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7233 const RISCVSubtarget &Subtarget) { 7234 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7235 EVT VT = Op.getValueType(); 7236 7237 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7238 SDLoc DL(Op); 7239 SDValue Op0 = Op.getOperand(0); 7240 SDValue Op1 = Op.getOperand(1); 7241 7242 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7243 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7244 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7245 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7246 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7247 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7248 if ((Reverse.getOpcode() == ISD::ROTL || 7249 Reverse.getOpcode() == ISD::ROTR) && 7250 Reverse.getOperand(0) == X && 7251 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7252 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7253 if (RotAmt == (VT.getSizeInBits() / 2)) 7254 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7255 DAG.getConstant(RotAmt, DL, VT)); 7256 } 7257 return SDValue(); 7258 }; 7259 7260 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7261 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7262 return V; 7263 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7264 return V; 7265 7266 // OR is commutable so canonicalize its OR operand to the left 7267 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7268 std::swap(Op0, Op1); 7269 if (Op0.getOpcode() != ISD::OR) 7270 return SDValue(); 7271 SDValue OrOp0 = Op0.getOperand(0); 7272 SDValue OrOp1 = Op0.getOperand(1); 7273 auto LHS = matchGREVIPat(OrOp0); 7274 // OR is commutable so swap the operands and try again: x might have been 7275 // on the left 7276 if (!LHS) { 7277 std::swap(OrOp0, OrOp1); 7278 LHS = matchGREVIPat(OrOp0); 7279 } 7280 auto RHS = matchGREVIPat(Op1); 7281 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7282 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7283 DAG.getConstant(LHS->ShAmt, DL, VT)); 7284 } 7285 } 7286 return SDValue(); 7287 } 7288 7289 // Matches any of the following bit-manipulation patterns: 7290 // (and (shl x, 1), (0x22222222 << 1)) 7291 // (and (srl x, 1), 0x22222222) 7292 // (shl (and x, 0x22222222), 1) 7293 // (srl (and x, (0x22222222 << 1)), 1) 7294 // where the shift amount and mask may vary thus: 7295 // [1] = 0x22222222 / 0x44444444 7296 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7297 // [4] = 0x00F000F0 / 0x0F000F00 7298 // [8] = 0x0000FF00 / 0x00FF0000 7299 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7300 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7301 // These are the unshifted masks which we use to match bit-manipulation 7302 // patterns. They may be shifted left in certain circumstances. 7303 static const uint64_t BitmanipMasks[] = { 7304 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7305 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7306 7307 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7308 } 7309 7310 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7311 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7312 const RISCVSubtarget &Subtarget) { 7313 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7314 EVT VT = Op.getValueType(); 7315 7316 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7317 return SDValue(); 7318 7319 SDValue Op0 = Op.getOperand(0); 7320 SDValue Op1 = Op.getOperand(1); 7321 7322 // Or is commutable so canonicalize the second OR to the LHS. 7323 if (Op0.getOpcode() != ISD::OR) 7324 std::swap(Op0, Op1); 7325 if (Op0.getOpcode() != ISD::OR) 7326 return SDValue(); 7327 7328 // We found an inner OR, so our operands are the operands of the inner OR 7329 // and the other operand of the outer OR. 7330 SDValue A = Op0.getOperand(0); 7331 SDValue B = Op0.getOperand(1); 7332 SDValue C = Op1; 7333 7334 auto Match1 = matchSHFLPat(A); 7335 auto Match2 = matchSHFLPat(B); 7336 7337 // If neither matched, we failed. 7338 if (!Match1 && !Match2) 7339 return SDValue(); 7340 7341 // We had at least one match. if one failed, try the remaining C operand. 7342 if (!Match1) { 7343 std::swap(A, C); 7344 Match1 = matchSHFLPat(A); 7345 if (!Match1) 7346 return SDValue(); 7347 } else if (!Match2) { 7348 std::swap(B, C); 7349 Match2 = matchSHFLPat(B); 7350 if (!Match2) 7351 return SDValue(); 7352 } 7353 assert(Match1 && Match2); 7354 7355 // Make sure our matches pair up. 7356 if (!Match1->formsPairWith(*Match2)) 7357 return SDValue(); 7358 7359 // All the remains is to make sure C is an AND with the same input, that masks 7360 // out the bits that are being shuffled. 7361 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7362 C.getOperand(0) != Match1->Op) 7363 return SDValue(); 7364 7365 uint64_t Mask = C.getConstantOperandVal(1); 7366 7367 static const uint64_t BitmanipMasks[] = { 7368 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7369 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7370 }; 7371 7372 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7373 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7374 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7375 7376 if (Mask != ExpMask) 7377 return SDValue(); 7378 7379 SDLoc DL(Op); 7380 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7381 DAG.getConstant(Match1->ShAmt, DL, VT)); 7382 } 7383 7384 // Optimize (add (shl x, c0), (shl y, c1)) -> 7385 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7386 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7387 const RISCVSubtarget &Subtarget) { 7388 // Perform this optimization only in the zba extension. 7389 if (!Subtarget.hasStdExtZba()) 7390 return SDValue(); 7391 7392 // Skip for vector types and larger types. 7393 EVT VT = N->getValueType(0); 7394 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7395 return SDValue(); 7396 7397 // The two operand nodes must be SHL and have no other use. 7398 SDValue N0 = N->getOperand(0); 7399 SDValue N1 = N->getOperand(1); 7400 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7401 !N0->hasOneUse() || !N1->hasOneUse()) 7402 return SDValue(); 7403 7404 // Check c0 and c1. 7405 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7406 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7407 if (!N0C || !N1C) 7408 return SDValue(); 7409 int64_t C0 = N0C->getSExtValue(); 7410 int64_t C1 = N1C->getSExtValue(); 7411 if (C0 <= 0 || C1 <= 0) 7412 return SDValue(); 7413 7414 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7415 int64_t Bits = std::min(C0, C1); 7416 int64_t Diff = std::abs(C0 - C1); 7417 if (Diff != 1 && Diff != 2 && Diff != 3) 7418 return SDValue(); 7419 7420 // Build nodes. 7421 SDLoc DL(N); 7422 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7423 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7424 SDValue NA0 = 7425 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7426 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7427 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7428 } 7429 7430 // Combine 7431 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7432 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7433 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7434 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7435 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7436 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7437 // The grev patterns represents BSWAP. 7438 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7439 // off the grev. 7440 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7441 const RISCVSubtarget &Subtarget) { 7442 bool IsWInstruction = 7443 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7444 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7445 IsWInstruction) && 7446 "Unexpected opcode!"); 7447 SDValue Src = N->getOperand(0); 7448 EVT VT = N->getValueType(0); 7449 SDLoc DL(N); 7450 7451 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7452 return SDValue(); 7453 7454 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7455 !isa<ConstantSDNode>(Src.getOperand(1))) 7456 return SDValue(); 7457 7458 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7459 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7460 7461 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7462 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7463 unsigned ShAmt1 = N->getConstantOperandVal(1); 7464 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7465 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7466 return SDValue(); 7467 7468 Src = Src.getOperand(0); 7469 7470 // Toggle bit the MSB of the shift. 7471 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7472 if (CombinedShAmt == 0) 7473 return Src; 7474 7475 SDValue Res = DAG.getNode( 7476 RISCVISD::GREV, DL, VT, Src, 7477 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7478 if (!IsWInstruction) 7479 return Res; 7480 7481 // Sign extend the result to match the behavior of the rotate. This will be 7482 // selected to GREVIW in isel. 7483 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7484 DAG.getValueType(MVT::i32)); 7485 } 7486 7487 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7488 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7489 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7490 // not undo itself, but they are redundant. 7491 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7492 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7493 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7494 SDValue Src = N->getOperand(0); 7495 7496 if (Src.getOpcode() != N->getOpcode()) 7497 return SDValue(); 7498 7499 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7500 !isa<ConstantSDNode>(Src.getOperand(1))) 7501 return SDValue(); 7502 7503 unsigned ShAmt1 = N->getConstantOperandVal(1); 7504 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7505 Src = Src.getOperand(0); 7506 7507 unsigned CombinedShAmt; 7508 if (IsGORC) 7509 CombinedShAmt = ShAmt1 | ShAmt2; 7510 else 7511 CombinedShAmt = ShAmt1 ^ ShAmt2; 7512 7513 if (CombinedShAmt == 0) 7514 return Src; 7515 7516 SDLoc DL(N); 7517 return DAG.getNode( 7518 N->getOpcode(), DL, N->getValueType(0), Src, 7519 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7520 } 7521 7522 // Combine a constant select operand into its use: 7523 // 7524 // (and (select cond, -1, c), x) 7525 // -> (select cond, x, (and x, c)) [AllOnes=1] 7526 // (or (select cond, 0, c), x) 7527 // -> (select cond, x, (or x, c)) [AllOnes=0] 7528 // (xor (select cond, 0, c), x) 7529 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7530 // (add (select cond, 0, c), x) 7531 // -> (select cond, x, (add x, c)) [AllOnes=0] 7532 // (sub x, (select cond, 0, c)) 7533 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7534 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7535 SelectionDAG &DAG, bool AllOnes) { 7536 EVT VT = N->getValueType(0); 7537 7538 // Skip vectors. 7539 if (VT.isVector()) 7540 return SDValue(); 7541 7542 if ((Slct.getOpcode() != ISD::SELECT && 7543 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7544 !Slct.hasOneUse()) 7545 return SDValue(); 7546 7547 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7548 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7549 }; 7550 7551 bool SwapSelectOps; 7552 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7553 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7554 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7555 SDValue NonConstantVal; 7556 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7557 SwapSelectOps = false; 7558 NonConstantVal = FalseVal; 7559 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7560 SwapSelectOps = true; 7561 NonConstantVal = TrueVal; 7562 } else 7563 return SDValue(); 7564 7565 // Slct is now know to be the desired identity constant when CC is true. 7566 TrueVal = OtherOp; 7567 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7568 // Unless SwapSelectOps says the condition should be false. 7569 if (SwapSelectOps) 7570 std::swap(TrueVal, FalseVal); 7571 7572 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7573 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7574 {Slct.getOperand(0), Slct.getOperand(1), 7575 Slct.getOperand(2), TrueVal, FalseVal}); 7576 7577 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7578 {Slct.getOperand(0), TrueVal, FalseVal}); 7579 } 7580 7581 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7582 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7583 bool AllOnes) { 7584 SDValue N0 = N->getOperand(0); 7585 SDValue N1 = N->getOperand(1); 7586 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7587 return Result; 7588 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7589 return Result; 7590 return SDValue(); 7591 } 7592 7593 // Transform (add (mul x, c0), c1) -> 7594 // (add (mul (add x, c1/c0), c0), c1%c0). 7595 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7596 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7597 // to an infinite loop in DAGCombine if transformed. 7598 // Or transform (add (mul x, c0), c1) -> 7599 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7600 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7601 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7602 // lead to an infinite loop in DAGCombine if transformed. 7603 // Or transform (add (mul x, c0), c1) -> 7604 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7605 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7606 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7607 // lead to an infinite loop in DAGCombine if transformed. 7608 // Or transform (add (mul x, c0), c1) -> 7609 // (mul (add x, c1/c0), c0). 7610 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7611 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7612 const RISCVSubtarget &Subtarget) { 7613 // Skip for vector types and larger types. 7614 EVT VT = N->getValueType(0); 7615 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7616 return SDValue(); 7617 // The first operand node must be a MUL and has no other use. 7618 SDValue N0 = N->getOperand(0); 7619 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7620 return SDValue(); 7621 // Check if c0 and c1 match above conditions. 7622 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7623 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7624 if (!N0C || !N1C) 7625 return SDValue(); 7626 // If N0C has multiple uses it's possible one of the cases in 7627 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7628 // in an infinite loop. 7629 if (!N0C->hasOneUse()) 7630 return SDValue(); 7631 int64_t C0 = N0C->getSExtValue(); 7632 int64_t C1 = N1C->getSExtValue(); 7633 int64_t CA, CB; 7634 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7635 return SDValue(); 7636 // Search for proper CA (non-zero) and CB that both are simm12. 7637 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7638 !isInt<12>(C0 * (C1 / C0))) { 7639 CA = C1 / C0; 7640 CB = C1 % C0; 7641 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7642 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7643 CA = C1 / C0 + 1; 7644 CB = C1 % C0 - C0; 7645 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7646 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7647 CA = C1 / C0 - 1; 7648 CB = C1 % C0 + C0; 7649 } else 7650 return SDValue(); 7651 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7652 SDLoc DL(N); 7653 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7654 DAG.getConstant(CA, DL, VT)); 7655 SDValue New1 = 7656 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7657 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7658 } 7659 7660 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7661 const RISCVSubtarget &Subtarget) { 7662 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7663 return V; 7664 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7665 return V; 7666 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7667 // (select lhs, rhs, cc, x, (add x, y)) 7668 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7669 } 7670 7671 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7672 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7673 // (select lhs, rhs, cc, x, (sub x, y)) 7674 SDValue N0 = N->getOperand(0); 7675 SDValue N1 = N->getOperand(1); 7676 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7677 } 7678 7679 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7680 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7681 // (select lhs, rhs, cc, x, (and x, y)) 7682 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7683 } 7684 7685 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7686 const RISCVSubtarget &Subtarget) { 7687 if (Subtarget.hasStdExtZbp()) { 7688 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7689 return GREV; 7690 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7691 return GORC; 7692 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7693 return SHFL; 7694 } 7695 7696 // fold (or (select cond, 0, y), x) -> 7697 // (select cond, x, (or x, y)) 7698 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7699 } 7700 7701 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7702 // fold (xor (select cond, 0, y), x) -> 7703 // (select cond, x, (xor x, y)) 7704 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7705 } 7706 7707 static SDValue 7708 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 7709 const RISCVSubtarget &Subtarget) { 7710 SDValue Src = N->getOperand(0); 7711 EVT VT = N->getValueType(0); 7712 7713 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 7714 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7715 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 7716 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 7717 Src.getOperand(0)); 7718 7719 // Fold (i64 (sext_inreg (abs X), i32)) -> 7720 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 7721 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 7722 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 7723 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 7724 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 7725 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 7726 // may get combined into an earlier operation so we need to use 7727 // ComputeNumSignBits. 7728 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 7729 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 7730 // we can't assume that X has 33 sign bits. We must check. 7731 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 7732 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 7733 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 7734 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 7735 SDLoc DL(N); 7736 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 7737 SDValue Neg = 7738 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 7739 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 7740 DAG.getValueType(MVT::i32)); 7741 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 7742 } 7743 7744 return SDValue(); 7745 } 7746 7747 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7748 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7749 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7750 bool Commute = false) { 7751 assert((N->getOpcode() == RISCVISD::ADD_VL || 7752 N->getOpcode() == RISCVISD::SUB_VL) && 7753 "Unexpected opcode"); 7754 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7755 SDValue Op0 = N->getOperand(0); 7756 SDValue Op1 = N->getOperand(1); 7757 if (Commute) 7758 std::swap(Op0, Op1); 7759 7760 MVT VT = N->getSimpleValueType(0); 7761 7762 // Determine the narrow size for a widening add/sub. 7763 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7764 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7765 VT.getVectorElementCount()); 7766 7767 SDValue Mask = N->getOperand(2); 7768 SDValue VL = N->getOperand(3); 7769 7770 SDLoc DL(N); 7771 7772 // If the RHS is a sext or zext, we can form a widening op. 7773 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7774 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7775 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7776 unsigned ExtOpc = Op1.getOpcode(); 7777 Op1 = Op1.getOperand(0); 7778 // Re-introduce narrower extends if needed. 7779 if (Op1.getValueType() != NarrowVT) 7780 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7781 7782 unsigned WOpc; 7783 if (ExtOpc == RISCVISD::VSEXT_VL) 7784 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7785 else 7786 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7787 7788 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7789 } 7790 7791 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7792 // sext/zext? 7793 7794 return SDValue(); 7795 } 7796 7797 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7798 // vwsub(u).vv/vx. 7799 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7800 SDValue Op0 = N->getOperand(0); 7801 SDValue Op1 = N->getOperand(1); 7802 SDValue Mask = N->getOperand(2); 7803 SDValue VL = N->getOperand(3); 7804 7805 MVT VT = N->getSimpleValueType(0); 7806 MVT NarrowVT = Op1.getSimpleValueType(); 7807 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 7808 7809 unsigned VOpc; 7810 switch (N->getOpcode()) { 7811 default: llvm_unreachable("Unexpected opcode"); 7812 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 7813 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 7814 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 7815 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 7816 } 7817 7818 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 7819 N->getOpcode() == RISCVISD::VWSUB_W_VL; 7820 7821 SDLoc DL(N); 7822 7823 // If the LHS is a sext or zext, we can narrow this op to the same size as 7824 // the RHS. 7825 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 7826 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 7827 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 7828 unsigned ExtOpc = Op0.getOpcode(); 7829 Op0 = Op0.getOperand(0); 7830 // Re-introduce narrower extends if needed. 7831 if (Op0.getValueType() != NarrowVT) 7832 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7833 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 7834 } 7835 7836 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 7837 N->getOpcode() == RISCVISD::VWADDU_W_VL; 7838 7839 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 7840 // to commute and use a vwadd(u).vx instead. 7841 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 7842 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 7843 Op0 = Op0.getOperand(1); 7844 7845 // See if have enough sign bits or zero bits in the scalar to use a 7846 // widening add/sub by splatting to smaller element size. 7847 unsigned EltBits = VT.getScalarSizeInBits(); 7848 unsigned ScalarBits = Op0.getValueSizeInBits(); 7849 // Make sure we're getting all element bits from the scalar register. 7850 // FIXME: Support implicit sign extension of vmv.v.x? 7851 if (ScalarBits < EltBits) 7852 return SDValue(); 7853 7854 if (IsSigned) { 7855 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 7856 return SDValue(); 7857 } else { 7858 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7859 if (!DAG.MaskedValueIsZero(Op0, Mask)) 7860 return SDValue(); 7861 } 7862 7863 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7864 DAG.getUNDEF(NarrowVT), Op0, VL); 7865 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 7866 } 7867 7868 return SDValue(); 7869 } 7870 7871 // Try to form VWMUL, VWMULU or VWMULSU. 7872 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 7873 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 7874 bool Commute) { 7875 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7876 SDValue Op0 = N->getOperand(0); 7877 SDValue Op1 = N->getOperand(1); 7878 if (Commute) 7879 std::swap(Op0, Op1); 7880 7881 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7882 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7883 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 7884 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7885 return SDValue(); 7886 7887 SDValue Mask = N->getOperand(2); 7888 SDValue VL = N->getOperand(3); 7889 7890 // Make sure the mask and VL match. 7891 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7892 return SDValue(); 7893 7894 MVT VT = N->getSimpleValueType(0); 7895 7896 // Determine the narrow size for a widening multiply. 7897 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7898 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7899 VT.getVectorElementCount()); 7900 7901 SDLoc DL(N); 7902 7903 // See if the other operand is the same opcode. 7904 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 7905 if (!Op1.hasOneUse()) 7906 return SDValue(); 7907 7908 // Make sure the mask and VL match. 7909 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7910 return SDValue(); 7911 7912 Op1 = Op1.getOperand(0); 7913 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7914 // The operand is a splat of a scalar. 7915 7916 // The pasthru must be undef for tail agnostic 7917 if (!Op1.getOperand(0).isUndef()) 7918 return SDValue(); 7919 // The VL must be the same. 7920 if (Op1.getOperand(2) != VL) 7921 return SDValue(); 7922 7923 // Get the scalar value. 7924 Op1 = Op1.getOperand(1); 7925 7926 // See if have enough sign bits or zero bits in the scalar to use a 7927 // widening multiply by splatting to smaller element size. 7928 unsigned EltBits = VT.getScalarSizeInBits(); 7929 unsigned ScalarBits = Op1.getValueSizeInBits(); 7930 // Make sure we're getting all element bits from the scalar register. 7931 // FIXME: Support implicit sign extension of vmv.v.x? 7932 if (ScalarBits < EltBits) 7933 return SDValue(); 7934 7935 // If the LHS is a sign extend, try to use vwmul. 7936 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 7937 // Can use vwmul. 7938 } else { 7939 // Otherwise try to use vwmulu or vwmulsu. 7940 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7941 if (DAG.MaskedValueIsZero(Op1, Mask)) 7942 IsVWMULSU = IsSignExt; 7943 else 7944 return SDValue(); 7945 } 7946 7947 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7948 DAG.getUNDEF(NarrowVT), Op1, VL); 7949 } else 7950 return SDValue(); 7951 7952 Op0 = Op0.getOperand(0); 7953 7954 // Re-introduce narrower extends if needed. 7955 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7956 if (Op0.getValueType() != NarrowVT) 7957 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7958 // vwmulsu requires second operand to be zero extended. 7959 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 7960 if (Op1.getValueType() != NarrowVT) 7961 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7962 7963 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 7964 if (!IsVWMULSU) 7965 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7966 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7967 } 7968 7969 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 7970 switch (Op.getOpcode()) { 7971 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 7972 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 7973 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 7974 case ISD::FCEIL: return RISCVFPRndMode::RUP; 7975 case ISD::FROUND: return RISCVFPRndMode::RMM; 7976 } 7977 7978 return RISCVFPRndMode::Invalid; 7979 } 7980 7981 // Fold 7982 // (fp_to_int (froundeven X)) -> fcvt X, rne 7983 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7984 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7985 // (fp_to_int (fceil X)) -> fcvt X, rup 7986 // (fp_to_int (fround X)) -> fcvt X, rmm 7987 static SDValue performFP_TO_INTCombine(SDNode *N, 7988 TargetLowering::DAGCombinerInfo &DCI, 7989 const RISCVSubtarget &Subtarget) { 7990 SelectionDAG &DAG = DCI.DAG; 7991 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7992 MVT XLenVT = Subtarget.getXLenVT(); 7993 7994 // Only handle XLen or i32 types. Other types narrower than XLen will 7995 // eventually be legalized to XLenVT. 7996 EVT VT = N->getValueType(0); 7997 if (VT != MVT::i32 && VT != XLenVT) 7998 return SDValue(); 7999 8000 SDValue Src = N->getOperand(0); 8001 8002 // Ensure the FP type is also legal. 8003 if (!TLI.isTypeLegal(Src.getValueType())) 8004 return SDValue(); 8005 8006 // Don't do this for f16 with Zfhmin and not Zfh. 8007 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8008 return SDValue(); 8009 8010 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8011 if (FRM == RISCVFPRndMode::Invalid) 8012 return SDValue(); 8013 8014 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8015 8016 unsigned Opc; 8017 if (VT == XLenVT) 8018 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8019 else 8020 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8021 8022 SDLoc DL(N); 8023 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8024 DAG.getTargetConstant(FRM, DL, XLenVT)); 8025 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8026 } 8027 8028 // Fold 8029 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8030 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8031 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8032 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8033 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8034 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8035 TargetLowering::DAGCombinerInfo &DCI, 8036 const RISCVSubtarget &Subtarget) { 8037 SelectionDAG &DAG = DCI.DAG; 8038 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8039 MVT XLenVT = Subtarget.getXLenVT(); 8040 8041 // Only handle XLen types. Other types narrower than XLen will eventually be 8042 // legalized to XLenVT. 8043 EVT DstVT = N->getValueType(0); 8044 if (DstVT != XLenVT) 8045 return SDValue(); 8046 8047 SDValue Src = N->getOperand(0); 8048 8049 // Ensure the FP type is also legal. 8050 if (!TLI.isTypeLegal(Src.getValueType())) 8051 return SDValue(); 8052 8053 // Don't do this for f16 with Zfhmin and not Zfh. 8054 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8055 return SDValue(); 8056 8057 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8058 8059 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8060 if (FRM == RISCVFPRndMode::Invalid) 8061 return SDValue(); 8062 8063 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8064 8065 unsigned Opc; 8066 if (SatVT == DstVT) 8067 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8068 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8069 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8070 else 8071 return SDValue(); 8072 // FIXME: Support other SatVTs by clamping before or after the conversion. 8073 8074 Src = Src.getOperand(0); 8075 8076 SDLoc DL(N); 8077 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8078 DAG.getTargetConstant(FRM, DL, XLenVT)); 8079 8080 // RISCV FP-to-int conversions saturate to the destination register size, but 8081 // don't produce 0 for nan. 8082 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8083 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8084 } 8085 8086 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8087 // smaller than XLenVT. 8088 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8089 const RISCVSubtarget &Subtarget) { 8090 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8091 8092 SDValue Src = N->getOperand(0); 8093 if (Src.getOpcode() != ISD::BSWAP) 8094 return SDValue(); 8095 8096 EVT VT = N->getValueType(0); 8097 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8098 !isPowerOf2_32(VT.getSizeInBits())) 8099 return SDValue(); 8100 8101 SDLoc DL(N); 8102 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8103 DAG.getConstant(7, DL, VT)); 8104 } 8105 8106 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8107 DAGCombinerInfo &DCI) const { 8108 SelectionDAG &DAG = DCI.DAG; 8109 8110 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8111 // bits are demanded. N will be added to the Worklist if it was not deleted. 8112 // Caller should return SDValue(N, 0) if this returns true. 8113 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8114 SDValue Op = N->getOperand(OpNo); 8115 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8116 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8117 return false; 8118 8119 if (N->getOpcode() != ISD::DELETED_NODE) 8120 DCI.AddToWorklist(N); 8121 return true; 8122 }; 8123 8124 switch (N->getOpcode()) { 8125 default: 8126 break; 8127 case RISCVISD::SplitF64: { 8128 SDValue Op0 = N->getOperand(0); 8129 // If the input to SplitF64 is just BuildPairF64 then the operation is 8130 // redundant. Instead, use BuildPairF64's operands directly. 8131 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8132 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8133 8134 if (Op0->isUndef()) { 8135 SDValue Lo = DAG.getUNDEF(MVT::i32); 8136 SDValue Hi = DAG.getUNDEF(MVT::i32); 8137 return DCI.CombineTo(N, Lo, Hi); 8138 } 8139 8140 SDLoc DL(N); 8141 8142 // It's cheaper to materialise two 32-bit integers than to load a double 8143 // from the constant pool and transfer it to integer registers through the 8144 // stack. 8145 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8146 APInt V = C->getValueAPF().bitcastToAPInt(); 8147 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8148 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8149 return DCI.CombineTo(N, Lo, Hi); 8150 } 8151 8152 // This is a target-specific version of a DAGCombine performed in 8153 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8154 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8155 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8156 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8157 !Op0.getNode()->hasOneUse()) 8158 break; 8159 SDValue NewSplitF64 = 8160 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8161 Op0.getOperand(0)); 8162 SDValue Lo = NewSplitF64.getValue(0); 8163 SDValue Hi = NewSplitF64.getValue(1); 8164 APInt SignBit = APInt::getSignMask(32); 8165 if (Op0.getOpcode() == ISD::FNEG) { 8166 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8167 DAG.getConstant(SignBit, DL, MVT::i32)); 8168 return DCI.CombineTo(N, Lo, NewHi); 8169 } 8170 assert(Op0.getOpcode() == ISD::FABS); 8171 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8172 DAG.getConstant(~SignBit, DL, MVT::i32)); 8173 return DCI.CombineTo(N, Lo, NewHi); 8174 } 8175 case RISCVISD::SLLW: 8176 case RISCVISD::SRAW: 8177 case RISCVISD::SRLW: { 8178 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8179 if (SimplifyDemandedLowBitsHelper(0, 32) || 8180 SimplifyDemandedLowBitsHelper(1, 5)) 8181 return SDValue(N, 0); 8182 8183 break; 8184 } 8185 case ISD::ROTR: 8186 case ISD::ROTL: 8187 case RISCVISD::RORW: 8188 case RISCVISD::ROLW: { 8189 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8190 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8191 if (SimplifyDemandedLowBitsHelper(0, 32) || 8192 SimplifyDemandedLowBitsHelper(1, 5)) 8193 return SDValue(N, 0); 8194 } 8195 8196 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8197 } 8198 case RISCVISD::CLZW: 8199 case RISCVISD::CTZW: { 8200 // Only the lower 32 bits of the first operand are read 8201 if (SimplifyDemandedLowBitsHelper(0, 32)) 8202 return SDValue(N, 0); 8203 break; 8204 } 8205 case RISCVISD::GREV: 8206 case RISCVISD::GORC: { 8207 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8208 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8209 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8210 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8211 return SDValue(N, 0); 8212 8213 return combineGREVI_GORCI(N, DAG); 8214 } 8215 case RISCVISD::GREVW: 8216 case RISCVISD::GORCW: { 8217 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8218 if (SimplifyDemandedLowBitsHelper(0, 32) || 8219 SimplifyDemandedLowBitsHelper(1, 5)) 8220 return SDValue(N, 0); 8221 8222 break; 8223 } 8224 case RISCVISD::SHFL: 8225 case RISCVISD::UNSHFL: { 8226 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8227 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8228 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8229 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8230 return SDValue(N, 0); 8231 8232 break; 8233 } 8234 case RISCVISD::SHFLW: 8235 case RISCVISD::UNSHFLW: { 8236 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8237 if (SimplifyDemandedLowBitsHelper(0, 32) || 8238 SimplifyDemandedLowBitsHelper(1, 4)) 8239 return SDValue(N, 0); 8240 8241 break; 8242 } 8243 case RISCVISD::BCOMPRESSW: 8244 case RISCVISD::BDECOMPRESSW: { 8245 // Only the lower 32 bits of LHS and RHS are read. 8246 if (SimplifyDemandedLowBitsHelper(0, 32) || 8247 SimplifyDemandedLowBitsHelper(1, 32)) 8248 return SDValue(N, 0); 8249 8250 break; 8251 } 8252 case RISCVISD::FSR: 8253 case RISCVISD::FSL: 8254 case RISCVISD::FSRW: 8255 case RISCVISD::FSLW: { 8256 bool IsWInstruction = 8257 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8258 unsigned BitWidth = 8259 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8260 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8261 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8262 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8263 return SDValue(N, 0); 8264 8265 break; 8266 } 8267 case RISCVISD::FMV_X_ANYEXTH: 8268 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8269 SDLoc DL(N); 8270 SDValue Op0 = N->getOperand(0); 8271 MVT VT = N->getSimpleValueType(0); 8272 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8273 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8274 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8275 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8276 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8277 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8278 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8279 assert(Op0.getOperand(0).getValueType() == VT && 8280 "Unexpected value type!"); 8281 return Op0.getOperand(0); 8282 } 8283 8284 // This is a target-specific version of a DAGCombine performed in 8285 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8286 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8287 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8288 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8289 !Op0.getNode()->hasOneUse()) 8290 break; 8291 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8292 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8293 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8294 if (Op0.getOpcode() == ISD::FNEG) 8295 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8296 DAG.getConstant(SignBit, DL, VT)); 8297 8298 assert(Op0.getOpcode() == ISD::FABS); 8299 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8300 DAG.getConstant(~SignBit, DL, VT)); 8301 } 8302 case ISD::ADD: 8303 return performADDCombine(N, DAG, Subtarget); 8304 case ISD::SUB: 8305 return performSUBCombine(N, DAG); 8306 case ISD::AND: 8307 return performANDCombine(N, DAG); 8308 case ISD::OR: 8309 return performORCombine(N, DAG, Subtarget); 8310 case ISD::XOR: 8311 return performXORCombine(N, DAG); 8312 case ISD::SIGN_EXTEND_INREG: 8313 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8314 case ISD::ZERO_EXTEND: 8315 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8316 // type legalization. This is safe because fp_to_uint produces poison if 8317 // it overflows. 8318 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8319 SDValue Src = N->getOperand(0); 8320 if (Src.getOpcode() == ISD::FP_TO_UINT && 8321 isTypeLegal(Src.getOperand(0).getValueType())) 8322 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8323 Src.getOperand(0)); 8324 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8325 isTypeLegal(Src.getOperand(1).getValueType())) { 8326 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8327 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8328 Src.getOperand(0), Src.getOperand(1)); 8329 DCI.CombineTo(N, Res); 8330 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8331 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8332 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8333 } 8334 } 8335 return SDValue(); 8336 case RISCVISD::SELECT_CC: { 8337 // Transform 8338 SDValue LHS = N->getOperand(0); 8339 SDValue RHS = N->getOperand(1); 8340 SDValue TrueV = N->getOperand(3); 8341 SDValue FalseV = N->getOperand(4); 8342 8343 // If the True and False values are the same, we don't need a select_cc. 8344 if (TrueV == FalseV) 8345 return TrueV; 8346 8347 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8348 if (!ISD::isIntEqualitySetCC(CCVal)) 8349 break; 8350 8351 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8352 // (select_cc X, Y, lt, trueV, falseV) 8353 // Sometimes the setcc is introduced after select_cc has been formed. 8354 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8355 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8356 // If we're looking for eq 0 instead of ne 0, we need to invert the 8357 // condition. 8358 bool Invert = CCVal == ISD::SETEQ; 8359 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8360 if (Invert) 8361 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8362 8363 SDLoc DL(N); 8364 RHS = LHS.getOperand(1); 8365 LHS = LHS.getOperand(0); 8366 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8367 8368 SDValue TargetCC = DAG.getCondCode(CCVal); 8369 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8370 {LHS, RHS, TargetCC, TrueV, FalseV}); 8371 } 8372 8373 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8374 // (select_cc X, Y, eq/ne, trueV, falseV) 8375 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8376 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8377 {LHS.getOperand(0), LHS.getOperand(1), 8378 N->getOperand(2), TrueV, FalseV}); 8379 // (select_cc X, 1, setne, trueV, falseV) -> 8380 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8381 // This can occur when legalizing some floating point comparisons. 8382 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8383 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8384 SDLoc DL(N); 8385 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8386 SDValue TargetCC = DAG.getCondCode(CCVal); 8387 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8388 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8389 {LHS, RHS, TargetCC, TrueV, FalseV}); 8390 } 8391 8392 break; 8393 } 8394 case RISCVISD::BR_CC: { 8395 SDValue LHS = N->getOperand(1); 8396 SDValue RHS = N->getOperand(2); 8397 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8398 if (!ISD::isIntEqualitySetCC(CCVal)) 8399 break; 8400 8401 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8402 // (br_cc X, Y, lt, dest) 8403 // Sometimes the setcc is introduced after br_cc has been formed. 8404 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8405 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8406 // If we're looking for eq 0 instead of ne 0, we need to invert the 8407 // condition. 8408 bool Invert = CCVal == ISD::SETEQ; 8409 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8410 if (Invert) 8411 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8412 8413 SDLoc DL(N); 8414 RHS = LHS.getOperand(1); 8415 LHS = LHS.getOperand(0); 8416 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8417 8418 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8419 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8420 N->getOperand(4)); 8421 } 8422 8423 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8424 // (br_cc X, Y, eq/ne, trueV, falseV) 8425 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8426 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8427 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8428 N->getOperand(3), N->getOperand(4)); 8429 8430 // (br_cc X, 1, setne, br_cc) -> 8431 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8432 // This can occur when legalizing some floating point comparisons. 8433 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8434 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8435 SDLoc DL(N); 8436 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8437 SDValue TargetCC = DAG.getCondCode(CCVal); 8438 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8439 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8440 N->getOperand(0), LHS, RHS, TargetCC, 8441 N->getOperand(4)); 8442 } 8443 break; 8444 } 8445 case ISD::BITREVERSE: 8446 return performBITREVERSECombine(N, DAG, Subtarget); 8447 case ISD::FP_TO_SINT: 8448 case ISD::FP_TO_UINT: 8449 return performFP_TO_INTCombine(N, DCI, Subtarget); 8450 case ISD::FP_TO_SINT_SAT: 8451 case ISD::FP_TO_UINT_SAT: 8452 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8453 case ISD::FCOPYSIGN: { 8454 EVT VT = N->getValueType(0); 8455 if (!VT.isVector()) 8456 break; 8457 // There is a form of VFSGNJ which injects the negated sign of its second 8458 // operand. Try and bubble any FNEG up after the extend/round to produce 8459 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8460 // TRUNC=1. 8461 SDValue In2 = N->getOperand(1); 8462 // Avoid cases where the extend/round has multiple uses, as duplicating 8463 // those is typically more expensive than removing a fneg. 8464 if (!In2.hasOneUse()) 8465 break; 8466 if (In2.getOpcode() != ISD::FP_EXTEND && 8467 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8468 break; 8469 In2 = In2.getOperand(0); 8470 if (In2.getOpcode() != ISD::FNEG) 8471 break; 8472 SDLoc DL(N); 8473 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8474 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8475 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8476 } 8477 case ISD::MGATHER: 8478 case ISD::MSCATTER: 8479 case ISD::VP_GATHER: 8480 case ISD::VP_SCATTER: { 8481 if (!DCI.isBeforeLegalize()) 8482 break; 8483 SDValue Index, ScaleOp; 8484 bool IsIndexScaled = false; 8485 bool IsIndexSigned = false; 8486 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8487 Index = VPGSN->getIndex(); 8488 ScaleOp = VPGSN->getScale(); 8489 IsIndexScaled = VPGSN->isIndexScaled(); 8490 IsIndexSigned = VPGSN->isIndexSigned(); 8491 } else { 8492 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8493 Index = MGSN->getIndex(); 8494 ScaleOp = MGSN->getScale(); 8495 IsIndexScaled = MGSN->isIndexScaled(); 8496 IsIndexSigned = MGSN->isIndexSigned(); 8497 } 8498 EVT IndexVT = Index.getValueType(); 8499 MVT XLenVT = Subtarget.getXLenVT(); 8500 // RISCV indexed loads only support the "unsigned unscaled" addressing 8501 // mode, so anything else must be manually legalized. 8502 bool NeedsIdxLegalization = 8503 IsIndexScaled || 8504 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8505 if (!NeedsIdxLegalization) 8506 break; 8507 8508 SDLoc DL(N); 8509 8510 // Any index legalization should first promote to XLenVT, so we don't lose 8511 // bits when scaling. This may create an illegal index type so we let 8512 // LLVM's legalization take care of the splitting. 8513 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8514 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8515 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8516 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8517 DL, IndexVT, Index); 8518 } 8519 8520 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8521 if (IsIndexScaled && Scale != 1) { 8522 // Manually scale the indices by the element size. 8523 // TODO: Sanitize the scale operand here? 8524 // TODO: For VP nodes, should we use VP_SHL here? 8525 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8526 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8527 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8528 } 8529 8530 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8531 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8532 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8533 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8534 VPGN->getScale(), VPGN->getMask(), 8535 VPGN->getVectorLength()}, 8536 VPGN->getMemOperand(), NewIndexTy); 8537 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8538 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8539 {VPSN->getChain(), VPSN->getValue(), 8540 VPSN->getBasePtr(), Index, VPSN->getScale(), 8541 VPSN->getMask(), VPSN->getVectorLength()}, 8542 VPSN->getMemOperand(), NewIndexTy); 8543 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8544 return DAG.getMaskedGather( 8545 N->getVTList(), MGN->getMemoryVT(), DL, 8546 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8547 MGN->getBasePtr(), Index, MGN->getScale()}, 8548 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8549 const auto *MSN = cast<MaskedScatterSDNode>(N); 8550 return DAG.getMaskedScatter( 8551 N->getVTList(), MSN->getMemoryVT(), DL, 8552 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8553 Index, MSN->getScale()}, 8554 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8555 } 8556 case RISCVISD::SRA_VL: 8557 case RISCVISD::SRL_VL: 8558 case RISCVISD::SHL_VL: { 8559 SDValue ShAmt = N->getOperand(1); 8560 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8561 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8562 SDLoc DL(N); 8563 SDValue VL = N->getOperand(3); 8564 EVT VT = N->getValueType(0); 8565 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8566 ShAmt.getOperand(1), VL); 8567 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8568 N->getOperand(2), N->getOperand(3)); 8569 } 8570 break; 8571 } 8572 case ISD::SRA: 8573 case ISD::SRL: 8574 case ISD::SHL: { 8575 SDValue ShAmt = N->getOperand(1); 8576 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8577 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8578 SDLoc DL(N); 8579 EVT VT = N->getValueType(0); 8580 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8581 ShAmt.getOperand(1), 8582 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8583 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8584 } 8585 break; 8586 } 8587 case RISCVISD::ADD_VL: 8588 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8589 return V; 8590 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8591 case RISCVISD::SUB_VL: 8592 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8593 case RISCVISD::VWADD_W_VL: 8594 case RISCVISD::VWADDU_W_VL: 8595 case RISCVISD::VWSUB_W_VL: 8596 case RISCVISD::VWSUBU_W_VL: 8597 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8598 case RISCVISD::MUL_VL: 8599 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8600 return V; 8601 // Mul is commutative. 8602 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8603 case ISD::STORE: { 8604 auto *Store = cast<StoreSDNode>(N); 8605 SDValue Val = Store->getValue(); 8606 // Combine store of vmv.x.s to vse with VL of 1. 8607 // FIXME: Support FP. 8608 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8609 SDValue Src = Val.getOperand(0); 8610 EVT VecVT = Src.getValueType(); 8611 EVT MemVT = Store->getMemoryVT(); 8612 // The memory VT and the element type must match. 8613 if (VecVT.getVectorElementType() == MemVT) { 8614 SDLoc DL(N); 8615 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8616 return DAG.getStoreVP( 8617 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8618 DAG.getConstant(1, DL, MaskVT), 8619 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8620 Store->getMemOperand(), Store->getAddressingMode(), 8621 Store->isTruncatingStore(), /*IsCompress*/ false); 8622 } 8623 } 8624 8625 break; 8626 } 8627 case ISD::SPLAT_VECTOR: { 8628 EVT VT = N->getValueType(0); 8629 // Only perform this combine on legal MVT types. 8630 if (!isTypeLegal(VT)) 8631 break; 8632 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8633 DAG, Subtarget)) 8634 return Gather; 8635 break; 8636 } 8637 case RISCVISD::VMV_V_X_VL: { 8638 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8639 // scalar input. 8640 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8641 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8642 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8643 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8644 return SDValue(N, 0); 8645 8646 break; 8647 } 8648 case ISD::INTRINSIC_WO_CHAIN: { 8649 unsigned IntNo = N->getConstantOperandVal(0); 8650 switch (IntNo) { 8651 // By default we do not combine any intrinsic. 8652 default: 8653 return SDValue(); 8654 case Intrinsic::riscv_vcpop: 8655 case Intrinsic::riscv_vcpop_mask: 8656 case Intrinsic::riscv_vfirst: 8657 case Intrinsic::riscv_vfirst_mask: { 8658 SDValue VL = N->getOperand(2); 8659 if (IntNo == Intrinsic::riscv_vcpop_mask || 8660 IntNo == Intrinsic::riscv_vfirst_mask) 8661 VL = N->getOperand(3); 8662 if (!isNullConstant(VL)) 8663 return SDValue(); 8664 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8665 SDLoc DL(N); 8666 EVT VT = N->getValueType(0); 8667 if (IntNo == Intrinsic::riscv_vfirst || 8668 IntNo == Intrinsic::riscv_vfirst_mask) 8669 return DAG.getConstant(-1, DL, VT); 8670 return DAG.getConstant(0, DL, VT); 8671 } 8672 } 8673 } 8674 } 8675 8676 return SDValue(); 8677 } 8678 8679 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8680 const SDNode *N, CombineLevel Level) const { 8681 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8682 // materialised in fewer instructions than `(OP _, c1)`: 8683 // 8684 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8685 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8686 SDValue N0 = N->getOperand(0); 8687 EVT Ty = N0.getValueType(); 8688 if (Ty.isScalarInteger() && 8689 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8690 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8691 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8692 if (C1 && C2) { 8693 const APInt &C1Int = C1->getAPIntValue(); 8694 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8695 8696 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8697 // and the combine should happen, to potentially allow further combines 8698 // later. 8699 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8700 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8701 return true; 8702 8703 // We can materialise `c1` in an add immediate, so it's "free", and the 8704 // combine should be prevented. 8705 if (C1Int.getMinSignedBits() <= 64 && 8706 isLegalAddImmediate(C1Int.getSExtValue())) 8707 return false; 8708 8709 // Neither constant will fit into an immediate, so find materialisation 8710 // costs. 8711 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8712 Subtarget.getFeatureBits(), 8713 /*CompressionCost*/true); 8714 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8715 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8716 /*CompressionCost*/true); 8717 8718 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8719 // combine should be prevented. 8720 if (C1Cost < ShiftedC1Cost) 8721 return false; 8722 } 8723 } 8724 return true; 8725 } 8726 8727 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8728 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8729 TargetLoweringOpt &TLO) const { 8730 // Delay this optimization as late as possible. 8731 if (!TLO.LegalOps) 8732 return false; 8733 8734 EVT VT = Op.getValueType(); 8735 if (VT.isVector()) 8736 return false; 8737 8738 // Only handle AND for now. 8739 if (Op.getOpcode() != ISD::AND) 8740 return false; 8741 8742 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8743 if (!C) 8744 return false; 8745 8746 const APInt &Mask = C->getAPIntValue(); 8747 8748 // Clear all non-demanded bits initially. 8749 APInt ShrunkMask = Mask & DemandedBits; 8750 8751 // Try to make a smaller immediate by setting undemanded bits. 8752 8753 APInt ExpandedMask = Mask | ~DemandedBits; 8754 8755 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8756 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8757 }; 8758 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8759 if (NewMask == Mask) 8760 return true; 8761 SDLoc DL(Op); 8762 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8763 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8764 return TLO.CombineTo(Op, NewOp); 8765 }; 8766 8767 // If the shrunk mask fits in sign extended 12 bits, let the target 8768 // independent code apply it. 8769 if (ShrunkMask.isSignedIntN(12)) 8770 return false; 8771 8772 // Preserve (and X, 0xffff) when zext.h is supported. 8773 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8774 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8775 if (IsLegalMask(NewMask)) 8776 return UseMask(NewMask); 8777 } 8778 8779 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8780 if (VT == MVT::i64) { 8781 APInt NewMask = APInt(64, 0xffffffff); 8782 if (IsLegalMask(NewMask)) 8783 return UseMask(NewMask); 8784 } 8785 8786 // For the remaining optimizations, we need to be able to make a negative 8787 // number through a combination of mask and undemanded bits. 8788 if (!ExpandedMask.isNegative()) 8789 return false; 8790 8791 // What is the fewest number of bits we need to represent the negative number. 8792 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8793 8794 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8795 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8796 APInt NewMask = ShrunkMask; 8797 if (MinSignedBits <= 12) 8798 NewMask.setBitsFrom(11); 8799 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8800 NewMask.setBitsFrom(31); 8801 else 8802 return false; 8803 8804 // Check that our new mask is a subset of the demanded mask. 8805 assert(IsLegalMask(NewMask)); 8806 return UseMask(NewMask); 8807 } 8808 8809 static void computeGREV(APInt &Src, unsigned ShAmt) { 8810 ShAmt &= Src.getBitWidth() - 1; 8811 uint64_t x = Src.getZExtValue(); 8812 if (ShAmt & 1) 8813 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 8814 if (ShAmt & 2) 8815 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 8816 if (ShAmt & 4) 8817 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 8818 if (ShAmt & 8) 8819 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 8820 if (ShAmt & 16) 8821 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 8822 if (ShAmt & 32) 8823 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 8824 Src = x; 8825 } 8826 8827 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8828 KnownBits &Known, 8829 const APInt &DemandedElts, 8830 const SelectionDAG &DAG, 8831 unsigned Depth) const { 8832 unsigned BitWidth = Known.getBitWidth(); 8833 unsigned Opc = Op.getOpcode(); 8834 assert((Opc >= ISD::BUILTIN_OP_END || 8835 Opc == ISD::INTRINSIC_WO_CHAIN || 8836 Opc == ISD::INTRINSIC_W_CHAIN || 8837 Opc == ISD::INTRINSIC_VOID) && 8838 "Should use MaskedValueIsZero if you don't know whether Op" 8839 " is a target node!"); 8840 8841 Known.resetAll(); 8842 switch (Opc) { 8843 default: break; 8844 case RISCVISD::SELECT_CC: { 8845 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8846 // If we don't know any bits, early out. 8847 if (Known.isUnknown()) 8848 break; 8849 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8850 8851 // Only known if known in both the LHS and RHS. 8852 Known = KnownBits::commonBits(Known, Known2); 8853 break; 8854 } 8855 case RISCVISD::REMUW: { 8856 KnownBits Known2; 8857 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8858 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8859 // We only care about the lower 32 bits. 8860 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8861 // Restore the original width by sign extending. 8862 Known = Known.sext(BitWidth); 8863 break; 8864 } 8865 case RISCVISD::DIVUW: { 8866 KnownBits Known2; 8867 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8868 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8869 // We only care about the lower 32 bits. 8870 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8871 // Restore the original width by sign extending. 8872 Known = Known.sext(BitWidth); 8873 break; 8874 } 8875 case RISCVISD::CTZW: { 8876 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8877 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 8878 unsigned LowBits = Log2_32(PossibleTZ) + 1; 8879 Known.Zero.setBitsFrom(LowBits); 8880 break; 8881 } 8882 case RISCVISD::CLZW: { 8883 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8884 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 8885 unsigned LowBits = Log2_32(PossibleLZ) + 1; 8886 Known.Zero.setBitsFrom(LowBits); 8887 break; 8888 } 8889 case RISCVISD::GREV: { 8890 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8891 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8892 unsigned ShAmt = C->getZExtValue(); 8893 computeGREV(Known.Zero, ShAmt); 8894 computeGREV(Known.One, ShAmt); 8895 } 8896 break; 8897 } 8898 case RISCVISD::READ_VLENB: { 8899 // If we know the minimum VLen from Zvl extensions, we can use that to 8900 // determine the trailing zeros of VLENB. 8901 // FIXME: Limit to 128 bit vectors until we have more testing. 8902 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 8903 if (MinVLenB > 0) 8904 Known.Zero.setLowBits(Log2_32(MinVLenB)); 8905 // We assume VLENB is no more than 65536 / 8 bytes. 8906 Known.Zero.setBitsFrom(14); 8907 break; 8908 } 8909 case ISD::INTRINSIC_W_CHAIN: 8910 case ISD::INTRINSIC_WO_CHAIN: { 8911 unsigned IntNo = 8912 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 8913 switch (IntNo) { 8914 default: 8915 // We can't do anything for most intrinsics. 8916 break; 8917 case Intrinsic::riscv_vsetvli: 8918 case Intrinsic::riscv_vsetvlimax: 8919 case Intrinsic::riscv_vsetvli_opt: 8920 case Intrinsic::riscv_vsetvlimax_opt: 8921 // Assume that VL output is positive and would fit in an int32_t. 8922 // TODO: VLEN might be capped at 16 bits in a future V spec update. 8923 if (BitWidth >= 32) 8924 Known.Zero.setBitsFrom(31); 8925 break; 8926 } 8927 break; 8928 } 8929 } 8930 } 8931 8932 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 8933 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 8934 unsigned Depth) const { 8935 switch (Op.getOpcode()) { 8936 default: 8937 break; 8938 case RISCVISD::SELECT_CC: { 8939 unsigned Tmp = 8940 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 8941 if (Tmp == 1) return 1; // Early out. 8942 unsigned Tmp2 = 8943 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 8944 return std::min(Tmp, Tmp2); 8945 } 8946 case RISCVISD::SLLW: 8947 case RISCVISD::SRAW: 8948 case RISCVISD::SRLW: 8949 case RISCVISD::DIVW: 8950 case RISCVISD::DIVUW: 8951 case RISCVISD::REMUW: 8952 case RISCVISD::ROLW: 8953 case RISCVISD::RORW: 8954 case RISCVISD::GREVW: 8955 case RISCVISD::GORCW: 8956 case RISCVISD::FSLW: 8957 case RISCVISD::FSRW: 8958 case RISCVISD::SHFLW: 8959 case RISCVISD::UNSHFLW: 8960 case RISCVISD::BCOMPRESSW: 8961 case RISCVISD::BDECOMPRESSW: 8962 case RISCVISD::BFPW: 8963 case RISCVISD::FCVT_W_RV64: 8964 case RISCVISD::FCVT_WU_RV64: 8965 case RISCVISD::STRICT_FCVT_W_RV64: 8966 case RISCVISD::STRICT_FCVT_WU_RV64: 8967 // TODO: As the result is sign-extended, this is conservatively correct. A 8968 // more precise answer could be calculated for SRAW depending on known 8969 // bits in the shift amount. 8970 return 33; 8971 case RISCVISD::SHFL: 8972 case RISCVISD::UNSHFL: { 8973 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 8974 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 8975 // will stay within the upper 32 bits. If there were more than 32 sign bits 8976 // before there will be at least 33 sign bits after. 8977 if (Op.getValueType() == MVT::i64 && 8978 isa<ConstantSDNode>(Op.getOperand(1)) && 8979 (Op.getConstantOperandVal(1) & 0x10) == 0) { 8980 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 8981 if (Tmp > 32) 8982 return 33; 8983 } 8984 break; 8985 } 8986 case RISCVISD::VMV_X_S: { 8987 // The number of sign bits of the scalar result is computed by obtaining the 8988 // element type of the input vector operand, subtracting its width from the 8989 // XLEN, and then adding one (sign bit within the element type). If the 8990 // element type is wider than XLen, the least-significant XLEN bits are 8991 // taken. 8992 unsigned XLen = Subtarget.getXLen(); 8993 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 8994 if (EltBits <= XLen) 8995 return XLen - EltBits + 1; 8996 break; 8997 } 8998 } 8999 9000 return 1; 9001 } 9002 9003 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9004 MachineBasicBlock *BB) { 9005 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9006 9007 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9008 // Should the count have wrapped while it was being read, we need to try 9009 // again. 9010 // ... 9011 // read: 9012 // rdcycleh x3 # load high word of cycle 9013 // rdcycle x2 # load low word of cycle 9014 // rdcycleh x4 # load high word of cycle 9015 // bne x3, x4, read # check if high word reads match, otherwise try again 9016 // ... 9017 9018 MachineFunction &MF = *BB->getParent(); 9019 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9020 MachineFunction::iterator It = ++BB->getIterator(); 9021 9022 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9023 MF.insert(It, LoopMBB); 9024 9025 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9026 MF.insert(It, DoneMBB); 9027 9028 // Transfer the remainder of BB and its successor edges to DoneMBB. 9029 DoneMBB->splice(DoneMBB->begin(), BB, 9030 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9031 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9032 9033 BB->addSuccessor(LoopMBB); 9034 9035 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9036 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9037 Register LoReg = MI.getOperand(0).getReg(); 9038 Register HiReg = MI.getOperand(1).getReg(); 9039 DebugLoc DL = MI.getDebugLoc(); 9040 9041 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9042 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9043 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9044 .addReg(RISCV::X0); 9045 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9046 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9047 .addReg(RISCV::X0); 9048 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9049 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9050 .addReg(RISCV::X0); 9051 9052 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9053 .addReg(HiReg) 9054 .addReg(ReadAgainReg) 9055 .addMBB(LoopMBB); 9056 9057 LoopMBB->addSuccessor(LoopMBB); 9058 LoopMBB->addSuccessor(DoneMBB); 9059 9060 MI.eraseFromParent(); 9061 9062 return DoneMBB; 9063 } 9064 9065 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9066 MachineBasicBlock *BB) { 9067 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9068 9069 MachineFunction &MF = *BB->getParent(); 9070 DebugLoc DL = MI.getDebugLoc(); 9071 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9072 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9073 Register LoReg = MI.getOperand(0).getReg(); 9074 Register HiReg = MI.getOperand(1).getReg(); 9075 Register SrcReg = MI.getOperand(2).getReg(); 9076 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9077 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9078 9079 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9080 RI); 9081 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9082 MachineMemOperand *MMOLo = 9083 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9084 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9085 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9086 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9087 .addFrameIndex(FI) 9088 .addImm(0) 9089 .addMemOperand(MMOLo); 9090 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9091 .addFrameIndex(FI) 9092 .addImm(4) 9093 .addMemOperand(MMOHi); 9094 MI.eraseFromParent(); // The pseudo instruction is gone now. 9095 return BB; 9096 } 9097 9098 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9099 MachineBasicBlock *BB) { 9100 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9101 "Unexpected instruction"); 9102 9103 MachineFunction &MF = *BB->getParent(); 9104 DebugLoc DL = MI.getDebugLoc(); 9105 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9106 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9107 Register DstReg = MI.getOperand(0).getReg(); 9108 Register LoReg = MI.getOperand(1).getReg(); 9109 Register HiReg = MI.getOperand(2).getReg(); 9110 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9111 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9112 9113 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9114 MachineMemOperand *MMOLo = 9115 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9116 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9117 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9118 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9119 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9120 .addFrameIndex(FI) 9121 .addImm(0) 9122 .addMemOperand(MMOLo); 9123 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9124 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9125 .addFrameIndex(FI) 9126 .addImm(4) 9127 .addMemOperand(MMOHi); 9128 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9129 MI.eraseFromParent(); // The pseudo instruction is gone now. 9130 return BB; 9131 } 9132 9133 static bool isSelectPseudo(MachineInstr &MI) { 9134 switch (MI.getOpcode()) { 9135 default: 9136 return false; 9137 case RISCV::Select_GPR_Using_CC_GPR: 9138 case RISCV::Select_FPR16_Using_CC_GPR: 9139 case RISCV::Select_FPR32_Using_CC_GPR: 9140 case RISCV::Select_FPR64_Using_CC_GPR: 9141 return true; 9142 } 9143 } 9144 9145 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9146 unsigned RelOpcode, unsigned EqOpcode, 9147 const RISCVSubtarget &Subtarget) { 9148 DebugLoc DL = MI.getDebugLoc(); 9149 Register DstReg = MI.getOperand(0).getReg(); 9150 Register Src1Reg = MI.getOperand(1).getReg(); 9151 Register Src2Reg = MI.getOperand(2).getReg(); 9152 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9153 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9154 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9155 9156 // Save the current FFLAGS. 9157 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9158 9159 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9160 .addReg(Src1Reg) 9161 .addReg(Src2Reg); 9162 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9163 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9164 9165 // Restore the FFLAGS. 9166 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9167 .addReg(SavedFFlags, RegState::Kill); 9168 9169 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9170 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9171 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9172 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9173 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9174 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9175 9176 // Erase the pseudoinstruction. 9177 MI.eraseFromParent(); 9178 return BB; 9179 } 9180 9181 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9182 MachineBasicBlock *BB, 9183 const RISCVSubtarget &Subtarget) { 9184 // To "insert" Select_* instructions, we actually have to insert the triangle 9185 // control-flow pattern. The incoming instructions know the destination vreg 9186 // to set, the condition code register to branch on, the true/false values to 9187 // select between, and the condcode to use to select the appropriate branch. 9188 // 9189 // We produce the following control flow: 9190 // HeadMBB 9191 // | \ 9192 // | IfFalseMBB 9193 // | / 9194 // TailMBB 9195 // 9196 // When we find a sequence of selects we attempt to optimize their emission 9197 // by sharing the control flow. Currently we only handle cases where we have 9198 // multiple selects with the exact same condition (same LHS, RHS and CC). 9199 // The selects may be interleaved with other instructions if the other 9200 // instructions meet some requirements we deem safe: 9201 // - They are debug instructions. Otherwise, 9202 // - They do not have side-effects, do not access memory and their inputs do 9203 // not depend on the results of the select pseudo-instructions. 9204 // The TrueV/FalseV operands of the selects cannot depend on the result of 9205 // previous selects in the sequence. 9206 // These conditions could be further relaxed. See the X86 target for a 9207 // related approach and more information. 9208 Register LHS = MI.getOperand(1).getReg(); 9209 Register RHS = MI.getOperand(2).getReg(); 9210 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9211 9212 SmallVector<MachineInstr *, 4> SelectDebugValues; 9213 SmallSet<Register, 4> SelectDests; 9214 SelectDests.insert(MI.getOperand(0).getReg()); 9215 9216 MachineInstr *LastSelectPseudo = &MI; 9217 9218 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9219 SequenceMBBI != E; ++SequenceMBBI) { 9220 if (SequenceMBBI->isDebugInstr()) 9221 continue; 9222 else if (isSelectPseudo(*SequenceMBBI)) { 9223 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9224 SequenceMBBI->getOperand(2).getReg() != RHS || 9225 SequenceMBBI->getOperand(3).getImm() != CC || 9226 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9227 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9228 break; 9229 LastSelectPseudo = &*SequenceMBBI; 9230 SequenceMBBI->collectDebugValues(SelectDebugValues); 9231 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9232 } else { 9233 if (SequenceMBBI->hasUnmodeledSideEffects() || 9234 SequenceMBBI->mayLoadOrStore()) 9235 break; 9236 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9237 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9238 })) 9239 break; 9240 } 9241 } 9242 9243 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9244 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9245 DebugLoc DL = MI.getDebugLoc(); 9246 MachineFunction::iterator I = ++BB->getIterator(); 9247 9248 MachineBasicBlock *HeadMBB = BB; 9249 MachineFunction *F = BB->getParent(); 9250 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9251 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9252 9253 F->insert(I, IfFalseMBB); 9254 F->insert(I, TailMBB); 9255 9256 // Transfer debug instructions associated with the selects to TailMBB. 9257 for (MachineInstr *DebugInstr : SelectDebugValues) { 9258 TailMBB->push_back(DebugInstr->removeFromParent()); 9259 } 9260 9261 // Move all instructions after the sequence to TailMBB. 9262 TailMBB->splice(TailMBB->end(), HeadMBB, 9263 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9264 // Update machine-CFG edges by transferring all successors of the current 9265 // block to the new block which will contain the Phi nodes for the selects. 9266 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9267 // Set the successors for HeadMBB. 9268 HeadMBB->addSuccessor(IfFalseMBB); 9269 HeadMBB->addSuccessor(TailMBB); 9270 9271 // Insert appropriate branch. 9272 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9273 .addReg(LHS) 9274 .addReg(RHS) 9275 .addMBB(TailMBB); 9276 9277 // IfFalseMBB just falls through to TailMBB. 9278 IfFalseMBB->addSuccessor(TailMBB); 9279 9280 // Create PHIs for all of the select pseudo-instructions. 9281 auto SelectMBBI = MI.getIterator(); 9282 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9283 auto InsertionPoint = TailMBB->begin(); 9284 while (SelectMBBI != SelectEnd) { 9285 auto Next = std::next(SelectMBBI); 9286 if (isSelectPseudo(*SelectMBBI)) { 9287 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9288 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9289 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9290 .addReg(SelectMBBI->getOperand(4).getReg()) 9291 .addMBB(HeadMBB) 9292 .addReg(SelectMBBI->getOperand(5).getReg()) 9293 .addMBB(IfFalseMBB); 9294 SelectMBBI->eraseFromParent(); 9295 } 9296 SelectMBBI = Next; 9297 } 9298 9299 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9300 return TailMBB; 9301 } 9302 9303 MachineBasicBlock * 9304 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9305 MachineBasicBlock *BB) const { 9306 switch (MI.getOpcode()) { 9307 default: 9308 llvm_unreachable("Unexpected instr type to insert"); 9309 case RISCV::ReadCycleWide: 9310 assert(!Subtarget.is64Bit() && 9311 "ReadCycleWrite is only to be used on riscv32"); 9312 return emitReadCycleWidePseudo(MI, BB); 9313 case RISCV::Select_GPR_Using_CC_GPR: 9314 case RISCV::Select_FPR16_Using_CC_GPR: 9315 case RISCV::Select_FPR32_Using_CC_GPR: 9316 case RISCV::Select_FPR64_Using_CC_GPR: 9317 return emitSelectPseudo(MI, BB, Subtarget); 9318 case RISCV::BuildPairF64Pseudo: 9319 return emitBuildPairF64Pseudo(MI, BB); 9320 case RISCV::SplitF64Pseudo: 9321 return emitSplitF64Pseudo(MI, BB); 9322 case RISCV::PseudoQuietFLE_H: 9323 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9324 case RISCV::PseudoQuietFLT_H: 9325 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9326 case RISCV::PseudoQuietFLE_S: 9327 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9328 case RISCV::PseudoQuietFLT_S: 9329 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9330 case RISCV::PseudoQuietFLE_D: 9331 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9332 case RISCV::PseudoQuietFLT_D: 9333 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9334 } 9335 } 9336 9337 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9338 SDNode *Node) const { 9339 // Add FRM dependency to any instructions with dynamic rounding mode. 9340 unsigned Opc = MI.getOpcode(); 9341 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9342 if (Idx < 0) 9343 return; 9344 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9345 return; 9346 // If the instruction already reads FRM, don't add another read. 9347 if (MI.readsRegister(RISCV::FRM)) 9348 return; 9349 MI.addOperand( 9350 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9351 } 9352 9353 // Calling Convention Implementation. 9354 // The expectations for frontend ABI lowering vary from target to target. 9355 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9356 // details, but this is a longer term goal. For now, we simply try to keep the 9357 // role of the frontend as simple and well-defined as possible. The rules can 9358 // be summarised as: 9359 // * Never split up large scalar arguments. We handle them here. 9360 // * If a hardfloat calling convention is being used, and the struct may be 9361 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9362 // available, then pass as two separate arguments. If either the GPRs or FPRs 9363 // are exhausted, then pass according to the rule below. 9364 // * If a struct could never be passed in registers or directly in a stack 9365 // slot (as it is larger than 2*XLEN and the floating point rules don't 9366 // apply), then pass it using a pointer with the byval attribute. 9367 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9368 // word-sized array or a 2*XLEN scalar (depending on alignment). 9369 // * The frontend can determine whether a struct is returned by reference or 9370 // not based on its size and fields. If it will be returned by reference, the 9371 // frontend must modify the prototype so a pointer with the sret annotation is 9372 // passed as the first argument. This is not necessary for large scalar 9373 // returns. 9374 // * Struct return values and varargs should be coerced to structs containing 9375 // register-size fields in the same situations they would be for fixed 9376 // arguments. 9377 9378 static const MCPhysReg ArgGPRs[] = { 9379 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9380 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9381 }; 9382 static const MCPhysReg ArgFPR16s[] = { 9383 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9384 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9385 }; 9386 static const MCPhysReg ArgFPR32s[] = { 9387 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9388 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9389 }; 9390 static const MCPhysReg ArgFPR64s[] = { 9391 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9392 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9393 }; 9394 // This is an interim calling convention and it may be changed in the future. 9395 static const MCPhysReg ArgVRs[] = { 9396 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9397 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9398 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9399 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9400 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9401 RISCV::V20M2, RISCV::V22M2}; 9402 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9403 RISCV::V20M4}; 9404 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9405 9406 // Pass a 2*XLEN argument that has been split into two XLEN values through 9407 // registers or the stack as necessary. 9408 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9409 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9410 MVT ValVT2, MVT LocVT2, 9411 ISD::ArgFlagsTy ArgFlags2) { 9412 unsigned XLenInBytes = XLen / 8; 9413 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9414 // At least one half can be passed via register. 9415 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9416 VA1.getLocVT(), CCValAssign::Full)); 9417 } else { 9418 // Both halves must be passed on the stack, with proper alignment. 9419 Align StackAlign = 9420 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9421 State.addLoc( 9422 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9423 State.AllocateStack(XLenInBytes, StackAlign), 9424 VA1.getLocVT(), CCValAssign::Full)); 9425 State.addLoc(CCValAssign::getMem( 9426 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9427 LocVT2, CCValAssign::Full)); 9428 return false; 9429 } 9430 9431 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9432 // The second half can also be passed via register. 9433 State.addLoc( 9434 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9435 } else { 9436 // The second half is passed via the stack, without additional alignment. 9437 State.addLoc(CCValAssign::getMem( 9438 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9439 LocVT2, CCValAssign::Full)); 9440 } 9441 9442 return false; 9443 } 9444 9445 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9446 Optional<unsigned> FirstMaskArgument, 9447 CCState &State, const RISCVTargetLowering &TLI) { 9448 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9449 if (RC == &RISCV::VRRegClass) { 9450 // Assign the first mask argument to V0. 9451 // This is an interim calling convention and it may be changed in the 9452 // future. 9453 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9454 return State.AllocateReg(RISCV::V0); 9455 return State.AllocateReg(ArgVRs); 9456 } 9457 if (RC == &RISCV::VRM2RegClass) 9458 return State.AllocateReg(ArgVRM2s); 9459 if (RC == &RISCV::VRM4RegClass) 9460 return State.AllocateReg(ArgVRM4s); 9461 if (RC == &RISCV::VRM8RegClass) 9462 return State.AllocateReg(ArgVRM8s); 9463 llvm_unreachable("Unhandled register class for ValueType"); 9464 } 9465 9466 // Implements the RISC-V calling convention. Returns true upon failure. 9467 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9468 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9469 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9470 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9471 Optional<unsigned> FirstMaskArgument) { 9472 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9473 assert(XLen == 32 || XLen == 64); 9474 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9475 9476 // Any return value split in to more than two values can't be returned 9477 // directly. Vectors are returned via the available vector registers. 9478 if (!LocVT.isVector() && IsRet && ValNo > 1) 9479 return true; 9480 9481 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9482 // variadic argument, or if no F16/F32 argument registers are available. 9483 bool UseGPRForF16_F32 = true; 9484 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9485 // variadic argument, or if no F64 argument registers are available. 9486 bool UseGPRForF64 = true; 9487 9488 switch (ABI) { 9489 default: 9490 llvm_unreachable("Unexpected ABI"); 9491 case RISCVABI::ABI_ILP32: 9492 case RISCVABI::ABI_LP64: 9493 break; 9494 case RISCVABI::ABI_ILP32F: 9495 case RISCVABI::ABI_LP64F: 9496 UseGPRForF16_F32 = !IsFixed; 9497 break; 9498 case RISCVABI::ABI_ILP32D: 9499 case RISCVABI::ABI_LP64D: 9500 UseGPRForF16_F32 = !IsFixed; 9501 UseGPRForF64 = !IsFixed; 9502 break; 9503 } 9504 9505 // FPR16, FPR32, and FPR64 alias each other. 9506 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9507 UseGPRForF16_F32 = true; 9508 UseGPRForF64 = true; 9509 } 9510 9511 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9512 // similar local variables rather than directly checking against the target 9513 // ABI. 9514 9515 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9516 LocVT = XLenVT; 9517 LocInfo = CCValAssign::BCvt; 9518 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9519 LocVT = MVT::i64; 9520 LocInfo = CCValAssign::BCvt; 9521 } 9522 9523 // If this is a variadic argument, the RISC-V calling convention requires 9524 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9525 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9526 // be used regardless of whether the original argument was split during 9527 // legalisation or not. The argument will not be passed by registers if the 9528 // original type is larger than 2*XLEN, so the register alignment rule does 9529 // not apply. 9530 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9531 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9532 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9533 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9534 // Skip 'odd' register if necessary. 9535 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9536 State.AllocateReg(ArgGPRs); 9537 } 9538 9539 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9540 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9541 State.getPendingArgFlags(); 9542 9543 assert(PendingLocs.size() == PendingArgFlags.size() && 9544 "PendingLocs and PendingArgFlags out of sync"); 9545 9546 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9547 // registers are exhausted. 9548 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9549 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9550 "Can't lower f64 if it is split"); 9551 // Depending on available argument GPRS, f64 may be passed in a pair of 9552 // GPRs, split between a GPR and the stack, or passed completely on the 9553 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9554 // cases. 9555 Register Reg = State.AllocateReg(ArgGPRs); 9556 LocVT = MVT::i32; 9557 if (!Reg) { 9558 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9559 State.addLoc( 9560 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9561 return false; 9562 } 9563 if (!State.AllocateReg(ArgGPRs)) 9564 State.AllocateStack(4, Align(4)); 9565 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9566 return false; 9567 } 9568 9569 // Fixed-length vectors are located in the corresponding scalable-vector 9570 // container types. 9571 if (ValVT.isFixedLengthVector()) 9572 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9573 9574 // Split arguments might be passed indirectly, so keep track of the pending 9575 // values. Split vectors are passed via a mix of registers and indirectly, so 9576 // treat them as we would any other argument. 9577 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9578 LocVT = XLenVT; 9579 LocInfo = CCValAssign::Indirect; 9580 PendingLocs.push_back( 9581 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9582 PendingArgFlags.push_back(ArgFlags); 9583 if (!ArgFlags.isSplitEnd()) { 9584 return false; 9585 } 9586 } 9587 9588 // If the split argument only had two elements, it should be passed directly 9589 // in registers or on the stack. 9590 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9591 PendingLocs.size() <= 2) { 9592 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9593 // Apply the normal calling convention rules to the first half of the 9594 // split argument. 9595 CCValAssign VA = PendingLocs[0]; 9596 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9597 PendingLocs.clear(); 9598 PendingArgFlags.clear(); 9599 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9600 ArgFlags); 9601 } 9602 9603 // Allocate to a register if possible, or else a stack slot. 9604 Register Reg; 9605 unsigned StoreSizeBytes = XLen / 8; 9606 Align StackAlign = Align(XLen / 8); 9607 9608 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9609 Reg = State.AllocateReg(ArgFPR16s); 9610 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9611 Reg = State.AllocateReg(ArgFPR32s); 9612 else if (ValVT == MVT::f64 && !UseGPRForF64) 9613 Reg = State.AllocateReg(ArgFPR64s); 9614 else if (ValVT.isVector()) { 9615 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9616 if (!Reg) { 9617 // For return values, the vector must be passed fully via registers or 9618 // via the stack. 9619 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9620 // but we're using all of them. 9621 if (IsRet) 9622 return true; 9623 // Try using a GPR to pass the address 9624 if ((Reg = State.AllocateReg(ArgGPRs))) { 9625 LocVT = XLenVT; 9626 LocInfo = CCValAssign::Indirect; 9627 } else if (ValVT.isScalableVector()) { 9628 LocVT = XLenVT; 9629 LocInfo = CCValAssign::Indirect; 9630 } else { 9631 // Pass fixed-length vectors on the stack. 9632 LocVT = ValVT; 9633 StoreSizeBytes = ValVT.getStoreSize(); 9634 // Align vectors to their element sizes, being careful for vXi1 9635 // vectors. 9636 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9637 } 9638 } 9639 } else { 9640 Reg = State.AllocateReg(ArgGPRs); 9641 } 9642 9643 unsigned StackOffset = 9644 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9645 9646 // If we reach this point and PendingLocs is non-empty, we must be at the 9647 // end of a split argument that must be passed indirectly. 9648 if (!PendingLocs.empty()) { 9649 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9650 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9651 9652 for (auto &It : PendingLocs) { 9653 if (Reg) 9654 It.convertToReg(Reg); 9655 else 9656 It.convertToMem(StackOffset); 9657 State.addLoc(It); 9658 } 9659 PendingLocs.clear(); 9660 PendingArgFlags.clear(); 9661 return false; 9662 } 9663 9664 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9665 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9666 "Expected an XLenVT or vector types at this stage"); 9667 9668 if (Reg) { 9669 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9670 return false; 9671 } 9672 9673 // When a floating-point value is passed on the stack, no bit-conversion is 9674 // needed. 9675 if (ValVT.isFloatingPoint()) { 9676 LocVT = ValVT; 9677 LocInfo = CCValAssign::Full; 9678 } 9679 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9680 return false; 9681 } 9682 9683 template <typename ArgTy> 9684 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9685 for (const auto &ArgIdx : enumerate(Args)) { 9686 MVT ArgVT = ArgIdx.value().VT; 9687 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9688 return ArgIdx.index(); 9689 } 9690 return None; 9691 } 9692 9693 void RISCVTargetLowering::analyzeInputArgs( 9694 MachineFunction &MF, CCState &CCInfo, 9695 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9696 RISCVCCAssignFn Fn) const { 9697 unsigned NumArgs = Ins.size(); 9698 FunctionType *FType = MF.getFunction().getFunctionType(); 9699 9700 Optional<unsigned> FirstMaskArgument; 9701 if (Subtarget.hasVInstructions()) 9702 FirstMaskArgument = preAssignMask(Ins); 9703 9704 for (unsigned i = 0; i != NumArgs; ++i) { 9705 MVT ArgVT = Ins[i].VT; 9706 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9707 9708 Type *ArgTy = nullptr; 9709 if (IsRet) 9710 ArgTy = FType->getReturnType(); 9711 else if (Ins[i].isOrigArg()) 9712 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9713 9714 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9715 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9716 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9717 FirstMaskArgument)) { 9718 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9719 << EVT(ArgVT).getEVTString() << '\n'); 9720 llvm_unreachable(nullptr); 9721 } 9722 } 9723 } 9724 9725 void RISCVTargetLowering::analyzeOutputArgs( 9726 MachineFunction &MF, CCState &CCInfo, 9727 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9728 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9729 unsigned NumArgs = Outs.size(); 9730 9731 Optional<unsigned> FirstMaskArgument; 9732 if (Subtarget.hasVInstructions()) 9733 FirstMaskArgument = preAssignMask(Outs); 9734 9735 for (unsigned i = 0; i != NumArgs; i++) { 9736 MVT ArgVT = Outs[i].VT; 9737 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9738 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9739 9740 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9741 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9742 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9743 FirstMaskArgument)) { 9744 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9745 << EVT(ArgVT).getEVTString() << "\n"); 9746 llvm_unreachable(nullptr); 9747 } 9748 } 9749 } 9750 9751 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9752 // values. 9753 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9754 const CCValAssign &VA, const SDLoc &DL, 9755 const RISCVSubtarget &Subtarget) { 9756 switch (VA.getLocInfo()) { 9757 default: 9758 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9759 case CCValAssign::Full: 9760 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9761 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9762 break; 9763 case CCValAssign::BCvt: 9764 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9765 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9766 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9767 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9768 else 9769 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9770 break; 9771 } 9772 return Val; 9773 } 9774 9775 // The caller is responsible for loading the full value if the argument is 9776 // passed with CCValAssign::Indirect. 9777 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9778 const CCValAssign &VA, const SDLoc &DL, 9779 const RISCVTargetLowering &TLI) { 9780 MachineFunction &MF = DAG.getMachineFunction(); 9781 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9782 EVT LocVT = VA.getLocVT(); 9783 SDValue Val; 9784 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9785 Register VReg = RegInfo.createVirtualRegister(RC); 9786 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9787 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9788 9789 if (VA.getLocInfo() == CCValAssign::Indirect) 9790 return Val; 9791 9792 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9793 } 9794 9795 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9796 const CCValAssign &VA, const SDLoc &DL, 9797 const RISCVSubtarget &Subtarget) { 9798 EVT LocVT = VA.getLocVT(); 9799 9800 switch (VA.getLocInfo()) { 9801 default: 9802 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9803 case CCValAssign::Full: 9804 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9805 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9806 break; 9807 case CCValAssign::BCvt: 9808 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9809 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9810 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9811 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9812 else 9813 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9814 break; 9815 } 9816 return Val; 9817 } 9818 9819 // The caller is responsible for loading the full value if the argument is 9820 // passed with CCValAssign::Indirect. 9821 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9822 const CCValAssign &VA, const SDLoc &DL) { 9823 MachineFunction &MF = DAG.getMachineFunction(); 9824 MachineFrameInfo &MFI = MF.getFrameInfo(); 9825 EVT LocVT = VA.getLocVT(); 9826 EVT ValVT = VA.getValVT(); 9827 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9828 if (ValVT.isScalableVector()) { 9829 // When the value is a scalable vector, we save the pointer which points to 9830 // the scalable vector value in the stack. The ValVT will be the pointer 9831 // type, instead of the scalable vector type. 9832 ValVT = LocVT; 9833 } 9834 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9835 /*IsImmutable=*/true); 9836 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9837 SDValue Val; 9838 9839 ISD::LoadExtType ExtType; 9840 switch (VA.getLocInfo()) { 9841 default: 9842 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9843 case CCValAssign::Full: 9844 case CCValAssign::Indirect: 9845 case CCValAssign::BCvt: 9846 ExtType = ISD::NON_EXTLOAD; 9847 break; 9848 } 9849 Val = DAG.getExtLoad( 9850 ExtType, DL, LocVT, Chain, FIN, 9851 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9852 return Val; 9853 } 9854 9855 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9856 const CCValAssign &VA, const SDLoc &DL) { 9857 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9858 "Unexpected VA"); 9859 MachineFunction &MF = DAG.getMachineFunction(); 9860 MachineFrameInfo &MFI = MF.getFrameInfo(); 9861 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9862 9863 if (VA.isMemLoc()) { 9864 // f64 is passed on the stack. 9865 int FI = 9866 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9867 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9868 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9869 MachinePointerInfo::getFixedStack(MF, FI)); 9870 } 9871 9872 assert(VA.isRegLoc() && "Expected register VA assignment"); 9873 9874 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9875 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 9876 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 9877 SDValue Hi; 9878 if (VA.getLocReg() == RISCV::X17) { 9879 // Second half of f64 is passed on the stack. 9880 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 9881 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9882 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 9883 MachinePointerInfo::getFixedStack(MF, FI)); 9884 } else { 9885 // Second half of f64 is passed in another GPR. 9886 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9887 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 9888 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 9889 } 9890 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 9891 } 9892 9893 // FastCC has less than 1% performance improvement for some particular 9894 // benchmark. But theoretically, it may has benenfit for some cases. 9895 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 9896 unsigned ValNo, MVT ValVT, MVT LocVT, 9897 CCValAssign::LocInfo LocInfo, 9898 ISD::ArgFlagsTy ArgFlags, CCState &State, 9899 bool IsFixed, bool IsRet, Type *OrigTy, 9900 const RISCVTargetLowering &TLI, 9901 Optional<unsigned> FirstMaskArgument) { 9902 9903 // X5 and X6 might be used for save-restore libcall. 9904 static const MCPhysReg GPRList[] = { 9905 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 9906 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 9907 RISCV::X29, RISCV::X30, RISCV::X31}; 9908 9909 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9910 if (unsigned Reg = State.AllocateReg(GPRList)) { 9911 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9912 return false; 9913 } 9914 } 9915 9916 if (LocVT == MVT::f16) { 9917 static const MCPhysReg FPR16List[] = { 9918 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 9919 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 9920 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 9921 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 9922 if (unsigned Reg = State.AllocateReg(FPR16List)) { 9923 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9924 return false; 9925 } 9926 } 9927 9928 if (LocVT == MVT::f32) { 9929 static const MCPhysReg FPR32List[] = { 9930 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 9931 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 9932 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 9933 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 9934 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9935 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9936 return false; 9937 } 9938 } 9939 9940 if (LocVT == MVT::f64) { 9941 static const MCPhysReg FPR64List[] = { 9942 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 9943 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 9944 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 9945 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 9946 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9947 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9948 return false; 9949 } 9950 } 9951 9952 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 9953 unsigned Offset4 = State.AllocateStack(4, Align(4)); 9954 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 9955 return false; 9956 } 9957 9958 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 9959 unsigned Offset5 = State.AllocateStack(8, Align(8)); 9960 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 9961 return false; 9962 } 9963 9964 if (LocVT.isVector()) { 9965 if (unsigned Reg = 9966 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 9967 // Fixed-length vectors are located in the corresponding scalable-vector 9968 // container types. 9969 if (ValVT.isFixedLengthVector()) 9970 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9971 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9972 } else { 9973 // Try and pass the address via a "fast" GPR. 9974 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 9975 LocInfo = CCValAssign::Indirect; 9976 LocVT = TLI.getSubtarget().getXLenVT(); 9977 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 9978 } else if (ValVT.isFixedLengthVector()) { 9979 auto StackAlign = 9980 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9981 unsigned StackOffset = 9982 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 9983 State.addLoc( 9984 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9985 } else { 9986 // Can't pass scalable vectors on the stack. 9987 return true; 9988 } 9989 } 9990 9991 return false; 9992 } 9993 9994 return true; // CC didn't match. 9995 } 9996 9997 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9998 CCValAssign::LocInfo LocInfo, 9999 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10000 10001 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10002 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10003 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10004 static const MCPhysReg GPRList[] = { 10005 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10006 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10007 if (unsigned Reg = State.AllocateReg(GPRList)) { 10008 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10009 return false; 10010 } 10011 } 10012 10013 if (LocVT == MVT::f32) { 10014 // Pass in STG registers: F1, ..., F6 10015 // fs0 ... fs5 10016 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10017 RISCV::F18_F, RISCV::F19_F, 10018 RISCV::F20_F, RISCV::F21_F}; 10019 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10020 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10021 return false; 10022 } 10023 } 10024 10025 if (LocVT == MVT::f64) { 10026 // Pass in STG registers: D1, ..., D6 10027 // fs6 ... fs11 10028 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10029 RISCV::F24_D, RISCV::F25_D, 10030 RISCV::F26_D, RISCV::F27_D}; 10031 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10032 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10033 return false; 10034 } 10035 } 10036 10037 report_fatal_error("No registers left in GHC calling convention"); 10038 return true; 10039 } 10040 10041 // Transform physical registers into virtual registers. 10042 SDValue RISCVTargetLowering::LowerFormalArguments( 10043 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10044 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10045 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10046 10047 MachineFunction &MF = DAG.getMachineFunction(); 10048 10049 switch (CallConv) { 10050 default: 10051 report_fatal_error("Unsupported calling convention"); 10052 case CallingConv::C: 10053 case CallingConv::Fast: 10054 break; 10055 case CallingConv::GHC: 10056 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10057 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10058 report_fatal_error( 10059 "GHC calling convention requires the F and D instruction set extensions"); 10060 } 10061 10062 const Function &Func = MF.getFunction(); 10063 if (Func.hasFnAttribute("interrupt")) { 10064 if (!Func.arg_empty()) 10065 report_fatal_error( 10066 "Functions with the interrupt attribute cannot have arguments!"); 10067 10068 StringRef Kind = 10069 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10070 10071 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10072 report_fatal_error( 10073 "Function interrupt attribute argument not supported!"); 10074 } 10075 10076 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10077 MVT XLenVT = Subtarget.getXLenVT(); 10078 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10079 // Used with vargs to acumulate store chains. 10080 std::vector<SDValue> OutChains; 10081 10082 // Assign locations to all of the incoming arguments. 10083 SmallVector<CCValAssign, 16> ArgLocs; 10084 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10085 10086 if (CallConv == CallingConv::GHC) 10087 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10088 else 10089 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10090 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10091 : CC_RISCV); 10092 10093 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10094 CCValAssign &VA = ArgLocs[i]; 10095 SDValue ArgValue; 10096 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10097 // case. 10098 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10099 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10100 else if (VA.isRegLoc()) 10101 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10102 else 10103 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10104 10105 if (VA.getLocInfo() == CCValAssign::Indirect) { 10106 // If the original argument was split and passed by reference (e.g. i128 10107 // on RV32), we need to load all parts of it here (using the same 10108 // address). Vectors may be partly split to registers and partly to the 10109 // stack, in which case the base address is partly offset and subsequent 10110 // stores are relative to that. 10111 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10112 MachinePointerInfo())); 10113 unsigned ArgIndex = Ins[i].OrigArgIndex; 10114 unsigned ArgPartOffset = Ins[i].PartOffset; 10115 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10116 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10117 CCValAssign &PartVA = ArgLocs[i + 1]; 10118 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10119 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10120 if (PartVA.getValVT().isScalableVector()) 10121 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10122 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10123 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10124 MachinePointerInfo())); 10125 ++i; 10126 } 10127 continue; 10128 } 10129 InVals.push_back(ArgValue); 10130 } 10131 10132 if (IsVarArg) { 10133 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10134 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10135 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10136 MachineFrameInfo &MFI = MF.getFrameInfo(); 10137 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10138 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10139 10140 // Offset of the first variable argument from stack pointer, and size of 10141 // the vararg save area. For now, the varargs save area is either zero or 10142 // large enough to hold a0-a7. 10143 int VaArgOffset, VarArgsSaveSize; 10144 10145 // If all registers are allocated, then all varargs must be passed on the 10146 // stack and we don't need to save any argregs. 10147 if (ArgRegs.size() == Idx) { 10148 VaArgOffset = CCInfo.getNextStackOffset(); 10149 VarArgsSaveSize = 0; 10150 } else { 10151 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10152 VaArgOffset = -VarArgsSaveSize; 10153 } 10154 10155 // Record the frame index of the first variable argument 10156 // which is a value necessary to VASTART. 10157 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10158 RVFI->setVarArgsFrameIndex(FI); 10159 10160 // If saving an odd number of registers then create an extra stack slot to 10161 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10162 // offsets to even-numbered registered remain 2*XLEN-aligned. 10163 if (Idx % 2) { 10164 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10165 VarArgsSaveSize += XLenInBytes; 10166 } 10167 10168 // Copy the integer registers that may have been used for passing varargs 10169 // to the vararg save area. 10170 for (unsigned I = Idx; I < ArgRegs.size(); 10171 ++I, VaArgOffset += XLenInBytes) { 10172 const Register Reg = RegInfo.createVirtualRegister(RC); 10173 RegInfo.addLiveIn(ArgRegs[I], Reg); 10174 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10175 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10176 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10177 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10178 MachinePointerInfo::getFixedStack(MF, FI)); 10179 cast<StoreSDNode>(Store.getNode()) 10180 ->getMemOperand() 10181 ->setValue((Value *)nullptr); 10182 OutChains.push_back(Store); 10183 } 10184 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10185 } 10186 10187 // All stores are grouped in one node to allow the matching between 10188 // the size of Ins and InVals. This only happens for vararg functions. 10189 if (!OutChains.empty()) { 10190 OutChains.push_back(Chain); 10191 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10192 } 10193 10194 return Chain; 10195 } 10196 10197 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10198 /// for tail call optimization. 10199 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10200 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10201 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10202 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10203 10204 auto &Callee = CLI.Callee; 10205 auto CalleeCC = CLI.CallConv; 10206 auto &Outs = CLI.Outs; 10207 auto &Caller = MF.getFunction(); 10208 auto CallerCC = Caller.getCallingConv(); 10209 10210 // Exception-handling functions need a special set of instructions to 10211 // indicate a return to the hardware. Tail-calling another function would 10212 // probably break this. 10213 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10214 // should be expanded as new function attributes are introduced. 10215 if (Caller.hasFnAttribute("interrupt")) 10216 return false; 10217 10218 // Do not tail call opt if the stack is used to pass parameters. 10219 if (CCInfo.getNextStackOffset() != 0) 10220 return false; 10221 10222 // Do not tail call opt if any parameters need to be passed indirectly. 10223 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10224 // passed indirectly. So the address of the value will be passed in a 10225 // register, or if not available, then the address is put on the stack. In 10226 // order to pass indirectly, space on the stack often needs to be allocated 10227 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10228 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10229 // are passed CCValAssign::Indirect. 10230 for (auto &VA : ArgLocs) 10231 if (VA.getLocInfo() == CCValAssign::Indirect) 10232 return false; 10233 10234 // Do not tail call opt if either caller or callee uses struct return 10235 // semantics. 10236 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10237 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10238 if (IsCallerStructRet || IsCalleeStructRet) 10239 return false; 10240 10241 // Externally-defined functions with weak linkage should not be 10242 // tail-called. The behaviour of branch instructions in this situation (as 10243 // used for tail calls) is implementation-defined, so we cannot rely on the 10244 // linker replacing the tail call with a return. 10245 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10246 const GlobalValue *GV = G->getGlobal(); 10247 if (GV->hasExternalWeakLinkage()) 10248 return false; 10249 } 10250 10251 // The callee has to preserve all registers the caller needs to preserve. 10252 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10253 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10254 if (CalleeCC != CallerCC) { 10255 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10256 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10257 return false; 10258 } 10259 10260 // Byval parameters hand the function a pointer directly into the stack area 10261 // we want to reuse during a tail call. Working around this *is* possible 10262 // but less efficient and uglier in LowerCall. 10263 for (auto &Arg : Outs) 10264 if (Arg.Flags.isByVal()) 10265 return false; 10266 10267 return true; 10268 } 10269 10270 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10271 return DAG.getDataLayout().getPrefTypeAlign( 10272 VT.getTypeForEVT(*DAG.getContext())); 10273 } 10274 10275 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10276 // and output parameter nodes. 10277 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10278 SmallVectorImpl<SDValue> &InVals) const { 10279 SelectionDAG &DAG = CLI.DAG; 10280 SDLoc &DL = CLI.DL; 10281 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10282 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10283 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10284 SDValue Chain = CLI.Chain; 10285 SDValue Callee = CLI.Callee; 10286 bool &IsTailCall = CLI.IsTailCall; 10287 CallingConv::ID CallConv = CLI.CallConv; 10288 bool IsVarArg = CLI.IsVarArg; 10289 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10290 MVT XLenVT = Subtarget.getXLenVT(); 10291 10292 MachineFunction &MF = DAG.getMachineFunction(); 10293 10294 // Analyze the operands of the call, assigning locations to each operand. 10295 SmallVector<CCValAssign, 16> ArgLocs; 10296 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10297 10298 if (CallConv == CallingConv::GHC) 10299 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10300 else 10301 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10302 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10303 : CC_RISCV); 10304 10305 // Check if it's really possible to do a tail call. 10306 if (IsTailCall) 10307 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10308 10309 if (IsTailCall) 10310 ++NumTailCalls; 10311 else if (CLI.CB && CLI.CB->isMustTailCall()) 10312 report_fatal_error("failed to perform tail call elimination on a call " 10313 "site marked musttail"); 10314 10315 // Get a count of how many bytes are to be pushed on the stack. 10316 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10317 10318 // Create local copies for byval args 10319 SmallVector<SDValue, 8> ByValArgs; 10320 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10321 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10322 if (!Flags.isByVal()) 10323 continue; 10324 10325 SDValue Arg = OutVals[i]; 10326 unsigned Size = Flags.getByValSize(); 10327 Align Alignment = Flags.getNonZeroByValAlign(); 10328 10329 int FI = 10330 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10331 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10332 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10333 10334 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10335 /*IsVolatile=*/false, 10336 /*AlwaysInline=*/false, IsTailCall, 10337 MachinePointerInfo(), MachinePointerInfo()); 10338 ByValArgs.push_back(FIPtr); 10339 } 10340 10341 if (!IsTailCall) 10342 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10343 10344 // Copy argument values to their designated locations. 10345 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10346 SmallVector<SDValue, 8> MemOpChains; 10347 SDValue StackPtr; 10348 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10349 CCValAssign &VA = ArgLocs[i]; 10350 SDValue ArgValue = OutVals[i]; 10351 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10352 10353 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10354 bool IsF64OnRV32DSoftABI = 10355 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10356 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10357 SDValue SplitF64 = DAG.getNode( 10358 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10359 SDValue Lo = SplitF64.getValue(0); 10360 SDValue Hi = SplitF64.getValue(1); 10361 10362 Register RegLo = VA.getLocReg(); 10363 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10364 10365 if (RegLo == RISCV::X17) { 10366 // Second half of f64 is passed on the stack. 10367 // Work out the address of the stack slot. 10368 if (!StackPtr.getNode()) 10369 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10370 // Emit the store. 10371 MemOpChains.push_back( 10372 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10373 } else { 10374 // Second half of f64 is passed in another GPR. 10375 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10376 Register RegHigh = RegLo + 1; 10377 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10378 } 10379 continue; 10380 } 10381 10382 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10383 // as any other MemLoc. 10384 10385 // Promote the value if needed. 10386 // For now, only handle fully promoted and indirect arguments. 10387 if (VA.getLocInfo() == CCValAssign::Indirect) { 10388 // Store the argument in a stack slot and pass its address. 10389 Align StackAlign = 10390 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10391 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10392 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10393 // If the original argument was split (e.g. i128), we need 10394 // to store the required parts of it here (and pass just one address). 10395 // Vectors may be partly split to registers and partly to the stack, in 10396 // which case the base address is partly offset and subsequent stores are 10397 // relative to that. 10398 unsigned ArgIndex = Outs[i].OrigArgIndex; 10399 unsigned ArgPartOffset = Outs[i].PartOffset; 10400 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10401 // Calculate the total size to store. We don't have access to what we're 10402 // actually storing other than performing the loop and collecting the 10403 // info. 10404 SmallVector<std::pair<SDValue, SDValue>> Parts; 10405 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10406 SDValue PartValue = OutVals[i + 1]; 10407 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10408 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10409 EVT PartVT = PartValue.getValueType(); 10410 if (PartVT.isScalableVector()) 10411 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10412 StoredSize += PartVT.getStoreSize(); 10413 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10414 Parts.push_back(std::make_pair(PartValue, Offset)); 10415 ++i; 10416 } 10417 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10418 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10419 MemOpChains.push_back( 10420 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10421 MachinePointerInfo::getFixedStack(MF, FI))); 10422 for (const auto &Part : Parts) { 10423 SDValue PartValue = Part.first; 10424 SDValue PartOffset = Part.second; 10425 SDValue Address = 10426 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10427 MemOpChains.push_back( 10428 DAG.getStore(Chain, DL, PartValue, Address, 10429 MachinePointerInfo::getFixedStack(MF, FI))); 10430 } 10431 ArgValue = SpillSlot; 10432 } else { 10433 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10434 } 10435 10436 // Use local copy if it is a byval arg. 10437 if (Flags.isByVal()) 10438 ArgValue = ByValArgs[j++]; 10439 10440 if (VA.isRegLoc()) { 10441 // Queue up the argument copies and emit them at the end. 10442 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10443 } else { 10444 assert(VA.isMemLoc() && "Argument not register or memory"); 10445 assert(!IsTailCall && "Tail call not allowed if stack is used " 10446 "for passing parameters"); 10447 10448 // Work out the address of the stack slot. 10449 if (!StackPtr.getNode()) 10450 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10451 SDValue Address = 10452 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10453 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10454 10455 // Emit the store. 10456 MemOpChains.push_back( 10457 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10458 } 10459 } 10460 10461 // Join the stores, which are independent of one another. 10462 if (!MemOpChains.empty()) 10463 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10464 10465 SDValue Glue; 10466 10467 // Build a sequence of copy-to-reg nodes, chained and glued together. 10468 for (auto &Reg : RegsToPass) { 10469 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10470 Glue = Chain.getValue(1); 10471 } 10472 10473 // Validate that none of the argument registers have been marked as 10474 // reserved, if so report an error. Do the same for the return address if this 10475 // is not a tailcall. 10476 validateCCReservedRegs(RegsToPass, MF); 10477 if (!IsTailCall && 10478 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10479 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10480 MF.getFunction(), 10481 "Return address register required, but has been reserved."}); 10482 10483 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10484 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10485 // split it and then direct call can be matched by PseudoCALL. 10486 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10487 const GlobalValue *GV = S->getGlobal(); 10488 10489 unsigned OpFlags = RISCVII::MO_CALL; 10490 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10491 OpFlags = RISCVII::MO_PLT; 10492 10493 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10494 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10495 unsigned OpFlags = RISCVII::MO_CALL; 10496 10497 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10498 nullptr)) 10499 OpFlags = RISCVII::MO_PLT; 10500 10501 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10502 } 10503 10504 // The first call operand is the chain and the second is the target address. 10505 SmallVector<SDValue, 8> Ops; 10506 Ops.push_back(Chain); 10507 Ops.push_back(Callee); 10508 10509 // Add argument registers to the end of the list so that they are 10510 // known live into the call. 10511 for (auto &Reg : RegsToPass) 10512 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10513 10514 if (!IsTailCall) { 10515 // Add a register mask operand representing the call-preserved registers. 10516 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10517 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10518 assert(Mask && "Missing call preserved mask for calling convention"); 10519 Ops.push_back(DAG.getRegisterMask(Mask)); 10520 } 10521 10522 // Glue the call to the argument copies, if any. 10523 if (Glue.getNode()) 10524 Ops.push_back(Glue); 10525 10526 // Emit the call. 10527 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10528 10529 if (IsTailCall) { 10530 MF.getFrameInfo().setHasTailCall(); 10531 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10532 } 10533 10534 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10535 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10536 Glue = Chain.getValue(1); 10537 10538 // Mark the end of the call, which is glued to the call itself. 10539 Chain = DAG.getCALLSEQ_END(Chain, 10540 DAG.getConstant(NumBytes, DL, PtrVT, true), 10541 DAG.getConstant(0, DL, PtrVT, true), 10542 Glue, DL); 10543 Glue = Chain.getValue(1); 10544 10545 // Assign locations to each value returned by this call. 10546 SmallVector<CCValAssign, 16> RVLocs; 10547 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10548 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10549 10550 // Copy all of the result registers out of their specified physreg. 10551 for (auto &VA : RVLocs) { 10552 // Copy the value out 10553 SDValue RetValue = 10554 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10555 // Glue the RetValue to the end of the call sequence 10556 Chain = RetValue.getValue(1); 10557 Glue = RetValue.getValue(2); 10558 10559 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10560 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10561 SDValue RetValue2 = 10562 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10563 Chain = RetValue2.getValue(1); 10564 Glue = RetValue2.getValue(2); 10565 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10566 RetValue2); 10567 } 10568 10569 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10570 10571 InVals.push_back(RetValue); 10572 } 10573 10574 return Chain; 10575 } 10576 10577 bool RISCVTargetLowering::CanLowerReturn( 10578 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10579 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10580 SmallVector<CCValAssign, 16> RVLocs; 10581 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10582 10583 Optional<unsigned> FirstMaskArgument; 10584 if (Subtarget.hasVInstructions()) 10585 FirstMaskArgument = preAssignMask(Outs); 10586 10587 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10588 MVT VT = Outs[i].VT; 10589 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10590 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10591 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10592 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10593 *this, FirstMaskArgument)) 10594 return false; 10595 } 10596 return true; 10597 } 10598 10599 SDValue 10600 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10601 bool IsVarArg, 10602 const SmallVectorImpl<ISD::OutputArg> &Outs, 10603 const SmallVectorImpl<SDValue> &OutVals, 10604 const SDLoc &DL, SelectionDAG &DAG) const { 10605 const MachineFunction &MF = DAG.getMachineFunction(); 10606 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10607 10608 // Stores the assignment of the return value to a location. 10609 SmallVector<CCValAssign, 16> RVLocs; 10610 10611 // Info about the registers and stack slot. 10612 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10613 *DAG.getContext()); 10614 10615 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10616 nullptr, CC_RISCV); 10617 10618 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10619 report_fatal_error("GHC functions return void only"); 10620 10621 SDValue Glue; 10622 SmallVector<SDValue, 4> RetOps(1, Chain); 10623 10624 // Copy the result values into the output registers. 10625 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10626 SDValue Val = OutVals[i]; 10627 CCValAssign &VA = RVLocs[i]; 10628 assert(VA.isRegLoc() && "Can only return in registers!"); 10629 10630 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10631 // Handle returning f64 on RV32D with a soft float ABI. 10632 assert(VA.isRegLoc() && "Expected return via registers"); 10633 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10634 DAG.getVTList(MVT::i32, MVT::i32), Val); 10635 SDValue Lo = SplitF64.getValue(0); 10636 SDValue Hi = SplitF64.getValue(1); 10637 Register RegLo = VA.getLocReg(); 10638 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10639 Register RegHi = RegLo + 1; 10640 10641 if (STI.isRegisterReservedByUser(RegLo) || 10642 STI.isRegisterReservedByUser(RegHi)) 10643 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10644 MF.getFunction(), 10645 "Return value register required, but has been reserved."}); 10646 10647 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10648 Glue = Chain.getValue(1); 10649 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10650 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10651 Glue = Chain.getValue(1); 10652 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10653 } else { 10654 // Handle a 'normal' return. 10655 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10656 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10657 10658 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10659 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10660 MF.getFunction(), 10661 "Return value register required, but has been reserved."}); 10662 10663 // Guarantee that all emitted copies are stuck together. 10664 Glue = Chain.getValue(1); 10665 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10666 } 10667 } 10668 10669 RetOps[0] = Chain; // Update chain. 10670 10671 // Add the glue node if we have it. 10672 if (Glue.getNode()) { 10673 RetOps.push_back(Glue); 10674 } 10675 10676 unsigned RetOpc = RISCVISD::RET_FLAG; 10677 // Interrupt service routines use different return instructions. 10678 const Function &Func = DAG.getMachineFunction().getFunction(); 10679 if (Func.hasFnAttribute("interrupt")) { 10680 if (!Func.getReturnType()->isVoidTy()) 10681 report_fatal_error( 10682 "Functions with the interrupt attribute must have void return type!"); 10683 10684 MachineFunction &MF = DAG.getMachineFunction(); 10685 StringRef Kind = 10686 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10687 10688 if (Kind == "user") 10689 RetOpc = RISCVISD::URET_FLAG; 10690 else if (Kind == "supervisor") 10691 RetOpc = RISCVISD::SRET_FLAG; 10692 else 10693 RetOpc = RISCVISD::MRET_FLAG; 10694 } 10695 10696 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10697 } 10698 10699 void RISCVTargetLowering::validateCCReservedRegs( 10700 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10701 MachineFunction &MF) const { 10702 const Function &F = MF.getFunction(); 10703 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10704 10705 if (llvm::any_of(Regs, [&STI](auto Reg) { 10706 return STI.isRegisterReservedByUser(Reg.first); 10707 })) 10708 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10709 F, "Argument register required, but has been reserved."}); 10710 } 10711 10712 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10713 return CI->isTailCall(); 10714 } 10715 10716 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10717 #define NODE_NAME_CASE(NODE) \ 10718 case RISCVISD::NODE: \ 10719 return "RISCVISD::" #NODE; 10720 // clang-format off 10721 switch ((RISCVISD::NodeType)Opcode) { 10722 case RISCVISD::FIRST_NUMBER: 10723 break; 10724 NODE_NAME_CASE(RET_FLAG) 10725 NODE_NAME_CASE(URET_FLAG) 10726 NODE_NAME_CASE(SRET_FLAG) 10727 NODE_NAME_CASE(MRET_FLAG) 10728 NODE_NAME_CASE(CALL) 10729 NODE_NAME_CASE(SELECT_CC) 10730 NODE_NAME_CASE(BR_CC) 10731 NODE_NAME_CASE(BuildPairF64) 10732 NODE_NAME_CASE(SplitF64) 10733 NODE_NAME_CASE(TAIL) 10734 NODE_NAME_CASE(MULHSU) 10735 NODE_NAME_CASE(SLLW) 10736 NODE_NAME_CASE(SRAW) 10737 NODE_NAME_CASE(SRLW) 10738 NODE_NAME_CASE(DIVW) 10739 NODE_NAME_CASE(DIVUW) 10740 NODE_NAME_CASE(REMUW) 10741 NODE_NAME_CASE(ROLW) 10742 NODE_NAME_CASE(RORW) 10743 NODE_NAME_CASE(CLZW) 10744 NODE_NAME_CASE(CTZW) 10745 NODE_NAME_CASE(FSLW) 10746 NODE_NAME_CASE(FSRW) 10747 NODE_NAME_CASE(FSL) 10748 NODE_NAME_CASE(FSR) 10749 NODE_NAME_CASE(FMV_H_X) 10750 NODE_NAME_CASE(FMV_X_ANYEXTH) 10751 NODE_NAME_CASE(FMV_X_SIGNEXTH) 10752 NODE_NAME_CASE(FMV_W_X_RV64) 10753 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10754 NODE_NAME_CASE(FCVT_X) 10755 NODE_NAME_CASE(FCVT_XU) 10756 NODE_NAME_CASE(FCVT_W_RV64) 10757 NODE_NAME_CASE(FCVT_WU_RV64) 10758 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10759 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10760 NODE_NAME_CASE(READ_CYCLE_WIDE) 10761 NODE_NAME_CASE(GREV) 10762 NODE_NAME_CASE(GREVW) 10763 NODE_NAME_CASE(GORC) 10764 NODE_NAME_CASE(GORCW) 10765 NODE_NAME_CASE(SHFL) 10766 NODE_NAME_CASE(SHFLW) 10767 NODE_NAME_CASE(UNSHFL) 10768 NODE_NAME_CASE(UNSHFLW) 10769 NODE_NAME_CASE(BFP) 10770 NODE_NAME_CASE(BFPW) 10771 NODE_NAME_CASE(BCOMPRESS) 10772 NODE_NAME_CASE(BCOMPRESSW) 10773 NODE_NAME_CASE(BDECOMPRESS) 10774 NODE_NAME_CASE(BDECOMPRESSW) 10775 NODE_NAME_CASE(VMV_V_X_VL) 10776 NODE_NAME_CASE(VFMV_V_F_VL) 10777 NODE_NAME_CASE(VMV_X_S) 10778 NODE_NAME_CASE(VMV_S_X_VL) 10779 NODE_NAME_CASE(VFMV_S_F_VL) 10780 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10781 NODE_NAME_CASE(READ_VLENB) 10782 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10783 NODE_NAME_CASE(VSLIDEUP_VL) 10784 NODE_NAME_CASE(VSLIDE1UP_VL) 10785 NODE_NAME_CASE(VSLIDEDOWN_VL) 10786 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10787 NODE_NAME_CASE(VID_VL) 10788 NODE_NAME_CASE(VFNCVT_ROD_VL) 10789 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10790 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10791 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10792 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10793 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10794 NODE_NAME_CASE(VECREDUCE_AND_VL) 10795 NODE_NAME_CASE(VECREDUCE_OR_VL) 10796 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10797 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10798 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10799 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10800 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10801 NODE_NAME_CASE(ADD_VL) 10802 NODE_NAME_CASE(AND_VL) 10803 NODE_NAME_CASE(MUL_VL) 10804 NODE_NAME_CASE(OR_VL) 10805 NODE_NAME_CASE(SDIV_VL) 10806 NODE_NAME_CASE(SHL_VL) 10807 NODE_NAME_CASE(SREM_VL) 10808 NODE_NAME_CASE(SRA_VL) 10809 NODE_NAME_CASE(SRL_VL) 10810 NODE_NAME_CASE(SUB_VL) 10811 NODE_NAME_CASE(UDIV_VL) 10812 NODE_NAME_CASE(UREM_VL) 10813 NODE_NAME_CASE(XOR_VL) 10814 NODE_NAME_CASE(SADDSAT_VL) 10815 NODE_NAME_CASE(UADDSAT_VL) 10816 NODE_NAME_CASE(SSUBSAT_VL) 10817 NODE_NAME_CASE(USUBSAT_VL) 10818 NODE_NAME_CASE(FADD_VL) 10819 NODE_NAME_CASE(FSUB_VL) 10820 NODE_NAME_CASE(FMUL_VL) 10821 NODE_NAME_CASE(FDIV_VL) 10822 NODE_NAME_CASE(FNEG_VL) 10823 NODE_NAME_CASE(FABS_VL) 10824 NODE_NAME_CASE(FSQRT_VL) 10825 NODE_NAME_CASE(FMA_VL) 10826 NODE_NAME_CASE(FCOPYSIGN_VL) 10827 NODE_NAME_CASE(SMIN_VL) 10828 NODE_NAME_CASE(SMAX_VL) 10829 NODE_NAME_CASE(UMIN_VL) 10830 NODE_NAME_CASE(UMAX_VL) 10831 NODE_NAME_CASE(FMINNUM_VL) 10832 NODE_NAME_CASE(FMAXNUM_VL) 10833 NODE_NAME_CASE(MULHS_VL) 10834 NODE_NAME_CASE(MULHU_VL) 10835 NODE_NAME_CASE(FP_TO_SINT_VL) 10836 NODE_NAME_CASE(FP_TO_UINT_VL) 10837 NODE_NAME_CASE(SINT_TO_FP_VL) 10838 NODE_NAME_CASE(UINT_TO_FP_VL) 10839 NODE_NAME_CASE(FP_EXTEND_VL) 10840 NODE_NAME_CASE(FP_ROUND_VL) 10841 NODE_NAME_CASE(VWMUL_VL) 10842 NODE_NAME_CASE(VWMULU_VL) 10843 NODE_NAME_CASE(VWMULSU_VL) 10844 NODE_NAME_CASE(VWADD_VL) 10845 NODE_NAME_CASE(VWADDU_VL) 10846 NODE_NAME_CASE(VWSUB_VL) 10847 NODE_NAME_CASE(VWSUBU_VL) 10848 NODE_NAME_CASE(VWADD_W_VL) 10849 NODE_NAME_CASE(VWADDU_W_VL) 10850 NODE_NAME_CASE(VWSUB_W_VL) 10851 NODE_NAME_CASE(VWSUBU_W_VL) 10852 NODE_NAME_CASE(SETCC_VL) 10853 NODE_NAME_CASE(VSELECT_VL) 10854 NODE_NAME_CASE(VP_MERGE_VL) 10855 NODE_NAME_CASE(VMAND_VL) 10856 NODE_NAME_CASE(VMOR_VL) 10857 NODE_NAME_CASE(VMXOR_VL) 10858 NODE_NAME_CASE(VMCLR_VL) 10859 NODE_NAME_CASE(VMSET_VL) 10860 NODE_NAME_CASE(VRGATHER_VX_VL) 10861 NODE_NAME_CASE(VRGATHER_VV_VL) 10862 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10863 NODE_NAME_CASE(VSEXT_VL) 10864 NODE_NAME_CASE(VZEXT_VL) 10865 NODE_NAME_CASE(VCPOP_VL) 10866 NODE_NAME_CASE(READ_CSR) 10867 NODE_NAME_CASE(WRITE_CSR) 10868 NODE_NAME_CASE(SWAP_CSR) 10869 } 10870 // clang-format on 10871 return nullptr; 10872 #undef NODE_NAME_CASE 10873 } 10874 10875 /// getConstraintType - Given a constraint letter, return the type of 10876 /// constraint it is for this target. 10877 RISCVTargetLowering::ConstraintType 10878 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 10879 if (Constraint.size() == 1) { 10880 switch (Constraint[0]) { 10881 default: 10882 break; 10883 case 'f': 10884 return C_RegisterClass; 10885 case 'I': 10886 case 'J': 10887 case 'K': 10888 return C_Immediate; 10889 case 'A': 10890 return C_Memory; 10891 case 'S': // A symbolic address 10892 return C_Other; 10893 } 10894 } else { 10895 if (Constraint == "vr" || Constraint == "vm") 10896 return C_RegisterClass; 10897 } 10898 return TargetLowering::getConstraintType(Constraint); 10899 } 10900 10901 std::pair<unsigned, const TargetRegisterClass *> 10902 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10903 StringRef Constraint, 10904 MVT VT) const { 10905 // First, see if this is a constraint that directly corresponds to a 10906 // RISCV register class. 10907 if (Constraint.size() == 1) { 10908 switch (Constraint[0]) { 10909 case 'r': 10910 // TODO: Support fixed vectors up to XLen for P extension? 10911 if (VT.isVector()) 10912 break; 10913 return std::make_pair(0U, &RISCV::GPRRegClass); 10914 case 'f': 10915 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 10916 return std::make_pair(0U, &RISCV::FPR16RegClass); 10917 if (Subtarget.hasStdExtF() && VT == MVT::f32) 10918 return std::make_pair(0U, &RISCV::FPR32RegClass); 10919 if (Subtarget.hasStdExtD() && VT == MVT::f64) 10920 return std::make_pair(0U, &RISCV::FPR64RegClass); 10921 break; 10922 default: 10923 break; 10924 } 10925 } else if (Constraint == "vr") { 10926 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 10927 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10928 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 10929 return std::make_pair(0U, RC); 10930 } 10931 } else if (Constraint == "vm") { 10932 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 10933 return std::make_pair(0U, &RISCV::VMV0RegClass); 10934 } 10935 10936 // Clang will correctly decode the usage of register name aliases into their 10937 // official names. However, other frontends like `rustc` do not. This allows 10938 // users of these frontends to use the ABI names for registers in LLVM-style 10939 // register constraints. 10940 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 10941 .Case("{zero}", RISCV::X0) 10942 .Case("{ra}", RISCV::X1) 10943 .Case("{sp}", RISCV::X2) 10944 .Case("{gp}", RISCV::X3) 10945 .Case("{tp}", RISCV::X4) 10946 .Case("{t0}", RISCV::X5) 10947 .Case("{t1}", RISCV::X6) 10948 .Case("{t2}", RISCV::X7) 10949 .Cases("{s0}", "{fp}", RISCV::X8) 10950 .Case("{s1}", RISCV::X9) 10951 .Case("{a0}", RISCV::X10) 10952 .Case("{a1}", RISCV::X11) 10953 .Case("{a2}", RISCV::X12) 10954 .Case("{a3}", RISCV::X13) 10955 .Case("{a4}", RISCV::X14) 10956 .Case("{a5}", RISCV::X15) 10957 .Case("{a6}", RISCV::X16) 10958 .Case("{a7}", RISCV::X17) 10959 .Case("{s2}", RISCV::X18) 10960 .Case("{s3}", RISCV::X19) 10961 .Case("{s4}", RISCV::X20) 10962 .Case("{s5}", RISCV::X21) 10963 .Case("{s6}", RISCV::X22) 10964 .Case("{s7}", RISCV::X23) 10965 .Case("{s8}", RISCV::X24) 10966 .Case("{s9}", RISCV::X25) 10967 .Case("{s10}", RISCV::X26) 10968 .Case("{s11}", RISCV::X27) 10969 .Case("{t3}", RISCV::X28) 10970 .Case("{t4}", RISCV::X29) 10971 .Case("{t5}", RISCV::X30) 10972 .Case("{t6}", RISCV::X31) 10973 .Default(RISCV::NoRegister); 10974 if (XRegFromAlias != RISCV::NoRegister) 10975 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 10976 10977 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 10978 // TableGen record rather than the AsmName to choose registers for InlineAsm 10979 // constraints, plus we want to match those names to the widest floating point 10980 // register type available, manually select floating point registers here. 10981 // 10982 // The second case is the ABI name of the register, so that frontends can also 10983 // use the ABI names in register constraint lists. 10984 if (Subtarget.hasStdExtF()) { 10985 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 10986 .Cases("{f0}", "{ft0}", RISCV::F0_F) 10987 .Cases("{f1}", "{ft1}", RISCV::F1_F) 10988 .Cases("{f2}", "{ft2}", RISCV::F2_F) 10989 .Cases("{f3}", "{ft3}", RISCV::F3_F) 10990 .Cases("{f4}", "{ft4}", RISCV::F4_F) 10991 .Cases("{f5}", "{ft5}", RISCV::F5_F) 10992 .Cases("{f6}", "{ft6}", RISCV::F6_F) 10993 .Cases("{f7}", "{ft7}", RISCV::F7_F) 10994 .Cases("{f8}", "{fs0}", RISCV::F8_F) 10995 .Cases("{f9}", "{fs1}", RISCV::F9_F) 10996 .Cases("{f10}", "{fa0}", RISCV::F10_F) 10997 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10998 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10999 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11000 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11001 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11002 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11003 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11004 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11005 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11006 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11007 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11008 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11009 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11010 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11011 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11012 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11013 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11014 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11015 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11016 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11017 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11018 .Default(RISCV::NoRegister); 11019 if (FReg != RISCV::NoRegister) { 11020 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11021 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11022 unsigned RegNo = FReg - RISCV::F0_F; 11023 unsigned DReg = RISCV::F0_D + RegNo; 11024 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11025 } 11026 if (VT == MVT::f32 || VT == MVT::Other) 11027 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11028 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11029 unsigned RegNo = FReg - RISCV::F0_F; 11030 unsigned HReg = RISCV::F0_H + RegNo; 11031 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11032 } 11033 } 11034 } 11035 11036 if (Subtarget.hasVInstructions()) { 11037 Register VReg = StringSwitch<Register>(Constraint.lower()) 11038 .Case("{v0}", RISCV::V0) 11039 .Case("{v1}", RISCV::V1) 11040 .Case("{v2}", RISCV::V2) 11041 .Case("{v3}", RISCV::V3) 11042 .Case("{v4}", RISCV::V4) 11043 .Case("{v5}", RISCV::V5) 11044 .Case("{v6}", RISCV::V6) 11045 .Case("{v7}", RISCV::V7) 11046 .Case("{v8}", RISCV::V8) 11047 .Case("{v9}", RISCV::V9) 11048 .Case("{v10}", RISCV::V10) 11049 .Case("{v11}", RISCV::V11) 11050 .Case("{v12}", RISCV::V12) 11051 .Case("{v13}", RISCV::V13) 11052 .Case("{v14}", RISCV::V14) 11053 .Case("{v15}", RISCV::V15) 11054 .Case("{v16}", RISCV::V16) 11055 .Case("{v17}", RISCV::V17) 11056 .Case("{v18}", RISCV::V18) 11057 .Case("{v19}", RISCV::V19) 11058 .Case("{v20}", RISCV::V20) 11059 .Case("{v21}", RISCV::V21) 11060 .Case("{v22}", RISCV::V22) 11061 .Case("{v23}", RISCV::V23) 11062 .Case("{v24}", RISCV::V24) 11063 .Case("{v25}", RISCV::V25) 11064 .Case("{v26}", RISCV::V26) 11065 .Case("{v27}", RISCV::V27) 11066 .Case("{v28}", RISCV::V28) 11067 .Case("{v29}", RISCV::V29) 11068 .Case("{v30}", RISCV::V30) 11069 .Case("{v31}", RISCV::V31) 11070 .Default(RISCV::NoRegister); 11071 if (VReg != RISCV::NoRegister) { 11072 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11073 return std::make_pair(VReg, &RISCV::VMRegClass); 11074 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11075 return std::make_pair(VReg, &RISCV::VRRegClass); 11076 for (const auto *RC : 11077 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11078 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11079 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11080 return std::make_pair(VReg, RC); 11081 } 11082 } 11083 } 11084 } 11085 11086 std::pair<Register, const TargetRegisterClass *> Res = 11087 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11088 11089 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11090 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11091 // Subtarget into account. 11092 if (Res.second == &RISCV::GPRF16RegClass || 11093 Res.second == &RISCV::GPRF32RegClass || 11094 Res.second == &RISCV::GPRF64RegClass) 11095 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11096 11097 return Res; 11098 } 11099 11100 unsigned 11101 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11102 // Currently only support length 1 constraints. 11103 if (ConstraintCode.size() == 1) { 11104 switch (ConstraintCode[0]) { 11105 case 'A': 11106 return InlineAsm::Constraint_A; 11107 default: 11108 break; 11109 } 11110 } 11111 11112 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11113 } 11114 11115 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11116 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11117 SelectionDAG &DAG) const { 11118 // Currently only support length 1 constraints. 11119 if (Constraint.length() == 1) { 11120 switch (Constraint[0]) { 11121 case 'I': 11122 // Validate & create a 12-bit signed immediate operand. 11123 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11124 uint64_t CVal = C->getSExtValue(); 11125 if (isInt<12>(CVal)) 11126 Ops.push_back( 11127 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11128 } 11129 return; 11130 case 'J': 11131 // Validate & create an integer zero operand. 11132 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11133 if (C->getZExtValue() == 0) 11134 Ops.push_back( 11135 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11136 return; 11137 case 'K': 11138 // Validate & create a 5-bit unsigned immediate operand. 11139 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11140 uint64_t CVal = C->getZExtValue(); 11141 if (isUInt<5>(CVal)) 11142 Ops.push_back( 11143 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11144 } 11145 return; 11146 case 'S': 11147 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11148 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11149 GA->getValueType(0))); 11150 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11151 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11152 BA->getValueType(0))); 11153 } 11154 return; 11155 default: 11156 break; 11157 } 11158 } 11159 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11160 } 11161 11162 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11163 Instruction *Inst, 11164 AtomicOrdering Ord) const { 11165 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11166 return Builder.CreateFence(Ord); 11167 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11168 return Builder.CreateFence(AtomicOrdering::Release); 11169 return nullptr; 11170 } 11171 11172 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11173 Instruction *Inst, 11174 AtomicOrdering Ord) const { 11175 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11176 return Builder.CreateFence(AtomicOrdering::Acquire); 11177 return nullptr; 11178 } 11179 11180 TargetLowering::AtomicExpansionKind 11181 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11182 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11183 // point operations can't be used in an lr/sc sequence without breaking the 11184 // forward-progress guarantee. 11185 if (AI->isFloatingPointOperation()) 11186 return AtomicExpansionKind::CmpXChg; 11187 11188 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11189 if (Size == 8 || Size == 16) 11190 return AtomicExpansionKind::MaskedIntrinsic; 11191 return AtomicExpansionKind::None; 11192 } 11193 11194 static Intrinsic::ID 11195 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11196 if (XLen == 32) { 11197 switch (BinOp) { 11198 default: 11199 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11200 case AtomicRMWInst::Xchg: 11201 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11202 case AtomicRMWInst::Add: 11203 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11204 case AtomicRMWInst::Sub: 11205 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11206 case AtomicRMWInst::Nand: 11207 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11208 case AtomicRMWInst::Max: 11209 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11210 case AtomicRMWInst::Min: 11211 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11212 case AtomicRMWInst::UMax: 11213 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11214 case AtomicRMWInst::UMin: 11215 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11216 } 11217 } 11218 11219 if (XLen == 64) { 11220 switch (BinOp) { 11221 default: 11222 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11223 case AtomicRMWInst::Xchg: 11224 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11225 case AtomicRMWInst::Add: 11226 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11227 case AtomicRMWInst::Sub: 11228 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11229 case AtomicRMWInst::Nand: 11230 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11231 case AtomicRMWInst::Max: 11232 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11233 case AtomicRMWInst::Min: 11234 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11235 case AtomicRMWInst::UMax: 11236 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11237 case AtomicRMWInst::UMin: 11238 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11239 } 11240 } 11241 11242 llvm_unreachable("Unexpected XLen\n"); 11243 } 11244 11245 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11246 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11247 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11248 unsigned XLen = Subtarget.getXLen(); 11249 Value *Ordering = 11250 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11251 Type *Tys[] = {AlignedAddr->getType()}; 11252 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11253 AI->getModule(), 11254 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11255 11256 if (XLen == 64) { 11257 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11258 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11259 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11260 } 11261 11262 Value *Result; 11263 11264 // Must pass the shift amount needed to sign extend the loaded value prior 11265 // to performing a signed comparison for min/max. ShiftAmt is the number of 11266 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11267 // is the number of bits to left+right shift the value in order to 11268 // sign-extend. 11269 if (AI->getOperation() == AtomicRMWInst::Min || 11270 AI->getOperation() == AtomicRMWInst::Max) { 11271 const DataLayout &DL = AI->getModule()->getDataLayout(); 11272 unsigned ValWidth = 11273 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11274 Value *SextShamt = 11275 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11276 Result = Builder.CreateCall(LrwOpScwLoop, 11277 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11278 } else { 11279 Result = 11280 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11281 } 11282 11283 if (XLen == 64) 11284 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11285 return Result; 11286 } 11287 11288 TargetLowering::AtomicExpansionKind 11289 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11290 AtomicCmpXchgInst *CI) const { 11291 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11292 if (Size == 8 || Size == 16) 11293 return AtomicExpansionKind::MaskedIntrinsic; 11294 return AtomicExpansionKind::None; 11295 } 11296 11297 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11298 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11299 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11300 unsigned XLen = Subtarget.getXLen(); 11301 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11302 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11303 if (XLen == 64) { 11304 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11305 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11306 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11307 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11308 } 11309 Type *Tys[] = {AlignedAddr->getType()}; 11310 Function *MaskedCmpXchg = 11311 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11312 Value *Result = Builder.CreateCall( 11313 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11314 if (XLen == 64) 11315 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11316 return Result; 11317 } 11318 11319 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11320 return false; 11321 } 11322 11323 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11324 EVT VT) const { 11325 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11326 return false; 11327 11328 switch (FPVT.getSimpleVT().SimpleTy) { 11329 case MVT::f16: 11330 return Subtarget.hasStdExtZfh(); 11331 case MVT::f32: 11332 return Subtarget.hasStdExtF(); 11333 case MVT::f64: 11334 return Subtarget.hasStdExtD(); 11335 default: 11336 return false; 11337 } 11338 } 11339 11340 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11341 // If we are using the small code model, we can reduce size of jump table 11342 // entry to 4 bytes. 11343 if (Subtarget.is64Bit() && !isPositionIndependent() && 11344 getTargetMachine().getCodeModel() == CodeModel::Small) { 11345 return MachineJumpTableInfo::EK_Custom32; 11346 } 11347 return TargetLowering::getJumpTableEncoding(); 11348 } 11349 11350 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11351 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11352 unsigned uid, MCContext &Ctx) const { 11353 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11354 getTargetMachine().getCodeModel() == CodeModel::Small); 11355 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11356 } 11357 11358 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11359 EVT VT) const { 11360 VT = VT.getScalarType(); 11361 11362 if (!VT.isSimple()) 11363 return false; 11364 11365 switch (VT.getSimpleVT().SimpleTy) { 11366 case MVT::f16: 11367 return Subtarget.hasStdExtZfh(); 11368 case MVT::f32: 11369 return Subtarget.hasStdExtF(); 11370 case MVT::f64: 11371 return Subtarget.hasStdExtD(); 11372 default: 11373 break; 11374 } 11375 11376 return false; 11377 } 11378 11379 Register RISCVTargetLowering::getExceptionPointerRegister( 11380 const Constant *PersonalityFn) const { 11381 return RISCV::X10; 11382 } 11383 11384 Register RISCVTargetLowering::getExceptionSelectorRegister( 11385 const Constant *PersonalityFn) const { 11386 return RISCV::X11; 11387 } 11388 11389 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11390 // Return false to suppress the unnecessary extensions if the LibCall 11391 // arguments or return value is f32 type for LP64 ABI. 11392 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11393 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11394 return false; 11395 11396 return true; 11397 } 11398 11399 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11400 if (Subtarget.is64Bit() && Type == MVT::i32) 11401 return true; 11402 11403 return IsSigned; 11404 } 11405 11406 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11407 SDValue C) const { 11408 // Check integral scalar types. 11409 if (VT.isScalarInteger()) { 11410 // Omit the optimization if the sub target has the M extension and the data 11411 // size exceeds XLen. 11412 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11413 return false; 11414 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11415 // Break the MUL to a SLLI and an ADD/SUB. 11416 const APInt &Imm = ConstNode->getAPIntValue(); 11417 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11418 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11419 return true; 11420 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11421 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11422 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11423 (Imm - 8).isPowerOf2())) 11424 return true; 11425 // Omit the following optimization if the sub target has the M extension 11426 // and the data size >= XLen. 11427 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11428 return false; 11429 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11430 // a pair of LUI/ADDI. 11431 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11432 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11433 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11434 (1 - ImmS).isPowerOf2()) 11435 return true; 11436 } 11437 } 11438 } 11439 11440 return false; 11441 } 11442 11443 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11444 SDValue ConstNode) const { 11445 // Let the DAGCombiner decide for vectors. 11446 EVT VT = AddNode.getValueType(); 11447 if (VT.isVector()) 11448 return true; 11449 11450 // Let the DAGCombiner decide for larger types. 11451 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11452 return true; 11453 11454 // It is worse if c1 is simm12 while c1*c2 is not. 11455 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11456 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11457 const APInt &C1 = C1Node->getAPIntValue(); 11458 const APInt &C2 = C2Node->getAPIntValue(); 11459 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11460 return false; 11461 11462 // Default to true and let the DAGCombiner decide. 11463 return true; 11464 } 11465 11466 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11467 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11468 bool *Fast) const { 11469 if (!VT.isVector()) 11470 return false; 11471 11472 EVT ElemVT = VT.getVectorElementType(); 11473 if (Alignment >= ElemVT.getStoreSize()) { 11474 if (Fast) 11475 *Fast = true; 11476 return true; 11477 } 11478 11479 return false; 11480 } 11481 11482 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11483 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11484 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11485 bool IsABIRegCopy = CC.hasValue(); 11486 EVT ValueVT = Val.getValueType(); 11487 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11488 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11489 // and cast to f32. 11490 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11491 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11492 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11493 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11494 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11495 Parts[0] = Val; 11496 return true; 11497 } 11498 11499 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11500 LLVMContext &Context = *DAG.getContext(); 11501 EVT ValueEltVT = ValueVT.getVectorElementType(); 11502 EVT PartEltVT = PartVT.getVectorElementType(); 11503 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11504 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11505 if (PartVTBitSize % ValueVTBitSize == 0) { 11506 assert(PartVTBitSize >= ValueVTBitSize); 11507 // If the element types are different, bitcast to the same element type of 11508 // PartVT first. 11509 // Give an example here, we want copy a <vscale x 1 x i8> value to 11510 // <vscale x 4 x i16>. 11511 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11512 // subvector, then we can bitcast to <vscale x 4 x i16>. 11513 if (ValueEltVT != PartEltVT) { 11514 if (PartVTBitSize > ValueVTBitSize) { 11515 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11516 assert(Count != 0 && "The number of element should not be zero."); 11517 EVT SameEltTypeVT = 11518 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11519 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11520 DAG.getUNDEF(SameEltTypeVT), Val, 11521 DAG.getVectorIdxConstant(0, DL)); 11522 } 11523 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11524 } else { 11525 Val = 11526 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11527 Val, DAG.getVectorIdxConstant(0, DL)); 11528 } 11529 Parts[0] = Val; 11530 return true; 11531 } 11532 } 11533 return false; 11534 } 11535 11536 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11537 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11538 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11539 bool IsABIRegCopy = CC.hasValue(); 11540 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11541 SDValue Val = Parts[0]; 11542 11543 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11544 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11545 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11546 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11547 return Val; 11548 } 11549 11550 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11551 LLVMContext &Context = *DAG.getContext(); 11552 SDValue Val = Parts[0]; 11553 EVT ValueEltVT = ValueVT.getVectorElementType(); 11554 EVT PartEltVT = PartVT.getVectorElementType(); 11555 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11556 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11557 if (PartVTBitSize % ValueVTBitSize == 0) { 11558 assert(PartVTBitSize >= ValueVTBitSize); 11559 EVT SameEltTypeVT = ValueVT; 11560 // If the element types are different, convert it to the same element type 11561 // of PartVT. 11562 // Give an example here, we want copy a <vscale x 1 x i8> value from 11563 // <vscale x 4 x i16>. 11564 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11565 // then we can extract <vscale x 1 x i8>. 11566 if (ValueEltVT != PartEltVT) { 11567 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11568 assert(Count != 0 && "The number of element should not be zero."); 11569 SameEltTypeVT = 11570 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11571 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11572 } 11573 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11574 DAG.getVectorIdxConstant(0, DL)); 11575 return Val; 11576 } 11577 } 11578 return SDValue(); 11579 } 11580 11581 SDValue 11582 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11583 SelectionDAG &DAG, 11584 SmallVectorImpl<SDNode *> &Created) const { 11585 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11586 if (isIntDivCheap(N->getValueType(0), Attr)) 11587 return SDValue(N, 0); // Lower SDIV as SDIV 11588 11589 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11590 "Unexpected divisor!"); 11591 11592 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11593 if (!Subtarget.hasStdExtZbt()) 11594 return SDValue(); 11595 11596 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11597 // Besides, more critical path instructions will be generated when dividing 11598 // by 2. So we keep using the original DAGs for these cases. 11599 unsigned Lg2 = Divisor.countTrailingZeros(); 11600 if (Lg2 == 1 || Lg2 >= 12) 11601 return SDValue(); 11602 11603 // fold (sdiv X, pow2) 11604 EVT VT = N->getValueType(0); 11605 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11606 return SDValue(); 11607 11608 SDLoc DL(N); 11609 SDValue N0 = N->getOperand(0); 11610 SDValue Zero = DAG.getConstant(0, DL, VT); 11611 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11612 11613 // Add (N0 < 0) ? Pow2 - 1 : 0; 11614 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11615 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11616 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11617 11618 Created.push_back(Cmp.getNode()); 11619 Created.push_back(Add.getNode()); 11620 Created.push_back(Sel.getNode()); 11621 11622 // Divide by pow2. 11623 SDValue SRA = 11624 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11625 11626 // If we're dividing by a positive value, we're done. Otherwise, we must 11627 // negate the result. 11628 if (Divisor.isNonNegative()) 11629 return SRA; 11630 11631 Created.push_back(SRA.getNode()); 11632 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11633 } 11634 11635 #define GET_REGISTER_MATCHER 11636 #include "RISCVGenAsmMatcher.inc" 11637 11638 Register 11639 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11640 const MachineFunction &MF) const { 11641 Register Reg = MatchRegisterAltName(RegName); 11642 if (Reg == RISCV::NoRegister) 11643 Reg = MatchRegisterName(RegName); 11644 if (Reg == RISCV::NoRegister) 11645 report_fatal_error( 11646 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11647 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11648 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11649 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11650 StringRef(RegName) + "\".")); 11651 return Reg; 11652 } 11653 11654 namespace llvm { 11655 namespace RISCVVIntrinsicsTable { 11656 11657 #define GET_RISCVVIntrinsicsTable_IMPL 11658 #include "RISCVGenSearchableTables.inc" 11659 11660 } // namespace RISCVVIntrinsicsTable 11661 11662 } // namespace llvm 11663