1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 116 assert(Size <= 512 && isPowerOf2_32(Size)); 117 const TargetRegisterClass *RC; 118 if (Size <= 64) 119 RC = &RISCV::VRRegClass; 120 else if (Size == 128) 121 RC = &RISCV::VRM2RegClass; 122 else if (Size == 256) 123 RC = &RISCV::VRM4RegClass; 124 else 125 RC = &RISCV::VRM8RegClass; 126 127 addRegisterClass(VT, RC); 128 }; 129 130 for (MVT VT : BoolVecVTs) 131 addRegClassForRVV(VT); 132 for (MVT VT : IntVecVTs) { 133 if (VT.getVectorElementType() == MVT::i64 && 134 !Subtarget.hasVInstructionsI64()) 135 continue; 136 addRegClassForRVV(VT); 137 } 138 139 if (Subtarget.hasVInstructionsF16()) 140 for (MVT VT : F16VecVTs) 141 addRegClassForRVV(VT); 142 143 if (Subtarget.hasVInstructionsF32()) 144 for (MVT VT : F32VecVTs) 145 addRegClassForRVV(VT); 146 147 if (Subtarget.hasVInstructionsF64()) 148 for (MVT VT : F64VecVTs) 149 addRegClassForRVV(VT); 150 151 if (Subtarget.useRVVForFixedLengthVectors()) { 152 auto addRegClassForFixedVectors = [this](MVT VT) { 153 MVT ContainerVT = getContainerForFixedLengthVector(VT); 154 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 155 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 156 addRegisterClass(VT, TRI.getRegClass(RCID)); 157 }; 158 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 159 if (useRVVForFixedLengthVectorVT(VT)) 160 addRegClassForFixedVectors(VT); 161 162 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 163 if (useRVVForFixedLengthVectorVT(VT)) 164 addRegClassForFixedVectors(VT); 165 } 166 } 167 168 // Compute derived properties from the register classes. 169 computeRegisterProperties(STI.getRegisterInfo()); 170 171 setStackPointerRegisterToSaveRestore(RISCV::X2); 172 173 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 174 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 175 176 // TODO: add all necessary setOperationAction calls. 177 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 178 179 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 180 setOperationAction(ISD::BR_CC, XLenVT, Expand); 181 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 182 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 183 184 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 185 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 186 187 setOperationAction(ISD::VASTART, MVT::Other, Custom); 188 setOperationAction(ISD::VAARG, MVT::Other, Expand); 189 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 190 setOperationAction(ISD::VAEND, MVT::Other, Expand); 191 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 193 if (!Subtarget.hasStdExtZbb()) { 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 196 } 197 198 if (Subtarget.is64Bit()) { 199 setOperationAction(ISD::ADD, MVT::i32, Custom); 200 setOperationAction(ISD::SUB, MVT::i32, Custom); 201 setOperationAction(ISD::SHL, MVT::i32, Custom); 202 setOperationAction(ISD::SRA, MVT::i32, Custom); 203 setOperationAction(ISD::SRL, MVT::i32, Custom); 204 205 setOperationAction(ISD::UADDO, MVT::i32, Custom); 206 setOperationAction(ISD::USUBO, MVT::i32, Custom); 207 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 208 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 209 } else { 210 setLibcallName(RTLIB::SHL_I128, nullptr); 211 setLibcallName(RTLIB::SRL_I128, nullptr); 212 setLibcallName(RTLIB::SRA_I128, nullptr); 213 setLibcallName(RTLIB::MUL_I128, nullptr); 214 setLibcallName(RTLIB::MULO_I64, nullptr); 215 } 216 217 if (!Subtarget.hasStdExtM()) { 218 setOperationAction(ISD::MUL, XLenVT, Expand); 219 setOperationAction(ISD::MULHS, XLenVT, Expand); 220 setOperationAction(ISD::MULHU, XLenVT, Expand); 221 setOperationAction(ISD::SDIV, XLenVT, Expand); 222 setOperationAction(ISD::UDIV, XLenVT, Expand); 223 setOperationAction(ISD::SREM, XLenVT, Expand); 224 setOperationAction(ISD::UREM, XLenVT, Expand); 225 } else { 226 if (Subtarget.is64Bit()) { 227 setOperationAction(ISD::MUL, MVT::i32, Custom); 228 setOperationAction(ISD::MUL, MVT::i128, Custom); 229 230 setOperationAction(ISD::SDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UDIV, MVT::i8, Custom); 232 setOperationAction(ISD::UREM, MVT::i8, Custom); 233 setOperationAction(ISD::SDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UDIV, MVT::i16, Custom); 235 setOperationAction(ISD::UREM, MVT::i16, Custom); 236 setOperationAction(ISD::SDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UDIV, MVT::i32, Custom); 238 setOperationAction(ISD::UREM, MVT::i32, Custom); 239 } else { 240 setOperationAction(ISD::MUL, MVT::i64, Custom); 241 } 242 } 243 244 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 246 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 247 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 248 249 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 251 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 252 253 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 254 Subtarget.hasStdExtZbkb()) { 255 if (Subtarget.is64Bit()) { 256 setOperationAction(ISD::ROTL, MVT::i32, Custom); 257 setOperationAction(ISD::ROTR, MVT::i32, Custom); 258 } 259 } else { 260 setOperationAction(ISD::ROTL, XLenVT, Expand); 261 setOperationAction(ISD::ROTR, XLenVT, Expand); 262 } 263 264 if (Subtarget.hasStdExtZbp()) { 265 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 266 // more combining. 267 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 268 setOperationAction(ISD::BSWAP, XLenVT, Custom); 269 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 270 // BSWAP i8 doesn't exist. 271 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 272 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 273 274 if (Subtarget.is64Bit()) { 275 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 276 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 277 } 278 } else { 279 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 280 // pattern match it directly in isel. 281 setOperationAction(ISD::BSWAP, XLenVT, 282 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 283 ? Legal 284 : Expand); 285 // Zbkb can use rev8+brev8 to implement bitreverse. 286 setOperationAction(ISD::BITREVERSE, XLenVT, 287 Subtarget.hasStdExtZbkb() ? Custom : Expand); 288 } 289 290 if (Subtarget.hasStdExtZbb()) { 291 setOperationAction(ISD::SMIN, XLenVT, Legal); 292 setOperationAction(ISD::SMAX, XLenVT, Legal); 293 setOperationAction(ISD::UMIN, XLenVT, Legal); 294 setOperationAction(ISD::UMAX, XLenVT, Legal); 295 296 if (Subtarget.is64Bit()) { 297 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 298 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 299 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 300 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 301 } 302 } else { 303 setOperationAction(ISD::CTTZ, XLenVT, Expand); 304 setOperationAction(ISD::CTLZ, XLenVT, Expand); 305 setOperationAction(ISD::CTPOP, XLenVT, Expand); 306 307 if (Subtarget.is64Bit()) 308 setOperationAction(ISD::ABS, MVT::i32, Custom); 309 } 310 311 if (Subtarget.hasStdExtZbt()) { 312 setOperationAction(ISD::FSHL, XLenVT, Custom); 313 setOperationAction(ISD::FSHR, XLenVT, Custom); 314 setOperationAction(ISD::SELECT, XLenVT, Legal); 315 316 if (Subtarget.is64Bit()) { 317 setOperationAction(ISD::FSHL, MVT::i32, Custom); 318 setOperationAction(ISD::FSHR, MVT::i32, Custom); 319 } 320 } else { 321 setOperationAction(ISD::SELECT, XLenVT, Custom); 322 } 323 324 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 325 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 326 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 327 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 328 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 329 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 330 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 331 332 static const ISD::CondCode FPCCToExpand[] = { 333 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 334 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 335 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 336 337 static const ISD::NodeType FPOpToExpand[] = { 338 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 339 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 340 341 if (Subtarget.hasStdExtZfh()) 342 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 343 344 if (Subtarget.hasStdExtZfh()) { 345 for (auto NT : FPLegalNodeTypes) 346 setOperationAction(NT, MVT::f16, Legal); 347 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 348 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 349 for (auto CC : FPCCToExpand) 350 setCondCodeAction(CC, MVT::f16, Expand); 351 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 352 setOperationAction(ISD::SELECT, MVT::f16, Custom); 353 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 354 355 setOperationAction(ISD::FREM, MVT::f16, Promote); 356 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 357 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 358 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 359 setOperationAction(ISD::FRINT, MVT::f16, Promote); 360 setOperationAction(ISD::FROUND, MVT::f16, Promote); 361 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 362 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 363 setOperationAction(ISD::FPOW, MVT::f16, Promote); 364 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 365 setOperationAction(ISD::FCOS, MVT::f16, Promote); 366 setOperationAction(ISD::FSIN, MVT::f16, Promote); 367 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 368 setOperationAction(ISD::FEXP, MVT::f16, Promote); 369 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 370 setOperationAction(ISD::FLOG, MVT::f16, Promote); 371 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 372 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 373 374 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 375 // complete support for all operations in LegalizeDAG. 376 377 // We need to custom promote this. 378 if (Subtarget.is64Bit()) 379 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 380 } 381 382 if (Subtarget.hasStdExtF()) { 383 for (auto NT : FPLegalNodeTypes) 384 setOperationAction(NT, MVT::f32, Legal); 385 for (auto CC : FPCCToExpand) 386 setCondCodeAction(CC, MVT::f32, Expand); 387 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 388 setOperationAction(ISD::SELECT, MVT::f32, Custom); 389 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 390 for (auto Op : FPOpToExpand) 391 setOperationAction(Op, MVT::f32, Expand); 392 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 393 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 394 } 395 396 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 397 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 398 399 if (Subtarget.hasStdExtD()) { 400 for (auto NT : FPLegalNodeTypes) 401 setOperationAction(NT, MVT::f64, Legal); 402 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 403 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 404 for (auto CC : FPCCToExpand) 405 setCondCodeAction(CC, MVT::f64, Expand); 406 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 407 setOperationAction(ISD::SELECT, MVT::f64, Custom); 408 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 409 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 410 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 411 for (auto Op : FPOpToExpand) 412 setOperationAction(Op, MVT::f64, Expand); 413 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 414 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 415 } 416 417 if (Subtarget.is64Bit()) { 418 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 419 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 420 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 421 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 422 } 423 424 if (Subtarget.hasStdExtF()) { 425 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 426 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 427 428 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 429 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 430 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 431 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 432 433 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 434 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 435 } 436 437 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 438 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 439 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 440 setOperationAction(ISD::JumpTable, XLenVT, Custom); 441 442 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 443 444 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 445 // Unfortunately this can't be determined just from the ISA naming string. 446 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 447 Subtarget.is64Bit() ? Legal : Custom); 448 449 setOperationAction(ISD::TRAP, MVT::Other, Legal); 450 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 451 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 452 if (Subtarget.is64Bit()) 453 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 454 455 if (Subtarget.hasStdExtA()) { 456 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 457 setMinCmpXchgSizeInBits(32); 458 } else { 459 setMaxAtomicSizeInBitsSupported(0); 460 } 461 462 setBooleanContents(ZeroOrOneBooleanContent); 463 464 if (Subtarget.hasVInstructions()) { 465 setBooleanVectorContents(ZeroOrOneBooleanContent); 466 467 setOperationAction(ISD::VSCALE, XLenVT, Custom); 468 469 // RVV intrinsics may have illegal operands. 470 // We also need to custom legalize vmv.x.s. 471 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 474 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 475 if (Subtarget.is64Bit()) { 476 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 477 } else { 478 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 479 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 480 } 481 482 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 483 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 484 485 static const unsigned IntegerVPOps[] = { 486 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 487 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 488 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 489 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 490 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 491 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 492 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 493 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FPTOSI, 494 ISD::VP_FPTOUI}; 495 496 static const unsigned FloatingPointVPOps[] = { 497 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 498 ISD::VP_FDIV, ISD::VP_FNEG, ISD::VP_FMA, 499 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN, 500 ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, ISD::VP_SELECT, 501 ISD::VP_SITOFP, ISD::VP_UITOFP}; 502 503 if (!Subtarget.is64Bit()) { 504 // We must custom-lower certain vXi64 operations on RV32 due to the vector 505 // element type being illegal. 506 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 507 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 508 509 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 510 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 511 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 512 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 513 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 514 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 515 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 516 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 517 518 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 519 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 520 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 521 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 522 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 523 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 524 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 525 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 526 } 527 528 for (MVT VT : BoolVecVTs) { 529 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 530 531 // Mask VTs are custom-expanded into a series of standard nodes 532 setOperationAction(ISD::TRUNCATE, VT, Custom); 533 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 534 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 535 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 536 537 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 538 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 539 540 setOperationAction(ISD::SELECT, VT, Custom); 541 setOperationAction(ISD::SELECT_CC, VT, Expand); 542 setOperationAction(ISD::VSELECT, VT, Expand); 543 setOperationAction(ISD::VP_MERGE, VT, Expand); 544 setOperationAction(ISD::VP_SELECT, VT, Expand); 545 546 setOperationAction(ISD::VP_AND, VT, Custom); 547 setOperationAction(ISD::VP_OR, VT, Custom); 548 setOperationAction(ISD::VP_XOR, VT, Custom); 549 550 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 551 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 552 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 553 554 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 555 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 556 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 557 558 // RVV has native int->float & float->int conversions where the 559 // element type sizes are within one power-of-two of each other. Any 560 // wider distances between type sizes have to be lowered as sequences 561 // which progressively narrow the gap in stages. 562 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 563 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 564 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 565 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 566 567 // Expand all extending loads to types larger than this, and truncating 568 // stores from types larger than this. 569 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 570 setTruncStoreAction(OtherVT, VT, Expand); 571 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 572 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 573 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 574 } 575 } 576 577 for (MVT VT : IntVecVTs) { 578 if (VT.getVectorElementType() == MVT::i64 && 579 !Subtarget.hasVInstructionsI64()) 580 continue; 581 582 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 583 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 584 585 // Vectors implement MULHS/MULHU. 586 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 587 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 588 589 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 590 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 591 setOperationAction(ISD::MULHU, VT, Expand); 592 setOperationAction(ISD::MULHS, VT, Expand); 593 } 594 595 setOperationAction(ISD::SMIN, VT, Legal); 596 setOperationAction(ISD::SMAX, VT, Legal); 597 setOperationAction(ISD::UMIN, VT, Legal); 598 setOperationAction(ISD::UMAX, VT, Legal); 599 600 setOperationAction(ISD::ROTL, VT, Expand); 601 setOperationAction(ISD::ROTR, VT, Expand); 602 603 setOperationAction(ISD::CTTZ, VT, Expand); 604 setOperationAction(ISD::CTLZ, VT, Expand); 605 setOperationAction(ISD::CTPOP, VT, Expand); 606 607 setOperationAction(ISD::BSWAP, VT, Expand); 608 609 // Custom-lower extensions and truncations from/to mask types. 610 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 611 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 612 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 613 614 // RVV has native int->float & float->int conversions where the 615 // element type sizes are within one power-of-two of each other. Any 616 // wider distances between type sizes have to be lowered as sequences 617 // which progressively narrow the gap in stages. 618 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 619 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 620 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 621 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 622 623 setOperationAction(ISD::SADDSAT, VT, Legal); 624 setOperationAction(ISD::UADDSAT, VT, Legal); 625 setOperationAction(ISD::SSUBSAT, VT, Legal); 626 setOperationAction(ISD::USUBSAT, VT, Legal); 627 628 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 629 // nodes which truncate by one power of two at a time. 630 setOperationAction(ISD::TRUNCATE, VT, Custom); 631 632 // Custom-lower insert/extract operations to simplify patterns. 633 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 634 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 635 636 // Custom-lower reduction operations to set up the corresponding custom 637 // nodes' operands. 638 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 639 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 640 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 641 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 642 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 643 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 644 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 645 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 646 647 for (unsigned VPOpc : IntegerVPOps) 648 setOperationAction(VPOpc, VT, Custom); 649 650 setOperationAction(ISD::LOAD, VT, Custom); 651 setOperationAction(ISD::STORE, VT, Custom); 652 653 setOperationAction(ISD::MLOAD, VT, Custom); 654 setOperationAction(ISD::MSTORE, VT, Custom); 655 setOperationAction(ISD::MGATHER, VT, Custom); 656 setOperationAction(ISD::MSCATTER, VT, Custom); 657 658 setOperationAction(ISD::VP_LOAD, VT, Custom); 659 setOperationAction(ISD::VP_STORE, VT, Custom); 660 setOperationAction(ISD::VP_GATHER, VT, Custom); 661 setOperationAction(ISD::VP_SCATTER, VT, Custom); 662 663 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 664 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 665 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 666 667 setOperationAction(ISD::SELECT, VT, Custom); 668 setOperationAction(ISD::SELECT_CC, VT, Expand); 669 670 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 671 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 672 673 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 674 setTruncStoreAction(VT, OtherVT, Expand); 675 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 676 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 677 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 678 } 679 680 // Splice 681 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 682 683 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 684 // type that can represent the value exactly. 685 if (VT.getVectorElementType() != MVT::i64) { 686 MVT FloatEltVT = 687 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 688 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 689 if (isTypeLegal(FloatVT)) { 690 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 691 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 692 } 693 } 694 } 695 696 // Expand various CCs to best match the RVV ISA, which natively supports UNE 697 // but no other unordered comparisons, and supports all ordered comparisons 698 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 699 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 700 // and we pattern-match those back to the "original", swapping operands once 701 // more. This way we catch both operations and both "vf" and "fv" forms with 702 // fewer patterns. 703 static const ISD::CondCode VFPCCToExpand[] = { 704 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 705 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 706 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 707 }; 708 709 // Sets common operation actions on RVV floating-point vector types. 710 const auto SetCommonVFPActions = [&](MVT VT) { 711 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 712 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 713 // sizes are within one power-of-two of each other. Therefore conversions 714 // between vXf16 and vXf64 must be lowered as sequences which convert via 715 // vXf32. 716 setOperationAction(ISD::FP_ROUND, VT, Custom); 717 setOperationAction(ISD::FP_EXTEND, VT, Custom); 718 // Custom-lower insert/extract operations to simplify patterns. 719 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 720 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 721 // Expand various condition codes (explained above). 722 for (auto CC : VFPCCToExpand) 723 setCondCodeAction(CC, VT, Expand); 724 725 setOperationAction(ISD::FMINNUM, VT, Legal); 726 setOperationAction(ISD::FMAXNUM, VT, Legal); 727 728 setOperationAction(ISD::FTRUNC, VT, Custom); 729 setOperationAction(ISD::FCEIL, VT, Custom); 730 setOperationAction(ISD::FFLOOR, VT, Custom); 731 setOperationAction(ISD::FROUND, VT, Custom); 732 733 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 734 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 735 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 736 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 737 738 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 739 740 setOperationAction(ISD::LOAD, VT, Custom); 741 setOperationAction(ISD::STORE, VT, Custom); 742 743 setOperationAction(ISD::MLOAD, VT, Custom); 744 setOperationAction(ISD::MSTORE, VT, Custom); 745 setOperationAction(ISD::MGATHER, VT, Custom); 746 setOperationAction(ISD::MSCATTER, VT, Custom); 747 748 setOperationAction(ISD::VP_LOAD, VT, Custom); 749 setOperationAction(ISD::VP_STORE, VT, Custom); 750 setOperationAction(ISD::VP_GATHER, VT, Custom); 751 setOperationAction(ISD::VP_SCATTER, VT, Custom); 752 753 setOperationAction(ISD::SELECT, VT, Custom); 754 setOperationAction(ISD::SELECT_CC, VT, Expand); 755 756 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 757 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 758 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 759 760 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 761 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 762 763 for (unsigned VPOpc : FloatingPointVPOps) 764 setOperationAction(VPOpc, VT, Custom); 765 }; 766 767 // Sets common extload/truncstore actions on RVV floating-point vector 768 // types. 769 const auto SetCommonVFPExtLoadTruncStoreActions = 770 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 771 for (auto SmallVT : SmallerVTs) { 772 setTruncStoreAction(VT, SmallVT, Expand); 773 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 774 } 775 }; 776 777 if (Subtarget.hasVInstructionsF16()) 778 for (MVT VT : F16VecVTs) 779 SetCommonVFPActions(VT); 780 781 for (MVT VT : F32VecVTs) { 782 if (Subtarget.hasVInstructionsF32()) 783 SetCommonVFPActions(VT); 784 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 785 } 786 787 for (MVT VT : F64VecVTs) { 788 if (Subtarget.hasVInstructionsF64()) 789 SetCommonVFPActions(VT); 790 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 791 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 792 } 793 794 if (Subtarget.useRVVForFixedLengthVectors()) { 795 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 796 if (!useRVVForFixedLengthVectorVT(VT)) 797 continue; 798 799 // By default everything must be expanded. 800 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 801 setOperationAction(Op, VT, Expand); 802 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 803 setTruncStoreAction(VT, OtherVT, Expand); 804 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 805 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 806 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 807 } 808 809 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 810 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 811 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 812 813 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 814 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 815 816 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 817 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 818 819 setOperationAction(ISD::LOAD, VT, Custom); 820 setOperationAction(ISD::STORE, VT, Custom); 821 822 setOperationAction(ISD::SETCC, VT, Custom); 823 824 setOperationAction(ISD::SELECT, VT, Custom); 825 826 setOperationAction(ISD::TRUNCATE, VT, Custom); 827 828 setOperationAction(ISD::BITCAST, VT, Custom); 829 830 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 831 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 832 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 833 834 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 835 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 836 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 837 838 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 839 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 840 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 841 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 842 843 // Operations below are different for between masks and other vectors. 844 if (VT.getVectorElementType() == MVT::i1) { 845 setOperationAction(ISD::VP_AND, VT, Custom); 846 setOperationAction(ISD::VP_OR, VT, Custom); 847 setOperationAction(ISD::VP_XOR, VT, Custom); 848 setOperationAction(ISD::AND, VT, Custom); 849 setOperationAction(ISD::OR, VT, Custom); 850 setOperationAction(ISD::XOR, VT, Custom); 851 852 setOperationAction(ISD::VP_FPTOSI, VT, Custom); 853 setOperationAction(ISD::VP_FPTOUI, VT, Custom); 854 continue; 855 } 856 857 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 858 // it before type legalization for i64 vectors on RV32. It will then be 859 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 860 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 861 // improvements first. 862 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 863 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 864 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 865 } 866 867 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 868 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 869 870 setOperationAction(ISD::MLOAD, VT, Custom); 871 setOperationAction(ISD::MSTORE, VT, Custom); 872 setOperationAction(ISD::MGATHER, VT, Custom); 873 setOperationAction(ISD::MSCATTER, VT, Custom); 874 875 setOperationAction(ISD::VP_LOAD, VT, Custom); 876 setOperationAction(ISD::VP_STORE, VT, Custom); 877 setOperationAction(ISD::VP_GATHER, VT, Custom); 878 setOperationAction(ISD::VP_SCATTER, VT, Custom); 879 880 setOperationAction(ISD::ADD, VT, Custom); 881 setOperationAction(ISD::MUL, VT, Custom); 882 setOperationAction(ISD::SUB, VT, Custom); 883 setOperationAction(ISD::AND, VT, Custom); 884 setOperationAction(ISD::OR, VT, Custom); 885 setOperationAction(ISD::XOR, VT, Custom); 886 setOperationAction(ISD::SDIV, VT, Custom); 887 setOperationAction(ISD::SREM, VT, Custom); 888 setOperationAction(ISD::UDIV, VT, Custom); 889 setOperationAction(ISD::UREM, VT, Custom); 890 setOperationAction(ISD::SHL, VT, Custom); 891 setOperationAction(ISD::SRA, VT, Custom); 892 setOperationAction(ISD::SRL, VT, Custom); 893 894 setOperationAction(ISD::SMIN, VT, Custom); 895 setOperationAction(ISD::SMAX, VT, Custom); 896 setOperationAction(ISD::UMIN, VT, Custom); 897 setOperationAction(ISD::UMAX, VT, Custom); 898 setOperationAction(ISD::ABS, VT, Custom); 899 900 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 901 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 902 setOperationAction(ISD::MULHS, VT, Custom); 903 setOperationAction(ISD::MULHU, VT, Custom); 904 } 905 906 setOperationAction(ISD::SADDSAT, VT, Custom); 907 setOperationAction(ISD::UADDSAT, VT, Custom); 908 setOperationAction(ISD::SSUBSAT, VT, Custom); 909 setOperationAction(ISD::USUBSAT, VT, Custom); 910 911 setOperationAction(ISD::VSELECT, VT, Custom); 912 setOperationAction(ISD::SELECT_CC, VT, Expand); 913 914 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 915 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 916 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 917 918 // Custom-lower reduction operations to set up the corresponding custom 919 // nodes' operands. 920 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 921 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 922 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 923 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 924 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 925 926 for (unsigned VPOpc : IntegerVPOps) 927 setOperationAction(VPOpc, VT, Custom); 928 929 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 930 // type that can represent the value exactly. 931 if (VT.getVectorElementType() != MVT::i64) { 932 MVT FloatEltVT = 933 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 934 EVT FloatVT = 935 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 936 if (isTypeLegal(FloatVT)) { 937 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 938 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 939 } 940 } 941 } 942 943 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 944 if (!useRVVForFixedLengthVectorVT(VT)) 945 continue; 946 947 // By default everything must be expanded. 948 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 949 setOperationAction(Op, VT, Expand); 950 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 951 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 952 setTruncStoreAction(VT, OtherVT, Expand); 953 } 954 955 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 956 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 957 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 958 959 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 960 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 961 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 962 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 963 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 964 965 setOperationAction(ISD::LOAD, VT, Custom); 966 setOperationAction(ISD::STORE, VT, Custom); 967 setOperationAction(ISD::MLOAD, VT, Custom); 968 setOperationAction(ISD::MSTORE, VT, Custom); 969 setOperationAction(ISD::MGATHER, VT, Custom); 970 setOperationAction(ISD::MSCATTER, VT, Custom); 971 972 setOperationAction(ISD::VP_LOAD, VT, Custom); 973 setOperationAction(ISD::VP_STORE, VT, Custom); 974 setOperationAction(ISD::VP_GATHER, VT, Custom); 975 setOperationAction(ISD::VP_SCATTER, VT, Custom); 976 977 setOperationAction(ISD::FADD, VT, Custom); 978 setOperationAction(ISD::FSUB, VT, Custom); 979 setOperationAction(ISD::FMUL, VT, Custom); 980 setOperationAction(ISD::FDIV, VT, Custom); 981 setOperationAction(ISD::FNEG, VT, Custom); 982 setOperationAction(ISD::FABS, VT, Custom); 983 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 984 setOperationAction(ISD::FSQRT, VT, Custom); 985 setOperationAction(ISD::FMA, VT, Custom); 986 setOperationAction(ISD::FMINNUM, VT, Custom); 987 setOperationAction(ISD::FMAXNUM, VT, Custom); 988 989 setOperationAction(ISD::FP_ROUND, VT, Custom); 990 setOperationAction(ISD::FP_EXTEND, VT, Custom); 991 992 setOperationAction(ISD::FTRUNC, VT, Custom); 993 setOperationAction(ISD::FCEIL, VT, Custom); 994 setOperationAction(ISD::FFLOOR, VT, Custom); 995 setOperationAction(ISD::FROUND, VT, Custom); 996 997 for (auto CC : VFPCCToExpand) 998 setCondCodeAction(CC, VT, Expand); 999 1000 setOperationAction(ISD::VSELECT, VT, Custom); 1001 setOperationAction(ISD::SELECT, VT, Custom); 1002 setOperationAction(ISD::SELECT_CC, VT, Expand); 1003 1004 setOperationAction(ISD::BITCAST, VT, Custom); 1005 1006 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1007 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1008 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1009 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1010 1011 for (unsigned VPOpc : FloatingPointVPOps) 1012 setOperationAction(VPOpc, VT, Custom); 1013 } 1014 1015 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1016 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1017 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1018 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1019 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1020 if (Subtarget.hasStdExtZfh()) 1021 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1022 if (Subtarget.hasStdExtF()) 1023 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1024 if (Subtarget.hasStdExtD()) 1025 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1026 } 1027 } 1028 1029 // Function alignments. 1030 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1031 setMinFunctionAlignment(FunctionAlignment); 1032 setPrefFunctionAlignment(FunctionAlignment); 1033 1034 setMinimumJumpTableEntries(5); 1035 1036 // Jumps are expensive, compared to logic 1037 setJumpIsExpensive(); 1038 1039 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 1040 ISD::OR, ISD::XOR}); 1041 1042 if (Subtarget.hasStdExtZbp()) 1043 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 1044 if (Subtarget.hasStdExtZbkb()) 1045 setTargetDAGCombine(ISD::BITREVERSE); 1046 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 1047 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 1048 if (Subtarget.hasStdExtF()) 1049 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 1050 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 1051 if (Subtarget.hasVInstructions()) 1052 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 1053 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 1054 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 1055 1056 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1057 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1058 } 1059 1060 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1061 LLVMContext &Context, 1062 EVT VT) const { 1063 if (!VT.isVector()) 1064 return getPointerTy(DL); 1065 if (Subtarget.hasVInstructions() && 1066 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1067 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1068 return VT.changeVectorElementTypeToInteger(); 1069 } 1070 1071 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1072 return Subtarget.getXLenVT(); 1073 } 1074 1075 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1076 const CallInst &I, 1077 MachineFunction &MF, 1078 unsigned Intrinsic) const { 1079 auto &DL = I.getModule()->getDataLayout(); 1080 switch (Intrinsic) { 1081 default: 1082 return false; 1083 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1084 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1085 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1086 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1087 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1088 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1089 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1090 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1091 case Intrinsic::riscv_masked_cmpxchg_i32: 1092 Info.opc = ISD::INTRINSIC_W_CHAIN; 1093 Info.memVT = MVT::i32; 1094 Info.ptrVal = I.getArgOperand(0); 1095 Info.offset = 0; 1096 Info.align = Align(4); 1097 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1098 MachineMemOperand::MOVolatile; 1099 return true; 1100 case Intrinsic::riscv_masked_strided_load: 1101 Info.opc = ISD::INTRINSIC_W_CHAIN; 1102 Info.ptrVal = I.getArgOperand(1); 1103 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1104 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1105 Info.size = MemoryLocation::UnknownSize; 1106 Info.flags |= MachineMemOperand::MOLoad; 1107 return true; 1108 case Intrinsic::riscv_masked_strided_store: 1109 Info.opc = ISD::INTRINSIC_VOID; 1110 Info.ptrVal = I.getArgOperand(1); 1111 Info.memVT = 1112 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1113 Info.align = Align( 1114 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1115 8); 1116 Info.size = MemoryLocation::UnknownSize; 1117 Info.flags |= MachineMemOperand::MOStore; 1118 return true; 1119 case Intrinsic::riscv_seg2_load: 1120 case Intrinsic::riscv_seg3_load: 1121 case Intrinsic::riscv_seg4_load: 1122 case Intrinsic::riscv_seg5_load: 1123 case Intrinsic::riscv_seg6_load: 1124 case Intrinsic::riscv_seg7_load: 1125 case Intrinsic::riscv_seg8_load: 1126 Info.opc = ISD::INTRINSIC_W_CHAIN; 1127 Info.ptrVal = I.getArgOperand(0); 1128 Info.memVT = 1129 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1130 Info.align = 1131 Align(DL.getTypeSizeInBits( 1132 I.getType()->getStructElementType(0)->getScalarType()) / 1133 8); 1134 Info.size = MemoryLocation::UnknownSize; 1135 Info.flags |= MachineMemOperand::MOLoad; 1136 return true; 1137 } 1138 } 1139 1140 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1141 const AddrMode &AM, Type *Ty, 1142 unsigned AS, 1143 Instruction *I) const { 1144 // No global is ever allowed as a base. 1145 if (AM.BaseGV) 1146 return false; 1147 1148 // Require a 12-bit signed offset. 1149 if (!isInt<12>(AM.BaseOffs)) 1150 return false; 1151 1152 switch (AM.Scale) { 1153 case 0: // "r+i" or just "i", depending on HasBaseReg. 1154 break; 1155 case 1: 1156 if (!AM.HasBaseReg) // allow "r+i". 1157 break; 1158 return false; // disallow "r+r" or "r+r+i". 1159 default: 1160 return false; 1161 } 1162 1163 return true; 1164 } 1165 1166 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1167 return isInt<12>(Imm); 1168 } 1169 1170 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1171 return isInt<12>(Imm); 1172 } 1173 1174 // On RV32, 64-bit integers are split into their high and low parts and held 1175 // in two different registers, so the trunc is free since the low register can 1176 // just be used. 1177 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1178 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1179 return false; 1180 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1181 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1182 return (SrcBits == 64 && DestBits == 32); 1183 } 1184 1185 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1186 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1187 !SrcVT.isInteger() || !DstVT.isInteger()) 1188 return false; 1189 unsigned SrcBits = SrcVT.getSizeInBits(); 1190 unsigned DestBits = DstVT.getSizeInBits(); 1191 return (SrcBits == 64 && DestBits == 32); 1192 } 1193 1194 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1195 // Zexts are free if they can be combined with a load. 1196 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1197 // poorly with type legalization of compares preferring sext. 1198 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1199 EVT MemVT = LD->getMemoryVT(); 1200 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1201 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1202 LD->getExtensionType() == ISD::ZEXTLOAD)) 1203 return true; 1204 } 1205 1206 return TargetLowering::isZExtFree(Val, VT2); 1207 } 1208 1209 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1210 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1211 } 1212 1213 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1214 return Subtarget.hasStdExtZbb(); 1215 } 1216 1217 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1218 return Subtarget.hasStdExtZbb(); 1219 } 1220 1221 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1222 EVT VT = Y.getValueType(); 1223 1224 // FIXME: Support vectors once we have tests. 1225 if (VT.isVector()) 1226 return false; 1227 1228 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1229 Subtarget.hasStdExtZbkb()) && 1230 !isa<ConstantSDNode>(Y); 1231 } 1232 1233 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1234 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1235 auto *C = dyn_cast<ConstantSDNode>(Y); 1236 return C && C->getAPIntValue().ule(10); 1237 } 1238 1239 /// Check if sinking \p I's operands to I's basic block is profitable, because 1240 /// the operands can be folded into a target instruction, e.g. 1241 /// splats of scalars can fold into vector instructions. 1242 bool RISCVTargetLowering::shouldSinkOperands( 1243 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1244 using namespace llvm::PatternMatch; 1245 1246 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1247 return false; 1248 1249 auto IsSinker = [&](Instruction *I, int Operand) { 1250 switch (I->getOpcode()) { 1251 case Instruction::Add: 1252 case Instruction::Sub: 1253 case Instruction::Mul: 1254 case Instruction::And: 1255 case Instruction::Or: 1256 case Instruction::Xor: 1257 case Instruction::FAdd: 1258 case Instruction::FSub: 1259 case Instruction::FMul: 1260 case Instruction::FDiv: 1261 case Instruction::ICmp: 1262 case Instruction::FCmp: 1263 return true; 1264 case Instruction::Shl: 1265 case Instruction::LShr: 1266 case Instruction::AShr: 1267 case Instruction::UDiv: 1268 case Instruction::SDiv: 1269 case Instruction::URem: 1270 case Instruction::SRem: 1271 return Operand == 1; 1272 case Instruction::Call: 1273 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1274 switch (II->getIntrinsicID()) { 1275 case Intrinsic::fma: 1276 case Intrinsic::vp_fma: 1277 return Operand == 0 || Operand == 1; 1278 // FIXME: Our patterns can only match vx/vf instructions when the splat 1279 // it on the RHS, because TableGen doesn't recognize our VP operations 1280 // as commutative. 1281 case Intrinsic::vp_add: 1282 case Intrinsic::vp_mul: 1283 case Intrinsic::vp_and: 1284 case Intrinsic::vp_or: 1285 case Intrinsic::vp_xor: 1286 case Intrinsic::vp_fadd: 1287 case Intrinsic::vp_fmul: 1288 case Intrinsic::vp_shl: 1289 case Intrinsic::vp_lshr: 1290 case Intrinsic::vp_ashr: 1291 case Intrinsic::vp_udiv: 1292 case Intrinsic::vp_sdiv: 1293 case Intrinsic::vp_urem: 1294 case Intrinsic::vp_srem: 1295 return Operand == 1; 1296 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1297 // explicit patterns for both LHS and RHS (as 'vr' versions). 1298 case Intrinsic::vp_sub: 1299 case Intrinsic::vp_fsub: 1300 case Intrinsic::vp_fdiv: 1301 return Operand == 0 || Operand == 1; 1302 default: 1303 return false; 1304 } 1305 } 1306 return false; 1307 default: 1308 return false; 1309 } 1310 }; 1311 1312 for (auto OpIdx : enumerate(I->operands())) { 1313 if (!IsSinker(I, OpIdx.index())) 1314 continue; 1315 1316 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1317 // Make sure we are not already sinking this operand 1318 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1319 continue; 1320 1321 // We are looking for a splat that can be sunk. 1322 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1323 m_Undef(), m_ZeroMask()))) 1324 continue; 1325 1326 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1327 // and vector registers 1328 for (Use &U : Op->uses()) { 1329 Instruction *Insn = cast<Instruction>(U.getUser()); 1330 if (!IsSinker(Insn, U.getOperandNo())) 1331 return false; 1332 } 1333 1334 Ops.push_back(&Op->getOperandUse(0)); 1335 Ops.push_back(&OpIdx.value()); 1336 } 1337 return true; 1338 } 1339 1340 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1341 bool ForCodeSize) const { 1342 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1343 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1344 return false; 1345 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1346 return false; 1347 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1348 return false; 1349 return Imm.isZero(); 1350 } 1351 1352 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1353 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1354 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1355 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1356 } 1357 1358 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1359 CallingConv::ID CC, 1360 EVT VT) const { 1361 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1362 // We might still end up using a GPR but that will be decided based on ABI. 1363 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1364 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1365 return MVT::f32; 1366 1367 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1368 } 1369 1370 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1371 CallingConv::ID CC, 1372 EVT VT) const { 1373 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1374 // We might still end up using a GPR but that will be decided based on ABI. 1375 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1376 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1377 return 1; 1378 1379 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1380 } 1381 1382 // Changes the condition code and swaps operands if necessary, so the SetCC 1383 // operation matches one of the comparisons supported directly by branches 1384 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1385 // with 1/-1. 1386 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1387 ISD::CondCode &CC, SelectionDAG &DAG) { 1388 // Convert X > -1 to X >= 0. 1389 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1390 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1391 CC = ISD::SETGE; 1392 return; 1393 } 1394 // Convert X < 1 to 0 >= X. 1395 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1396 RHS = LHS; 1397 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1398 CC = ISD::SETGE; 1399 return; 1400 } 1401 1402 switch (CC) { 1403 default: 1404 break; 1405 case ISD::SETGT: 1406 case ISD::SETLE: 1407 case ISD::SETUGT: 1408 case ISD::SETULE: 1409 CC = ISD::getSetCCSwappedOperands(CC); 1410 std::swap(LHS, RHS); 1411 break; 1412 } 1413 } 1414 1415 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1416 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1417 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1418 if (VT.getVectorElementType() == MVT::i1) 1419 KnownSize *= 8; 1420 1421 switch (KnownSize) { 1422 default: 1423 llvm_unreachable("Invalid LMUL."); 1424 case 8: 1425 return RISCVII::VLMUL::LMUL_F8; 1426 case 16: 1427 return RISCVII::VLMUL::LMUL_F4; 1428 case 32: 1429 return RISCVII::VLMUL::LMUL_F2; 1430 case 64: 1431 return RISCVII::VLMUL::LMUL_1; 1432 case 128: 1433 return RISCVII::VLMUL::LMUL_2; 1434 case 256: 1435 return RISCVII::VLMUL::LMUL_4; 1436 case 512: 1437 return RISCVII::VLMUL::LMUL_8; 1438 } 1439 } 1440 1441 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1442 switch (LMul) { 1443 default: 1444 llvm_unreachable("Invalid LMUL."); 1445 case RISCVII::VLMUL::LMUL_F8: 1446 case RISCVII::VLMUL::LMUL_F4: 1447 case RISCVII::VLMUL::LMUL_F2: 1448 case RISCVII::VLMUL::LMUL_1: 1449 return RISCV::VRRegClassID; 1450 case RISCVII::VLMUL::LMUL_2: 1451 return RISCV::VRM2RegClassID; 1452 case RISCVII::VLMUL::LMUL_4: 1453 return RISCV::VRM4RegClassID; 1454 case RISCVII::VLMUL::LMUL_8: 1455 return RISCV::VRM8RegClassID; 1456 } 1457 } 1458 1459 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1460 RISCVII::VLMUL LMUL = getLMUL(VT); 1461 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1462 LMUL == RISCVII::VLMUL::LMUL_F4 || 1463 LMUL == RISCVII::VLMUL::LMUL_F2 || 1464 LMUL == RISCVII::VLMUL::LMUL_1) { 1465 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1466 "Unexpected subreg numbering"); 1467 return RISCV::sub_vrm1_0 + Index; 1468 } 1469 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1470 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1471 "Unexpected subreg numbering"); 1472 return RISCV::sub_vrm2_0 + Index; 1473 } 1474 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1475 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1476 "Unexpected subreg numbering"); 1477 return RISCV::sub_vrm4_0 + Index; 1478 } 1479 llvm_unreachable("Invalid vector type."); 1480 } 1481 1482 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1483 if (VT.getVectorElementType() == MVT::i1) 1484 return RISCV::VRRegClassID; 1485 return getRegClassIDForLMUL(getLMUL(VT)); 1486 } 1487 1488 // Attempt to decompose a subvector insert/extract between VecVT and 1489 // SubVecVT via subregister indices. Returns the subregister index that 1490 // can perform the subvector insert/extract with the given element index, as 1491 // well as the index corresponding to any leftover subvectors that must be 1492 // further inserted/extracted within the register class for SubVecVT. 1493 std::pair<unsigned, unsigned> 1494 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1495 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1496 const RISCVRegisterInfo *TRI) { 1497 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1498 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1499 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1500 "Register classes not ordered"); 1501 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1502 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1503 // Try to compose a subregister index that takes us from the incoming 1504 // LMUL>1 register class down to the outgoing one. At each step we half 1505 // the LMUL: 1506 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1507 // Note that this is not guaranteed to find a subregister index, such as 1508 // when we are extracting from one VR type to another. 1509 unsigned SubRegIdx = RISCV::NoSubRegister; 1510 for (const unsigned RCID : 1511 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1512 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1513 VecVT = VecVT.getHalfNumVectorElementsVT(); 1514 bool IsHi = 1515 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1516 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1517 getSubregIndexByMVT(VecVT, IsHi)); 1518 if (IsHi) 1519 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1520 } 1521 return {SubRegIdx, InsertExtractIdx}; 1522 } 1523 1524 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1525 // stores for those types. 1526 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1527 return !Subtarget.useRVVForFixedLengthVectors() || 1528 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1529 } 1530 1531 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1532 if (ScalarTy->isPointerTy()) 1533 return true; 1534 1535 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1536 ScalarTy->isIntegerTy(32)) 1537 return true; 1538 1539 if (ScalarTy->isIntegerTy(64)) 1540 return Subtarget.hasVInstructionsI64(); 1541 1542 if (ScalarTy->isHalfTy()) 1543 return Subtarget.hasVInstructionsF16(); 1544 if (ScalarTy->isFloatTy()) 1545 return Subtarget.hasVInstructionsF32(); 1546 if (ScalarTy->isDoubleTy()) 1547 return Subtarget.hasVInstructionsF64(); 1548 1549 return false; 1550 } 1551 1552 static SDValue getVLOperand(SDValue Op) { 1553 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1554 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1555 "Unexpected opcode"); 1556 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1557 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1558 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1559 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1560 if (!II) 1561 return SDValue(); 1562 return Op.getOperand(II->VLOperand + 1 + HasChain); 1563 } 1564 1565 static bool useRVVForFixedLengthVectorVT(MVT VT, 1566 const RISCVSubtarget &Subtarget) { 1567 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1568 if (!Subtarget.useRVVForFixedLengthVectors()) 1569 return false; 1570 1571 // We only support a set of vector types with a consistent maximum fixed size 1572 // across all supported vector element types to avoid legalization issues. 1573 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1574 // fixed-length vector type we support is 1024 bytes. 1575 if (VT.getFixedSizeInBits() > 1024 * 8) 1576 return false; 1577 1578 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1579 1580 MVT EltVT = VT.getVectorElementType(); 1581 1582 // Don't use RVV for vectors we cannot scalarize if required. 1583 switch (EltVT.SimpleTy) { 1584 // i1 is supported but has different rules. 1585 default: 1586 return false; 1587 case MVT::i1: 1588 // Masks can only use a single register. 1589 if (VT.getVectorNumElements() > MinVLen) 1590 return false; 1591 MinVLen /= 8; 1592 break; 1593 case MVT::i8: 1594 case MVT::i16: 1595 case MVT::i32: 1596 break; 1597 case MVT::i64: 1598 if (!Subtarget.hasVInstructionsI64()) 1599 return false; 1600 break; 1601 case MVT::f16: 1602 if (!Subtarget.hasVInstructionsF16()) 1603 return false; 1604 break; 1605 case MVT::f32: 1606 if (!Subtarget.hasVInstructionsF32()) 1607 return false; 1608 break; 1609 case MVT::f64: 1610 if (!Subtarget.hasVInstructionsF64()) 1611 return false; 1612 break; 1613 } 1614 1615 // Reject elements larger than ELEN. 1616 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1617 return false; 1618 1619 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1620 // Don't use RVV for types that don't fit. 1621 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1622 return false; 1623 1624 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1625 // the base fixed length RVV support in place. 1626 if (!VT.isPow2VectorType()) 1627 return false; 1628 1629 return true; 1630 } 1631 1632 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1633 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1634 } 1635 1636 // Return the largest legal scalable vector type that matches VT's element type. 1637 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1638 const RISCVSubtarget &Subtarget) { 1639 // This may be called before legal types are setup. 1640 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1641 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1642 "Expected legal fixed length vector!"); 1643 1644 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1645 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1646 1647 MVT EltVT = VT.getVectorElementType(); 1648 switch (EltVT.SimpleTy) { 1649 default: 1650 llvm_unreachable("unexpected element type for RVV container"); 1651 case MVT::i1: 1652 case MVT::i8: 1653 case MVT::i16: 1654 case MVT::i32: 1655 case MVT::i64: 1656 case MVT::f16: 1657 case MVT::f32: 1658 case MVT::f64: { 1659 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1660 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1661 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1662 unsigned NumElts = 1663 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1664 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1665 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1666 return MVT::getScalableVectorVT(EltVT, NumElts); 1667 } 1668 } 1669 } 1670 1671 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1672 const RISCVSubtarget &Subtarget) { 1673 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1674 Subtarget); 1675 } 1676 1677 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1678 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1679 } 1680 1681 // Grow V to consume an entire RVV register. 1682 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1683 const RISCVSubtarget &Subtarget) { 1684 assert(VT.isScalableVector() && 1685 "Expected to convert into a scalable vector!"); 1686 assert(V.getValueType().isFixedLengthVector() && 1687 "Expected a fixed length vector operand!"); 1688 SDLoc DL(V); 1689 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1690 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1691 } 1692 1693 // Shrink V so it's just big enough to maintain a VT's worth of data. 1694 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1695 const RISCVSubtarget &Subtarget) { 1696 assert(VT.isFixedLengthVector() && 1697 "Expected to convert into a fixed length vector!"); 1698 assert(V.getValueType().isScalableVector() && 1699 "Expected a scalable vector operand!"); 1700 SDLoc DL(V); 1701 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1702 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1703 } 1704 1705 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1706 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1707 // the vector type that it is contained in. 1708 static std::pair<SDValue, SDValue> 1709 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1710 const RISCVSubtarget &Subtarget) { 1711 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1712 MVT XLenVT = Subtarget.getXLenVT(); 1713 SDValue VL = VecVT.isFixedLengthVector() 1714 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1715 : DAG.getRegister(RISCV::X0, XLenVT); 1716 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1717 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1718 return {Mask, VL}; 1719 } 1720 1721 // As above but assuming the given type is a scalable vector type. 1722 static std::pair<SDValue, SDValue> 1723 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1724 const RISCVSubtarget &Subtarget) { 1725 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1726 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1727 } 1728 1729 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1730 // of either is (currently) supported. This can get us into an infinite loop 1731 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1732 // as a ..., etc. 1733 // Until either (or both) of these can reliably lower any node, reporting that 1734 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1735 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1736 // which is not desirable. 1737 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1738 EVT VT, unsigned DefinedValues) const { 1739 return false; 1740 } 1741 1742 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1743 const RISCVSubtarget &Subtarget) { 1744 // RISCV FP-to-int conversions saturate to the destination register size, but 1745 // don't produce 0 for nan. We can use a conversion instruction and fix the 1746 // nan case with a compare and a select. 1747 SDValue Src = Op.getOperand(0); 1748 1749 EVT DstVT = Op.getValueType(); 1750 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1751 1752 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1753 unsigned Opc; 1754 if (SatVT == DstVT) 1755 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1756 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1757 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1758 else 1759 return SDValue(); 1760 // FIXME: Support other SatVTs by clamping before or after the conversion. 1761 1762 SDLoc DL(Op); 1763 SDValue FpToInt = DAG.getNode( 1764 Opc, DL, DstVT, Src, 1765 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1766 1767 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1768 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1769 } 1770 1771 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1772 // and back. Taking care to avoid converting values that are nan or already 1773 // correct. 1774 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1775 // have FRM dependencies modeled yet. 1776 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1777 MVT VT = Op.getSimpleValueType(); 1778 assert(VT.isVector() && "Unexpected type"); 1779 1780 SDLoc DL(Op); 1781 1782 // Freeze the source since we are increasing the number of uses. 1783 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1784 1785 // Truncate to integer and convert back to FP. 1786 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1787 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1788 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1789 1790 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1791 1792 if (Op.getOpcode() == ISD::FCEIL) { 1793 // If the truncated value is the greater than or equal to the original 1794 // value, we've computed the ceil. Otherwise, we went the wrong way and 1795 // need to increase by 1. 1796 // FIXME: This should use a masked operation. Handle here or in isel? 1797 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1798 DAG.getConstantFP(1.0, DL, VT)); 1799 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1800 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1801 } else if (Op.getOpcode() == ISD::FFLOOR) { 1802 // If the truncated value is the less than or equal to the original value, 1803 // we've computed the floor. Otherwise, we went the wrong way and need to 1804 // decrease by 1. 1805 // FIXME: This should use a masked operation. Handle here or in isel? 1806 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1807 DAG.getConstantFP(1.0, DL, VT)); 1808 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1809 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1810 } 1811 1812 // Restore the original sign so that -0.0 is preserved. 1813 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1814 1815 // Determine the largest integer that can be represented exactly. This and 1816 // values larger than it don't have any fractional bits so don't need to 1817 // be converted. 1818 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1819 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1820 APFloat MaxVal = APFloat(FltSem); 1821 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1822 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1823 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1824 1825 // If abs(Src) was larger than MaxVal or nan, keep it. 1826 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1827 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1828 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1829 } 1830 1831 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1832 // This mode isn't supported in vector hardware on RISCV. But as long as we 1833 // aren't compiling with trapping math, we can emulate this with 1834 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1835 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1836 // dependencies modeled yet. 1837 // FIXME: Use masked operations to avoid final merge. 1838 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1839 MVT VT = Op.getSimpleValueType(); 1840 assert(VT.isVector() && "Unexpected type"); 1841 1842 SDLoc DL(Op); 1843 1844 // Freeze the source since we are increasing the number of uses. 1845 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1846 1847 // We do the conversion on the absolute value and fix the sign at the end. 1848 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1849 1850 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1851 bool Ignored; 1852 APFloat Point5Pred = APFloat(0.5f); 1853 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1854 Point5Pred.next(/*nextDown*/ true); 1855 1856 // Add the adjustment. 1857 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1858 DAG.getConstantFP(Point5Pred, DL, VT)); 1859 1860 // Truncate to integer and convert back to fp. 1861 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1862 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1863 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1864 1865 // Restore the original sign. 1866 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1867 1868 // Determine the largest integer that can be represented exactly. This and 1869 // values larger than it don't have any fractional bits so don't need to 1870 // be converted. 1871 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1872 APFloat MaxVal = APFloat(FltSem); 1873 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1874 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1875 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1876 1877 // If abs(Src) was larger than MaxVal or nan, keep it. 1878 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1879 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1880 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1881 } 1882 1883 struct VIDSequence { 1884 int64_t StepNumerator; 1885 unsigned StepDenominator; 1886 int64_t Addend; 1887 }; 1888 1889 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1890 // to the (non-zero) step S and start value X. This can be then lowered as the 1891 // RVV sequence (VID * S) + X, for example. 1892 // The step S is represented as an integer numerator divided by a positive 1893 // denominator. Note that the implementation currently only identifies 1894 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1895 // cannot detect 2/3, for example. 1896 // Note that this method will also match potentially unappealing index 1897 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1898 // determine whether this is worth generating code for. 1899 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1900 unsigned NumElts = Op.getNumOperands(); 1901 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1902 if (!Op.getValueType().isInteger()) 1903 return None; 1904 1905 Optional<unsigned> SeqStepDenom; 1906 Optional<int64_t> SeqStepNum, SeqAddend; 1907 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1908 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1909 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1910 // Assume undef elements match the sequence; we just have to be careful 1911 // when interpolating across them. 1912 if (Op.getOperand(Idx).isUndef()) 1913 continue; 1914 // The BUILD_VECTOR must be all constants. 1915 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1916 return None; 1917 1918 uint64_t Val = Op.getConstantOperandVal(Idx) & 1919 maskTrailingOnes<uint64_t>(EltSizeInBits); 1920 1921 if (PrevElt) { 1922 // Calculate the step since the last non-undef element, and ensure 1923 // it's consistent across the entire sequence. 1924 unsigned IdxDiff = Idx - PrevElt->second; 1925 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1926 1927 // A zero-value value difference means that we're somewhere in the middle 1928 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1929 // step change before evaluating the sequence. 1930 if (ValDiff != 0) { 1931 int64_t Remainder = ValDiff % IdxDiff; 1932 // Normalize the step if it's greater than 1. 1933 if (Remainder != ValDiff) { 1934 // The difference must cleanly divide the element span. 1935 if (Remainder != 0) 1936 return None; 1937 ValDiff /= IdxDiff; 1938 IdxDiff = 1; 1939 } 1940 1941 if (!SeqStepNum) 1942 SeqStepNum = ValDiff; 1943 else if (ValDiff != SeqStepNum) 1944 return None; 1945 1946 if (!SeqStepDenom) 1947 SeqStepDenom = IdxDiff; 1948 else if (IdxDiff != *SeqStepDenom) 1949 return None; 1950 } 1951 } 1952 1953 // Record and/or check any addend. 1954 if (SeqStepNum && SeqStepDenom) { 1955 uint64_t ExpectedVal = 1956 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1957 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1958 if (!SeqAddend) 1959 SeqAddend = Addend; 1960 else if (SeqAddend != Addend) 1961 return None; 1962 } 1963 1964 // Record this non-undef element for later. 1965 if (!PrevElt || PrevElt->first != Val) 1966 PrevElt = std::make_pair(Val, Idx); 1967 } 1968 // We need to have logged both a step and an addend for this to count as 1969 // a legal index sequence. 1970 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1971 return None; 1972 1973 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1974 } 1975 1976 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1977 // and lower it as a VRGATHER_VX_VL from the source vector. 1978 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1979 SelectionDAG &DAG, 1980 const RISCVSubtarget &Subtarget) { 1981 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1982 return SDValue(); 1983 SDValue Vec = SplatVal.getOperand(0); 1984 // Only perform this optimization on vectors of the same size for simplicity. 1985 if (Vec.getValueType() != VT) 1986 return SDValue(); 1987 SDValue Idx = SplatVal.getOperand(1); 1988 // The index must be a legal type. 1989 if (Idx.getValueType() != Subtarget.getXLenVT()) 1990 return SDValue(); 1991 1992 MVT ContainerVT = VT; 1993 if (VT.isFixedLengthVector()) { 1994 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1995 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1996 } 1997 1998 SDValue Mask, VL; 1999 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2000 2001 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2002 Idx, Mask, VL); 2003 2004 if (!VT.isFixedLengthVector()) 2005 return Gather; 2006 2007 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2008 } 2009 2010 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2011 const RISCVSubtarget &Subtarget) { 2012 MVT VT = Op.getSimpleValueType(); 2013 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2014 2015 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2016 2017 SDLoc DL(Op); 2018 SDValue Mask, VL; 2019 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2020 2021 MVT XLenVT = Subtarget.getXLenVT(); 2022 unsigned NumElts = Op.getNumOperands(); 2023 2024 if (VT.getVectorElementType() == MVT::i1) { 2025 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2026 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2027 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2028 } 2029 2030 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2031 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2032 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2033 } 2034 2035 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2036 // scalar integer chunks whose bit-width depends on the number of mask 2037 // bits and XLEN. 2038 // First, determine the most appropriate scalar integer type to use. This 2039 // is at most XLenVT, but may be shrunk to a smaller vector element type 2040 // according to the size of the final vector - use i8 chunks rather than 2041 // XLenVT if we're producing a v8i1. This results in more consistent 2042 // codegen across RV32 and RV64. 2043 unsigned NumViaIntegerBits = 2044 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2045 NumViaIntegerBits = std::min(NumViaIntegerBits, 2046 Subtarget.getMaxELENForFixedLengthVectors()); 2047 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2048 // If we have to use more than one INSERT_VECTOR_ELT then this 2049 // optimization is likely to increase code size; avoid peforming it in 2050 // such a case. We can use a load from a constant pool in this case. 2051 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2052 return SDValue(); 2053 // Now we can create our integer vector type. Note that it may be larger 2054 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2055 MVT IntegerViaVecVT = 2056 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2057 divideCeil(NumElts, NumViaIntegerBits)); 2058 2059 uint64_t Bits = 0; 2060 unsigned BitPos = 0, IntegerEltIdx = 0; 2061 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2062 2063 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2064 // Once we accumulate enough bits to fill our scalar type, insert into 2065 // our vector and clear our accumulated data. 2066 if (I != 0 && I % NumViaIntegerBits == 0) { 2067 if (NumViaIntegerBits <= 32) 2068 Bits = SignExtend64(Bits, 32); 2069 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2070 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2071 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2072 Bits = 0; 2073 BitPos = 0; 2074 IntegerEltIdx++; 2075 } 2076 SDValue V = Op.getOperand(I); 2077 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2078 Bits |= ((uint64_t)BitValue << BitPos); 2079 } 2080 2081 // Insert the (remaining) scalar value into position in our integer 2082 // vector type. 2083 if (NumViaIntegerBits <= 32) 2084 Bits = SignExtend64(Bits, 32); 2085 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2086 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2087 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2088 2089 if (NumElts < NumViaIntegerBits) { 2090 // If we're producing a smaller vector than our minimum legal integer 2091 // type, bitcast to the equivalent (known-legal) mask type, and extract 2092 // our final mask. 2093 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2094 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2095 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2096 DAG.getConstant(0, DL, XLenVT)); 2097 } else { 2098 // Else we must have produced an integer type with the same size as the 2099 // mask type; bitcast for the final result. 2100 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2101 Vec = DAG.getBitcast(VT, Vec); 2102 } 2103 2104 return Vec; 2105 } 2106 2107 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2108 // vector type, we have a legal equivalently-sized i8 type, so we can use 2109 // that. 2110 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2111 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2112 2113 SDValue WideVec; 2114 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2115 // For a splat, perform a scalar truncate before creating the wider 2116 // vector. 2117 assert(Splat.getValueType() == XLenVT && 2118 "Unexpected type for i1 splat value"); 2119 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2120 DAG.getConstant(1, DL, XLenVT)); 2121 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2122 } else { 2123 SmallVector<SDValue, 8> Ops(Op->op_values()); 2124 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2125 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2126 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2127 } 2128 2129 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2130 } 2131 2132 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2133 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2134 return Gather; 2135 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2136 : RISCVISD::VMV_V_X_VL; 2137 Splat = 2138 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2139 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2140 } 2141 2142 // Try and match index sequences, which we can lower to the vid instruction 2143 // with optional modifications. An all-undef vector is matched by 2144 // getSplatValue, above. 2145 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2146 int64_t StepNumerator = SimpleVID->StepNumerator; 2147 unsigned StepDenominator = SimpleVID->StepDenominator; 2148 int64_t Addend = SimpleVID->Addend; 2149 2150 assert(StepNumerator != 0 && "Invalid step"); 2151 bool Negate = false; 2152 int64_t SplatStepVal = StepNumerator; 2153 unsigned StepOpcode = ISD::MUL; 2154 if (StepNumerator != 1) { 2155 if (isPowerOf2_64(std::abs(StepNumerator))) { 2156 Negate = StepNumerator < 0; 2157 StepOpcode = ISD::SHL; 2158 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2159 } 2160 } 2161 2162 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2163 // threshold since it's the immediate value many RVV instructions accept. 2164 // There is no vmul.vi instruction so ensure multiply constant can fit in 2165 // a single addi instruction. 2166 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2167 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2168 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2169 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2170 // Convert right out of the scalable type so we can use standard ISD 2171 // nodes for the rest of the computation. If we used scalable types with 2172 // these, we'd lose the fixed-length vector info and generate worse 2173 // vsetvli code. 2174 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2175 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2176 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2177 SDValue SplatStep = DAG.getSplatBuildVector( 2178 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2179 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2180 } 2181 if (StepDenominator != 1) { 2182 SDValue SplatStep = DAG.getSplatBuildVector( 2183 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2184 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2185 } 2186 if (Addend != 0 || Negate) { 2187 SDValue SplatAddend = DAG.getSplatBuildVector( 2188 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2189 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2190 } 2191 return VID; 2192 } 2193 } 2194 2195 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2196 // when re-interpreted as a vector with a larger element type. For example, 2197 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2198 // could be instead splat as 2199 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2200 // TODO: This optimization could also work on non-constant splats, but it 2201 // would require bit-manipulation instructions to construct the splat value. 2202 SmallVector<SDValue> Sequence; 2203 unsigned EltBitSize = VT.getScalarSizeInBits(); 2204 const auto *BV = cast<BuildVectorSDNode>(Op); 2205 if (VT.isInteger() && EltBitSize < 64 && 2206 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2207 BV->getRepeatedSequence(Sequence) && 2208 (Sequence.size() * EltBitSize) <= 64) { 2209 unsigned SeqLen = Sequence.size(); 2210 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2211 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2212 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2213 ViaIntVT == MVT::i64) && 2214 "Unexpected sequence type"); 2215 2216 unsigned EltIdx = 0; 2217 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2218 uint64_t SplatValue = 0; 2219 // Construct the amalgamated value which can be splatted as this larger 2220 // vector type. 2221 for (const auto &SeqV : Sequence) { 2222 if (!SeqV.isUndef()) 2223 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2224 << (EltIdx * EltBitSize)); 2225 EltIdx++; 2226 } 2227 2228 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2229 // achieve better constant materializion. 2230 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2231 SplatValue = SignExtend64(SplatValue, 32); 2232 2233 // Since we can't introduce illegal i64 types at this stage, we can only 2234 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2235 // way we can use RVV instructions to splat. 2236 assert((ViaIntVT.bitsLE(XLenVT) || 2237 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2238 "Unexpected bitcast sequence"); 2239 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2240 SDValue ViaVL = 2241 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2242 MVT ViaContainerVT = 2243 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2244 SDValue Splat = 2245 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2246 DAG.getUNDEF(ViaContainerVT), 2247 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2248 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2249 return DAG.getBitcast(VT, Splat); 2250 } 2251 } 2252 2253 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2254 // which constitute a large proportion of the elements. In such cases we can 2255 // splat a vector with the dominant element and make up the shortfall with 2256 // INSERT_VECTOR_ELTs. 2257 // Note that this includes vectors of 2 elements by association. The 2258 // upper-most element is the "dominant" one, allowing us to use a splat to 2259 // "insert" the upper element, and an insert of the lower element at position 2260 // 0, which improves codegen. 2261 SDValue DominantValue; 2262 unsigned MostCommonCount = 0; 2263 DenseMap<SDValue, unsigned> ValueCounts; 2264 unsigned NumUndefElts = 2265 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2266 2267 // Track the number of scalar loads we know we'd be inserting, estimated as 2268 // any non-zero floating-point constant. Other kinds of element are either 2269 // already in registers or are materialized on demand. The threshold at which 2270 // a vector load is more desirable than several scalar materializion and 2271 // vector-insertion instructions is not known. 2272 unsigned NumScalarLoads = 0; 2273 2274 for (SDValue V : Op->op_values()) { 2275 if (V.isUndef()) 2276 continue; 2277 2278 ValueCounts.insert(std::make_pair(V, 0)); 2279 unsigned &Count = ValueCounts[V]; 2280 2281 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2282 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2283 2284 // Is this value dominant? In case of a tie, prefer the highest element as 2285 // it's cheaper to insert near the beginning of a vector than it is at the 2286 // end. 2287 if (++Count >= MostCommonCount) { 2288 DominantValue = V; 2289 MostCommonCount = Count; 2290 } 2291 } 2292 2293 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2294 unsigned NumDefElts = NumElts - NumUndefElts; 2295 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2296 2297 // Don't perform this optimization when optimizing for size, since 2298 // materializing elements and inserting them tends to cause code bloat. 2299 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2300 ((MostCommonCount > DominantValueCountThreshold) || 2301 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2302 // Start by splatting the most common element. 2303 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2304 2305 DenseSet<SDValue> Processed{DominantValue}; 2306 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2307 for (const auto &OpIdx : enumerate(Op->ops())) { 2308 const SDValue &V = OpIdx.value(); 2309 if (V.isUndef() || !Processed.insert(V).second) 2310 continue; 2311 if (ValueCounts[V] == 1) { 2312 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2313 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2314 } else { 2315 // Blend in all instances of this value using a VSELECT, using a 2316 // mask where each bit signals whether that element is the one 2317 // we're after. 2318 SmallVector<SDValue> Ops; 2319 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2320 return DAG.getConstant(V == V1, DL, XLenVT); 2321 }); 2322 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2323 DAG.getBuildVector(SelMaskTy, DL, Ops), 2324 DAG.getSplatBuildVector(VT, DL, V), Vec); 2325 } 2326 } 2327 2328 return Vec; 2329 } 2330 2331 return SDValue(); 2332 } 2333 2334 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2335 SDValue Lo, SDValue Hi, SDValue VL, 2336 SelectionDAG &DAG) { 2337 if (!Passthru) 2338 Passthru = DAG.getUNDEF(VT); 2339 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2340 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2341 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2342 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2343 // node in order to try and match RVV vector/scalar instructions. 2344 if ((LoC >> 31) == HiC) 2345 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2346 2347 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2348 // vmv.v.x whose EEW = 32 to lower it. 2349 auto *Const = dyn_cast<ConstantSDNode>(VL); 2350 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2351 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2352 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2353 // access the subtarget here now. 2354 auto InterVec = DAG.getNode( 2355 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2356 DAG.getRegister(RISCV::X0, MVT::i32)); 2357 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2358 } 2359 } 2360 2361 // Fall back to a stack store and stride x0 vector load. 2362 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2363 Hi, VL); 2364 } 2365 2366 // Called by type legalization to handle splat of i64 on RV32. 2367 // FIXME: We can optimize this when the type has sign or zero bits in one 2368 // of the halves. 2369 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2370 SDValue Scalar, SDValue VL, 2371 SelectionDAG &DAG) { 2372 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2373 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2374 DAG.getConstant(0, DL, MVT::i32)); 2375 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2376 DAG.getConstant(1, DL, MVT::i32)); 2377 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2378 } 2379 2380 // This function lowers a splat of a scalar operand Splat with the vector 2381 // length VL. It ensures the final sequence is type legal, which is useful when 2382 // lowering a splat after type legalization. 2383 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2384 MVT VT, SDLoc DL, SelectionDAG &DAG, 2385 const RISCVSubtarget &Subtarget) { 2386 bool HasPassthru = Passthru && !Passthru.isUndef(); 2387 if (!HasPassthru && !Passthru) 2388 Passthru = DAG.getUNDEF(VT); 2389 if (VT.isFloatingPoint()) { 2390 // If VL is 1, we could use vfmv.s.f. 2391 if (isOneConstant(VL)) 2392 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2393 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2394 } 2395 2396 MVT XLenVT = Subtarget.getXLenVT(); 2397 2398 // Simplest case is that the operand needs to be promoted to XLenVT. 2399 if (Scalar.getValueType().bitsLE(XLenVT)) { 2400 // If the operand is a constant, sign extend to increase our chances 2401 // of being able to use a .vi instruction. ANY_EXTEND would become a 2402 // a zero extend and the simm5 check in isel would fail. 2403 // FIXME: Should we ignore the upper bits in isel instead? 2404 unsigned ExtOpc = 2405 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2406 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2407 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2408 // If VL is 1 and the scalar value won't benefit from immediate, we could 2409 // use vmv.s.x. 2410 if (isOneConstant(VL) && 2411 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2412 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2413 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2414 } 2415 2416 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2417 "Unexpected scalar for splat lowering!"); 2418 2419 if (isOneConstant(VL) && isNullConstant(Scalar)) 2420 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2421 DAG.getConstant(0, DL, XLenVT), VL); 2422 2423 // Otherwise use the more complicated splatting algorithm. 2424 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2425 } 2426 2427 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2428 const RISCVSubtarget &Subtarget) { 2429 // We need to be able to widen elements to the next larger integer type. 2430 if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors()) 2431 return false; 2432 2433 int Size = Mask.size(); 2434 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2435 2436 int Srcs[] = {-1, -1}; 2437 for (int i = 0; i != Size; ++i) { 2438 // Ignore undef elements. 2439 if (Mask[i] < 0) 2440 continue; 2441 2442 // Is this an even or odd element. 2443 int Pol = i % 2; 2444 2445 // Ensure we consistently use the same source for this element polarity. 2446 int Src = Mask[i] / Size; 2447 if (Srcs[Pol] < 0) 2448 Srcs[Pol] = Src; 2449 if (Srcs[Pol] != Src) 2450 return false; 2451 2452 // Make sure the element within the source is appropriate for this element 2453 // in the destination. 2454 int Elt = Mask[i] % Size; 2455 if (Elt != i / 2) 2456 return false; 2457 } 2458 2459 // We need to find a source for each polarity and they can't be the same. 2460 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2461 return false; 2462 2463 // Swap the sources if the second source was in the even polarity. 2464 SwapSources = Srcs[0] > Srcs[1]; 2465 2466 return true; 2467 } 2468 2469 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2470 /// and then extract the original number of elements from the rotated result. 2471 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2472 /// returned rotation amount is for a rotate right, where elements move from 2473 /// higher elements to lower elements. \p LoSrc indicates the first source 2474 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2475 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2476 /// 0 or 1 if a rotation is found. 2477 /// 2478 /// NOTE: We talk about rotate to the right which matches how bit shift and 2479 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2480 /// and the table below write vectors with the lowest elements on the left. 2481 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2482 int Size = Mask.size(); 2483 2484 // We need to detect various ways of spelling a rotation: 2485 // [11, 12, 13, 14, 15, 0, 1, 2] 2486 // [-1, 12, 13, 14, -1, -1, 1, -1] 2487 // [-1, -1, -1, -1, -1, -1, 1, 2] 2488 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2489 // [-1, 4, 5, 6, -1, -1, 9, -1] 2490 // [-1, 4, 5, 6, -1, -1, -1, -1] 2491 int Rotation = 0; 2492 LoSrc = -1; 2493 HiSrc = -1; 2494 for (int i = 0; i != Size; ++i) { 2495 int M = Mask[i]; 2496 if (M < 0) 2497 continue; 2498 2499 // Determine where a rotate vector would have started. 2500 int StartIdx = i - (M % Size); 2501 // The identity rotation isn't interesting, stop. 2502 if (StartIdx == 0) 2503 return -1; 2504 2505 // If we found the tail of a vector the rotation must be the missing 2506 // front. If we found the head of a vector, it must be how much of the 2507 // head. 2508 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2509 2510 if (Rotation == 0) 2511 Rotation = CandidateRotation; 2512 else if (Rotation != CandidateRotation) 2513 // The rotations don't match, so we can't match this mask. 2514 return -1; 2515 2516 // Compute which value this mask is pointing at. 2517 int MaskSrc = M < Size ? 0 : 1; 2518 2519 // Compute which of the two target values this index should be assigned to. 2520 // This reflects whether the high elements are remaining or the low elemnts 2521 // are remaining. 2522 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2523 2524 // Either set up this value if we've not encountered it before, or check 2525 // that it remains consistent. 2526 if (TargetSrc < 0) 2527 TargetSrc = MaskSrc; 2528 else if (TargetSrc != MaskSrc) 2529 // This may be a rotation, but it pulls from the inputs in some 2530 // unsupported interleaving. 2531 return -1; 2532 } 2533 2534 // Check that we successfully analyzed the mask, and normalize the results. 2535 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2536 assert((LoSrc >= 0 || HiSrc >= 0) && 2537 "Failed to find a rotated input vector!"); 2538 2539 return Rotation; 2540 } 2541 2542 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2543 const RISCVSubtarget &Subtarget) { 2544 SDValue V1 = Op.getOperand(0); 2545 SDValue V2 = Op.getOperand(1); 2546 SDLoc DL(Op); 2547 MVT XLenVT = Subtarget.getXLenVT(); 2548 MVT VT = Op.getSimpleValueType(); 2549 unsigned NumElts = VT.getVectorNumElements(); 2550 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2551 2552 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2553 2554 SDValue TrueMask, VL; 2555 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2556 2557 if (SVN->isSplat()) { 2558 const int Lane = SVN->getSplatIndex(); 2559 if (Lane >= 0) { 2560 MVT SVT = VT.getVectorElementType(); 2561 2562 // Turn splatted vector load into a strided load with an X0 stride. 2563 SDValue V = V1; 2564 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2565 // with undef. 2566 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2567 int Offset = Lane; 2568 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2569 int OpElements = 2570 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2571 V = V.getOperand(Offset / OpElements); 2572 Offset %= OpElements; 2573 } 2574 2575 // We need to ensure the load isn't atomic or volatile. 2576 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2577 auto *Ld = cast<LoadSDNode>(V); 2578 Offset *= SVT.getStoreSize(); 2579 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2580 TypeSize::Fixed(Offset), DL); 2581 2582 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2583 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2584 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2585 SDValue IntID = 2586 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2587 SDValue Ops[] = {Ld->getChain(), 2588 IntID, 2589 DAG.getUNDEF(ContainerVT), 2590 NewAddr, 2591 DAG.getRegister(RISCV::X0, XLenVT), 2592 VL}; 2593 SDValue NewLoad = DAG.getMemIntrinsicNode( 2594 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2595 DAG.getMachineFunction().getMachineMemOperand( 2596 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2597 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2598 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2599 } 2600 2601 // Otherwise use a scalar load and splat. This will give the best 2602 // opportunity to fold a splat into the operation. ISel can turn it into 2603 // the x0 strided load if we aren't able to fold away the select. 2604 if (SVT.isFloatingPoint()) 2605 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2606 Ld->getPointerInfo().getWithOffset(Offset), 2607 Ld->getOriginalAlign(), 2608 Ld->getMemOperand()->getFlags()); 2609 else 2610 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2611 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2612 Ld->getOriginalAlign(), 2613 Ld->getMemOperand()->getFlags()); 2614 DAG.makeEquivalentMemoryOrdering(Ld, V); 2615 2616 unsigned Opc = 2617 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2618 SDValue Splat = 2619 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2620 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2621 } 2622 2623 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2624 assert(Lane < (int)NumElts && "Unexpected lane!"); 2625 SDValue Gather = 2626 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2627 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2628 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2629 } 2630 } 2631 2632 ArrayRef<int> Mask = SVN->getMask(); 2633 2634 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2635 // be undef which can be handled with a single SLIDEDOWN/UP. 2636 int LoSrc, HiSrc; 2637 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2638 if (Rotation > 0) { 2639 SDValue LoV, HiV; 2640 if (LoSrc >= 0) { 2641 LoV = LoSrc == 0 ? V1 : V2; 2642 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2643 } 2644 if (HiSrc >= 0) { 2645 HiV = HiSrc == 0 ? V1 : V2; 2646 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2647 } 2648 2649 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2650 // to slide LoV up by (NumElts - Rotation). 2651 unsigned InvRotate = NumElts - Rotation; 2652 2653 SDValue Res = DAG.getUNDEF(ContainerVT); 2654 if (HiV) { 2655 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2656 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2657 // causes multiple vsetvlis in some test cases such as lowering 2658 // reduce.mul 2659 SDValue DownVL = VL; 2660 if (LoV) 2661 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2662 Res = 2663 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2664 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2665 } 2666 if (LoV) 2667 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2668 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2669 2670 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2671 } 2672 2673 // Detect an interleave shuffle and lower to 2674 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2675 bool SwapSources; 2676 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2677 // Swap sources if needed. 2678 if (SwapSources) 2679 std::swap(V1, V2); 2680 2681 // Extract the lower half of the vectors. 2682 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2683 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2684 DAG.getConstant(0, DL, XLenVT)); 2685 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2686 DAG.getConstant(0, DL, XLenVT)); 2687 2688 // Double the element width and halve the number of elements in an int type. 2689 unsigned EltBits = VT.getScalarSizeInBits(); 2690 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2691 MVT WideIntVT = 2692 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2693 // Convert this to a scalable vector. We need to base this on the 2694 // destination size to ensure there's always a type with a smaller LMUL. 2695 MVT WideIntContainerVT = 2696 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2697 2698 // Convert sources to scalable vectors with the same element count as the 2699 // larger type. 2700 MVT HalfContainerVT = MVT::getVectorVT( 2701 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2702 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2703 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2704 2705 // Cast sources to integer. 2706 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2707 MVT IntHalfVT = 2708 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2709 V1 = DAG.getBitcast(IntHalfVT, V1); 2710 V2 = DAG.getBitcast(IntHalfVT, V2); 2711 2712 // Freeze V2 since we use it twice and we need to be sure that the add and 2713 // multiply see the same value. 2714 V2 = DAG.getFreeze(V2); 2715 2716 // Recreate TrueMask using the widened type's element count. 2717 MVT MaskVT = 2718 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2719 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2720 2721 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2722 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2723 V2, TrueMask, VL); 2724 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2725 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2726 DAG.getUNDEF(IntHalfVT), 2727 DAG.getAllOnesConstant(DL, XLenVT)); 2728 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2729 V2, Multiplier, TrueMask, VL); 2730 // Add the new copies to our previous addition giving us 2^eltbits copies of 2731 // V2. This is equivalent to shifting V2 left by eltbits. This should 2732 // combine with the vwmulu.vv above to form vwmaccu.vv. 2733 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2734 TrueMask, VL); 2735 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2736 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2737 // vector VT. 2738 ContainerVT = 2739 MVT::getVectorVT(VT.getVectorElementType(), 2740 WideIntContainerVT.getVectorElementCount() * 2); 2741 Add = DAG.getBitcast(ContainerVT, Add); 2742 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2743 } 2744 2745 // Detect shuffles which can be re-expressed as vector selects; these are 2746 // shuffles in which each element in the destination is taken from an element 2747 // at the corresponding index in either source vectors. 2748 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2749 int MaskIndex = MaskIdx.value(); 2750 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2751 }); 2752 2753 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2754 2755 SmallVector<SDValue> MaskVals; 2756 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2757 // merged with a second vrgather. 2758 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2759 2760 // By default we preserve the original operand order, and use a mask to 2761 // select LHS as true and RHS as false. However, since RVV vector selects may 2762 // feature splats but only on the LHS, we may choose to invert our mask and 2763 // instead select between RHS and LHS. 2764 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2765 bool InvertMask = IsSelect == SwapOps; 2766 2767 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2768 // half. 2769 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2770 2771 // Now construct the mask that will be used by the vselect or blended 2772 // vrgather operation. For vrgathers, construct the appropriate indices into 2773 // each vector. 2774 for (int MaskIndex : Mask) { 2775 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2776 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2777 if (!IsSelect) { 2778 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2779 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2780 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2781 : DAG.getUNDEF(XLenVT)); 2782 GatherIndicesRHS.push_back( 2783 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2784 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2785 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2786 ++LHSIndexCounts[MaskIndex]; 2787 if (!IsLHSOrUndefIndex) 2788 ++RHSIndexCounts[MaskIndex - NumElts]; 2789 } 2790 } 2791 2792 if (SwapOps) { 2793 std::swap(V1, V2); 2794 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2795 } 2796 2797 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2798 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2799 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2800 2801 if (IsSelect) 2802 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2803 2804 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2805 // On such a large vector we're unable to use i8 as the index type. 2806 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2807 // may involve vector splitting if we're already at LMUL=8, or our 2808 // user-supplied maximum fixed-length LMUL. 2809 return SDValue(); 2810 } 2811 2812 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2813 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2814 MVT IndexVT = VT.changeTypeToInteger(); 2815 // Since we can't introduce illegal index types at this stage, use i16 and 2816 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2817 // than XLenVT. 2818 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2819 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2820 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2821 } 2822 2823 MVT IndexContainerVT = 2824 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2825 2826 SDValue Gather; 2827 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2828 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2829 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2830 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2831 Subtarget); 2832 } else { 2833 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2834 // If only one index is used, we can use a "splat" vrgather. 2835 // TODO: We can splat the most-common index and fix-up any stragglers, if 2836 // that's beneficial. 2837 if (LHSIndexCounts.size() == 1) { 2838 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2839 Gather = 2840 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2841 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2842 } else { 2843 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2844 LHSIndices = 2845 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2846 2847 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2848 TrueMask, VL); 2849 } 2850 } 2851 2852 // If a second vector operand is used by this shuffle, blend it in with an 2853 // additional vrgather. 2854 if (!V2.isUndef()) { 2855 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2856 // If only one index is used, we can use a "splat" vrgather. 2857 // TODO: We can splat the most-common index and fix-up any stragglers, if 2858 // that's beneficial. 2859 if (RHSIndexCounts.size() == 1) { 2860 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2861 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2862 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2863 } else { 2864 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2865 RHSIndices = 2866 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2867 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2868 VL); 2869 } 2870 2871 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2872 SelectMask = 2873 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2874 2875 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2876 Gather, VL); 2877 } 2878 2879 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2880 } 2881 2882 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2883 // Support splats for any type. These should type legalize well. 2884 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2885 return true; 2886 2887 // Only support legal VTs for other shuffles for now. 2888 if (!isTypeLegal(VT)) 2889 return false; 2890 2891 MVT SVT = VT.getSimpleVT(); 2892 2893 bool SwapSources; 2894 int LoSrc, HiSrc; 2895 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2896 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2897 } 2898 2899 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2900 SDLoc DL, SelectionDAG &DAG, 2901 const RISCVSubtarget &Subtarget) { 2902 if (VT.isScalableVector()) 2903 return DAG.getFPExtendOrRound(Op, DL, VT); 2904 assert(VT.isFixedLengthVector() && 2905 "Unexpected value type for RVV FP extend/round lowering"); 2906 SDValue Mask, VL; 2907 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2908 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2909 ? RISCVISD::FP_EXTEND_VL 2910 : RISCVISD::FP_ROUND_VL; 2911 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2912 } 2913 2914 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2915 // the exponent. 2916 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2917 MVT VT = Op.getSimpleValueType(); 2918 unsigned EltSize = VT.getScalarSizeInBits(); 2919 SDValue Src = Op.getOperand(0); 2920 SDLoc DL(Op); 2921 2922 // We need a FP type that can represent the value. 2923 // TODO: Use f16 for i8 when possible? 2924 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2925 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2926 2927 // Legal types should have been checked in the RISCVTargetLowering 2928 // constructor. 2929 // TODO: Splitting may make sense in some cases. 2930 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2931 "Expected legal float type!"); 2932 2933 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2934 // The trailing zero count is equal to log2 of this single bit value. 2935 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2936 SDValue Neg = 2937 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2938 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2939 } 2940 2941 // We have a legal FP type, convert to it. 2942 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2943 // Bitcast to integer and shift the exponent to the LSB. 2944 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2945 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2946 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2947 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2948 DAG.getConstant(ShiftAmt, DL, IntVT)); 2949 // Truncate back to original type to allow vnsrl. 2950 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2951 // The exponent contains log2 of the value in biased form. 2952 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2953 2954 // For trailing zeros, we just need to subtract the bias. 2955 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2956 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2957 DAG.getConstant(ExponentBias, DL, VT)); 2958 2959 // For leading zeros, we need to remove the bias and convert from log2 to 2960 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2961 unsigned Adjust = ExponentBias + (EltSize - 1); 2962 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2963 } 2964 2965 // While RVV has alignment restrictions, we should always be able to load as a 2966 // legal equivalently-sized byte-typed vector instead. This method is 2967 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2968 // the load is already correctly-aligned, it returns SDValue(). 2969 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2970 SelectionDAG &DAG) const { 2971 auto *Load = cast<LoadSDNode>(Op); 2972 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2973 2974 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2975 Load->getMemoryVT(), 2976 *Load->getMemOperand())) 2977 return SDValue(); 2978 2979 SDLoc DL(Op); 2980 MVT VT = Op.getSimpleValueType(); 2981 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2982 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2983 "Unexpected unaligned RVV load type"); 2984 MVT NewVT = 2985 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2986 assert(NewVT.isValid() && 2987 "Expecting equally-sized RVV vector types to be legal"); 2988 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2989 Load->getPointerInfo(), Load->getOriginalAlign(), 2990 Load->getMemOperand()->getFlags()); 2991 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2992 } 2993 2994 // While RVV has alignment restrictions, we should always be able to store as a 2995 // legal equivalently-sized byte-typed vector instead. This method is 2996 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2997 // returns SDValue() if the store is already correctly aligned. 2998 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2999 SelectionDAG &DAG) const { 3000 auto *Store = cast<StoreSDNode>(Op); 3001 assert(Store && Store->getValue().getValueType().isVector() && 3002 "Expected vector store"); 3003 3004 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3005 Store->getMemoryVT(), 3006 *Store->getMemOperand())) 3007 return SDValue(); 3008 3009 SDLoc DL(Op); 3010 SDValue StoredVal = Store->getValue(); 3011 MVT VT = StoredVal.getSimpleValueType(); 3012 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3013 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3014 "Unexpected unaligned RVV store type"); 3015 MVT NewVT = 3016 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3017 assert(NewVT.isValid() && 3018 "Expecting equally-sized RVV vector types to be legal"); 3019 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3020 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3021 Store->getPointerInfo(), Store->getOriginalAlign(), 3022 Store->getMemOperand()->getFlags()); 3023 } 3024 3025 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3026 SelectionDAG &DAG) const { 3027 switch (Op.getOpcode()) { 3028 default: 3029 report_fatal_error("unimplemented operand"); 3030 case ISD::GlobalAddress: 3031 return lowerGlobalAddress(Op, DAG); 3032 case ISD::BlockAddress: 3033 return lowerBlockAddress(Op, DAG); 3034 case ISD::ConstantPool: 3035 return lowerConstantPool(Op, DAG); 3036 case ISD::JumpTable: 3037 return lowerJumpTable(Op, DAG); 3038 case ISD::GlobalTLSAddress: 3039 return lowerGlobalTLSAddress(Op, DAG); 3040 case ISD::SELECT: 3041 return lowerSELECT(Op, DAG); 3042 case ISD::BRCOND: 3043 return lowerBRCOND(Op, DAG); 3044 case ISD::VASTART: 3045 return lowerVASTART(Op, DAG); 3046 case ISD::FRAMEADDR: 3047 return lowerFRAMEADDR(Op, DAG); 3048 case ISD::RETURNADDR: 3049 return lowerRETURNADDR(Op, DAG); 3050 case ISD::SHL_PARTS: 3051 return lowerShiftLeftParts(Op, DAG); 3052 case ISD::SRA_PARTS: 3053 return lowerShiftRightParts(Op, DAG, true); 3054 case ISD::SRL_PARTS: 3055 return lowerShiftRightParts(Op, DAG, false); 3056 case ISD::BITCAST: { 3057 SDLoc DL(Op); 3058 EVT VT = Op.getValueType(); 3059 SDValue Op0 = Op.getOperand(0); 3060 EVT Op0VT = Op0.getValueType(); 3061 MVT XLenVT = Subtarget.getXLenVT(); 3062 if (VT.isFixedLengthVector()) { 3063 // We can handle fixed length vector bitcasts with a simple replacement 3064 // in isel. 3065 if (Op0VT.isFixedLengthVector()) 3066 return Op; 3067 // When bitcasting from scalar to fixed-length vector, insert the scalar 3068 // into a one-element vector of the result type, and perform a vector 3069 // bitcast. 3070 if (!Op0VT.isVector()) { 3071 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3072 if (!isTypeLegal(BVT)) 3073 return SDValue(); 3074 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3075 DAG.getUNDEF(BVT), Op0, 3076 DAG.getConstant(0, DL, XLenVT))); 3077 } 3078 return SDValue(); 3079 } 3080 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3081 // thus: bitcast the vector to a one-element vector type whose element type 3082 // is the same as the result type, and extract the first element. 3083 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3084 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3085 if (!isTypeLegal(BVT)) 3086 return SDValue(); 3087 SDValue BVec = DAG.getBitcast(BVT, Op0); 3088 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3089 DAG.getConstant(0, DL, XLenVT)); 3090 } 3091 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3092 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3093 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3094 return FPConv; 3095 } 3096 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3097 Subtarget.hasStdExtF()) { 3098 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3099 SDValue FPConv = 3100 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3101 return FPConv; 3102 } 3103 return SDValue(); 3104 } 3105 case ISD::INTRINSIC_WO_CHAIN: 3106 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3107 case ISD::INTRINSIC_W_CHAIN: 3108 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3109 case ISD::INTRINSIC_VOID: 3110 return LowerINTRINSIC_VOID(Op, DAG); 3111 case ISD::BSWAP: 3112 case ISD::BITREVERSE: { 3113 MVT VT = Op.getSimpleValueType(); 3114 SDLoc DL(Op); 3115 if (Subtarget.hasStdExtZbp()) { 3116 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3117 // Start with the maximum immediate value which is the bitwidth - 1. 3118 unsigned Imm = VT.getSizeInBits() - 1; 3119 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3120 if (Op.getOpcode() == ISD::BSWAP) 3121 Imm &= ~0x7U; 3122 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3123 DAG.getConstant(Imm, DL, VT)); 3124 } 3125 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3126 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3127 // Expand bitreverse to a bswap(rev8) followed by brev8. 3128 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3129 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3130 // as brev8 by an isel pattern. 3131 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3132 DAG.getConstant(7, DL, VT)); 3133 } 3134 case ISD::FSHL: 3135 case ISD::FSHR: { 3136 MVT VT = Op.getSimpleValueType(); 3137 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3138 SDLoc DL(Op); 3139 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3140 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3141 // accidentally setting the extra bit. 3142 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3143 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3144 DAG.getConstant(ShAmtWidth, DL, VT)); 3145 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3146 // instruction use different orders. fshl will return its first operand for 3147 // shift of zero, fshr will return its second operand. fsl and fsr both 3148 // return rs1 so the ISD nodes need to have different operand orders. 3149 // Shift amount is in rs2. 3150 SDValue Op0 = Op.getOperand(0); 3151 SDValue Op1 = Op.getOperand(1); 3152 unsigned Opc = RISCVISD::FSL; 3153 if (Op.getOpcode() == ISD::FSHR) { 3154 std::swap(Op0, Op1); 3155 Opc = RISCVISD::FSR; 3156 } 3157 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3158 } 3159 case ISD::TRUNCATE: { 3160 SDLoc DL(Op); 3161 MVT VT = Op.getSimpleValueType(); 3162 // Only custom-lower vector truncates 3163 if (!VT.isVector()) 3164 return Op; 3165 3166 // Truncates to mask types are handled differently 3167 if (VT.getVectorElementType() == MVT::i1) 3168 return lowerVectorMaskTrunc(Op, DAG); 3169 3170 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3171 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3172 // truncate by one power of two at a time. 3173 MVT DstEltVT = VT.getVectorElementType(); 3174 3175 SDValue Src = Op.getOperand(0); 3176 MVT SrcVT = Src.getSimpleValueType(); 3177 MVT SrcEltVT = SrcVT.getVectorElementType(); 3178 3179 assert(DstEltVT.bitsLT(SrcEltVT) && 3180 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3181 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3182 "Unexpected vector truncate lowering"); 3183 3184 MVT ContainerVT = SrcVT; 3185 if (SrcVT.isFixedLengthVector()) { 3186 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3187 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3188 } 3189 3190 SDValue Result = Src; 3191 SDValue Mask, VL; 3192 std::tie(Mask, VL) = 3193 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3194 LLVMContext &Context = *DAG.getContext(); 3195 const ElementCount Count = ContainerVT.getVectorElementCount(); 3196 do { 3197 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3198 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3199 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3200 Mask, VL); 3201 } while (SrcEltVT != DstEltVT); 3202 3203 if (SrcVT.isFixedLengthVector()) 3204 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3205 3206 return Result; 3207 } 3208 case ISD::ANY_EXTEND: 3209 case ISD::ZERO_EXTEND: 3210 if (Op.getOperand(0).getValueType().isVector() && 3211 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3212 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3213 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3214 case ISD::SIGN_EXTEND: 3215 if (Op.getOperand(0).getValueType().isVector() && 3216 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3217 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3218 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3219 case ISD::SPLAT_VECTOR_PARTS: 3220 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3221 case ISD::INSERT_VECTOR_ELT: 3222 return lowerINSERT_VECTOR_ELT(Op, DAG); 3223 case ISD::EXTRACT_VECTOR_ELT: 3224 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3225 case ISD::VSCALE: { 3226 MVT VT = Op.getSimpleValueType(); 3227 SDLoc DL(Op); 3228 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3229 // We define our scalable vector types for lmul=1 to use a 64 bit known 3230 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3231 // vscale as VLENB / 8. 3232 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3233 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3234 report_fatal_error("Support for VLEN==32 is incomplete."); 3235 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3236 // We assume VLENB is a multiple of 8. We manually choose the best shift 3237 // here because SimplifyDemandedBits isn't always able to simplify it. 3238 uint64_t Val = Op.getConstantOperandVal(0); 3239 if (isPowerOf2_64(Val)) { 3240 uint64_t Log2 = Log2_64(Val); 3241 if (Log2 < 3) 3242 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3243 DAG.getConstant(3 - Log2, DL, VT)); 3244 if (Log2 > 3) 3245 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3246 DAG.getConstant(Log2 - 3, DL, VT)); 3247 return VLENB; 3248 } 3249 // If the multiplier is a multiple of 8, scale it down to avoid needing 3250 // to shift the VLENB value. 3251 if ((Val % 8) == 0) 3252 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3253 DAG.getConstant(Val / 8, DL, VT)); 3254 } 3255 3256 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3257 DAG.getConstant(3, DL, VT)); 3258 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3259 } 3260 case ISD::FPOWI: { 3261 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3262 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3263 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3264 Op.getOperand(1).getValueType() == MVT::i32) { 3265 SDLoc DL(Op); 3266 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3267 SDValue Powi = 3268 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3269 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3270 DAG.getIntPtrConstant(0, DL)); 3271 } 3272 return SDValue(); 3273 } 3274 case ISD::FP_EXTEND: { 3275 // RVV can only do fp_extend to types double the size as the source. We 3276 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3277 // via f32. 3278 SDLoc DL(Op); 3279 MVT VT = Op.getSimpleValueType(); 3280 SDValue Src = Op.getOperand(0); 3281 MVT SrcVT = Src.getSimpleValueType(); 3282 3283 // Prepare any fixed-length vector operands. 3284 MVT ContainerVT = VT; 3285 if (SrcVT.isFixedLengthVector()) { 3286 ContainerVT = getContainerForFixedLengthVector(VT); 3287 MVT SrcContainerVT = 3288 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3289 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3290 } 3291 3292 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3293 SrcVT.getVectorElementType() != MVT::f16) { 3294 // For scalable vectors, we only need to close the gap between 3295 // vXf16->vXf64. 3296 if (!VT.isFixedLengthVector()) 3297 return Op; 3298 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3299 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3300 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3301 } 3302 3303 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3304 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3305 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3306 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3307 3308 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3309 DL, DAG, Subtarget); 3310 if (VT.isFixedLengthVector()) 3311 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3312 return Extend; 3313 } 3314 case ISD::FP_ROUND: { 3315 // RVV can only do fp_round to types half the size as the source. We 3316 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3317 // conversion instruction. 3318 SDLoc DL(Op); 3319 MVT VT = Op.getSimpleValueType(); 3320 SDValue Src = Op.getOperand(0); 3321 MVT SrcVT = Src.getSimpleValueType(); 3322 3323 // Prepare any fixed-length vector operands. 3324 MVT ContainerVT = VT; 3325 if (VT.isFixedLengthVector()) { 3326 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3327 ContainerVT = 3328 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3329 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3330 } 3331 3332 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3333 SrcVT.getVectorElementType() != MVT::f64) { 3334 // For scalable vectors, we only need to close the gap between 3335 // vXf64<->vXf16. 3336 if (!VT.isFixedLengthVector()) 3337 return Op; 3338 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3339 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3340 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3341 } 3342 3343 SDValue Mask, VL; 3344 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3345 3346 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3347 SDValue IntermediateRound = 3348 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3349 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3350 DL, DAG, Subtarget); 3351 3352 if (VT.isFixedLengthVector()) 3353 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3354 return Round; 3355 } 3356 case ISD::FP_TO_SINT: 3357 case ISD::FP_TO_UINT: 3358 case ISD::SINT_TO_FP: 3359 case ISD::UINT_TO_FP: { 3360 // RVV can only do fp<->int conversions to types half/double the size as 3361 // the source. We custom-lower any conversions that do two hops into 3362 // sequences. 3363 MVT VT = Op.getSimpleValueType(); 3364 if (!VT.isVector()) 3365 return Op; 3366 SDLoc DL(Op); 3367 SDValue Src = Op.getOperand(0); 3368 MVT EltVT = VT.getVectorElementType(); 3369 MVT SrcVT = Src.getSimpleValueType(); 3370 MVT SrcEltVT = SrcVT.getVectorElementType(); 3371 unsigned EltSize = EltVT.getSizeInBits(); 3372 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3373 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3374 "Unexpected vector element types"); 3375 3376 bool IsInt2FP = SrcEltVT.isInteger(); 3377 // Widening conversions 3378 if (EltSize > (2 * SrcEltSize)) { 3379 if (IsInt2FP) { 3380 // Do a regular integer sign/zero extension then convert to float. 3381 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3382 VT.getVectorElementCount()); 3383 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3384 ? ISD::ZERO_EXTEND 3385 : ISD::SIGN_EXTEND; 3386 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3387 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3388 } 3389 // FP2Int 3390 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3391 // Do one doubling fp_extend then complete the operation by converting 3392 // to int. 3393 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3394 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3395 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3396 } 3397 3398 // Narrowing conversions 3399 if (SrcEltSize > (2 * EltSize)) { 3400 if (IsInt2FP) { 3401 // One narrowing int_to_fp, then an fp_round. 3402 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3403 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3404 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3405 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3406 } 3407 // FP2Int 3408 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3409 // representable by the integer, the result is poison. 3410 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3411 VT.getVectorElementCount()); 3412 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3413 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3414 } 3415 3416 // Scalable vectors can exit here. Patterns will handle equally-sized 3417 // conversions halving/doubling ones. 3418 if (!VT.isFixedLengthVector()) 3419 return Op; 3420 3421 // For fixed-length vectors we lower to a custom "VL" node. 3422 unsigned RVVOpc = 0; 3423 switch (Op.getOpcode()) { 3424 default: 3425 llvm_unreachable("Impossible opcode"); 3426 case ISD::FP_TO_SINT: 3427 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3428 break; 3429 case ISD::FP_TO_UINT: 3430 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3431 break; 3432 case ISD::SINT_TO_FP: 3433 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3434 break; 3435 case ISD::UINT_TO_FP: 3436 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3437 break; 3438 } 3439 3440 MVT ContainerVT, SrcContainerVT; 3441 // Derive the reference container type from the larger vector type. 3442 if (SrcEltSize > EltSize) { 3443 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3444 ContainerVT = 3445 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3446 } else { 3447 ContainerVT = getContainerForFixedLengthVector(VT); 3448 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3449 } 3450 3451 SDValue Mask, VL; 3452 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3453 3454 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3455 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3456 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3457 } 3458 case ISD::FP_TO_SINT_SAT: 3459 case ISD::FP_TO_UINT_SAT: 3460 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3461 case ISD::FTRUNC: 3462 case ISD::FCEIL: 3463 case ISD::FFLOOR: 3464 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3465 case ISD::FROUND: 3466 return lowerFROUND(Op, DAG); 3467 case ISD::VECREDUCE_ADD: 3468 case ISD::VECREDUCE_UMAX: 3469 case ISD::VECREDUCE_SMAX: 3470 case ISD::VECREDUCE_UMIN: 3471 case ISD::VECREDUCE_SMIN: 3472 return lowerVECREDUCE(Op, DAG); 3473 case ISD::VECREDUCE_AND: 3474 case ISD::VECREDUCE_OR: 3475 case ISD::VECREDUCE_XOR: 3476 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3477 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3478 return lowerVECREDUCE(Op, DAG); 3479 case ISD::VECREDUCE_FADD: 3480 case ISD::VECREDUCE_SEQ_FADD: 3481 case ISD::VECREDUCE_FMIN: 3482 case ISD::VECREDUCE_FMAX: 3483 return lowerFPVECREDUCE(Op, DAG); 3484 case ISD::VP_REDUCE_ADD: 3485 case ISD::VP_REDUCE_UMAX: 3486 case ISD::VP_REDUCE_SMAX: 3487 case ISD::VP_REDUCE_UMIN: 3488 case ISD::VP_REDUCE_SMIN: 3489 case ISD::VP_REDUCE_FADD: 3490 case ISD::VP_REDUCE_SEQ_FADD: 3491 case ISD::VP_REDUCE_FMIN: 3492 case ISD::VP_REDUCE_FMAX: 3493 return lowerVPREDUCE(Op, DAG); 3494 case ISD::VP_REDUCE_AND: 3495 case ISD::VP_REDUCE_OR: 3496 case ISD::VP_REDUCE_XOR: 3497 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3498 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3499 return lowerVPREDUCE(Op, DAG); 3500 case ISD::INSERT_SUBVECTOR: 3501 return lowerINSERT_SUBVECTOR(Op, DAG); 3502 case ISD::EXTRACT_SUBVECTOR: 3503 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3504 case ISD::STEP_VECTOR: 3505 return lowerSTEP_VECTOR(Op, DAG); 3506 case ISD::VECTOR_REVERSE: 3507 return lowerVECTOR_REVERSE(Op, DAG); 3508 case ISD::VECTOR_SPLICE: 3509 return lowerVECTOR_SPLICE(Op, DAG); 3510 case ISD::BUILD_VECTOR: 3511 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3512 case ISD::SPLAT_VECTOR: 3513 if (Op.getValueType().getVectorElementType() == MVT::i1) 3514 return lowerVectorMaskSplat(Op, DAG); 3515 return SDValue(); 3516 case ISD::VECTOR_SHUFFLE: 3517 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3518 case ISD::CONCAT_VECTORS: { 3519 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3520 // better than going through the stack, as the default expansion does. 3521 SDLoc DL(Op); 3522 MVT VT = Op.getSimpleValueType(); 3523 unsigned NumOpElts = 3524 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3525 SDValue Vec = DAG.getUNDEF(VT); 3526 for (const auto &OpIdx : enumerate(Op->ops())) { 3527 SDValue SubVec = OpIdx.value(); 3528 // Don't insert undef subvectors. 3529 if (SubVec.isUndef()) 3530 continue; 3531 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3532 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3533 } 3534 return Vec; 3535 } 3536 case ISD::LOAD: 3537 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3538 return V; 3539 if (Op.getValueType().isFixedLengthVector()) 3540 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3541 return Op; 3542 case ISD::STORE: 3543 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3544 return V; 3545 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3546 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3547 return Op; 3548 case ISD::MLOAD: 3549 case ISD::VP_LOAD: 3550 return lowerMaskedLoad(Op, DAG); 3551 case ISD::MSTORE: 3552 case ISD::VP_STORE: 3553 return lowerMaskedStore(Op, DAG); 3554 case ISD::SETCC: 3555 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3556 case ISD::ADD: 3557 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3558 case ISD::SUB: 3559 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3560 case ISD::MUL: 3561 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3562 case ISD::MULHS: 3563 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3564 case ISD::MULHU: 3565 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3566 case ISD::AND: 3567 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3568 RISCVISD::AND_VL); 3569 case ISD::OR: 3570 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3571 RISCVISD::OR_VL); 3572 case ISD::XOR: 3573 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3574 RISCVISD::XOR_VL); 3575 case ISD::SDIV: 3576 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3577 case ISD::SREM: 3578 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3579 case ISD::UDIV: 3580 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3581 case ISD::UREM: 3582 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3583 case ISD::SHL: 3584 case ISD::SRA: 3585 case ISD::SRL: 3586 if (Op.getSimpleValueType().isFixedLengthVector()) 3587 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3588 // This can be called for an i32 shift amount that needs to be promoted. 3589 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3590 "Unexpected custom legalisation"); 3591 return SDValue(); 3592 case ISD::SADDSAT: 3593 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3594 case ISD::UADDSAT: 3595 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3596 case ISD::SSUBSAT: 3597 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3598 case ISD::USUBSAT: 3599 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3600 case ISD::FADD: 3601 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3602 case ISD::FSUB: 3603 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3604 case ISD::FMUL: 3605 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3606 case ISD::FDIV: 3607 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3608 case ISD::FNEG: 3609 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3610 case ISD::FABS: 3611 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3612 case ISD::FSQRT: 3613 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3614 case ISD::FMA: 3615 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3616 case ISD::SMIN: 3617 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3618 case ISD::SMAX: 3619 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3620 case ISD::UMIN: 3621 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3622 case ISD::UMAX: 3623 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3624 case ISD::FMINNUM: 3625 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3626 case ISD::FMAXNUM: 3627 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3628 case ISD::ABS: 3629 return lowerABS(Op, DAG); 3630 case ISD::CTLZ_ZERO_UNDEF: 3631 case ISD::CTTZ_ZERO_UNDEF: 3632 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3633 case ISD::VSELECT: 3634 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3635 case ISD::FCOPYSIGN: 3636 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3637 case ISD::MGATHER: 3638 case ISD::VP_GATHER: 3639 return lowerMaskedGather(Op, DAG); 3640 case ISD::MSCATTER: 3641 case ISD::VP_SCATTER: 3642 return lowerMaskedScatter(Op, DAG); 3643 case ISD::FLT_ROUNDS_: 3644 return lowerGET_ROUNDING(Op, DAG); 3645 case ISD::SET_ROUNDING: 3646 return lowerSET_ROUNDING(Op, DAG); 3647 case ISD::VP_SELECT: 3648 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3649 case ISD::VP_MERGE: 3650 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3651 case ISD::VP_ADD: 3652 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3653 case ISD::VP_SUB: 3654 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3655 case ISD::VP_MUL: 3656 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3657 case ISD::VP_SDIV: 3658 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3659 case ISD::VP_UDIV: 3660 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3661 case ISD::VP_SREM: 3662 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3663 case ISD::VP_UREM: 3664 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3665 case ISD::VP_AND: 3666 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3667 case ISD::VP_OR: 3668 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3669 case ISD::VP_XOR: 3670 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3671 case ISD::VP_ASHR: 3672 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3673 case ISD::VP_LSHR: 3674 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3675 case ISD::VP_SHL: 3676 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3677 case ISD::VP_FADD: 3678 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3679 case ISD::VP_FSUB: 3680 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3681 case ISD::VP_FMUL: 3682 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3683 case ISD::VP_FDIV: 3684 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3685 case ISD::VP_FNEG: 3686 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3687 case ISD::VP_FMA: 3688 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3689 case ISD::VP_FPTOSI: 3690 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3691 case ISD::VP_FPTOUI: 3692 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3693 case ISD::VP_SITOFP: 3694 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3695 case ISD::VP_UITOFP: 3696 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_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 value, we can truncate it and rely on the 4626 // instruction to sign-extend since SEW>XLEN. 4627 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4628 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4629 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4630 } 4631 4632 switch (IntNo) { 4633 case Intrinsic::riscv_vslide1up: 4634 case Intrinsic::riscv_vslide1down: 4635 case Intrinsic::riscv_vslide1up_mask: 4636 case Intrinsic::riscv_vslide1down_mask: { 4637 // We need to special case these when the scalar is larger than XLen. 4638 unsigned NumOps = Op.getNumOperands(); 4639 bool IsMasked = NumOps == 7; 4640 4641 // Convert the vector source to the equivalent nxvXi32 vector. 4642 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4643 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4644 4645 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4646 DAG.getConstant(0, DL, XLenVT)); 4647 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4648 DAG.getConstant(1, DL, XLenVT)); 4649 4650 // Double the VL since we halved SEW. 4651 SDValue AVL = getVLOperand(Op); 4652 SDValue I32VL; 4653 4654 // Optimize for constant AVL 4655 if (isa<ConstantSDNode>(AVL)) { 4656 unsigned EltSize = VT.getScalarSizeInBits(); 4657 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4658 4659 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4660 unsigned MaxVLMAX = 4661 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4662 4663 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4664 unsigned MinVLMAX = 4665 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4666 4667 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4668 if (AVLInt <= MinVLMAX) { 4669 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4670 } else if (AVLInt >= 2 * MaxVLMAX) { 4671 // Just set vl to VLMAX in this situation 4672 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4673 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4674 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4675 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4676 SDValue SETVLMAX = DAG.getTargetConstant( 4677 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4678 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4679 LMUL); 4680 } else { 4681 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4682 // is related to the hardware implementation. 4683 // So let the following code handle 4684 } 4685 } 4686 if (!I32VL) { 4687 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4688 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4689 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4690 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4691 SDValue SETVL = 4692 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4693 // Using vsetvli instruction to get actually used length which related to 4694 // the hardware implementation 4695 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4696 SEW, LMUL); 4697 I32VL = 4698 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4699 } 4700 4701 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4702 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL); 4703 4704 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4705 // instructions. 4706 SDValue Passthru; 4707 if (IsMasked) 4708 Passthru = DAG.getUNDEF(I32VT); 4709 else 4710 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4711 4712 if (IntNo == Intrinsic::riscv_vslide1up || 4713 IntNo == Intrinsic::riscv_vslide1up_mask) { 4714 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4715 ScalarHi, I32Mask, I32VL); 4716 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4717 ScalarLo, I32Mask, I32VL); 4718 } else { 4719 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4720 ScalarLo, I32Mask, I32VL); 4721 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4722 ScalarHi, I32Mask, I32VL); 4723 } 4724 4725 // Convert back to nxvXi64. 4726 Vec = DAG.getBitcast(VT, Vec); 4727 4728 if (!IsMasked) 4729 return Vec; 4730 // Apply mask after the operation. 4731 SDValue Mask = Operands[NumOps - 3]; 4732 SDValue MaskedOff = Operands[1]; 4733 // Assume Policy operand is the last operand. 4734 uint64_t Policy = 4735 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4736 // We don't need to select maskedoff if it's undef. 4737 if (MaskedOff.isUndef()) 4738 return Vec; 4739 // TAMU 4740 if (Policy == RISCVII::TAIL_AGNOSTIC) 4741 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4742 AVL); 4743 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4744 // It's fine because vmerge does not care mask policy. 4745 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4746 AVL); 4747 } 4748 } 4749 4750 // We need to convert the scalar to a splat vector. 4751 SDValue VL = getVLOperand(Op); 4752 assert(VL.getValueType() == XLenVT); 4753 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4754 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4755 } 4756 4757 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4758 SelectionDAG &DAG) const { 4759 unsigned IntNo = Op.getConstantOperandVal(0); 4760 SDLoc DL(Op); 4761 MVT XLenVT = Subtarget.getXLenVT(); 4762 4763 switch (IntNo) { 4764 default: 4765 break; // Don't custom lower most intrinsics. 4766 case Intrinsic::thread_pointer: { 4767 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4768 return DAG.getRegister(RISCV::X4, PtrVT); 4769 } 4770 case Intrinsic::riscv_orc_b: 4771 case Intrinsic::riscv_brev8: { 4772 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4773 unsigned Opc = 4774 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4775 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4776 DAG.getConstant(7, DL, XLenVT)); 4777 } 4778 case Intrinsic::riscv_grev: 4779 case Intrinsic::riscv_gorc: { 4780 unsigned Opc = 4781 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4782 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4783 } 4784 case Intrinsic::riscv_zip: 4785 case Intrinsic::riscv_unzip: { 4786 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4787 // For i32 the immediate is 15. For i64 the immediate is 31. 4788 unsigned Opc = 4789 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4790 unsigned BitWidth = Op.getValueSizeInBits(); 4791 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4792 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4793 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4794 } 4795 case Intrinsic::riscv_shfl: 4796 case Intrinsic::riscv_unshfl: { 4797 unsigned Opc = 4798 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4799 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4800 } 4801 case Intrinsic::riscv_bcompress: 4802 case Intrinsic::riscv_bdecompress: { 4803 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4804 : RISCVISD::BDECOMPRESS; 4805 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4806 } 4807 case Intrinsic::riscv_bfp: 4808 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4809 Op.getOperand(2)); 4810 case Intrinsic::riscv_fsl: 4811 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4812 Op.getOperand(2), Op.getOperand(3)); 4813 case Intrinsic::riscv_fsr: 4814 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4815 Op.getOperand(2), Op.getOperand(3)); 4816 case Intrinsic::riscv_vmv_x_s: 4817 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4818 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4819 Op.getOperand(1)); 4820 case Intrinsic::riscv_vmv_v_x: 4821 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4822 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4823 Subtarget); 4824 case Intrinsic::riscv_vfmv_v_f: 4825 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4826 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4827 case Intrinsic::riscv_vmv_s_x: { 4828 SDValue Scalar = Op.getOperand(2); 4829 4830 if (Scalar.getValueType().bitsLE(XLenVT)) { 4831 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4832 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4833 Op.getOperand(1), Scalar, Op.getOperand(3)); 4834 } 4835 4836 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4837 4838 // This is an i64 value that lives in two scalar registers. We have to 4839 // insert this in a convoluted way. First we build vXi64 splat containing 4840 // the two values that we assemble using some bit math. Next we'll use 4841 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4842 // to merge element 0 from our splat into the source vector. 4843 // FIXME: This is probably not the best way to do this, but it is 4844 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4845 // point. 4846 // sw lo, (a0) 4847 // sw hi, 4(a0) 4848 // vlse vX, (a0) 4849 // 4850 // vid.v vVid 4851 // vmseq.vx mMask, vVid, 0 4852 // vmerge.vvm vDest, vSrc, vVal, mMask 4853 MVT VT = Op.getSimpleValueType(); 4854 SDValue Vec = Op.getOperand(1); 4855 SDValue VL = getVLOperand(Op); 4856 4857 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4858 if (Op.getOperand(1).isUndef()) 4859 return SplattedVal; 4860 SDValue SplattedIdx = 4861 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4862 DAG.getConstant(0, DL, MVT::i32), VL); 4863 4864 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4865 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4866 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4867 SDValue SelectCond = 4868 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4869 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4870 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4871 Vec, VL); 4872 } 4873 } 4874 4875 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4876 } 4877 4878 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4879 SelectionDAG &DAG) const { 4880 unsigned IntNo = Op.getConstantOperandVal(1); 4881 switch (IntNo) { 4882 default: 4883 break; 4884 case Intrinsic::riscv_masked_strided_load: { 4885 SDLoc DL(Op); 4886 MVT XLenVT = Subtarget.getXLenVT(); 4887 4888 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4889 // the selection of the masked intrinsics doesn't do this for us. 4890 SDValue Mask = Op.getOperand(5); 4891 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4892 4893 MVT VT = Op->getSimpleValueType(0); 4894 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4895 4896 SDValue PassThru = Op.getOperand(2); 4897 if (!IsUnmasked) { 4898 MVT MaskVT = 4899 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4900 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4901 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4902 } 4903 4904 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4905 4906 SDValue IntID = DAG.getTargetConstant( 4907 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4908 XLenVT); 4909 4910 auto *Load = cast<MemIntrinsicSDNode>(Op); 4911 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4912 if (IsUnmasked) 4913 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4914 else 4915 Ops.push_back(PassThru); 4916 Ops.push_back(Op.getOperand(3)); // Ptr 4917 Ops.push_back(Op.getOperand(4)); // Stride 4918 if (!IsUnmasked) 4919 Ops.push_back(Mask); 4920 Ops.push_back(VL); 4921 if (!IsUnmasked) { 4922 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4923 Ops.push_back(Policy); 4924 } 4925 4926 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4927 SDValue Result = 4928 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4929 Load->getMemoryVT(), Load->getMemOperand()); 4930 SDValue Chain = Result.getValue(1); 4931 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4932 return DAG.getMergeValues({Result, Chain}, DL); 4933 } 4934 case Intrinsic::riscv_seg2_load: 4935 case Intrinsic::riscv_seg3_load: 4936 case Intrinsic::riscv_seg4_load: 4937 case Intrinsic::riscv_seg5_load: 4938 case Intrinsic::riscv_seg6_load: 4939 case Intrinsic::riscv_seg7_load: 4940 case Intrinsic::riscv_seg8_load: { 4941 SDLoc DL(Op); 4942 static const Intrinsic::ID VlsegInts[7] = { 4943 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4944 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4945 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4946 Intrinsic::riscv_vlseg8}; 4947 unsigned NF = Op->getNumValues() - 1; 4948 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4949 MVT XLenVT = Subtarget.getXLenVT(); 4950 MVT VT = Op->getSimpleValueType(0); 4951 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4952 4953 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4954 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4955 auto *Load = cast<MemIntrinsicSDNode>(Op); 4956 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4957 ContainerVTs.push_back(MVT::Other); 4958 SDVTList VTs = DAG.getVTList(ContainerVTs); 4959 SDValue Result = 4960 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, 4961 {Load->getChain(), IntID, Op.getOperand(2), VL}, 4962 Load->getMemoryVT(), Load->getMemOperand()); 4963 SmallVector<SDValue, 9> Results; 4964 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4965 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4966 DAG, Subtarget)); 4967 Results.push_back(Result.getValue(NF)); 4968 return DAG.getMergeValues(Results, DL); 4969 } 4970 } 4971 4972 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4973 } 4974 4975 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4976 SelectionDAG &DAG) const { 4977 unsigned IntNo = Op.getConstantOperandVal(1); 4978 switch (IntNo) { 4979 default: 4980 break; 4981 case Intrinsic::riscv_masked_strided_store: { 4982 SDLoc DL(Op); 4983 MVT XLenVT = Subtarget.getXLenVT(); 4984 4985 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4986 // the selection of the masked intrinsics doesn't do this for us. 4987 SDValue Mask = Op.getOperand(5); 4988 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4989 4990 SDValue Val = Op.getOperand(2); 4991 MVT VT = Val.getSimpleValueType(); 4992 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4993 4994 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4995 if (!IsUnmasked) { 4996 MVT MaskVT = 4997 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4998 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4999 } 5000 5001 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5002 5003 SDValue IntID = DAG.getTargetConstant( 5004 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5005 XLenVT); 5006 5007 auto *Store = cast<MemIntrinsicSDNode>(Op); 5008 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5009 Ops.push_back(Val); 5010 Ops.push_back(Op.getOperand(3)); // Ptr 5011 Ops.push_back(Op.getOperand(4)); // Stride 5012 if (!IsUnmasked) 5013 Ops.push_back(Mask); 5014 Ops.push_back(VL); 5015 5016 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5017 Ops, Store->getMemoryVT(), 5018 Store->getMemOperand()); 5019 } 5020 } 5021 5022 return SDValue(); 5023 } 5024 5025 static MVT getLMUL1VT(MVT VT) { 5026 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5027 "Unexpected vector MVT"); 5028 return MVT::getScalableVectorVT( 5029 VT.getVectorElementType(), 5030 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5031 } 5032 5033 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5034 switch (ISDOpcode) { 5035 default: 5036 llvm_unreachable("Unhandled reduction"); 5037 case ISD::VECREDUCE_ADD: 5038 return RISCVISD::VECREDUCE_ADD_VL; 5039 case ISD::VECREDUCE_UMAX: 5040 return RISCVISD::VECREDUCE_UMAX_VL; 5041 case ISD::VECREDUCE_SMAX: 5042 return RISCVISD::VECREDUCE_SMAX_VL; 5043 case ISD::VECREDUCE_UMIN: 5044 return RISCVISD::VECREDUCE_UMIN_VL; 5045 case ISD::VECREDUCE_SMIN: 5046 return RISCVISD::VECREDUCE_SMIN_VL; 5047 case ISD::VECREDUCE_AND: 5048 return RISCVISD::VECREDUCE_AND_VL; 5049 case ISD::VECREDUCE_OR: 5050 return RISCVISD::VECREDUCE_OR_VL; 5051 case ISD::VECREDUCE_XOR: 5052 return RISCVISD::VECREDUCE_XOR_VL; 5053 } 5054 } 5055 5056 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5057 SelectionDAG &DAG, 5058 bool IsVP) const { 5059 SDLoc DL(Op); 5060 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5061 MVT VecVT = Vec.getSimpleValueType(); 5062 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5063 Op.getOpcode() == ISD::VECREDUCE_OR || 5064 Op.getOpcode() == ISD::VECREDUCE_XOR || 5065 Op.getOpcode() == ISD::VP_REDUCE_AND || 5066 Op.getOpcode() == ISD::VP_REDUCE_OR || 5067 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5068 "Unexpected reduction lowering"); 5069 5070 MVT XLenVT = Subtarget.getXLenVT(); 5071 assert(Op.getValueType() == XLenVT && 5072 "Expected reduction output to be legalized to XLenVT"); 5073 5074 MVT ContainerVT = VecVT; 5075 if (VecVT.isFixedLengthVector()) { 5076 ContainerVT = getContainerForFixedLengthVector(VecVT); 5077 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5078 } 5079 5080 SDValue Mask, VL; 5081 if (IsVP) { 5082 Mask = Op.getOperand(2); 5083 VL = Op.getOperand(3); 5084 } else { 5085 std::tie(Mask, VL) = 5086 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5087 } 5088 5089 unsigned BaseOpc; 5090 ISD::CondCode CC; 5091 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5092 5093 switch (Op.getOpcode()) { 5094 default: 5095 llvm_unreachable("Unhandled reduction"); 5096 case ISD::VECREDUCE_AND: 5097 case ISD::VP_REDUCE_AND: { 5098 // vcpop ~x == 0 5099 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5100 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5101 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5102 CC = ISD::SETEQ; 5103 BaseOpc = ISD::AND; 5104 break; 5105 } 5106 case ISD::VECREDUCE_OR: 5107 case ISD::VP_REDUCE_OR: 5108 // vcpop x != 0 5109 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5110 CC = ISD::SETNE; 5111 BaseOpc = ISD::OR; 5112 break; 5113 case ISD::VECREDUCE_XOR: 5114 case ISD::VP_REDUCE_XOR: { 5115 // ((vcpop x) & 1) != 0 5116 SDValue One = DAG.getConstant(1, DL, XLenVT); 5117 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5118 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5119 CC = ISD::SETNE; 5120 BaseOpc = ISD::XOR; 5121 break; 5122 } 5123 } 5124 5125 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5126 5127 if (!IsVP) 5128 return SetCC; 5129 5130 // Now include the start value in the operation. 5131 // Note that we must return the start value when no elements are operated 5132 // upon. The vcpop instructions we've emitted in each case above will return 5133 // 0 for an inactive vector, and so we've already received the neutral value: 5134 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5135 // can simply include the start value. 5136 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5137 } 5138 5139 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5140 SelectionDAG &DAG) const { 5141 SDLoc DL(Op); 5142 SDValue Vec = Op.getOperand(0); 5143 EVT VecEVT = Vec.getValueType(); 5144 5145 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5146 5147 // Due to ordering in legalize types we may have a vector type that needs to 5148 // be split. Do that manually so we can get down to a legal type. 5149 while (getTypeAction(*DAG.getContext(), VecEVT) == 5150 TargetLowering::TypeSplitVector) { 5151 SDValue Lo, Hi; 5152 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5153 VecEVT = Lo.getValueType(); 5154 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5155 } 5156 5157 // TODO: The type may need to be widened rather than split. Or widened before 5158 // it can be split. 5159 if (!isTypeLegal(VecEVT)) 5160 return SDValue(); 5161 5162 MVT VecVT = VecEVT.getSimpleVT(); 5163 MVT VecEltVT = VecVT.getVectorElementType(); 5164 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5165 5166 MVT ContainerVT = VecVT; 5167 if (VecVT.isFixedLengthVector()) { 5168 ContainerVT = getContainerForFixedLengthVector(VecVT); 5169 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5170 } 5171 5172 MVT M1VT = getLMUL1VT(ContainerVT); 5173 MVT XLenVT = Subtarget.getXLenVT(); 5174 5175 SDValue Mask, VL; 5176 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5177 5178 SDValue NeutralElem = 5179 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5180 SDValue IdentitySplat = 5181 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5182 M1VT, DL, DAG, Subtarget); 5183 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5184 IdentitySplat, Mask, VL); 5185 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5186 DAG.getConstant(0, DL, XLenVT)); 5187 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5188 } 5189 5190 // Given a reduction op, this function returns the matching reduction opcode, 5191 // the vector SDValue and the scalar SDValue required to lower this to a 5192 // RISCVISD node. 5193 static std::tuple<unsigned, SDValue, SDValue> 5194 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5195 SDLoc DL(Op); 5196 auto Flags = Op->getFlags(); 5197 unsigned Opcode = Op.getOpcode(); 5198 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5199 switch (Opcode) { 5200 default: 5201 llvm_unreachable("Unhandled reduction"); 5202 case ISD::VECREDUCE_FADD: { 5203 // Use positive zero if we can. It is cheaper to materialize. 5204 SDValue Zero = 5205 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5206 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5207 } 5208 case ISD::VECREDUCE_SEQ_FADD: 5209 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5210 Op.getOperand(0)); 5211 case ISD::VECREDUCE_FMIN: 5212 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5213 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5214 case ISD::VECREDUCE_FMAX: 5215 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5216 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5217 } 5218 } 5219 5220 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5221 SelectionDAG &DAG) const { 5222 SDLoc DL(Op); 5223 MVT VecEltVT = Op.getSimpleValueType(); 5224 5225 unsigned RVVOpcode; 5226 SDValue VectorVal, ScalarVal; 5227 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5228 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5229 MVT VecVT = VectorVal.getSimpleValueType(); 5230 5231 MVT ContainerVT = VecVT; 5232 if (VecVT.isFixedLengthVector()) { 5233 ContainerVT = getContainerForFixedLengthVector(VecVT); 5234 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5235 } 5236 5237 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5238 MVT XLenVT = Subtarget.getXLenVT(); 5239 5240 SDValue Mask, VL; 5241 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5242 5243 SDValue ScalarSplat = 5244 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5245 M1VT, DL, DAG, Subtarget); 5246 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5247 VectorVal, ScalarSplat, Mask, VL); 5248 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5249 DAG.getConstant(0, DL, XLenVT)); 5250 } 5251 5252 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5253 switch (ISDOpcode) { 5254 default: 5255 llvm_unreachable("Unhandled reduction"); 5256 case ISD::VP_REDUCE_ADD: 5257 return RISCVISD::VECREDUCE_ADD_VL; 5258 case ISD::VP_REDUCE_UMAX: 5259 return RISCVISD::VECREDUCE_UMAX_VL; 5260 case ISD::VP_REDUCE_SMAX: 5261 return RISCVISD::VECREDUCE_SMAX_VL; 5262 case ISD::VP_REDUCE_UMIN: 5263 return RISCVISD::VECREDUCE_UMIN_VL; 5264 case ISD::VP_REDUCE_SMIN: 5265 return RISCVISD::VECREDUCE_SMIN_VL; 5266 case ISD::VP_REDUCE_AND: 5267 return RISCVISD::VECREDUCE_AND_VL; 5268 case ISD::VP_REDUCE_OR: 5269 return RISCVISD::VECREDUCE_OR_VL; 5270 case ISD::VP_REDUCE_XOR: 5271 return RISCVISD::VECREDUCE_XOR_VL; 5272 case ISD::VP_REDUCE_FADD: 5273 return RISCVISD::VECREDUCE_FADD_VL; 5274 case ISD::VP_REDUCE_SEQ_FADD: 5275 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5276 case ISD::VP_REDUCE_FMAX: 5277 return RISCVISD::VECREDUCE_FMAX_VL; 5278 case ISD::VP_REDUCE_FMIN: 5279 return RISCVISD::VECREDUCE_FMIN_VL; 5280 } 5281 } 5282 5283 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5284 SelectionDAG &DAG) const { 5285 SDLoc DL(Op); 5286 SDValue Vec = Op.getOperand(1); 5287 EVT VecEVT = Vec.getValueType(); 5288 5289 // TODO: The type may need to be widened rather than split. Or widened before 5290 // it can be split. 5291 if (!isTypeLegal(VecEVT)) 5292 return SDValue(); 5293 5294 MVT VecVT = VecEVT.getSimpleVT(); 5295 MVT VecEltVT = VecVT.getVectorElementType(); 5296 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5297 5298 MVT ContainerVT = VecVT; 5299 if (VecVT.isFixedLengthVector()) { 5300 ContainerVT = getContainerForFixedLengthVector(VecVT); 5301 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5302 } 5303 5304 SDValue VL = Op.getOperand(3); 5305 SDValue Mask = Op.getOperand(2); 5306 5307 MVT M1VT = getLMUL1VT(ContainerVT); 5308 MVT XLenVT = Subtarget.getXLenVT(); 5309 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5310 5311 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5312 DAG.getConstant(1, DL, XLenVT), M1VT, 5313 DL, DAG, Subtarget); 5314 SDValue Reduction = 5315 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5316 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5317 DAG.getConstant(0, DL, XLenVT)); 5318 if (!VecVT.isInteger()) 5319 return Elt0; 5320 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5321 } 5322 5323 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5324 SelectionDAG &DAG) const { 5325 SDValue Vec = Op.getOperand(0); 5326 SDValue SubVec = Op.getOperand(1); 5327 MVT VecVT = Vec.getSimpleValueType(); 5328 MVT SubVecVT = SubVec.getSimpleValueType(); 5329 5330 SDLoc DL(Op); 5331 MVT XLenVT = Subtarget.getXLenVT(); 5332 unsigned OrigIdx = Op.getConstantOperandVal(2); 5333 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5334 5335 // We don't have the ability to slide mask vectors up indexed by their i1 5336 // elements; the smallest we can do is i8. Often we are able to bitcast to 5337 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5338 // into a scalable one, we might not necessarily have enough scalable 5339 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5340 if (SubVecVT.getVectorElementType() == MVT::i1 && 5341 (OrigIdx != 0 || !Vec.isUndef())) { 5342 if (VecVT.getVectorMinNumElements() >= 8 && 5343 SubVecVT.getVectorMinNumElements() >= 8) { 5344 assert(OrigIdx % 8 == 0 && "Invalid index"); 5345 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5346 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5347 "Unexpected mask vector lowering"); 5348 OrigIdx /= 8; 5349 SubVecVT = 5350 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5351 SubVecVT.isScalableVector()); 5352 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5353 VecVT.isScalableVector()); 5354 Vec = DAG.getBitcast(VecVT, Vec); 5355 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5356 } else { 5357 // We can't slide this mask vector up indexed by its i1 elements. 5358 // This poses a problem when we wish to insert a scalable vector which 5359 // can't be re-expressed as a larger type. Just choose the slow path and 5360 // extend to a larger type, then truncate back down. 5361 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5362 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5363 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5364 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5365 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5366 Op.getOperand(2)); 5367 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5368 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5369 } 5370 } 5371 5372 // If the subvector vector is a fixed-length type, we cannot use subregister 5373 // manipulation to simplify the codegen; we don't know which register of a 5374 // LMUL group contains the specific subvector as we only know the minimum 5375 // register size. Therefore we must slide the vector group up the full 5376 // amount. 5377 if (SubVecVT.isFixedLengthVector()) { 5378 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5379 return Op; 5380 MVT ContainerVT = VecVT; 5381 if (VecVT.isFixedLengthVector()) { 5382 ContainerVT = getContainerForFixedLengthVector(VecVT); 5383 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5384 } 5385 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5386 DAG.getUNDEF(ContainerVT), SubVec, 5387 DAG.getConstant(0, DL, XLenVT)); 5388 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5389 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5390 return DAG.getBitcast(Op.getValueType(), SubVec); 5391 } 5392 SDValue Mask = 5393 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5394 // Set the vector length to only the number of elements we care about. Note 5395 // that for slideup this includes the offset. 5396 SDValue VL = 5397 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5398 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5399 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5400 SubVec, SlideupAmt, Mask, VL); 5401 if (VecVT.isFixedLengthVector()) 5402 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5403 return DAG.getBitcast(Op.getValueType(), Slideup); 5404 } 5405 5406 unsigned SubRegIdx, RemIdx; 5407 std::tie(SubRegIdx, RemIdx) = 5408 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5409 VecVT, SubVecVT, OrigIdx, TRI); 5410 5411 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5412 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5413 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5414 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5415 5416 // 1. If the Idx has been completely eliminated and this subvector's size is 5417 // a vector register or a multiple thereof, or the surrounding elements are 5418 // undef, then this is a subvector insert which naturally aligns to a vector 5419 // register. These can easily be handled using subregister manipulation. 5420 // 2. If the subvector is smaller than a vector register, then the insertion 5421 // must preserve the undisturbed elements of the register. We do this by 5422 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5423 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5424 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5425 // LMUL=1 type back into the larger vector (resolving to another subregister 5426 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5427 // to avoid allocating a large register group to hold our subvector. 5428 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5429 return Op; 5430 5431 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5432 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5433 // (in our case undisturbed). This means we can set up a subvector insertion 5434 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5435 // size of the subvector. 5436 MVT InterSubVT = VecVT; 5437 SDValue AlignedExtract = Vec; 5438 unsigned AlignedIdx = OrigIdx - RemIdx; 5439 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5440 InterSubVT = getLMUL1VT(VecVT); 5441 // Extract a subvector equal to the nearest full vector register type. This 5442 // should resolve to a EXTRACT_SUBREG instruction. 5443 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5444 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5445 } 5446 5447 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5448 // For scalable vectors this must be further multiplied by vscale. 5449 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5450 5451 SDValue Mask, VL; 5452 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5453 5454 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5455 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5456 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5457 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5458 5459 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5460 DAG.getUNDEF(InterSubVT), SubVec, 5461 DAG.getConstant(0, DL, XLenVT)); 5462 5463 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5464 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5465 5466 // If required, insert this subvector back into the correct vector register. 5467 // This should resolve to an INSERT_SUBREG instruction. 5468 if (VecVT.bitsGT(InterSubVT)) 5469 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5470 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5471 5472 // We might have bitcast from a mask type: cast back to the original type if 5473 // required. 5474 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5475 } 5476 5477 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5478 SelectionDAG &DAG) const { 5479 SDValue Vec = Op.getOperand(0); 5480 MVT SubVecVT = Op.getSimpleValueType(); 5481 MVT VecVT = Vec.getSimpleValueType(); 5482 5483 SDLoc DL(Op); 5484 MVT XLenVT = Subtarget.getXLenVT(); 5485 unsigned OrigIdx = Op.getConstantOperandVal(1); 5486 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5487 5488 // We don't have the ability to slide mask vectors down indexed by their i1 5489 // elements; the smallest we can do is i8. Often we are able to bitcast to 5490 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5491 // from a scalable one, we might not necessarily have enough scalable 5492 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5493 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5494 if (VecVT.getVectorMinNumElements() >= 8 && 5495 SubVecVT.getVectorMinNumElements() >= 8) { 5496 assert(OrigIdx % 8 == 0 && "Invalid index"); 5497 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5498 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5499 "Unexpected mask vector lowering"); 5500 OrigIdx /= 8; 5501 SubVecVT = 5502 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5503 SubVecVT.isScalableVector()); 5504 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5505 VecVT.isScalableVector()); 5506 Vec = DAG.getBitcast(VecVT, Vec); 5507 } else { 5508 // We can't slide this mask vector down, indexed by its i1 elements. 5509 // This poses a problem when we wish to extract a scalable vector which 5510 // can't be re-expressed as a larger type. Just choose the slow path and 5511 // extend to a larger type, then truncate back down. 5512 // TODO: We could probably improve this when extracting certain fixed 5513 // from fixed, where we can extract as i8 and shift the correct element 5514 // right to reach the desired subvector? 5515 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5516 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5517 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5518 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5519 Op.getOperand(1)); 5520 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5521 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5522 } 5523 } 5524 5525 // If the subvector vector is a fixed-length type, we cannot use subregister 5526 // manipulation to simplify the codegen; we don't know which register of a 5527 // LMUL group contains the specific subvector as we only know the minimum 5528 // register size. Therefore we must slide the vector group down the full 5529 // amount. 5530 if (SubVecVT.isFixedLengthVector()) { 5531 // With an index of 0 this is a cast-like subvector, which can be performed 5532 // with subregister operations. 5533 if (OrigIdx == 0) 5534 return Op; 5535 MVT ContainerVT = VecVT; 5536 if (VecVT.isFixedLengthVector()) { 5537 ContainerVT = getContainerForFixedLengthVector(VecVT); 5538 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5539 } 5540 SDValue Mask = 5541 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5542 // Set the vector length to only the number of elements we care about. This 5543 // avoids sliding down elements we're going to discard straight away. 5544 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5545 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5546 SDValue Slidedown = 5547 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5548 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5549 // Now we can use a cast-like subvector extract to get the result. 5550 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5551 DAG.getConstant(0, DL, XLenVT)); 5552 return DAG.getBitcast(Op.getValueType(), Slidedown); 5553 } 5554 5555 unsigned SubRegIdx, RemIdx; 5556 std::tie(SubRegIdx, RemIdx) = 5557 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5558 VecVT, SubVecVT, OrigIdx, TRI); 5559 5560 // If the Idx has been completely eliminated then this is a subvector extract 5561 // which naturally aligns to a vector register. These can easily be handled 5562 // using subregister manipulation. 5563 if (RemIdx == 0) 5564 return Op; 5565 5566 // Else we must shift our vector register directly to extract the subvector. 5567 // Do this using VSLIDEDOWN. 5568 5569 // If the vector type is an LMUL-group type, extract a subvector equal to the 5570 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5571 // instruction. 5572 MVT InterSubVT = VecVT; 5573 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5574 InterSubVT = getLMUL1VT(VecVT); 5575 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5576 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5577 } 5578 5579 // Slide this vector register down by the desired number of elements in order 5580 // to place the desired subvector starting at element 0. 5581 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5582 // For scalable vectors this must be further multiplied by vscale. 5583 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5584 5585 SDValue Mask, VL; 5586 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5587 SDValue Slidedown = 5588 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5589 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5590 5591 // Now the vector is in the right position, extract our final subvector. This 5592 // should resolve to a COPY. 5593 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5594 DAG.getConstant(0, DL, XLenVT)); 5595 5596 // We might have bitcast from a mask type: cast back to the original type if 5597 // required. 5598 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5599 } 5600 5601 // Lower step_vector to the vid instruction. Any non-identity step value must 5602 // be accounted for my manual expansion. 5603 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5604 SelectionDAG &DAG) const { 5605 SDLoc DL(Op); 5606 MVT VT = Op.getSimpleValueType(); 5607 MVT XLenVT = Subtarget.getXLenVT(); 5608 SDValue Mask, VL; 5609 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5610 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5611 uint64_t StepValImm = Op.getConstantOperandVal(0); 5612 if (StepValImm != 1) { 5613 if (isPowerOf2_64(StepValImm)) { 5614 SDValue StepVal = 5615 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5616 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5617 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5618 } else { 5619 SDValue StepVal = lowerScalarSplat( 5620 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5621 VL, VT, DL, DAG, Subtarget); 5622 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5623 } 5624 } 5625 return StepVec; 5626 } 5627 5628 // Implement vector_reverse using vrgather.vv with indices determined by 5629 // subtracting the id of each element from (VLMAX-1). This will convert 5630 // the indices like so: 5631 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5632 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5633 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5634 SelectionDAG &DAG) const { 5635 SDLoc DL(Op); 5636 MVT VecVT = Op.getSimpleValueType(); 5637 unsigned EltSize = VecVT.getScalarSizeInBits(); 5638 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5639 5640 unsigned MaxVLMAX = 0; 5641 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5642 if (VectorBitsMax != 0) 5643 MaxVLMAX = 5644 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5645 5646 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5647 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5648 5649 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5650 // to use vrgatherei16.vv. 5651 // TODO: It's also possible to use vrgatherei16.vv for other types to 5652 // decrease register width for the index calculation. 5653 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5654 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5655 // Reverse each half, then reassemble them in reverse order. 5656 // NOTE: It's also possible that after splitting that VLMAX no longer 5657 // requires vrgatherei16.vv. 5658 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5659 SDValue Lo, Hi; 5660 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5661 EVT LoVT, HiVT; 5662 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5663 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5664 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5665 // Reassemble the low and high pieces reversed. 5666 // FIXME: This is a CONCAT_VECTORS. 5667 SDValue Res = 5668 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5669 DAG.getIntPtrConstant(0, DL)); 5670 return DAG.getNode( 5671 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5672 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5673 } 5674 5675 // Just promote the int type to i16 which will double the LMUL. 5676 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5677 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5678 } 5679 5680 MVT XLenVT = Subtarget.getXLenVT(); 5681 SDValue Mask, VL; 5682 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5683 5684 // Calculate VLMAX-1 for the desired SEW. 5685 unsigned MinElts = VecVT.getVectorMinNumElements(); 5686 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5687 DAG.getConstant(MinElts, DL, XLenVT)); 5688 SDValue VLMinus1 = 5689 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5690 5691 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5692 bool IsRV32E64 = 5693 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5694 SDValue SplatVL; 5695 if (!IsRV32E64) 5696 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5697 else 5698 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5699 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5700 5701 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5702 SDValue Indices = 5703 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5704 5705 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5706 } 5707 5708 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5709 SelectionDAG &DAG) const { 5710 SDLoc DL(Op); 5711 SDValue V1 = Op.getOperand(0); 5712 SDValue V2 = Op.getOperand(1); 5713 MVT XLenVT = Subtarget.getXLenVT(); 5714 MVT VecVT = Op.getSimpleValueType(); 5715 5716 unsigned MinElts = VecVT.getVectorMinNumElements(); 5717 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5718 DAG.getConstant(MinElts, DL, XLenVT)); 5719 5720 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5721 SDValue DownOffset, UpOffset; 5722 if (ImmValue >= 0) { 5723 // The operand is a TargetConstant, we need to rebuild it as a regular 5724 // constant. 5725 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5726 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5727 } else { 5728 // The operand is a TargetConstant, we need to rebuild it as a regular 5729 // constant rather than negating the original operand. 5730 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5731 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5732 } 5733 5734 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5735 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax); 5736 5737 SDValue SlideDown = 5738 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5739 DownOffset, TrueMask, UpOffset); 5740 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5741 TrueMask, 5742 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5743 } 5744 5745 SDValue 5746 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5747 SelectionDAG &DAG) const { 5748 SDLoc DL(Op); 5749 auto *Load = cast<LoadSDNode>(Op); 5750 5751 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5752 Load->getMemoryVT(), 5753 *Load->getMemOperand()) && 5754 "Expecting a correctly-aligned load"); 5755 5756 MVT VT = Op.getSimpleValueType(); 5757 MVT XLenVT = Subtarget.getXLenVT(); 5758 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5759 5760 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5761 5762 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5763 SDValue IntID = DAG.getTargetConstant( 5764 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5765 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5766 if (!IsMaskOp) 5767 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5768 Ops.push_back(Load->getBasePtr()); 5769 Ops.push_back(VL); 5770 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5771 SDValue NewLoad = 5772 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5773 Load->getMemoryVT(), Load->getMemOperand()); 5774 5775 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5776 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5777 } 5778 5779 SDValue 5780 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5781 SelectionDAG &DAG) const { 5782 SDLoc DL(Op); 5783 auto *Store = cast<StoreSDNode>(Op); 5784 5785 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5786 Store->getMemoryVT(), 5787 *Store->getMemOperand()) && 5788 "Expecting a correctly-aligned store"); 5789 5790 SDValue StoreVal = Store->getValue(); 5791 MVT VT = StoreVal.getSimpleValueType(); 5792 MVT XLenVT = Subtarget.getXLenVT(); 5793 5794 // If the size less than a byte, we need to pad with zeros to make a byte. 5795 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5796 VT = MVT::v8i1; 5797 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5798 DAG.getConstant(0, DL, VT), StoreVal, 5799 DAG.getIntPtrConstant(0, DL)); 5800 } 5801 5802 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5803 5804 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5805 5806 SDValue NewValue = 5807 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5808 5809 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5810 SDValue IntID = DAG.getTargetConstant( 5811 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5812 return DAG.getMemIntrinsicNode( 5813 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5814 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5815 Store->getMemoryVT(), Store->getMemOperand()); 5816 } 5817 5818 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5819 SelectionDAG &DAG) const { 5820 SDLoc DL(Op); 5821 MVT VT = Op.getSimpleValueType(); 5822 5823 const auto *MemSD = cast<MemSDNode>(Op); 5824 EVT MemVT = MemSD->getMemoryVT(); 5825 MachineMemOperand *MMO = MemSD->getMemOperand(); 5826 SDValue Chain = MemSD->getChain(); 5827 SDValue BasePtr = MemSD->getBasePtr(); 5828 5829 SDValue Mask, PassThru, VL; 5830 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5831 Mask = VPLoad->getMask(); 5832 PassThru = DAG.getUNDEF(VT); 5833 VL = VPLoad->getVectorLength(); 5834 } else { 5835 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5836 Mask = MLoad->getMask(); 5837 PassThru = MLoad->getPassThru(); 5838 } 5839 5840 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5841 5842 MVT XLenVT = Subtarget.getXLenVT(); 5843 5844 MVT ContainerVT = VT; 5845 if (VT.isFixedLengthVector()) { 5846 ContainerVT = getContainerForFixedLengthVector(VT); 5847 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5848 if (!IsUnmasked) { 5849 MVT MaskVT = 5850 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5851 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5852 } 5853 } 5854 5855 if (!VL) 5856 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5857 5858 unsigned IntID = 5859 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5860 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5861 if (IsUnmasked) 5862 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5863 else 5864 Ops.push_back(PassThru); 5865 Ops.push_back(BasePtr); 5866 if (!IsUnmasked) 5867 Ops.push_back(Mask); 5868 Ops.push_back(VL); 5869 if (!IsUnmasked) 5870 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5871 5872 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5873 5874 SDValue Result = 5875 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5876 Chain = Result.getValue(1); 5877 5878 if (VT.isFixedLengthVector()) 5879 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5880 5881 return DAG.getMergeValues({Result, Chain}, DL); 5882 } 5883 5884 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5885 SelectionDAG &DAG) const { 5886 SDLoc DL(Op); 5887 5888 const auto *MemSD = cast<MemSDNode>(Op); 5889 EVT MemVT = MemSD->getMemoryVT(); 5890 MachineMemOperand *MMO = MemSD->getMemOperand(); 5891 SDValue Chain = MemSD->getChain(); 5892 SDValue BasePtr = MemSD->getBasePtr(); 5893 SDValue Val, Mask, VL; 5894 5895 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5896 Val = VPStore->getValue(); 5897 Mask = VPStore->getMask(); 5898 VL = VPStore->getVectorLength(); 5899 } else { 5900 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5901 Val = MStore->getValue(); 5902 Mask = MStore->getMask(); 5903 } 5904 5905 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5906 5907 MVT VT = Val.getSimpleValueType(); 5908 MVT XLenVT = Subtarget.getXLenVT(); 5909 5910 MVT ContainerVT = VT; 5911 if (VT.isFixedLengthVector()) { 5912 ContainerVT = getContainerForFixedLengthVector(VT); 5913 5914 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5915 if (!IsUnmasked) { 5916 MVT MaskVT = 5917 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5918 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5919 } 5920 } 5921 5922 if (!VL) 5923 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5924 5925 unsigned IntID = 5926 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5927 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5928 Ops.push_back(Val); 5929 Ops.push_back(BasePtr); 5930 if (!IsUnmasked) 5931 Ops.push_back(Mask); 5932 Ops.push_back(VL); 5933 5934 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5935 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5936 } 5937 5938 SDValue 5939 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5940 SelectionDAG &DAG) const { 5941 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5942 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5943 5944 MVT VT = Op.getSimpleValueType(); 5945 5946 SDValue Op1 = 5947 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5948 SDValue Op2 = 5949 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5950 5951 SDLoc DL(Op); 5952 SDValue VL = 5953 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5954 5955 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5956 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5957 5958 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5959 Op.getOperand(2), Mask, VL); 5960 5961 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5962 } 5963 5964 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5965 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5966 MVT VT = Op.getSimpleValueType(); 5967 5968 if (VT.getVectorElementType() == MVT::i1) 5969 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5970 5971 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5972 } 5973 5974 SDValue 5975 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5976 SelectionDAG &DAG) const { 5977 unsigned Opc; 5978 switch (Op.getOpcode()) { 5979 default: llvm_unreachable("Unexpected opcode!"); 5980 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5981 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5982 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5983 } 5984 5985 return lowerToScalableOp(Op, DAG, Opc); 5986 } 5987 5988 // Lower vector ABS to smax(X, sub(0, X)). 5989 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5990 SDLoc DL(Op); 5991 MVT VT = Op.getSimpleValueType(); 5992 SDValue X = Op.getOperand(0); 5993 5994 assert(VT.isFixedLengthVector() && "Unexpected type"); 5995 5996 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5997 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5998 5999 SDValue Mask, VL; 6000 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6001 6002 SDValue SplatZero = DAG.getNode( 6003 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6004 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6005 SDValue NegX = 6006 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6007 SDValue Max = 6008 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6009 6010 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6011 } 6012 6013 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6014 SDValue Op, SelectionDAG &DAG) const { 6015 SDLoc DL(Op); 6016 MVT VT = Op.getSimpleValueType(); 6017 SDValue Mag = Op.getOperand(0); 6018 SDValue Sign = Op.getOperand(1); 6019 assert(Mag.getValueType() == Sign.getValueType() && 6020 "Can only handle COPYSIGN with matching types."); 6021 6022 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6023 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6024 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6025 6026 SDValue Mask, VL; 6027 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6028 6029 SDValue CopySign = 6030 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6031 6032 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6033 } 6034 6035 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6036 SDValue Op, SelectionDAG &DAG) const { 6037 MVT VT = Op.getSimpleValueType(); 6038 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6039 6040 MVT I1ContainerVT = 6041 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6042 6043 SDValue CC = 6044 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6045 SDValue Op1 = 6046 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6047 SDValue Op2 = 6048 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6049 6050 SDLoc DL(Op); 6051 SDValue Mask, VL; 6052 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6053 6054 SDValue Select = 6055 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6056 6057 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6058 } 6059 6060 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6061 unsigned NewOpc, 6062 bool HasMask) const { 6063 MVT VT = Op.getSimpleValueType(); 6064 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6065 6066 // Create list of operands by converting existing ones to scalable types. 6067 SmallVector<SDValue, 6> Ops; 6068 for (const SDValue &V : Op->op_values()) { 6069 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6070 6071 // Pass through non-vector operands. 6072 if (!V.getValueType().isVector()) { 6073 Ops.push_back(V); 6074 continue; 6075 } 6076 6077 // "cast" fixed length vector to a scalable vector. 6078 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6079 "Only fixed length vectors are supported!"); 6080 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6081 } 6082 6083 SDLoc DL(Op); 6084 SDValue Mask, VL; 6085 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6086 if (HasMask) 6087 Ops.push_back(Mask); 6088 Ops.push_back(VL); 6089 6090 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6091 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6092 } 6093 6094 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6095 // * Operands of each node are assumed to be in the same order. 6096 // * The EVL operand is promoted from i32 to i64 on RV64. 6097 // * Fixed-length vectors are converted to their scalable-vector container 6098 // types. 6099 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6100 unsigned RISCVISDOpc) const { 6101 SDLoc DL(Op); 6102 MVT VT = Op.getSimpleValueType(); 6103 SmallVector<SDValue, 4> Ops; 6104 6105 for (const auto &OpIdx : enumerate(Op->ops())) { 6106 SDValue V = OpIdx.value(); 6107 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6108 // Pass through operands which aren't fixed-length vectors. 6109 if (!V.getValueType().isFixedLengthVector()) { 6110 Ops.push_back(V); 6111 continue; 6112 } 6113 // "cast" fixed length vector to a scalable vector. 6114 MVT OpVT = V.getSimpleValueType(); 6115 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6116 assert(useRVVForFixedLengthVectorVT(OpVT) && 6117 "Only fixed length vectors are supported!"); 6118 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6119 } 6120 6121 if (!VT.isFixedLengthVector()) 6122 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6123 6124 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6125 6126 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6127 6128 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6129 } 6130 6131 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6132 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6133 unsigned RISCVISDOpc) const { 6134 SDLoc DL(Op); 6135 6136 SDValue Src = Op.getOperand(0); 6137 SDValue Mask = Op.getOperand(1); 6138 SDValue VL = Op.getOperand(2); 6139 6140 MVT DstVT = Op.getSimpleValueType(); 6141 MVT SrcVT = Src.getSimpleValueType(); 6142 if (DstVT.isFixedLengthVector()) { 6143 DstVT = getContainerForFixedLengthVector(DstVT); 6144 SrcVT = getContainerForFixedLengthVector(SrcVT); 6145 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6146 MVT MaskVT = MVT::getVectorVT(MVT::i1, DstVT.getVectorElementCount()); 6147 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6148 } 6149 6150 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6151 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6152 ? RISCVISD::VSEXT_VL 6153 : RISCVISD::VZEXT_VL; 6154 6155 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6156 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6157 6158 SDValue Result; 6159 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6160 if (SrcVT.isInteger()) { 6161 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6162 6163 // Do we need to do any pre-widening before converting? 6164 if (SrcEltSize == 1) { 6165 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6166 MVT XLenVT = Subtarget.getXLenVT(); 6167 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6168 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6169 DAG.getUNDEF(IntVT), Zero, VL); 6170 SDValue One = DAG.getConstant( 6171 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6172 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6173 DAG.getUNDEF(IntVT), One, VL); 6174 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6175 ZeroSplat, VL); 6176 } else if (DstEltSize > (2 * SrcEltSize)) { 6177 // Widen before converting. 6178 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6179 DstVT.getVectorElementCount()); 6180 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, {Src, Mask, VL}); 6181 } 6182 6183 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, {Src, Mask, VL}); 6184 } else { 6185 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6186 "Wrong input/output vector types"); 6187 6188 // Convert f16 to f32 then convert f32 to i64. 6189 if (DstEltSize > (2 * SrcEltSize)) { 6190 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6191 MVT InterimFVT = 6192 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6193 Src = DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, 6194 {Src, Mask, VL}); 6195 } 6196 6197 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, {Src, Mask, VL}); 6198 } 6199 } else { // Narrowing + Conversion 6200 if (SrcVT.isInteger()) { 6201 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6202 // First do a narrowing convert to an FP type half the size, then round 6203 // the FP type to a small FP type if needed. 6204 6205 MVT InterimFVT = DstVT; 6206 if (SrcEltSize > (2 * DstEltSize)) { 6207 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6208 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6209 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6210 } 6211 6212 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, {Src, Mask, VL}); 6213 6214 if (InterimFVT != DstVT) { 6215 Src = Result; 6216 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, {Src, Mask, VL}); 6217 } 6218 } else { 6219 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6220 "Wrong input/output vector types"); 6221 // First do a narrowing conversion to an integer half the size, then 6222 // truncate if needed. 6223 6224 // TODO: Handle mask vectors 6225 assert(DstVT.getVectorElementType() != MVT::i1 && 6226 "Don't know how to handle masks yet!"); 6227 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6228 DstVT.getVectorElementCount()); 6229 6230 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, {Src, Mask, VL}); 6231 6232 while (InterimIVT != DstVT) { 6233 SrcEltSize /= 2; 6234 Src = Result; 6235 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6236 DstVT.getVectorElementCount()); 6237 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6238 {Src, Mask, VL}); 6239 } 6240 } 6241 } 6242 6243 MVT VT = Op.getSimpleValueType(); 6244 if (!VT.isFixedLengthVector()) 6245 return Result; 6246 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6247 } 6248 6249 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6250 unsigned MaskOpc, 6251 unsigned VecOpc) const { 6252 MVT VT = Op.getSimpleValueType(); 6253 if (VT.getVectorElementType() != MVT::i1) 6254 return lowerVPOp(Op, DAG, VecOpc); 6255 6256 // It is safe to drop mask parameter as masked-off elements are undef. 6257 SDValue Op1 = Op->getOperand(0); 6258 SDValue Op2 = Op->getOperand(1); 6259 SDValue VL = Op->getOperand(3); 6260 6261 MVT ContainerVT = VT; 6262 const bool IsFixed = VT.isFixedLengthVector(); 6263 if (IsFixed) { 6264 ContainerVT = getContainerForFixedLengthVector(VT); 6265 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6266 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6267 } 6268 6269 SDLoc DL(Op); 6270 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6271 if (!IsFixed) 6272 return Val; 6273 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6274 } 6275 6276 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6277 // matched to a RVV indexed load. The RVV indexed load instructions only 6278 // support the "unsigned unscaled" addressing mode; indices are implicitly 6279 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6280 // signed or scaled indexing is extended to the XLEN value type and scaled 6281 // accordingly. 6282 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6283 SelectionDAG &DAG) const { 6284 SDLoc DL(Op); 6285 MVT VT = Op.getSimpleValueType(); 6286 6287 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6288 EVT MemVT = MemSD->getMemoryVT(); 6289 MachineMemOperand *MMO = MemSD->getMemOperand(); 6290 SDValue Chain = MemSD->getChain(); 6291 SDValue BasePtr = MemSD->getBasePtr(); 6292 6293 ISD::LoadExtType LoadExtType; 6294 SDValue Index, Mask, PassThru, VL; 6295 6296 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6297 Index = VPGN->getIndex(); 6298 Mask = VPGN->getMask(); 6299 PassThru = DAG.getUNDEF(VT); 6300 VL = VPGN->getVectorLength(); 6301 // VP doesn't support extending loads. 6302 LoadExtType = ISD::NON_EXTLOAD; 6303 } else { 6304 // Else it must be a MGATHER. 6305 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6306 Index = MGN->getIndex(); 6307 Mask = MGN->getMask(); 6308 PassThru = MGN->getPassThru(); 6309 LoadExtType = MGN->getExtensionType(); 6310 } 6311 6312 MVT IndexVT = Index.getSimpleValueType(); 6313 MVT XLenVT = Subtarget.getXLenVT(); 6314 6315 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6316 "Unexpected VTs!"); 6317 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6318 // Targets have to explicitly opt-in for extending vector loads. 6319 assert(LoadExtType == ISD::NON_EXTLOAD && 6320 "Unexpected extending MGATHER/VP_GATHER"); 6321 (void)LoadExtType; 6322 6323 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6324 // the selection of the masked intrinsics doesn't do this for us. 6325 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6326 6327 MVT ContainerVT = VT; 6328 if (VT.isFixedLengthVector()) { 6329 // We need to use the larger of the result and index type to determine the 6330 // scalable type to use so we don't increase LMUL for any operand/result. 6331 if (VT.bitsGE(IndexVT)) { 6332 ContainerVT = getContainerForFixedLengthVector(VT); 6333 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6334 ContainerVT.getVectorElementCount()); 6335 } else { 6336 IndexVT = getContainerForFixedLengthVector(IndexVT); 6337 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6338 IndexVT.getVectorElementCount()); 6339 } 6340 6341 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6342 6343 if (!IsUnmasked) { 6344 MVT MaskVT = 6345 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6346 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6347 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6348 } 6349 } 6350 6351 if (!VL) 6352 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6353 6354 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6355 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6356 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6357 VL); 6358 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6359 TrueMask, VL); 6360 } 6361 6362 unsigned IntID = 6363 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6364 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6365 if (IsUnmasked) 6366 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6367 else 6368 Ops.push_back(PassThru); 6369 Ops.push_back(BasePtr); 6370 Ops.push_back(Index); 6371 if (!IsUnmasked) 6372 Ops.push_back(Mask); 6373 Ops.push_back(VL); 6374 if (!IsUnmasked) 6375 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6376 6377 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6378 SDValue Result = 6379 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6380 Chain = Result.getValue(1); 6381 6382 if (VT.isFixedLengthVector()) 6383 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6384 6385 return DAG.getMergeValues({Result, Chain}, DL); 6386 } 6387 6388 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6389 // matched to a RVV indexed store. The RVV indexed store instructions only 6390 // support the "unsigned unscaled" addressing mode; indices are implicitly 6391 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6392 // signed or scaled indexing is extended to the XLEN value type and scaled 6393 // accordingly. 6394 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6395 SelectionDAG &DAG) const { 6396 SDLoc DL(Op); 6397 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6398 EVT MemVT = MemSD->getMemoryVT(); 6399 MachineMemOperand *MMO = MemSD->getMemOperand(); 6400 SDValue Chain = MemSD->getChain(); 6401 SDValue BasePtr = MemSD->getBasePtr(); 6402 6403 bool IsTruncatingStore = false; 6404 SDValue Index, Mask, Val, VL; 6405 6406 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6407 Index = VPSN->getIndex(); 6408 Mask = VPSN->getMask(); 6409 Val = VPSN->getValue(); 6410 VL = VPSN->getVectorLength(); 6411 // VP doesn't support truncating stores. 6412 IsTruncatingStore = false; 6413 } else { 6414 // Else it must be a MSCATTER. 6415 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6416 Index = MSN->getIndex(); 6417 Mask = MSN->getMask(); 6418 Val = MSN->getValue(); 6419 IsTruncatingStore = MSN->isTruncatingStore(); 6420 } 6421 6422 MVT VT = Val.getSimpleValueType(); 6423 MVT IndexVT = Index.getSimpleValueType(); 6424 MVT XLenVT = Subtarget.getXLenVT(); 6425 6426 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6427 "Unexpected VTs!"); 6428 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6429 // Targets have to explicitly opt-in for extending vector loads and 6430 // truncating vector stores. 6431 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6432 (void)IsTruncatingStore; 6433 6434 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6435 // the selection of the masked intrinsics doesn't do this for us. 6436 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6437 6438 MVT ContainerVT = VT; 6439 if (VT.isFixedLengthVector()) { 6440 // We need to use the larger of the value and index type to determine the 6441 // scalable type to use so we don't increase LMUL for any operand/result. 6442 if (VT.bitsGE(IndexVT)) { 6443 ContainerVT = getContainerForFixedLengthVector(VT); 6444 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6445 ContainerVT.getVectorElementCount()); 6446 } else { 6447 IndexVT = getContainerForFixedLengthVector(IndexVT); 6448 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6449 IndexVT.getVectorElementCount()); 6450 } 6451 6452 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6453 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6454 6455 if (!IsUnmasked) { 6456 MVT MaskVT = 6457 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6458 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6459 } 6460 } 6461 6462 if (!VL) 6463 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6464 6465 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6466 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6467 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6468 VL); 6469 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6470 TrueMask, VL); 6471 } 6472 6473 unsigned IntID = 6474 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6475 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6476 Ops.push_back(Val); 6477 Ops.push_back(BasePtr); 6478 Ops.push_back(Index); 6479 if (!IsUnmasked) 6480 Ops.push_back(Mask); 6481 Ops.push_back(VL); 6482 6483 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6484 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6485 } 6486 6487 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6488 SelectionDAG &DAG) const { 6489 const MVT XLenVT = Subtarget.getXLenVT(); 6490 SDLoc DL(Op); 6491 SDValue Chain = Op->getOperand(0); 6492 SDValue SysRegNo = DAG.getTargetConstant( 6493 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6494 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6495 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6496 6497 // Encoding used for rounding mode in RISCV differs from that used in 6498 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6499 // table, which consists of a sequence of 4-bit fields, each representing 6500 // corresponding FLT_ROUNDS mode. 6501 static const int Table = 6502 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6503 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6504 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6505 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6506 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6507 6508 SDValue Shift = 6509 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6510 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6511 DAG.getConstant(Table, DL, XLenVT), Shift); 6512 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6513 DAG.getConstant(7, DL, XLenVT)); 6514 6515 return DAG.getMergeValues({Masked, Chain}, DL); 6516 } 6517 6518 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6519 SelectionDAG &DAG) const { 6520 const MVT XLenVT = Subtarget.getXLenVT(); 6521 SDLoc DL(Op); 6522 SDValue Chain = Op->getOperand(0); 6523 SDValue RMValue = Op->getOperand(1); 6524 SDValue SysRegNo = DAG.getTargetConstant( 6525 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6526 6527 // Encoding used for rounding mode in RISCV differs from that used in 6528 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6529 // a table, which consists of a sequence of 4-bit fields, each representing 6530 // corresponding RISCV mode. 6531 static const unsigned Table = 6532 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6533 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6534 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6535 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6536 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6537 6538 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6539 DAG.getConstant(2, DL, XLenVT)); 6540 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6541 DAG.getConstant(Table, DL, XLenVT), Shift); 6542 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6543 DAG.getConstant(0x7, DL, XLenVT)); 6544 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6545 RMValue); 6546 } 6547 6548 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6549 switch (IntNo) { 6550 default: 6551 llvm_unreachable("Unexpected Intrinsic"); 6552 case Intrinsic::riscv_bcompress: 6553 return RISCVISD::BCOMPRESSW; 6554 case Intrinsic::riscv_bdecompress: 6555 return RISCVISD::BDECOMPRESSW; 6556 case Intrinsic::riscv_bfp: 6557 return RISCVISD::BFPW; 6558 case Intrinsic::riscv_fsl: 6559 return RISCVISD::FSLW; 6560 case Intrinsic::riscv_fsr: 6561 return RISCVISD::FSRW; 6562 } 6563 } 6564 6565 // Converts the given intrinsic to a i64 operation with any extension. 6566 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6567 unsigned IntNo) { 6568 SDLoc DL(N); 6569 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6570 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6571 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6572 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6573 // ReplaceNodeResults requires we maintain the same type for the return value. 6574 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6575 } 6576 6577 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6578 // form of the given Opcode. 6579 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6580 switch (Opcode) { 6581 default: 6582 llvm_unreachable("Unexpected opcode"); 6583 case ISD::SHL: 6584 return RISCVISD::SLLW; 6585 case ISD::SRA: 6586 return RISCVISD::SRAW; 6587 case ISD::SRL: 6588 return RISCVISD::SRLW; 6589 case ISD::SDIV: 6590 return RISCVISD::DIVW; 6591 case ISD::UDIV: 6592 return RISCVISD::DIVUW; 6593 case ISD::UREM: 6594 return RISCVISD::REMUW; 6595 case ISD::ROTL: 6596 return RISCVISD::ROLW; 6597 case ISD::ROTR: 6598 return RISCVISD::RORW; 6599 } 6600 } 6601 6602 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6603 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6604 // otherwise be promoted to i64, making it difficult to select the 6605 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6606 // type i8/i16/i32 is lost. 6607 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6608 unsigned ExtOpc = ISD::ANY_EXTEND) { 6609 SDLoc DL(N); 6610 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6611 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6612 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6613 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6614 // ReplaceNodeResults requires we maintain the same type for the return value. 6615 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6616 } 6617 6618 // Converts the given 32-bit operation to a i64 operation with signed extension 6619 // semantic to reduce the signed extension instructions. 6620 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6621 SDLoc DL(N); 6622 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6623 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6624 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6625 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6626 DAG.getValueType(MVT::i32)); 6627 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6628 } 6629 6630 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6631 SmallVectorImpl<SDValue> &Results, 6632 SelectionDAG &DAG) const { 6633 SDLoc DL(N); 6634 switch (N->getOpcode()) { 6635 default: 6636 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6637 case ISD::STRICT_FP_TO_SINT: 6638 case ISD::STRICT_FP_TO_UINT: 6639 case ISD::FP_TO_SINT: 6640 case ISD::FP_TO_UINT: { 6641 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6642 "Unexpected custom legalisation"); 6643 bool IsStrict = N->isStrictFPOpcode(); 6644 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6645 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6646 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6647 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6648 TargetLowering::TypeSoftenFloat) { 6649 if (!isTypeLegal(Op0.getValueType())) 6650 return; 6651 if (IsStrict) { 6652 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6653 : RISCVISD::STRICT_FCVT_WU_RV64; 6654 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6655 SDValue Res = DAG.getNode( 6656 Opc, DL, VTs, N->getOperand(0), Op0, 6657 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6658 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6659 Results.push_back(Res.getValue(1)); 6660 return; 6661 } 6662 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6663 SDValue Res = 6664 DAG.getNode(Opc, DL, MVT::i64, Op0, 6665 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6666 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6667 return; 6668 } 6669 // If the FP type needs to be softened, emit a library call using the 'si' 6670 // version. If we left it to default legalization we'd end up with 'di'. If 6671 // the FP type doesn't need to be softened just let generic type 6672 // legalization promote the result type. 6673 RTLIB::Libcall LC; 6674 if (IsSigned) 6675 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6676 else 6677 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6678 MakeLibCallOptions CallOptions; 6679 EVT OpVT = Op0.getValueType(); 6680 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6681 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6682 SDValue Result; 6683 std::tie(Result, Chain) = 6684 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6685 Results.push_back(Result); 6686 if (IsStrict) 6687 Results.push_back(Chain); 6688 break; 6689 } 6690 case ISD::READCYCLECOUNTER: { 6691 assert(!Subtarget.is64Bit() && 6692 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6693 6694 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6695 SDValue RCW = 6696 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6697 6698 Results.push_back( 6699 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6700 Results.push_back(RCW.getValue(2)); 6701 break; 6702 } 6703 case ISD::MUL: { 6704 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6705 unsigned XLen = Subtarget.getXLen(); 6706 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6707 if (Size > XLen) { 6708 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6709 SDValue LHS = N->getOperand(0); 6710 SDValue RHS = N->getOperand(1); 6711 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6712 6713 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6714 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6715 // We need exactly one side to be unsigned. 6716 if (LHSIsU == RHSIsU) 6717 return; 6718 6719 auto MakeMULPair = [&](SDValue S, SDValue U) { 6720 MVT XLenVT = Subtarget.getXLenVT(); 6721 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6722 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6723 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6724 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6725 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6726 }; 6727 6728 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6729 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6730 6731 // The other operand should be signed, but still prefer MULH when 6732 // possible. 6733 if (RHSIsU && LHSIsS && !RHSIsS) 6734 Results.push_back(MakeMULPair(LHS, RHS)); 6735 else if (LHSIsU && RHSIsS && !LHSIsS) 6736 Results.push_back(MakeMULPair(RHS, LHS)); 6737 6738 return; 6739 } 6740 LLVM_FALLTHROUGH; 6741 } 6742 case ISD::ADD: 6743 case ISD::SUB: 6744 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6745 "Unexpected custom legalisation"); 6746 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6747 break; 6748 case ISD::SHL: 6749 case ISD::SRA: 6750 case ISD::SRL: 6751 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6752 "Unexpected custom legalisation"); 6753 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6754 Results.push_back(customLegalizeToWOp(N, DAG)); 6755 break; 6756 } 6757 6758 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6759 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6760 // shift amount. 6761 if (N->getOpcode() == ISD::SHL) { 6762 SDLoc DL(N); 6763 SDValue NewOp0 = 6764 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6765 SDValue NewOp1 = 6766 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6767 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6768 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6769 DAG.getValueType(MVT::i32)); 6770 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6771 } 6772 6773 break; 6774 case ISD::ROTL: 6775 case ISD::ROTR: 6776 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6777 "Unexpected custom legalisation"); 6778 Results.push_back(customLegalizeToWOp(N, DAG)); 6779 break; 6780 case ISD::CTTZ: 6781 case ISD::CTTZ_ZERO_UNDEF: 6782 case ISD::CTLZ: 6783 case ISD::CTLZ_ZERO_UNDEF: { 6784 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6785 "Unexpected custom legalisation"); 6786 6787 SDValue NewOp0 = 6788 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6789 bool IsCTZ = 6790 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6791 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6792 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6793 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6794 return; 6795 } 6796 case ISD::SDIV: 6797 case ISD::UDIV: 6798 case ISD::UREM: { 6799 MVT VT = N->getSimpleValueType(0); 6800 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6801 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6802 "Unexpected custom legalisation"); 6803 // Don't promote division/remainder by constant since we should expand those 6804 // to multiply by magic constant. 6805 // FIXME: What if the expansion is disabled for minsize. 6806 if (N->getOperand(1).getOpcode() == ISD::Constant) 6807 return; 6808 6809 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6810 // the upper 32 bits. For other types we need to sign or zero extend 6811 // based on the opcode. 6812 unsigned ExtOpc = ISD::ANY_EXTEND; 6813 if (VT != MVT::i32) 6814 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6815 : ISD::ZERO_EXTEND; 6816 6817 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6818 break; 6819 } 6820 case ISD::UADDO: 6821 case ISD::USUBO: { 6822 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6823 "Unexpected custom legalisation"); 6824 bool IsAdd = N->getOpcode() == ISD::UADDO; 6825 // Create an ADDW or SUBW. 6826 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6827 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6828 SDValue Res = 6829 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6830 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6831 DAG.getValueType(MVT::i32)); 6832 6833 SDValue Overflow; 6834 if (IsAdd && isOneConstant(RHS)) { 6835 // Special case uaddo X, 1 overflowed if the addition result is 0. 6836 // FIXME: We can do this for any constant RHS by using (X + C) < C. 6837 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6838 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6839 } else { 6840 // Sign extend the LHS and perform an unsigned compare with the ADDW 6841 // result. Since the inputs are sign extended from i32, this is equivalent 6842 // to comparing the lower 32 bits. 6843 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6844 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6845 IsAdd ? ISD::SETULT : ISD::SETUGT); 6846 } 6847 6848 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6849 Results.push_back(Overflow); 6850 return; 6851 } 6852 case ISD::UADDSAT: 6853 case ISD::USUBSAT: { 6854 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6855 "Unexpected custom legalisation"); 6856 if (Subtarget.hasStdExtZbb()) { 6857 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6858 // sign extend allows overflow of the lower 32 bits to be detected on 6859 // the promoted size. 6860 SDValue LHS = 6861 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6862 SDValue RHS = 6863 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6864 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6865 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6866 return; 6867 } 6868 6869 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6870 // promotion for UADDO/USUBO. 6871 Results.push_back(expandAddSubSat(N, DAG)); 6872 return; 6873 } 6874 case ISD::ABS: { 6875 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6876 "Unexpected custom legalisation"); 6877 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6878 6879 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6880 6881 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6882 6883 // Freeze the source so we can increase it's use count. 6884 Src = DAG.getFreeze(Src); 6885 6886 // Copy sign bit to all bits using the sraiw pattern. 6887 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6888 DAG.getValueType(MVT::i32)); 6889 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6890 DAG.getConstant(31, DL, MVT::i64)); 6891 6892 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6893 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6894 6895 // NOTE: The result is only required to be anyextended, but sext is 6896 // consistent with type legalization of sub. 6897 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6898 DAG.getValueType(MVT::i32)); 6899 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6900 return; 6901 } 6902 case ISD::BITCAST: { 6903 EVT VT = N->getValueType(0); 6904 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6905 SDValue Op0 = N->getOperand(0); 6906 EVT Op0VT = Op0.getValueType(); 6907 MVT XLenVT = Subtarget.getXLenVT(); 6908 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6909 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6910 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6911 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6912 Subtarget.hasStdExtF()) { 6913 SDValue FPConv = 6914 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6915 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6916 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6917 isTypeLegal(Op0VT)) { 6918 // Custom-legalize bitcasts from fixed-length vector types to illegal 6919 // scalar types in order to improve codegen. Bitcast the vector to a 6920 // one-element vector type whose element type is the same as the result 6921 // type, and extract the first element. 6922 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6923 if (isTypeLegal(BVT)) { 6924 SDValue BVec = DAG.getBitcast(BVT, Op0); 6925 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6926 DAG.getConstant(0, DL, XLenVT))); 6927 } 6928 } 6929 break; 6930 } 6931 case RISCVISD::GREV: 6932 case RISCVISD::GORC: 6933 case RISCVISD::SHFL: { 6934 MVT VT = N->getSimpleValueType(0); 6935 MVT XLenVT = Subtarget.getXLenVT(); 6936 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 6937 "Unexpected custom legalisation"); 6938 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6939 assert((Subtarget.hasStdExtZbp() || 6940 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 6941 N->getConstantOperandVal(1) == 7)) && 6942 "Unexpected extension"); 6943 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6944 SDValue NewOp1 = 6945 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 6946 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 6947 // ReplaceNodeResults requires we maintain the same type for the return 6948 // value. 6949 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 6950 break; 6951 } 6952 case ISD::BSWAP: 6953 case ISD::BITREVERSE: { 6954 MVT VT = N->getSimpleValueType(0); 6955 MVT XLenVT = Subtarget.getXLenVT(); 6956 assert((VT == MVT::i8 || VT == MVT::i16 || 6957 (VT == MVT::i32 && Subtarget.is64Bit())) && 6958 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6959 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6960 unsigned Imm = VT.getSizeInBits() - 1; 6961 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6962 if (N->getOpcode() == ISD::BSWAP) 6963 Imm &= ~0x7U; 6964 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 6965 DAG.getConstant(Imm, DL, XLenVT)); 6966 // ReplaceNodeResults requires we maintain the same type for the return 6967 // value. 6968 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6969 break; 6970 } 6971 case ISD::FSHL: 6972 case ISD::FSHR: { 6973 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6974 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6975 SDValue NewOp0 = 6976 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6977 SDValue NewOp1 = 6978 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6979 SDValue NewShAmt = 6980 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6981 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6982 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6983 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6984 DAG.getConstant(0x1f, DL, MVT::i64)); 6985 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6986 // instruction use different orders. fshl will return its first operand for 6987 // shift of zero, fshr will return its second operand. fsl and fsr both 6988 // return rs1 so the ISD nodes need to have different operand orders. 6989 // Shift amount is in rs2. 6990 unsigned Opc = RISCVISD::FSLW; 6991 if (N->getOpcode() == ISD::FSHR) { 6992 std::swap(NewOp0, NewOp1); 6993 Opc = RISCVISD::FSRW; 6994 } 6995 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6996 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6997 break; 6998 } 6999 case ISD::EXTRACT_VECTOR_ELT: { 7000 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7001 // type is illegal (currently only vXi64 RV32). 7002 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7003 // transferred to the destination register. We issue two of these from the 7004 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7005 // first element. 7006 SDValue Vec = N->getOperand(0); 7007 SDValue Idx = N->getOperand(1); 7008 7009 // The vector type hasn't been legalized yet so we can't issue target 7010 // specific nodes if it needs legalization. 7011 // FIXME: We would manually legalize if it's important. 7012 if (!isTypeLegal(Vec.getValueType())) 7013 return; 7014 7015 MVT VecVT = Vec.getSimpleValueType(); 7016 7017 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7018 VecVT.getVectorElementType() == MVT::i64 && 7019 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7020 7021 // If this is a fixed vector, we need to convert it to a scalable vector. 7022 MVT ContainerVT = VecVT; 7023 if (VecVT.isFixedLengthVector()) { 7024 ContainerVT = getContainerForFixedLengthVector(VecVT); 7025 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7026 } 7027 7028 MVT XLenVT = Subtarget.getXLenVT(); 7029 7030 // Use a VL of 1 to avoid processing more elements than we need. 7031 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 7032 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7033 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 7034 7035 // Unless the index is known to be 0, we must slide the vector down to get 7036 // the desired element into index 0. 7037 if (!isNullConstant(Idx)) { 7038 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7039 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7040 } 7041 7042 // Extract the lower XLEN bits of the correct vector element. 7043 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7044 7045 // To extract the upper XLEN bits of the vector element, shift the first 7046 // element right by 32 bits and re-extract the lower XLEN bits. 7047 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7048 DAG.getUNDEF(ContainerVT), 7049 DAG.getConstant(32, DL, XLenVT), VL); 7050 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7051 ThirtyTwoV, Mask, VL); 7052 7053 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7054 7055 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7056 break; 7057 } 7058 case ISD::INTRINSIC_WO_CHAIN: { 7059 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7060 switch (IntNo) { 7061 default: 7062 llvm_unreachable( 7063 "Don't know how to custom type legalize this intrinsic!"); 7064 case Intrinsic::riscv_grev: 7065 case Intrinsic::riscv_gorc: { 7066 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7067 "Unexpected custom legalisation"); 7068 SDValue NewOp1 = 7069 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7070 SDValue NewOp2 = 7071 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7072 unsigned Opc = 7073 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7074 // If the control is a constant, promote the node by clearing any extra 7075 // bits bits in the control. isel will form greviw/gorciw if the result is 7076 // sign extended. 7077 if (isa<ConstantSDNode>(NewOp2)) { 7078 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7079 DAG.getConstant(0x1f, DL, MVT::i64)); 7080 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7081 } 7082 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7083 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7084 break; 7085 } 7086 case Intrinsic::riscv_bcompress: 7087 case Intrinsic::riscv_bdecompress: 7088 case Intrinsic::riscv_bfp: { 7089 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7090 "Unexpected custom legalisation"); 7091 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7092 break; 7093 } 7094 case Intrinsic::riscv_fsl: 7095 case Intrinsic::riscv_fsr: { 7096 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7097 "Unexpected custom legalisation"); 7098 SDValue NewOp1 = 7099 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7100 SDValue NewOp2 = 7101 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7102 SDValue NewOp3 = 7103 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 7104 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 7105 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 7106 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7107 break; 7108 } 7109 case Intrinsic::riscv_orc_b: { 7110 // Lower to the GORCI encoding for orc.b with the operand extended. 7111 SDValue NewOp = 7112 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7113 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7114 DAG.getConstant(7, DL, MVT::i64)); 7115 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7116 return; 7117 } 7118 case Intrinsic::riscv_shfl: 7119 case Intrinsic::riscv_unshfl: { 7120 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7121 "Unexpected custom legalisation"); 7122 SDValue NewOp1 = 7123 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7124 SDValue NewOp2 = 7125 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7126 unsigned Opc = 7127 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7128 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7129 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7130 // will be shuffled the same way as the lower 32 bit half, but the two 7131 // halves won't cross. 7132 if (isa<ConstantSDNode>(NewOp2)) { 7133 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7134 DAG.getConstant(0xf, DL, MVT::i64)); 7135 Opc = 7136 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7137 } 7138 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7139 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7140 break; 7141 } 7142 case Intrinsic::riscv_vmv_x_s: { 7143 EVT VT = N->getValueType(0); 7144 MVT XLenVT = Subtarget.getXLenVT(); 7145 if (VT.bitsLT(XLenVT)) { 7146 // Simple case just extract using vmv.x.s and truncate. 7147 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7148 Subtarget.getXLenVT(), N->getOperand(1)); 7149 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7150 return; 7151 } 7152 7153 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7154 "Unexpected custom legalization"); 7155 7156 // We need to do the move in two steps. 7157 SDValue Vec = N->getOperand(1); 7158 MVT VecVT = Vec.getSimpleValueType(); 7159 7160 // First extract the lower XLEN bits of the element. 7161 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7162 7163 // To extract the upper XLEN bits of the vector element, shift the first 7164 // element right by 32 bits and re-extract the lower XLEN bits. 7165 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7166 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7167 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 7168 SDValue ThirtyTwoV = 7169 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7170 DAG.getConstant(32, DL, XLenVT), VL); 7171 SDValue LShr32 = 7172 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7173 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7174 7175 Results.push_back( 7176 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7177 break; 7178 } 7179 } 7180 break; 7181 } 7182 case ISD::VECREDUCE_ADD: 7183 case ISD::VECREDUCE_AND: 7184 case ISD::VECREDUCE_OR: 7185 case ISD::VECREDUCE_XOR: 7186 case ISD::VECREDUCE_SMAX: 7187 case ISD::VECREDUCE_UMAX: 7188 case ISD::VECREDUCE_SMIN: 7189 case ISD::VECREDUCE_UMIN: 7190 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7191 Results.push_back(V); 7192 break; 7193 case ISD::VP_REDUCE_ADD: 7194 case ISD::VP_REDUCE_AND: 7195 case ISD::VP_REDUCE_OR: 7196 case ISD::VP_REDUCE_XOR: 7197 case ISD::VP_REDUCE_SMAX: 7198 case ISD::VP_REDUCE_UMAX: 7199 case ISD::VP_REDUCE_SMIN: 7200 case ISD::VP_REDUCE_UMIN: 7201 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7202 Results.push_back(V); 7203 break; 7204 case ISD::FLT_ROUNDS_: { 7205 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7206 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7207 Results.push_back(Res.getValue(0)); 7208 Results.push_back(Res.getValue(1)); 7209 break; 7210 } 7211 } 7212 } 7213 7214 // A structure to hold one of the bit-manipulation patterns below. Together, a 7215 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7216 // (or (and (shl x, 1), 0xAAAAAAAA), 7217 // (and (srl x, 1), 0x55555555)) 7218 struct RISCVBitmanipPat { 7219 SDValue Op; 7220 unsigned ShAmt; 7221 bool IsSHL; 7222 7223 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7224 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7225 } 7226 }; 7227 7228 // Matches patterns of the form 7229 // (and (shl x, C2), (C1 << C2)) 7230 // (and (srl x, C2), C1) 7231 // (shl (and x, C1), C2) 7232 // (srl (and x, (C1 << C2)), C2) 7233 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7234 // The expected masks for each shift amount are specified in BitmanipMasks where 7235 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7236 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7237 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7238 // XLen is 64. 7239 static Optional<RISCVBitmanipPat> 7240 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7241 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7242 "Unexpected number of masks"); 7243 Optional<uint64_t> Mask; 7244 // Optionally consume a mask around the shift operation. 7245 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7246 Mask = Op.getConstantOperandVal(1); 7247 Op = Op.getOperand(0); 7248 } 7249 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7250 return None; 7251 bool IsSHL = Op.getOpcode() == ISD::SHL; 7252 7253 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7254 return None; 7255 uint64_t ShAmt = Op.getConstantOperandVal(1); 7256 7257 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7258 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7259 return None; 7260 // If we don't have enough masks for 64 bit, then we must be trying to 7261 // match SHFL so we're only allowed to shift 1/4 of the width. 7262 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7263 return None; 7264 7265 SDValue Src = Op.getOperand(0); 7266 7267 // The expected mask is shifted left when the AND is found around SHL 7268 // patterns. 7269 // ((x >> 1) & 0x55555555) 7270 // ((x << 1) & 0xAAAAAAAA) 7271 bool SHLExpMask = IsSHL; 7272 7273 if (!Mask) { 7274 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7275 // the mask is all ones: consume that now. 7276 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7277 Mask = Src.getConstantOperandVal(1); 7278 Src = Src.getOperand(0); 7279 // The expected mask is now in fact shifted left for SRL, so reverse the 7280 // decision. 7281 // ((x & 0xAAAAAAAA) >> 1) 7282 // ((x & 0x55555555) << 1) 7283 SHLExpMask = !SHLExpMask; 7284 } else { 7285 // Use a default shifted mask of all-ones if there's no AND, truncated 7286 // down to the expected width. This simplifies the logic later on. 7287 Mask = maskTrailingOnes<uint64_t>(Width); 7288 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7289 } 7290 } 7291 7292 unsigned MaskIdx = Log2_32(ShAmt); 7293 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7294 7295 if (SHLExpMask) 7296 ExpMask <<= ShAmt; 7297 7298 if (Mask != ExpMask) 7299 return None; 7300 7301 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7302 } 7303 7304 // Matches any of the following bit-manipulation patterns: 7305 // (and (shl x, 1), (0x55555555 << 1)) 7306 // (and (srl x, 1), 0x55555555) 7307 // (shl (and x, 0x55555555), 1) 7308 // (srl (and x, (0x55555555 << 1)), 1) 7309 // where the shift amount and mask may vary thus: 7310 // [1] = 0x55555555 / 0xAAAAAAAA 7311 // [2] = 0x33333333 / 0xCCCCCCCC 7312 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7313 // [8] = 0x00FF00FF / 0xFF00FF00 7314 // [16] = 0x0000FFFF / 0xFFFFFFFF 7315 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7316 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7317 // These are the unshifted masks which we use to match bit-manipulation 7318 // patterns. They may be shifted left in certain circumstances. 7319 static const uint64_t BitmanipMasks[] = { 7320 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7321 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7322 7323 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7324 } 7325 7326 // Match the following pattern as a GREVI(W) operation 7327 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7328 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7329 const RISCVSubtarget &Subtarget) { 7330 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7331 EVT VT = Op.getValueType(); 7332 7333 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7334 auto LHS = matchGREVIPat(Op.getOperand(0)); 7335 auto RHS = matchGREVIPat(Op.getOperand(1)); 7336 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7337 SDLoc DL(Op); 7338 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7339 DAG.getConstant(LHS->ShAmt, DL, VT)); 7340 } 7341 } 7342 return SDValue(); 7343 } 7344 7345 // Matches any the following pattern as a GORCI(W) operation 7346 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7347 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7348 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7349 // Note that with the variant of 3., 7350 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7351 // the inner pattern will first be matched as GREVI and then the outer 7352 // pattern will be matched to GORC via the first rule above. 7353 // 4. (or (rotl/rotr x, bitwidth/2), x) 7354 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7355 const RISCVSubtarget &Subtarget) { 7356 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7357 EVT VT = Op.getValueType(); 7358 7359 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7360 SDLoc DL(Op); 7361 SDValue Op0 = Op.getOperand(0); 7362 SDValue Op1 = Op.getOperand(1); 7363 7364 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7365 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7366 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7367 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7368 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7369 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7370 if ((Reverse.getOpcode() == ISD::ROTL || 7371 Reverse.getOpcode() == ISD::ROTR) && 7372 Reverse.getOperand(0) == X && 7373 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7374 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7375 if (RotAmt == (VT.getSizeInBits() / 2)) 7376 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7377 DAG.getConstant(RotAmt, DL, VT)); 7378 } 7379 return SDValue(); 7380 }; 7381 7382 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7383 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7384 return V; 7385 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7386 return V; 7387 7388 // OR is commutable so canonicalize its OR operand to the left 7389 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7390 std::swap(Op0, Op1); 7391 if (Op0.getOpcode() != ISD::OR) 7392 return SDValue(); 7393 SDValue OrOp0 = Op0.getOperand(0); 7394 SDValue OrOp1 = Op0.getOperand(1); 7395 auto LHS = matchGREVIPat(OrOp0); 7396 // OR is commutable so swap the operands and try again: x might have been 7397 // on the left 7398 if (!LHS) { 7399 std::swap(OrOp0, OrOp1); 7400 LHS = matchGREVIPat(OrOp0); 7401 } 7402 auto RHS = matchGREVIPat(Op1); 7403 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7404 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7405 DAG.getConstant(LHS->ShAmt, DL, VT)); 7406 } 7407 } 7408 return SDValue(); 7409 } 7410 7411 // Matches any of the following bit-manipulation patterns: 7412 // (and (shl x, 1), (0x22222222 << 1)) 7413 // (and (srl x, 1), 0x22222222) 7414 // (shl (and x, 0x22222222), 1) 7415 // (srl (and x, (0x22222222 << 1)), 1) 7416 // where the shift amount and mask may vary thus: 7417 // [1] = 0x22222222 / 0x44444444 7418 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7419 // [4] = 0x00F000F0 / 0x0F000F00 7420 // [8] = 0x0000FF00 / 0x00FF0000 7421 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7422 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7423 // These are the unshifted masks which we use to match bit-manipulation 7424 // patterns. They may be shifted left in certain circumstances. 7425 static const uint64_t BitmanipMasks[] = { 7426 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7427 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7428 7429 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7430 } 7431 7432 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7433 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7434 const RISCVSubtarget &Subtarget) { 7435 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7436 EVT VT = Op.getValueType(); 7437 7438 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7439 return SDValue(); 7440 7441 SDValue Op0 = Op.getOperand(0); 7442 SDValue Op1 = Op.getOperand(1); 7443 7444 // Or is commutable so canonicalize the second OR to the LHS. 7445 if (Op0.getOpcode() != ISD::OR) 7446 std::swap(Op0, Op1); 7447 if (Op0.getOpcode() != ISD::OR) 7448 return SDValue(); 7449 7450 // We found an inner OR, so our operands are the operands of the inner OR 7451 // and the other operand of the outer OR. 7452 SDValue A = Op0.getOperand(0); 7453 SDValue B = Op0.getOperand(1); 7454 SDValue C = Op1; 7455 7456 auto Match1 = matchSHFLPat(A); 7457 auto Match2 = matchSHFLPat(B); 7458 7459 // If neither matched, we failed. 7460 if (!Match1 && !Match2) 7461 return SDValue(); 7462 7463 // We had at least one match. if one failed, try the remaining C operand. 7464 if (!Match1) { 7465 std::swap(A, C); 7466 Match1 = matchSHFLPat(A); 7467 if (!Match1) 7468 return SDValue(); 7469 } else if (!Match2) { 7470 std::swap(B, C); 7471 Match2 = matchSHFLPat(B); 7472 if (!Match2) 7473 return SDValue(); 7474 } 7475 assert(Match1 && Match2); 7476 7477 // Make sure our matches pair up. 7478 if (!Match1->formsPairWith(*Match2)) 7479 return SDValue(); 7480 7481 // All the remains is to make sure C is an AND with the same input, that masks 7482 // out the bits that are being shuffled. 7483 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7484 C.getOperand(0) != Match1->Op) 7485 return SDValue(); 7486 7487 uint64_t Mask = C.getConstantOperandVal(1); 7488 7489 static const uint64_t BitmanipMasks[] = { 7490 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7491 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7492 }; 7493 7494 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7495 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7496 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7497 7498 if (Mask != ExpMask) 7499 return SDValue(); 7500 7501 SDLoc DL(Op); 7502 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7503 DAG.getConstant(Match1->ShAmt, DL, VT)); 7504 } 7505 7506 // Optimize (add (shl x, c0), (shl y, c1)) -> 7507 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7508 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7509 const RISCVSubtarget &Subtarget) { 7510 // Perform this optimization only in the zba extension. 7511 if (!Subtarget.hasStdExtZba()) 7512 return SDValue(); 7513 7514 // Skip for vector types and larger types. 7515 EVT VT = N->getValueType(0); 7516 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7517 return SDValue(); 7518 7519 // The two operand nodes must be SHL and have no other use. 7520 SDValue N0 = N->getOperand(0); 7521 SDValue N1 = N->getOperand(1); 7522 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7523 !N0->hasOneUse() || !N1->hasOneUse()) 7524 return SDValue(); 7525 7526 // Check c0 and c1. 7527 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7528 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7529 if (!N0C || !N1C) 7530 return SDValue(); 7531 int64_t C0 = N0C->getSExtValue(); 7532 int64_t C1 = N1C->getSExtValue(); 7533 if (C0 <= 0 || C1 <= 0) 7534 return SDValue(); 7535 7536 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7537 int64_t Bits = std::min(C0, C1); 7538 int64_t Diff = std::abs(C0 - C1); 7539 if (Diff != 1 && Diff != 2 && Diff != 3) 7540 return SDValue(); 7541 7542 // Build nodes. 7543 SDLoc DL(N); 7544 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7545 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7546 SDValue NA0 = 7547 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7548 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7549 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7550 } 7551 7552 // Combine 7553 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7554 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7555 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7556 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7557 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7558 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7559 // The grev patterns represents BSWAP. 7560 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7561 // off the grev. 7562 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7563 const RISCVSubtarget &Subtarget) { 7564 bool IsWInstruction = 7565 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7566 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7567 IsWInstruction) && 7568 "Unexpected opcode!"); 7569 SDValue Src = N->getOperand(0); 7570 EVT VT = N->getValueType(0); 7571 SDLoc DL(N); 7572 7573 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7574 return SDValue(); 7575 7576 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7577 !isa<ConstantSDNode>(Src.getOperand(1))) 7578 return SDValue(); 7579 7580 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7581 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7582 7583 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7584 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7585 unsigned ShAmt1 = N->getConstantOperandVal(1); 7586 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7587 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7588 return SDValue(); 7589 7590 Src = Src.getOperand(0); 7591 7592 // Toggle bit the MSB of the shift. 7593 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7594 if (CombinedShAmt == 0) 7595 return Src; 7596 7597 SDValue Res = DAG.getNode( 7598 RISCVISD::GREV, DL, VT, Src, 7599 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7600 if (!IsWInstruction) 7601 return Res; 7602 7603 // Sign extend the result to match the behavior of the rotate. This will be 7604 // selected to GREVIW in isel. 7605 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7606 DAG.getValueType(MVT::i32)); 7607 } 7608 7609 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7610 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7611 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7612 // not undo itself, but they are redundant. 7613 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7614 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7615 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7616 SDValue Src = N->getOperand(0); 7617 7618 if (Src.getOpcode() != N->getOpcode()) 7619 return SDValue(); 7620 7621 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7622 !isa<ConstantSDNode>(Src.getOperand(1))) 7623 return SDValue(); 7624 7625 unsigned ShAmt1 = N->getConstantOperandVal(1); 7626 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7627 Src = Src.getOperand(0); 7628 7629 unsigned CombinedShAmt; 7630 if (IsGORC) 7631 CombinedShAmt = ShAmt1 | ShAmt2; 7632 else 7633 CombinedShAmt = ShAmt1 ^ ShAmt2; 7634 7635 if (CombinedShAmt == 0) 7636 return Src; 7637 7638 SDLoc DL(N); 7639 return DAG.getNode( 7640 N->getOpcode(), DL, N->getValueType(0), Src, 7641 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7642 } 7643 7644 // Combine a constant select operand into its use: 7645 // 7646 // (and (select cond, -1, c), x) 7647 // -> (select cond, x, (and x, c)) [AllOnes=1] 7648 // (or (select cond, 0, c), x) 7649 // -> (select cond, x, (or x, c)) [AllOnes=0] 7650 // (xor (select cond, 0, c), x) 7651 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7652 // (add (select cond, 0, c), x) 7653 // -> (select cond, x, (add x, c)) [AllOnes=0] 7654 // (sub x, (select cond, 0, c)) 7655 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7656 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7657 SelectionDAG &DAG, bool AllOnes) { 7658 EVT VT = N->getValueType(0); 7659 7660 // Skip vectors. 7661 if (VT.isVector()) 7662 return SDValue(); 7663 7664 if ((Slct.getOpcode() != ISD::SELECT && 7665 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7666 !Slct.hasOneUse()) 7667 return SDValue(); 7668 7669 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7670 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7671 }; 7672 7673 bool SwapSelectOps; 7674 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7675 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7676 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7677 SDValue NonConstantVal; 7678 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7679 SwapSelectOps = false; 7680 NonConstantVal = FalseVal; 7681 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7682 SwapSelectOps = true; 7683 NonConstantVal = TrueVal; 7684 } else 7685 return SDValue(); 7686 7687 // Slct is now know to be the desired identity constant when CC is true. 7688 TrueVal = OtherOp; 7689 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7690 // Unless SwapSelectOps says the condition should be false. 7691 if (SwapSelectOps) 7692 std::swap(TrueVal, FalseVal); 7693 7694 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7695 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7696 {Slct.getOperand(0), Slct.getOperand(1), 7697 Slct.getOperand(2), TrueVal, FalseVal}); 7698 7699 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7700 {Slct.getOperand(0), TrueVal, FalseVal}); 7701 } 7702 7703 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7704 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7705 bool AllOnes) { 7706 SDValue N0 = N->getOperand(0); 7707 SDValue N1 = N->getOperand(1); 7708 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7709 return Result; 7710 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7711 return Result; 7712 return SDValue(); 7713 } 7714 7715 // Transform (add (mul x, c0), c1) -> 7716 // (add (mul (add x, c1/c0), c0), c1%c0). 7717 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7718 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7719 // to an infinite loop in DAGCombine if transformed. 7720 // Or transform (add (mul x, c0), c1) -> 7721 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7722 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7723 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7724 // lead to an infinite loop in DAGCombine if transformed. 7725 // Or transform (add (mul x, c0), c1) -> 7726 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7727 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7728 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7729 // lead to an infinite loop in DAGCombine if transformed. 7730 // Or transform (add (mul x, c0), c1) -> 7731 // (mul (add x, c1/c0), c0). 7732 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7733 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7734 const RISCVSubtarget &Subtarget) { 7735 // Skip for vector types and larger types. 7736 EVT VT = N->getValueType(0); 7737 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7738 return SDValue(); 7739 // The first operand node must be a MUL and has no other use. 7740 SDValue N0 = N->getOperand(0); 7741 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7742 return SDValue(); 7743 // Check if c0 and c1 match above conditions. 7744 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7745 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7746 if (!N0C || !N1C) 7747 return SDValue(); 7748 // If N0C has multiple uses it's possible one of the cases in 7749 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7750 // in an infinite loop. 7751 if (!N0C->hasOneUse()) 7752 return SDValue(); 7753 int64_t C0 = N0C->getSExtValue(); 7754 int64_t C1 = N1C->getSExtValue(); 7755 int64_t CA, CB; 7756 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7757 return SDValue(); 7758 // Search for proper CA (non-zero) and CB that both are simm12. 7759 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7760 !isInt<12>(C0 * (C1 / C0))) { 7761 CA = C1 / C0; 7762 CB = C1 % C0; 7763 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7764 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7765 CA = C1 / C0 + 1; 7766 CB = C1 % C0 - C0; 7767 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7768 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7769 CA = C1 / C0 - 1; 7770 CB = C1 % C0 + C0; 7771 } else 7772 return SDValue(); 7773 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7774 SDLoc DL(N); 7775 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7776 DAG.getConstant(CA, DL, VT)); 7777 SDValue New1 = 7778 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7779 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7780 } 7781 7782 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7783 const RISCVSubtarget &Subtarget) { 7784 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7785 return V; 7786 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7787 return V; 7788 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7789 // (select lhs, rhs, cc, x, (add x, y)) 7790 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7791 } 7792 7793 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7794 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7795 // (select lhs, rhs, cc, x, (sub x, y)) 7796 SDValue N0 = N->getOperand(0); 7797 SDValue N1 = N->getOperand(1); 7798 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7799 } 7800 7801 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7802 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7803 // (select lhs, rhs, cc, x, (and x, y)) 7804 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7805 } 7806 7807 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7808 const RISCVSubtarget &Subtarget) { 7809 if (Subtarget.hasStdExtZbp()) { 7810 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7811 return GREV; 7812 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7813 return GORC; 7814 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7815 return SHFL; 7816 } 7817 7818 // fold (or (select cond, 0, y), x) -> 7819 // (select cond, x, (or x, y)) 7820 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7821 } 7822 7823 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7824 // fold (xor (select cond, 0, y), x) -> 7825 // (select cond, x, (xor x, y)) 7826 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7827 } 7828 7829 static SDValue 7830 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 7831 const RISCVSubtarget &Subtarget) { 7832 SDValue Src = N->getOperand(0); 7833 EVT VT = N->getValueType(0); 7834 7835 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 7836 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7837 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 7838 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 7839 Src.getOperand(0)); 7840 7841 // Fold (i64 (sext_inreg (abs X), i32)) -> 7842 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 7843 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 7844 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 7845 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 7846 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 7847 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 7848 // may get combined into an earlier operation so we need to use 7849 // ComputeNumSignBits. 7850 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 7851 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 7852 // we can't assume that X has 33 sign bits. We must check. 7853 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 7854 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 7855 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 7856 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 7857 SDLoc DL(N); 7858 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 7859 SDValue Neg = 7860 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 7861 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 7862 DAG.getValueType(MVT::i32)); 7863 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 7864 } 7865 7866 return SDValue(); 7867 } 7868 7869 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7870 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7871 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7872 bool Commute = false) { 7873 assert((N->getOpcode() == RISCVISD::ADD_VL || 7874 N->getOpcode() == RISCVISD::SUB_VL) && 7875 "Unexpected opcode"); 7876 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7877 SDValue Op0 = N->getOperand(0); 7878 SDValue Op1 = N->getOperand(1); 7879 if (Commute) 7880 std::swap(Op0, Op1); 7881 7882 MVT VT = N->getSimpleValueType(0); 7883 7884 // Determine the narrow size for a widening add/sub. 7885 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7886 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7887 VT.getVectorElementCount()); 7888 7889 SDValue Mask = N->getOperand(2); 7890 SDValue VL = N->getOperand(3); 7891 7892 SDLoc DL(N); 7893 7894 // If the RHS is a sext or zext, we can form a widening op. 7895 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7896 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7897 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7898 unsigned ExtOpc = Op1.getOpcode(); 7899 Op1 = Op1.getOperand(0); 7900 // Re-introduce narrower extends if needed. 7901 if (Op1.getValueType() != NarrowVT) 7902 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7903 7904 unsigned WOpc; 7905 if (ExtOpc == RISCVISD::VSEXT_VL) 7906 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7907 else 7908 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7909 7910 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7911 } 7912 7913 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7914 // sext/zext? 7915 7916 return SDValue(); 7917 } 7918 7919 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7920 // vwsub(u).vv/vx. 7921 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7922 SDValue Op0 = N->getOperand(0); 7923 SDValue Op1 = N->getOperand(1); 7924 SDValue Mask = N->getOperand(2); 7925 SDValue VL = N->getOperand(3); 7926 7927 MVT VT = N->getSimpleValueType(0); 7928 MVT NarrowVT = Op1.getSimpleValueType(); 7929 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 7930 7931 unsigned VOpc; 7932 switch (N->getOpcode()) { 7933 default: llvm_unreachable("Unexpected opcode"); 7934 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 7935 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 7936 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 7937 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 7938 } 7939 7940 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 7941 N->getOpcode() == RISCVISD::VWSUB_W_VL; 7942 7943 SDLoc DL(N); 7944 7945 // If the LHS is a sext or zext, we can narrow this op to the same size as 7946 // the RHS. 7947 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 7948 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 7949 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 7950 unsigned ExtOpc = Op0.getOpcode(); 7951 Op0 = Op0.getOperand(0); 7952 // Re-introduce narrower extends if needed. 7953 if (Op0.getValueType() != NarrowVT) 7954 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7955 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 7956 } 7957 7958 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 7959 N->getOpcode() == RISCVISD::VWADDU_W_VL; 7960 7961 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 7962 // to commute and use a vwadd(u).vx instead. 7963 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 7964 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 7965 Op0 = Op0.getOperand(1); 7966 7967 // See if have enough sign bits or zero bits in the scalar to use a 7968 // widening add/sub by splatting to smaller element size. 7969 unsigned EltBits = VT.getScalarSizeInBits(); 7970 unsigned ScalarBits = Op0.getValueSizeInBits(); 7971 // Make sure we're getting all element bits from the scalar register. 7972 // FIXME: Support implicit sign extension of vmv.v.x? 7973 if (ScalarBits < EltBits) 7974 return SDValue(); 7975 7976 if (IsSigned) { 7977 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 7978 return SDValue(); 7979 } else { 7980 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7981 if (!DAG.MaskedValueIsZero(Op0, Mask)) 7982 return SDValue(); 7983 } 7984 7985 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7986 DAG.getUNDEF(NarrowVT), Op0, VL); 7987 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 7988 } 7989 7990 return SDValue(); 7991 } 7992 7993 // Try to form VWMUL, VWMULU or VWMULSU. 7994 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 7995 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 7996 bool Commute) { 7997 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7998 SDValue Op0 = N->getOperand(0); 7999 SDValue Op1 = N->getOperand(1); 8000 if (Commute) 8001 std::swap(Op0, Op1); 8002 8003 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8004 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8005 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8006 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8007 return SDValue(); 8008 8009 SDValue Mask = N->getOperand(2); 8010 SDValue VL = N->getOperand(3); 8011 8012 // Make sure the mask and VL match. 8013 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8014 return SDValue(); 8015 8016 MVT VT = N->getSimpleValueType(0); 8017 8018 // Determine the narrow size for a widening multiply. 8019 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8020 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8021 VT.getVectorElementCount()); 8022 8023 SDLoc DL(N); 8024 8025 // See if the other operand is the same opcode. 8026 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8027 if (!Op1.hasOneUse()) 8028 return SDValue(); 8029 8030 // Make sure the mask and VL match. 8031 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8032 return SDValue(); 8033 8034 Op1 = Op1.getOperand(0); 8035 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8036 // The operand is a splat of a scalar. 8037 8038 // The pasthru must be undef for tail agnostic 8039 if (!Op1.getOperand(0).isUndef()) 8040 return SDValue(); 8041 // The VL must be the same. 8042 if (Op1.getOperand(2) != VL) 8043 return SDValue(); 8044 8045 // Get the scalar value. 8046 Op1 = Op1.getOperand(1); 8047 8048 // See if have enough sign bits or zero bits in the scalar to use a 8049 // widening multiply by splatting to smaller element size. 8050 unsigned EltBits = VT.getScalarSizeInBits(); 8051 unsigned ScalarBits = Op1.getValueSizeInBits(); 8052 // Make sure we're getting all element bits from the scalar register. 8053 // FIXME: Support implicit sign extension of vmv.v.x? 8054 if (ScalarBits < EltBits) 8055 return SDValue(); 8056 8057 // If the LHS is a sign extend, try to use vwmul. 8058 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8059 // Can use vwmul. 8060 } else { 8061 // Otherwise try to use vwmulu or vwmulsu. 8062 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8063 if (DAG.MaskedValueIsZero(Op1, Mask)) 8064 IsVWMULSU = IsSignExt; 8065 else 8066 return SDValue(); 8067 } 8068 8069 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8070 DAG.getUNDEF(NarrowVT), Op1, VL); 8071 } else 8072 return SDValue(); 8073 8074 Op0 = Op0.getOperand(0); 8075 8076 // Re-introduce narrower extends if needed. 8077 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8078 if (Op0.getValueType() != NarrowVT) 8079 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8080 // vwmulsu requires second operand to be zero extended. 8081 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8082 if (Op1.getValueType() != NarrowVT) 8083 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8084 8085 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8086 if (!IsVWMULSU) 8087 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8088 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8089 } 8090 8091 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8092 switch (Op.getOpcode()) { 8093 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8094 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8095 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8096 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8097 case ISD::FROUND: return RISCVFPRndMode::RMM; 8098 } 8099 8100 return RISCVFPRndMode::Invalid; 8101 } 8102 8103 // Fold 8104 // (fp_to_int (froundeven X)) -> fcvt X, rne 8105 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8106 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8107 // (fp_to_int (fceil X)) -> fcvt X, rup 8108 // (fp_to_int (fround X)) -> fcvt X, rmm 8109 static SDValue performFP_TO_INTCombine(SDNode *N, 8110 TargetLowering::DAGCombinerInfo &DCI, 8111 const RISCVSubtarget &Subtarget) { 8112 SelectionDAG &DAG = DCI.DAG; 8113 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8114 MVT XLenVT = Subtarget.getXLenVT(); 8115 8116 // Only handle XLen or i32 types. Other types narrower than XLen will 8117 // eventually be legalized to XLenVT. 8118 EVT VT = N->getValueType(0); 8119 if (VT != MVT::i32 && VT != XLenVT) 8120 return SDValue(); 8121 8122 SDValue Src = N->getOperand(0); 8123 8124 // Ensure the FP type is also legal. 8125 if (!TLI.isTypeLegal(Src.getValueType())) 8126 return SDValue(); 8127 8128 // Don't do this for f16 with Zfhmin and not Zfh. 8129 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8130 return SDValue(); 8131 8132 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8133 if (FRM == RISCVFPRndMode::Invalid) 8134 return SDValue(); 8135 8136 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8137 8138 unsigned Opc; 8139 if (VT == XLenVT) 8140 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8141 else 8142 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8143 8144 SDLoc DL(N); 8145 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8146 DAG.getTargetConstant(FRM, DL, XLenVT)); 8147 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8148 } 8149 8150 // Fold 8151 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8152 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8153 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8154 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8155 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8156 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8157 TargetLowering::DAGCombinerInfo &DCI, 8158 const RISCVSubtarget &Subtarget) { 8159 SelectionDAG &DAG = DCI.DAG; 8160 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8161 MVT XLenVT = Subtarget.getXLenVT(); 8162 8163 // Only handle XLen types. Other types narrower than XLen will eventually be 8164 // legalized to XLenVT. 8165 EVT DstVT = N->getValueType(0); 8166 if (DstVT != XLenVT) 8167 return SDValue(); 8168 8169 SDValue Src = N->getOperand(0); 8170 8171 // Ensure the FP type is also legal. 8172 if (!TLI.isTypeLegal(Src.getValueType())) 8173 return SDValue(); 8174 8175 // Don't do this for f16 with Zfhmin and not Zfh. 8176 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8177 return SDValue(); 8178 8179 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8180 8181 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8182 if (FRM == RISCVFPRndMode::Invalid) 8183 return SDValue(); 8184 8185 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8186 8187 unsigned Opc; 8188 if (SatVT == DstVT) 8189 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8190 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8191 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8192 else 8193 return SDValue(); 8194 // FIXME: Support other SatVTs by clamping before or after the conversion. 8195 8196 Src = Src.getOperand(0); 8197 8198 SDLoc DL(N); 8199 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8200 DAG.getTargetConstant(FRM, DL, XLenVT)); 8201 8202 // RISCV FP-to-int conversions saturate to the destination register size, but 8203 // don't produce 0 for nan. 8204 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8205 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8206 } 8207 8208 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8209 // smaller than XLenVT. 8210 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8211 const RISCVSubtarget &Subtarget) { 8212 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8213 8214 SDValue Src = N->getOperand(0); 8215 if (Src.getOpcode() != ISD::BSWAP) 8216 return SDValue(); 8217 8218 EVT VT = N->getValueType(0); 8219 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8220 !isPowerOf2_32(VT.getSizeInBits())) 8221 return SDValue(); 8222 8223 SDLoc DL(N); 8224 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8225 DAG.getConstant(7, DL, VT)); 8226 } 8227 8228 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8229 DAGCombinerInfo &DCI) const { 8230 SelectionDAG &DAG = DCI.DAG; 8231 8232 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8233 // bits are demanded. N will be added to the Worklist if it was not deleted. 8234 // Caller should return SDValue(N, 0) if this returns true. 8235 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8236 SDValue Op = N->getOperand(OpNo); 8237 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8238 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8239 return false; 8240 8241 if (N->getOpcode() != ISD::DELETED_NODE) 8242 DCI.AddToWorklist(N); 8243 return true; 8244 }; 8245 8246 switch (N->getOpcode()) { 8247 default: 8248 break; 8249 case RISCVISD::SplitF64: { 8250 SDValue Op0 = N->getOperand(0); 8251 // If the input to SplitF64 is just BuildPairF64 then the operation is 8252 // redundant. Instead, use BuildPairF64's operands directly. 8253 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8254 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8255 8256 if (Op0->isUndef()) { 8257 SDValue Lo = DAG.getUNDEF(MVT::i32); 8258 SDValue Hi = DAG.getUNDEF(MVT::i32); 8259 return DCI.CombineTo(N, Lo, Hi); 8260 } 8261 8262 SDLoc DL(N); 8263 8264 // It's cheaper to materialise two 32-bit integers than to load a double 8265 // from the constant pool and transfer it to integer registers through the 8266 // stack. 8267 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8268 APInt V = C->getValueAPF().bitcastToAPInt(); 8269 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8270 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8271 return DCI.CombineTo(N, Lo, Hi); 8272 } 8273 8274 // This is a target-specific version of a DAGCombine performed in 8275 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8276 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8277 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8278 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8279 !Op0.getNode()->hasOneUse()) 8280 break; 8281 SDValue NewSplitF64 = 8282 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8283 Op0.getOperand(0)); 8284 SDValue Lo = NewSplitF64.getValue(0); 8285 SDValue Hi = NewSplitF64.getValue(1); 8286 APInt SignBit = APInt::getSignMask(32); 8287 if (Op0.getOpcode() == ISD::FNEG) { 8288 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8289 DAG.getConstant(SignBit, DL, MVT::i32)); 8290 return DCI.CombineTo(N, Lo, NewHi); 8291 } 8292 assert(Op0.getOpcode() == ISD::FABS); 8293 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8294 DAG.getConstant(~SignBit, DL, MVT::i32)); 8295 return DCI.CombineTo(N, Lo, NewHi); 8296 } 8297 case RISCVISD::SLLW: 8298 case RISCVISD::SRAW: 8299 case RISCVISD::SRLW: { 8300 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8301 if (SimplifyDemandedLowBitsHelper(0, 32) || 8302 SimplifyDemandedLowBitsHelper(1, 5)) 8303 return SDValue(N, 0); 8304 8305 break; 8306 } 8307 case ISD::ROTR: 8308 case ISD::ROTL: 8309 case RISCVISD::RORW: 8310 case RISCVISD::ROLW: { 8311 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8312 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8313 if (SimplifyDemandedLowBitsHelper(0, 32) || 8314 SimplifyDemandedLowBitsHelper(1, 5)) 8315 return SDValue(N, 0); 8316 } 8317 8318 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8319 } 8320 case RISCVISD::CLZW: 8321 case RISCVISD::CTZW: { 8322 // Only the lower 32 bits of the first operand are read 8323 if (SimplifyDemandedLowBitsHelper(0, 32)) 8324 return SDValue(N, 0); 8325 break; 8326 } 8327 case RISCVISD::GREV: 8328 case RISCVISD::GORC: { 8329 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8330 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8331 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8332 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8333 return SDValue(N, 0); 8334 8335 return combineGREVI_GORCI(N, DAG); 8336 } 8337 case RISCVISD::GREVW: 8338 case RISCVISD::GORCW: { 8339 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8340 if (SimplifyDemandedLowBitsHelper(0, 32) || 8341 SimplifyDemandedLowBitsHelper(1, 5)) 8342 return SDValue(N, 0); 8343 8344 break; 8345 } 8346 case RISCVISD::SHFL: 8347 case RISCVISD::UNSHFL: { 8348 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8349 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8350 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8351 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8352 return SDValue(N, 0); 8353 8354 break; 8355 } 8356 case RISCVISD::SHFLW: 8357 case RISCVISD::UNSHFLW: { 8358 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8359 if (SimplifyDemandedLowBitsHelper(0, 32) || 8360 SimplifyDemandedLowBitsHelper(1, 4)) 8361 return SDValue(N, 0); 8362 8363 break; 8364 } 8365 case RISCVISD::BCOMPRESSW: 8366 case RISCVISD::BDECOMPRESSW: { 8367 // Only the lower 32 bits of LHS and RHS are read. 8368 if (SimplifyDemandedLowBitsHelper(0, 32) || 8369 SimplifyDemandedLowBitsHelper(1, 32)) 8370 return SDValue(N, 0); 8371 8372 break; 8373 } 8374 case RISCVISD::FSR: 8375 case RISCVISD::FSL: 8376 case RISCVISD::FSRW: 8377 case RISCVISD::FSLW: { 8378 bool IsWInstruction = 8379 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8380 unsigned BitWidth = 8381 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8382 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8383 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8384 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8385 return SDValue(N, 0); 8386 8387 break; 8388 } 8389 case RISCVISD::FMV_X_ANYEXTH: 8390 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8391 SDLoc DL(N); 8392 SDValue Op0 = N->getOperand(0); 8393 MVT VT = N->getSimpleValueType(0); 8394 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8395 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8396 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8397 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8398 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8399 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8400 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8401 assert(Op0.getOperand(0).getValueType() == VT && 8402 "Unexpected value type!"); 8403 return Op0.getOperand(0); 8404 } 8405 8406 // This is a target-specific version of a DAGCombine performed in 8407 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8408 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8409 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8410 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8411 !Op0.getNode()->hasOneUse()) 8412 break; 8413 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8414 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8415 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8416 if (Op0.getOpcode() == ISD::FNEG) 8417 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8418 DAG.getConstant(SignBit, DL, VT)); 8419 8420 assert(Op0.getOpcode() == ISD::FABS); 8421 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8422 DAG.getConstant(~SignBit, DL, VT)); 8423 } 8424 case ISD::ADD: 8425 return performADDCombine(N, DAG, Subtarget); 8426 case ISD::SUB: 8427 return performSUBCombine(N, DAG); 8428 case ISD::AND: 8429 return performANDCombine(N, DAG); 8430 case ISD::OR: 8431 return performORCombine(N, DAG, Subtarget); 8432 case ISD::XOR: 8433 return performXORCombine(N, DAG); 8434 case ISD::SIGN_EXTEND_INREG: 8435 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8436 case ISD::ZERO_EXTEND: 8437 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8438 // type legalization. This is safe because fp_to_uint produces poison if 8439 // it overflows. 8440 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8441 SDValue Src = N->getOperand(0); 8442 if (Src.getOpcode() == ISD::FP_TO_UINT && 8443 isTypeLegal(Src.getOperand(0).getValueType())) 8444 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8445 Src.getOperand(0)); 8446 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8447 isTypeLegal(Src.getOperand(1).getValueType())) { 8448 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8449 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8450 Src.getOperand(0), Src.getOperand(1)); 8451 DCI.CombineTo(N, Res); 8452 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8453 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8454 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8455 } 8456 } 8457 return SDValue(); 8458 case RISCVISD::SELECT_CC: { 8459 // Transform 8460 SDValue LHS = N->getOperand(0); 8461 SDValue RHS = N->getOperand(1); 8462 SDValue TrueV = N->getOperand(3); 8463 SDValue FalseV = N->getOperand(4); 8464 8465 // If the True and False values are the same, we don't need a select_cc. 8466 if (TrueV == FalseV) 8467 return TrueV; 8468 8469 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8470 if (!ISD::isIntEqualitySetCC(CCVal)) 8471 break; 8472 8473 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8474 // (select_cc X, Y, lt, trueV, falseV) 8475 // Sometimes the setcc is introduced after select_cc has been formed. 8476 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8477 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8478 // If we're looking for eq 0 instead of ne 0, we need to invert the 8479 // condition. 8480 bool Invert = CCVal == ISD::SETEQ; 8481 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8482 if (Invert) 8483 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8484 8485 SDLoc DL(N); 8486 RHS = LHS.getOperand(1); 8487 LHS = LHS.getOperand(0); 8488 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8489 8490 SDValue TargetCC = DAG.getCondCode(CCVal); 8491 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8492 {LHS, RHS, TargetCC, TrueV, FalseV}); 8493 } 8494 8495 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8496 // (select_cc X, Y, eq/ne, trueV, falseV) 8497 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8498 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8499 {LHS.getOperand(0), LHS.getOperand(1), 8500 N->getOperand(2), TrueV, FalseV}); 8501 // (select_cc X, 1, setne, trueV, falseV) -> 8502 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8503 // This can occur when legalizing some floating point comparisons. 8504 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8505 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8506 SDLoc DL(N); 8507 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8508 SDValue TargetCC = DAG.getCondCode(CCVal); 8509 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8510 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8511 {LHS, RHS, TargetCC, TrueV, FalseV}); 8512 } 8513 8514 break; 8515 } 8516 case RISCVISD::BR_CC: { 8517 SDValue LHS = N->getOperand(1); 8518 SDValue RHS = N->getOperand(2); 8519 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8520 if (!ISD::isIntEqualitySetCC(CCVal)) 8521 break; 8522 8523 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8524 // (br_cc X, Y, lt, dest) 8525 // Sometimes the setcc is introduced after br_cc has been formed. 8526 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8527 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8528 // If we're looking for eq 0 instead of ne 0, we need to invert the 8529 // condition. 8530 bool Invert = CCVal == ISD::SETEQ; 8531 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8532 if (Invert) 8533 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8534 8535 SDLoc DL(N); 8536 RHS = LHS.getOperand(1); 8537 LHS = LHS.getOperand(0); 8538 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8539 8540 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8541 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8542 N->getOperand(4)); 8543 } 8544 8545 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8546 // (br_cc X, Y, eq/ne, trueV, falseV) 8547 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8548 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8549 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8550 N->getOperand(3), N->getOperand(4)); 8551 8552 // (br_cc X, 1, setne, br_cc) -> 8553 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8554 // This can occur when legalizing some floating point comparisons. 8555 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8556 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8557 SDLoc DL(N); 8558 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8559 SDValue TargetCC = DAG.getCondCode(CCVal); 8560 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8561 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8562 N->getOperand(0), LHS, RHS, TargetCC, 8563 N->getOperand(4)); 8564 } 8565 break; 8566 } 8567 case ISD::BITREVERSE: 8568 return performBITREVERSECombine(N, DAG, Subtarget); 8569 case ISD::FP_TO_SINT: 8570 case ISD::FP_TO_UINT: 8571 return performFP_TO_INTCombine(N, DCI, Subtarget); 8572 case ISD::FP_TO_SINT_SAT: 8573 case ISD::FP_TO_UINT_SAT: 8574 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8575 case ISD::FCOPYSIGN: { 8576 EVT VT = N->getValueType(0); 8577 if (!VT.isVector()) 8578 break; 8579 // There is a form of VFSGNJ which injects the negated sign of its second 8580 // operand. Try and bubble any FNEG up after the extend/round to produce 8581 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8582 // TRUNC=1. 8583 SDValue In2 = N->getOperand(1); 8584 // Avoid cases where the extend/round has multiple uses, as duplicating 8585 // those is typically more expensive than removing a fneg. 8586 if (!In2.hasOneUse()) 8587 break; 8588 if (In2.getOpcode() != ISD::FP_EXTEND && 8589 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8590 break; 8591 In2 = In2.getOperand(0); 8592 if (In2.getOpcode() != ISD::FNEG) 8593 break; 8594 SDLoc DL(N); 8595 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8596 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8597 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8598 } 8599 case ISD::MGATHER: 8600 case ISD::MSCATTER: 8601 case ISD::VP_GATHER: 8602 case ISD::VP_SCATTER: { 8603 if (!DCI.isBeforeLegalize()) 8604 break; 8605 SDValue Index, ScaleOp; 8606 bool IsIndexScaled = false; 8607 bool IsIndexSigned = false; 8608 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8609 Index = VPGSN->getIndex(); 8610 ScaleOp = VPGSN->getScale(); 8611 IsIndexScaled = VPGSN->isIndexScaled(); 8612 IsIndexSigned = VPGSN->isIndexSigned(); 8613 } else { 8614 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8615 Index = MGSN->getIndex(); 8616 ScaleOp = MGSN->getScale(); 8617 IsIndexScaled = MGSN->isIndexScaled(); 8618 IsIndexSigned = MGSN->isIndexSigned(); 8619 } 8620 EVT IndexVT = Index.getValueType(); 8621 MVT XLenVT = Subtarget.getXLenVT(); 8622 // RISCV indexed loads only support the "unsigned unscaled" addressing 8623 // mode, so anything else must be manually legalized. 8624 bool NeedsIdxLegalization = 8625 IsIndexScaled || 8626 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8627 if (!NeedsIdxLegalization) 8628 break; 8629 8630 SDLoc DL(N); 8631 8632 // Any index legalization should first promote to XLenVT, so we don't lose 8633 // bits when scaling. This may create an illegal index type so we let 8634 // LLVM's legalization take care of the splitting. 8635 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8636 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8637 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8638 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8639 DL, IndexVT, Index); 8640 } 8641 8642 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8643 if (IsIndexScaled && Scale != 1) { 8644 // Manually scale the indices by the element size. 8645 // TODO: Sanitize the scale operand here? 8646 // TODO: For VP nodes, should we use VP_SHL here? 8647 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8648 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8649 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8650 } 8651 8652 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8653 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8654 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8655 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8656 VPGN->getScale(), VPGN->getMask(), 8657 VPGN->getVectorLength()}, 8658 VPGN->getMemOperand(), NewIndexTy); 8659 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8660 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8661 {VPSN->getChain(), VPSN->getValue(), 8662 VPSN->getBasePtr(), Index, VPSN->getScale(), 8663 VPSN->getMask(), VPSN->getVectorLength()}, 8664 VPSN->getMemOperand(), NewIndexTy); 8665 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8666 return DAG.getMaskedGather( 8667 N->getVTList(), MGN->getMemoryVT(), DL, 8668 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8669 MGN->getBasePtr(), Index, MGN->getScale()}, 8670 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8671 const auto *MSN = cast<MaskedScatterSDNode>(N); 8672 return DAG.getMaskedScatter( 8673 N->getVTList(), MSN->getMemoryVT(), DL, 8674 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8675 Index, MSN->getScale()}, 8676 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8677 } 8678 case RISCVISD::SRA_VL: 8679 case RISCVISD::SRL_VL: 8680 case RISCVISD::SHL_VL: { 8681 SDValue ShAmt = N->getOperand(1); 8682 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8683 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8684 SDLoc DL(N); 8685 SDValue VL = N->getOperand(3); 8686 EVT VT = N->getValueType(0); 8687 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8688 ShAmt.getOperand(1), VL); 8689 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8690 N->getOperand(2), N->getOperand(3)); 8691 } 8692 break; 8693 } 8694 case ISD::SRA: 8695 case ISD::SRL: 8696 case ISD::SHL: { 8697 SDValue ShAmt = N->getOperand(1); 8698 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8699 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8700 SDLoc DL(N); 8701 EVT VT = N->getValueType(0); 8702 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8703 ShAmt.getOperand(1), 8704 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8705 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8706 } 8707 break; 8708 } 8709 case RISCVISD::ADD_VL: 8710 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8711 return V; 8712 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8713 case RISCVISD::SUB_VL: 8714 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8715 case RISCVISD::VWADD_W_VL: 8716 case RISCVISD::VWADDU_W_VL: 8717 case RISCVISD::VWSUB_W_VL: 8718 case RISCVISD::VWSUBU_W_VL: 8719 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8720 case RISCVISD::MUL_VL: 8721 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8722 return V; 8723 // Mul is commutative. 8724 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8725 case ISD::STORE: { 8726 auto *Store = cast<StoreSDNode>(N); 8727 SDValue Val = Store->getValue(); 8728 // Combine store of vmv.x.s to vse with VL of 1. 8729 // FIXME: Support FP. 8730 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8731 SDValue Src = Val.getOperand(0); 8732 EVT VecVT = Src.getValueType(); 8733 EVT MemVT = Store->getMemoryVT(); 8734 // The memory VT and the element type must match. 8735 if (VecVT.getVectorElementType() == MemVT) { 8736 SDLoc DL(N); 8737 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8738 return DAG.getStoreVP( 8739 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8740 DAG.getConstant(1, DL, MaskVT), 8741 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8742 Store->getMemOperand(), Store->getAddressingMode(), 8743 Store->isTruncatingStore(), /*IsCompress*/ false); 8744 } 8745 } 8746 8747 break; 8748 } 8749 case ISD::SPLAT_VECTOR: { 8750 EVT VT = N->getValueType(0); 8751 // Only perform this combine on legal MVT types. 8752 if (!isTypeLegal(VT)) 8753 break; 8754 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8755 DAG, Subtarget)) 8756 return Gather; 8757 break; 8758 } 8759 case RISCVISD::VMV_V_X_VL: { 8760 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8761 // scalar input. 8762 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8763 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8764 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8765 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8766 return SDValue(N, 0); 8767 8768 break; 8769 } 8770 case ISD::INTRINSIC_WO_CHAIN: { 8771 unsigned IntNo = N->getConstantOperandVal(0); 8772 switch (IntNo) { 8773 // By default we do not combine any intrinsic. 8774 default: 8775 return SDValue(); 8776 case Intrinsic::riscv_vcpop: 8777 case Intrinsic::riscv_vcpop_mask: 8778 case Intrinsic::riscv_vfirst: 8779 case Intrinsic::riscv_vfirst_mask: { 8780 SDValue VL = N->getOperand(2); 8781 if (IntNo == Intrinsic::riscv_vcpop_mask || 8782 IntNo == Intrinsic::riscv_vfirst_mask) 8783 VL = N->getOperand(3); 8784 if (!isNullConstant(VL)) 8785 return SDValue(); 8786 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8787 SDLoc DL(N); 8788 EVT VT = N->getValueType(0); 8789 if (IntNo == Intrinsic::riscv_vfirst || 8790 IntNo == Intrinsic::riscv_vfirst_mask) 8791 return DAG.getConstant(-1, DL, VT); 8792 return DAG.getConstant(0, DL, VT); 8793 } 8794 } 8795 } 8796 } 8797 8798 return SDValue(); 8799 } 8800 8801 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8802 const SDNode *N, CombineLevel Level) const { 8803 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8804 // materialised in fewer instructions than `(OP _, c1)`: 8805 // 8806 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8807 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8808 SDValue N0 = N->getOperand(0); 8809 EVT Ty = N0.getValueType(); 8810 if (Ty.isScalarInteger() && 8811 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8812 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8813 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8814 if (C1 && C2) { 8815 const APInt &C1Int = C1->getAPIntValue(); 8816 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8817 8818 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8819 // and the combine should happen, to potentially allow further combines 8820 // later. 8821 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8822 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8823 return true; 8824 8825 // We can materialise `c1` in an add immediate, so it's "free", and the 8826 // combine should be prevented. 8827 if (C1Int.getMinSignedBits() <= 64 && 8828 isLegalAddImmediate(C1Int.getSExtValue())) 8829 return false; 8830 8831 // Neither constant will fit into an immediate, so find materialisation 8832 // costs. 8833 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8834 Subtarget.getFeatureBits(), 8835 /*CompressionCost*/true); 8836 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8837 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8838 /*CompressionCost*/true); 8839 8840 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8841 // combine should be prevented. 8842 if (C1Cost < ShiftedC1Cost) 8843 return false; 8844 } 8845 } 8846 return true; 8847 } 8848 8849 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8850 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8851 TargetLoweringOpt &TLO) const { 8852 // Delay this optimization as late as possible. 8853 if (!TLO.LegalOps) 8854 return false; 8855 8856 EVT VT = Op.getValueType(); 8857 if (VT.isVector()) 8858 return false; 8859 8860 // Only handle AND for now. 8861 if (Op.getOpcode() != ISD::AND) 8862 return false; 8863 8864 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8865 if (!C) 8866 return false; 8867 8868 const APInt &Mask = C->getAPIntValue(); 8869 8870 // Clear all non-demanded bits initially. 8871 APInt ShrunkMask = Mask & DemandedBits; 8872 8873 // Try to make a smaller immediate by setting undemanded bits. 8874 8875 APInt ExpandedMask = Mask | ~DemandedBits; 8876 8877 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8878 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8879 }; 8880 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8881 if (NewMask == Mask) 8882 return true; 8883 SDLoc DL(Op); 8884 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8885 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8886 return TLO.CombineTo(Op, NewOp); 8887 }; 8888 8889 // If the shrunk mask fits in sign extended 12 bits, let the target 8890 // independent code apply it. 8891 if (ShrunkMask.isSignedIntN(12)) 8892 return false; 8893 8894 // Preserve (and X, 0xffff) when zext.h is supported. 8895 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8896 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8897 if (IsLegalMask(NewMask)) 8898 return UseMask(NewMask); 8899 } 8900 8901 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8902 if (VT == MVT::i64) { 8903 APInt NewMask = APInt(64, 0xffffffff); 8904 if (IsLegalMask(NewMask)) 8905 return UseMask(NewMask); 8906 } 8907 8908 // For the remaining optimizations, we need to be able to make a negative 8909 // number through a combination of mask and undemanded bits. 8910 if (!ExpandedMask.isNegative()) 8911 return false; 8912 8913 // What is the fewest number of bits we need to represent the negative number. 8914 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8915 8916 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8917 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8918 APInt NewMask = ShrunkMask; 8919 if (MinSignedBits <= 12) 8920 NewMask.setBitsFrom(11); 8921 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8922 NewMask.setBitsFrom(31); 8923 else 8924 return false; 8925 8926 // Check that our new mask is a subset of the demanded mask. 8927 assert(IsLegalMask(NewMask)); 8928 return UseMask(NewMask); 8929 } 8930 8931 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 8932 static const uint64_t GREVMasks[] = { 8933 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 8934 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 8935 8936 for (unsigned Stage = 0; Stage != 6; ++Stage) { 8937 unsigned Shift = 1 << Stage; 8938 if (ShAmt & Shift) { 8939 uint64_t Mask = GREVMasks[Stage]; 8940 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 8941 if (IsGORC) 8942 Res |= x; 8943 x = Res; 8944 } 8945 } 8946 8947 return x; 8948 } 8949 8950 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8951 KnownBits &Known, 8952 const APInt &DemandedElts, 8953 const SelectionDAG &DAG, 8954 unsigned Depth) const { 8955 unsigned BitWidth = Known.getBitWidth(); 8956 unsigned Opc = Op.getOpcode(); 8957 assert((Opc >= ISD::BUILTIN_OP_END || 8958 Opc == ISD::INTRINSIC_WO_CHAIN || 8959 Opc == ISD::INTRINSIC_W_CHAIN || 8960 Opc == ISD::INTRINSIC_VOID) && 8961 "Should use MaskedValueIsZero if you don't know whether Op" 8962 " is a target node!"); 8963 8964 Known.resetAll(); 8965 switch (Opc) { 8966 default: break; 8967 case RISCVISD::SELECT_CC: { 8968 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8969 // If we don't know any bits, early out. 8970 if (Known.isUnknown()) 8971 break; 8972 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8973 8974 // Only known if known in both the LHS and RHS. 8975 Known = KnownBits::commonBits(Known, Known2); 8976 break; 8977 } 8978 case RISCVISD::REMUW: { 8979 KnownBits Known2; 8980 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8981 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8982 // We only care about the lower 32 bits. 8983 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8984 // Restore the original width by sign extending. 8985 Known = Known.sext(BitWidth); 8986 break; 8987 } 8988 case RISCVISD::DIVUW: { 8989 KnownBits Known2; 8990 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8991 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8992 // We only care about the lower 32 bits. 8993 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8994 // Restore the original width by sign extending. 8995 Known = Known.sext(BitWidth); 8996 break; 8997 } 8998 case RISCVISD::CTZW: { 8999 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9000 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9001 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9002 Known.Zero.setBitsFrom(LowBits); 9003 break; 9004 } 9005 case RISCVISD::CLZW: { 9006 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9007 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9008 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9009 Known.Zero.setBitsFrom(LowBits); 9010 break; 9011 } 9012 case RISCVISD::GREV: 9013 case RISCVISD::GORC: { 9014 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9015 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9016 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9017 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9018 // To compute zeros, we need to invert the value and invert it back after. 9019 Known.Zero = 9020 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9021 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9022 } 9023 break; 9024 } 9025 case RISCVISD::READ_VLENB: { 9026 // If we know the minimum VLen from Zvl extensions, we can use that to 9027 // determine the trailing zeros of VLENB. 9028 // FIXME: Limit to 128 bit vectors until we have more testing. 9029 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 9030 if (MinVLenB > 0) 9031 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9032 // We assume VLENB is no more than 65536 / 8 bytes. 9033 Known.Zero.setBitsFrom(14); 9034 break; 9035 } 9036 case ISD::INTRINSIC_W_CHAIN: 9037 case ISD::INTRINSIC_WO_CHAIN: { 9038 unsigned IntNo = 9039 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9040 switch (IntNo) { 9041 default: 9042 // We can't do anything for most intrinsics. 9043 break; 9044 case Intrinsic::riscv_vsetvli: 9045 case Intrinsic::riscv_vsetvlimax: 9046 case Intrinsic::riscv_vsetvli_opt: 9047 case Intrinsic::riscv_vsetvlimax_opt: 9048 // Assume that VL output is positive and would fit in an int32_t. 9049 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9050 if (BitWidth >= 32) 9051 Known.Zero.setBitsFrom(31); 9052 break; 9053 } 9054 break; 9055 } 9056 } 9057 } 9058 9059 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9060 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9061 unsigned Depth) const { 9062 switch (Op.getOpcode()) { 9063 default: 9064 break; 9065 case RISCVISD::SELECT_CC: { 9066 unsigned Tmp = 9067 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9068 if (Tmp == 1) return 1; // Early out. 9069 unsigned Tmp2 = 9070 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9071 return std::min(Tmp, Tmp2); 9072 } 9073 case RISCVISD::SLLW: 9074 case RISCVISD::SRAW: 9075 case RISCVISD::SRLW: 9076 case RISCVISD::DIVW: 9077 case RISCVISD::DIVUW: 9078 case RISCVISD::REMUW: 9079 case RISCVISD::ROLW: 9080 case RISCVISD::RORW: 9081 case RISCVISD::GREVW: 9082 case RISCVISD::GORCW: 9083 case RISCVISD::FSLW: 9084 case RISCVISD::FSRW: 9085 case RISCVISD::SHFLW: 9086 case RISCVISD::UNSHFLW: 9087 case RISCVISD::BCOMPRESSW: 9088 case RISCVISD::BDECOMPRESSW: 9089 case RISCVISD::BFPW: 9090 case RISCVISD::FCVT_W_RV64: 9091 case RISCVISD::FCVT_WU_RV64: 9092 case RISCVISD::STRICT_FCVT_W_RV64: 9093 case RISCVISD::STRICT_FCVT_WU_RV64: 9094 // TODO: As the result is sign-extended, this is conservatively correct. A 9095 // more precise answer could be calculated for SRAW depending on known 9096 // bits in the shift amount. 9097 return 33; 9098 case RISCVISD::SHFL: 9099 case RISCVISD::UNSHFL: { 9100 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9101 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9102 // will stay within the upper 32 bits. If there were more than 32 sign bits 9103 // before there will be at least 33 sign bits after. 9104 if (Op.getValueType() == MVT::i64 && 9105 isa<ConstantSDNode>(Op.getOperand(1)) && 9106 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9107 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9108 if (Tmp > 32) 9109 return 33; 9110 } 9111 break; 9112 } 9113 case RISCVISD::VMV_X_S: { 9114 // The number of sign bits of the scalar result is computed by obtaining the 9115 // element type of the input vector operand, subtracting its width from the 9116 // XLEN, and then adding one (sign bit within the element type). If the 9117 // element type is wider than XLen, the least-significant XLEN bits are 9118 // taken. 9119 unsigned XLen = Subtarget.getXLen(); 9120 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9121 if (EltBits <= XLen) 9122 return XLen - EltBits + 1; 9123 break; 9124 } 9125 } 9126 9127 return 1; 9128 } 9129 9130 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9131 MachineBasicBlock *BB) { 9132 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9133 9134 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9135 // Should the count have wrapped while it was being read, we need to try 9136 // again. 9137 // ... 9138 // read: 9139 // rdcycleh x3 # load high word of cycle 9140 // rdcycle x2 # load low word of cycle 9141 // rdcycleh x4 # load high word of cycle 9142 // bne x3, x4, read # check if high word reads match, otherwise try again 9143 // ... 9144 9145 MachineFunction &MF = *BB->getParent(); 9146 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9147 MachineFunction::iterator It = ++BB->getIterator(); 9148 9149 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9150 MF.insert(It, LoopMBB); 9151 9152 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9153 MF.insert(It, DoneMBB); 9154 9155 // Transfer the remainder of BB and its successor edges to DoneMBB. 9156 DoneMBB->splice(DoneMBB->begin(), BB, 9157 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9158 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9159 9160 BB->addSuccessor(LoopMBB); 9161 9162 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9163 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9164 Register LoReg = MI.getOperand(0).getReg(); 9165 Register HiReg = MI.getOperand(1).getReg(); 9166 DebugLoc DL = MI.getDebugLoc(); 9167 9168 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9169 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9170 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9171 .addReg(RISCV::X0); 9172 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9173 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9174 .addReg(RISCV::X0); 9175 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9176 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9177 .addReg(RISCV::X0); 9178 9179 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9180 .addReg(HiReg) 9181 .addReg(ReadAgainReg) 9182 .addMBB(LoopMBB); 9183 9184 LoopMBB->addSuccessor(LoopMBB); 9185 LoopMBB->addSuccessor(DoneMBB); 9186 9187 MI.eraseFromParent(); 9188 9189 return DoneMBB; 9190 } 9191 9192 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9193 MachineBasicBlock *BB) { 9194 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9195 9196 MachineFunction &MF = *BB->getParent(); 9197 DebugLoc DL = MI.getDebugLoc(); 9198 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9199 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9200 Register LoReg = MI.getOperand(0).getReg(); 9201 Register HiReg = MI.getOperand(1).getReg(); 9202 Register SrcReg = MI.getOperand(2).getReg(); 9203 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9204 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9205 9206 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9207 RI); 9208 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9209 MachineMemOperand *MMOLo = 9210 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9211 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9212 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9213 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9214 .addFrameIndex(FI) 9215 .addImm(0) 9216 .addMemOperand(MMOLo); 9217 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9218 .addFrameIndex(FI) 9219 .addImm(4) 9220 .addMemOperand(MMOHi); 9221 MI.eraseFromParent(); // The pseudo instruction is gone now. 9222 return BB; 9223 } 9224 9225 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9226 MachineBasicBlock *BB) { 9227 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9228 "Unexpected instruction"); 9229 9230 MachineFunction &MF = *BB->getParent(); 9231 DebugLoc DL = MI.getDebugLoc(); 9232 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9233 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9234 Register DstReg = MI.getOperand(0).getReg(); 9235 Register LoReg = MI.getOperand(1).getReg(); 9236 Register HiReg = MI.getOperand(2).getReg(); 9237 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9238 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9239 9240 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9241 MachineMemOperand *MMOLo = 9242 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9243 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9244 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9245 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9246 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9247 .addFrameIndex(FI) 9248 .addImm(0) 9249 .addMemOperand(MMOLo); 9250 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9251 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9252 .addFrameIndex(FI) 9253 .addImm(4) 9254 .addMemOperand(MMOHi); 9255 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9256 MI.eraseFromParent(); // The pseudo instruction is gone now. 9257 return BB; 9258 } 9259 9260 static bool isSelectPseudo(MachineInstr &MI) { 9261 switch (MI.getOpcode()) { 9262 default: 9263 return false; 9264 case RISCV::Select_GPR_Using_CC_GPR: 9265 case RISCV::Select_FPR16_Using_CC_GPR: 9266 case RISCV::Select_FPR32_Using_CC_GPR: 9267 case RISCV::Select_FPR64_Using_CC_GPR: 9268 return true; 9269 } 9270 } 9271 9272 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9273 unsigned RelOpcode, unsigned EqOpcode, 9274 const RISCVSubtarget &Subtarget) { 9275 DebugLoc DL = MI.getDebugLoc(); 9276 Register DstReg = MI.getOperand(0).getReg(); 9277 Register Src1Reg = MI.getOperand(1).getReg(); 9278 Register Src2Reg = MI.getOperand(2).getReg(); 9279 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9280 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9281 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9282 9283 // Save the current FFLAGS. 9284 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9285 9286 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9287 .addReg(Src1Reg) 9288 .addReg(Src2Reg); 9289 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9290 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9291 9292 // Restore the FFLAGS. 9293 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9294 .addReg(SavedFFlags, RegState::Kill); 9295 9296 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9297 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9298 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9299 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9300 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9301 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9302 9303 // Erase the pseudoinstruction. 9304 MI.eraseFromParent(); 9305 return BB; 9306 } 9307 9308 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9309 MachineBasicBlock *BB, 9310 const RISCVSubtarget &Subtarget) { 9311 // To "insert" Select_* instructions, we actually have to insert the triangle 9312 // control-flow pattern. The incoming instructions know the destination vreg 9313 // to set, the condition code register to branch on, the true/false values to 9314 // select between, and the condcode to use to select the appropriate branch. 9315 // 9316 // We produce the following control flow: 9317 // HeadMBB 9318 // | \ 9319 // | IfFalseMBB 9320 // | / 9321 // TailMBB 9322 // 9323 // When we find a sequence of selects we attempt to optimize their emission 9324 // by sharing the control flow. Currently we only handle cases where we have 9325 // multiple selects with the exact same condition (same LHS, RHS and CC). 9326 // The selects may be interleaved with other instructions if the other 9327 // instructions meet some requirements we deem safe: 9328 // - They are debug instructions. Otherwise, 9329 // - They do not have side-effects, do not access memory and their inputs do 9330 // not depend on the results of the select pseudo-instructions. 9331 // The TrueV/FalseV operands of the selects cannot depend on the result of 9332 // previous selects in the sequence. 9333 // These conditions could be further relaxed. See the X86 target for a 9334 // related approach and more information. 9335 Register LHS = MI.getOperand(1).getReg(); 9336 Register RHS = MI.getOperand(2).getReg(); 9337 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9338 9339 SmallVector<MachineInstr *, 4> SelectDebugValues; 9340 SmallSet<Register, 4> SelectDests; 9341 SelectDests.insert(MI.getOperand(0).getReg()); 9342 9343 MachineInstr *LastSelectPseudo = &MI; 9344 9345 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9346 SequenceMBBI != E; ++SequenceMBBI) { 9347 if (SequenceMBBI->isDebugInstr()) 9348 continue; 9349 else if (isSelectPseudo(*SequenceMBBI)) { 9350 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9351 SequenceMBBI->getOperand(2).getReg() != RHS || 9352 SequenceMBBI->getOperand(3).getImm() != CC || 9353 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9354 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9355 break; 9356 LastSelectPseudo = &*SequenceMBBI; 9357 SequenceMBBI->collectDebugValues(SelectDebugValues); 9358 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9359 } else { 9360 if (SequenceMBBI->hasUnmodeledSideEffects() || 9361 SequenceMBBI->mayLoadOrStore()) 9362 break; 9363 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9364 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9365 })) 9366 break; 9367 } 9368 } 9369 9370 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9371 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9372 DebugLoc DL = MI.getDebugLoc(); 9373 MachineFunction::iterator I = ++BB->getIterator(); 9374 9375 MachineBasicBlock *HeadMBB = BB; 9376 MachineFunction *F = BB->getParent(); 9377 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9378 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9379 9380 F->insert(I, IfFalseMBB); 9381 F->insert(I, TailMBB); 9382 9383 // Transfer debug instructions associated with the selects to TailMBB. 9384 for (MachineInstr *DebugInstr : SelectDebugValues) { 9385 TailMBB->push_back(DebugInstr->removeFromParent()); 9386 } 9387 9388 // Move all instructions after the sequence to TailMBB. 9389 TailMBB->splice(TailMBB->end(), HeadMBB, 9390 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9391 // Update machine-CFG edges by transferring all successors of the current 9392 // block to the new block which will contain the Phi nodes for the selects. 9393 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9394 // Set the successors for HeadMBB. 9395 HeadMBB->addSuccessor(IfFalseMBB); 9396 HeadMBB->addSuccessor(TailMBB); 9397 9398 // Insert appropriate branch. 9399 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9400 .addReg(LHS) 9401 .addReg(RHS) 9402 .addMBB(TailMBB); 9403 9404 // IfFalseMBB just falls through to TailMBB. 9405 IfFalseMBB->addSuccessor(TailMBB); 9406 9407 // Create PHIs for all of the select pseudo-instructions. 9408 auto SelectMBBI = MI.getIterator(); 9409 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9410 auto InsertionPoint = TailMBB->begin(); 9411 while (SelectMBBI != SelectEnd) { 9412 auto Next = std::next(SelectMBBI); 9413 if (isSelectPseudo(*SelectMBBI)) { 9414 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9415 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9416 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9417 .addReg(SelectMBBI->getOperand(4).getReg()) 9418 .addMBB(HeadMBB) 9419 .addReg(SelectMBBI->getOperand(5).getReg()) 9420 .addMBB(IfFalseMBB); 9421 SelectMBBI->eraseFromParent(); 9422 } 9423 SelectMBBI = Next; 9424 } 9425 9426 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9427 return TailMBB; 9428 } 9429 9430 MachineBasicBlock * 9431 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9432 MachineBasicBlock *BB) const { 9433 switch (MI.getOpcode()) { 9434 default: 9435 llvm_unreachable("Unexpected instr type to insert"); 9436 case RISCV::ReadCycleWide: 9437 assert(!Subtarget.is64Bit() && 9438 "ReadCycleWrite is only to be used on riscv32"); 9439 return emitReadCycleWidePseudo(MI, BB); 9440 case RISCV::Select_GPR_Using_CC_GPR: 9441 case RISCV::Select_FPR16_Using_CC_GPR: 9442 case RISCV::Select_FPR32_Using_CC_GPR: 9443 case RISCV::Select_FPR64_Using_CC_GPR: 9444 return emitSelectPseudo(MI, BB, Subtarget); 9445 case RISCV::BuildPairF64Pseudo: 9446 return emitBuildPairF64Pseudo(MI, BB); 9447 case RISCV::SplitF64Pseudo: 9448 return emitSplitF64Pseudo(MI, BB); 9449 case RISCV::PseudoQuietFLE_H: 9450 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9451 case RISCV::PseudoQuietFLT_H: 9452 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9453 case RISCV::PseudoQuietFLE_S: 9454 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9455 case RISCV::PseudoQuietFLT_S: 9456 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9457 case RISCV::PseudoQuietFLE_D: 9458 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9459 case RISCV::PseudoQuietFLT_D: 9460 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9461 } 9462 } 9463 9464 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9465 SDNode *Node) const { 9466 // Add FRM dependency to any instructions with dynamic rounding mode. 9467 unsigned Opc = MI.getOpcode(); 9468 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9469 if (Idx < 0) 9470 return; 9471 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9472 return; 9473 // If the instruction already reads FRM, don't add another read. 9474 if (MI.readsRegister(RISCV::FRM)) 9475 return; 9476 MI.addOperand( 9477 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9478 } 9479 9480 // Calling Convention Implementation. 9481 // The expectations for frontend ABI lowering vary from target to target. 9482 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9483 // details, but this is a longer term goal. For now, we simply try to keep the 9484 // role of the frontend as simple and well-defined as possible. The rules can 9485 // be summarised as: 9486 // * Never split up large scalar arguments. We handle them here. 9487 // * If a hardfloat calling convention is being used, and the struct may be 9488 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9489 // available, then pass as two separate arguments. If either the GPRs or FPRs 9490 // are exhausted, then pass according to the rule below. 9491 // * If a struct could never be passed in registers or directly in a stack 9492 // slot (as it is larger than 2*XLEN and the floating point rules don't 9493 // apply), then pass it using a pointer with the byval attribute. 9494 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9495 // word-sized array or a 2*XLEN scalar (depending on alignment). 9496 // * The frontend can determine whether a struct is returned by reference or 9497 // not based on its size and fields. If it will be returned by reference, the 9498 // frontend must modify the prototype so a pointer with the sret annotation is 9499 // passed as the first argument. This is not necessary for large scalar 9500 // returns. 9501 // * Struct return values and varargs should be coerced to structs containing 9502 // register-size fields in the same situations they would be for fixed 9503 // arguments. 9504 9505 static const MCPhysReg ArgGPRs[] = { 9506 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9507 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9508 }; 9509 static const MCPhysReg ArgFPR16s[] = { 9510 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9511 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9512 }; 9513 static const MCPhysReg ArgFPR32s[] = { 9514 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9515 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9516 }; 9517 static const MCPhysReg ArgFPR64s[] = { 9518 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9519 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9520 }; 9521 // This is an interim calling convention and it may be changed in the future. 9522 static const MCPhysReg ArgVRs[] = { 9523 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9524 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9525 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9526 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9527 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9528 RISCV::V20M2, RISCV::V22M2}; 9529 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9530 RISCV::V20M4}; 9531 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9532 9533 // Pass a 2*XLEN argument that has been split into two XLEN values through 9534 // registers or the stack as necessary. 9535 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9536 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9537 MVT ValVT2, MVT LocVT2, 9538 ISD::ArgFlagsTy ArgFlags2) { 9539 unsigned XLenInBytes = XLen / 8; 9540 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9541 // At least one half can be passed via register. 9542 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9543 VA1.getLocVT(), CCValAssign::Full)); 9544 } else { 9545 // Both halves must be passed on the stack, with proper alignment. 9546 Align StackAlign = 9547 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9548 State.addLoc( 9549 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9550 State.AllocateStack(XLenInBytes, StackAlign), 9551 VA1.getLocVT(), CCValAssign::Full)); 9552 State.addLoc(CCValAssign::getMem( 9553 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9554 LocVT2, CCValAssign::Full)); 9555 return false; 9556 } 9557 9558 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9559 // The second half can also be passed via register. 9560 State.addLoc( 9561 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9562 } else { 9563 // The second half is passed via the stack, without additional alignment. 9564 State.addLoc(CCValAssign::getMem( 9565 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9566 LocVT2, CCValAssign::Full)); 9567 } 9568 9569 return false; 9570 } 9571 9572 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9573 Optional<unsigned> FirstMaskArgument, 9574 CCState &State, const RISCVTargetLowering &TLI) { 9575 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9576 if (RC == &RISCV::VRRegClass) { 9577 // Assign the first mask argument to V0. 9578 // This is an interim calling convention and it may be changed in the 9579 // future. 9580 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9581 return State.AllocateReg(RISCV::V0); 9582 return State.AllocateReg(ArgVRs); 9583 } 9584 if (RC == &RISCV::VRM2RegClass) 9585 return State.AllocateReg(ArgVRM2s); 9586 if (RC == &RISCV::VRM4RegClass) 9587 return State.AllocateReg(ArgVRM4s); 9588 if (RC == &RISCV::VRM8RegClass) 9589 return State.AllocateReg(ArgVRM8s); 9590 llvm_unreachable("Unhandled register class for ValueType"); 9591 } 9592 9593 // Implements the RISC-V calling convention. Returns true upon failure. 9594 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9595 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9596 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9597 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9598 Optional<unsigned> FirstMaskArgument) { 9599 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9600 assert(XLen == 32 || XLen == 64); 9601 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9602 9603 // Any return value split in to more than two values can't be returned 9604 // directly. Vectors are returned via the available vector registers. 9605 if (!LocVT.isVector() && IsRet && ValNo > 1) 9606 return true; 9607 9608 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9609 // variadic argument, or if no F16/F32 argument registers are available. 9610 bool UseGPRForF16_F32 = true; 9611 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9612 // variadic argument, or if no F64 argument registers are available. 9613 bool UseGPRForF64 = true; 9614 9615 switch (ABI) { 9616 default: 9617 llvm_unreachable("Unexpected ABI"); 9618 case RISCVABI::ABI_ILP32: 9619 case RISCVABI::ABI_LP64: 9620 break; 9621 case RISCVABI::ABI_ILP32F: 9622 case RISCVABI::ABI_LP64F: 9623 UseGPRForF16_F32 = !IsFixed; 9624 break; 9625 case RISCVABI::ABI_ILP32D: 9626 case RISCVABI::ABI_LP64D: 9627 UseGPRForF16_F32 = !IsFixed; 9628 UseGPRForF64 = !IsFixed; 9629 break; 9630 } 9631 9632 // FPR16, FPR32, and FPR64 alias each other. 9633 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9634 UseGPRForF16_F32 = true; 9635 UseGPRForF64 = true; 9636 } 9637 9638 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9639 // similar local variables rather than directly checking against the target 9640 // ABI. 9641 9642 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9643 LocVT = XLenVT; 9644 LocInfo = CCValAssign::BCvt; 9645 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9646 LocVT = MVT::i64; 9647 LocInfo = CCValAssign::BCvt; 9648 } 9649 9650 // If this is a variadic argument, the RISC-V calling convention requires 9651 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9652 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9653 // be used regardless of whether the original argument was split during 9654 // legalisation or not. The argument will not be passed by registers if the 9655 // original type is larger than 2*XLEN, so the register alignment rule does 9656 // not apply. 9657 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9658 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9659 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9660 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9661 // Skip 'odd' register if necessary. 9662 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9663 State.AllocateReg(ArgGPRs); 9664 } 9665 9666 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9667 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9668 State.getPendingArgFlags(); 9669 9670 assert(PendingLocs.size() == PendingArgFlags.size() && 9671 "PendingLocs and PendingArgFlags out of sync"); 9672 9673 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9674 // registers are exhausted. 9675 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9676 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9677 "Can't lower f64 if it is split"); 9678 // Depending on available argument GPRS, f64 may be passed in a pair of 9679 // GPRs, split between a GPR and the stack, or passed completely on the 9680 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9681 // cases. 9682 Register Reg = State.AllocateReg(ArgGPRs); 9683 LocVT = MVT::i32; 9684 if (!Reg) { 9685 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9686 State.addLoc( 9687 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9688 return false; 9689 } 9690 if (!State.AllocateReg(ArgGPRs)) 9691 State.AllocateStack(4, Align(4)); 9692 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9693 return false; 9694 } 9695 9696 // Fixed-length vectors are located in the corresponding scalable-vector 9697 // container types. 9698 if (ValVT.isFixedLengthVector()) 9699 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9700 9701 // Split arguments might be passed indirectly, so keep track of the pending 9702 // values. Split vectors are passed via a mix of registers and indirectly, so 9703 // treat them as we would any other argument. 9704 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9705 LocVT = XLenVT; 9706 LocInfo = CCValAssign::Indirect; 9707 PendingLocs.push_back( 9708 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9709 PendingArgFlags.push_back(ArgFlags); 9710 if (!ArgFlags.isSplitEnd()) { 9711 return false; 9712 } 9713 } 9714 9715 // If the split argument only had two elements, it should be passed directly 9716 // in registers or on the stack. 9717 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9718 PendingLocs.size() <= 2) { 9719 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9720 // Apply the normal calling convention rules to the first half of the 9721 // split argument. 9722 CCValAssign VA = PendingLocs[0]; 9723 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9724 PendingLocs.clear(); 9725 PendingArgFlags.clear(); 9726 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9727 ArgFlags); 9728 } 9729 9730 // Allocate to a register if possible, or else a stack slot. 9731 Register Reg; 9732 unsigned StoreSizeBytes = XLen / 8; 9733 Align StackAlign = Align(XLen / 8); 9734 9735 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9736 Reg = State.AllocateReg(ArgFPR16s); 9737 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9738 Reg = State.AllocateReg(ArgFPR32s); 9739 else if (ValVT == MVT::f64 && !UseGPRForF64) 9740 Reg = State.AllocateReg(ArgFPR64s); 9741 else if (ValVT.isVector()) { 9742 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9743 if (!Reg) { 9744 // For return values, the vector must be passed fully via registers or 9745 // via the stack. 9746 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9747 // but we're using all of them. 9748 if (IsRet) 9749 return true; 9750 // Try using a GPR to pass the address 9751 if ((Reg = State.AllocateReg(ArgGPRs))) { 9752 LocVT = XLenVT; 9753 LocInfo = CCValAssign::Indirect; 9754 } else if (ValVT.isScalableVector()) { 9755 LocVT = XLenVT; 9756 LocInfo = CCValAssign::Indirect; 9757 } else { 9758 // Pass fixed-length vectors on the stack. 9759 LocVT = ValVT; 9760 StoreSizeBytes = ValVT.getStoreSize(); 9761 // Align vectors to their element sizes, being careful for vXi1 9762 // vectors. 9763 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9764 } 9765 } 9766 } else { 9767 Reg = State.AllocateReg(ArgGPRs); 9768 } 9769 9770 unsigned StackOffset = 9771 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9772 9773 // If we reach this point and PendingLocs is non-empty, we must be at the 9774 // end of a split argument that must be passed indirectly. 9775 if (!PendingLocs.empty()) { 9776 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9777 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9778 9779 for (auto &It : PendingLocs) { 9780 if (Reg) 9781 It.convertToReg(Reg); 9782 else 9783 It.convertToMem(StackOffset); 9784 State.addLoc(It); 9785 } 9786 PendingLocs.clear(); 9787 PendingArgFlags.clear(); 9788 return false; 9789 } 9790 9791 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9792 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9793 "Expected an XLenVT or vector types at this stage"); 9794 9795 if (Reg) { 9796 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9797 return false; 9798 } 9799 9800 // When a floating-point value is passed on the stack, no bit-conversion is 9801 // needed. 9802 if (ValVT.isFloatingPoint()) { 9803 LocVT = ValVT; 9804 LocInfo = CCValAssign::Full; 9805 } 9806 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9807 return false; 9808 } 9809 9810 template <typename ArgTy> 9811 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9812 for (const auto &ArgIdx : enumerate(Args)) { 9813 MVT ArgVT = ArgIdx.value().VT; 9814 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9815 return ArgIdx.index(); 9816 } 9817 return None; 9818 } 9819 9820 void RISCVTargetLowering::analyzeInputArgs( 9821 MachineFunction &MF, CCState &CCInfo, 9822 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9823 RISCVCCAssignFn Fn) const { 9824 unsigned NumArgs = Ins.size(); 9825 FunctionType *FType = MF.getFunction().getFunctionType(); 9826 9827 Optional<unsigned> FirstMaskArgument; 9828 if (Subtarget.hasVInstructions()) 9829 FirstMaskArgument = preAssignMask(Ins); 9830 9831 for (unsigned i = 0; i != NumArgs; ++i) { 9832 MVT ArgVT = Ins[i].VT; 9833 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9834 9835 Type *ArgTy = nullptr; 9836 if (IsRet) 9837 ArgTy = FType->getReturnType(); 9838 else if (Ins[i].isOrigArg()) 9839 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9840 9841 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9842 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9843 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9844 FirstMaskArgument)) { 9845 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9846 << EVT(ArgVT).getEVTString() << '\n'); 9847 llvm_unreachable(nullptr); 9848 } 9849 } 9850 } 9851 9852 void RISCVTargetLowering::analyzeOutputArgs( 9853 MachineFunction &MF, CCState &CCInfo, 9854 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9855 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9856 unsigned NumArgs = Outs.size(); 9857 9858 Optional<unsigned> FirstMaskArgument; 9859 if (Subtarget.hasVInstructions()) 9860 FirstMaskArgument = preAssignMask(Outs); 9861 9862 for (unsigned i = 0; i != NumArgs; i++) { 9863 MVT ArgVT = Outs[i].VT; 9864 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9865 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9866 9867 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9868 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9869 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9870 FirstMaskArgument)) { 9871 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9872 << EVT(ArgVT).getEVTString() << "\n"); 9873 llvm_unreachable(nullptr); 9874 } 9875 } 9876 } 9877 9878 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9879 // values. 9880 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9881 const CCValAssign &VA, const SDLoc &DL, 9882 const RISCVSubtarget &Subtarget) { 9883 switch (VA.getLocInfo()) { 9884 default: 9885 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9886 case CCValAssign::Full: 9887 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9888 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9889 break; 9890 case CCValAssign::BCvt: 9891 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9892 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9893 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9894 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9895 else 9896 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9897 break; 9898 } 9899 return Val; 9900 } 9901 9902 // The caller is responsible for loading the full value if the argument is 9903 // passed with CCValAssign::Indirect. 9904 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9905 const CCValAssign &VA, const SDLoc &DL, 9906 const RISCVTargetLowering &TLI) { 9907 MachineFunction &MF = DAG.getMachineFunction(); 9908 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9909 EVT LocVT = VA.getLocVT(); 9910 SDValue Val; 9911 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9912 Register VReg = RegInfo.createVirtualRegister(RC); 9913 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9914 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9915 9916 if (VA.getLocInfo() == CCValAssign::Indirect) 9917 return Val; 9918 9919 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9920 } 9921 9922 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9923 const CCValAssign &VA, const SDLoc &DL, 9924 const RISCVSubtarget &Subtarget) { 9925 EVT LocVT = VA.getLocVT(); 9926 9927 switch (VA.getLocInfo()) { 9928 default: 9929 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9930 case CCValAssign::Full: 9931 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9932 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9933 break; 9934 case CCValAssign::BCvt: 9935 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9936 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9937 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9938 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9939 else 9940 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9941 break; 9942 } 9943 return Val; 9944 } 9945 9946 // The caller is responsible for loading the full value if the argument is 9947 // passed with CCValAssign::Indirect. 9948 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9949 const CCValAssign &VA, const SDLoc &DL) { 9950 MachineFunction &MF = DAG.getMachineFunction(); 9951 MachineFrameInfo &MFI = MF.getFrameInfo(); 9952 EVT LocVT = VA.getLocVT(); 9953 EVT ValVT = VA.getValVT(); 9954 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9955 if (ValVT.isScalableVector()) { 9956 // When the value is a scalable vector, we save the pointer which points to 9957 // the scalable vector value in the stack. The ValVT will be the pointer 9958 // type, instead of the scalable vector type. 9959 ValVT = LocVT; 9960 } 9961 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9962 /*IsImmutable=*/true); 9963 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9964 SDValue Val; 9965 9966 ISD::LoadExtType ExtType; 9967 switch (VA.getLocInfo()) { 9968 default: 9969 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9970 case CCValAssign::Full: 9971 case CCValAssign::Indirect: 9972 case CCValAssign::BCvt: 9973 ExtType = ISD::NON_EXTLOAD; 9974 break; 9975 } 9976 Val = DAG.getExtLoad( 9977 ExtType, DL, LocVT, Chain, FIN, 9978 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9979 return Val; 9980 } 9981 9982 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9983 const CCValAssign &VA, const SDLoc &DL) { 9984 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9985 "Unexpected VA"); 9986 MachineFunction &MF = DAG.getMachineFunction(); 9987 MachineFrameInfo &MFI = MF.getFrameInfo(); 9988 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9989 9990 if (VA.isMemLoc()) { 9991 // f64 is passed on the stack. 9992 int FI = 9993 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9994 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9995 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9996 MachinePointerInfo::getFixedStack(MF, FI)); 9997 } 9998 9999 assert(VA.isRegLoc() && "Expected register VA assignment"); 10000 10001 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10002 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10003 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10004 SDValue Hi; 10005 if (VA.getLocReg() == RISCV::X17) { 10006 // Second half of f64 is passed on the stack. 10007 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10008 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10009 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10010 MachinePointerInfo::getFixedStack(MF, FI)); 10011 } else { 10012 // Second half of f64 is passed in another GPR. 10013 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10014 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10015 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10016 } 10017 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10018 } 10019 10020 // FastCC has less than 1% performance improvement for some particular 10021 // benchmark. But theoretically, it may has benenfit for some cases. 10022 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10023 unsigned ValNo, MVT ValVT, MVT LocVT, 10024 CCValAssign::LocInfo LocInfo, 10025 ISD::ArgFlagsTy ArgFlags, CCState &State, 10026 bool IsFixed, bool IsRet, Type *OrigTy, 10027 const RISCVTargetLowering &TLI, 10028 Optional<unsigned> FirstMaskArgument) { 10029 10030 // X5 and X6 might be used for save-restore libcall. 10031 static const MCPhysReg GPRList[] = { 10032 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10033 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10034 RISCV::X29, RISCV::X30, RISCV::X31}; 10035 10036 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10037 if (unsigned Reg = State.AllocateReg(GPRList)) { 10038 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10039 return false; 10040 } 10041 } 10042 10043 if (LocVT == MVT::f16) { 10044 static const MCPhysReg FPR16List[] = { 10045 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10046 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10047 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10048 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10049 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10050 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10051 return false; 10052 } 10053 } 10054 10055 if (LocVT == MVT::f32) { 10056 static const MCPhysReg FPR32List[] = { 10057 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10058 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10059 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10060 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10061 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10062 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10063 return false; 10064 } 10065 } 10066 10067 if (LocVT == MVT::f64) { 10068 static const MCPhysReg FPR64List[] = { 10069 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10070 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10071 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10072 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10073 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10074 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10075 return false; 10076 } 10077 } 10078 10079 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10080 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10081 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10082 return false; 10083 } 10084 10085 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10086 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10087 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10088 return false; 10089 } 10090 10091 if (LocVT.isVector()) { 10092 if (unsigned Reg = 10093 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10094 // Fixed-length vectors are located in the corresponding scalable-vector 10095 // container types. 10096 if (ValVT.isFixedLengthVector()) 10097 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10098 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10099 } else { 10100 // Try and pass the address via a "fast" GPR. 10101 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10102 LocInfo = CCValAssign::Indirect; 10103 LocVT = TLI.getSubtarget().getXLenVT(); 10104 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10105 } else if (ValVT.isFixedLengthVector()) { 10106 auto StackAlign = 10107 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10108 unsigned StackOffset = 10109 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10110 State.addLoc( 10111 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10112 } else { 10113 // Can't pass scalable vectors on the stack. 10114 return true; 10115 } 10116 } 10117 10118 return false; 10119 } 10120 10121 return true; // CC didn't match. 10122 } 10123 10124 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10125 CCValAssign::LocInfo LocInfo, 10126 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10127 10128 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10129 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10130 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10131 static const MCPhysReg GPRList[] = { 10132 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10133 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10134 if (unsigned Reg = State.AllocateReg(GPRList)) { 10135 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10136 return false; 10137 } 10138 } 10139 10140 if (LocVT == MVT::f32) { 10141 // Pass in STG registers: F1, ..., F6 10142 // fs0 ... fs5 10143 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10144 RISCV::F18_F, RISCV::F19_F, 10145 RISCV::F20_F, RISCV::F21_F}; 10146 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10147 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10148 return false; 10149 } 10150 } 10151 10152 if (LocVT == MVT::f64) { 10153 // Pass in STG registers: D1, ..., D6 10154 // fs6 ... fs11 10155 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10156 RISCV::F24_D, RISCV::F25_D, 10157 RISCV::F26_D, RISCV::F27_D}; 10158 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10159 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10160 return false; 10161 } 10162 } 10163 10164 report_fatal_error("No registers left in GHC calling convention"); 10165 return true; 10166 } 10167 10168 // Transform physical registers into virtual registers. 10169 SDValue RISCVTargetLowering::LowerFormalArguments( 10170 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10171 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10172 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10173 10174 MachineFunction &MF = DAG.getMachineFunction(); 10175 10176 switch (CallConv) { 10177 default: 10178 report_fatal_error("Unsupported calling convention"); 10179 case CallingConv::C: 10180 case CallingConv::Fast: 10181 break; 10182 case CallingConv::GHC: 10183 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10184 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10185 report_fatal_error( 10186 "GHC calling convention requires the F and D instruction set extensions"); 10187 } 10188 10189 const Function &Func = MF.getFunction(); 10190 if (Func.hasFnAttribute("interrupt")) { 10191 if (!Func.arg_empty()) 10192 report_fatal_error( 10193 "Functions with the interrupt attribute cannot have arguments!"); 10194 10195 StringRef Kind = 10196 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10197 10198 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10199 report_fatal_error( 10200 "Function interrupt attribute argument not supported!"); 10201 } 10202 10203 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10204 MVT XLenVT = Subtarget.getXLenVT(); 10205 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10206 // Used with vargs to acumulate store chains. 10207 std::vector<SDValue> OutChains; 10208 10209 // Assign locations to all of the incoming arguments. 10210 SmallVector<CCValAssign, 16> ArgLocs; 10211 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10212 10213 if (CallConv == CallingConv::GHC) 10214 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10215 else 10216 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10217 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10218 : CC_RISCV); 10219 10220 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10221 CCValAssign &VA = ArgLocs[i]; 10222 SDValue ArgValue; 10223 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10224 // case. 10225 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10226 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10227 else if (VA.isRegLoc()) 10228 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10229 else 10230 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10231 10232 if (VA.getLocInfo() == CCValAssign::Indirect) { 10233 // If the original argument was split and passed by reference (e.g. i128 10234 // on RV32), we need to load all parts of it here (using the same 10235 // address). Vectors may be partly split to registers and partly to the 10236 // stack, in which case the base address is partly offset and subsequent 10237 // stores are relative to that. 10238 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10239 MachinePointerInfo())); 10240 unsigned ArgIndex = Ins[i].OrigArgIndex; 10241 unsigned ArgPartOffset = Ins[i].PartOffset; 10242 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10243 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10244 CCValAssign &PartVA = ArgLocs[i + 1]; 10245 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10246 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10247 if (PartVA.getValVT().isScalableVector()) 10248 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10249 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10250 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10251 MachinePointerInfo())); 10252 ++i; 10253 } 10254 continue; 10255 } 10256 InVals.push_back(ArgValue); 10257 } 10258 10259 if (IsVarArg) { 10260 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10261 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10262 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10263 MachineFrameInfo &MFI = MF.getFrameInfo(); 10264 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10265 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10266 10267 // Offset of the first variable argument from stack pointer, and size of 10268 // the vararg save area. For now, the varargs save area is either zero or 10269 // large enough to hold a0-a7. 10270 int VaArgOffset, VarArgsSaveSize; 10271 10272 // If all registers are allocated, then all varargs must be passed on the 10273 // stack and we don't need to save any argregs. 10274 if (ArgRegs.size() == Idx) { 10275 VaArgOffset = CCInfo.getNextStackOffset(); 10276 VarArgsSaveSize = 0; 10277 } else { 10278 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10279 VaArgOffset = -VarArgsSaveSize; 10280 } 10281 10282 // Record the frame index of the first variable argument 10283 // which is a value necessary to VASTART. 10284 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10285 RVFI->setVarArgsFrameIndex(FI); 10286 10287 // If saving an odd number of registers then create an extra stack slot to 10288 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10289 // offsets to even-numbered registered remain 2*XLEN-aligned. 10290 if (Idx % 2) { 10291 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10292 VarArgsSaveSize += XLenInBytes; 10293 } 10294 10295 // Copy the integer registers that may have been used for passing varargs 10296 // to the vararg save area. 10297 for (unsigned I = Idx; I < ArgRegs.size(); 10298 ++I, VaArgOffset += XLenInBytes) { 10299 const Register Reg = RegInfo.createVirtualRegister(RC); 10300 RegInfo.addLiveIn(ArgRegs[I], Reg); 10301 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10302 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10303 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10304 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10305 MachinePointerInfo::getFixedStack(MF, FI)); 10306 cast<StoreSDNode>(Store.getNode()) 10307 ->getMemOperand() 10308 ->setValue((Value *)nullptr); 10309 OutChains.push_back(Store); 10310 } 10311 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10312 } 10313 10314 // All stores are grouped in one node to allow the matching between 10315 // the size of Ins and InVals. This only happens for vararg functions. 10316 if (!OutChains.empty()) { 10317 OutChains.push_back(Chain); 10318 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10319 } 10320 10321 return Chain; 10322 } 10323 10324 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10325 /// for tail call optimization. 10326 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10327 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10328 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10329 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10330 10331 auto &Callee = CLI.Callee; 10332 auto CalleeCC = CLI.CallConv; 10333 auto &Outs = CLI.Outs; 10334 auto &Caller = MF.getFunction(); 10335 auto CallerCC = Caller.getCallingConv(); 10336 10337 // Exception-handling functions need a special set of instructions to 10338 // indicate a return to the hardware. Tail-calling another function would 10339 // probably break this. 10340 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10341 // should be expanded as new function attributes are introduced. 10342 if (Caller.hasFnAttribute("interrupt")) 10343 return false; 10344 10345 // Do not tail call opt if the stack is used to pass parameters. 10346 if (CCInfo.getNextStackOffset() != 0) 10347 return false; 10348 10349 // Do not tail call opt if any parameters need to be passed indirectly. 10350 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10351 // passed indirectly. So the address of the value will be passed in a 10352 // register, or if not available, then the address is put on the stack. In 10353 // order to pass indirectly, space on the stack often needs to be allocated 10354 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10355 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10356 // are passed CCValAssign::Indirect. 10357 for (auto &VA : ArgLocs) 10358 if (VA.getLocInfo() == CCValAssign::Indirect) 10359 return false; 10360 10361 // Do not tail call opt if either caller or callee uses struct return 10362 // semantics. 10363 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10364 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10365 if (IsCallerStructRet || IsCalleeStructRet) 10366 return false; 10367 10368 // Externally-defined functions with weak linkage should not be 10369 // tail-called. The behaviour of branch instructions in this situation (as 10370 // used for tail calls) is implementation-defined, so we cannot rely on the 10371 // linker replacing the tail call with a return. 10372 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10373 const GlobalValue *GV = G->getGlobal(); 10374 if (GV->hasExternalWeakLinkage()) 10375 return false; 10376 } 10377 10378 // The callee has to preserve all registers the caller needs to preserve. 10379 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10380 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10381 if (CalleeCC != CallerCC) { 10382 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10383 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10384 return false; 10385 } 10386 10387 // Byval parameters hand the function a pointer directly into the stack area 10388 // we want to reuse during a tail call. Working around this *is* possible 10389 // but less efficient and uglier in LowerCall. 10390 for (auto &Arg : Outs) 10391 if (Arg.Flags.isByVal()) 10392 return false; 10393 10394 return true; 10395 } 10396 10397 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10398 return DAG.getDataLayout().getPrefTypeAlign( 10399 VT.getTypeForEVT(*DAG.getContext())); 10400 } 10401 10402 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10403 // and output parameter nodes. 10404 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10405 SmallVectorImpl<SDValue> &InVals) const { 10406 SelectionDAG &DAG = CLI.DAG; 10407 SDLoc &DL = CLI.DL; 10408 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10409 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10410 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10411 SDValue Chain = CLI.Chain; 10412 SDValue Callee = CLI.Callee; 10413 bool &IsTailCall = CLI.IsTailCall; 10414 CallingConv::ID CallConv = CLI.CallConv; 10415 bool IsVarArg = CLI.IsVarArg; 10416 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10417 MVT XLenVT = Subtarget.getXLenVT(); 10418 10419 MachineFunction &MF = DAG.getMachineFunction(); 10420 10421 // Analyze the operands of the call, assigning locations to each operand. 10422 SmallVector<CCValAssign, 16> ArgLocs; 10423 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10424 10425 if (CallConv == CallingConv::GHC) 10426 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10427 else 10428 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10429 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10430 : CC_RISCV); 10431 10432 // Check if it's really possible to do a tail call. 10433 if (IsTailCall) 10434 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10435 10436 if (IsTailCall) 10437 ++NumTailCalls; 10438 else if (CLI.CB && CLI.CB->isMustTailCall()) 10439 report_fatal_error("failed to perform tail call elimination on a call " 10440 "site marked musttail"); 10441 10442 // Get a count of how many bytes are to be pushed on the stack. 10443 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10444 10445 // Create local copies for byval args 10446 SmallVector<SDValue, 8> ByValArgs; 10447 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10448 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10449 if (!Flags.isByVal()) 10450 continue; 10451 10452 SDValue Arg = OutVals[i]; 10453 unsigned Size = Flags.getByValSize(); 10454 Align Alignment = Flags.getNonZeroByValAlign(); 10455 10456 int FI = 10457 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10458 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10459 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10460 10461 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10462 /*IsVolatile=*/false, 10463 /*AlwaysInline=*/false, IsTailCall, 10464 MachinePointerInfo(), MachinePointerInfo()); 10465 ByValArgs.push_back(FIPtr); 10466 } 10467 10468 if (!IsTailCall) 10469 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10470 10471 // Copy argument values to their designated locations. 10472 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10473 SmallVector<SDValue, 8> MemOpChains; 10474 SDValue StackPtr; 10475 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10476 CCValAssign &VA = ArgLocs[i]; 10477 SDValue ArgValue = OutVals[i]; 10478 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10479 10480 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10481 bool IsF64OnRV32DSoftABI = 10482 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10483 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10484 SDValue SplitF64 = DAG.getNode( 10485 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10486 SDValue Lo = SplitF64.getValue(0); 10487 SDValue Hi = SplitF64.getValue(1); 10488 10489 Register RegLo = VA.getLocReg(); 10490 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10491 10492 if (RegLo == RISCV::X17) { 10493 // Second half of f64 is passed on the stack. 10494 // Work out the address of the stack slot. 10495 if (!StackPtr.getNode()) 10496 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10497 // Emit the store. 10498 MemOpChains.push_back( 10499 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10500 } else { 10501 // Second half of f64 is passed in another GPR. 10502 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10503 Register RegHigh = RegLo + 1; 10504 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10505 } 10506 continue; 10507 } 10508 10509 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10510 // as any other MemLoc. 10511 10512 // Promote the value if needed. 10513 // For now, only handle fully promoted and indirect arguments. 10514 if (VA.getLocInfo() == CCValAssign::Indirect) { 10515 // Store the argument in a stack slot and pass its address. 10516 Align StackAlign = 10517 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10518 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10519 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10520 // If the original argument was split (e.g. i128), we need 10521 // to store the required parts of it here (and pass just one address). 10522 // Vectors may be partly split to registers and partly to the stack, in 10523 // which case the base address is partly offset and subsequent stores are 10524 // relative to that. 10525 unsigned ArgIndex = Outs[i].OrigArgIndex; 10526 unsigned ArgPartOffset = Outs[i].PartOffset; 10527 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10528 // Calculate the total size to store. We don't have access to what we're 10529 // actually storing other than performing the loop and collecting the 10530 // info. 10531 SmallVector<std::pair<SDValue, SDValue>> Parts; 10532 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10533 SDValue PartValue = OutVals[i + 1]; 10534 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10535 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10536 EVT PartVT = PartValue.getValueType(); 10537 if (PartVT.isScalableVector()) 10538 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10539 StoredSize += PartVT.getStoreSize(); 10540 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10541 Parts.push_back(std::make_pair(PartValue, Offset)); 10542 ++i; 10543 } 10544 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10545 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10546 MemOpChains.push_back( 10547 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10548 MachinePointerInfo::getFixedStack(MF, FI))); 10549 for (const auto &Part : Parts) { 10550 SDValue PartValue = Part.first; 10551 SDValue PartOffset = Part.second; 10552 SDValue Address = 10553 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10554 MemOpChains.push_back( 10555 DAG.getStore(Chain, DL, PartValue, Address, 10556 MachinePointerInfo::getFixedStack(MF, FI))); 10557 } 10558 ArgValue = SpillSlot; 10559 } else { 10560 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10561 } 10562 10563 // Use local copy if it is a byval arg. 10564 if (Flags.isByVal()) 10565 ArgValue = ByValArgs[j++]; 10566 10567 if (VA.isRegLoc()) { 10568 // Queue up the argument copies and emit them at the end. 10569 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10570 } else { 10571 assert(VA.isMemLoc() && "Argument not register or memory"); 10572 assert(!IsTailCall && "Tail call not allowed if stack is used " 10573 "for passing parameters"); 10574 10575 // Work out the address of the stack slot. 10576 if (!StackPtr.getNode()) 10577 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10578 SDValue Address = 10579 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10580 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10581 10582 // Emit the store. 10583 MemOpChains.push_back( 10584 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10585 } 10586 } 10587 10588 // Join the stores, which are independent of one another. 10589 if (!MemOpChains.empty()) 10590 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10591 10592 SDValue Glue; 10593 10594 // Build a sequence of copy-to-reg nodes, chained and glued together. 10595 for (auto &Reg : RegsToPass) { 10596 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10597 Glue = Chain.getValue(1); 10598 } 10599 10600 // Validate that none of the argument registers have been marked as 10601 // reserved, if so report an error. Do the same for the return address if this 10602 // is not a tailcall. 10603 validateCCReservedRegs(RegsToPass, MF); 10604 if (!IsTailCall && 10605 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10606 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10607 MF.getFunction(), 10608 "Return address register required, but has been reserved."}); 10609 10610 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10611 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10612 // split it and then direct call can be matched by PseudoCALL. 10613 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10614 const GlobalValue *GV = S->getGlobal(); 10615 10616 unsigned OpFlags = RISCVII::MO_CALL; 10617 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10618 OpFlags = RISCVII::MO_PLT; 10619 10620 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10621 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10622 unsigned OpFlags = RISCVII::MO_CALL; 10623 10624 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10625 nullptr)) 10626 OpFlags = RISCVII::MO_PLT; 10627 10628 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10629 } 10630 10631 // The first call operand is the chain and the second is the target address. 10632 SmallVector<SDValue, 8> Ops; 10633 Ops.push_back(Chain); 10634 Ops.push_back(Callee); 10635 10636 // Add argument registers to the end of the list so that they are 10637 // known live into the call. 10638 for (auto &Reg : RegsToPass) 10639 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10640 10641 if (!IsTailCall) { 10642 // Add a register mask operand representing the call-preserved registers. 10643 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10644 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10645 assert(Mask && "Missing call preserved mask for calling convention"); 10646 Ops.push_back(DAG.getRegisterMask(Mask)); 10647 } 10648 10649 // Glue the call to the argument copies, if any. 10650 if (Glue.getNode()) 10651 Ops.push_back(Glue); 10652 10653 // Emit the call. 10654 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10655 10656 if (IsTailCall) { 10657 MF.getFrameInfo().setHasTailCall(); 10658 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10659 } 10660 10661 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10662 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10663 Glue = Chain.getValue(1); 10664 10665 // Mark the end of the call, which is glued to the call itself. 10666 Chain = DAG.getCALLSEQ_END(Chain, 10667 DAG.getConstant(NumBytes, DL, PtrVT, true), 10668 DAG.getConstant(0, DL, PtrVT, true), 10669 Glue, DL); 10670 Glue = Chain.getValue(1); 10671 10672 // Assign locations to each value returned by this call. 10673 SmallVector<CCValAssign, 16> RVLocs; 10674 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10675 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10676 10677 // Copy all of the result registers out of their specified physreg. 10678 for (auto &VA : RVLocs) { 10679 // Copy the value out 10680 SDValue RetValue = 10681 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10682 // Glue the RetValue to the end of the call sequence 10683 Chain = RetValue.getValue(1); 10684 Glue = RetValue.getValue(2); 10685 10686 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10687 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10688 SDValue RetValue2 = 10689 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10690 Chain = RetValue2.getValue(1); 10691 Glue = RetValue2.getValue(2); 10692 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10693 RetValue2); 10694 } 10695 10696 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10697 10698 InVals.push_back(RetValue); 10699 } 10700 10701 return Chain; 10702 } 10703 10704 bool RISCVTargetLowering::CanLowerReturn( 10705 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10706 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10707 SmallVector<CCValAssign, 16> RVLocs; 10708 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10709 10710 Optional<unsigned> FirstMaskArgument; 10711 if (Subtarget.hasVInstructions()) 10712 FirstMaskArgument = preAssignMask(Outs); 10713 10714 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10715 MVT VT = Outs[i].VT; 10716 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10717 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10718 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10719 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10720 *this, FirstMaskArgument)) 10721 return false; 10722 } 10723 return true; 10724 } 10725 10726 SDValue 10727 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10728 bool IsVarArg, 10729 const SmallVectorImpl<ISD::OutputArg> &Outs, 10730 const SmallVectorImpl<SDValue> &OutVals, 10731 const SDLoc &DL, SelectionDAG &DAG) const { 10732 const MachineFunction &MF = DAG.getMachineFunction(); 10733 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10734 10735 // Stores the assignment of the return value to a location. 10736 SmallVector<CCValAssign, 16> RVLocs; 10737 10738 // Info about the registers and stack slot. 10739 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10740 *DAG.getContext()); 10741 10742 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10743 nullptr, CC_RISCV); 10744 10745 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10746 report_fatal_error("GHC functions return void only"); 10747 10748 SDValue Glue; 10749 SmallVector<SDValue, 4> RetOps(1, Chain); 10750 10751 // Copy the result values into the output registers. 10752 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10753 SDValue Val = OutVals[i]; 10754 CCValAssign &VA = RVLocs[i]; 10755 assert(VA.isRegLoc() && "Can only return in registers!"); 10756 10757 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10758 // Handle returning f64 on RV32D with a soft float ABI. 10759 assert(VA.isRegLoc() && "Expected return via registers"); 10760 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10761 DAG.getVTList(MVT::i32, MVT::i32), Val); 10762 SDValue Lo = SplitF64.getValue(0); 10763 SDValue Hi = SplitF64.getValue(1); 10764 Register RegLo = VA.getLocReg(); 10765 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10766 Register RegHi = RegLo + 1; 10767 10768 if (STI.isRegisterReservedByUser(RegLo) || 10769 STI.isRegisterReservedByUser(RegHi)) 10770 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10771 MF.getFunction(), 10772 "Return value register required, but has been reserved."}); 10773 10774 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10775 Glue = Chain.getValue(1); 10776 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10777 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10778 Glue = Chain.getValue(1); 10779 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10780 } else { 10781 // Handle a 'normal' return. 10782 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10783 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10784 10785 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10786 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10787 MF.getFunction(), 10788 "Return value register required, but has been reserved."}); 10789 10790 // Guarantee that all emitted copies are stuck together. 10791 Glue = Chain.getValue(1); 10792 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10793 } 10794 } 10795 10796 RetOps[0] = Chain; // Update chain. 10797 10798 // Add the glue node if we have it. 10799 if (Glue.getNode()) { 10800 RetOps.push_back(Glue); 10801 } 10802 10803 unsigned RetOpc = RISCVISD::RET_FLAG; 10804 // Interrupt service routines use different return instructions. 10805 const Function &Func = DAG.getMachineFunction().getFunction(); 10806 if (Func.hasFnAttribute("interrupt")) { 10807 if (!Func.getReturnType()->isVoidTy()) 10808 report_fatal_error( 10809 "Functions with the interrupt attribute must have void return type!"); 10810 10811 MachineFunction &MF = DAG.getMachineFunction(); 10812 StringRef Kind = 10813 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10814 10815 if (Kind == "user") 10816 RetOpc = RISCVISD::URET_FLAG; 10817 else if (Kind == "supervisor") 10818 RetOpc = RISCVISD::SRET_FLAG; 10819 else 10820 RetOpc = RISCVISD::MRET_FLAG; 10821 } 10822 10823 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10824 } 10825 10826 void RISCVTargetLowering::validateCCReservedRegs( 10827 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10828 MachineFunction &MF) const { 10829 const Function &F = MF.getFunction(); 10830 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10831 10832 if (llvm::any_of(Regs, [&STI](auto Reg) { 10833 return STI.isRegisterReservedByUser(Reg.first); 10834 })) 10835 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10836 F, "Argument register required, but has been reserved."}); 10837 } 10838 10839 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10840 return CI->isTailCall(); 10841 } 10842 10843 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10844 #define NODE_NAME_CASE(NODE) \ 10845 case RISCVISD::NODE: \ 10846 return "RISCVISD::" #NODE; 10847 // clang-format off 10848 switch ((RISCVISD::NodeType)Opcode) { 10849 case RISCVISD::FIRST_NUMBER: 10850 break; 10851 NODE_NAME_CASE(RET_FLAG) 10852 NODE_NAME_CASE(URET_FLAG) 10853 NODE_NAME_CASE(SRET_FLAG) 10854 NODE_NAME_CASE(MRET_FLAG) 10855 NODE_NAME_CASE(CALL) 10856 NODE_NAME_CASE(SELECT_CC) 10857 NODE_NAME_CASE(BR_CC) 10858 NODE_NAME_CASE(BuildPairF64) 10859 NODE_NAME_CASE(SplitF64) 10860 NODE_NAME_CASE(TAIL) 10861 NODE_NAME_CASE(MULHSU) 10862 NODE_NAME_CASE(SLLW) 10863 NODE_NAME_CASE(SRAW) 10864 NODE_NAME_CASE(SRLW) 10865 NODE_NAME_CASE(DIVW) 10866 NODE_NAME_CASE(DIVUW) 10867 NODE_NAME_CASE(REMUW) 10868 NODE_NAME_CASE(ROLW) 10869 NODE_NAME_CASE(RORW) 10870 NODE_NAME_CASE(CLZW) 10871 NODE_NAME_CASE(CTZW) 10872 NODE_NAME_CASE(FSLW) 10873 NODE_NAME_CASE(FSRW) 10874 NODE_NAME_CASE(FSL) 10875 NODE_NAME_CASE(FSR) 10876 NODE_NAME_CASE(FMV_H_X) 10877 NODE_NAME_CASE(FMV_X_ANYEXTH) 10878 NODE_NAME_CASE(FMV_X_SIGNEXTH) 10879 NODE_NAME_CASE(FMV_W_X_RV64) 10880 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10881 NODE_NAME_CASE(FCVT_X) 10882 NODE_NAME_CASE(FCVT_XU) 10883 NODE_NAME_CASE(FCVT_W_RV64) 10884 NODE_NAME_CASE(FCVT_WU_RV64) 10885 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10886 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10887 NODE_NAME_CASE(READ_CYCLE_WIDE) 10888 NODE_NAME_CASE(GREV) 10889 NODE_NAME_CASE(GREVW) 10890 NODE_NAME_CASE(GORC) 10891 NODE_NAME_CASE(GORCW) 10892 NODE_NAME_CASE(SHFL) 10893 NODE_NAME_CASE(SHFLW) 10894 NODE_NAME_CASE(UNSHFL) 10895 NODE_NAME_CASE(UNSHFLW) 10896 NODE_NAME_CASE(BFP) 10897 NODE_NAME_CASE(BFPW) 10898 NODE_NAME_CASE(BCOMPRESS) 10899 NODE_NAME_CASE(BCOMPRESSW) 10900 NODE_NAME_CASE(BDECOMPRESS) 10901 NODE_NAME_CASE(BDECOMPRESSW) 10902 NODE_NAME_CASE(VMV_V_X_VL) 10903 NODE_NAME_CASE(VFMV_V_F_VL) 10904 NODE_NAME_CASE(VMV_X_S) 10905 NODE_NAME_CASE(VMV_S_X_VL) 10906 NODE_NAME_CASE(VFMV_S_F_VL) 10907 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10908 NODE_NAME_CASE(READ_VLENB) 10909 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10910 NODE_NAME_CASE(VSLIDEUP_VL) 10911 NODE_NAME_CASE(VSLIDE1UP_VL) 10912 NODE_NAME_CASE(VSLIDEDOWN_VL) 10913 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10914 NODE_NAME_CASE(VID_VL) 10915 NODE_NAME_CASE(VFNCVT_ROD_VL) 10916 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10917 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10918 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10919 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10920 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10921 NODE_NAME_CASE(VECREDUCE_AND_VL) 10922 NODE_NAME_CASE(VECREDUCE_OR_VL) 10923 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10924 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10925 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10926 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10927 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10928 NODE_NAME_CASE(ADD_VL) 10929 NODE_NAME_CASE(AND_VL) 10930 NODE_NAME_CASE(MUL_VL) 10931 NODE_NAME_CASE(OR_VL) 10932 NODE_NAME_CASE(SDIV_VL) 10933 NODE_NAME_CASE(SHL_VL) 10934 NODE_NAME_CASE(SREM_VL) 10935 NODE_NAME_CASE(SRA_VL) 10936 NODE_NAME_CASE(SRL_VL) 10937 NODE_NAME_CASE(SUB_VL) 10938 NODE_NAME_CASE(UDIV_VL) 10939 NODE_NAME_CASE(UREM_VL) 10940 NODE_NAME_CASE(XOR_VL) 10941 NODE_NAME_CASE(SADDSAT_VL) 10942 NODE_NAME_CASE(UADDSAT_VL) 10943 NODE_NAME_CASE(SSUBSAT_VL) 10944 NODE_NAME_CASE(USUBSAT_VL) 10945 NODE_NAME_CASE(FADD_VL) 10946 NODE_NAME_CASE(FSUB_VL) 10947 NODE_NAME_CASE(FMUL_VL) 10948 NODE_NAME_CASE(FDIV_VL) 10949 NODE_NAME_CASE(FNEG_VL) 10950 NODE_NAME_CASE(FABS_VL) 10951 NODE_NAME_CASE(FSQRT_VL) 10952 NODE_NAME_CASE(FMA_VL) 10953 NODE_NAME_CASE(FCOPYSIGN_VL) 10954 NODE_NAME_CASE(SMIN_VL) 10955 NODE_NAME_CASE(SMAX_VL) 10956 NODE_NAME_CASE(UMIN_VL) 10957 NODE_NAME_CASE(UMAX_VL) 10958 NODE_NAME_CASE(FMINNUM_VL) 10959 NODE_NAME_CASE(FMAXNUM_VL) 10960 NODE_NAME_CASE(MULHS_VL) 10961 NODE_NAME_CASE(MULHU_VL) 10962 NODE_NAME_CASE(FP_TO_SINT_VL) 10963 NODE_NAME_CASE(FP_TO_UINT_VL) 10964 NODE_NAME_CASE(SINT_TO_FP_VL) 10965 NODE_NAME_CASE(UINT_TO_FP_VL) 10966 NODE_NAME_CASE(FP_EXTEND_VL) 10967 NODE_NAME_CASE(FP_ROUND_VL) 10968 NODE_NAME_CASE(VWMUL_VL) 10969 NODE_NAME_CASE(VWMULU_VL) 10970 NODE_NAME_CASE(VWMULSU_VL) 10971 NODE_NAME_CASE(VWADD_VL) 10972 NODE_NAME_CASE(VWADDU_VL) 10973 NODE_NAME_CASE(VWSUB_VL) 10974 NODE_NAME_CASE(VWSUBU_VL) 10975 NODE_NAME_CASE(VWADD_W_VL) 10976 NODE_NAME_CASE(VWADDU_W_VL) 10977 NODE_NAME_CASE(VWSUB_W_VL) 10978 NODE_NAME_CASE(VWSUBU_W_VL) 10979 NODE_NAME_CASE(SETCC_VL) 10980 NODE_NAME_CASE(VSELECT_VL) 10981 NODE_NAME_CASE(VP_MERGE_VL) 10982 NODE_NAME_CASE(VMAND_VL) 10983 NODE_NAME_CASE(VMOR_VL) 10984 NODE_NAME_CASE(VMXOR_VL) 10985 NODE_NAME_CASE(VMCLR_VL) 10986 NODE_NAME_CASE(VMSET_VL) 10987 NODE_NAME_CASE(VRGATHER_VX_VL) 10988 NODE_NAME_CASE(VRGATHER_VV_VL) 10989 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10990 NODE_NAME_CASE(VSEXT_VL) 10991 NODE_NAME_CASE(VZEXT_VL) 10992 NODE_NAME_CASE(VCPOP_VL) 10993 NODE_NAME_CASE(READ_CSR) 10994 NODE_NAME_CASE(WRITE_CSR) 10995 NODE_NAME_CASE(SWAP_CSR) 10996 } 10997 // clang-format on 10998 return nullptr; 10999 #undef NODE_NAME_CASE 11000 } 11001 11002 /// getConstraintType - Given a constraint letter, return the type of 11003 /// constraint it is for this target. 11004 RISCVTargetLowering::ConstraintType 11005 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11006 if (Constraint.size() == 1) { 11007 switch (Constraint[0]) { 11008 default: 11009 break; 11010 case 'f': 11011 return C_RegisterClass; 11012 case 'I': 11013 case 'J': 11014 case 'K': 11015 return C_Immediate; 11016 case 'A': 11017 return C_Memory; 11018 case 'S': // A symbolic address 11019 return C_Other; 11020 } 11021 } else { 11022 if (Constraint == "vr" || Constraint == "vm") 11023 return C_RegisterClass; 11024 } 11025 return TargetLowering::getConstraintType(Constraint); 11026 } 11027 11028 std::pair<unsigned, const TargetRegisterClass *> 11029 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11030 StringRef Constraint, 11031 MVT VT) const { 11032 // First, see if this is a constraint that directly corresponds to a 11033 // RISCV register class. 11034 if (Constraint.size() == 1) { 11035 switch (Constraint[0]) { 11036 case 'r': 11037 // TODO: Support fixed vectors up to XLen for P extension? 11038 if (VT.isVector()) 11039 break; 11040 return std::make_pair(0U, &RISCV::GPRRegClass); 11041 case 'f': 11042 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11043 return std::make_pair(0U, &RISCV::FPR16RegClass); 11044 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11045 return std::make_pair(0U, &RISCV::FPR32RegClass); 11046 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11047 return std::make_pair(0U, &RISCV::FPR64RegClass); 11048 break; 11049 default: 11050 break; 11051 } 11052 } else if (Constraint == "vr") { 11053 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11054 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11055 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11056 return std::make_pair(0U, RC); 11057 } 11058 } else if (Constraint == "vm") { 11059 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11060 return std::make_pair(0U, &RISCV::VMV0RegClass); 11061 } 11062 11063 // Clang will correctly decode the usage of register name aliases into their 11064 // official names. However, other frontends like `rustc` do not. This allows 11065 // users of these frontends to use the ABI names for registers in LLVM-style 11066 // register constraints. 11067 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11068 .Case("{zero}", RISCV::X0) 11069 .Case("{ra}", RISCV::X1) 11070 .Case("{sp}", RISCV::X2) 11071 .Case("{gp}", RISCV::X3) 11072 .Case("{tp}", RISCV::X4) 11073 .Case("{t0}", RISCV::X5) 11074 .Case("{t1}", RISCV::X6) 11075 .Case("{t2}", RISCV::X7) 11076 .Cases("{s0}", "{fp}", RISCV::X8) 11077 .Case("{s1}", RISCV::X9) 11078 .Case("{a0}", RISCV::X10) 11079 .Case("{a1}", RISCV::X11) 11080 .Case("{a2}", RISCV::X12) 11081 .Case("{a3}", RISCV::X13) 11082 .Case("{a4}", RISCV::X14) 11083 .Case("{a5}", RISCV::X15) 11084 .Case("{a6}", RISCV::X16) 11085 .Case("{a7}", RISCV::X17) 11086 .Case("{s2}", RISCV::X18) 11087 .Case("{s3}", RISCV::X19) 11088 .Case("{s4}", RISCV::X20) 11089 .Case("{s5}", RISCV::X21) 11090 .Case("{s6}", RISCV::X22) 11091 .Case("{s7}", RISCV::X23) 11092 .Case("{s8}", RISCV::X24) 11093 .Case("{s9}", RISCV::X25) 11094 .Case("{s10}", RISCV::X26) 11095 .Case("{s11}", RISCV::X27) 11096 .Case("{t3}", RISCV::X28) 11097 .Case("{t4}", RISCV::X29) 11098 .Case("{t5}", RISCV::X30) 11099 .Case("{t6}", RISCV::X31) 11100 .Default(RISCV::NoRegister); 11101 if (XRegFromAlias != RISCV::NoRegister) 11102 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11103 11104 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11105 // TableGen record rather than the AsmName to choose registers for InlineAsm 11106 // constraints, plus we want to match those names to the widest floating point 11107 // register type available, manually select floating point registers here. 11108 // 11109 // The second case is the ABI name of the register, so that frontends can also 11110 // use the ABI names in register constraint lists. 11111 if (Subtarget.hasStdExtF()) { 11112 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11113 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11114 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11115 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11116 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11117 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11118 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11119 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11120 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11121 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11122 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11123 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11124 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11125 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11126 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11127 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11128 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11129 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11130 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11131 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11132 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11133 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11134 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11135 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11136 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11137 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11138 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11139 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11140 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11141 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11142 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11143 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11144 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11145 .Default(RISCV::NoRegister); 11146 if (FReg != RISCV::NoRegister) { 11147 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11148 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11149 unsigned RegNo = FReg - RISCV::F0_F; 11150 unsigned DReg = RISCV::F0_D + RegNo; 11151 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11152 } 11153 if (VT == MVT::f32 || VT == MVT::Other) 11154 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11155 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11156 unsigned RegNo = FReg - RISCV::F0_F; 11157 unsigned HReg = RISCV::F0_H + RegNo; 11158 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11159 } 11160 } 11161 } 11162 11163 if (Subtarget.hasVInstructions()) { 11164 Register VReg = StringSwitch<Register>(Constraint.lower()) 11165 .Case("{v0}", RISCV::V0) 11166 .Case("{v1}", RISCV::V1) 11167 .Case("{v2}", RISCV::V2) 11168 .Case("{v3}", RISCV::V3) 11169 .Case("{v4}", RISCV::V4) 11170 .Case("{v5}", RISCV::V5) 11171 .Case("{v6}", RISCV::V6) 11172 .Case("{v7}", RISCV::V7) 11173 .Case("{v8}", RISCV::V8) 11174 .Case("{v9}", RISCV::V9) 11175 .Case("{v10}", RISCV::V10) 11176 .Case("{v11}", RISCV::V11) 11177 .Case("{v12}", RISCV::V12) 11178 .Case("{v13}", RISCV::V13) 11179 .Case("{v14}", RISCV::V14) 11180 .Case("{v15}", RISCV::V15) 11181 .Case("{v16}", RISCV::V16) 11182 .Case("{v17}", RISCV::V17) 11183 .Case("{v18}", RISCV::V18) 11184 .Case("{v19}", RISCV::V19) 11185 .Case("{v20}", RISCV::V20) 11186 .Case("{v21}", RISCV::V21) 11187 .Case("{v22}", RISCV::V22) 11188 .Case("{v23}", RISCV::V23) 11189 .Case("{v24}", RISCV::V24) 11190 .Case("{v25}", RISCV::V25) 11191 .Case("{v26}", RISCV::V26) 11192 .Case("{v27}", RISCV::V27) 11193 .Case("{v28}", RISCV::V28) 11194 .Case("{v29}", RISCV::V29) 11195 .Case("{v30}", RISCV::V30) 11196 .Case("{v31}", RISCV::V31) 11197 .Default(RISCV::NoRegister); 11198 if (VReg != RISCV::NoRegister) { 11199 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11200 return std::make_pair(VReg, &RISCV::VMRegClass); 11201 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11202 return std::make_pair(VReg, &RISCV::VRRegClass); 11203 for (const auto *RC : 11204 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11205 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11206 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11207 return std::make_pair(VReg, RC); 11208 } 11209 } 11210 } 11211 } 11212 11213 std::pair<Register, const TargetRegisterClass *> Res = 11214 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11215 11216 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11217 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11218 // Subtarget into account. 11219 if (Res.second == &RISCV::GPRF16RegClass || 11220 Res.second == &RISCV::GPRF32RegClass || 11221 Res.second == &RISCV::GPRF64RegClass) 11222 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11223 11224 return Res; 11225 } 11226 11227 unsigned 11228 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11229 // Currently only support length 1 constraints. 11230 if (ConstraintCode.size() == 1) { 11231 switch (ConstraintCode[0]) { 11232 case 'A': 11233 return InlineAsm::Constraint_A; 11234 default: 11235 break; 11236 } 11237 } 11238 11239 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11240 } 11241 11242 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11243 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11244 SelectionDAG &DAG) const { 11245 // Currently only support length 1 constraints. 11246 if (Constraint.length() == 1) { 11247 switch (Constraint[0]) { 11248 case 'I': 11249 // Validate & create a 12-bit signed immediate operand. 11250 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11251 uint64_t CVal = C->getSExtValue(); 11252 if (isInt<12>(CVal)) 11253 Ops.push_back( 11254 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11255 } 11256 return; 11257 case 'J': 11258 // Validate & create an integer zero operand. 11259 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11260 if (C->getZExtValue() == 0) 11261 Ops.push_back( 11262 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11263 return; 11264 case 'K': 11265 // Validate & create a 5-bit unsigned immediate operand. 11266 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11267 uint64_t CVal = C->getZExtValue(); 11268 if (isUInt<5>(CVal)) 11269 Ops.push_back( 11270 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11271 } 11272 return; 11273 case 'S': 11274 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11275 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11276 GA->getValueType(0))); 11277 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11278 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11279 BA->getValueType(0))); 11280 } 11281 return; 11282 default: 11283 break; 11284 } 11285 } 11286 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11287 } 11288 11289 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11290 Instruction *Inst, 11291 AtomicOrdering Ord) const { 11292 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11293 return Builder.CreateFence(Ord); 11294 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11295 return Builder.CreateFence(AtomicOrdering::Release); 11296 return nullptr; 11297 } 11298 11299 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11300 Instruction *Inst, 11301 AtomicOrdering Ord) const { 11302 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11303 return Builder.CreateFence(AtomicOrdering::Acquire); 11304 return nullptr; 11305 } 11306 11307 TargetLowering::AtomicExpansionKind 11308 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11309 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11310 // point operations can't be used in an lr/sc sequence without breaking the 11311 // forward-progress guarantee. 11312 if (AI->isFloatingPointOperation()) 11313 return AtomicExpansionKind::CmpXChg; 11314 11315 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11316 if (Size == 8 || Size == 16) 11317 return AtomicExpansionKind::MaskedIntrinsic; 11318 return AtomicExpansionKind::None; 11319 } 11320 11321 static Intrinsic::ID 11322 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11323 if (XLen == 32) { 11324 switch (BinOp) { 11325 default: 11326 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11327 case AtomicRMWInst::Xchg: 11328 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11329 case AtomicRMWInst::Add: 11330 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11331 case AtomicRMWInst::Sub: 11332 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11333 case AtomicRMWInst::Nand: 11334 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11335 case AtomicRMWInst::Max: 11336 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11337 case AtomicRMWInst::Min: 11338 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11339 case AtomicRMWInst::UMax: 11340 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11341 case AtomicRMWInst::UMin: 11342 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11343 } 11344 } 11345 11346 if (XLen == 64) { 11347 switch (BinOp) { 11348 default: 11349 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11350 case AtomicRMWInst::Xchg: 11351 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11352 case AtomicRMWInst::Add: 11353 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11354 case AtomicRMWInst::Sub: 11355 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11356 case AtomicRMWInst::Nand: 11357 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11358 case AtomicRMWInst::Max: 11359 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11360 case AtomicRMWInst::Min: 11361 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11362 case AtomicRMWInst::UMax: 11363 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11364 case AtomicRMWInst::UMin: 11365 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11366 } 11367 } 11368 11369 llvm_unreachable("Unexpected XLen\n"); 11370 } 11371 11372 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11373 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11374 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11375 unsigned XLen = Subtarget.getXLen(); 11376 Value *Ordering = 11377 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11378 Type *Tys[] = {AlignedAddr->getType()}; 11379 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11380 AI->getModule(), 11381 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11382 11383 if (XLen == 64) { 11384 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11385 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11386 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11387 } 11388 11389 Value *Result; 11390 11391 // Must pass the shift amount needed to sign extend the loaded value prior 11392 // to performing a signed comparison for min/max. ShiftAmt is the number of 11393 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11394 // is the number of bits to left+right shift the value in order to 11395 // sign-extend. 11396 if (AI->getOperation() == AtomicRMWInst::Min || 11397 AI->getOperation() == AtomicRMWInst::Max) { 11398 const DataLayout &DL = AI->getModule()->getDataLayout(); 11399 unsigned ValWidth = 11400 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11401 Value *SextShamt = 11402 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11403 Result = Builder.CreateCall(LrwOpScwLoop, 11404 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11405 } else { 11406 Result = 11407 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11408 } 11409 11410 if (XLen == 64) 11411 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11412 return Result; 11413 } 11414 11415 TargetLowering::AtomicExpansionKind 11416 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11417 AtomicCmpXchgInst *CI) const { 11418 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11419 if (Size == 8 || Size == 16) 11420 return AtomicExpansionKind::MaskedIntrinsic; 11421 return AtomicExpansionKind::None; 11422 } 11423 11424 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11425 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11426 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11427 unsigned XLen = Subtarget.getXLen(); 11428 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11429 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11430 if (XLen == 64) { 11431 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11432 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11433 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11434 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11435 } 11436 Type *Tys[] = {AlignedAddr->getType()}; 11437 Function *MaskedCmpXchg = 11438 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11439 Value *Result = Builder.CreateCall( 11440 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11441 if (XLen == 64) 11442 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11443 return Result; 11444 } 11445 11446 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11447 return false; 11448 } 11449 11450 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11451 EVT VT) const { 11452 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11453 return false; 11454 11455 switch (FPVT.getSimpleVT().SimpleTy) { 11456 case MVT::f16: 11457 return Subtarget.hasStdExtZfh(); 11458 case MVT::f32: 11459 return Subtarget.hasStdExtF(); 11460 case MVT::f64: 11461 return Subtarget.hasStdExtD(); 11462 default: 11463 return false; 11464 } 11465 } 11466 11467 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11468 // If we are using the small code model, we can reduce size of jump table 11469 // entry to 4 bytes. 11470 if (Subtarget.is64Bit() && !isPositionIndependent() && 11471 getTargetMachine().getCodeModel() == CodeModel::Small) { 11472 return MachineJumpTableInfo::EK_Custom32; 11473 } 11474 return TargetLowering::getJumpTableEncoding(); 11475 } 11476 11477 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11478 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11479 unsigned uid, MCContext &Ctx) const { 11480 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11481 getTargetMachine().getCodeModel() == CodeModel::Small); 11482 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11483 } 11484 11485 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11486 EVT VT) const { 11487 VT = VT.getScalarType(); 11488 11489 if (!VT.isSimple()) 11490 return false; 11491 11492 switch (VT.getSimpleVT().SimpleTy) { 11493 case MVT::f16: 11494 return Subtarget.hasStdExtZfh(); 11495 case MVT::f32: 11496 return Subtarget.hasStdExtF(); 11497 case MVT::f64: 11498 return Subtarget.hasStdExtD(); 11499 default: 11500 break; 11501 } 11502 11503 return false; 11504 } 11505 11506 Register RISCVTargetLowering::getExceptionPointerRegister( 11507 const Constant *PersonalityFn) const { 11508 return RISCV::X10; 11509 } 11510 11511 Register RISCVTargetLowering::getExceptionSelectorRegister( 11512 const Constant *PersonalityFn) const { 11513 return RISCV::X11; 11514 } 11515 11516 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11517 // Return false to suppress the unnecessary extensions if the LibCall 11518 // arguments or return value is f32 type for LP64 ABI. 11519 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11520 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11521 return false; 11522 11523 return true; 11524 } 11525 11526 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11527 if (Subtarget.is64Bit() && Type == MVT::i32) 11528 return true; 11529 11530 return IsSigned; 11531 } 11532 11533 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11534 SDValue C) const { 11535 // Check integral scalar types. 11536 if (VT.isScalarInteger()) { 11537 // Omit the optimization if the sub target has the M extension and the data 11538 // size exceeds XLen. 11539 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11540 return false; 11541 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11542 // Break the MUL to a SLLI and an ADD/SUB. 11543 const APInt &Imm = ConstNode->getAPIntValue(); 11544 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11545 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11546 return true; 11547 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11548 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11549 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11550 (Imm - 8).isPowerOf2())) 11551 return true; 11552 // Omit the following optimization if the sub target has the M extension 11553 // and the data size >= XLen. 11554 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11555 return false; 11556 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11557 // a pair of LUI/ADDI. 11558 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11559 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11560 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11561 (1 - ImmS).isPowerOf2()) 11562 return true; 11563 } 11564 } 11565 } 11566 11567 return false; 11568 } 11569 11570 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11571 SDValue ConstNode) const { 11572 // Let the DAGCombiner decide for vectors. 11573 EVT VT = AddNode.getValueType(); 11574 if (VT.isVector()) 11575 return true; 11576 11577 // Let the DAGCombiner decide for larger types. 11578 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11579 return true; 11580 11581 // It is worse if c1 is simm12 while c1*c2 is not. 11582 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11583 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11584 const APInt &C1 = C1Node->getAPIntValue(); 11585 const APInt &C2 = C2Node->getAPIntValue(); 11586 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11587 return false; 11588 11589 // Default to true and let the DAGCombiner decide. 11590 return true; 11591 } 11592 11593 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11594 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11595 bool *Fast) const { 11596 if (!VT.isVector()) 11597 return false; 11598 11599 EVT ElemVT = VT.getVectorElementType(); 11600 if (Alignment >= ElemVT.getStoreSize()) { 11601 if (Fast) 11602 *Fast = true; 11603 return true; 11604 } 11605 11606 return false; 11607 } 11608 11609 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11610 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11611 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11612 bool IsABIRegCopy = CC.hasValue(); 11613 EVT ValueVT = Val.getValueType(); 11614 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11615 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11616 // and cast to f32. 11617 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11618 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11619 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11620 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11621 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11622 Parts[0] = Val; 11623 return true; 11624 } 11625 11626 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11627 LLVMContext &Context = *DAG.getContext(); 11628 EVT ValueEltVT = ValueVT.getVectorElementType(); 11629 EVT PartEltVT = PartVT.getVectorElementType(); 11630 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11631 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11632 if (PartVTBitSize % ValueVTBitSize == 0) { 11633 assert(PartVTBitSize >= ValueVTBitSize); 11634 // If the element types are different, bitcast to the same element type of 11635 // PartVT first. 11636 // Give an example here, we want copy a <vscale x 1 x i8> value to 11637 // <vscale x 4 x i16>. 11638 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11639 // subvector, then we can bitcast to <vscale x 4 x i16>. 11640 if (ValueEltVT != PartEltVT) { 11641 if (PartVTBitSize > ValueVTBitSize) { 11642 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11643 assert(Count != 0 && "The number of element should not be zero."); 11644 EVT SameEltTypeVT = 11645 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11646 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11647 DAG.getUNDEF(SameEltTypeVT), Val, 11648 DAG.getVectorIdxConstant(0, DL)); 11649 } 11650 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11651 } else { 11652 Val = 11653 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11654 Val, DAG.getVectorIdxConstant(0, DL)); 11655 } 11656 Parts[0] = Val; 11657 return true; 11658 } 11659 } 11660 return false; 11661 } 11662 11663 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11664 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11665 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11666 bool IsABIRegCopy = CC.hasValue(); 11667 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11668 SDValue Val = Parts[0]; 11669 11670 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11671 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11672 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11673 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11674 return Val; 11675 } 11676 11677 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11678 LLVMContext &Context = *DAG.getContext(); 11679 SDValue Val = Parts[0]; 11680 EVT ValueEltVT = ValueVT.getVectorElementType(); 11681 EVT PartEltVT = PartVT.getVectorElementType(); 11682 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11683 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11684 if (PartVTBitSize % ValueVTBitSize == 0) { 11685 assert(PartVTBitSize >= ValueVTBitSize); 11686 EVT SameEltTypeVT = ValueVT; 11687 // If the element types are different, convert it to the same element type 11688 // of PartVT. 11689 // Give an example here, we want copy a <vscale x 1 x i8> value from 11690 // <vscale x 4 x i16>. 11691 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11692 // then we can extract <vscale x 1 x i8>. 11693 if (ValueEltVT != PartEltVT) { 11694 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11695 assert(Count != 0 && "The number of element should not be zero."); 11696 SameEltTypeVT = 11697 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11698 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11699 } 11700 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11701 DAG.getVectorIdxConstant(0, DL)); 11702 return Val; 11703 } 11704 } 11705 return SDValue(); 11706 } 11707 11708 SDValue 11709 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11710 SelectionDAG &DAG, 11711 SmallVectorImpl<SDNode *> &Created) const { 11712 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11713 if (isIntDivCheap(N->getValueType(0), Attr)) 11714 return SDValue(N, 0); // Lower SDIV as SDIV 11715 11716 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11717 "Unexpected divisor!"); 11718 11719 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11720 if (!Subtarget.hasStdExtZbt()) 11721 return SDValue(); 11722 11723 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11724 // Besides, more critical path instructions will be generated when dividing 11725 // by 2. So we keep using the original DAGs for these cases. 11726 unsigned Lg2 = Divisor.countTrailingZeros(); 11727 if (Lg2 == 1 || Lg2 >= 12) 11728 return SDValue(); 11729 11730 // fold (sdiv X, pow2) 11731 EVT VT = N->getValueType(0); 11732 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11733 return SDValue(); 11734 11735 SDLoc DL(N); 11736 SDValue N0 = N->getOperand(0); 11737 SDValue Zero = DAG.getConstant(0, DL, VT); 11738 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11739 11740 // Add (N0 < 0) ? Pow2 - 1 : 0; 11741 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11742 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11743 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11744 11745 Created.push_back(Cmp.getNode()); 11746 Created.push_back(Add.getNode()); 11747 Created.push_back(Sel.getNode()); 11748 11749 // Divide by pow2. 11750 SDValue SRA = 11751 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11752 11753 // If we're dividing by a positive value, we're done. Otherwise, we must 11754 // negate the result. 11755 if (Divisor.isNonNegative()) 11756 return SRA; 11757 11758 Created.push_back(SRA.getNode()); 11759 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11760 } 11761 11762 #define GET_REGISTER_MATCHER 11763 #include "RISCVGenAsmMatcher.inc" 11764 11765 Register 11766 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11767 const MachineFunction &MF) const { 11768 Register Reg = MatchRegisterAltName(RegName); 11769 if (Reg == RISCV::NoRegister) 11770 Reg = MatchRegisterName(RegName); 11771 if (Reg == RISCV::NoRegister) 11772 report_fatal_error( 11773 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11774 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11775 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11776 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11777 StringRef(RegName) + "\".")); 11778 return Reg; 11779 } 11780 11781 namespace llvm { 11782 namespace RISCVVIntrinsicsTable { 11783 11784 #define GET_RISCVVIntrinsicsTable_IMPL 11785 #include "RISCVGenSearchableTables.inc" 11786 11787 } // namespace RISCVVIntrinsicsTable 11788 11789 } // namespace llvm 11790