1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 116 assert(Size <= 512 && isPowerOf2_32(Size)); 117 const TargetRegisterClass *RC; 118 if (Size <= 64) 119 RC = &RISCV::VRRegClass; 120 else if (Size == 128) 121 RC = &RISCV::VRM2RegClass; 122 else if (Size == 256) 123 RC = &RISCV::VRM4RegClass; 124 else 125 RC = &RISCV::VRM8RegClass; 126 127 addRegisterClass(VT, RC); 128 }; 129 130 for (MVT VT : BoolVecVTs) 131 addRegClassForRVV(VT); 132 for (MVT VT : IntVecVTs) { 133 if (VT.getVectorElementType() == MVT::i64 && 134 !Subtarget.hasVInstructionsI64()) 135 continue; 136 addRegClassForRVV(VT); 137 } 138 139 if (Subtarget.hasVInstructionsF16()) 140 for (MVT VT : F16VecVTs) 141 addRegClassForRVV(VT); 142 143 if (Subtarget.hasVInstructionsF32()) 144 for (MVT VT : F32VecVTs) 145 addRegClassForRVV(VT); 146 147 if (Subtarget.hasVInstructionsF64()) 148 for (MVT VT : F64VecVTs) 149 addRegClassForRVV(VT); 150 151 if (Subtarget.useRVVForFixedLengthVectors()) { 152 auto addRegClassForFixedVectors = [this](MVT VT) { 153 MVT ContainerVT = getContainerForFixedLengthVector(VT); 154 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 155 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 156 addRegisterClass(VT, TRI.getRegClass(RCID)); 157 }; 158 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 159 if (useRVVForFixedLengthVectorVT(VT)) 160 addRegClassForFixedVectors(VT); 161 162 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 163 if (useRVVForFixedLengthVectorVT(VT)) 164 addRegClassForFixedVectors(VT); 165 } 166 } 167 168 // Compute derived properties from the register classes. 169 computeRegisterProperties(STI.getRegisterInfo()); 170 171 setStackPointerRegisterToSaveRestore(RISCV::X2); 172 173 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 174 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 175 176 // TODO: add all necessary setOperationAction calls. 177 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 178 179 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 180 setOperationAction(ISD::BR_CC, XLenVT, Expand); 181 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 182 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 183 184 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 185 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 186 187 setOperationAction(ISD::VASTART, MVT::Other, Custom); 188 setOperationAction(ISD::VAARG, MVT::Other, Expand); 189 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 190 setOperationAction(ISD::VAEND, MVT::Other, Expand); 191 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 193 if (!Subtarget.hasStdExtZbb()) { 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 196 } 197 198 if (Subtarget.is64Bit()) { 199 setOperationAction(ISD::ADD, MVT::i32, Custom); 200 setOperationAction(ISD::SUB, MVT::i32, Custom); 201 setOperationAction(ISD::SHL, MVT::i32, Custom); 202 setOperationAction(ISD::SRA, MVT::i32, Custom); 203 setOperationAction(ISD::SRL, MVT::i32, Custom); 204 205 setOperationAction(ISD::UADDO, MVT::i32, Custom); 206 setOperationAction(ISD::USUBO, MVT::i32, Custom); 207 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 208 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 209 } else { 210 setLibcallName(RTLIB::SHL_I128, nullptr); 211 setLibcallName(RTLIB::SRL_I128, nullptr); 212 setLibcallName(RTLIB::SRA_I128, nullptr); 213 setLibcallName(RTLIB::MUL_I128, nullptr); 214 setLibcallName(RTLIB::MULO_I64, nullptr); 215 } 216 217 if (!Subtarget.hasStdExtM()) { 218 setOperationAction(ISD::MUL, XLenVT, Expand); 219 setOperationAction(ISD::MULHS, XLenVT, Expand); 220 setOperationAction(ISD::MULHU, XLenVT, Expand); 221 setOperationAction(ISD::SDIV, XLenVT, Expand); 222 setOperationAction(ISD::UDIV, XLenVT, Expand); 223 setOperationAction(ISD::SREM, XLenVT, Expand); 224 setOperationAction(ISD::UREM, XLenVT, Expand); 225 } else { 226 if (Subtarget.is64Bit()) { 227 setOperationAction(ISD::MUL, MVT::i32, Custom); 228 setOperationAction(ISD::MUL, MVT::i128, Custom); 229 230 setOperationAction(ISD::SDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UDIV, MVT::i8, Custom); 232 setOperationAction(ISD::UREM, MVT::i8, Custom); 233 setOperationAction(ISD::SDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UDIV, MVT::i16, Custom); 235 setOperationAction(ISD::UREM, MVT::i16, Custom); 236 setOperationAction(ISD::SDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UDIV, MVT::i32, Custom); 238 setOperationAction(ISD::UREM, MVT::i32, Custom); 239 } else { 240 setOperationAction(ISD::MUL, MVT::i64, Custom); 241 } 242 } 243 244 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 246 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 247 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 248 249 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 251 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 252 253 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 254 Subtarget.hasStdExtZbkb()) { 255 if (Subtarget.is64Bit()) { 256 setOperationAction(ISD::ROTL, MVT::i32, Custom); 257 setOperationAction(ISD::ROTR, MVT::i32, Custom); 258 } 259 } else { 260 setOperationAction(ISD::ROTL, XLenVT, Expand); 261 setOperationAction(ISD::ROTR, XLenVT, Expand); 262 } 263 264 if (Subtarget.hasStdExtZbp()) { 265 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 266 // more combining. 267 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 268 setOperationAction(ISD::BSWAP, XLenVT, Custom); 269 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 270 // BSWAP i8 doesn't exist. 271 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 272 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 273 274 if (Subtarget.is64Bit()) { 275 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 276 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 277 } 278 } else { 279 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 280 // pattern match it directly in isel. 281 setOperationAction(ISD::BSWAP, XLenVT, 282 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 283 ? Legal 284 : Expand); 285 // Zbkb can use rev8+brev8 to implement bitreverse. 286 setOperationAction(ISD::BITREVERSE, XLenVT, 287 Subtarget.hasStdExtZbkb() ? Custom : Expand); 288 } 289 290 if (Subtarget.hasStdExtZbb()) { 291 setOperationAction(ISD::SMIN, XLenVT, Legal); 292 setOperationAction(ISD::SMAX, XLenVT, Legal); 293 setOperationAction(ISD::UMIN, XLenVT, Legal); 294 setOperationAction(ISD::UMAX, XLenVT, Legal); 295 296 if (Subtarget.is64Bit()) { 297 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 298 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 299 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 300 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 301 } 302 } else { 303 setOperationAction(ISD::CTTZ, XLenVT, Expand); 304 setOperationAction(ISD::CTLZ, XLenVT, Expand); 305 setOperationAction(ISD::CTPOP, XLenVT, Expand); 306 } 307 308 if (Subtarget.hasStdExtZbt()) { 309 setOperationAction(ISD::FSHL, XLenVT, Custom); 310 setOperationAction(ISD::FSHR, XLenVT, Custom); 311 setOperationAction(ISD::SELECT, XLenVT, Legal); 312 313 if (Subtarget.is64Bit()) { 314 setOperationAction(ISD::FSHL, MVT::i32, Custom); 315 setOperationAction(ISD::FSHR, MVT::i32, Custom); 316 } 317 } else { 318 setOperationAction(ISD::SELECT, XLenVT, Custom); 319 } 320 321 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 322 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 323 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 324 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 325 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 326 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 327 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 328 329 static const ISD::CondCode FPCCToExpand[] = { 330 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 331 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 332 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 333 334 static const ISD::NodeType FPOpToExpand[] = { 335 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 336 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 337 338 if (Subtarget.hasStdExtZfh()) 339 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 340 341 if (Subtarget.hasStdExtZfh()) { 342 for (auto NT : FPLegalNodeTypes) 343 setOperationAction(NT, MVT::f16, Legal); 344 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 345 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 346 for (auto CC : FPCCToExpand) 347 setCondCodeAction(CC, MVT::f16, Expand); 348 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 349 setOperationAction(ISD::SELECT, MVT::f16, Custom); 350 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 351 352 setOperationAction(ISD::FREM, MVT::f16, Promote); 353 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 354 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 355 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 356 setOperationAction(ISD::FRINT, MVT::f16, Promote); 357 setOperationAction(ISD::FROUND, MVT::f16, Promote); 358 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 359 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 360 setOperationAction(ISD::FPOW, MVT::f16, Promote); 361 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 362 setOperationAction(ISD::FCOS, MVT::f16, Promote); 363 setOperationAction(ISD::FSIN, MVT::f16, Promote); 364 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 365 setOperationAction(ISD::FEXP, MVT::f16, Promote); 366 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 367 setOperationAction(ISD::FLOG, MVT::f16, Promote); 368 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 369 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 370 371 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 372 // complete support for all operations in LegalizeDAG. 373 374 // We need to custom promote this. 375 if (Subtarget.is64Bit()) 376 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 377 } 378 379 if (Subtarget.hasStdExtF()) { 380 for (auto NT : FPLegalNodeTypes) 381 setOperationAction(NT, MVT::f32, Legal); 382 for (auto CC : FPCCToExpand) 383 setCondCodeAction(CC, MVT::f32, Expand); 384 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 385 setOperationAction(ISD::SELECT, MVT::f32, Custom); 386 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 387 for (auto Op : FPOpToExpand) 388 setOperationAction(Op, MVT::f32, Expand); 389 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 390 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 391 } 392 393 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 394 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 395 396 if (Subtarget.hasStdExtD()) { 397 for (auto NT : FPLegalNodeTypes) 398 setOperationAction(NT, MVT::f64, Legal); 399 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 400 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 401 for (auto CC : FPCCToExpand) 402 setCondCodeAction(CC, MVT::f64, Expand); 403 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 404 setOperationAction(ISD::SELECT, MVT::f64, Custom); 405 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 406 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 407 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 408 for (auto Op : FPOpToExpand) 409 setOperationAction(Op, MVT::f64, Expand); 410 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 411 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 412 } 413 414 if (Subtarget.is64Bit()) { 415 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 416 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 417 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 418 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 419 } 420 421 if (Subtarget.hasStdExtF()) { 422 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 423 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 424 425 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 426 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 427 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 428 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 429 430 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 431 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 432 } 433 434 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 435 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 436 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 437 setOperationAction(ISD::JumpTable, XLenVT, Custom); 438 439 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 440 441 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 442 // Unfortunately this can't be determined just from the ISA naming string. 443 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 444 Subtarget.is64Bit() ? Legal : Custom); 445 446 setOperationAction(ISD::TRAP, MVT::Other, Legal); 447 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 448 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 449 if (Subtarget.is64Bit()) 450 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 451 452 if (Subtarget.hasStdExtA()) { 453 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 454 setMinCmpXchgSizeInBits(32); 455 } else { 456 setMaxAtomicSizeInBitsSupported(0); 457 } 458 459 setBooleanContents(ZeroOrOneBooleanContent); 460 461 if (Subtarget.hasVInstructions()) { 462 setBooleanVectorContents(ZeroOrOneBooleanContent); 463 464 setOperationAction(ISD::VSCALE, XLenVT, Custom); 465 466 // RVV intrinsics may have illegal operands. 467 // We also need to custom legalize vmv.x.s. 468 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 469 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 470 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 471 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 472 if (Subtarget.is64Bit()) { 473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 474 } else { 475 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 476 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 477 } 478 479 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 480 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 481 482 static const unsigned IntegerVPOps[] = { 483 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 484 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 485 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 486 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 487 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 488 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 489 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 490 ISD::VP_MERGE, ISD::VP_SELECT}; 491 492 static const unsigned FloatingPointVPOps[] = { 493 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 494 ISD::VP_FDIV, ISD::VP_FNEG, ISD::VP_FMA, 495 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN, 496 ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, ISD::VP_SELECT}; 497 498 if (!Subtarget.is64Bit()) { 499 // We must custom-lower certain vXi64 operations on RV32 due to the vector 500 // element type being illegal. 501 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 502 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 503 504 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 505 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 506 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 507 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 508 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 509 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 510 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 511 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 512 513 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 514 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 515 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 516 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 517 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 518 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 519 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 520 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 521 } 522 523 for (MVT VT : BoolVecVTs) { 524 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 525 526 // Mask VTs are custom-expanded into a series of standard nodes 527 setOperationAction(ISD::TRUNCATE, VT, Custom); 528 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 529 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 530 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 531 532 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 533 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 534 535 setOperationAction(ISD::SELECT, VT, Custom); 536 setOperationAction(ISD::SELECT_CC, VT, Expand); 537 setOperationAction(ISD::VSELECT, VT, Expand); 538 setOperationAction(ISD::VP_MERGE, VT, Expand); 539 setOperationAction(ISD::VP_SELECT, VT, Expand); 540 541 setOperationAction(ISD::VP_AND, VT, Custom); 542 setOperationAction(ISD::VP_OR, VT, Custom); 543 setOperationAction(ISD::VP_XOR, VT, Custom); 544 545 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 546 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 547 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 548 549 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 550 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 551 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 552 553 // RVV has native int->float & float->int conversions where the 554 // element type sizes are within one power-of-two of each other. Any 555 // wider distances between type sizes have to be lowered as sequences 556 // which progressively narrow the gap in stages. 557 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 558 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 559 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 560 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 561 562 // Expand all extending loads to types larger than this, and truncating 563 // stores from types larger than this. 564 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 565 setTruncStoreAction(OtherVT, VT, Expand); 566 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 567 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 568 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 569 } 570 } 571 572 for (MVT VT : IntVecVTs) { 573 if (VT.getVectorElementType() == MVT::i64 && 574 !Subtarget.hasVInstructionsI64()) 575 continue; 576 577 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 578 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 579 580 // Vectors implement MULHS/MULHU. 581 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 582 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 583 584 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 585 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 586 setOperationAction(ISD::MULHU, VT, Expand); 587 setOperationAction(ISD::MULHS, VT, Expand); 588 } 589 590 setOperationAction(ISD::SMIN, VT, Legal); 591 setOperationAction(ISD::SMAX, VT, Legal); 592 setOperationAction(ISD::UMIN, VT, Legal); 593 setOperationAction(ISD::UMAX, VT, Legal); 594 595 setOperationAction(ISD::ROTL, VT, Expand); 596 setOperationAction(ISD::ROTR, VT, Expand); 597 598 setOperationAction(ISD::CTTZ, VT, Expand); 599 setOperationAction(ISD::CTLZ, VT, Expand); 600 setOperationAction(ISD::CTPOP, VT, Expand); 601 602 setOperationAction(ISD::BSWAP, VT, Expand); 603 604 // Custom-lower extensions and truncations from/to mask types. 605 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 606 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 607 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 608 609 // RVV has native int->float & float->int conversions where the 610 // element type sizes are within one power-of-two of each other. Any 611 // wider distances between type sizes have to be lowered as sequences 612 // which progressively narrow the gap in stages. 613 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 614 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 615 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 616 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 617 618 setOperationAction(ISD::SADDSAT, VT, Legal); 619 setOperationAction(ISD::UADDSAT, VT, Legal); 620 setOperationAction(ISD::SSUBSAT, VT, Legal); 621 setOperationAction(ISD::USUBSAT, VT, Legal); 622 623 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 624 // nodes which truncate by one power of two at a time. 625 setOperationAction(ISD::TRUNCATE, VT, Custom); 626 627 // Custom-lower insert/extract operations to simplify patterns. 628 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 629 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 630 631 // Custom-lower reduction operations to set up the corresponding custom 632 // nodes' operands. 633 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 634 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 635 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 636 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 637 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 638 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 639 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 640 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 641 642 for (unsigned VPOpc : IntegerVPOps) 643 setOperationAction(VPOpc, VT, Custom); 644 645 setOperationAction(ISD::LOAD, VT, Custom); 646 setOperationAction(ISD::STORE, VT, Custom); 647 648 setOperationAction(ISD::MLOAD, VT, Custom); 649 setOperationAction(ISD::MSTORE, VT, Custom); 650 setOperationAction(ISD::MGATHER, VT, Custom); 651 setOperationAction(ISD::MSCATTER, VT, Custom); 652 653 setOperationAction(ISD::VP_LOAD, VT, Custom); 654 setOperationAction(ISD::VP_STORE, VT, Custom); 655 setOperationAction(ISD::VP_GATHER, VT, Custom); 656 setOperationAction(ISD::VP_SCATTER, VT, Custom); 657 658 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 659 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 660 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 661 662 setOperationAction(ISD::SELECT, VT, Custom); 663 setOperationAction(ISD::SELECT_CC, VT, Expand); 664 665 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 666 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 667 668 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 669 setTruncStoreAction(VT, OtherVT, Expand); 670 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 671 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 672 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 673 } 674 675 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 676 // type that can represent the value exactly. 677 if (VT.getVectorElementType() != MVT::i64) { 678 MVT FloatEltVT = 679 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 680 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 681 if (isTypeLegal(FloatVT)) { 682 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 683 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 684 } 685 } 686 } 687 688 // Expand various CCs to best match the RVV ISA, which natively supports UNE 689 // but no other unordered comparisons, and supports all ordered comparisons 690 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 691 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 692 // and we pattern-match those back to the "original", swapping operands once 693 // more. This way we catch both operations and both "vf" and "fv" forms with 694 // fewer patterns. 695 static const ISD::CondCode VFPCCToExpand[] = { 696 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 697 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 698 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 699 }; 700 701 // Sets common operation actions on RVV floating-point vector types. 702 const auto SetCommonVFPActions = [&](MVT VT) { 703 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 704 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 705 // sizes are within one power-of-two of each other. Therefore conversions 706 // between vXf16 and vXf64 must be lowered as sequences which convert via 707 // vXf32. 708 setOperationAction(ISD::FP_ROUND, VT, Custom); 709 setOperationAction(ISD::FP_EXTEND, VT, Custom); 710 // Custom-lower insert/extract operations to simplify patterns. 711 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 712 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 713 // Expand various condition codes (explained above). 714 for (auto CC : VFPCCToExpand) 715 setCondCodeAction(CC, VT, Expand); 716 717 setOperationAction(ISD::FMINNUM, VT, Legal); 718 setOperationAction(ISD::FMAXNUM, VT, Legal); 719 720 setOperationAction(ISD::FTRUNC, VT, Custom); 721 setOperationAction(ISD::FCEIL, VT, Custom); 722 setOperationAction(ISD::FFLOOR, VT, Custom); 723 setOperationAction(ISD::FROUND, VT, Custom); 724 725 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 726 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 727 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 728 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 729 730 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 731 732 setOperationAction(ISD::LOAD, VT, Custom); 733 setOperationAction(ISD::STORE, VT, Custom); 734 735 setOperationAction(ISD::MLOAD, VT, Custom); 736 setOperationAction(ISD::MSTORE, VT, Custom); 737 setOperationAction(ISD::MGATHER, VT, Custom); 738 setOperationAction(ISD::MSCATTER, VT, Custom); 739 740 setOperationAction(ISD::VP_LOAD, VT, Custom); 741 setOperationAction(ISD::VP_STORE, VT, Custom); 742 setOperationAction(ISD::VP_GATHER, VT, Custom); 743 setOperationAction(ISD::VP_SCATTER, VT, Custom); 744 745 setOperationAction(ISD::SELECT, VT, Custom); 746 setOperationAction(ISD::SELECT_CC, VT, Expand); 747 748 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 749 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 750 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 751 752 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 753 754 for (unsigned VPOpc : FloatingPointVPOps) 755 setOperationAction(VPOpc, VT, Custom); 756 }; 757 758 // Sets common extload/truncstore actions on RVV floating-point vector 759 // types. 760 const auto SetCommonVFPExtLoadTruncStoreActions = 761 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 762 for (auto SmallVT : SmallerVTs) { 763 setTruncStoreAction(VT, SmallVT, Expand); 764 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 765 } 766 }; 767 768 if (Subtarget.hasVInstructionsF16()) 769 for (MVT VT : F16VecVTs) 770 SetCommonVFPActions(VT); 771 772 for (MVT VT : F32VecVTs) { 773 if (Subtarget.hasVInstructionsF32()) 774 SetCommonVFPActions(VT); 775 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 776 } 777 778 for (MVT VT : F64VecVTs) { 779 if (Subtarget.hasVInstructionsF64()) 780 SetCommonVFPActions(VT); 781 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 782 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 783 } 784 785 if (Subtarget.useRVVForFixedLengthVectors()) { 786 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 787 if (!useRVVForFixedLengthVectorVT(VT)) 788 continue; 789 790 // By default everything must be expanded. 791 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 792 setOperationAction(Op, VT, Expand); 793 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 794 setTruncStoreAction(VT, OtherVT, Expand); 795 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 796 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 797 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 798 } 799 800 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 801 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 802 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 803 804 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 805 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 806 807 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 808 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 809 810 setOperationAction(ISD::LOAD, VT, Custom); 811 setOperationAction(ISD::STORE, VT, Custom); 812 813 setOperationAction(ISD::SETCC, VT, Custom); 814 815 setOperationAction(ISD::SELECT, VT, Custom); 816 817 setOperationAction(ISD::TRUNCATE, VT, Custom); 818 819 setOperationAction(ISD::BITCAST, VT, Custom); 820 821 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 822 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 823 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 824 825 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 826 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 827 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 828 829 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 830 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 831 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 832 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 833 834 // Operations below are different for between masks and other vectors. 835 if (VT.getVectorElementType() == MVT::i1) { 836 setOperationAction(ISD::VP_AND, VT, Custom); 837 setOperationAction(ISD::VP_OR, VT, Custom); 838 setOperationAction(ISD::VP_XOR, VT, Custom); 839 setOperationAction(ISD::AND, VT, Custom); 840 setOperationAction(ISD::OR, VT, Custom); 841 setOperationAction(ISD::XOR, VT, Custom); 842 continue; 843 } 844 845 // Use SPLAT_VECTOR to prevent type legalization from destroying the 846 // splats when type legalizing i64 scalar on RV32. 847 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 848 // improvements first. 849 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 850 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 851 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 852 } 853 854 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 855 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 856 857 setOperationAction(ISD::MLOAD, VT, Custom); 858 setOperationAction(ISD::MSTORE, VT, Custom); 859 setOperationAction(ISD::MGATHER, VT, Custom); 860 setOperationAction(ISD::MSCATTER, VT, Custom); 861 862 setOperationAction(ISD::VP_LOAD, VT, Custom); 863 setOperationAction(ISD::VP_STORE, VT, Custom); 864 setOperationAction(ISD::VP_GATHER, VT, Custom); 865 setOperationAction(ISD::VP_SCATTER, VT, Custom); 866 867 setOperationAction(ISD::ADD, VT, Custom); 868 setOperationAction(ISD::MUL, VT, Custom); 869 setOperationAction(ISD::SUB, VT, Custom); 870 setOperationAction(ISD::AND, VT, Custom); 871 setOperationAction(ISD::OR, VT, Custom); 872 setOperationAction(ISD::XOR, VT, Custom); 873 setOperationAction(ISD::SDIV, VT, Custom); 874 setOperationAction(ISD::SREM, VT, Custom); 875 setOperationAction(ISD::UDIV, VT, Custom); 876 setOperationAction(ISD::UREM, VT, Custom); 877 setOperationAction(ISD::SHL, VT, Custom); 878 setOperationAction(ISD::SRA, VT, Custom); 879 setOperationAction(ISD::SRL, VT, Custom); 880 881 setOperationAction(ISD::SMIN, VT, Custom); 882 setOperationAction(ISD::SMAX, VT, Custom); 883 setOperationAction(ISD::UMIN, VT, Custom); 884 setOperationAction(ISD::UMAX, VT, Custom); 885 setOperationAction(ISD::ABS, VT, Custom); 886 887 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 888 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 889 setOperationAction(ISD::MULHS, VT, Custom); 890 setOperationAction(ISD::MULHU, VT, Custom); 891 } 892 893 setOperationAction(ISD::SADDSAT, VT, Custom); 894 setOperationAction(ISD::UADDSAT, VT, Custom); 895 setOperationAction(ISD::SSUBSAT, VT, Custom); 896 setOperationAction(ISD::USUBSAT, VT, Custom); 897 898 setOperationAction(ISD::VSELECT, VT, Custom); 899 setOperationAction(ISD::SELECT_CC, VT, Expand); 900 901 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 902 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 903 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 904 905 // Custom-lower reduction operations to set up the corresponding custom 906 // nodes' operands. 907 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 908 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 909 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 910 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 911 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 912 913 for (unsigned VPOpc : IntegerVPOps) 914 setOperationAction(VPOpc, VT, Custom); 915 916 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 917 // type that can represent the value exactly. 918 if (VT.getVectorElementType() != MVT::i64) { 919 MVT FloatEltVT = 920 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 921 EVT FloatVT = 922 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 923 if (isTypeLegal(FloatVT)) { 924 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 925 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 926 } 927 } 928 } 929 930 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 931 if (!useRVVForFixedLengthVectorVT(VT)) 932 continue; 933 934 // By default everything must be expanded. 935 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 936 setOperationAction(Op, VT, Expand); 937 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 938 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 939 setTruncStoreAction(VT, OtherVT, Expand); 940 } 941 942 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 943 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 944 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 945 946 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 947 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 948 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 949 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 950 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 951 952 setOperationAction(ISD::LOAD, VT, Custom); 953 setOperationAction(ISD::STORE, VT, Custom); 954 setOperationAction(ISD::MLOAD, VT, Custom); 955 setOperationAction(ISD::MSTORE, VT, Custom); 956 setOperationAction(ISD::MGATHER, VT, Custom); 957 setOperationAction(ISD::MSCATTER, VT, Custom); 958 959 setOperationAction(ISD::VP_LOAD, VT, Custom); 960 setOperationAction(ISD::VP_STORE, VT, Custom); 961 setOperationAction(ISD::VP_GATHER, VT, Custom); 962 setOperationAction(ISD::VP_SCATTER, VT, Custom); 963 964 setOperationAction(ISD::FADD, VT, Custom); 965 setOperationAction(ISD::FSUB, VT, Custom); 966 setOperationAction(ISD::FMUL, VT, Custom); 967 setOperationAction(ISD::FDIV, VT, Custom); 968 setOperationAction(ISD::FNEG, VT, Custom); 969 setOperationAction(ISD::FABS, VT, Custom); 970 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 971 setOperationAction(ISD::FSQRT, VT, Custom); 972 setOperationAction(ISD::FMA, VT, Custom); 973 setOperationAction(ISD::FMINNUM, VT, Custom); 974 setOperationAction(ISD::FMAXNUM, VT, Custom); 975 976 setOperationAction(ISD::FP_ROUND, VT, Custom); 977 setOperationAction(ISD::FP_EXTEND, VT, Custom); 978 979 setOperationAction(ISD::FTRUNC, VT, Custom); 980 setOperationAction(ISD::FCEIL, VT, Custom); 981 setOperationAction(ISD::FFLOOR, VT, Custom); 982 setOperationAction(ISD::FROUND, VT, Custom); 983 984 for (auto CC : VFPCCToExpand) 985 setCondCodeAction(CC, VT, Expand); 986 987 setOperationAction(ISD::VSELECT, VT, Custom); 988 setOperationAction(ISD::SELECT, VT, Custom); 989 setOperationAction(ISD::SELECT_CC, VT, Expand); 990 991 setOperationAction(ISD::BITCAST, VT, Custom); 992 993 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 994 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 995 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 996 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 997 998 for (unsigned VPOpc : FloatingPointVPOps) 999 setOperationAction(VPOpc, VT, Custom); 1000 } 1001 1002 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1003 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1004 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1005 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1006 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1007 if (Subtarget.hasStdExtZfh()) 1008 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1009 if (Subtarget.hasStdExtF()) 1010 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1011 if (Subtarget.hasStdExtD()) 1012 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1013 } 1014 } 1015 1016 // Function alignments. 1017 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1018 setMinFunctionAlignment(FunctionAlignment); 1019 setPrefFunctionAlignment(FunctionAlignment); 1020 1021 setMinimumJumpTableEntries(5); 1022 1023 // Jumps are expensive, compared to logic 1024 setJumpIsExpensive(); 1025 1026 setTargetDAGCombine(ISD::ADD); 1027 setTargetDAGCombine(ISD::SUB); 1028 setTargetDAGCombine(ISD::AND); 1029 setTargetDAGCombine(ISD::OR); 1030 setTargetDAGCombine(ISD::XOR); 1031 setTargetDAGCombine(ISD::ROTL); 1032 setTargetDAGCombine(ISD::ROTR); 1033 setTargetDAGCombine(ISD::ANY_EXTEND); 1034 if (Subtarget.hasStdExtZfh()) 1035 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 1036 if (Subtarget.hasStdExtF()) { 1037 setTargetDAGCombine(ISD::ZERO_EXTEND); 1038 setTargetDAGCombine(ISD::FP_TO_SINT); 1039 setTargetDAGCombine(ISD::FP_TO_UINT); 1040 setTargetDAGCombine(ISD::FP_TO_SINT_SAT); 1041 setTargetDAGCombine(ISD::FP_TO_UINT_SAT); 1042 } 1043 if (Subtarget.hasVInstructions()) { 1044 setTargetDAGCombine(ISD::FCOPYSIGN); 1045 setTargetDAGCombine(ISD::MGATHER); 1046 setTargetDAGCombine(ISD::MSCATTER); 1047 setTargetDAGCombine(ISD::VP_GATHER); 1048 setTargetDAGCombine(ISD::VP_SCATTER); 1049 setTargetDAGCombine(ISD::SRA); 1050 setTargetDAGCombine(ISD::SRL); 1051 setTargetDAGCombine(ISD::SHL); 1052 setTargetDAGCombine(ISD::STORE); 1053 setTargetDAGCombine(ISD::SPLAT_VECTOR); 1054 } 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 } 1120 } 1121 1122 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1123 const AddrMode &AM, Type *Ty, 1124 unsigned AS, 1125 Instruction *I) const { 1126 // No global is ever allowed as a base. 1127 if (AM.BaseGV) 1128 return false; 1129 1130 // Require a 12-bit signed offset. 1131 if (!isInt<12>(AM.BaseOffs)) 1132 return false; 1133 1134 switch (AM.Scale) { 1135 case 0: // "r+i" or just "i", depending on HasBaseReg. 1136 break; 1137 case 1: 1138 if (!AM.HasBaseReg) // allow "r+i". 1139 break; 1140 return false; // disallow "r+r" or "r+r+i". 1141 default: 1142 return false; 1143 } 1144 1145 return true; 1146 } 1147 1148 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1149 return isInt<12>(Imm); 1150 } 1151 1152 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1153 return isInt<12>(Imm); 1154 } 1155 1156 // On RV32, 64-bit integers are split into their high and low parts and held 1157 // in two different registers, so the trunc is free since the low register can 1158 // just be used. 1159 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1160 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1161 return false; 1162 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1163 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1164 return (SrcBits == 64 && DestBits == 32); 1165 } 1166 1167 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1168 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1169 !SrcVT.isInteger() || !DstVT.isInteger()) 1170 return false; 1171 unsigned SrcBits = SrcVT.getSizeInBits(); 1172 unsigned DestBits = DstVT.getSizeInBits(); 1173 return (SrcBits == 64 && DestBits == 32); 1174 } 1175 1176 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1177 // Zexts are free if they can be combined with a load. 1178 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1179 // poorly with type legalization of compares preferring sext. 1180 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1181 EVT MemVT = LD->getMemoryVT(); 1182 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1183 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1184 LD->getExtensionType() == ISD::ZEXTLOAD)) 1185 return true; 1186 } 1187 1188 return TargetLowering::isZExtFree(Val, VT2); 1189 } 1190 1191 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1192 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1193 } 1194 1195 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1196 return Subtarget.hasStdExtZbb(); 1197 } 1198 1199 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1200 return Subtarget.hasStdExtZbb(); 1201 } 1202 1203 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1204 EVT VT = Y.getValueType(); 1205 1206 // FIXME: Support vectors once we have tests. 1207 if (VT.isVector()) 1208 return false; 1209 1210 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1211 Subtarget.hasStdExtZbkb()) && 1212 !isa<ConstantSDNode>(Y); 1213 } 1214 1215 /// Check if sinking \p I's operands to I's basic block is profitable, because 1216 /// the operands can be folded into a target instruction, e.g. 1217 /// splats of scalars can fold into vector instructions. 1218 bool RISCVTargetLowering::shouldSinkOperands( 1219 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1220 using namespace llvm::PatternMatch; 1221 1222 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1223 return false; 1224 1225 auto IsSinker = [&](Instruction *I, int Operand) { 1226 switch (I->getOpcode()) { 1227 case Instruction::Add: 1228 case Instruction::Sub: 1229 case Instruction::Mul: 1230 case Instruction::And: 1231 case Instruction::Or: 1232 case Instruction::Xor: 1233 case Instruction::FAdd: 1234 case Instruction::FSub: 1235 case Instruction::FMul: 1236 case Instruction::FDiv: 1237 case Instruction::ICmp: 1238 case Instruction::FCmp: 1239 return true; 1240 case Instruction::Shl: 1241 case Instruction::LShr: 1242 case Instruction::AShr: 1243 case Instruction::UDiv: 1244 case Instruction::SDiv: 1245 case Instruction::URem: 1246 case Instruction::SRem: 1247 return Operand == 1; 1248 case Instruction::Call: 1249 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1250 switch (II->getIntrinsicID()) { 1251 case Intrinsic::fma: 1252 case Intrinsic::vp_fma: 1253 return Operand == 0 || Operand == 1; 1254 // FIXME: Our patterns can only match vx/vf instructions when the splat 1255 // it on the RHS, because TableGen doesn't recognize our VP operations 1256 // as commutative. 1257 case Intrinsic::vp_add: 1258 case Intrinsic::vp_mul: 1259 case Intrinsic::vp_and: 1260 case Intrinsic::vp_or: 1261 case Intrinsic::vp_xor: 1262 case Intrinsic::vp_fadd: 1263 case Intrinsic::vp_fmul: 1264 case Intrinsic::vp_shl: 1265 case Intrinsic::vp_lshr: 1266 case Intrinsic::vp_ashr: 1267 case Intrinsic::vp_udiv: 1268 case Intrinsic::vp_sdiv: 1269 case Intrinsic::vp_urem: 1270 case Intrinsic::vp_srem: 1271 return Operand == 1; 1272 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1273 // explicit patterns for both LHS and RHS (as 'vr' versions). 1274 case Intrinsic::vp_sub: 1275 case Intrinsic::vp_fsub: 1276 case Intrinsic::vp_fdiv: 1277 return Operand == 0 || Operand == 1; 1278 default: 1279 return false; 1280 } 1281 } 1282 return false; 1283 default: 1284 return false; 1285 } 1286 }; 1287 1288 for (auto OpIdx : enumerate(I->operands())) { 1289 if (!IsSinker(I, OpIdx.index())) 1290 continue; 1291 1292 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1293 // Make sure we are not already sinking this operand 1294 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1295 continue; 1296 1297 // We are looking for a splat that can be sunk. 1298 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1299 m_Undef(), m_ZeroMask()))) 1300 continue; 1301 1302 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1303 // and vector registers 1304 for (Use &U : Op->uses()) { 1305 Instruction *Insn = cast<Instruction>(U.getUser()); 1306 if (!IsSinker(Insn, U.getOperandNo())) 1307 return false; 1308 } 1309 1310 Ops.push_back(&Op->getOperandUse(0)); 1311 Ops.push_back(&OpIdx.value()); 1312 } 1313 return true; 1314 } 1315 1316 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1317 bool ForCodeSize) const { 1318 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1319 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1320 return false; 1321 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1322 return false; 1323 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1324 return false; 1325 return Imm.isZero(); 1326 } 1327 1328 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1329 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1330 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1331 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1332 } 1333 1334 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1335 CallingConv::ID CC, 1336 EVT VT) const { 1337 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1338 // We might still end up using a GPR but that will be decided based on ABI. 1339 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1340 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1341 return MVT::f32; 1342 1343 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1344 } 1345 1346 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1347 CallingConv::ID CC, 1348 EVT VT) const { 1349 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1350 // We might still end up using a GPR but that will be decided based on ABI. 1351 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1352 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1353 return 1; 1354 1355 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1356 } 1357 1358 // Changes the condition code and swaps operands if necessary, so the SetCC 1359 // operation matches one of the comparisons supported directly by branches 1360 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1361 // with 1/-1. 1362 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1363 ISD::CondCode &CC, SelectionDAG &DAG) { 1364 // Convert X > -1 to X >= 0. 1365 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1366 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1367 CC = ISD::SETGE; 1368 return; 1369 } 1370 // Convert X < 1 to 0 >= X. 1371 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1372 RHS = LHS; 1373 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1374 CC = ISD::SETGE; 1375 return; 1376 } 1377 1378 switch (CC) { 1379 default: 1380 break; 1381 case ISD::SETGT: 1382 case ISD::SETLE: 1383 case ISD::SETUGT: 1384 case ISD::SETULE: 1385 CC = ISD::getSetCCSwappedOperands(CC); 1386 std::swap(LHS, RHS); 1387 break; 1388 } 1389 } 1390 1391 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1392 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1393 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1394 if (VT.getVectorElementType() == MVT::i1) 1395 KnownSize *= 8; 1396 1397 switch (KnownSize) { 1398 default: 1399 llvm_unreachable("Invalid LMUL."); 1400 case 8: 1401 return RISCVII::VLMUL::LMUL_F8; 1402 case 16: 1403 return RISCVII::VLMUL::LMUL_F4; 1404 case 32: 1405 return RISCVII::VLMUL::LMUL_F2; 1406 case 64: 1407 return RISCVII::VLMUL::LMUL_1; 1408 case 128: 1409 return RISCVII::VLMUL::LMUL_2; 1410 case 256: 1411 return RISCVII::VLMUL::LMUL_4; 1412 case 512: 1413 return RISCVII::VLMUL::LMUL_8; 1414 } 1415 } 1416 1417 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1418 switch (LMul) { 1419 default: 1420 llvm_unreachable("Invalid LMUL."); 1421 case RISCVII::VLMUL::LMUL_F8: 1422 case RISCVII::VLMUL::LMUL_F4: 1423 case RISCVII::VLMUL::LMUL_F2: 1424 case RISCVII::VLMUL::LMUL_1: 1425 return RISCV::VRRegClassID; 1426 case RISCVII::VLMUL::LMUL_2: 1427 return RISCV::VRM2RegClassID; 1428 case RISCVII::VLMUL::LMUL_4: 1429 return RISCV::VRM4RegClassID; 1430 case RISCVII::VLMUL::LMUL_8: 1431 return RISCV::VRM8RegClassID; 1432 } 1433 } 1434 1435 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1436 RISCVII::VLMUL LMUL = getLMUL(VT); 1437 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1438 LMUL == RISCVII::VLMUL::LMUL_F4 || 1439 LMUL == RISCVII::VLMUL::LMUL_F2 || 1440 LMUL == RISCVII::VLMUL::LMUL_1) { 1441 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1442 "Unexpected subreg numbering"); 1443 return RISCV::sub_vrm1_0 + Index; 1444 } 1445 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1446 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1447 "Unexpected subreg numbering"); 1448 return RISCV::sub_vrm2_0 + Index; 1449 } 1450 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1451 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1452 "Unexpected subreg numbering"); 1453 return RISCV::sub_vrm4_0 + Index; 1454 } 1455 llvm_unreachable("Invalid vector type."); 1456 } 1457 1458 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1459 if (VT.getVectorElementType() == MVT::i1) 1460 return RISCV::VRRegClassID; 1461 return getRegClassIDForLMUL(getLMUL(VT)); 1462 } 1463 1464 // Attempt to decompose a subvector insert/extract between VecVT and 1465 // SubVecVT via subregister indices. Returns the subregister index that 1466 // can perform the subvector insert/extract with the given element index, as 1467 // well as the index corresponding to any leftover subvectors that must be 1468 // further inserted/extracted within the register class for SubVecVT. 1469 std::pair<unsigned, unsigned> 1470 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1471 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1472 const RISCVRegisterInfo *TRI) { 1473 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1474 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1475 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1476 "Register classes not ordered"); 1477 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1478 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1479 // Try to compose a subregister index that takes us from the incoming 1480 // LMUL>1 register class down to the outgoing one. At each step we half 1481 // the LMUL: 1482 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1483 // Note that this is not guaranteed to find a subregister index, such as 1484 // when we are extracting from one VR type to another. 1485 unsigned SubRegIdx = RISCV::NoSubRegister; 1486 for (const unsigned RCID : 1487 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1488 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1489 VecVT = VecVT.getHalfNumVectorElementsVT(); 1490 bool IsHi = 1491 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1492 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1493 getSubregIndexByMVT(VecVT, IsHi)); 1494 if (IsHi) 1495 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1496 } 1497 return {SubRegIdx, InsertExtractIdx}; 1498 } 1499 1500 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1501 // stores for those types. 1502 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1503 return !Subtarget.useRVVForFixedLengthVectors() || 1504 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1505 } 1506 1507 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1508 if (ScalarTy->isPointerTy()) 1509 return true; 1510 1511 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1512 ScalarTy->isIntegerTy(32)) 1513 return true; 1514 1515 if (ScalarTy->isIntegerTy(64)) 1516 return Subtarget.hasVInstructionsI64(); 1517 1518 if (ScalarTy->isHalfTy()) 1519 return Subtarget.hasVInstructionsF16(); 1520 if (ScalarTy->isFloatTy()) 1521 return Subtarget.hasVInstructionsF32(); 1522 if (ScalarTy->isDoubleTy()) 1523 return Subtarget.hasVInstructionsF64(); 1524 1525 return false; 1526 } 1527 1528 static SDValue getVLOperand(SDValue Op) { 1529 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1530 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1531 "Unexpected opcode"); 1532 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1533 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1534 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1535 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1536 if (!II) 1537 return SDValue(); 1538 return Op.getOperand(II->VLOperand + 1 + HasChain); 1539 } 1540 1541 static bool useRVVForFixedLengthVectorVT(MVT VT, 1542 const RISCVSubtarget &Subtarget) { 1543 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1544 if (!Subtarget.useRVVForFixedLengthVectors()) 1545 return false; 1546 1547 // We only support a set of vector types with a consistent maximum fixed size 1548 // across all supported vector element types to avoid legalization issues. 1549 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1550 // fixed-length vector type we support is 1024 bytes. 1551 if (VT.getFixedSizeInBits() > 1024 * 8) 1552 return false; 1553 1554 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1555 1556 MVT EltVT = VT.getVectorElementType(); 1557 1558 // Don't use RVV for vectors we cannot scalarize if required. 1559 switch (EltVT.SimpleTy) { 1560 // i1 is supported but has different rules. 1561 default: 1562 return false; 1563 case MVT::i1: 1564 // Masks can only use a single register. 1565 if (VT.getVectorNumElements() > MinVLen) 1566 return false; 1567 MinVLen /= 8; 1568 break; 1569 case MVT::i8: 1570 case MVT::i16: 1571 case MVT::i32: 1572 break; 1573 case MVT::i64: 1574 if (!Subtarget.hasVInstructionsI64()) 1575 return false; 1576 break; 1577 case MVT::f16: 1578 if (!Subtarget.hasVInstructionsF16()) 1579 return false; 1580 break; 1581 case MVT::f32: 1582 if (!Subtarget.hasVInstructionsF32()) 1583 return false; 1584 break; 1585 case MVT::f64: 1586 if (!Subtarget.hasVInstructionsF64()) 1587 return false; 1588 break; 1589 } 1590 1591 // Reject elements larger than ELEN. 1592 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1593 return false; 1594 1595 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1596 // Don't use RVV for types that don't fit. 1597 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1598 return false; 1599 1600 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1601 // the base fixed length RVV support in place. 1602 if (!VT.isPow2VectorType()) 1603 return false; 1604 1605 return true; 1606 } 1607 1608 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1609 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1610 } 1611 1612 // Return the largest legal scalable vector type that matches VT's element type. 1613 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1614 const RISCVSubtarget &Subtarget) { 1615 // This may be called before legal types are setup. 1616 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1617 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1618 "Expected legal fixed length vector!"); 1619 1620 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1621 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1622 1623 MVT EltVT = VT.getVectorElementType(); 1624 switch (EltVT.SimpleTy) { 1625 default: 1626 llvm_unreachable("unexpected element type for RVV container"); 1627 case MVT::i1: 1628 case MVT::i8: 1629 case MVT::i16: 1630 case MVT::i32: 1631 case MVT::i64: 1632 case MVT::f16: 1633 case MVT::f32: 1634 case MVT::f64: { 1635 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1636 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1637 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1638 unsigned NumElts = 1639 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1640 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1641 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1642 return MVT::getScalableVectorVT(EltVT, NumElts); 1643 } 1644 } 1645 } 1646 1647 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1648 const RISCVSubtarget &Subtarget) { 1649 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1650 Subtarget); 1651 } 1652 1653 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1654 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1655 } 1656 1657 // Grow V to consume an entire RVV register. 1658 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1659 const RISCVSubtarget &Subtarget) { 1660 assert(VT.isScalableVector() && 1661 "Expected to convert into a scalable vector!"); 1662 assert(V.getValueType().isFixedLengthVector() && 1663 "Expected a fixed length vector operand!"); 1664 SDLoc DL(V); 1665 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1666 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1667 } 1668 1669 // Shrink V so it's just big enough to maintain a VT's worth of data. 1670 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1671 const RISCVSubtarget &Subtarget) { 1672 assert(VT.isFixedLengthVector() && 1673 "Expected to convert into a fixed length vector!"); 1674 assert(V.getValueType().isScalableVector() && 1675 "Expected a scalable vector operand!"); 1676 SDLoc DL(V); 1677 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1678 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1679 } 1680 1681 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1682 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1683 // the vector type that it is contained in. 1684 static std::pair<SDValue, SDValue> 1685 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1686 const RISCVSubtarget &Subtarget) { 1687 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1688 MVT XLenVT = Subtarget.getXLenVT(); 1689 SDValue VL = VecVT.isFixedLengthVector() 1690 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1691 : DAG.getRegister(RISCV::X0, XLenVT); 1692 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1693 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1694 return {Mask, VL}; 1695 } 1696 1697 // As above but assuming the given type is a scalable vector type. 1698 static std::pair<SDValue, SDValue> 1699 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1700 const RISCVSubtarget &Subtarget) { 1701 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1702 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1703 } 1704 1705 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1706 // of either is (currently) supported. This can get us into an infinite loop 1707 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1708 // as a ..., etc. 1709 // Until either (or both) of these can reliably lower any node, reporting that 1710 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1711 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1712 // which is not desirable. 1713 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1714 EVT VT, unsigned DefinedValues) const { 1715 return false; 1716 } 1717 1718 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1719 const RISCVSubtarget &Subtarget) { 1720 // RISCV FP-to-int conversions saturate to the destination register size, but 1721 // don't produce 0 for nan. We can use a conversion instruction and fix the 1722 // nan case with a compare and a select. 1723 SDValue Src = Op.getOperand(0); 1724 1725 EVT DstVT = Op.getValueType(); 1726 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1727 1728 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1729 unsigned Opc; 1730 if (SatVT == DstVT) 1731 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1732 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1733 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1734 else 1735 return SDValue(); 1736 // FIXME: Support other SatVTs by clamping before or after the conversion. 1737 1738 SDLoc DL(Op); 1739 SDValue FpToInt = DAG.getNode( 1740 Opc, DL, DstVT, Src, 1741 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1742 1743 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1744 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1745 } 1746 1747 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1748 // and back. Taking care to avoid converting values that are nan or already 1749 // correct. 1750 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1751 // have FRM dependencies modeled yet. 1752 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1753 MVT VT = Op.getSimpleValueType(); 1754 assert(VT.isVector() && "Unexpected type"); 1755 1756 SDLoc DL(Op); 1757 1758 // Freeze the source since we are increasing the number of uses. 1759 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1760 1761 // Truncate to integer and convert back to FP. 1762 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1763 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1764 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1765 1766 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1767 1768 if (Op.getOpcode() == ISD::FCEIL) { 1769 // If the truncated value is the greater than or equal to the original 1770 // value, we've computed the ceil. Otherwise, we went the wrong way and 1771 // need to increase by 1. 1772 // FIXME: This should use a masked operation. Handle here or in isel? 1773 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1774 DAG.getConstantFP(1.0, DL, VT)); 1775 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1776 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1777 } else if (Op.getOpcode() == ISD::FFLOOR) { 1778 // If the truncated value is the less than or equal to the original value, 1779 // we've computed the floor. Otherwise, we went the wrong way and need to 1780 // decrease by 1. 1781 // FIXME: This should use a masked operation. Handle here or in isel? 1782 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1783 DAG.getConstantFP(1.0, DL, VT)); 1784 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1785 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1786 } 1787 1788 // Restore the original sign so that -0.0 is preserved. 1789 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1790 1791 // Determine the largest integer that can be represented exactly. This and 1792 // values larger than it don't have any fractional bits so don't need to 1793 // be converted. 1794 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1795 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1796 APFloat MaxVal = APFloat(FltSem); 1797 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1798 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1799 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1800 1801 // If abs(Src) was larger than MaxVal or nan, keep it. 1802 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1803 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1804 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1805 } 1806 1807 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1808 // This mode isn't supported in vector hardware on RISCV. But as long as we 1809 // aren't compiling with trapping math, we can emulate this with 1810 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1811 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1812 // dependencies modeled yet. 1813 // FIXME: Use masked operations to avoid final merge. 1814 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1815 MVT VT = Op.getSimpleValueType(); 1816 assert(VT.isVector() && "Unexpected type"); 1817 1818 SDLoc DL(Op); 1819 1820 // Freeze the source since we are increasing the number of uses. 1821 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1822 1823 // We do the conversion on the absolute value and fix the sign at the end. 1824 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1825 1826 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1827 bool Ignored; 1828 APFloat Point5Pred = APFloat(0.5f); 1829 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1830 Point5Pred.next(/*nextDown*/ true); 1831 1832 // Add the adjustment. 1833 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1834 DAG.getConstantFP(Point5Pred, DL, VT)); 1835 1836 // Truncate to integer and convert back to fp. 1837 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1838 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1839 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1840 1841 // Restore the original sign. 1842 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1843 1844 // Determine the largest integer that can be represented exactly. This and 1845 // values larger than it don't have any fractional bits so don't need to 1846 // be converted. 1847 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1848 APFloat MaxVal = APFloat(FltSem); 1849 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1850 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1851 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1852 1853 // If abs(Src) was larger than MaxVal or nan, keep it. 1854 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1855 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1856 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1857 } 1858 1859 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1860 const RISCVSubtarget &Subtarget) { 1861 MVT VT = Op.getSimpleValueType(); 1862 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1863 1864 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1865 1866 SDLoc DL(Op); 1867 SDValue Mask, VL; 1868 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1869 1870 unsigned Opc = 1871 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1872 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 1873 Op.getOperand(0), VL); 1874 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1875 } 1876 1877 struct VIDSequence { 1878 int64_t StepNumerator; 1879 unsigned StepDenominator; 1880 int64_t Addend; 1881 }; 1882 1883 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1884 // to the (non-zero) step S and start value X. This can be then lowered as the 1885 // RVV sequence (VID * S) + X, for example. 1886 // The step S is represented as an integer numerator divided by a positive 1887 // denominator. Note that the implementation currently only identifies 1888 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1889 // cannot detect 2/3, for example. 1890 // Note that this method will also match potentially unappealing index 1891 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1892 // determine whether this is worth generating code for. 1893 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1894 unsigned NumElts = Op.getNumOperands(); 1895 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1896 if (!Op.getValueType().isInteger()) 1897 return None; 1898 1899 Optional<unsigned> SeqStepDenom; 1900 Optional<int64_t> SeqStepNum, SeqAddend; 1901 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1902 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1903 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1904 // Assume undef elements match the sequence; we just have to be careful 1905 // when interpolating across them. 1906 if (Op.getOperand(Idx).isUndef()) 1907 continue; 1908 // The BUILD_VECTOR must be all constants. 1909 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1910 return None; 1911 1912 uint64_t Val = Op.getConstantOperandVal(Idx) & 1913 maskTrailingOnes<uint64_t>(EltSizeInBits); 1914 1915 if (PrevElt) { 1916 // Calculate the step since the last non-undef element, and ensure 1917 // it's consistent across the entire sequence. 1918 unsigned IdxDiff = Idx - PrevElt->second; 1919 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1920 1921 // A zero-value value difference means that we're somewhere in the middle 1922 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1923 // step change before evaluating the sequence. 1924 if (ValDiff != 0) { 1925 int64_t Remainder = ValDiff % IdxDiff; 1926 // Normalize the step if it's greater than 1. 1927 if (Remainder != ValDiff) { 1928 // The difference must cleanly divide the element span. 1929 if (Remainder != 0) 1930 return None; 1931 ValDiff /= IdxDiff; 1932 IdxDiff = 1; 1933 } 1934 1935 if (!SeqStepNum) 1936 SeqStepNum = ValDiff; 1937 else if (ValDiff != SeqStepNum) 1938 return None; 1939 1940 if (!SeqStepDenom) 1941 SeqStepDenom = IdxDiff; 1942 else if (IdxDiff != *SeqStepDenom) 1943 return None; 1944 } 1945 } 1946 1947 // Record and/or check any addend. 1948 if (SeqStepNum && SeqStepDenom) { 1949 uint64_t ExpectedVal = 1950 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1951 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1952 if (!SeqAddend) 1953 SeqAddend = Addend; 1954 else if (SeqAddend != Addend) 1955 return None; 1956 } 1957 1958 // Record this non-undef element for later. 1959 if (!PrevElt || PrevElt->first != Val) 1960 PrevElt = std::make_pair(Val, Idx); 1961 } 1962 // We need to have logged both a step and an addend for this to count as 1963 // a legal index sequence. 1964 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1965 return None; 1966 1967 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1968 } 1969 1970 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1971 // and lower it as a VRGATHER_VX_VL from the source vector. 1972 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1973 SelectionDAG &DAG, 1974 const RISCVSubtarget &Subtarget) { 1975 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1976 return SDValue(); 1977 SDValue Vec = SplatVal.getOperand(0); 1978 // Only perform this optimization on vectors of the same size for simplicity. 1979 if (Vec.getValueType() != VT) 1980 return SDValue(); 1981 SDValue Idx = SplatVal.getOperand(1); 1982 // The index must be a legal type. 1983 if (Idx.getValueType() != Subtarget.getXLenVT()) 1984 return SDValue(); 1985 1986 MVT ContainerVT = VT; 1987 if (VT.isFixedLengthVector()) { 1988 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1989 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1990 } 1991 1992 SDValue Mask, VL; 1993 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1994 1995 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 1996 Idx, Mask, VL); 1997 1998 if (!VT.isFixedLengthVector()) 1999 return Gather; 2000 2001 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2002 } 2003 2004 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2005 const RISCVSubtarget &Subtarget) { 2006 MVT VT = Op.getSimpleValueType(); 2007 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2008 2009 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2010 2011 SDLoc DL(Op); 2012 SDValue Mask, VL; 2013 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2014 2015 MVT XLenVT = Subtarget.getXLenVT(); 2016 unsigned NumElts = Op.getNumOperands(); 2017 2018 if (VT.getVectorElementType() == MVT::i1) { 2019 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2020 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2021 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2022 } 2023 2024 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2025 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2026 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2027 } 2028 2029 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2030 // scalar integer chunks whose bit-width depends on the number of mask 2031 // bits and XLEN. 2032 // First, determine the most appropriate scalar integer type to use. This 2033 // is at most XLenVT, but may be shrunk to a smaller vector element type 2034 // according to the size of the final vector - use i8 chunks rather than 2035 // XLenVT if we're producing a v8i1. This results in more consistent 2036 // codegen across RV32 and RV64. 2037 unsigned NumViaIntegerBits = 2038 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2039 NumViaIntegerBits = std::min(NumViaIntegerBits, 2040 Subtarget.getMaxELENForFixedLengthVectors()); 2041 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2042 // If we have to use more than one INSERT_VECTOR_ELT then this 2043 // optimization is likely to increase code size; avoid peforming it in 2044 // such a case. We can use a load from a constant pool in this case. 2045 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2046 return SDValue(); 2047 // Now we can create our integer vector type. Note that it may be larger 2048 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2049 MVT IntegerViaVecVT = 2050 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2051 divideCeil(NumElts, NumViaIntegerBits)); 2052 2053 uint64_t Bits = 0; 2054 unsigned BitPos = 0, IntegerEltIdx = 0; 2055 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2056 2057 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2058 // Once we accumulate enough bits to fill our scalar type, insert into 2059 // our vector and clear our accumulated data. 2060 if (I != 0 && I % NumViaIntegerBits == 0) { 2061 if (NumViaIntegerBits <= 32) 2062 Bits = SignExtend64(Bits, 32); 2063 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2064 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2065 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2066 Bits = 0; 2067 BitPos = 0; 2068 IntegerEltIdx++; 2069 } 2070 SDValue V = Op.getOperand(I); 2071 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2072 Bits |= ((uint64_t)BitValue << BitPos); 2073 } 2074 2075 // Insert the (remaining) scalar value into position in our integer 2076 // vector type. 2077 if (NumViaIntegerBits <= 32) 2078 Bits = SignExtend64(Bits, 32); 2079 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2080 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2081 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2082 2083 if (NumElts < NumViaIntegerBits) { 2084 // If we're producing a smaller vector than our minimum legal integer 2085 // type, bitcast to the equivalent (known-legal) mask type, and extract 2086 // our final mask. 2087 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2088 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2089 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2090 DAG.getConstant(0, DL, XLenVT)); 2091 } else { 2092 // Else we must have produced an integer type with the same size as the 2093 // mask type; bitcast for the final result. 2094 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2095 Vec = DAG.getBitcast(VT, Vec); 2096 } 2097 2098 return Vec; 2099 } 2100 2101 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2102 // vector type, we have a legal equivalently-sized i8 type, so we can use 2103 // that. 2104 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2105 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2106 2107 SDValue WideVec; 2108 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2109 // For a splat, perform a scalar truncate before creating the wider 2110 // vector. 2111 assert(Splat.getValueType() == XLenVT && 2112 "Unexpected type for i1 splat value"); 2113 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2114 DAG.getConstant(1, DL, XLenVT)); 2115 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2116 } else { 2117 SmallVector<SDValue, 8> Ops(Op->op_values()); 2118 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2119 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2120 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2121 } 2122 2123 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2124 } 2125 2126 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2127 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2128 return Gather; 2129 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2130 : RISCVISD::VMV_V_X_VL; 2131 Splat = 2132 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2133 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2134 } 2135 2136 // Try and match index sequences, which we can lower to the vid instruction 2137 // with optional modifications. An all-undef vector is matched by 2138 // getSplatValue, above. 2139 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2140 int64_t StepNumerator = SimpleVID->StepNumerator; 2141 unsigned StepDenominator = SimpleVID->StepDenominator; 2142 int64_t Addend = SimpleVID->Addend; 2143 2144 assert(StepNumerator != 0 && "Invalid step"); 2145 bool Negate = false; 2146 int64_t SplatStepVal = StepNumerator; 2147 unsigned StepOpcode = ISD::MUL; 2148 if (StepNumerator != 1) { 2149 if (isPowerOf2_64(std::abs(StepNumerator))) { 2150 Negate = StepNumerator < 0; 2151 StepOpcode = ISD::SHL; 2152 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2153 } 2154 } 2155 2156 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2157 // threshold since it's the immediate value many RVV instructions accept. 2158 // There is no vmul.vi instruction so ensure multiply constant can fit in 2159 // a single addi instruction. 2160 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2161 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2162 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2163 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2164 // Convert right out of the scalable type so we can use standard ISD 2165 // nodes for the rest of the computation. If we used scalable types with 2166 // these, we'd lose the fixed-length vector info and generate worse 2167 // vsetvli code. 2168 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2169 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2170 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2171 SDValue SplatStep = DAG.getSplatVector( 2172 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2173 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2174 } 2175 if (StepDenominator != 1) { 2176 SDValue SplatStep = DAG.getSplatVector( 2177 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2178 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2179 } 2180 if (Addend != 0 || Negate) { 2181 SDValue SplatAddend = 2182 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2183 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2184 } 2185 return VID; 2186 } 2187 } 2188 2189 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2190 // when re-interpreted as a vector with a larger element type. For example, 2191 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2192 // could be instead splat as 2193 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2194 // TODO: This optimization could also work on non-constant splats, but it 2195 // would require bit-manipulation instructions to construct the splat value. 2196 SmallVector<SDValue> Sequence; 2197 unsigned EltBitSize = VT.getScalarSizeInBits(); 2198 const auto *BV = cast<BuildVectorSDNode>(Op); 2199 if (VT.isInteger() && EltBitSize < 64 && 2200 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2201 BV->getRepeatedSequence(Sequence) && 2202 (Sequence.size() * EltBitSize) <= 64) { 2203 unsigned SeqLen = Sequence.size(); 2204 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2205 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2206 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2207 ViaIntVT == MVT::i64) && 2208 "Unexpected sequence type"); 2209 2210 unsigned EltIdx = 0; 2211 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2212 uint64_t SplatValue = 0; 2213 // Construct the amalgamated value which can be splatted as this larger 2214 // vector type. 2215 for (const auto &SeqV : Sequence) { 2216 if (!SeqV.isUndef()) 2217 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2218 << (EltIdx * EltBitSize)); 2219 EltIdx++; 2220 } 2221 2222 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2223 // achieve better constant materializion. 2224 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2225 SplatValue = SignExtend64(SplatValue, 32); 2226 2227 // Since we can't introduce illegal i64 types at this stage, we can only 2228 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2229 // way we can use RVV instructions to splat. 2230 assert((ViaIntVT.bitsLE(XLenVT) || 2231 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2232 "Unexpected bitcast sequence"); 2233 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2234 SDValue ViaVL = 2235 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2236 MVT ViaContainerVT = 2237 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2238 SDValue Splat = 2239 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2240 DAG.getUNDEF(ViaContainerVT), 2241 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2242 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2243 return DAG.getBitcast(VT, Splat); 2244 } 2245 } 2246 2247 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2248 // which constitute a large proportion of the elements. In such cases we can 2249 // splat a vector with the dominant element and make up the shortfall with 2250 // INSERT_VECTOR_ELTs. 2251 // Note that this includes vectors of 2 elements by association. The 2252 // upper-most element is the "dominant" one, allowing us to use a splat to 2253 // "insert" the upper element, and an insert of the lower element at position 2254 // 0, which improves codegen. 2255 SDValue DominantValue; 2256 unsigned MostCommonCount = 0; 2257 DenseMap<SDValue, unsigned> ValueCounts; 2258 unsigned NumUndefElts = 2259 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2260 2261 // Track the number of scalar loads we know we'd be inserting, estimated as 2262 // any non-zero floating-point constant. Other kinds of element are either 2263 // already in registers or are materialized on demand. The threshold at which 2264 // a vector load is more desirable than several scalar materializion and 2265 // vector-insertion instructions is not known. 2266 unsigned NumScalarLoads = 0; 2267 2268 for (SDValue V : Op->op_values()) { 2269 if (V.isUndef()) 2270 continue; 2271 2272 ValueCounts.insert(std::make_pair(V, 0)); 2273 unsigned &Count = ValueCounts[V]; 2274 2275 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2276 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2277 2278 // Is this value dominant? In case of a tie, prefer the highest element as 2279 // it's cheaper to insert near the beginning of a vector than it is at the 2280 // end. 2281 if (++Count >= MostCommonCount) { 2282 DominantValue = V; 2283 MostCommonCount = Count; 2284 } 2285 } 2286 2287 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2288 unsigned NumDefElts = NumElts - NumUndefElts; 2289 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2290 2291 // Don't perform this optimization when optimizing for size, since 2292 // materializing elements and inserting them tends to cause code bloat. 2293 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2294 ((MostCommonCount > DominantValueCountThreshold) || 2295 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2296 // Start by splatting the most common element. 2297 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2298 2299 DenseSet<SDValue> Processed{DominantValue}; 2300 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2301 for (const auto &OpIdx : enumerate(Op->ops())) { 2302 const SDValue &V = OpIdx.value(); 2303 if (V.isUndef() || !Processed.insert(V).second) 2304 continue; 2305 if (ValueCounts[V] == 1) { 2306 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2307 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2308 } else { 2309 // Blend in all instances of this value using a VSELECT, using a 2310 // mask where each bit signals whether that element is the one 2311 // we're after. 2312 SmallVector<SDValue> Ops; 2313 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2314 return DAG.getConstant(V == V1, DL, XLenVT); 2315 }); 2316 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2317 DAG.getBuildVector(SelMaskTy, DL, Ops), 2318 DAG.getSplatBuildVector(VT, DL, V), Vec); 2319 } 2320 } 2321 2322 return Vec; 2323 } 2324 2325 return SDValue(); 2326 } 2327 2328 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2329 SDValue Lo, SDValue Hi, SDValue VL, 2330 SelectionDAG &DAG) { 2331 bool HasPassthru = Passthru && !Passthru.isUndef(); 2332 if (!HasPassthru && !Passthru) 2333 Passthru = DAG.getUNDEF(VT); 2334 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2335 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2336 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2337 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2338 // node in order to try and match RVV vector/scalar instructions. 2339 if ((LoC >> 31) == HiC) 2340 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2341 2342 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2343 // vmv.v.x whose EEW = 32 to lower it. 2344 auto *Const = dyn_cast<ConstantSDNode>(VL); 2345 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2346 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2347 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2348 // access the subtarget here now. 2349 auto InterVec = DAG.getNode( 2350 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2351 DAG.getRegister(RISCV::X0, MVT::i32)); 2352 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2353 } 2354 } 2355 2356 // Fall back to a stack store and stride x0 vector load. 2357 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2358 Hi, VL); 2359 } 2360 2361 // Called by type legalization to handle splat of i64 on RV32. 2362 // FIXME: We can optimize this when the type has sign or zero bits in one 2363 // of the halves. 2364 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2365 SDValue Scalar, SDValue VL, 2366 SelectionDAG &DAG) { 2367 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2368 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2369 DAG.getConstant(0, DL, MVT::i32)); 2370 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2371 DAG.getConstant(1, DL, MVT::i32)); 2372 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2373 } 2374 2375 // This function lowers a splat of a scalar operand Splat with the vector 2376 // length VL. It ensures the final sequence is type legal, which is useful when 2377 // lowering a splat after type legalization. 2378 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2379 MVT VT, SDLoc DL, SelectionDAG &DAG, 2380 const RISCVSubtarget &Subtarget) { 2381 bool HasPassthru = Passthru && !Passthru.isUndef(); 2382 if (!HasPassthru && !Passthru) 2383 Passthru = DAG.getUNDEF(VT); 2384 if (VT.isFloatingPoint()) { 2385 // If VL is 1, we could use vfmv.s.f. 2386 if (isOneConstant(VL)) 2387 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2388 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2389 } 2390 2391 MVT XLenVT = Subtarget.getXLenVT(); 2392 2393 // Simplest case is that the operand needs to be promoted to XLenVT. 2394 if (Scalar.getValueType().bitsLE(XLenVT)) { 2395 // If the operand is a constant, sign extend to increase our chances 2396 // of being able to use a .vi instruction. ANY_EXTEND would become a 2397 // a zero extend and the simm5 check in isel would fail. 2398 // FIXME: Should we ignore the upper bits in isel instead? 2399 unsigned ExtOpc = 2400 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2401 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2402 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2403 // If VL is 1 and the scalar value won't benefit from immediate, we could 2404 // use vmv.s.x. 2405 if (isOneConstant(VL) && 2406 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2407 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2408 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2409 } 2410 2411 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2412 "Unexpected scalar for splat lowering!"); 2413 2414 if (isOneConstant(VL) && isNullConstant(Scalar)) 2415 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2416 DAG.getConstant(0, DL, XLenVT), VL); 2417 2418 // Otherwise use the more complicated splatting algorithm. 2419 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2420 } 2421 2422 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2423 const RISCVSubtarget &Subtarget) { 2424 // We need to be able to widen elements to the next larger integer type. 2425 if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors()) 2426 return false; 2427 2428 int Size = Mask.size(); 2429 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2430 2431 int Srcs[] = {-1, -1}; 2432 for (int i = 0; i != Size; ++i) { 2433 // Ignore undef elements. 2434 if (Mask[i] < 0) 2435 continue; 2436 2437 // Is this an even or odd element. 2438 int Pol = i % 2; 2439 2440 // Ensure we consistently use the same source for this element polarity. 2441 int Src = Mask[i] / Size; 2442 if (Srcs[Pol] < 0) 2443 Srcs[Pol] = Src; 2444 if (Srcs[Pol] != Src) 2445 return false; 2446 2447 // Make sure the element within the source is appropriate for this element 2448 // in the destination. 2449 int Elt = Mask[i] % Size; 2450 if (Elt != i / 2) 2451 return false; 2452 } 2453 2454 // We need to find a source for each polarity and they can't be the same. 2455 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2456 return false; 2457 2458 // Swap the sources if the second source was in the even polarity. 2459 SwapSources = Srcs[0] > Srcs[1]; 2460 2461 return true; 2462 } 2463 2464 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2465 /// and then extract the original number of elements from the rotated result. 2466 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2467 /// returned rotation amount is for a rotate right, where elements move from 2468 /// higher elements to lower elements. \p LoSrc indicates the first source 2469 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2470 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2471 /// 0 or 1 if a rotation is found. 2472 /// 2473 /// NOTE: We talk about rotate to the right which matches how bit shift and 2474 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2475 /// and the table below write vectors with the lowest elements on the left. 2476 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2477 int Size = Mask.size(); 2478 2479 // We need to detect various ways of spelling a rotation: 2480 // [11, 12, 13, 14, 15, 0, 1, 2] 2481 // [-1, 12, 13, 14, -1, -1, 1, -1] 2482 // [-1, -1, -1, -1, -1, -1, 1, 2] 2483 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2484 // [-1, 4, 5, 6, -1, -1, 9, -1] 2485 // [-1, 4, 5, 6, -1, -1, -1, -1] 2486 int Rotation = 0; 2487 LoSrc = -1; 2488 HiSrc = -1; 2489 for (int i = 0; i != Size; ++i) { 2490 int M = Mask[i]; 2491 if (M < 0) 2492 continue; 2493 2494 // Determine where a rotate vector would have started. 2495 int StartIdx = i - (M % Size); 2496 // The identity rotation isn't interesting, stop. 2497 if (StartIdx == 0) 2498 return -1; 2499 2500 // If we found the tail of a vector the rotation must be the missing 2501 // front. If we found the head of a vector, it must be how much of the 2502 // head. 2503 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2504 2505 if (Rotation == 0) 2506 Rotation = CandidateRotation; 2507 else if (Rotation != CandidateRotation) 2508 // The rotations don't match, so we can't match this mask. 2509 return -1; 2510 2511 // Compute which value this mask is pointing at. 2512 int MaskSrc = M < Size ? 0 : 1; 2513 2514 // Compute which of the two target values this index should be assigned to. 2515 // This reflects whether the high elements are remaining or the low elemnts 2516 // are remaining. 2517 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2518 2519 // Either set up this value if we've not encountered it before, or check 2520 // that it remains consistent. 2521 if (TargetSrc < 0) 2522 TargetSrc = MaskSrc; 2523 else if (TargetSrc != MaskSrc) 2524 // This may be a rotation, but it pulls from the inputs in some 2525 // unsupported interleaving. 2526 return -1; 2527 } 2528 2529 // Check that we successfully analyzed the mask, and normalize the results. 2530 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2531 assert((LoSrc >= 0 || HiSrc >= 0) && 2532 "Failed to find a rotated input vector!"); 2533 2534 return Rotation; 2535 } 2536 2537 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2538 const RISCVSubtarget &Subtarget) { 2539 SDValue V1 = Op.getOperand(0); 2540 SDValue V2 = Op.getOperand(1); 2541 SDLoc DL(Op); 2542 MVT XLenVT = Subtarget.getXLenVT(); 2543 MVT VT = Op.getSimpleValueType(); 2544 unsigned NumElts = VT.getVectorNumElements(); 2545 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2546 2547 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2548 2549 SDValue TrueMask, VL; 2550 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2551 2552 if (SVN->isSplat()) { 2553 const int Lane = SVN->getSplatIndex(); 2554 if (Lane >= 0) { 2555 MVT SVT = VT.getVectorElementType(); 2556 2557 // Turn splatted vector load into a strided load with an X0 stride. 2558 SDValue V = V1; 2559 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2560 // with undef. 2561 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2562 int Offset = Lane; 2563 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2564 int OpElements = 2565 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2566 V = V.getOperand(Offset / OpElements); 2567 Offset %= OpElements; 2568 } 2569 2570 // We need to ensure the load isn't atomic or volatile. 2571 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2572 auto *Ld = cast<LoadSDNode>(V); 2573 Offset *= SVT.getStoreSize(); 2574 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2575 TypeSize::Fixed(Offset), DL); 2576 2577 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2578 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2579 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2580 SDValue IntID = 2581 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2582 SDValue Ops[] = {Ld->getChain(), 2583 IntID, 2584 DAG.getUNDEF(ContainerVT), 2585 NewAddr, 2586 DAG.getRegister(RISCV::X0, XLenVT), 2587 VL}; 2588 SDValue NewLoad = DAG.getMemIntrinsicNode( 2589 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2590 DAG.getMachineFunction().getMachineMemOperand( 2591 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2592 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2593 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2594 } 2595 2596 // Otherwise use a scalar load and splat. This will give the best 2597 // opportunity to fold a splat into the operation. ISel can turn it into 2598 // the x0 strided load if we aren't able to fold away the select. 2599 if (SVT.isFloatingPoint()) 2600 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2601 Ld->getPointerInfo().getWithOffset(Offset), 2602 Ld->getOriginalAlign(), 2603 Ld->getMemOperand()->getFlags()); 2604 else 2605 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2606 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2607 Ld->getOriginalAlign(), 2608 Ld->getMemOperand()->getFlags()); 2609 DAG.makeEquivalentMemoryOrdering(Ld, V); 2610 2611 unsigned Opc = 2612 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2613 SDValue Splat = 2614 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2615 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2616 } 2617 2618 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2619 assert(Lane < (int)NumElts && "Unexpected lane!"); 2620 SDValue Gather = 2621 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2622 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2623 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2624 } 2625 } 2626 2627 ArrayRef<int> Mask = SVN->getMask(); 2628 2629 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2630 // be undef which can be handled with a single SLIDEDOWN/UP. 2631 int LoSrc, HiSrc; 2632 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2633 if (Rotation > 0) { 2634 SDValue LoV, HiV; 2635 if (LoSrc >= 0) { 2636 LoV = LoSrc == 0 ? V1 : V2; 2637 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2638 } 2639 if (HiSrc >= 0) { 2640 HiV = HiSrc == 0 ? V1 : V2; 2641 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2642 } 2643 2644 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2645 // to slide LoV up by (NumElts - Rotation). 2646 unsigned InvRotate = NumElts - Rotation; 2647 2648 SDValue Res = DAG.getUNDEF(ContainerVT); 2649 if (HiV) { 2650 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2651 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2652 // causes multiple vsetvlis in some test cases such as lowering 2653 // reduce.mul 2654 SDValue DownVL = VL; 2655 if (LoV) 2656 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2657 Res = 2658 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2659 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2660 } 2661 if (LoV) 2662 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2663 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2664 2665 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2666 } 2667 2668 // Detect an interleave shuffle and lower to 2669 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2670 bool SwapSources; 2671 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2672 // Swap sources if needed. 2673 if (SwapSources) 2674 std::swap(V1, V2); 2675 2676 // Extract the lower half of the vectors. 2677 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2678 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2679 DAG.getConstant(0, DL, XLenVT)); 2680 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2681 DAG.getConstant(0, DL, XLenVT)); 2682 2683 // Double the element width and halve the number of elements in an int type. 2684 unsigned EltBits = VT.getScalarSizeInBits(); 2685 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2686 MVT WideIntVT = 2687 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2688 // Convert this to a scalable vector. We need to base this on the 2689 // destination size to ensure there's always a type with a smaller LMUL. 2690 MVT WideIntContainerVT = 2691 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2692 2693 // Convert sources to scalable vectors with the same element count as the 2694 // larger type. 2695 MVT HalfContainerVT = MVT::getVectorVT( 2696 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2697 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2698 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2699 2700 // Cast sources to integer. 2701 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2702 MVT IntHalfVT = 2703 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2704 V1 = DAG.getBitcast(IntHalfVT, V1); 2705 V2 = DAG.getBitcast(IntHalfVT, V2); 2706 2707 // Freeze V2 since we use it twice and we need to be sure that the add and 2708 // multiply see the same value. 2709 V2 = DAG.getFreeze(V2); 2710 2711 // Recreate TrueMask using the widened type's element count. 2712 MVT MaskVT = 2713 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2714 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2715 2716 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2717 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2718 V2, TrueMask, VL); 2719 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2720 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2721 DAG.getUNDEF(IntHalfVT), 2722 DAG.getAllOnesConstant(DL, XLenVT)); 2723 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2724 V2, Multiplier, TrueMask, VL); 2725 // Add the new copies to our previous addition giving us 2^eltbits copies of 2726 // V2. This is equivalent to shifting V2 left by eltbits. This should 2727 // combine with the vwmulu.vv above to form vwmaccu.vv. 2728 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2729 TrueMask, VL); 2730 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2731 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2732 // vector VT. 2733 ContainerVT = 2734 MVT::getVectorVT(VT.getVectorElementType(), 2735 WideIntContainerVT.getVectorElementCount() * 2); 2736 Add = DAG.getBitcast(ContainerVT, Add); 2737 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2738 } 2739 2740 // Detect shuffles which can be re-expressed as vector selects; these are 2741 // shuffles in which each element in the destination is taken from an element 2742 // at the corresponding index in either source vectors. 2743 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2744 int MaskIndex = MaskIdx.value(); 2745 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2746 }); 2747 2748 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2749 2750 SmallVector<SDValue> MaskVals; 2751 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2752 // merged with a second vrgather. 2753 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2754 2755 // By default we preserve the original operand order, and use a mask to 2756 // select LHS as true and RHS as false. However, since RVV vector selects may 2757 // feature splats but only on the LHS, we may choose to invert our mask and 2758 // instead select between RHS and LHS. 2759 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2760 bool InvertMask = IsSelect == SwapOps; 2761 2762 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2763 // half. 2764 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2765 2766 // Now construct the mask that will be used by the vselect or blended 2767 // vrgather operation. For vrgathers, construct the appropriate indices into 2768 // each vector. 2769 for (int MaskIndex : Mask) { 2770 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2771 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2772 if (!IsSelect) { 2773 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2774 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2775 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2776 : DAG.getUNDEF(XLenVT)); 2777 GatherIndicesRHS.push_back( 2778 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2779 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2780 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2781 ++LHSIndexCounts[MaskIndex]; 2782 if (!IsLHSOrUndefIndex) 2783 ++RHSIndexCounts[MaskIndex - NumElts]; 2784 } 2785 } 2786 2787 if (SwapOps) { 2788 std::swap(V1, V2); 2789 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2790 } 2791 2792 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2793 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2794 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2795 2796 if (IsSelect) 2797 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2798 2799 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2800 // On such a large vector we're unable to use i8 as the index type. 2801 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2802 // may involve vector splitting if we're already at LMUL=8, or our 2803 // user-supplied maximum fixed-length LMUL. 2804 return SDValue(); 2805 } 2806 2807 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2808 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2809 MVT IndexVT = VT.changeTypeToInteger(); 2810 // Since we can't introduce illegal index types at this stage, use i16 and 2811 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2812 // than XLenVT. 2813 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2814 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2815 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2816 } 2817 2818 MVT IndexContainerVT = 2819 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2820 2821 SDValue Gather; 2822 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2823 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2824 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2825 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2826 Subtarget); 2827 } else { 2828 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2829 // If only one index is used, we can use a "splat" vrgather. 2830 // TODO: We can splat the most-common index and fix-up any stragglers, if 2831 // that's beneficial. 2832 if (LHSIndexCounts.size() == 1) { 2833 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2834 Gather = 2835 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2836 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2837 } else { 2838 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2839 LHSIndices = 2840 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2841 2842 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2843 TrueMask, VL); 2844 } 2845 } 2846 2847 // If a second vector operand is used by this shuffle, blend it in with an 2848 // additional vrgather. 2849 if (!V2.isUndef()) { 2850 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2851 // If only one index is used, we can use a "splat" vrgather. 2852 // TODO: We can splat the most-common index and fix-up any stragglers, if 2853 // that's beneficial. 2854 if (RHSIndexCounts.size() == 1) { 2855 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2856 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2857 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2858 } else { 2859 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2860 RHSIndices = 2861 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2862 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2863 VL); 2864 } 2865 2866 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2867 SelectMask = 2868 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2869 2870 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2871 Gather, VL); 2872 } 2873 2874 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2875 } 2876 2877 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2878 // Support splats for any type. These should type legalize well. 2879 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2880 return true; 2881 2882 // Only support legal VTs for other shuffles for now. 2883 if (!isTypeLegal(VT)) 2884 return false; 2885 2886 MVT SVT = VT.getSimpleVT(); 2887 2888 bool SwapSources; 2889 int LoSrc, HiSrc; 2890 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2891 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2892 } 2893 2894 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2895 SDLoc DL, SelectionDAG &DAG, 2896 const RISCVSubtarget &Subtarget) { 2897 if (VT.isScalableVector()) 2898 return DAG.getFPExtendOrRound(Op, DL, VT); 2899 assert(VT.isFixedLengthVector() && 2900 "Unexpected value type for RVV FP extend/round lowering"); 2901 SDValue Mask, VL; 2902 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2903 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2904 ? RISCVISD::FP_EXTEND_VL 2905 : RISCVISD::FP_ROUND_VL; 2906 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2907 } 2908 2909 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2910 // the exponent. 2911 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2912 MVT VT = Op.getSimpleValueType(); 2913 unsigned EltSize = VT.getScalarSizeInBits(); 2914 SDValue Src = Op.getOperand(0); 2915 SDLoc DL(Op); 2916 2917 // We need a FP type that can represent the value. 2918 // TODO: Use f16 for i8 when possible? 2919 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2920 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2921 2922 // Legal types should have been checked in the RISCVTargetLowering 2923 // constructor. 2924 // TODO: Splitting may make sense in some cases. 2925 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2926 "Expected legal float type!"); 2927 2928 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2929 // The trailing zero count is equal to log2 of this single bit value. 2930 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2931 SDValue Neg = 2932 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2933 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2934 } 2935 2936 // We have a legal FP type, convert to it. 2937 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2938 // Bitcast to integer and shift the exponent to the LSB. 2939 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2940 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2941 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2942 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2943 DAG.getConstant(ShiftAmt, DL, IntVT)); 2944 // Truncate back to original type to allow vnsrl. 2945 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2946 // The exponent contains log2 of the value in biased form. 2947 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2948 2949 // For trailing zeros, we just need to subtract the bias. 2950 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2951 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2952 DAG.getConstant(ExponentBias, DL, VT)); 2953 2954 // For leading zeros, we need to remove the bias and convert from log2 to 2955 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2956 unsigned Adjust = ExponentBias + (EltSize - 1); 2957 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2958 } 2959 2960 // While RVV has alignment restrictions, we should always be able to load as a 2961 // legal equivalently-sized byte-typed vector instead. This method is 2962 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2963 // the load is already correctly-aligned, it returns SDValue(). 2964 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2965 SelectionDAG &DAG) const { 2966 auto *Load = cast<LoadSDNode>(Op); 2967 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2968 2969 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2970 Load->getMemoryVT(), 2971 *Load->getMemOperand())) 2972 return SDValue(); 2973 2974 SDLoc DL(Op); 2975 MVT VT = Op.getSimpleValueType(); 2976 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2977 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2978 "Unexpected unaligned RVV load type"); 2979 MVT NewVT = 2980 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2981 assert(NewVT.isValid() && 2982 "Expecting equally-sized RVV vector types to be legal"); 2983 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2984 Load->getPointerInfo(), Load->getOriginalAlign(), 2985 Load->getMemOperand()->getFlags()); 2986 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2987 } 2988 2989 // While RVV has alignment restrictions, we should always be able to store as a 2990 // legal equivalently-sized byte-typed vector instead. This method is 2991 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2992 // returns SDValue() if the store is already correctly aligned. 2993 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2994 SelectionDAG &DAG) const { 2995 auto *Store = cast<StoreSDNode>(Op); 2996 assert(Store && Store->getValue().getValueType().isVector() && 2997 "Expected vector store"); 2998 2999 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3000 Store->getMemoryVT(), 3001 *Store->getMemOperand())) 3002 return SDValue(); 3003 3004 SDLoc DL(Op); 3005 SDValue StoredVal = Store->getValue(); 3006 MVT VT = StoredVal.getSimpleValueType(); 3007 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3008 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3009 "Unexpected unaligned RVV store type"); 3010 MVT NewVT = 3011 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3012 assert(NewVT.isValid() && 3013 "Expecting equally-sized RVV vector types to be legal"); 3014 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3015 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3016 Store->getPointerInfo(), Store->getOriginalAlign(), 3017 Store->getMemOperand()->getFlags()); 3018 } 3019 3020 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3021 SelectionDAG &DAG) const { 3022 switch (Op.getOpcode()) { 3023 default: 3024 report_fatal_error("unimplemented operand"); 3025 case ISD::GlobalAddress: 3026 return lowerGlobalAddress(Op, DAG); 3027 case ISD::BlockAddress: 3028 return lowerBlockAddress(Op, DAG); 3029 case ISD::ConstantPool: 3030 return lowerConstantPool(Op, DAG); 3031 case ISD::JumpTable: 3032 return lowerJumpTable(Op, DAG); 3033 case ISD::GlobalTLSAddress: 3034 return lowerGlobalTLSAddress(Op, DAG); 3035 case ISD::SELECT: 3036 return lowerSELECT(Op, DAG); 3037 case ISD::BRCOND: 3038 return lowerBRCOND(Op, DAG); 3039 case ISD::VASTART: 3040 return lowerVASTART(Op, DAG); 3041 case ISD::FRAMEADDR: 3042 return lowerFRAMEADDR(Op, DAG); 3043 case ISD::RETURNADDR: 3044 return lowerRETURNADDR(Op, DAG); 3045 case ISD::SHL_PARTS: 3046 return lowerShiftLeftParts(Op, DAG); 3047 case ISD::SRA_PARTS: 3048 return lowerShiftRightParts(Op, DAG, true); 3049 case ISD::SRL_PARTS: 3050 return lowerShiftRightParts(Op, DAG, false); 3051 case ISD::BITCAST: { 3052 SDLoc DL(Op); 3053 EVT VT = Op.getValueType(); 3054 SDValue Op0 = Op.getOperand(0); 3055 EVT Op0VT = Op0.getValueType(); 3056 MVT XLenVT = Subtarget.getXLenVT(); 3057 if (VT.isFixedLengthVector()) { 3058 // We can handle fixed length vector bitcasts with a simple replacement 3059 // in isel. 3060 if (Op0VT.isFixedLengthVector()) 3061 return Op; 3062 // When bitcasting from scalar to fixed-length vector, insert the scalar 3063 // into a one-element vector of the result type, and perform a vector 3064 // bitcast. 3065 if (!Op0VT.isVector()) { 3066 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3067 if (!isTypeLegal(BVT)) 3068 return SDValue(); 3069 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3070 DAG.getUNDEF(BVT), Op0, 3071 DAG.getConstant(0, DL, XLenVT))); 3072 } 3073 return SDValue(); 3074 } 3075 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3076 // thus: bitcast the vector to a one-element vector type whose element type 3077 // is the same as the result type, and extract the first element. 3078 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3079 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3080 if (!isTypeLegal(BVT)) 3081 return SDValue(); 3082 SDValue BVec = DAG.getBitcast(BVT, Op0); 3083 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3084 DAG.getConstant(0, DL, XLenVT)); 3085 } 3086 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3087 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3088 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3089 return FPConv; 3090 } 3091 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3092 Subtarget.hasStdExtF()) { 3093 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3094 SDValue FPConv = 3095 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3096 return FPConv; 3097 } 3098 return SDValue(); 3099 } 3100 case ISD::INTRINSIC_WO_CHAIN: 3101 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3102 case ISD::INTRINSIC_W_CHAIN: 3103 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3104 case ISD::INTRINSIC_VOID: 3105 return LowerINTRINSIC_VOID(Op, DAG); 3106 case ISD::BSWAP: 3107 case ISD::BITREVERSE: { 3108 MVT VT = Op.getSimpleValueType(); 3109 SDLoc DL(Op); 3110 if (Subtarget.hasStdExtZbp()) { 3111 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3112 // Start with the maximum immediate value which is the bitwidth - 1. 3113 unsigned Imm = VT.getSizeInBits() - 1; 3114 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3115 if (Op.getOpcode() == ISD::BSWAP) 3116 Imm &= ~0x7U; 3117 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3118 DAG.getConstant(Imm, DL, VT)); 3119 } 3120 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3121 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3122 // Expand bitreverse to a bswap(rev8) followed by brev8. 3123 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3124 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3125 // as brev8 by an isel pattern. 3126 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3127 DAG.getConstant(7, DL, VT)); 3128 } 3129 case ISD::FSHL: 3130 case ISD::FSHR: { 3131 MVT VT = Op.getSimpleValueType(); 3132 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3133 SDLoc DL(Op); 3134 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3135 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3136 // accidentally setting the extra bit. 3137 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3138 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3139 DAG.getConstant(ShAmtWidth, DL, VT)); 3140 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3141 // instruction use different orders. fshl will return its first operand for 3142 // shift of zero, fshr will return its second operand. fsl and fsr both 3143 // return rs1 so the ISD nodes need to have different operand orders. 3144 // Shift amount is in rs2. 3145 SDValue Op0 = Op.getOperand(0); 3146 SDValue Op1 = Op.getOperand(1); 3147 unsigned Opc = RISCVISD::FSL; 3148 if (Op.getOpcode() == ISD::FSHR) { 3149 std::swap(Op0, Op1); 3150 Opc = RISCVISD::FSR; 3151 } 3152 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3153 } 3154 case ISD::TRUNCATE: { 3155 SDLoc DL(Op); 3156 MVT VT = Op.getSimpleValueType(); 3157 // Only custom-lower vector truncates 3158 if (!VT.isVector()) 3159 return Op; 3160 3161 // Truncates to mask types are handled differently 3162 if (VT.getVectorElementType() == MVT::i1) 3163 return lowerVectorMaskTrunc(Op, DAG); 3164 3165 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3166 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3167 // truncate by one power of two at a time. 3168 MVT DstEltVT = VT.getVectorElementType(); 3169 3170 SDValue Src = Op.getOperand(0); 3171 MVT SrcVT = Src.getSimpleValueType(); 3172 MVT SrcEltVT = SrcVT.getVectorElementType(); 3173 3174 assert(DstEltVT.bitsLT(SrcEltVT) && 3175 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3176 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3177 "Unexpected vector truncate lowering"); 3178 3179 MVT ContainerVT = SrcVT; 3180 if (SrcVT.isFixedLengthVector()) { 3181 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3182 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3183 } 3184 3185 SDValue Result = Src; 3186 SDValue Mask, VL; 3187 std::tie(Mask, VL) = 3188 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3189 LLVMContext &Context = *DAG.getContext(); 3190 const ElementCount Count = ContainerVT.getVectorElementCount(); 3191 do { 3192 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3193 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3194 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3195 Mask, VL); 3196 } while (SrcEltVT != DstEltVT); 3197 3198 if (SrcVT.isFixedLengthVector()) 3199 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3200 3201 return Result; 3202 } 3203 case ISD::ANY_EXTEND: 3204 case ISD::ZERO_EXTEND: 3205 if (Op.getOperand(0).getValueType().isVector() && 3206 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3207 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3208 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3209 case ISD::SIGN_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::VSEXT_VL); 3214 case ISD::SPLAT_VECTOR_PARTS: 3215 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3216 case ISD::INSERT_VECTOR_ELT: 3217 return lowerINSERT_VECTOR_ELT(Op, DAG); 3218 case ISD::EXTRACT_VECTOR_ELT: 3219 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3220 case ISD::VSCALE: { 3221 MVT VT = Op.getSimpleValueType(); 3222 SDLoc DL(Op); 3223 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3224 // We define our scalable vector types for lmul=1 to use a 64 bit known 3225 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3226 // vscale as VLENB / 8. 3227 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3228 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3229 report_fatal_error("Support for VLEN==32 is incomplete."); 3230 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3231 // We assume VLENB is a multiple of 8. We manually choose the best shift 3232 // here because SimplifyDemandedBits isn't always able to simplify it. 3233 uint64_t Val = Op.getConstantOperandVal(0); 3234 if (isPowerOf2_64(Val)) { 3235 uint64_t Log2 = Log2_64(Val); 3236 if (Log2 < 3) 3237 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3238 DAG.getConstant(3 - Log2, DL, VT)); 3239 if (Log2 > 3) 3240 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3241 DAG.getConstant(Log2 - 3, DL, VT)); 3242 return VLENB; 3243 } 3244 // If the multiplier is a multiple of 8, scale it down to avoid needing 3245 // to shift the VLENB value. 3246 if ((Val % 8) == 0) 3247 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3248 DAG.getConstant(Val / 8, DL, VT)); 3249 } 3250 3251 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3252 DAG.getConstant(3, DL, VT)); 3253 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3254 } 3255 case ISD::FPOWI: { 3256 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3257 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3258 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3259 Op.getOperand(1).getValueType() == MVT::i32) { 3260 SDLoc DL(Op); 3261 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3262 SDValue Powi = 3263 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3264 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3265 DAG.getIntPtrConstant(0, DL)); 3266 } 3267 return SDValue(); 3268 } 3269 case ISD::FP_EXTEND: { 3270 // RVV can only do fp_extend to types double the size as the source. We 3271 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3272 // via f32. 3273 SDLoc DL(Op); 3274 MVT VT = Op.getSimpleValueType(); 3275 SDValue Src = Op.getOperand(0); 3276 MVT SrcVT = Src.getSimpleValueType(); 3277 3278 // Prepare any fixed-length vector operands. 3279 MVT ContainerVT = VT; 3280 if (SrcVT.isFixedLengthVector()) { 3281 ContainerVT = getContainerForFixedLengthVector(VT); 3282 MVT SrcContainerVT = 3283 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3284 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3285 } 3286 3287 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3288 SrcVT.getVectorElementType() != MVT::f16) { 3289 // For scalable vectors, we only need to close the gap between 3290 // vXf16->vXf64. 3291 if (!VT.isFixedLengthVector()) 3292 return Op; 3293 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3294 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3295 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3296 } 3297 3298 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3299 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3300 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3301 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3302 3303 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3304 DL, DAG, Subtarget); 3305 if (VT.isFixedLengthVector()) 3306 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3307 return Extend; 3308 } 3309 case ISD::FP_ROUND: { 3310 // RVV can only do fp_round to types half the size as the source. We 3311 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3312 // conversion instruction. 3313 SDLoc DL(Op); 3314 MVT VT = Op.getSimpleValueType(); 3315 SDValue Src = Op.getOperand(0); 3316 MVT SrcVT = Src.getSimpleValueType(); 3317 3318 // Prepare any fixed-length vector operands. 3319 MVT ContainerVT = VT; 3320 if (VT.isFixedLengthVector()) { 3321 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3322 ContainerVT = 3323 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3324 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3325 } 3326 3327 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3328 SrcVT.getVectorElementType() != MVT::f64) { 3329 // For scalable vectors, we only need to close the gap between 3330 // vXf64<->vXf16. 3331 if (!VT.isFixedLengthVector()) 3332 return Op; 3333 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3334 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3335 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3336 } 3337 3338 SDValue Mask, VL; 3339 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3340 3341 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3342 SDValue IntermediateRound = 3343 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3344 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3345 DL, DAG, Subtarget); 3346 3347 if (VT.isFixedLengthVector()) 3348 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3349 return Round; 3350 } 3351 case ISD::FP_TO_SINT: 3352 case ISD::FP_TO_UINT: 3353 case ISD::SINT_TO_FP: 3354 case ISD::UINT_TO_FP: { 3355 // RVV can only do fp<->int conversions to types half/double the size as 3356 // the source. We custom-lower any conversions that do two hops into 3357 // sequences. 3358 MVT VT = Op.getSimpleValueType(); 3359 if (!VT.isVector()) 3360 return Op; 3361 SDLoc DL(Op); 3362 SDValue Src = Op.getOperand(0); 3363 MVT EltVT = VT.getVectorElementType(); 3364 MVT SrcVT = Src.getSimpleValueType(); 3365 MVT SrcEltVT = SrcVT.getVectorElementType(); 3366 unsigned EltSize = EltVT.getSizeInBits(); 3367 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3368 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3369 "Unexpected vector element types"); 3370 3371 bool IsInt2FP = SrcEltVT.isInteger(); 3372 // Widening conversions 3373 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 3374 if (IsInt2FP) { 3375 // Do a regular integer sign/zero extension then convert to float. 3376 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 3377 VT.getVectorElementCount()); 3378 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3379 ? ISD::ZERO_EXTEND 3380 : ISD::SIGN_EXTEND; 3381 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3382 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3383 } 3384 // FP2Int 3385 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3386 // Do one doubling fp_extend then complete the operation by converting 3387 // to int. 3388 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3389 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3390 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3391 } 3392 3393 // Narrowing conversions 3394 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 3395 if (IsInt2FP) { 3396 // One narrowing int_to_fp, then an fp_round. 3397 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3398 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3399 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3400 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3401 } 3402 // FP2Int 3403 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3404 // representable by the integer, the result is poison. 3405 MVT IVecVT = 3406 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3407 VT.getVectorElementCount()); 3408 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3409 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3410 } 3411 3412 // Scalable vectors can exit here. Patterns will handle equally-sized 3413 // conversions halving/doubling ones. 3414 if (!VT.isFixedLengthVector()) 3415 return Op; 3416 3417 // For fixed-length vectors we lower to a custom "VL" node. 3418 unsigned RVVOpc = 0; 3419 switch (Op.getOpcode()) { 3420 default: 3421 llvm_unreachable("Impossible opcode"); 3422 case ISD::FP_TO_SINT: 3423 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3424 break; 3425 case ISD::FP_TO_UINT: 3426 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3427 break; 3428 case ISD::SINT_TO_FP: 3429 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3430 break; 3431 case ISD::UINT_TO_FP: 3432 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3433 break; 3434 } 3435 3436 MVT ContainerVT, SrcContainerVT; 3437 // Derive the reference container type from the larger vector type. 3438 if (SrcEltSize > EltSize) { 3439 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3440 ContainerVT = 3441 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3442 } else { 3443 ContainerVT = getContainerForFixedLengthVector(VT); 3444 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3445 } 3446 3447 SDValue Mask, VL; 3448 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3449 3450 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3451 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3452 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3453 } 3454 case ISD::FP_TO_SINT_SAT: 3455 case ISD::FP_TO_UINT_SAT: 3456 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3457 case ISD::FTRUNC: 3458 case ISD::FCEIL: 3459 case ISD::FFLOOR: 3460 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3461 case ISD::FROUND: 3462 return lowerFROUND(Op, DAG); 3463 case ISD::VECREDUCE_ADD: 3464 case ISD::VECREDUCE_UMAX: 3465 case ISD::VECREDUCE_SMAX: 3466 case ISD::VECREDUCE_UMIN: 3467 case ISD::VECREDUCE_SMIN: 3468 return lowerVECREDUCE(Op, DAG); 3469 case ISD::VECREDUCE_AND: 3470 case ISD::VECREDUCE_OR: 3471 case ISD::VECREDUCE_XOR: 3472 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3473 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3474 return lowerVECREDUCE(Op, DAG); 3475 case ISD::VECREDUCE_FADD: 3476 case ISD::VECREDUCE_SEQ_FADD: 3477 case ISD::VECREDUCE_FMIN: 3478 case ISD::VECREDUCE_FMAX: 3479 return lowerFPVECREDUCE(Op, DAG); 3480 case ISD::VP_REDUCE_ADD: 3481 case ISD::VP_REDUCE_UMAX: 3482 case ISD::VP_REDUCE_SMAX: 3483 case ISD::VP_REDUCE_UMIN: 3484 case ISD::VP_REDUCE_SMIN: 3485 case ISD::VP_REDUCE_FADD: 3486 case ISD::VP_REDUCE_SEQ_FADD: 3487 case ISD::VP_REDUCE_FMIN: 3488 case ISD::VP_REDUCE_FMAX: 3489 return lowerVPREDUCE(Op, DAG); 3490 case ISD::VP_REDUCE_AND: 3491 case ISD::VP_REDUCE_OR: 3492 case ISD::VP_REDUCE_XOR: 3493 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3494 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3495 return lowerVPREDUCE(Op, DAG); 3496 case ISD::INSERT_SUBVECTOR: 3497 return lowerINSERT_SUBVECTOR(Op, DAG); 3498 case ISD::EXTRACT_SUBVECTOR: 3499 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3500 case ISD::STEP_VECTOR: 3501 return lowerSTEP_VECTOR(Op, DAG); 3502 case ISD::VECTOR_REVERSE: 3503 return lowerVECTOR_REVERSE(Op, DAG); 3504 case ISD::BUILD_VECTOR: 3505 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3506 case ISD::SPLAT_VECTOR: 3507 if (Op.getValueType().getVectorElementType() == MVT::i1) 3508 return lowerVectorMaskSplat(Op, DAG); 3509 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3510 case ISD::VECTOR_SHUFFLE: 3511 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3512 case ISD::CONCAT_VECTORS: { 3513 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3514 // better than going through the stack, as the default expansion does. 3515 SDLoc DL(Op); 3516 MVT VT = Op.getSimpleValueType(); 3517 unsigned NumOpElts = 3518 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3519 SDValue Vec = DAG.getUNDEF(VT); 3520 for (const auto &OpIdx : enumerate(Op->ops())) { 3521 SDValue SubVec = OpIdx.value(); 3522 // Don't insert undef subvectors. 3523 if (SubVec.isUndef()) 3524 continue; 3525 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3526 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3527 } 3528 return Vec; 3529 } 3530 case ISD::LOAD: 3531 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3532 return V; 3533 if (Op.getValueType().isFixedLengthVector()) 3534 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3535 return Op; 3536 case ISD::STORE: 3537 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3538 return V; 3539 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3540 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3541 return Op; 3542 case ISD::MLOAD: 3543 case ISD::VP_LOAD: 3544 return lowerMaskedLoad(Op, DAG); 3545 case ISD::MSTORE: 3546 case ISD::VP_STORE: 3547 return lowerMaskedStore(Op, DAG); 3548 case ISD::SETCC: 3549 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3550 case ISD::ADD: 3551 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3552 case ISD::SUB: 3553 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3554 case ISD::MUL: 3555 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3556 case ISD::MULHS: 3557 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3558 case ISD::MULHU: 3559 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3560 case ISD::AND: 3561 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3562 RISCVISD::AND_VL); 3563 case ISD::OR: 3564 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3565 RISCVISD::OR_VL); 3566 case ISD::XOR: 3567 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3568 RISCVISD::XOR_VL); 3569 case ISD::SDIV: 3570 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3571 case ISD::SREM: 3572 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3573 case ISD::UDIV: 3574 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3575 case ISD::UREM: 3576 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3577 case ISD::SHL: 3578 case ISD::SRA: 3579 case ISD::SRL: 3580 if (Op.getSimpleValueType().isFixedLengthVector()) 3581 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3582 // This can be called for an i32 shift amount that needs to be promoted. 3583 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3584 "Unexpected custom legalisation"); 3585 return SDValue(); 3586 case ISD::SADDSAT: 3587 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3588 case ISD::UADDSAT: 3589 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3590 case ISD::SSUBSAT: 3591 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3592 case ISD::USUBSAT: 3593 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3594 case ISD::FADD: 3595 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3596 case ISD::FSUB: 3597 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3598 case ISD::FMUL: 3599 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3600 case ISD::FDIV: 3601 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3602 case ISD::FNEG: 3603 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3604 case ISD::FABS: 3605 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3606 case ISD::FSQRT: 3607 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3608 case ISD::FMA: 3609 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3610 case ISD::SMIN: 3611 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3612 case ISD::SMAX: 3613 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3614 case ISD::UMIN: 3615 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3616 case ISD::UMAX: 3617 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3618 case ISD::FMINNUM: 3619 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3620 case ISD::FMAXNUM: 3621 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3622 case ISD::ABS: 3623 return lowerABS(Op, DAG); 3624 case ISD::CTLZ_ZERO_UNDEF: 3625 case ISD::CTTZ_ZERO_UNDEF: 3626 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3627 case ISD::VSELECT: 3628 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3629 case ISD::FCOPYSIGN: 3630 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3631 case ISD::MGATHER: 3632 case ISD::VP_GATHER: 3633 return lowerMaskedGather(Op, DAG); 3634 case ISD::MSCATTER: 3635 case ISD::VP_SCATTER: 3636 return lowerMaskedScatter(Op, DAG); 3637 case ISD::FLT_ROUNDS_: 3638 return lowerGET_ROUNDING(Op, DAG); 3639 case ISD::SET_ROUNDING: 3640 return lowerSET_ROUNDING(Op, DAG); 3641 case ISD::VP_SELECT: 3642 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3643 case ISD::VP_MERGE: 3644 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3645 case ISD::VP_ADD: 3646 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3647 case ISD::VP_SUB: 3648 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3649 case ISD::VP_MUL: 3650 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3651 case ISD::VP_SDIV: 3652 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3653 case ISD::VP_UDIV: 3654 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3655 case ISD::VP_SREM: 3656 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3657 case ISD::VP_UREM: 3658 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3659 case ISD::VP_AND: 3660 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3661 case ISD::VP_OR: 3662 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3663 case ISD::VP_XOR: 3664 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3665 case ISD::VP_ASHR: 3666 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3667 case ISD::VP_LSHR: 3668 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3669 case ISD::VP_SHL: 3670 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3671 case ISD::VP_FADD: 3672 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3673 case ISD::VP_FSUB: 3674 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3675 case ISD::VP_FMUL: 3676 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3677 case ISD::VP_FDIV: 3678 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3679 case ISD::VP_FNEG: 3680 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3681 case ISD::VP_FMA: 3682 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3683 } 3684 } 3685 3686 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3687 SelectionDAG &DAG, unsigned Flags) { 3688 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3689 } 3690 3691 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3692 SelectionDAG &DAG, unsigned Flags) { 3693 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3694 Flags); 3695 } 3696 3697 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3698 SelectionDAG &DAG, unsigned Flags) { 3699 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3700 N->getOffset(), Flags); 3701 } 3702 3703 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3704 SelectionDAG &DAG, unsigned Flags) { 3705 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3706 } 3707 3708 template <class NodeTy> 3709 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3710 bool IsLocal) const { 3711 SDLoc DL(N); 3712 EVT Ty = getPointerTy(DAG.getDataLayout()); 3713 3714 if (isPositionIndependent()) { 3715 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3716 if (IsLocal) 3717 // Use PC-relative addressing to access the symbol. This generates the 3718 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3719 // %pcrel_lo(auipc)). 3720 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3721 3722 // Use PC-relative addressing to access the GOT for this symbol, then load 3723 // the address from the GOT. This generates the pattern (PseudoLA sym), 3724 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3725 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3726 } 3727 3728 switch (getTargetMachine().getCodeModel()) { 3729 default: 3730 report_fatal_error("Unsupported code model for lowering"); 3731 case CodeModel::Small: { 3732 // Generate a sequence for accessing addresses within the first 2 GiB of 3733 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3734 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3735 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3736 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3737 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3738 } 3739 case CodeModel::Medium: { 3740 // Generate a sequence for accessing addresses within any 2GiB range within 3741 // the address space. This generates the pattern (PseudoLLA sym), which 3742 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3743 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3744 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3745 } 3746 } 3747 } 3748 3749 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3750 SelectionDAG &DAG) const { 3751 SDLoc DL(Op); 3752 EVT Ty = Op.getValueType(); 3753 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3754 int64_t Offset = N->getOffset(); 3755 MVT XLenVT = Subtarget.getXLenVT(); 3756 3757 const GlobalValue *GV = N->getGlobal(); 3758 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3759 SDValue Addr = getAddr(N, DAG, IsLocal); 3760 3761 // In order to maximise the opportunity for common subexpression elimination, 3762 // emit a separate ADD node for the global address offset instead of folding 3763 // it in the global address node. Later peephole optimisations may choose to 3764 // fold it back in when profitable. 3765 if (Offset != 0) 3766 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3767 DAG.getConstant(Offset, DL, XLenVT)); 3768 return Addr; 3769 } 3770 3771 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3772 SelectionDAG &DAG) const { 3773 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3774 3775 return getAddr(N, DAG); 3776 } 3777 3778 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3779 SelectionDAG &DAG) const { 3780 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3781 3782 return getAddr(N, DAG); 3783 } 3784 3785 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3786 SelectionDAG &DAG) const { 3787 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3788 3789 return getAddr(N, DAG); 3790 } 3791 3792 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3793 SelectionDAG &DAG, 3794 bool UseGOT) const { 3795 SDLoc DL(N); 3796 EVT Ty = getPointerTy(DAG.getDataLayout()); 3797 const GlobalValue *GV = N->getGlobal(); 3798 MVT XLenVT = Subtarget.getXLenVT(); 3799 3800 if (UseGOT) { 3801 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3802 // load the address from the GOT and add the thread pointer. This generates 3803 // the pattern (PseudoLA_TLS_IE sym), which expands to 3804 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3805 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3806 SDValue Load = 3807 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3808 3809 // Add the thread pointer. 3810 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3811 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3812 } 3813 3814 // Generate a sequence for accessing the address relative to the thread 3815 // pointer, with the appropriate adjustment for the thread pointer offset. 3816 // This generates the pattern 3817 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3818 SDValue AddrHi = 3819 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3820 SDValue AddrAdd = 3821 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3822 SDValue AddrLo = 3823 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3824 3825 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3826 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3827 SDValue MNAdd = SDValue( 3828 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3829 0); 3830 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3831 } 3832 3833 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3834 SelectionDAG &DAG) const { 3835 SDLoc DL(N); 3836 EVT Ty = getPointerTy(DAG.getDataLayout()); 3837 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3838 const GlobalValue *GV = N->getGlobal(); 3839 3840 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3841 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3842 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3843 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3844 SDValue Load = 3845 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3846 3847 // Prepare argument list to generate call. 3848 ArgListTy Args; 3849 ArgListEntry Entry; 3850 Entry.Node = Load; 3851 Entry.Ty = CallTy; 3852 Args.push_back(Entry); 3853 3854 // Setup call to __tls_get_addr. 3855 TargetLowering::CallLoweringInfo CLI(DAG); 3856 CLI.setDebugLoc(DL) 3857 .setChain(DAG.getEntryNode()) 3858 .setLibCallee(CallingConv::C, CallTy, 3859 DAG.getExternalSymbol("__tls_get_addr", Ty), 3860 std::move(Args)); 3861 3862 return LowerCallTo(CLI).first; 3863 } 3864 3865 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3866 SelectionDAG &DAG) const { 3867 SDLoc DL(Op); 3868 EVT Ty = Op.getValueType(); 3869 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3870 int64_t Offset = N->getOffset(); 3871 MVT XLenVT = Subtarget.getXLenVT(); 3872 3873 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3874 3875 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3876 CallingConv::GHC) 3877 report_fatal_error("In GHC calling convention TLS is not supported"); 3878 3879 SDValue Addr; 3880 switch (Model) { 3881 case TLSModel::LocalExec: 3882 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3883 break; 3884 case TLSModel::InitialExec: 3885 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3886 break; 3887 case TLSModel::LocalDynamic: 3888 case TLSModel::GeneralDynamic: 3889 Addr = getDynamicTLSAddr(N, DAG); 3890 break; 3891 } 3892 3893 // In order to maximise the opportunity for common subexpression elimination, 3894 // emit a separate ADD node for the global address offset instead of folding 3895 // it in the global address node. Later peephole optimisations may choose to 3896 // fold it back in when profitable. 3897 if (Offset != 0) 3898 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3899 DAG.getConstant(Offset, DL, XLenVT)); 3900 return Addr; 3901 } 3902 3903 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3904 SDValue CondV = Op.getOperand(0); 3905 SDValue TrueV = Op.getOperand(1); 3906 SDValue FalseV = Op.getOperand(2); 3907 SDLoc DL(Op); 3908 MVT VT = Op.getSimpleValueType(); 3909 MVT XLenVT = Subtarget.getXLenVT(); 3910 3911 // Lower vector SELECTs to VSELECTs by splatting the condition. 3912 if (VT.isVector()) { 3913 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3914 SDValue CondSplat = VT.isScalableVector() 3915 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3916 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3917 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3918 } 3919 3920 // If the result type is XLenVT and CondV is the output of a SETCC node 3921 // which also operated on XLenVT inputs, then merge the SETCC node into the 3922 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3923 // compare+branch instructions. i.e.: 3924 // (select (setcc lhs, rhs, cc), truev, falsev) 3925 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3926 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3927 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3928 SDValue LHS = CondV.getOperand(0); 3929 SDValue RHS = CondV.getOperand(1); 3930 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3931 ISD::CondCode CCVal = CC->get(); 3932 3933 // Special case for a select of 2 constants that have a diffence of 1. 3934 // Normally this is done by DAGCombine, but if the select is introduced by 3935 // type legalization or op legalization, we miss it. Restricting to SETLT 3936 // case for now because that is what signed saturating add/sub need. 3937 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3938 // but we would probably want to swap the true/false values if the condition 3939 // is SETGE/SETLE to avoid an XORI. 3940 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3941 CCVal == ISD::SETLT) { 3942 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3943 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3944 if (TrueVal - 1 == FalseVal) 3945 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3946 if (TrueVal + 1 == FalseVal) 3947 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3948 } 3949 3950 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3951 3952 SDValue TargetCC = DAG.getCondCode(CCVal); 3953 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3954 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3955 } 3956 3957 // Otherwise: 3958 // (select condv, truev, falsev) 3959 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3960 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3961 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3962 3963 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3964 3965 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3966 } 3967 3968 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3969 SDValue CondV = Op.getOperand(1); 3970 SDLoc DL(Op); 3971 MVT XLenVT = Subtarget.getXLenVT(); 3972 3973 if (CondV.getOpcode() == ISD::SETCC && 3974 CondV.getOperand(0).getValueType() == XLenVT) { 3975 SDValue LHS = CondV.getOperand(0); 3976 SDValue RHS = CondV.getOperand(1); 3977 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3978 3979 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3980 3981 SDValue TargetCC = DAG.getCondCode(CCVal); 3982 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3983 LHS, RHS, TargetCC, Op.getOperand(2)); 3984 } 3985 3986 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3987 CondV, DAG.getConstant(0, DL, XLenVT), 3988 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3989 } 3990 3991 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3992 MachineFunction &MF = DAG.getMachineFunction(); 3993 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3994 3995 SDLoc DL(Op); 3996 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3997 getPointerTy(MF.getDataLayout())); 3998 3999 // vastart just stores the address of the VarArgsFrameIndex slot into the 4000 // memory location argument. 4001 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4002 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 4003 MachinePointerInfo(SV)); 4004 } 4005 4006 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 4007 SelectionDAG &DAG) const { 4008 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4009 MachineFunction &MF = DAG.getMachineFunction(); 4010 MachineFrameInfo &MFI = MF.getFrameInfo(); 4011 MFI.setFrameAddressIsTaken(true); 4012 Register FrameReg = RI.getFrameRegister(MF); 4013 int XLenInBytes = Subtarget.getXLen() / 8; 4014 4015 EVT VT = Op.getValueType(); 4016 SDLoc DL(Op); 4017 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 4018 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4019 while (Depth--) { 4020 int Offset = -(XLenInBytes * 2); 4021 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 4022 DAG.getIntPtrConstant(Offset, DL)); 4023 FrameAddr = 4024 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 4025 } 4026 return FrameAddr; 4027 } 4028 4029 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 4030 SelectionDAG &DAG) const { 4031 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4032 MachineFunction &MF = DAG.getMachineFunction(); 4033 MachineFrameInfo &MFI = MF.getFrameInfo(); 4034 MFI.setReturnAddressIsTaken(true); 4035 MVT XLenVT = Subtarget.getXLenVT(); 4036 int XLenInBytes = Subtarget.getXLen() / 8; 4037 4038 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4039 return SDValue(); 4040 4041 EVT VT = Op.getValueType(); 4042 SDLoc DL(Op); 4043 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4044 if (Depth) { 4045 int Off = -XLenInBytes; 4046 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 4047 SDValue Offset = DAG.getConstant(Off, DL, VT); 4048 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4049 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4050 MachinePointerInfo()); 4051 } 4052 4053 // Return the value of the return address register, marking it an implicit 4054 // live-in. 4055 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 4056 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 4057 } 4058 4059 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4060 SelectionDAG &DAG) const { 4061 SDLoc DL(Op); 4062 SDValue Lo = Op.getOperand(0); 4063 SDValue Hi = Op.getOperand(1); 4064 SDValue Shamt = Op.getOperand(2); 4065 EVT VT = Lo.getValueType(); 4066 4067 // if Shamt-XLEN < 0: // Shamt < XLEN 4068 // Lo = Lo << Shamt 4069 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4070 // else: 4071 // Lo = 0 4072 // Hi = Lo << (Shamt-XLEN) 4073 4074 SDValue Zero = DAG.getConstant(0, DL, VT); 4075 SDValue One = DAG.getConstant(1, DL, VT); 4076 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4077 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4078 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4079 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4080 4081 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4082 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4083 SDValue ShiftRightLo = 4084 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4085 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4086 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4087 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4088 4089 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4090 4091 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4092 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4093 4094 SDValue Parts[2] = {Lo, Hi}; 4095 return DAG.getMergeValues(Parts, DL); 4096 } 4097 4098 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4099 bool IsSRA) 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 // SRA expansion: 4107 // if Shamt-XLEN < 0: // Shamt < XLEN 4108 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4109 // Hi = Hi >>s Shamt 4110 // else: 4111 // Lo = Hi >>s (Shamt-XLEN); 4112 // Hi = Hi >>s (XLEN-1) 4113 // 4114 // SRL expansion: 4115 // if Shamt-XLEN < 0: // Shamt < XLEN 4116 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4117 // Hi = Hi >>u Shamt 4118 // else: 4119 // Lo = Hi >>u (Shamt-XLEN); 4120 // Hi = 0; 4121 4122 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4123 4124 SDValue Zero = DAG.getConstant(0, DL, VT); 4125 SDValue One = DAG.getConstant(1, DL, VT); 4126 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4127 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4128 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4129 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4130 4131 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4132 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4133 SDValue ShiftLeftHi = 4134 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4135 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4136 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4137 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4138 SDValue HiFalse = 4139 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4140 4141 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4142 4143 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4144 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4145 4146 SDValue Parts[2] = {Lo, Hi}; 4147 return DAG.getMergeValues(Parts, DL); 4148 } 4149 4150 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4151 // legal equivalently-sized i8 type, so we can use that as a go-between. 4152 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4153 SelectionDAG &DAG) const { 4154 SDLoc DL(Op); 4155 MVT VT = Op.getSimpleValueType(); 4156 SDValue SplatVal = Op.getOperand(0); 4157 // All-zeros or all-ones splats are handled specially. 4158 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4159 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4160 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4161 } 4162 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4163 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4164 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4165 } 4166 MVT XLenVT = Subtarget.getXLenVT(); 4167 assert(SplatVal.getValueType() == XLenVT && 4168 "Unexpected type for i1 splat value"); 4169 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4170 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4171 DAG.getConstant(1, DL, XLenVT)); 4172 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4173 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4174 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4175 } 4176 4177 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4178 // illegal (currently only vXi64 RV32). 4179 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4180 // them to VMV_V_X_VL. 4181 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4182 SelectionDAG &DAG) const { 4183 SDLoc DL(Op); 4184 MVT VecVT = Op.getSimpleValueType(); 4185 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4186 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4187 4188 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4189 SDValue Lo = Op.getOperand(0); 4190 SDValue Hi = Op.getOperand(1); 4191 4192 if (VecVT.isFixedLengthVector()) { 4193 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4194 SDLoc DL(Op); 4195 SDValue Mask, VL; 4196 std::tie(Mask, VL) = 4197 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4198 4199 SDValue Res = 4200 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4201 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4202 } 4203 4204 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4205 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4206 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4207 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4208 // node in order to try and match RVV vector/scalar instructions. 4209 if ((LoC >> 31) == HiC) 4210 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4211 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4212 } 4213 4214 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4215 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4216 isa<ConstantSDNode>(Hi.getOperand(1)) && 4217 Hi.getConstantOperandVal(1) == 31) 4218 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4219 DAG.getRegister(RISCV::X0, MVT::i32)); 4220 4221 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4222 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4223 DAG.getUNDEF(VecVT), Lo, Hi, 4224 DAG.getRegister(RISCV::X0, MVT::i32)); 4225 } 4226 4227 // Custom-lower extensions from mask vectors by using a vselect either with 1 4228 // for zero/any-extension or -1 for sign-extension: 4229 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4230 // Note that any-extension is lowered identically to zero-extension. 4231 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4232 int64_t ExtTrueVal) const { 4233 SDLoc DL(Op); 4234 MVT VecVT = Op.getSimpleValueType(); 4235 SDValue Src = Op.getOperand(0); 4236 // Only custom-lower extensions from mask types 4237 assert(Src.getValueType().isVector() && 4238 Src.getValueType().getVectorElementType() == MVT::i1); 4239 4240 MVT XLenVT = Subtarget.getXLenVT(); 4241 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4242 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4243 4244 if (VecVT.isScalableVector()) { 4245 // Be careful not to introduce illegal scalar types at this stage, and be 4246 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 4247 // illegal and must be expanded. Since we know that the constants are 4248 // sign-extended 32-bit values, we use VMV_V_X_VL directly. 4249 bool IsRV32E64 = 4250 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 4251 4252 if (!IsRV32E64) { 4253 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 4254 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 4255 } else { 4256 SplatZero = 4257 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4258 SplatZero, DAG.getRegister(RISCV::X0, XLenVT)); 4259 SplatTrueVal = 4260 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4261 SplatTrueVal, DAG.getRegister(RISCV::X0, XLenVT)); 4262 } 4263 4264 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4265 } 4266 4267 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4268 MVT I1ContainerVT = 4269 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4270 4271 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4272 4273 SDValue Mask, VL; 4274 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4275 4276 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4277 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4278 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4279 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4280 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4281 SplatTrueVal, SplatZero, VL); 4282 4283 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4284 } 4285 4286 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4287 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4288 MVT ExtVT = Op.getSimpleValueType(); 4289 // Only custom-lower extensions from fixed-length vector types. 4290 if (!ExtVT.isFixedLengthVector()) 4291 return Op; 4292 MVT VT = Op.getOperand(0).getSimpleValueType(); 4293 // Grab the canonical container type for the extended type. Infer the smaller 4294 // type from that to ensure the same number of vector elements, as we know 4295 // the LMUL will be sufficient to hold the smaller type. 4296 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4297 // Get the extended container type manually to ensure the same number of 4298 // vector elements between source and dest. 4299 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4300 ContainerExtVT.getVectorElementCount()); 4301 4302 SDValue Op1 = 4303 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4304 4305 SDLoc DL(Op); 4306 SDValue Mask, VL; 4307 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4308 4309 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4310 4311 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4312 } 4313 4314 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4315 // setcc operation: 4316 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4317 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 4318 SelectionDAG &DAG) const { 4319 SDLoc DL(Op); 4320 EVT MaskVT = Op.getValueType(); 4321 // Only expect to custom-lower truncations to mask types 4322 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4323 "Unexpected type for vector mask lowering"); 4324 SDValue Src = Op.getOperand(0); 4325 MVT VecVT = Src.getSimpleValueType(); 4326 4327 // If this is a fixed vector, we need to convert it to a scalable vector. 4328 MVT ContainerVT = VecVT; 4329 if (VecVT.isFixedLengthVector()) { 4330 ContainerVT = getContainerForFixedLengthVector(VecVT); 4331 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4332 } 4333 4334 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4335 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4336 4337 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4338 DAG.getUNDEF(ContainerVT), SplatOne); 4339 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4340 DAG.getUNDEF(ContainerVT), SplatZero); 4341 4342 if (VecVT.isScalableVector()) { 4343 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 4344 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 4345 } 4346 4347 SDValue Mask, VL; 4348 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4349 4350 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4351 SDValue Trunc = 4352 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4353 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4354 DAG.getCondCode(ISD::SETNE), Mask, VL); 4355 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4356 } 4357 4358 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4359 // first position of a vector, and that vector is slid up to the insert index. 4360 // By limiting the active vector length to index+1 and merging with the 4361 // original vector (with an undisturbed tail policy for elements >= VL), we 4362 // achieve the desired result of leaving all elements untouched except the one 4363 // at VL-1, which is replaced with the desired value. 4364 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4365 SelectionDAG &DAG) const { 4366 SDLoc DL(Op); 4367 MVT VecVT = Op.getSimpleValueType(); 4368 SDValue Vec = Op.getOperand(0); 4369 SDValue Val = Op.getOperand(1); 4370 SDValue Idx = Op.getOperand(2); 4371 4372 if (VecVT.getVectorElementType() == MVT::i1) { 4373 // FIXME: For now we just promote to an i8 vector and insert into that, 4374 // but this is probably not optimal. 4375 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4376 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4377 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4378 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4379 } 4380 4381 MVT ContainerVT = VecVT; 4382 // If the operand is a fixed-length vector, convert to a scalable one. 4383 if (VecVT.isFixedLengthVector()) { 4384 ContainerVT = getContainerForFixedLengthVector(VecVT); 4385 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4386 } 4387 4388 MVT XLenVT = Subtarget.getXLenVT(); 4389 4390 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4391 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4392 // Even i64-element vectors on RV32 can be lowered without scalar 4393 // legalization if the most-significant 32 bits of the value are not affected 4394 // by the sign-extension of the lower 32 bits. 4395 // TODO: We could also catch sign extensions of a 32-bit value. 4396 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4397 const auto *CVal = cast<ConstantSDNode>(Val); 4398 if (isInt<32>(CVal->getSExtValue())) { 4399 IsLegalInsert = true; 4400 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4401 } 4402 } 4403 4404 SDValue Mask, VL; 4405 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4406 4407 SDValue ValInVec; 4408 4409 if (IsLegalInsert) { 4410 unsigned Opc = 4411 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4412 if (isNullConstant(Idx)) { 4413 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4414 if (!VecVT.isFixedLengthVector()) 4415 return Vec; 4416 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4417 } 4418 ValInVec = 4419 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4420 } else { 4421 // On RV32, i64-element vectors must be specially handled to place the 4422 // value at element 0, by using two vslide1up instructions in sequence on 4423 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4424 // this. 4425 SDValue One = DAG.getConstant(1, DL, XLenVT); 4426 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4427 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4428 MVT I32ContainerVT = 4429 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4430 SDValue I32Mask = 4431 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4432 // Limit the active VL to two. 4433 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4434 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4435 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4436 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4437 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4438 // First slide in the hi value, then the lo in underneath it. 4439 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4440 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4441 I32Mask, InsertI64VL); 4442 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4443 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4444 I32Mask, InsertI64VL); 4445 // Bitcast back to the right container type. 4446 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4447 } 4448 4449 // Now that the value is in a vector, slide it into position. 4450 SDValue InsertVL = 4451 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4452 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4453 ValInVec, Idx, Mask, InsertVL); 4454 if (!VecVT.isFixedLengthVector()) 4455 return Slideup; 4456 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4457 } 4458 4459 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4460 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4461 // types this is done using VMV_X_S to allow us to glean information about the 4462 // sign bits of the result. 4463 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4464 SelectionDAG &DAG) const { 4465 SDLoc DL(Op); 4466 SDValue Idx = Op.getOperand(1); 4467 SDValue Vec = Op.getOperand(0); 4468 EVT EltVT = Op.getValueType(); 4469 MVT VecVT = Vec.getSimpleValueType(); 4470 MVT XLenVT = Subtarget.getXLenVT(); 4471 4472 if (VecVT.getVectorElementType() == MVT::i1) { 4473 if (VecVT.isFixedLengthVector()) { 4474 unsigned NumElts = VecVT.getVectorNumElements(); 4475 if (NumElts >= 8) { 4476 MVT WideEltVT; 4477 unsigned WidenVecLen; 4478 SDValue ExtractElementIdx; 4479 SDValue ExtractBitIdx; 4480 unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors(); 4481 MVT LargestEltVT = MVT::getIntegerVT( 4482 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4483 if (NumElts <= LargestEltVT.getSizeInBits()) { 4484 assert(isPowerOf2_32(NumElts) && 4485 "the number of elements should be power of 2"); 4486 WideEltVT = MVT::getIntegerVT(NumElts); 4487 WidenVecLen = 1; 4488 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4489 ExtractBitIdx = Idx; 4490 } else { 4491 WideEltVT = LargestEltVT; 4492 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4493 // extract element index = index / element width 4494 ExtractElementIdx = DAG.getNode( 4495 ISD::SRL, DL, XLenVT, Idx, 4496 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4497 // mask bit index = index % element width 4498 ExtractBitIdx = DAG.getNode( 4499 ISD::AND, DL, XLenVT, Idx, 4500 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4501 } 4502 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4503 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4504 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4505 Vec, ExtractElementIdx); 4506 // Extract the bit from GPR. 4507 SDValue ShiftRight = 4508 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4509 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4510 DAG.getConstant(1, DL, XLenVT)); 4511 } 4512 } 4513 // Otherwise, promote to an i8 vector and extract from that. 4514 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4515 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4516 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4517 } 4518 4519 // If this is a fixed vector, we need to convert it to a scalable vector. 4520 MVT ContainerVT = VecVT; 4521 if (VecVT.isFixedLengthVector()) { 4522 ContainerVT = getContainerForFixedLengthVector(VecVT); 4523 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4524 } 4525 4526 // If the index is 0, the vector is already in the right position. 4527 if (!isNullConstant(Idx)) { 4528 // Use a VL of 1 to avoid processing more elements than we need. 4529 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4530 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4531 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4532 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4533 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4534 } 4535 4536 if (!EltVT.isInteger()) { 4537 // Floating-point extracts are handled in TableGen. 4538 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4539 DAG.getConstant(0, DL, XLenVT)); 4540 } 4541 4542 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4543 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4544 } 4545 4546 // Some RVV intrinsics may claim that they want an integer operand to be 4547 // promoted or expanded. 4548 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 4549 const RISCVSubtarget &Subtarget) { 4550 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4551 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4552 "Unexpected opcode"); 4553 4554 if (!Subtarget.hasVInstructions()) 4555 return SDValue(); 4556 4557 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4558 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4559 SDLoc DL(Op); 4560 4561 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4562 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4563 if (!II || !II->hasSplatOperand()) 4564 return SDValue(); 4565 4566 unsigned SplatOp = II->SplatOperand + 1 + HasChain; 4567 assert(SplatOp < Op.getNumOperands()); 4568 4569 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4570 SDValue &ScalarOp = Operands[SplatOp]; 4571 MVT OpVT = ScalarOp.getSimpleValueType(); 4572 MVT XLenVT = Subtarget.getXLenVT(); 4573 4574 // If this isn't a scalar, or its type is XLenVT we're done. 4575 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4576 return SDValue(); 4577 4578 // Simplest case is that the operand needs to be promoted to XLenVT. 4579 if (OpVT.bitsLT(XLenVT)) { 4580 // If the operand is a constant, sign extend to increase our chances 4581 // of being able to use a .vi instruction. ANY_EXTEND would become a 4582 // a zero extend and the simm5 check in isel would fail. 4583 // FIXME: Should we ignore the upper bits in isel instead? 4584 unsigned ExtOpc = 4585 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4586 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4587 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4588 } 4589 4590 // Use the previous operand to get the vXi64 VT. The result might be a mask 4591 // VT for compares. Using the previous operand assumes that the previous 4592 // operand will never have a smaller element size than a scalar operand and 4593 // that a widening operation never uses SEW=64. 4594 // NOTE: If this fails the below assert, we can probably just find the 4595 // element count from any operand or result and use it to construct the VT. 4596 assert(II->SplatOperand > 0 && "Unexpected splat operand!"); 4597 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4598 4599 // The more complex case is when the scalar is larger than XLenVT. 4600 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4601 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4602 4603 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4604 // on the instruction to sign-extend since SEW>XLEN. 4605 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4606 if (isInt<32>(CVal->getSExtValue())) { 4607 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4608 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4609 } 4610 } 4611 4612 // We need to convert the scalar to a splat vector. 4613 // FIXME: Can we implicitly truncate the scalar if it is known to 4614 // be sign extended? 4615 SDValue VL = getVLOperand(Op); 4616 assert(VL.getValueType() == XLenVT); 4617 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4618 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4619 } 4620 4621 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4622 SelectionDAG &DAG) const { 4623 unsigned IntNo = Op.getConstantOperandVal(0); 4624 SDLoc DL(Op); 4625 MVT XLenVT = Subtarget.getXLenVT(); 4626 4627 switch (IntNo) { 4628 default: 4629 break; // Don't custom lower most intrinsics. 4630 case Intrinsic::thread_pointer: { 4631 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4632 return DAG.getRegister(RISCV::X4, PtrVT); 4633 } 4634 case Intrinsic::riscv_orc_b: 4635 case Intrinsic::riscv_brev8: { 4636 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4637 unsigned Opc = 4638 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4639 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4640 DAG.getConstant(7, DL, XLenVT)); 4641 } 4642 case Intrinsic::riscv_grev: 4643 case Intrinsic::riscv_gorc: { 4644 unsigned Opc = 4645 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4646 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4647 } 4648 case Intrinsic::riscv_zip: 4649 case Intrinsic::riscv_unzip: { 4650 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4651 // For i32 the immdiate is 15. For i64 the immediate is 31. 4652 unsigned Opc = 4653 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4654 unsigned BitWidth = Op.getValueSizeInBits(); 4655 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4656 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4657 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4658 } 4659 case Intrinsic::riscv_shfl: 4660 case Intrinsic::riscv_unshfl: { 4661 unsigned Opc = 4662 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4663 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4664 } 4665 case Intrinsic::riscv_bcompress: 4666 case Intrinsic::riscv_bdecompress: { 4667 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4668 : RISCVISD::BDECOMPRESS; 4669 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4670 } 4671 case Intrinsic::riscv_bfp: 4672 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4673 Op.getOperand(2)); 4674 case Intrinsic::riscv_fsl: 4675 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4676 Op.getOperand(2), Op.getOperand(3)); 4677 case Intrinsic::riscv_fsr: 4678 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4679 Op.getOperand(2), Op.getOperand(3)); 4680 case Intrinsic::riscv_vmv_x_s: 4681 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4682 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4683 Op.getOperand(1)); 4684 case Intrinsic::riscv_vmv_v_x: 4685 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4686 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4687 Subtarget); 4688 case Intrinsic::riscv_vfmv_v_f: 4689 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4690 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4691 case Intrinsic::riscv_vmv_s_x: { 4692 SDValue Scalar = Op.getOperand(2); 4693 4694 if (Scalar.getValueType().bitsLE(XLenVT)) { 4695 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4696 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4697 Op.getOperand(1), Scalar, Op.getOperand(3)); 4698 } 4699 4700 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4701 4702 // This is an i64 value that lives in two scalar registers. We have to 4703 // insert this in a convoluted way. First we build vXi64 splat containing 4704 // the/ two values that we assemble using some bit math. Next we'll use 4705 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4706 // to merge element 0 from our splat into the source vector. 4707 // FIXME: This is probably not the best way to do this, but it is 4708 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4709 // point. 4710 // sw lo, (a0) 4711 // sw hi, 4(a0) 4712 // vlse vX, (a0) 4713 // 4714 // vid.v vVid 4715 // vmseq.vx mMask, vVid, 0 4716 // vmerge.vvm vDest, vSrc, vVal, mMask 4717 MVT VT = Op.getSimpleValueType(); 4718 SDValue Vec = Op.getOperand(1); 4719 SDValue VL = getVLOperand(Op); 4720 4721 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4722 if (Op.getOperand(1).isUndef()) 4723 return SplattedVal; 4724 SDValue SplattedIdx = 4725 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4726 DAG.getConstant(0, DL, MVT::i32), VL); 4727 4728 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4729 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4730 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4731 SDValue SelectCond = 4732 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4733 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4734 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4735 Vec, VL); 4736 } 4737 case Intrinsic::riscv_vslide1up: 4738 case Intrinsic::riscv_vslide1down: 4739 case Intrinsic::riscv_vslide1up_mask: 4740 case Intrinsic::riscv_vslide1down_mask: { 4741 // We need to special case these when the scalar is larger than XLen. 4742 unsigned NumOps = Op.getNumOperands(); 4743 bool IsMasked = NumOps == 7; 4744 SDValue Scalar = Op.getOperand(3); 4745 if (Scalar.getValueType().bitsLE(XLenVT)) 4746 break; 4747 4748 // Splatting a sign extended constant is fine. 4749 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4750 if (isInt<32>(CVal->getSExtValue())) 4751 break; 4752 4753 MVT VT = Op.getSimpleValueType(); 4754 assert(VT.getVectorElementType() == MVT::i64 && 4755 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4756 4757 // Convert the vector source to the equivalent nxvXi32 vector. 4758 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4759 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(2)); 4760 4761 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4762 DAG.getConstant(0, DL, XLenVT)); 4763 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4764 DAG.getConstant(1, DL, XLenVT)); 4765 4766 // Double the VL since we halved SEW. 4767 SDValue VL = getVLOperand(Op); 4768 SDValue I32VL = 4769 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4770 4771 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4772 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4773 4774 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4775 // instructions. 4776 SDValue Passthru = DAG.getBitcast(I32VT, Op.getOperand(1)); 4777 if (!IsMasked) { 4778 if (IntNo == Intrinsic::riscv_vslide1up) { 4779 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4780 ScalarHi, I32Mask, I32VL); 4781 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4782 ScalarLo, I32Mask, I32VL); 4783 } else { 4784 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4785 ScalarLo, I32Mask, I32VL); 4786 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4787 ScalarHi, I32Mask, I32VL); 4788 } 4789 } else { 4790 // TODO Those VSLIDE1 could be TAMA because we use vmerge to select 4791 // maskedoff 4792 SDValue Undef = DAG.getUNDEF(I32VT); 4793 if (IntNo == Intrinsic::riscv_vslide1up_mask) { 4794 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec, 4795 ScalarHi, I32Mask, I32VL); 4796 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec, 4797 ScalarLo, I32Mask, I32VL); 4798 } else { 4799 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec, 4800 ScalarLo, I32Mask, I32VL); 4801 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec, 4802 ScalarHi, I32Mask, I32VL); 4803 } 4804 } 4805 4806 // Convert back to nxvXi64. 4807 Vec = DAG.getBitcast(VT, Vec); 4808 4809 if (!IsMasked) 4810 return Vec; 4811 // Apply mask after the operation. 4812 SDValue Mask = Op.getOperand(NumOps - 3); 4813 SDValue MaskedOff = Op.getOperand(1); 4814 // Assume Policy operand is the last operand. 4815 uint64_t Policy = Op.getConstantOperandVal(NumOps - 1); 4816 // We don't need to select maskedoff if it's undef. 4817 if (MaskedOff.isUndef()) 4818 return Vec; 4819 // TAMU 4820 if (Policy == RISCVII::TAIL_AGNOSTIC) 4821 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4822 VL); 4823 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4824 // It's fine because vmerge does not care mask policy. 4825 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4826 } 4827 } 4828 4829 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4830 } 4831 4832 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4833 SelectionDAG &DAG) const { 4834 unsigned IntNo = Op.getConstantOperandVal(1); 4835 switch (IntNo) { 4836 default: 4837 break; 4838 case Intrinsic::riscv_masked_strided_load: { 4839 SDLoc DL(Op); 4840 MVT XLenVT = Subtarget.getXLenVT(); 4841 4842 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4843 // the selection of the masked intrinsics doesn't do this for us. 4844 SDValue Mask = Op.getOperand(5); 4845 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4846 4847 MVT VT = Op->getSimpleValueType(0); 4848 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4849 4850 SDValue PassThru = Op.getOperand(2); 4851 if (!IsUnmasked) { 4852 MVT MaskVT = 4853 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4854 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4855 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4856 } 4857 4858 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4859 4860 SDValue IntID = DAG.getTargetConstant( 4861 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4862 XLenVT); 4863 4864 auto *Load = cast<MemIntrinsicSDNode>(Op); 4865 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4866 if (IsUnmasked) 4867 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4868 else 4869 Ops.push_back(PassThru); 4870 Ops.push_back(Op.getOperand(3)); // Ptr 4871 Ops.push_back(Op.getOperand(4)); // Stride 4872 if (!IsUnmasked) 4873 Ops.push_back(Mask); 4874 Ops.push_back(VL); 4875 if (!IsUnmasked) { 4876 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4877 Ops.push_back(Policy); 4878 } 4879 4880 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4881 SDValue Result = 4882 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4883 Load->getMemoryVT(), Load->getMemOperand()); 4884 SDValue Chain = Result.getValue(1); 4885 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4886 return DAG.getMergeValues({Result, Chain}, DL); 4887 } 4888 } 4889 4890 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4891 } 4892 4893 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4894 SelectionDAG &DAG) const { 4895 unsigned IntNo = Op.getConstantOperandVal(1); 4896 switch (IntNo) { 4897 default: 4898 break; 4899 case Intrinsic::riscv_masked_strided_store: { 4900 SDLoc DL(Op); 4901 MVT XLenVT = Subtarget.getXLenVT(); 4902 4903 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4904 // the selection of the masked intrinsics doesn't do this for us. 4905 SDValue Mask = Op.getOperand(5); 4906 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4907 4908 SDValue Val = Op.getOperand(2); 4909 MVT VT = Val.getSimpleValueType(); 4910 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4911 4912 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4913 if (!IsUnmasked) { 4914 MVT MaskVT = 4915 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4916 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4917 } 4918 4919 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4920 4921 SDValue IntID = DAG.getTargetConstant( 4922 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4923 XLenVT); 4924 4925 auto *Store = cast<MemIntrinsicSDNode>(Op); 4926 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4927 Ops.push_back(Val); 4928 Ops.push_back(Op.getOperand(3)); // Ptr 4929 Ops.push_back(Op.getOperand(4)); // Stride 4930 if (!IsUnmasked) 4931 Ops.push_back(Mask); 4932 Ops.push_back(VL); 4933 4934 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4935 Ops, Store->getMemoryVT(), 4936 Store->getMemOperand()); 4937 } 4938 } 4939 4940 return SDValue(); 4941 } 4942 4943 static MVT getLMUL1VT(MVT VT) { 4944 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4945 "Unexpected vector MVT"); 4946 return MVT::getScalableVectorVT( 4947 VT.getVectorElementType(), 4948 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4949 } 4950 4951 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4952 switch (ISDOpcode) { 4953 default: 4954 llvm_unreachable("Unhandled reduction"); 4955 case ISD::VECREDUCE_ADD: 4956 return RISCVISD::VECREDUCE_ADD_VL; 4957 case ISD::VECREDUCE_UMAX: 4958 return RISCVISD::VECREDUCE_UMAX_VL; 4959 case ISD::VECREDUCE_SMAX: 4960 return RISCVISD::VECREDUCE_SMAX_VL; 4961 case ISD::VECREDUCE_UMIN: 4962 return RISCVISD::VECREDUCE_UMIN_VL; 4963 case ISD::VECREDUCE_SMIN: 4964 return RISCVISD::VECREDUCE_SMIN_VL; 4965 case ISD::VECREDUCE_AND: 4966 return RISCVISD::VECREDUCE_AND_VL; 4967 case ISD::VECREDUCE_OR: 4968 return RISCVISD::VECREDUCE_OR_VL; 4969 case ISD::VECREDUCE_XOR: 4970 return RISCVISD::VECREDUCE_XOR_VL; 4971 } 4972 } 4973 4974 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4975 SelectionDAG &DAG, 4976 bool IsVP) const { 4977 SDLoc DL(Op); 4978 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4979 MVT VecVT = Vec.getSimpleValueType(); 4980 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4981 Op.getOpcode() == ISD::VECREDUCE_OR || 4982 Op.getOpcode() == ISD::VECREDUCE_XOR || 4983 Op.getOpcode() == ISD::VP_REDUCE_AND || 4984 Op.getOpcode() == ISD::VP_REDUCE_OR || 4985 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4986 "Unexpected reduction lowering"); 4987 4988 MVT XLenVT = Subtarget.getXLenVT(); 4989 assert(Op.getValueType() == XLenVT && 4990 "Expected reduction output to be legalized to XLenVT"); 4991 4992 MVT ContainerVT = VecVT; 4993 if (VecVT.isFixedLengthVector()) { 4994 ContainerVT = getContainerForFixedLengthVector(VecVT); 4995 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4996 } 4997 4998 SDValue Mask, VL; 4999 if (IsVP) { 5000 Mask = Op.getOperand(2); 5001 VL = Op.getOperand(3); 5002 } else { 5003 std::tie(Mask, VL) = 5004 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5005 } 5006 5007 unsigned BaseOpc; 5008 ISD::CondCode CC; 5009 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5010 5011 switch (Op.getOpcode()) { 5012 default: 5013 llvm_unreachable("Unhandled reduction"); 5014 case ISD::VECREDUCE_AND: 5015 case ISD::VP_REDUCE_AND: { 5016 // vcpop ~x == 0 5017 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5018 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5019 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5020 CC = ISD::SETEQ; 5021 BaseOpc = ISD::AND; 5022 break; 5023 } 5024 case ISD::VECREDUCE_OR: 5025 case ISD::VP_REDUCE_OR: 5026 // vcpop x != 0 5027 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5028 CC = ISD::SETNE; 5029 BaseOpc = ISD::OR; 5030 break; 5031 case ISD::VECREDUCE_XOR: 5032 case ISD::VP_REDUCE_XOR: { 5033 // ((vcpop x) & 1) != 0 5034 SDValue One = DAG.getConstant(1, DL, XLenVT); 5035 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5036 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5037 CC = ISD::SETNE; 5038 BaseOpc = ISD::XOR; 5039 break; 5040 } 5041 } 5042 5043 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5044 5045 if (!IsVP) 5046 return SetCC; 5047 5048 // Now include the start value in the operation. 5049 // Note that we must return the start value when no elements are operated 5050 // upon. The vcpop instructions we've emitted in each case above will return 5051 // 0 for an inactive vector, and so we've already received the neutral value: 5052 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5053 // can simply include the start value. 5054 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5055 } 5056 5057 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5058 SelectionDAG &DAG) const { 5059 SDLoc DL(Op); 5060 SDValue Vec = Op.getOperand(0); 5061 EVT VecEVT = Vec.getValueType(); 5062 5063 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5064 5065 // Due to ordering in legalize types we may have a vector type that needs to 5066 // be split. Do that manually so we can get down to a legal type. 5067 while (getTypeAction(*DAG.getContext(), VecEVT) == 5068 TargetLowering::TypeSplitVector) { 5069 SDValue Lo, Hi; 5070 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5071 VecEVT = Lo.getValueType(); 5072 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5073 } 5074 5075 // TODO: The type may need to be widened rather than split. Or widened before 5076 // it can be split. 5077 if (!isTypeLegal(VecEVT)) 5078 return SDValue(); 5079 5080 MVT VecVT = VecEVT.getSimpleVT(); 5081 MVT VecEltVT = VecVT.getVectorElementType(); 5082 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5083 5084 MVT ContainerVT = VecVT; 5085 if (VecVT.isFixedLengthVector()) { 5086 ContainerVT = getContainerForFixedLengthVector(VecVT); 5087 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5088 } 5089 5090 MVT M1VT = getLMUL1VT(ContainerVT); 5091 MVT XLenVT = Subtarget.getXLenVT(); 5092 5093 SDValue Mask, VL; 5094 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5095 5096 SDValue NeutralElem = 5097 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5098 SDValue IdentitySplat = 5099 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5100 M1VT, DL, DAG, Subtarget); 5101 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5102 IdentitySplat, Mask, VL); 5103 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5104 DAG.getConstant(0, DL, XLenVT)); 5105 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5106 } 5107 5108 // Given a reduction op, this function returns the matching reduction opcode, 5109 // the vector SDValue and the scalar SDValue required to lower this to a 5110 // RISCVISD node. 5111 static std::tuple<unsigned, SDValue, SDValue> 5112 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5113 SDLoc DL(Op); 5114 auto Flags = Op->getFlags(); 5115 unsigned Opcode = Op.getOpcode(); 5116 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5117 switch (Opcode) { 5118 default: 5119 llvm_unreachable("Unhandled reduction"); 5120 case ISD::VECREDUCE_FADD: { 5121 // Use positive zero if we can. It is cheaper to materialize. 5122 SDValue Zero = 5123 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5124 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5125 } 5126 case ISD::VECREDUCE_SEQ_FADD: 5127 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5128 Op.getOperand(0)); 5129 case ISD::VECREDUCE_FMIN: 5130 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5131 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5132 case ISD::VECREDUCE_FMAX: 5133 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5134 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5135 } 5136 } 5137 5138 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5139 SelectionDAG &DAG) const { 5140 SDLoc DL(Op); 5141 MVT VecEltVT = Op.getSimpleValueType(); 5142 5143 unsigned RVVOpcode; 5144 SDValue VectorVal, ScalarVal; 5145 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5146 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5147 MVT VecVT = VectorVal.getSimpleValueType(); 5148 5149 MVT ContainerVT = VecVT; 5150 if (VecVT.isFixedLengthVector()) { 5151 ContainerVT = getContainerForFixedLengthVector(VecVT); 5152 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5153 } 5154 5155 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5156 MVT XLenVT = Subtarget.getXLenVT(); 5157 5158 SDValue Mask, VL; 5159 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5160 5161 SDValue ScalarSplat = 5162 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5163 M1VT, DL, DAG, Subtarget); 5164 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5165 VectorVal, ScalarSplat, Mask, VL); 5166 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5167 DAG.getConstant(0, DL, XLenVT)); 5168 } 5169 5170 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5171 switch (ISDOpcode) { 5172 default: 5173 llvm_unreachable("Unhandled reduction"); 5174 case ISD::VP_REDUCE_ADD: 5175 return RISCVISD::VECREDUCE_ADD_VL; 5176 case ISD::VP_REDUCE_UMAX: 5177 return RISCVISD::VECREDUCE_UMAX_VL; 5178 case ISD::VP_REDUCE_SMAX: 5179 return RISCVISD::VECREDUCE_SMAX_VL; 5180 case ISD::VP_REDUCE_UMIN: 5181 return RISCVISD::VECREDUCE_UMIN_VL; 5182 case ISD::VP_REDUCE_SMIN: 5183 return RISCVISD::VECREDUCE_SMIN_VL; 5184 case ISD::VP_REDUCE_AND: 5185 return RISCVISD::VECREDUCE_AND_VL; 5186 case ISD::VP_REDUCE_OR: 5187 return RISCVISD::VECREDUCE_OR_VL; 5188 case ISD::VP_REDUCE_XOR: 5189 return RISCVISD::VECREDUCE_XOR_VL; 5190 case ISD::VP_REDUCE_FADD: 5191 return RISCVISD::VECREDUCE_FADD_VL; 5192 case ISD::VP_REDUCE_SEQ_FADD: 5193 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5194 case ISD::VP_REDUCE_FMAX: 5195 return RISCVISD::VECREDUCE_FMAX_VL; 5196 case ISD::VP_REDUCE_FMIN: 5197 return RISCVISD::VECREDUCE_FMIN_VL; 5198 } 5199 } 5200 5201 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5202 SelectionDAG &DAG) const { 5203 SDLoc DL(Op); 5204 SDValue Vec = Op.getOperand(1); 5205 EVT VecEVT = Vec.getValueType(); 5206 5207 // TODO: The type may need to be widened rather than split. Or widened before 5208 // it can be split. 5209 if (!isTypeLegal(VecEVT)) 5210 return SDValue(); 5211 5212 MVT VecVT = VecEVT.getSimpleVT(); 5213 MVT VecEltVT = VecVT.getVectorElementType(); 5214 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5215 5216 MVT ContainerVT = VecVT; 5217 if (VecVT.isFixedLengthVector()) { 5218 ContainerVT = getContainerForFixedLengthVector(VecVT); 5219 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5220 } 5221 5222 SDValue VL = Op.getOperand(3); 5223 SDValue Mask = Op.getOperand(2); 5224 5225 MVT M1VT = getLMUL1VT(ContainerVT); 5226 MVT XLenVT = Subtarget.getXLenVT(); 5227 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5228 5229 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5230 DAG.getConstant(1, DL, XLenVT), M1VT, 5231 DL, DAG, Subtarget); 5232 SDValue Reduction = 5233 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5234 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5235 DAG.getConstant(0, DL, XLenVT)); 5236 if (!VecVT.isInteger()) 5237 return Elt0; 5238 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5239 } 5240 5241 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5242 SelectionDAG &DAG) const { 5243 SDValue Vec = Op.getOperand(0); 5244 SDValue SubVec = Op.getOperand(1); 5245 MVT VecVT = Vec.getSimpleValueType(); 5246 MVT SubVecVT = SubVec.getSimpleValueType(); 5247 5248 SDLoc DL(Op); 5249 MVT XLenVT = Subtarget.getXLenVT(); 5250 unsigned OrigIdx = Op.getConstantOperandVal(2); 5251 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5252 5253 // We don't have the ability to slide mask vectors up indexed by their i1 5254 // elements; the smallest we can do is i8. Often we are able to bitcast to 5255 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5256 // into a scalable one, we might not necessarily have enough scalable 5257 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5258 if (SubVecVT.getVectorElementType() == MVT::i1 && 5259 (OrigIdx != 0 || !Vec.isUndef())) { 5260 if (VecVT.getVectorMinNumElements() >= 8 && 5261 SubVecVT.getVectorMinNumElements() >= 8) { 5262 assert(OrigIdx % 8 == 0 && "Invalid index"); 5263 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5264 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5265 "Unexpected mask vector lowering"); 5266 OrigIdx /= 8; 5267 SubVecVT = 5268 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5269 SubVecVT.isScalableVector()); 5270 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5271 VecVT.isScalableVector()); 5272 Vec = DAG.getBitcast(VecVT, Vec); 5273 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5274 } else { 5275 // We can't slide this mask vector up indexed by its i1 elements. 5276 // This poses a problem when we wish to insert a scalable vector which 5277 // can't be re-expressed as a larger type. Just choose the slow path and 5278 // extend to a larger type, then truncate back down. 5279 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5280 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5281 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5282 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5283 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5284 Op.getOperand(2)); 5285 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5286 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5287 } 5288 } 5289 5290 // If the subvector vector is a fixed-length type, we cannot use subregister 5291 // manipulation to simplify the codegen; we don't know which register of a 5292 // LMUL group contains the specific subvector as we only know the minimum 5293 // register size. Therefore we must slide the vector group up the full 5294 // amount. 5295 if (SubVecVT.isFixedLengthVector()) { 5296 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5297 return Op; 5298 MVT ContainerVT = VecVT; 5299 if (VecVT.isFixedLengthVector()) { 5300 ContainerVT = getContainerForFixedLengthVector(VecVT); 5301 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5302 } 5303 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5304 DAG.getUNDEF(ContainerVT), SubVec, 5305 DAG.getConstant(0, DL, XLenVT)); 5306 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5307 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5308 return DAG.getBitcast(Op.getValueType(), SubVec); 5309 } 5310 SDValue Mask = 5311 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5312 // Set the vector length to only the number of elements we care about. Note 5313 // that for slideup this includes the offset. 5314 SDValue VL = 5315 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5316 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5317 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5318 SubVec, SlideupAmt, Mask, VL); 5319 if (VecVT.isFixedLengthVector()) 5320 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5321 return DAG.getBitcast(Op.getValueType(), Slideup); 5322 } 5323 5324 unsigned SubRegIdx, RemIdx; 5325 std::tie(SubRegIdx, RemIdx) = 5326 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5327 VecVT, SubVecVT, OrigIdx, TRI); 5328 5329 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5330 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5331 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5332 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5333 5334 // 1. If the Idx has been completely eliminated and this subvector's size is 5335 // a vector register or a multiple thereof, or the surrounding elements are 5336 // undef, then this is a subvector insert which naturally aligns to a vector 5337 // register. These can easily be handled using subregister manipulation. 5338 // 2. If the subvector is smaller than a vector register, then the insertion 5339 // must preserve the undisturbed elements of the register. We do this by 5340 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5341 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5342 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5343 // LMUL=1 type back into the larger vector (resolving to another subregister 5344 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5345 // to avoid allocating a large register group to hold our subvector. 5346 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5347 return Op; 5348 5349 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5350 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5351 // (in our case undisturbed). This means we can set up a subvector insertion 5352 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5353 // size of the subvector. 5354 MVT InterSubVT = VecVT; 5355 SDValue AlignedExtract = Vec; 5356 unsigned AlignedIdx = OrigIdx - RemIdx; 5357 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5358 InterSubVT = getLMUL1VT(VecVT); 5359 // Extract a subvector equal to the nearest full vector register type. This 5360 // should resolve to a EXTRACT_SUBREG instruction. 5361 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5362 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5363 } 5364 5365 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5366 // For scalable vectors this must be further multiplied by vscale. 5367 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5368 5369 SDValue Mask, VL; 5370 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5371 5372 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5373 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5374 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5375 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5376 5377 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5378 DAG.getUNDEF(InterSubVT), SubVec, 5379 DAG.getConstant(0, DL, XLenVT)); 5380 5381 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5382 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5383 5384 // If required, insert this subvector back into the correct vector register. 5385 // This should resolve to an INSERT_SUBREG instruction. 5386 if (VecVT.bitsGT(InterSubVT)) 5387 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5388 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5389 5390 // We might have bitcast from a mask type: cast back to the original type if 5391 // required. 5392 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5393 } 5394 5395 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5396 SelectionDAG &DAG) const { 5397 SDValue Vec = Op.getOperand(0); 5398 MVT SubVecVT = Op.getSimpleValueType(); 5399 MVT VecVT = Vec.getSimpleValueType(); 5400 5401 SDLoc DL(Op); 5402 MVT XLenVT = Subtarget.getXLenVT(); 5403 unsigned OrigIdx = Op.getConstantOperandVal(1); 5404 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5405 5406 // We don't have the ability to slide mask vectors down indexed by their i1 5407 // elements; the smallest we can do is i8. Often we are able to bitcast to 5408 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5409 // from a scalable one, we might not necessarily have enough scalable 5410 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5411 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5412 if (VecVT.getVectorMinNumElements() >= 8 && 5413 SubVecVT.getVectorMinNumElements() >= 8) { 5414 assert(OrigIdx % 8 == 0 && "Invalid index"); 5415 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5416 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5417 "Unexpected mask vector lowering"); 5418 OrigIdx /= 8; 5419 SubVecVT = 5420 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5421 SubVecVT.isScalableVector()); 5422 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5423 VecVT.isScalableVector()); 5424 Vec = DAG.getBitcast(VecVT, Vec); 5425 } else { 5426 // We can't slide this mask vector down, indexed by its i1 elements. 5427 // This poses a problem when we wish to extract a scalable vector which 5428 // can't be re-expressed as a larger type. Just choose the slow path and 5429 // extend to a larger type, then truncate back down. 5430 // TODO: We could probably improve this when extracting certain fixed 5431 // from fixed, where we can extract as i8 and shift the correct element 5432 // right to reach the desired subvector? 5433 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5434 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5435 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5436 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5437 Op.getOperand(1)); 5438 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5439 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5440 } 5441 } 5442 5443 // If the subvector vector is a fixed-length type, we cannot use subregister 5444 // manipulation to simplify the codegen; we don't know which register of a 5445 // LMUL group contains the specific subvector as we only know the minimum 5446 // register size. Therefore we must slide the vector group down the full 5447 // amount. 5448 if (SubVecVT.isFixedLengthVector()) { 5449 // With an index of 0 this is a cast-like subvector, which can be performed 5450 // with subregister operations. 5451 if (OrigIdx == 0) 5452 return Op; 5453 MVT ContainerVT = VecVT; 5454 if (VecVT.isFixedLengthVector()) { 5455 ContainerVT = getContainerForFixedLengthVector(VecVT); 5456 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5457 } 5458 SDValue Mask = 5459 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5460 // Set the vector length to only the number of elements we care about. This 5461 // avoids sliding down elements we're going to discard straight away. 5462 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5463 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5464 SDValue Slidedown = 5465 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5466 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5467 // Now we can use a cast-like subvector extract to get the result. 5468 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5469 DAG.getConstant(0, DL, XLenVT)); 5470 return DAG.getBitcast(Op.getValueType(), Slidedown); 5471 } 5472 5473 unsigned SubRegIdx, RemIdx; 5474 std::tie(SubRegIdx, RemIdx) = 5475 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5476 VecVT, SubVecVT, OrigIdx, TRI); 5477 5478 // If the Idx has been completely eliminated then this is a subvector extract 5479 // which naturally aligns to a vector register. These can easily be handled 5480 // using subregister manipulation. 5481 if (RemIdx == 0) 5482 return Op; 5483 5484 // Else we must shift our vector register directly to extract the subvector. 5485 // Do this using VSLIDEDOWN. 5486 5487 // If the vector type is an LMUL-group type, extract a subvector equal to the 5488 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5489 // instruction. 5490 MVT InterSubVT = VecVT; 5491 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5492 InterSubVT = getLMUL1VT(VecVT); 5493 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5494 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5495 } 5496 5497 // Slide this vector register down by the desired number of elements in order 5498 // to place the desired subvector starting at element 0. 5499 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5500 // For scalable vectors this must be further multiplied by vscale. 5501 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5502 5503 SDValue Mask, VL; 5504 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5505 SDValue Slidedown = 5506 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5507 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5508 5509 // Now the vector is in the right position, extract our final subvector. This 5510 // should resolve to a COPY. 5511 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5512 DAG.getConstant(0, DL, XLenVT)); 5513 5514 // We might have bitcast from a mask type: cast back to the original type if 5515 // required. 5516 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5517 } 5518 5519 // Lower step_vector to the vid instruction. Any non-identity step value must 5520 // be accounted for my manual expansion. 5521 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5522 SelectionDAG &DAG) const { 5523 SDLoc DL(Op); 5524 MVT VT = Op.getSimpleValueType(); 5525 MVT XLenVT = Subtarget.getXLenVT(); 5526 SDValue Mask, VL; 5527 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5528 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5529 uint64_t StepValImm = Op.getConstantOperandVal(0); 5530 if (StepValImm != 1) { 5531 if (isPowerOf2_64(StepValImm)) { 5532 SDValue StepVal = 5533 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5534 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5535 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5536 } else { 5537 SDValue StepVal = lowerScalarSplat( 5538 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5539 VL, VT, DL, DAG, Subtarget); 5540 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5541 } 5542 } 5543 return StepVec; 5544 } 5545 5546 // Implement vector_reverse using vrgather.vv with indices determined by 5547 // subtracting the id of each element from (VLMAX-1). This will convert 5548 // the indices like so: 5549 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5550 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5551 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5552 SelectionDAG &DAG) const { 5553 SDLoc DL(Op); 5554 MVT VecVT = Op.getSimpleValueType(); 5555 unsigned EltSize = VecVT.getScalarSizeInBits(); 5556 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5557 5558 unsigned MaxVLMAX = 0; 5559 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5560 if (VectorBitsMax != 0) 5561 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5562 5563 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5564 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5565 5566 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5567 // to use vrgatherei16.vv. 5568 // TODO: It's also possible to use vrgatherei16.vv for other types to 5569 // decrease register width for the index calculation. 5570 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5571 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5572 // Reverse each half, then reassemble them in reverse order. 5573 // NOTE: It's also possible that after splitting that VLMAX no longer 5574 // requires vrgatherei16.vv. 5575 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5576 SDValue Lo, Hi; 5577 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5578 EVT LoVT, HiVT; 5579 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5580 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5581 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5582 // Reassemble the low and high pieces reversed. 5583 // FIXME: This is a CONCAT_VECTORS. 5584 SDValue Res = 5585 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5586 DAG.getIntPtrConstant(0, DL)); 5587 return DAG.getNode( 5588 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5589 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5590 } 5591 5592 // Just promote the int type to i16 which will double the LMUL. 5593 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5594 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5595 } 5596 5597 MVT XLenVT = Subtarget.getXLenVT(); 5598 SDValue Mask, VL; 5599 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5600 5601 // Calculate VLMAX-1 for the desired SEW. 5602 unsigned MinElts = VecVT.getVectorMinNumElements(); 5603 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5604 DAG.getConstant(MinElts, DL, XLenVT)); 5605 SDValue VLMinus1 = 5606 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5607 5608 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5609 bool IsRV32E64 = 5610 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5611 SDValue SplatVL; 5612 if (!IsRV32E64) 5613 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5614 else 5615 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5616 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5617 5618 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5619 SDValue Indices = 5620 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5621 5622 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5623 } 5624 5625 SDValue 5626 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5627 SelectionDAG &DAG) const { 5628 SDLoc DL(Op); 5629 auto *Load = cast<LoadSDNode>(Op); 5630 5631 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5632 Load->getMemoryVT(), 5633 *Load->getMemOperand()) && 5634 "Expecting a correctly-aligned load"); 5635 5636 MVT VT = Op.getSimpleValueType(); 5637 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5638 5639 SDValue VL = 5640 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5641 5642 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5643 SDValue NewLoad = DAG.getMemIntrinsicNode( 5644 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5645 Load->getMemoryVT(), Load->getMemOperand()); 5646 5647 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5648 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5649 } 5650 5651 SDValue 5652 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5653 SelectionDAG &DAG) const { 5654 SDLoc DL(Op); 5655 auto *Store = cast<StoreSDNode>(Op); 5656 5657 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5658 Store->getMemoryVT(), 5659 *Store->getMemOperand()) && 5660 "Expecting a correctly-aligned store"); 5661 5662 SDValue StoreVal = Store->getValue(); 5663 MVT VT = StoreVal.getSimpleValueType(); 5664 5665 // If the size less than a byte, we need to pad with zeros to make a byte. 5666 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5667 VT = MVT::v8i1; 5668 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5669 DAG.getConstant(0, DL, VT), StoreVal, 5670 DAG.getIntPtrConstant(0, DL)); 5671 } 5672 5673 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5674 5675 SDValue VL = 5676 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5677 5678 SDValue NewValue = 5679 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5680 return DAG.getMemIntrinsicNode( 5681 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5682 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5683 Store->getMemoryVT(), Store->getMemOperand()); 5684 } 5685 5686 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5687 SelectionDAG &DAG) const { 5688 SDLoc DL(Op); 5689 MVT VT = Op.getSimpleValueType(); 5690 5691 const auto *MemSD = cast<MemSDNode>(Op); 5692 EVT MemVT = MemSD->getMemoryVT(); 5693 MachineMemOperand *MMO = MemSD->getMemOperand(); 5694 SDValue Chain = MemSD->getChain(); 5695 SDValue BasePtr = MemSD->getBasePtr(); 5696 5697 SDValue Mask, PassThru, VL; 5698 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5699 Mask = VPLoad->getMask(); 5700 PassThru = DAG.getUNDEF(VT); 5701 VL = VPLoad->getVectorLength(); 5702 } else { 5703 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5704 Mask = MLoad->getMask(); 5705 PassThru = MLoad->getPassThru(); 5706 } 5707 5708 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5709 5710 MVT XLenVT = Subtarget.getXLenVT(); 5711 5712 MVT ContainerVT = VT; 5713 if (VT.isFixedLengthVector()) { 5714 ContainerVT = getContainerForFixedLengthVector(VT); 5715 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5716 if (!IsUnmasked) { 5717 MVT MaskVT = 5718 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5719 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5720 } 5721 } 5722 5723 if (!VL) 5724 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5725 5726 unsigned IntID = 5727 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5728 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5729 if (IsUnmasked) 5730 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5731 else 5732 Ops.push_back(PassThru); 5733 Ops.push_back(BasePtr); 5734 if (!IsUnmasked) 5735 Ops.push_back(Mask); 5736 Ops.push_back(VL); 5737 if (!IsUnmasked) 5738 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5739 5740 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5741 5742 SDValue Result = 5743 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5744 Chain = Result.getValue(1); 5745 5746 if (VT.isFixedLengthVector()) 5747 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5748 5749 return DAG.getMergeValues({Result, Chain}, DL); 5750 } 5751 5752 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5753 SelectionDAG &DAG) const { 5754 SDLoc DL(Op); 5755 5756 const auto *MemSD = cast<MemSDNode>(Op); 5757 EVT MemVT = MemSD->getMemoryVT(); 5758 MachineMemOperand *MMO = MemSD->getMemOperand(); 5759 SDValue Chain = MemSD->getChain(); 5760 SDValue BasePtr = MemSD->getBasePtr(); 5761 SDValue Val, Mask, VL; 5762 5763 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5764 Val = VPStore->getValue(); 5765 Mask = VPStore->getMask(); 5766 VL = VPStore->getVectorLength(); 5767 } else { 5768 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5769 Val = MStore->getValue(); 5770 Mask = MStore->getMask(); 5771 } 5772 5773 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5774 5775 MVT VT = Val.getSimpleValueType(); 5776 MVT XLenVT = Subtarget.getXLenVT(); 5777 5778 MVT ContainerVT = VT; 5779 if (VT.isFixedLengthVector()) { 5780 ContainerVT = getContainerForFixedLengthVector(VT); 5781 5782 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5783 if (!IsUnmasked) { 5784 MVT MaskVT = 5785 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5786 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5787 } 5788 } 5789 5790 if (!VL) 5791 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5792 5793 unsigned IntID = 5794 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5795 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5796 Ops.push_back(Val); 5797 Ops.push_back(BasePtr); 5798 if (!IsUnmasked) 5799 Ops.push_back(Mask); 5800 Ops.push_back(VL); 5801 5802 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5803 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5804 } 5805 5806 SDValue 5807 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5808 SelectionDAG &DAG) const { 5809 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5810 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5811 5812 MVT VT = Op.getSimpleValueType(); 5813 5814 SDValue Op1 = 5815 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5816 SDValue Op2 = 5817 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5818 5819 SDLoc DL(Op); 5820 SDValue VL = 5821 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5822 5823 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5824 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5825 5826 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5827 Op.getOperand(2), Mask, VL); 5828 5829 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5830 } 5831 5832 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5833 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5834 MVT VT = Op.getSimpleValueType(); 5835 5836 if (VT.getVectorElementType() == MVT::i1) 5837 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5838 5839 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5840 } 5841 5842 SDValue 5843 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5844 SelectionDAG &DAG) const { 5845 unsigned Opc; 5846 switch (Op.getOpcode()) { 5847 default: llvm_unreachable("Unexpected opcode!"); 5848 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5849 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5850 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5851 } 5852 5853 return lowerToScalableOp(Op, DAG, Opc); 5854 } 5855 5856 // Lower vector ABS to smax(X, sub(0, X)). 5857 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5858 SDLoc DL(Op); 5859 MVT VT = Op.getSimpleValueType(); 5860 SDValue X = Op.getOperand(0); 5861 5862 assert(VT.isFixedLengthVector() && "Unexpected type"); 5863 5864 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5865 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5866 5867 SDValue Mask, VL; 5868 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5869 5870 SDValue SplatZero = DAG.getNode( 5871 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5872 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5873 SDValue NegX = 5874 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5875 SDValue Max = 5876 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5877 5878 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5879 } 5880 5881 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5882 SDValue Op, SelectionDAG &DAG) const { 5883 SDLoc DL(Op); 5884 MVT VT = Op.getSimpleValueType(); 5885 SDValue Mag = Op.getOperand(0); 5886 SDValue Sign = Op.getOperand(1); 5887 assert(Mag.getValueType() == Sign.getValueType() && 5888 "Can only handle COPYSIGN with matching types."); 5889 5890 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5891 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5892 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5893 5894 SDValue Mask, VL; 5895 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5896 5897 SDValue CopySign = 5898 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5899 5900 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5901 } 5902 5903 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5904 SDValue Op, SelectionDAG &DAG) const { 5905 MVT VT = Op.getSimpleValueType(); 5906 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5907 5908 MVT I1ContainerVT = 5909 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5910 5911 SDValue CC = 5912 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5913 SDValue Op1 = 5914 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5915 SDValue Op2 = 5916 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5917 5918 SDLoc DL(Op); 5919 SDValue Mask, VL; 5920 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5921 5922 SDValue Select = 5923 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5924 5925 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5926 } 5927 5928 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5929 unsigned NewOpc, 5930 bool HasMask) const { 5931 MVT VT = Op.getSimpleValueType(); 5932 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5933 5934 // Create list of operands by converting existing ones to scalable types. 5935 SmallVector<SDValue, 6> Ops; 5936 for (const SDValue &V : Op->op_values()) { 5937 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5938 5939 // Pass through non-vector operands. 5940 if (!V.getValueType().isVector()) { 5941 Ops.push_back(V); 5942 continue; 5943 } 5944 5945 // "cast" fixed length vector to a scalable vector. 5946 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5947 "Only fixed length vectors are supported!"); 5948 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5949 } 5950 5951 SDLoc DL(Op); 5952 SDValue Mask, VL; 5953 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5954 if (HasMask) 5955 Ops.push_back(Mask); 5956 Ops.push_back(VL); 5957 5958 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5959 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5960 } 5961 5962 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5963 // * Operands of each node are assumed to be in the same order. 5964 // * The EVL operand is promoted from i32 to i64 on RV64. 5965 // * Fixed-length vectors are converted to their scalable-vector container 5966 // types. 5967 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5968 unsigned RISCVISDOpc) const { 5969 SDLoc DL(Op); 5970 MVT VT = Op.getSimpleValueType(); 5971 SmallVector<SDValue, 4> Ops; 5972 5973 for (const auto &OpIdx : enumerate(Op->ops())) { 5974 SDValue V = OpIdx.value(); 5975 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5976 // Pass through operands which aren't fixed-length vectors. 5977 if (!V.getValueType().isFixedLengthVector()) { 5978 Ops.push_back(V); 5979 continue; 5980 } 5981 // "cast" fixed length vector to a scalable vector. 5982 MVT OpVT = V.getSimpleValueType(); 5983 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5984 assert(useRVVForFixedLengthVectorVT(OpVT) && 5985 "Only fixed length vectors are supported!"); 5986 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5987 } 5988 5989 if (!VT.isFixedLengthVector()) 5990 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5991 5992 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5993 5994 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5995 5996 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5997 } 5998 5999 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6000 unsigned MaskOpc, 6001 unsigned VecOpc) const { 6002 MVT VT = Op.getSimpleValueType(); 6003 if (VT.getVectorElementType() != MVT::i1) 6004 return lowerVPOp(Op, DAG, VecOpc); 6005 6006 // It is safe to drop mask parameter as masked-off elements are undef. 6007 SDValue Op1 = Op->getOperand(0); 6008 SDValue Op2 = Op->getOperand(1); 6009 SDValue VL = Op->getOperand(3); 6010 6011 MVT ContainerVT = VT; 6012 const bool IsFixed = VT.isFixedLengthVector(); 6013 if (IsFixed) { 6014 ContainerVT = getContainerForFixedLengthVector(VT); 6015 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6016 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6017 } 6018 6019 SDLoc DL(Op); 6020 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6021 if (!IsFixed) 6022 return Val; 6023 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6024 } 6025 6026 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6027 // matched to a RVV indexed load. The RVV indexed load instructions only 6028 // support the "unsigned unscaled" addressing mode; indices are implicitly 6029 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6030 // signed or scaled indexing is extended to the XLEN value type and scaled 6031 // accordingly. 6032 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6033 SelectionDAG &DAG) const { 6034 SDLoc DL(Op); 6035 MVT VT = Op.getSimpleValueType(); 6036 6037 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6038 EVT MemVT = MemSD->getMemoryVT(); 6039 MachineMemOperand *MMO = MemSD->getMemOperand(); 6040 SDValue Chain = MemSD->getChain(); 6041 SDValue BasePtr = MemSD->getBasePtr(); 6042 6043 ISD::LoadExtType LoadExtType; 6044 SDValue Index, Mask, PassThru, VL; 6045 6046 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6047 Index = VPGN->getIndex(); 6048 Mask = VPGN->getMask(); 6049 PassThru = DAG.getUNDEF(VT); 6050 VL = VPGN->getVectorLength(); 6051 // VP doesn't support extending loads. 6052 LoadExtType = ISD::NON_EXTLOAD; 6053 } else { 6054 // Else it must be a MGATHER. 6055 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6056 Index = MGN->getIndex(); 6057 Mask = MGN->getMask(); 6058 PassThru = MGN->getPassThru(); 6059 LoadExtType = MGN->getExtensionType(); 6060 } 6061 6062 MVT IndexVT = Index.getSimpleValueType(); 6063 MVT XLenVT = Subtarget.getXLenVT(); 6064 6065 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6066 "Unexpected VTs!"); 6067 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6068 // Targets have to explicitly opt-in for extending vector loads. 6069 assert(LoadExtType == ISD::NON_EXTLOAD && 6070 "Unexpected extending MGATHER/VP_GATHER"); 6071 (void)LoadExtType; 6072 6073 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6074 // the selection of the masked intrinsics doesn't do this for us. 6075 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6076 6077 MVT ContainerVT = VT; 6078 if (VT.isFixedLengthVector()) { 6079 // We need to use the larger of the result and index type to determine the 6080 // scalable type to use so we don't increase LMUL for any operand/result. 6081 if (VT.bitsGE(IndexVT)) { 6082 ContainerVT = getContainerForFixedLengthVector(VT); 6083 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6084 ContainerVT.getVectorElementCount()); 6085 } else { 6086 IndexVT = getContainerForFixedLengthVector(IndexVT); 6087 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6088 IndexVT.getVectorElementCount()); 6089 } 6090 6091 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6092 6093 if (!IsUnmasked) { 6094 MVT MaskVT = 6095 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6096 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6097 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6098 } 6099 } 6100 6101 if (!VL) 6102 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6103 6104 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6105 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6106 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6107 VL); 6108 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6109 TrueMask, VL); 6110 } 6111 6112 unsigned IntID = 6113 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6114 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6115 if (IsUnmasked) 6116 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6117 else 6118 Ops.push_back(PassThru); 6119 Ops.push_back(BasePtr); 6120 Ops.push_back(Index); 6121 if (!IsUnmasked) 6122 Ops.push_back(Mask); 6123 Ops.push_back(VL); 6124 if (!IsUnmasked) 6125 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6126 6127 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6128 SDValue Result = 6129 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6130 Chain = Result.getValue(1); 6131 6132 if (VT.isFixedLengthVector()) 6133 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6134 6135 return DAG.getMergeValues({Result, Chain}, DL); 6136 } 6137 6138 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6139 // matched to a RVV indexed store. The RVV indexed store instructions only 6140 // support the "unsigned unscaled" addressing mode; indices are implicitly 6141 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6142 // signed or scaled indexing is extended to the XLEN value type and scaled 6143 // accordingly. 6144 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6145 SelectionDAG &DAG) const { 6146 SDLoc DL(Op); 6147 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6148 EVT MemVT = MemSD->getMemoryVT(); 6149 MachineMemOperand *MMO = MemSD->getMemOperand(); 6150 SDValue Chain = MemSD->getChain(); 6151 SDValue BasePtr = MemSD->getBasePtr(); 6152 6153 bool IsTruncatingStore = false; 6154 SDValue Index, Mask, Val, VL; 6155 6156 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6157 Index = VPSN->getIndex(); 6158 Mask = VPSN->getMask(); 6159 Val = VPSN->getValue(); 6160 VL = VPSN->getVectorLength(); 6161 // VP doesn't support truncating stores. 6162 IsTruncatingStore = false; 6163 } else { 6164 // Else it must be a MSCATTER. 6165 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6166 Index = MSN->getIndex(); 6167 Mask = MSN->getMask(); 6168 Val = MSN->getValue(); 6169 IsTruncatingStore = MSN->isTruncatingStore(); 6170 } 6171 6172 MVT VT = Val.getSimpleValueType(); 6173 MVT IndexVT = Index.getSimpleValueType(); 6174 MVT XLenVT = Subtarget.getXLenVT(); 6175 6176 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6177 "Unexpected VTs!"); 6178 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6179 // Targets have to explicitly opt-in for extending vector loads and 6180 // truncating vector stores. 6181 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6182 (void)IsTruncatingStore; 6183 6184 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6185 // the selection of the masked intrinsics doesn't do this for us. 6186 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6187 6188 MVT ContainerVT = VT; 6189 if (VT.isFixedLengthVector()) { 6190 // We need to use the larger of the value and index type to determine the 6191 // scalable type to use so we don't increase LMUL for any operand/result. 6192 if (VT.bitsGE(IndexVT)) { 6193 ContainerVT = getContainerForFixedLengthVector(VT); 6194 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6195 ContainerVT.getVectorElementCount()); 6196 } else { 6197 IndexVT = getContainerForFixedLengthVector(IndexVT); 6198 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6199 IndexVT.getVectorElementCount()); 6200 } 6201 6202 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6203 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6204 6205 if (!IsUnmasked) { 6206 MVT MaskVT = 6207 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6208 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6209 } 6210 } 6211 6212 if (!VL) 6213 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6214 6215 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6216 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6217 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6218 VL); 6219 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6220 TrueMask, VL); 6221 } 6222 6223 unsigned IntID = 6224 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6225 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6226 Ops.push_back(Val); 6227 Ops.push_back(BasePtr); 6228 Ops.push_back(Index); 6229 if (!IsUnmasked) 6230 Ops.push_back(Mask); 6231 Ops.push_back(VL); 6232 6233 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6234 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6235 } 6236 6237 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6238 SelectionDAG &DAG) const { 6239 const MVT XLenVT = Subtarget.getXLenVT(); 6240 SDLoc DL(Op); 6241 SDValue Chain = Op->getOperand(0); 6242 SDValue SysRegNo = DAG.getTargetConstant( 6243 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6244 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6245 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6246 6247 // Encoding used for rounding mode in RISCV differs from that used in 6248 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6249 // table, which consists of a sequence of 4-bit fields, each representing 6250 // corresponding FLT_ROUNDS mode. 6251 static const int Table = 6252 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6253 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6254 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6255 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6256 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6257 6258 SDValue Shift = 6259 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6260 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6261 DAG.getConstant(Table, DL, XLenVT), Shift); 6262 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6263 DAG.getConstant(7, DL, XLenVT)); 6264 6265 return DAG.getMergeValues({Masked, Chain}, DL); 6266 } 6267 6268 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6269 SelectionDAG &DAG) const { 6270 const MVT XLenVT = Subtarget.getXLenVT(); 6271 SDLoc DL(Op); 6272 SDValue Chain = Op->getOperand(0); 6273 SDValue RMValue = Op->getOperand(1); 6274 SDValue SysRegNo = DAG.getTargetConstant( 6275 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6276 6277 // Encoding used for rounding mode in RISCV differs from that used in 6278 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6279 // a table, which consists of a sequence of 4-bit fields, each representing 6280 // corresponding RISCV mode. 6281 static const unsigned Table = 6282 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6283 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6284 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6285 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6286 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6287 6288 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6289 DAG.getConstant(2, DL, XLenVT)); 6290 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6291 DAG.getConstant(Table, DL, XLenVT), Shift); 6292 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6293 DAG.getConstant(0x7, DL, XLenVT)); 6294 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6295 RMValue); 6296 } 6297 6298 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6299 switch (IntNo) { 6300 default: 6301 llvm_unreachable("Unexpected Intrinsic"); 6302 case Intrinsic::riscv_grev: 6303 return RISCVISD::GREVW; 6304 case Intrinsic::riscv_gorc: 6305 return RISCVISD::GORCW; 6306 case Intrinsic::riscv_bcompress: 6307 return RISCVISD::BCOMPRESSW; 6308 case Intrinsic::riscv_bdecompress: 6309 return RISCVISD::BDECOMPRESSW; 6310 case Intrinsic::riscv_bfp: 6311 return RISCVISD::BFPW; 6312 case Intrinsic::riscv_fsl: 6313 return RISCVISD::FSLW; 6314 case Intrinsic::riscv_fsr: 6315 return RISCVISD::FSRW; 6316 } 6317 } 6318 6319 // Converts the given intrinsic to a i64 operation with any extension. 6320 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6321 unsigned IntNo) { 6322 SDLoc DL(N); 6323 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6324 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6325 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6326 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6327 // ReplaceNodeResults requires we maintain the same type for the return value. 6328 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6329 } 6330 6331 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6332 // form of the given Opcode. 6333 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6334 switch (Opcode) { 6335 default: 6336 llvm_unreachable("Unexpected opcode"); 6337 case ISD::SHL: 6338 return RISCVISD::SLLW; 6339 case ISD::SRA: 6340 return RISCVISD::SRAW; 6341 case ISD::SRL: 6342 return RISCVISD::SRLW; 6343 case ISD::SDIV: 6344 return RISCVISD::DIVW; 6345 case ISD::UDIV: 6346 return RISCVISD::DIVUW; 6347 case ISD::UREM: 6348 return RISCVISD::REMUW; 6349 case ISD::ROTL: 6350 return RISCVISD::ROLW; 6351 case ISD::ROTR: 6352 return RISCVISD::RORW; 6353 case RISCVISD::GREV: 6354 return RISCVISD::GREVW; 6355 case RISCVISD::GORC: 6356 return RISCVISD::GORCW; 6357 } 6358 } 6359 6360 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6361 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6362 // otherwise be promoted to i64, making it difficult to select the 6363 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6364 // type i8/i16/i32 is lost. 6365 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6366 unsigned ExtOpc = ISD::ANY_EXTEND) { 6367 SDLoc DL(N); 6368 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6369 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6370 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6371 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6372 // ReplaceNodeResults requires we maintain the same type for the return value. 6373 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6374 } 6375 6376 // Converts the given 32-bit operation to a i64 operation with signed extension 6377 // semantic to reduce the signed extension instructions. 6378 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6379 SDLoc DL(N); 6380 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6381 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6382 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6383 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6384 DAG.getValueType(MVT::i32)); 6385 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6386 } 6387 6388 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6389 SmallVectorImpl<SDValue> &Results, 6390 SelectionDAG &DAG) const { 6391 SDLoc DL(N); 6392 switch (N->getOpcode()) { 6393 default: 6394 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6395 case ISD::STRICT_FP_TO_SINT: 6396 case ISD::STRICT_FP_TO_UINT: 6397 case ISD::FP_TO_SINT: 6398 case ISD::FP_TO_UINT: { 6399 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6400 "Unexpected custom legalisation"); 6401 bool IsStrict = N->isStrictFPOpcode(); 6402 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6403 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6404 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6405 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6406 TargetLowering::TypeSoftenFloat) { 6407 if (!isTypeLegal(Op0.getValueType())) 6408 return; 6409 if (IsStrict) { 6410 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6411 : RISCVISD::STRICT_FCVT_WU_RV64; 6412 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6413 SDValue Res = DAG.getNode( 6414 Opc, DL, VTs, N->getOperand(0), Op0, 6415 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6416 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6417 Results.push_back(Res.getValue(1)); 6418 return; 6419 } 6420 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6421 SDValue Res = 6422 DAG.getNode(Opc, DL, MVT::i64, Op0, 6423 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6424 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6425 return; 6426 } 6427 // If the FP type needs to be softened, emit a library call using the 'si' 6428 // version. If we left it to default legalization we'd end up with 'di'. If 6429 // the FP type doesn't need to be softened just let generic type 6430 // legalization promote the result type. 6431 RTLIB::Libcall LC; 6432 if (IsSigned) 6433 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6434 else 6435 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6436 MakeLibCallOptions CallOptions; 6437 EVT OpVT = Op0.getValueType(); 6438 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6439 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6440 SDValue Result; 6441 std::tie(Result, Chain) = 6442 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6443 Results.push_back(Result); 6444 if (IsStrict) 6445 Results.push_back(Chain); 6446 break; 6447 } 6448 case ISD::READCYCLECOUNTER: { 6449 assert(!Subtarget.is64Bit() && 6450 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6451 6452 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6453 SDValue RCW = 6454 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6455 6456 Results.push_back( 6457 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6458 Results.push_back(RCW.getValue(2)); 6459 break; 6460 } 6461 case ISD::MUL: { 6462 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6463 unsigned XLen = Subtarget.getXLen(); 6464 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6465 if (Size > XLen) { 6466 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6467 SDValue LHS = N->getOperand(0); 6468 SDValue RHS = N->getOperand(1); 6469 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6470 6471 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6472 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6473 // We need exactly one side to be unsigned. 6474 if (LHSIsU == RHSIsU) 6475 return; 6476 6477 auto MakeMULPair = [&](SDValue S, SDValue U) { 6478 MVT XLenVT = Subtarget.getXLenVT(); 6479 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6480 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6481 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6482 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6483 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6484 }; 6485 6486 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6487 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6488 6489 // The other operand should be signed, but still prefer MULH when 6490 // possible. 6491 if (RHSIsU && LHSIsS && !RHSIsS) 6492 Results.push_back(MakeMULPair(LHS, RHS)); 6493 else if (LHSIsU && RHSIsS && !LHSIsS) 6494 Results.push_back(MakeMULPair(RHS, LHS)); 6495 6496 return; 6497 } 6498 LLVM_FALLTHROUGH; 6499 } 6500 case ISD::ADD: 6501 case ISD::SUB: 6502 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6503 "Unexpected custom legalisation"); 6504 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6505 break; 6506 case ISD::SHL: 6507 case ISD::SRA: 6508 case ISD::SRL: 6509 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6510 "Unexpected custom legalisation"); 6511 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6512 Results.push_back(customLegalizeToWOp(N, DAG)); 6513 break; 6514 } 6515 6516 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6517 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6518 // shift amount. 6519 if (N->getOpcode() == ISD::SHL) { 6520 SDLoc DL(N); 6521 SDValue NewOp0 = 6522 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6523 SDValue NewOp1 = 6524 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6525 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6526 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6527 DAG.getValueType(MVT::i32)); 6528 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6529 } 6530 6531 break; 6532 case ISD::ROTL: 6533 case ISD::ROTR: 6534 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6535 "Unexpected custom legalisation"); 6536 Results.push_back(customLegalizeToWOp(N, DAG)); 6537 break; 6538 case ISD::CTTZ: 6539 case ISD::CTTZ_ZERO_UNDEF: 6540 case ISD::CTLZ: 6541 case ISD::CTLZ_ZERO_UNDEF: { 6542 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6543 "Unexpected custom legalisation"); 6544 6545 SDValue NewOp0 = 6546 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6547 bool IsCTZ = 6548 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6549 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6550 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6551 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6552 return; 6553 } 6554 case ISD::SDIV: 6555 case ISD::UDIV: 6556 case ISD::UREM: { 6557 MVT VT = N->getSimpleValueType(0); 6558 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6559 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6560 "Unexpected custom legalisation"); 6561 // Don't promote division/remainder by constant since we should expand those 6562 // to multiply by magic constant. 6563 // FIXME: What if the expansion is disabled for minsize. 6564 if (N->getOperand(1).getOpcode() == ISD::Constant) 6565 return; 6566 6567 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6568 // the upper 32 bits. For other types we need to sign or zero extend 6569 // based on the opcode. 6570 unsigned ExtOpc = ISD::ANY_EXTEND; 6571 if (VT != MVT::i32) 6572 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6573 : ISD::ZERO_EXTEND; 6574 6575 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6576 break; 6577 } 6578 case ISD::UADDO: 6579 case ISD::USUBO: { 6580 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6581 "Unexpected custom legalisation"); 6582 bool IsAdd = N->getOpcode() == ISD::UADDO; 6583 // Create an ADDW or SUBW. 6584 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6585 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6586 SDValue Res = 6587 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6588 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6589 DAG.getValueType(MVT::i32)); 6590 6591 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6592 // Since the inputs are sign extended from i32, this is equivalent to 6593 // comparing the lower 32 bits. 6594 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6595 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6596 IsAdd ? ISD::SETULT : ISD::SETUGT); 6597 6598 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6599 Results.push_back(Overflow); 6600 return; 6601 } 6602 case ISD::UADDSAT: 6603 case ISD::USUBSAT: { 6604 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6605 "Unexpected custom legalisation"); 6606 if (Subtarget.hasStdExtZbb()) { 6607 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6608 // sign extend allows overflow of the lower 32 bits to be detected on 6609 // the promoted size. 6610 SDValue LHS = 6611 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6612 SDValue RHS = 6613 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6614 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6615 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6616 return; 6617 } 6618 6619 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6620 // promotion for UADDO/USUBO. 6621 Results.push_back(expandAddSubSat(N, DAG)); 6622 return; 6623 } 6624 case ISD::BITCAST: { 6625 EVT VT = N->getValueType(0); 6626 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6627 SDValue Op0 = N->getOperand(0); 6628 EVT Op0VT = Op0.getValueType(); 6629 MVT XLenVT = Subtarget.getXLenVT(); 6630 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6631 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6632 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6633 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6634 Subtarget.hasStdExtF()) { 6635 SDValue FPConv = 6636 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6637 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6638 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6639 isTypeLegal(Op0VT)) { 6640 // Custom-legalize bitcasts from fixed-length vector types to illegal 6641 // scalar types in order to improve codegen. Bitcast the vector to a 6642 // one-element vector type whose element type is the same as the result 6643 // type, and extract the first element. 6644 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6645 if (isTypeLegal(BVT)) { 6646 SDValue BVec = DAG.getBitcast(BVT, Op0); 6647 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6648 DAG.getConstant(0, DL, XLenVT))); 6649 } 6650 } 6651 break; 6652 } 6653 case RISCVISD::GREV: 6654 case RISCVISD::GORC: { 6655 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6656 "Unexpected custom legalisation"); 6657 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6658 // This is similar to customLegalizeToWOp, except that we pass the second 6659 // operand (a TargetConstant) straight through: it is already of type 6660 // XLenVT. 6661 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6662 SDValue NewOp0 = 6663 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6664 SDValue NewOp1 = 6665 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6666 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6667 // ReplaceNodeResults requires we maintain the same type for the return 6668 // value. 6669 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6670 break; 6671 } 6672 case RISCVISD::SHFL: { 6673 // There is no SHFLIW instruction, but we can just promote the operation. 6674 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6675 "Unexpected custom legalisation"); 6676 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6677 SDValue NewOp0 = 6678 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6679 SDValue NewOp1 = 6680 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6681 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6682 // ReplaceNodeResults requires we maintain the same type for the return 6683 // value. 6684 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6685 break; 6686 } 6687 case ISD::BSWAP: 6688 case ISD::BITREVERSE: { 6689 MVT VT = N->getSimpleValueType(0); 6690 MVT XLenVT = Subtarget.getXLenVT(); 6691 assert((VT == MVT::i8 || VT == MVT::i16 || 6692 (VT == MVT::i32 && Subtarget.is64Bit())) && 6693 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6694 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6695 unsigned Imm = VT.getSizeInBits() - 1; 6696 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6697 if (N->getOpcode() == ISD::BSWAP) 6698 Imm &= ~0x7U; 6699 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6700 SDValue GREVI = 6701 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6702 // ReplaceNodeResults requires we maintain the same type for the return 6703 // value. 6704 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6705 break; 6706 } 6707 case ISD::FSHL: 6708 case ISD::FSHR: { 6709 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6710 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6711 SDValue NewOp0 = 6712 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6713 SDValue NewOp1 = 6714 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6715 SDValue NewShAmt = 6716 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6717 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6718 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6719 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6720 DAG.getConstant(0x1f, DL, MVT::i64)); 6721 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6722 // instruction use different orders. fshl will return its first operand for 6723 // shift of zero, fshr will return its second operand. fsl and fsr both 6724 // return rs1 so the ISD nodes need to have different operand orders. 6725 // Shift amount is in rs2. 6726 unsigned Opc = RISCVISD::FSLW; 6727 if (N->getOpcode() == ISD::FSHR) { 6728 std::swap(NewOp0, NewOp1); 6729 Opc = RISCVISD::FSRW; 6730 } 6731 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6732 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6733 break; 6734 } 6735 case ISD::EXTRACT_VECTOR_ELT: { 6736 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6737 // type is illegal (currently only vXi64 RV32). 6738 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6739 // transferred to the destination register. We issue two of these from the 6740 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6741 // first element. 6742 SDValue Vec = N->getOperand(0); 6743 SDValue Idx = N->getOperand(1); 6744 6745 // The vector type hasn't been legalized yet so we can't issue target 6746 // specific nodes if it needs legalization. 6747 // FIXME: We would manually legalize if it's important. 6748 if (!isTypeLegal(Vec.getValueType())) 6749 return; 6750 6751 MVT VecVT = Vec.getSimpleValueType(); 6752 6753 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6754 VecVT.getVectorElementType() == MVT::i64 && 6755 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6756 6757 // If this is a fixed vector, we need to convert it to a scalable vector. 6758 MVT ContainerVT = VecVT; 6759 if (VecVT.isFixedLengthVector()) { 6760 ContainerVT = getContainerForFixedLengthVector(VecVT); 6761 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6762 } 6763 6764 MVT XLenVT = Subtarget.getXLenVT(); 6765 6766 // Use a VL of 1 to avoid processing more elements than we need. 6767 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6768 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6769 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6770 6771 // Unless the index is known to be 0, we must slide the vector down to get 6772 // the desired element into index 0. 6773 if (!isNullConstant(Idx)) { 6774 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6775 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6776 } 6777 6778 // Extract the lower XLEN bits of the correct vector element. 6779 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6780 6781 // To extract the upper XLEN bits of the vector element, shift the first 6782 // element right by 32 bits and re-extract the lower XLEN bits. 6783 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6784 DAG.getUNDEF(ContainerVT), 6785 DAG.getConstant(32, DL, XLenVT), VL); 6786 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6787 ThirtyTwoV, Mask, VL); 6788 6789 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6790 6791 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6792 break; 6793 } 6794 case ISD::INTRINSIC_WO_CHAIN: { 6795 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6796 switch (IntNo) { 6797 default: 6798 llvm_unreachable( 6799 "Don't know how to custom type legalize this intrinsic!"); 6800 case Intrinsic::riscv_grev: 6801 case Intrinsic::riscv_gorc: 6802 case Intrinsic::riscv_bcompress: 6803 case Intrinsic::riscv_bdecompress: 6804 case Intrinsic::riscv_bfp: { 6805 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6806 "Unexpected custom legalisation"); 6807 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6808 break; 6809 } 6810 case Intrinsic::riscv_fsl: 6811 case Intrinsic::riscv_fsr: { 6812 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6813 "Unexpected custom legalisation"); 6814 SDValue NewOp1 = 6815 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6816 SDValue NewOp2 = 6817 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6818 SDValue NewOp3 = 6819 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 6820 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 6821 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 6822 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6823 break; 6824 } 6825 case Intrinsic::riscv_orc_b: { 6826 // Lower to the GORCI encoding for orc.b with the operand extended. 6827 SDValue NewOp = 6828 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6829 // If Zbp is enabled, use GORCIW which will sign extend the result. 6830 unsigned Opc = 6831 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6832 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6833 DAG.getConstant(7, DL, MVT::i64)); 6834 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6835 return; 6836 } 6837 case Intrinsic::riscv_shfl: 6838 case Intrinsic::riscv_unshfl: { 6839 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6840 "Unexpected custom legalisation"); 6841 SDValue NewOp1 = 6842 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6843 SDValue NewOp2 = 6844 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6845 unsigned Opc = 6846 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6847 // There is no (UN)SHFLIW. If the control word is a constant, we can use 6848 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 6849 // will be shuffled the same way as the lower 32 bit half, but the two 6850 // halves won't cross. 6851 if (isa<ConstantSDNode>(NewOp2)) { 6852 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6853 DAG.getConstant(0xf, DL, MVT::i64)); 6854 Opc = 6855 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6856 } 6857 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6858 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6859 break; 6860 } 6861 case Intrinsic::riscv_vmv_x_s: { 6862 EVT VT = N->getValueType(0); 6863 MVT XLenVT = Subtarget.getXLenVT(); 6864 if (VT.bitsLT(XLenVT)) { 6865 // Simple case just extract using vmv.x.s and truncate. 6866 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6867 Subtarget.getXLenVT(), N->getOperand(1)); 6868 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6869 return; 6870 } 6871 6872 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6873 "Unexpected custom legalization"); 6874 6875 // We need to do the move in two steps. 6876 SDValue Vec = N->getOperand(1); 6877 MVT VecVT = Vec.getSimpleValueType(); 6878 6879 // First extract the lower XLEN bits of the element. 6880 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6881 6882 // To extract the upper XLEN bits of the vector element, shift the first 6883 // element right by 32 bits and re-extract the lower XLEN bits. 6884 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6885 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6886 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6887 SDValue ThirtyTwoV = 6888 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 6889 DAG.getConstant(32, DL, XLenVT), VL); 6890 SDValue LShr32 = 6891 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6892 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6893 6894 Results.push_back( 6895 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6896 break; 6897 } 6898 } 6899 break; 6900 } 6901 case ISD::VECREDUCE_ADD: 6902 case ISD::VECREDUCE_AND: 6903 case ISD::VECREDUCE_OR: 6904 case ISD::VECREDUCE_XOR: 6905 case ISD::VECREDUCE_SMAX: 6906 case ISD::VECREDUCE_UMAX: 6907 case ISD::VECREDUCE_SMIN: 6908 case ISD::VECREDUCE_UMIN: 6909 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6910 Results.push_back(V); 6911 break; 6912 case ISD::VP_REDUCE_ADD: 6913 case ISD::VP_REDUCE_AND: 6914 case ISD::VP_REDUCE_OR: 6915 case ISD::VP_REDUCE_XOR: 6916 case ISD::VP_REDUCE_SMAX: 6917 case ISD::VP_REDUCE_UMAX: 6918 case ISD::VP_REDUCE_SMIN: 6919 case ISD::VP_REDUCE_UMIN: 6920 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6921 Results.push_back(V); 6922 break; 6923 case ISD::FLT_ROUNDS_: { 6924 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6925 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6926 Results.push_back(Res.getValue(0)); 6927 Results.push_back(Res.getValue(1)); 6928 break; 6929 } 6930 } 6931 } 6932 6933 // A structure to hold one of the bit-manipulation patterns below. Together, a 6934 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6935 // (or (and (shl x, 1), 0xAAAAAAAA), 6936 // (and (srl x, 1), 0x55555555)) 6937 struct RISCVBitmanipPat { 6938 SDValue Op; 6939 unsigned ShAmt; 6940 bool IsSHL; 6941 6942 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6943 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6944 } 6945 }; 6946 6947 // Matches patterns of the form 6948 // (and (shl x, C2), (C1 << C2)) 6949 // (and (srl x, C2), C1) 6950 // (shl (and x, C1), C2) 6951 // (srl (and x, (C1 << C2)), C2) 6952 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6953 // The expected masks for each shift amount are specified in BitmanipMasks where 6954 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6955 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6956 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6957 // XLen is 64. 6958 static Optional<RISCVBitmanipPat> 6959 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6960 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6961 "Unexpected number of masks"); 6962 Optional<uint64_t> Mask; 6963 // Optionally consume a mask around the shift operation. 6964 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6965 Mask = Op.getConstantOperandVal(1); 6966 Op = Op.getOperand(0); 6967 } 6968 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6969 return None; 6970 bool IsSHL = Op.getOpcode() == ISD::SHL; 6971 6972 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6973 return None; 6974 uint64_t ShAmt = Op.getConstantOperandVal(1); 6975 6976 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6977 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6978 return None; 6979 // If we don't have enough masks for 64 bit, then we must be trying to 6980 // match SHFL so we're only allowed to shift 1/4 of the width. 6981 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6982 return None; 6983 6984 SDValue Src = Op.getOperand(0); 6985 6986 // The expected mask is shifted left when the AND is found around SHL 6987 // patterns. 6988 // ((x >> 1) & 0x55555555) 6989 // ((x << 1) & 0xAAAAAAAA) 6990 bool SHLExpMask = IsSHL; 6991 6992 if (!Mask) { 6993 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6994 // the mask is all ones: consume that now. 6995 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6996 Mask = Src.getConstantOperandVal(1); 6997 Src = Src.getOperand(0); 6998 // The expected mask is now in fact shifted left for SRL, so reverse the 6999 // decision. 7000 // ((x & 0xAAAAAAAA) >> 1) 7001 // ((x & 0x55555555) << 1) 7002 SHLExpMask = !SHLExpMask; 7003 } else { 7004 // Use a default shifted mask of all-ones if there's no AND, truncated 7005 // down to the expected width. This simplifies the logic later on. 7006 Mask = maskTrailingOnes<uint64_t>(Width); 7007 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7008 } 7009 } 7010 7011 unsigned MaskIdx = Log2_32(ShAmt); 7012 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7013 7014 if (SHLExpMask) 7015 ExpMask <<= ShAmt; 7016 7017 if (Mask != ExpMask) 7018 return None; 7019 7020 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7021 } 7022 7023 // Matches any of the following bit-manipulation patterns: 7024 // (and (shl x, 1), (0x55555555 << 1)) 7025 // (and (srl x, 1), 0x55555555) 7026 // (shl (and x, 0x55555555), 1) 7027 // (srl (and x, (0x55555555 << 1)), 1) 7028 // where the shift amount and mask may vary thus: 7029 // [1] = 0x55555555 / 0xAAAAAAAA 7030 // [2] = 0x33333333 / 0xCCCCCCCC 7031 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7032 // [8] = 0x00FF00FF / 0xFF00FF00 7033 // [16] = 0x0000FFFF / 0xFFFFFFFF 7034 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7035 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7036 // These are the unshifted masks which we use to match bit-manipulation 7037 // patterns. They may be shifted left in certain circumstances. 7038 static const uint64_t BitmanipMasks[] = { 7039 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7040 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7041 7042 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7043 } 7044 7045 // Match the following pattern as a GREVI(W) operation 7046 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7047 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7048 const RISCVSubtarget &Subtarget) { 7049 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7050 EVT VT = Op.getValueType(); 7051 7052 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7053 auto LHS = matchGREVIPat(Op.getOperand(0)); 7054 auto RHS = matchGREVIPat(Op.getOperand(1)); 7055 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7056 SDLoc DL(Op); 7057 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7058 DAG.getConstant(LHS->ShAmt, DL, VT)); 7059 } 7060 } 7061 return SDValue(); 7062 } 7063 7064 // Matches any the following pattern as a GORCI(W) operation 7065 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7066 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7067 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7068 // Note that with the variant of 3., 7069 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7070 // the inner pattern will first be matched as GREVI and then the outer 7071 // pattern will be matched to GORC via the first rule above. 7072 // 4. (or (rotl/rotr x, bitwidth/2), x) 7073 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7074 const RISCVSubtarget &Subtarget) { 7075 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7076 EVT VT = Op.getValueType(); 7077 7078 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7079 SDLoc DL(Op); 7080 SDValue Op0 = Op.getOperand(0); 7081 SDValue Op1 = Op.getOperand(1); 7082 7083 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7084 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7085 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7086 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7087 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7088 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7089 if ((Reverse.getOpcode() == ISD::ROTL || 7090 Reverse.getOpcode() == ISD::ROTR) && 7091 Reverse.getOperand(0) == X && 7092 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7093 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7094 if (RotAmt == (VT.getSizeInBits() / 2)) 7095 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7096 DAG.getConstant(RotAmt, DL, VT)); 7097 } 7098 return SDValue(); 7099 }; 7100 7101 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7102 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7103 return V; 7104 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7105 return V; 7106 7107 // OR is commutable so canonicalize its OR operand to the left 7108 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7109 std::swap(Op0, Op1); 7110 if (Op0.getOpcode() != ISD::OR) 7111 return SDValue(); 7112 SDValue OrOp0 = Op0.getOperand(0); 7113 SDValue OrOp1 = Op0.getOperand(1); 7114 auto LHS = matchGREVIPat(OrOp0); 7115 // OR is commutable so swap the operands and try again: x might have been 7116 // on the left 7117 if (!LHS) { 7118 std::swap(OrOp0, OrOp1); 7119 LHS = matchGREVIPat(OrOp0); 7120 } 7121 auto RHS = matchGREVIPat(Op1); 7122 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7123 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7124 DAG.getConstant(LHS->ShAmt, DL, VT)); 7125 } 7126 } 7127 return SDValue(); 7128 } 7129 7130 // Matches any of the following bit-manipulation patterns: 7131 // (and (shl x, 1), (0x22222222 << 1)) 7132 // (and (srl x, 1), 0x22222222) 7133 // (shl (and x, 0x22222222), 1) 7134 // (srl (and x, (0x22222222 << 1)), 1) 7135 // where the shift amount and mask may vary thus: 7136 // [1] = 0x22222222 / 0x44444444 7137 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7138 // [4] = 0x00F000F0 / 0x0F000F00 7139 // [8] = 0x0000FF00 / 0x00FF0000 7140 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7141 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7142 // These are the unshifted masks which we use to match bit-manipulation 7143 // patterns. They may be shifted left in certain circumstances. 7144 static const uint64_t BitmanipMasks[] = { 7145 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7146 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7147 7148 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7149 } 7150 7151 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7152 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7153 const RISCVSubtarget &Subtarget) { 7154 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7155 EVT VT = Op.getValueType(); 7156 7157 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7158 return SDValue(); 7159 7160 SDValue Op0 = Op.getOperand(0); 7161 SDValue Op1 = Op.getOperand(1); 7162 7163 // Or is commutable so canonicalize the second OR to the LHS. 7164 if (Op0.getOpcode() != ISD::OR) 7165 std::swap(Op0, Op1); 7166 if (Op0.getOpcode() != ISD::OR) 7167 return SDValue(); 7168 7169 // We found an inner OR, so our operands are the operands of the inner OR 7170 // and the other operand of the outer OR. 7171 SDValue A = Op0.getOperand(0); 7172 SDValue B = Op0.getOperand(1); 7173 SDValue C = Op1; 7174 7175 auto Match1 = matchSHFLPat(A); 7176 auto Match2 = matchSHFLPat(B); 7177 7178 // If neither matched, we failed. 7179 if (!Match1 && !Match2) 7180 return SDValue(); 7181 7182 // We had at least one match. if one failed, try the remaining C operand. 7183 if (!Match1) { 7184 std::swap(A, C); 7185 Match1 = matchSHFLPat(A); 7186 if (!Match1) 7187 return SDValue(); 7188 } else if (!Match2) { 7189 std::swap(B, C); 7190 Match2 = matchSHFLPat(B); 7191 if (!Match2) 7192 return SDValue(); 7193 } 7194 assert(Match1 && Match2); 7195 7196 // Make sure our matches pair up. 7197 if (!Match1->formsPairWith(*Match2)) 7198 return SDValue(); 7199 7200 // All the remains is to make sure C is an AND with the same input, that masks 7201 // out the bits that are being shuffled. 7202 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7203 C.getOperand(0) != Match1->Op) 7204 return SDValue(); 7205 7206 uint64_t Mask = C.getConstantOperandVal(1); 7207 7208 static const uint64_t BitmanipMasks[] = { 7209 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7210 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7211 }; 7212 7213 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7214 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7215 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7216 7217 if (Mask != ExpMask) 7218 return SDValue(); 7219 7220 SDLoc DL(Op); 7221 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7222 DAG.getConstant(Match1->ShAmt, DL, VT)); 7223 } 7224 7225 // Optimize (add (shl x, c0), (shl y, c1)) -> 7226 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7227 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7228 const RISCVSubtarget &Subtarget) { 7229 // Perform this optimization only in the zba extension. 7230 if (!Subtarget.hasStdExtZba()) 7231 return SDValue(); 7232 7233 // Skip for vector types and larger types. 7234 EVT VT = N->getValueType(0); 7235 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7236 return SDValue(); 7237 7238 // The two operand nodes must be SHL and have no other use. 7239 SDValue N0 = N->getOperand(0); 7240 SDValue N1 = N->getOperand(1); 7241 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7242 !N0->hasOneUse() || !N1->hasOneUse()) 7243 return SDValue(); 7244 7245 // Check c0 and c1. 7246 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7247 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7248 if (!N0C || !N1C) 7249 return SDValue(); 7250 int64_t C0 = N0C->getSExtValue(); 7251 int64_t C1 = N1C->getSExtValue(); 7252 if (C0 <= 0 || C1 <= 0) 7253 return SDValue(); 7254 7255 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7256 int64_t Bits = std::min(C0, C1); 7257 int64_t Diff = std::abs(C0 - C1); 7258 if (Diff != 1 && Diff != 2 && Diff != 3) 7259 return SDValue(); 7260 7261 // Build nodes. 7262 SDLoc DL(N); 7263 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7264 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7265 SDValue NA0 = 7266 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7267 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7268 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7269 } 7270 7271 // Combine 7272 // ROTR ((GREV x, 24), 16) -> (GREVI x, 8) 7273 // ROTL ((GREV x, 24), 16) -> (GREVI x, 8) 7274 // RORW ((GREVW x, 24), 16) -> (GREVIW x, 8) 7275 // ROLW ((GREVW x, 24), 16) -> (GREVIW x, 8) 7276 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG) { 7277 SDValue Src = N->getOperand(0); 7278 SDLoc DL(N); 7279 unsigned Opc; 7280 7281 if ((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL) && 7282 Src.getOpcode() == RISCVISD::GREV) 7283 Opc = RISCVISD::GREV; 7284 else if ((N->getOpcode() == RISCVISD::RORW || 7285 N->getOpcode() == RISCVISD::ROLW) && 7286 Src.getOpcode() == RISCVISD::GREVW) 7287 Opc = RISCVISD::GREVW; 7288 else 7289 return SDValue(); 7290 7291 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7292 !isa<ConstantSDNode>(Src.getOperand(1))) 7293 return SDValue(); 7294 7295 unsigned ShAmt1 = N->getConstantOperandVal(1); 7296 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7297 if (ShAmt1 != 16 && ShAmt2 != 24) 7298 return SDValue(); 7299 7300 Src = Src.getOperand(0); 7301 return DAG.getNode(Opc, DL, N->getValueType(0), Src, 7302 DAG.getConstant(8, DL, N->getOperand(1).getValueType())); 7303 } 7304 7305 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7306 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7307 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7308 // not undo itself, but they are redundant. 7309 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7310 SDValue Src = N->getOperand(0); 7311 7312 if (Src.getOpcode() != N->getOpcode()) 7313 return SDValue(); 7314 7315 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7316 !isa<ConstantSDNode>(Src.getOperand(1))) 7317 return SDValue(); 7318 7319 unsigned ShAmt1 = N->getConstantOperandVal(1); 7320 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7321 Src = Src.getOperand(0); 7322 7323 unsigned CombinedShAmt; 7324 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 7325 CombinedShAmt = ShAmt1 | ShAmt2; 7326 else 7327 CombinedShAmt = ShAmt1 ^ ShAmt2; 7328 7329 if (CombinedShAmt == 0) 7330 return Src; 7331 7332 SDLoc DL(N); 7333 return DAG.getNode( 7334 N->getOpcode(), DL, N->getValueType(0), Src, 7335 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7336 } 7337 7338 // Combine a constant select operand into its use: 7339 // 7340 // (and (select cond, -1, c), x) 7341 // -> (select cond, x, (and x, c)) [AllOnes=1] 7342 // (or (select cond, 0, c), x) 7343 // -> (select cond, x, (or x, c)) [AllOnes=0] 7344 // (xor (select cond, 0, c), x) 7345 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7346 // (add (select cond, 0, c), x) 7347 // -> (select cond, x, (add x, c)) [AllOnes=0] 7348 // (sub x, (select cond, 0, c)) 7349 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7350 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7351 SelectionDAG &DAG, bool AllOnes) { 7352 EVT VT = N->getValueType(0); 7353 7354 // Skip vectors. 7355 if (VT.isVector()) 7356 return SDValue(); 7357 7358 if ((Slct.getOpcode() != ISD::SELECT && 7359 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7360 !Slct.hasOneUse()) 7361 return SDValue(); 7362 7363 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7364 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7365 }; 7366 7367 bool SwapSelectOps; 7368 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7369 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7370 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7371 SDValue NonConstantVal; 7372 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7373 SwapSelectOps = false; 7374 NonConstantVal = FalseVal; 7375 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7376 SwapSelectOps = true; 7377 NonConstantVal = TrueVal; 7378 } else 7379 return SDValue(); 7380 7381 // Slct is now know to be the desired identity constant when CC is true. 7382 TrueVal = OtherOp; 7383 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7384 // Unless SwapSelectOps says the condition should be false. 7385 if (SwapSelectOps) 7386 std::swap(TrueVal, FalseVal); 7387 7388 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7389 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7390 {Slct.getOperand(0), Slct.getOperand(1), 7391 Slct.getOperand(2), TrueVal, FalseVal}); 7392 7393 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7394 {Slct.getOperand(0), TrueVal, FalseVal}); 7395 } 7396 7397 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7398 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7399 bool AllOnes) { 7400 SDValue N0 = N->getOperand(0); 7401 SDValue N1 = N->getOperand(1); 7402 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7403 return Result; 7404 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7405 return Result; 7406 return SDValue(); 7407 } 7408 7409 // Transform (add (mul x, c0), c1) -> 7410 // (add (mul (add x, c1/c0), c0), c1%c0). 7411 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7412 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7413 // to an infinite loop in DAGCombine if transformed. 7414 // Or transform (add (mul x, c0), c1) -> 7415 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7416 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7417 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7418 // lead to an infinite loop in DAGCombine if transformed. 7419 // Or transform (add (mul x, c0), c1) -> 7420 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7421 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7422 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7423 // lead to an infinite loop in DAGCombine if transformed. 7424 // Or transform (add (mul x, c0), c1) -> 7425 // (mul (add x, c1/c0), c0). 7426 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7427 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7428 const RISCVSubtarget &Subtarget) { 7429 // Skip for vector types and larger types. 7430 EVT VT = N->getValueType(0); 7431 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7432 return SDValue(); 7433 // The first operand node must be a MUL and has no other use. 7434 SDValue N0 = N->getOperand(0); 7435 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7436 return SDValue(); 7437 // Check if c0 and c1 match above conditions. 7438 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7439 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7440 if (!N0C || !N1C) 7441 return SDValue(); 7442 // If N0C has multiple uses it's possible one of the cases in 7443 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7444 // in an infinite loop. 7445 if (!N0C->hasOneUse()) 7446 return SDValue(); 7447 int64_t C0 = N0C->getSExtValue(); 7448 int64_t C1 = N1C->getSExtValue(); 7449 int64_t CA, CB; 7450 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7451 return SDValue(); 7452 // Search for proper CA (non-zero) and CB that both are simm12. 7453 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7454 !isInt<12>(C0 * (C1 / C0))) { 7455 CA = C1 / C0; 7456 CB = C1 % C0; 7457 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7458 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7459 CA = C1 / C0 + 1; 7460 CB = C1 % C0 - C0; 7461 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7462 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7463 CA = C1 / C0 - 1; 7464 CB = C1 % C0 + C0; 7465 } else 7466 return SDValue(); 7467 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7468 SDLoc DL(N); 7469 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7470 DAG.getConstant(CA, DL, VT)); 7471 SDValue New1 = 7472 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7473 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7474 } 7475 7476 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7477 const RISCVSubtarget &Subtarget) { 7478 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7479 return V; 7480 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7481 return V; 7482 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7483 // (select lhs, rhs, cc, x, (add x, y)) 7484 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7485 } 7486 7487 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7488 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7489 // (select lhs, rhs, cc, x, (sub x, y)) 7490 SDValue N0 = N->getOperand(0); 7491 SDValue N1 = N->getOperand(1); 7492 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7493 } 7494 7495 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7496 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7497 // (select lhs, rhs, cc, x, (and x, y)) 7498 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7499 } 7500 7501 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7502 const RISCVSubtarget &Subtarget) { 7503 if (Subtarget.hasStdExtZbp()) { 7504 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7505 return GREV; 7506 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7507 return GORC; 7508 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7509 return SHFL; 7510 } 7511 7512 // fold (or (select cond, 0, y), x) -> 7513 // (select cond, x, (or x, y)) 7514 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7515 } 7516 7517 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7518 // fold (xor (select cond, 0, y), x) -> 7519 // (select cond, x, (xor x, y)) 7520 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7521 } 7522 7523 static SDValue performSIGN_EXTEND_INREG(SDNode *N, SelectionDAG &DAG) { 7524 SDValue Src = N->getOperand(0); 7525 7526 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 7527 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7528 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 7529 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), N->getValueType(0), 7530 Src.getOperand(0)); 7531 7532 return SDValue(); 7533 } 7534 7535 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 7536 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 7537 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 7538 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 7539 // ADDW/SUBW/MULW. 7540 static SDValue performANY_EXTENDCombine(SDNode *N, 7541 TargetLowering::DAGCombinerInfo &DCI, 7542 const RISCVSubtarget &Subtarget) { 7543 if (!Subtarget.is64Bit()) 7544 return SDValue(); 7545 7546 SelectionDAG &DAG = DCI.DAG; 7547 7548 SDValue Src = N->getOperand(0); 7549 EVT VT = N->getValueType(0); 7550 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 7551 return SDValue(); 7552 7553 // The opcode must be one that can implicitly sign_extend. 7554 // FIXME: Additional opcodes. 7555 switch (Src.getOpcode()) { 7556 default: 7557 return SDValue(); 7558 case ISD::MUL: 7559 if (!Subtarget.hasStdExtM()) 7560 return SDValue(); 7561 LLVM_FALLTHROUGH; 7562 case ISD::ADD: 7563 case ISD::SUB: 7564 break; 7565 } 7566 7567 // Only handle cases where the result is used by a CopyToReg. That likely 7568 // means the value is a liveout of the basic block. This helps prevent 7569 // infinite combine loops like PR51206. 7570 if (none_of(N->uses(), 7571 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 7572 return SDValue(); 7573 7574 SmallVector<SDNode *, 4> SetCCs; 7575 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 7576 UE = Src.getNode()->use_end(); 7577 UI != UE; ++UI) { 7578 SDNode *User = *UI; 7579 if (User == N) 7580 continue; 7581 if (UI.getUse().getResNo() != Src.getResNo()) 7582 continue; 7583 // All i32 setccs are legalized by sign extending operands. 7584 if (User->getOpcode() == ISD::SETCC) { 7585 SetCCs.push_back(User); 7586 continue; 7587 } 7588 // We don't know if we can extend this user. 7589 break; 7590 } 7591 7592 // If we don't have any SetCCs, this isn't worthwhile. 7593 if (SetCCs.empty()) 7594 return SDValue(); 7595 7596 SDLoc DL(N); 7597 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 7598 DCI.CombineTo(N, SExt); 7599 7600 // Promote all the setccs. 7601 for (SDNode *SetCC : SetCCs) { 7602 SmallVector<SDValue, 4> Ops; 7603 7604 for (unsigned j = 0; j != 2; ++j) { 7605 SDValue SOp = SetCC->getOperand(j); 7606 if (SOp == Src) 7607 Ops.push_back(SExt); 7608 else 7609 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 7610 } 7611 7612 Ops.push_back(SetCC->getOperand(2)); 7613 DCI.CombineTo(SetCC, 7614 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7615 } 7616 return SDValue(N, 0); 7617 } 7618 7619 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7620 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7621 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7622 bool Commute = false) { 7623 assert((N->getOpcode() == RISCVISD::ADD_VL || 7624 N->getOpcode() == RISCVISD::SUB_VL) && 7625 "Unexpected opcode"); 7626 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7627 SDValue Op0 = N->getOperand(0); 7628 SDValue Op1 = N->getOperand(1); 7629 if (Commute) 7630 std::swap(Op0, Op1); 7631 7632 MVT VT = N->getSimpleValueType(0); 7633 7634 // Determine the narrow size for a widening add/sub. 7635 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7636 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7637 VT.getVectorElementCount()); 7638 7639 SDValue Mask = N->getOperand(2); 7640 SDValue VL = N->getOperand(3); 7641 7642 SDLoc DL(N); 7643 7644 // If the RHS is a sext or zext, we can form a widening op. 7645 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7646 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7647 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7648 unsigned ExtOpc = Op1.getOpcode(); 7649 Op1 = Op1.getOperand(0); 7650 // Re-introduce narrower extends if needed. 7651 if (Op1.getValueType() != NarrowVT) 7652 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7653 7654 unsigned WOpc; 7655 if (ExtOpc == RISCVISD::VSEXT_VL) 7656 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7657 else 7658 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7659 7660 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7661 } 7662 7663 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7664 // sext/zext? 7665 7666 return SDValue(); 7667 } 7668 7669 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7670 // vwsub(u).vv/vx. 7671 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7672 SDValue Op0 = N->getOperand(0); 7673 SDValue Op1 = N->getOperand(1); 7674 SDValue Mask = N->getOperand(2); 7675 SDValue VL = N->getOperand(3); 7676 7677 MVT VT = N->getSimpleValueType(0); 7678 MVT NarrowVT = Op1.getSimpleValueType(); 7679 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 7680 7681 unsigned VOpc; 7682 switch (N->getOpcode()) { 7683 default: llvm_unreachable("Unexpected opcode"); 7684 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 7685 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 7686 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 7687 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 7688 } 7689 7690 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 7691 N->getOpcode() == RISCVISD::VWSUB_W_VL; 7692 7693 SDLoc DL(N); 7694 7695 // If the LHS is a sext or zext, we can narrow this op to the same size as 7696 // the RHS. 7697 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 7698 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 7699 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 7700 unsigned ExtOpc = Op0.getOpcode(); 7701 Op0 = Op0.getOperand(0); 7702 // Re-introduce narrower extends if needed. 7703 if (Op0.getValueType() != NarrowVT) 7704 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7705 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 7706 } 7707 7708 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 7709 N->getOpcode() == RISCVISD::VWADDU_W_VL; 7710 7711 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 7712 // to commute and use a vwadd(u).vx instead. 7713 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 7714 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 7715 Op0 = Op0.getOperand(1); 7716 7717 // See if have enough sign bits or zero bits in the scalar to use a 7718 // widening add/sub by splatting to smaller element size. 7719 unsigned EltBits = VT.getScalarSizeInBits(); 7720 unsigned ScalarBits = Op0.getValueSizeInBits(); 7721 // Make sure we're getting all element bits from the scalar register. 7722 // FIXME: Support implicit sign extension of vmv.v.x? 7723 if (ScalarBits < EltBits) 7724 return SDValue(); 7725 7726 if (IsSigned) { 7727 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 7728 return SDValue(); 7729 } else { 7730 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7731 if (!DAG.MaskedValueIsZero(Op0, Mask)) 7732 return SDValue(); 7733 } 7734 7735 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7736 DAG.getUNDEF(NarrowVT), Op0, VL); 7737 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 7738 } 7739 7740 return SDValue(); 7741 } 7742 7743 // Try to form VWMUL, VWMULU or VWMULSU. 7744 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 7745 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 7746 bool Commute) { 7747 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7748 SDValue Op0 = N->getOperand(0); 7749 SDValue Op1 = N->getOperand(1); 7750 if (Commute) 7751 std::swap(Op0, Op1); 7752 7753 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7754 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7755 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 7756 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7757 return SDValue(); 7758 7759 SDValue Mask = N->getOperand(2); 7760 SDValue VL = N->getOperand(3); 7761 7762 // Make sure the mask and VL match. 7763 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7764 return SDValue(); 7765 7766 MVT VT = N->getSimpleValueType(0); 7767 7768 // Determine the narrow size for a widening multiply. 7769 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7770 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7771 VT.getVectorElementCount()); 7772 7773 SDLoc DL(N); 7774 7775 // See if the other operand is the same opcode. 7776 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 7777 if (!Op1.hasOneUse()) 7778 return SDValue(); 7779 7780 // Make sure the mask and VL match. 7781 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7782 return SDValue(); 7783 7784 Op1 = Op1.getOperand(0); 7785 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7786 // The operand is a splat of a scalar. 7787 7788 // The pasthru must be undef for tail agnostic 7789 if (!Op1.getOperand(0).isUndef()) 7790 return SDValue(); 7791 // The VL must be the same. 7792 if (Op1.getOperand(2) != VL) 7793 return SDValue(); 7794 7795 // Get the scalar value. 7796 Op1 = Op1.getOperand(1); 7797 7798 // See if have enough sign bits or zero bits in the scalar to use a 7799 // widening multiply by splatting to smaller element size. 7800 unsigned EltBits = VT.getScalarSizeInBits(); 7801 unsigned ScalarBits = Op1.getValueSizeInBits(); 7802 // Make sure we're getting all element bits from the scalar register. 7803 // FIXME: Support implicit sign extension of vmv.v.x? 7804 if (ScalarBits < EltBits) 7805 return SDValue(); 7806 7807 // If the LHS is a sign extend, try to use vwmul. 7808 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 7809 // Can use vwmul. 7810 } else { 7811 // Otherwise try to use vwmulu or vwmulsu. 7812 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7813 if (DAG.MaskedValueIsZero(Op1, Mask)) 7814 IsVWMULSU = IsSignExt; 7815 else 7816 return SDValue(); 7817 } 7818 7819 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7820 DAG.getUNDEF(NarrowVT), Op1, VL); 7821 } else 7822 return SDValue(); 7823 7824 Op0 = Op0.getOperand(0); 7825 7826 // Re-introduce narrower extends if needed. 7827 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7828 if (Op0.getValueType() != NarrowVT) 7829 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7830 // vwmulsu requires second operand to be zero extended. 7831 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 7832 if (Op1.getValueType() != NarrowVT) 7833 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7834 7835 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 7836 if (!IsVWMULSU) 7837 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7838 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7839 } 7840 7841 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 7842 switch (Op.getOpcode()) { 7843 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 7844 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 7845 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 7846 case ISD::FCEIL: return RISCVFPRndMode::RUP; 7847 case ISD::FROUND: return RISCVFPRndMode::RMM; 7848 } 7849 7850 return RISCVFPRndMode::Invalid; 7851 } 7852 7853 // Fold 7854 // (fp_to_int (froundeven X)) -> fcvt X, rne 7855 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7856 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7857 // (fp_to_int (fceil X)) -> fcvt X, rup 7858 // (fp_to_int (fround X)) -> fcvt X, rmm 7859 static SDValue performFP_TO_INTCombine(SDNode *N, 7860 TargetLowering::DAGCombinerInfo &DCI, 7861 const RISCVSubtarget &Subtarget) { 7862 SelectionDAG &DAG = DCI.DAG; 7863 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7864 MVT XLenVT = Subtarget.getXLenVT(); 7865 7866 // Only handle XLen or i32 types. Other types narrower than XLen will 7867 // eventually be legalized to XLenVT. 7868 EVT VT = N->getValueType(0); 7869 if (VT != MVT::i32 && VT != XLenVT) 7870 return SDValue(); 7871 7872 SDValue Src = N->getOperand(0); 7873 7874 // Ensure the FP type is also legal. 7875 if (!TLI.isTypeLegal(Src.getValueType())) 7876 return SDValue(); 7877 7878 // Don't do this for f16 with Zfhmin and not Zfh. 7879 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7880 return SDValue(); 7881 7882 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7883 if (FRM == RISCVFPRndMode::Invalid) 7884 return SDValue(); 7885 7886 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7887 7888 unsigned Opc; 7889 if (VT == XLenVT) 7890 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7891 else 7892 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7893 7894 SDLoc DL(N); 7895 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 7896 DAG.getTargetConstant(FRM, DL, XLenVT)); 7897 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 7898 } 7899 7900 // Fold 7901 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 7902 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 7903 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 7904 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 7905 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 7906 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 7907 TargetLowering::DAGCombinerInfo &DCI, 7908 const RISCVSubtarget &Subtarget) { 7909 SelectionDAG &DAG = DCI.DAG; 7910 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7911 MVT XLenVT = Subtarget.getXLenVT(); 7912 7913 // Only handle XLen types. Other types narrower than XLen will eventually be 7914 // legalized to XLenVT. 7915 EVT DstVT = N->getValueType(0); 7916 if (DstVT != XLenVT) 7917 return SDValue(); 7918 7919 SDValue Src = N->getOperand(0); 7920 7921 // Ensure the FP type is also legal. 7922 if (!TLI.isTypeLegal(Src.getValueType())) 7923 return SDValue(); 7924 7925 // Don't do this for f16 with Zfhmin and not Zfh. 7926 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7927 return SDValue(); 7928 7929 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7930 7931 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7932 if (FRM == RISCVFPRndMode::Invalid) 7933 return SDValue(); 7934 7935 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 7936 7937 unsigned Opc; 7938 if (SatVT == DstVT) 7939 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7940 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 7941 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7942 else 7943 return SDValue(); 7944 // FIXME: Support other SatVTs by clamping before or after the conversion. 7945 7946 Src = Src.getOperand(0); 7947 7948 SDLoc DL(N); 7949 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 7950 DAG.getTargetConstant(FRM, DL, XLenVT)); 7951 7952 // RISCV FP-to-int conversions saturate to the destination register size, but 7953 // don't produce 0 for nan. 7954 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 7955 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 7956 } 7957 7958 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 7959 DAGCombinerInfo &DCI) const { 7960 SelectionDAG &DAG = DCI.DAG; 7961 7962 // Helper to call SimplifyDemandedBits on an operand of N where only some low 7963 // bits are demanded. N will be added to the Worklist if it was not deleted. 7964 // Caller should return SDValue(N, 0) if this returns true. 7965 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 7966 SDValue Op = N->getOperand(OpNo); 7967 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 7968 if (!SimplifyDemandedBits(Op, Mask, DCI)) 7969 return false; 7970 7971 if (N->getOpcode() != ISD::DELETED_NODE) 7972 DCI.AddToWorklist(N); 7973 return true; 7974 }; 7975 7976 switch (N->getOpcode()) { 7977 default: 7978 break; 7979 case RISCVISD::SplitF64: { 7980 SDValue Op0 = N->getOperand(0); 7981 // If the input to SplitF64 is just BuildPairF64 then the operation is 7982 // redundant. Instead, use BuildPairF64's operands directly. 7983 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 7984 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 7985 7986 if (Op0->isUndef()) { 7987 SDValue Lo = DAG.getUNDEF(MVT::i32); 7988 SDValue Hi = DAG.getUNDEF(MVT::i32); 7989 return DCI.CombineTo(N, Lo, Hi); 7990 } 7991 7992 SDLoc DL(N); 7993 7994 // It's cheaper to materialise two 32-bit integers than to load a double 7995 // from the constant pool and transfer it to integer registers through the 7996 // stack. 7997 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 7998 APInt V = C->getValueAPF().bitcastToAPInt(); 7999 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8000 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8001 return DCI.CombineTo(N, Lo, Hi); 8002 } 8003 8004 // This is a target-specific version of a DAGCombine performed in 8005 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8006 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8007 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8008 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8009 !Op0.getNode()->hasOneUse()) 8010 break; 8011 SDValue NewSplitF64 = 8012 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8013 Op0.getOperand(0)); 8014 SDValue Lo = NewSplitF64.getValue(0); 8015 SDValue Hi = NewSplitF64.getValue(1); 8016 APInt SignBit = APInt::getSignMask(32); 8017 if (Op0.getOpcode() == ISD::FNEG) { 8018 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8019 DAG.getConstant(SignBit, DL, MVT::i32)); 8020 return DCI.CombineTo(N, Lo, NewHi); 8021 } 8022 assert(Op0.getOpcode() == ISD::FABS); 8023 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8024 DAG.getConstant(~SignBit, DL, MVT::i32)); 8025 return DCI.CombineTo(N, Lo, NewHi); 8026 } 8027 case RISCVISD::SLLW: 8028 case RISCVISD::SRAW: 8029 case RISCVISD::SRLW: 8030 case RISCVISD::ROLW: 8031 case RISCVISD::RORW: { 8032 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8033 if (SimplifyDemandedLowBitsHelper(0, 32) || 8034 SimplifyDemandedLowBitsHelper(1, 5)) 8035 return SDValue(N, 0); 8036 8037 return combineROTR_ROTL_RORW_ROLW(N, DAG); 8038 } 8039 case ISD::ROTR: 8040 case ISD::ROTL: 8041 return combineROTR_ROTL_RORW_ROLW(N, DAG); 8042 case RISCVISD::CLZW: 8043 case RISCVISD::CTZW: { 8044 // Only the lower 32 bits of the first operand are read 8045 if (SimplifyDemandedLowBitsHelper(0, 32)) 8046 return SDValue(N, 0); 8047 break; 8048 } 8049 case RISCVISD::GREV: 8050 case RISCVISD::GORC: { 8051 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8052 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8053 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8054 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8055 return SDValue(N, 0); 8056 8057 return combineGREVI_GORCI(N, DAG); 8058 } 8059 case RISCVISD::GREVW: 8060 case RISCVISD::GORCW: { 8061 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8062 if (SimplifyDemandedLowBitsHelper(0, 32) || 8063 SimplifyDemandedLowBitsHelper(1, 5)) 8064 return SDValue(N, 0); 8065 8066 return combineGREVI_GORCI(N, DAG); 8067 } 8068 case RISCVISD::SHFL: 8069 case RISCVISD::UNSHFL: { 8070 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8071 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8072 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8073 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8074 return SDValue(N, 0); 8075 8076 break; 8077 } 8078 case RISCVISD::SHFLW: 8079 case RISCVISD::UNSHFLW: { 8080 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8081 if (SimplifyDemandedLowBitsHelper(0, 32) || 8082 SimplifyDemandedLowBitsHelper(1, 4)) 8083 return SDValue(N, 0); 8084 8085 break; 8086 } 8087 case RISCVISD::BCOMPRESSW: 8088 case RISCVISD::BDECOMPRESSW: { 8089 // Only the lower 32 bits of LHS and RHS are read. 8090 if (SimplifyDemandedLowBitsHelper(0, 32) || 8091 SimplifyDemandedLowBitsHelper(1, 32)) 8092 return SDValue(N, 0); 8093 8094 break; 8095 } 8096 case RISCVISD::FMV_X_ANYEXTH: 8097 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8098 SDLoc DL(N); 8099 SDValue Op0 = N->getOperand(0); 8100 MVT VT = N->getSimpleValueType(0); 8101 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8102 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8103 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8104 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8105 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8106 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8107 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8108 assert(Op0.getOperand(0).getValueType() == VT && 8109 "Unexpected value type!"); 8110 return Op0.getOperand(0); 8111 } 8112 8113 // This is a target-specific version of a DAGCombine performed in 8114 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8115 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8116 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8117 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8118 !Op0.getNode()->hasOneUse()) 8119 break; 8120 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8121 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8122 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8123 if (Op0.getOpcode() == ISD::FNEG) 8124 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8125 DAG.getConstant(SignBit, DL, VT)); 8126 8127 assert(Op0.getOpcode() == ISD::FABS); 8128 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8129 DAG.getConstant(~SignBit, DL, VT)); 8130 } 8131 case ISD::ADD: 8132 return performADDCombine(N, DAG, Subtarget); 8133 case ISD::SUB: 8134 return performSUBCombine(N, DAG); 8135 case ISD::AND: 8136 return performANDCombine(N, DAG); 8137 case ISD::OR: 8138 return performORCombine(N, DAG, Subtarget); 8139 case ISD::XOR: 8140 return performXORCombine(N, DAG); 8141 case ISD::SIGN_EXTEND_INREG: 8142 return performSIGN_EXTEND_INREG(N, DAG); 8143 case ISD::ANY_EXTEND: 8144 return performANY_EXTENDCombine(N, DCI, Subtarget); 8145 case ISD::ZERO_EXTEND: 8146 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8147 // type legalization. This is safe because fp_to_uint produces poison if 8148 // it overflows. 8149 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8150 SDValue Src = N->getOperand(0); 8151 if (Src.getOpcode() == ISD::FP_TO_UINT && 8152 isTypeLegal(Src.getOperand(0).getValueType())) 8153 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8154 Src.getOperand(0)); 8155 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8156 isTypeLegal(Src.getOperand(1).getValueType())) { 8157 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8158 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8159 Src.getOperand(0), Src.getOperand(1)); 8160 DCI.CombineTo(N, Res); 8161 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8162 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8163 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8164 } 8165 } 8166 return SDValue(); 8167 case RISCVISD::SELECT_CC: { 8168 // Transform 8169 SDValue LHS = N->getOperand(0); 8170 SDValue RHS = N->getOperand(1); 8171 SDValue TrueV = N->getOperand(3); 8172 SDValue FalseV = N->getOperand(4); 8173 8174 // If the True and False values are the same, we don't need a select_cc. 8175 if (TrueV == FalseV) 8176 return TrueV; 8177 8178 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8179 if (!ISD::isIntEqualitySetCC(CCVal)) 8180 break; 8181 8182 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8183 // (select_cc X, Y, lt, trueV, falseV) 8184 // Sometimes the setcc is introduced after select_cc has been formed. 8185 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8186 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8187 // If we're looking for eq 0 instead of ne 0, we need to invert the 8188 // condition. 8189 bool Invert = CCVal == ISD::SETEQ; 8190 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8191 if (Invert) 8192 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8193 8194 SDLoc DL(N); 8195 RHS = LHS.getOperand(1); 8196 LHS = LHS.getOperand(0); 8197 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8198 8199 SDValue TargetCC = DAG.getCondCode(CCVal); 8200 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8201 {LHS, RHS, TargetCC, TrueV, FalseV}); 8202 } 8203 8204 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8205 // (select_cc X, Y, eq/ne, trueV, falseV) 8206 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8207 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8208 {LHS.getOperand(0), LHS.getOperand(1), 8209 N->getOperand(2), TrueV, FalseV}); 8210 // (select_cc X, 1, setne, trueV, falseV) -> 8211 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8212 // This can occur when legalizing some floating point comparisons. 8213 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8214 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8215 SDLoc DL(N); 8216 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8217 SDValue TargetCC = DAG.getCondCode(CCVal); 8218 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8219 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8220 {LHS, RHS, TargetCC, TrueV, FalseV}); 8221 } 8222 8223 break; 8224 } 8225 case RISCVISD::BR_CC: { 8226 SDValue LHS = N->getOperand(1); 8227 SDValue RHS = N->getOperand(2); 8228 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8229 if (!ISD::isIntEqualitySetCC(CCVal)) 8230 break; 8231 8232 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8233 // (br_cc X, Y, lt, dest) 8234 // Sometimes the setcc is introduced after br_cc has been formed. 8235 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8236 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8237 // If we're looking for eq 0 instead of ne 0, we need to invert the 8238 // condition. 8239 bool Invert = CCVal == ISD::SETEQ; 8240 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8241 if (Invert) 8242 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8243 8244 SDLoc DL(N); 8245 RHS = LHS.getOperand(1); 8246 LHS = LHS.getOperand(0); 8247 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8248 8249 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8250 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8251 N->getOperand(4)); 8252 } 8253 8254 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8255 // (br_cc X, Y, eq/ne, trueV, falseV) 8256 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8257 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8258 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8259 N->getOperand(3), N->getOperand(4)); 8260 8261 // (br_cc X, 1, setne, br_cc) -> 8262 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8263 // This can occur when legalizing some floating point comparisons. 8264 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8265 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8266 SDLoc DL(N); 8267 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8268 SDValue TargetCC = DAG.getCondCode(CCVal); 8269 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8270 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8271 N->getOperand(0), LHS, RHS, TargetCC, 8272 N->getOperand(4)); 8273 } 8274 break; 8275 } 8276 case ISD::FP_TO_SINT: 8277 case ISD::FP_TO_UINT: 8278 return performFP_TO_INTCombine(N, DCI, Subtarget); 8279 case ISD::FP_TO_SINT_SAT: 8280 case ISD::FP_TO_UINT_SAT: 8281 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8282 case ISD::FCOPYSIGN: { 8283 EVT VT = N->getValueType(0); 8284 if (!VT.isVector()) 8285 break; 8286 // There is a form of VFSGNJ which injects the negated sign of its second 8287 // operand. Try and bubble any FNEG up after the extend/round to produce 8288 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8289 // TRUNC=1. 8290 SDValue In2 = N->getOperand(1); 8291 // Avoid cases where the extend/round has multiple uses, as duplicating 8292 // those is typically more expensive than removing a fneg. 8293 if (!In2.hasOneUse()) 8294 break; 8295 if (In2.getOpcode() != ISD::FP_EXTEND && 8296 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8297 break; 8298 In2 = In2.getOperand(0); 8299 if (In2.getOpcode() != ISD::FNEG) 8300 break; 8301 SDLoc DL(N); 8302 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8303 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8304 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8305 } 8306 case ISD::MGATHER: 8307 case ISD::MSCATTER: 8308 case ISD::VP_GATHER: 8309 case ISD::VP_SCATTER: { 8310 if (!DCI.isBeforeLegalize()) 8311 break; 8312 SDValue Index, ScaleOp; 8313 bool IsIndexScaled = false; 8314 bool IsIndexSigned = false; 8315 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8316 Index = VPGSN->getIndex(); 8317 ScaleOp = VPGSN->getScale(); 8318 IsIndexScaled = VPGSN->isIndexScaled(); 8319 IsIndexSigned = VPGSN->isIndexSigned(); 8320 } else { 8321 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8322 Index = MGSN->getIndex(); 8323 ScaleOp = MGSN->getScale(); 8324 IsIndexScaled = MGSN->isIndexScaled(); 8325 IsIndexSigned = MGSN->isIndexSigned(); 8326 } 8327 EVT IndexVT = Index.getValueType(); 8328 MVT XLenVT = Subtarget.getXLenVT(); 8329 // RISCV indexed loads only support the "unsigned unscaled" addressing 8330 // mode, so anything else must be manually legalized. 8331 bool NeedsIdxLegalization = 8332 IsIndexScaled || 8333 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8334 if (!NeedsIdxLegalization) 8335 break; 8336 8337 SDLoc DL(N); 8338 8339 // Any index legalization should first promote to XLenVT, so we don't lose 8340 // bits when scaling. This may create an illegal index type so we let 8341 // LLVM's legalization take care of the splitting. 8342 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8343 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8344 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8345 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8346 DL, IndexVT, Index); 8347 } 8348 8349 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8350 if (IsIndexScaled && Scale != 1) { 8351 // Manually scale the indices by the element size. 8352 // TODO: Sanitize the scale operand here? 8353 // TODO: For VP nodes, should we use VP_SHL here? 8354 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8355 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8356 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8357 } 8358 8359 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8360 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8361 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8362 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8363 VPGN->getScale(), VPGN->getMask(), 8364 VPGN->getVectorLength()}, 8365 VPGN->getMemOperand(), NewIndexTy); 8366 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8367 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8368 {VPSN->getChain(), VPSN->getValue(), 8369 VPSN->getBasePtr(), Index, VPSN->getScale(), 8370 VPSN->getMask(), VPSN->getVectorLength()}, 8371 VPSN->getMemOperand(), NewIndexTy); 8372 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8373 return DAG.getMaskedGather( 8374 N->getVTList(), MGN->getMemoryVT(), DL, 8375 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8376 MGN->getBasePtr(), Index, MGN->getScale()}, 8377 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8378 const auto *MSN = cast<MaskedScatterSDNode>(N); 8379 return DAG.getMaskedScatter( 8380 N->getVTList(), MSN->getMemoryVT(), DL, 8381 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8382 Index, MSN->getScale()}, 8383 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8384 } 8385 case RISCVISD::SRA_VL: 8386 case RISCVISD::SRL_VL: 8387 case RISCVISD::SHL_VL: { 8388 SDValue ShAmt = N->getOperand(1); 8389 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8390 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8391 SDLoc DL(N); 8392 SDValue VL = N->getOperand(3); 8393 EVT VT = N->getValueType(0); 8394 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8395 ShAmt.getOperand(1), VL); 8396 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8397 N->getOperand(2), N->getOperand(3)); 8398 } 8399 break; 8400 } 8401 case ISD::SRA: 8402 case ISD::SRL: 8403 case ISD::SHL: { 8404 SDValue ShAmt = N->getOperand(1); 8405 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8406 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8407 SDLoc DL(N); 8408 EVT VT = N->getValueType(0); 8409 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8410 ShAmt.getOperand(1), 8411 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8412 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8413 } 8414 break; 8415 } 8416 case RISCVISD::ADD_VL: 8417 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8418 return V; 8419 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8420 case RISCVISD::SUB_VL: 8421 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8422 case RISCVISD::VWADD_W_VL: 8423 case RISCVISD::VWADDU_W_VL: 8424 case RISCVISD::VWSUB_W_VL: 8425 case RISCVISD::VWSUBU_W_VL: 8426 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8427 case RISCVISD::MUL_VL: 8428 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8429 return V; 8430 // Mul is commutative. 8431 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8432 case ISD::STORE: { 8433 auto *Store = cast<StoreSDNode>(N); 8434 SDValue Val = Store->getValue(); 8435 // Combine store of vmv.x.s to vse with VL of 1. 8436 // FIXME: Support FP. 8437 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8438 SDValue Src = Val.getOperand(0); 8439 EVT VecVT = Src.getValueType(); 8440 EVT MemVT = Store->getMemoryVT(); 8441 // The memory VT and the element type must match. 8442 if (VecVT.getVectorElementType() == MemVT) { 8443 SDLoc DL(N); 8444 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8445 return DAG.getStoreVP( 8446 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8447 DAG.getConstant(1, DL, MaskVT), 8448 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8449 Store->getMemOperand(), Store->getAddressingMode(), 8450 Store->isTruncatingStore(), /*IsCompress*/ false); 8451 } 8452 } 8453 8454 break; 8455 } 8456 case ISD::SPLAT_VECTOR: { 8457 EVT VT = N->getValueType(0); 8458 // Only perform this combine on legal MVT types. 8459 if (!isTypeLegal(VT)) 8460 break; 8461 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8462 DAG, Subtarget)) 8463 return Gather; 8464 break; 8465 } 8466 case RISCVISD::VMV_V_X_VL: { 8467 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8468 // scalar input. 8469 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8470 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8471 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8472 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8473 return SDValue(N, 0); 8474 8475 break; 8476 } 8477 } 8478 8479 return SDValue(); 8480 } 8481 8482 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8483 const SDNode *N, CombineLevel Level) const { 8484 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8485 // materialised in fewer instructions than `(OP _, c1)`: 8486 // 8487 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8488 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8489 SDValue N0 = N->getOperand(0); 8490 EVT Ty = N0.getValueType(); 8491 if (Ty.isScalarInteger() && 8492 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8493 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8494 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8495 if (C1 && C2) { 8496 const APInt &C1Int = C1->getAPIntValue(); 8497 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8498 8499 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8500 // and the combine should happen, to potentially allow further combines 8501 // later. 8502 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8503 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8504 return true; 8505 8506 // We can materialise `c1` in an add immediate, so it's "free", and the 8507 // combine should be prevented. 8508 if (C1Int.getMinSignedBits() <= 64 && 8509 isLegalAddImmediate(C1Int.getSExtValue())) 8510 return false; 8511 8512 // Neither constant will fit into an immediate, so find materialisation 8513 // costs. 8514 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8515 Subtarget.getFeatureBits(), 8516 /*CompressionCost*/true); 8517 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8518 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8519 /*CompressionCost*/true); 8520 8521 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8522 // combine should be prevented. 8523 if (C1Cost < ShiftedC1Cost) 8524 return false; 8525 } 8526 } 8527 return true; 8528 } 8529 8530 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8531 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8532 TargetLoweringOpt &TLO) const { 8533 // Delay this optimization as late as possible. 8534 if (!TLO.LegalOps) 8535 return false; 8536 8537 EVT VT = Op.getValueType(); 8538 if (VT.isVector()) 8539 return false; 8540 8541 // Only handle AND for now. 8542 if (Op.getOpcode() != ISD::AND) 8543 return false; 8544 8545 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8546 if (!C) 8547 return false; 8548 8549 const APInt &Mask = C->getAPIntValue(); 8550 8551 // Clear all non-demanded bits initially. 8552 APInt ShrunkMask = Mask & DemandedBits; 8553 8554 // Try to make a smaller immediate by setting undemanded bits. 8555 8556 APInt ExpandedMask = Mask | ~DemandedBits; 8557 8558 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8559 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8560 }; 8561 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8562 if (NewMask == Mask) 8563 return true; 8564 SDLoc DL(Op); 8565 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8566 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8567 return TLO.CombineTo(Op, NewOp); 8568 }; 8569 8570 // If the shrunk mask fits in sign extended 12 bits, let the target 8571 // independent code apply it. 8572 if (ShrunkMask.isSignedIntN(12)) 8573 return false; 8574 8575 // Preserve (and X, 0xffff) when zext.h is supported. 8576 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8577 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8578 if (IsLegalMask(NewMask)) 8579 return UseMask(NewMask); 8580 } 8581 8582 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8583 if (VT == MVT::i64) { 8584 APInt NewMask = APInt(64, 0xffffffff); 8585 if (IsLegalMask(NewMask)) 8586 return UseMask(NewMask); 8587 } 8588 8589 // For the remaining optimizations, we need to be able to make a negative 8590 // number through a combination of mask and undemanded bits. 8591 if (!ExpandedMask.isNegative()) 8592 return false; 8593 8594 // What is the fewest number of bits we need to represent the negative number. 8595 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8596 8597 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8598 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8599 APInt NewMask = ShrunkMask; 8600 if (MinSignedBits <= 12) 8601 NewMask.setBitsFrom(11); 8602 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8603 NewMask.setBitsFrom(31); 8604 else 8605 return false; 8606 8607 // Check that our new mask is a subset of the demanded mask. 8608 assert(IsLegalMask(NewMask)); 8609 return UseMask(NewMask); 8610 } 8611 8612 static void computeGREV(APInt &Src, unsigned ShAmt) { 8613 ShAmt &= Src.getBitWidth() - 1; 8614 uint64_t x = Src.getZExtValue(); 8615 if (ShAmt & 1) 8616 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 8617 if (ShAmt & 2) 8618 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 8619 if (ShAmt & 4) 8620 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 8621 if (ShAmt & 8) 8622 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 8623 if (ShAmt & 16) 8624 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 8625 if (ShAmt & 32) 8626 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 8627 Src = x; 8628 } 8629 8630 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8631 KnownBits &Known, 8632 const APInt &DemandedElts, 8633 const SelectionDAG &DAG, 8634 unsigned Depth) const { 8635 unsigned BitWidth = Known.getBitWidth(); 8636 unsigned Opc = Op.getOpcode(); 8637 assert((Opc >= ISD::BUILTIN_OP_END || 8638 Opc == ISD::INTRINSIC_WO_CHAIN || 8639 Opc == ISD::INTRINSIC_W_CHAIN || 8640 Opc == ISD::INTRINSIC_VOID) && 8641 "Should use MaskedValueIsZero if you don't know whether Op" 8642 " is a target node!"); 8643 8644 Known.resetAll(); 8645 switch (Opc) { 8646 default: break; 8647 case RISCVISD::SELECT_CC: { 8648 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8649 // If we don't know any bits, early out. 8650 if (Known.isUnknown()) 8651 break; 8652 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8653 8654 // Only known if known in both the LHS and RHS. 8655 Known = KnownBits::commonBits(Known, Known2); 8656 break; 8657 } 8658 case RISCVISD::REMUW: { 8659 KnownBits Known2; 8660 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8661 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8662 // We only care about the lower 32 bits. 8663 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8664 // Restore the original width by sign extending. 8665 Known = Known.sext(BitWidth); 8666 break; 8667 } 8668 case RISCVISD::DIVUW: { 8669 KnownBits Known2; 8670 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8671 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8672 // We only care about the lower 32 bits. 8673 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8674 // Restore the original width by sign extending. 8675 Known = Known.sext(BitWidth); 8676 break; 8677 } 8678 case RISCVISD::CTZW: { 8679 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8680 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 8681 unsigned LowBits = Log2_32(PossibleTZ) + 1; 8682 Known.Zero.setBitsFrom(LowBits); 8683 break; 8684 } 8685 case RISCVISD::CLZW: { 8686 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8687 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 8688 unsigned LowBits = Log2_32(PossibleLZ) + 1; 8689 Known.Zero.setBitsFrom(LowBits); 8690 break; 8691 } 8692 case RISCVISD::GREV: 8693 case RISCVISD::GREVW: { 8694 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8695 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8696 if (Opc == RISCVISD::GREVW) 8697 Known = Known.trunc(32); 8698 unsigned ShAmt = C->getZExtValue(); 8699 computeGREV(Known.Zero, ShAmt); 8700 computeGREV(Known.One, ShAmt); 8701 if (Opc == RISCVISD::GREVW) 8702 Known = Known.sext(BitWidth); 8703 } 8704 break; 8705 } 8706 case RISCVISD::READ_VLENB: { 8707 // If we know the minimum VLen from Zvl extensions, we can use that to 8708 // determine the trailing zeros of VLENB. 8709 // FIXME: Limit to 128 bit vectors until we have more testing. 8710 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 8711 if (MinVLenB > 0) 8712 Known.Zero.setLowBits(Log2_32(MinVLenB)); 8713 // We assume VLENB is no more than 65536 / 8 bytes. 8714 Known.Zero.setBitsFrom(14); 8715 break; 8716 } 8717 case ISD::INTRINSIC_W_CHAIN: 8718 case ISD::INTRINSIC_WO_CHAIN: { 8719 unsigned IntNo = 8720 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 8721 switch (IntNo) { 8722 default: 8723 // We can't do anything for most intrinsics. 8724 break; 8725 case Intrinsic::riscv_vsetvli: 8726 case Intrinsic::riscv_vsetvlimax: 8727 case Intrinsic::riscv_vsetvli_opt: 8728 case Intrinsic::riscv_vsetvlimax_opt: 8729 // Assume that VL output is positive and would fit in an int32_t. 8730 // TODO: VLEN might be capped at 16 bits in a future V spec update. 8731 if (BitWidth >= 32) 8732 Known.Zero.setBitsFrom(31); 8733 break; 8734 } 8735 break; 8736 } 8737 } 8738 } 8739 8740 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 8741 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 8742 unsigned Depth) const { 8743 switch (Op.getOpcode()) { 8744 default: 8745 break; 8746 case RISCVISD::SELECT_CC: { 8747 unsigned Tmp = 8748 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 8749 if (Tmp == 1) return 1; // Early out. 8750 unsigned Tmp2 = 8751 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 8752 return std::min(Tmp, Tmp2); 8753 } 8754 case RISCVISD::SLLW: 8755 case RISCVISD::SRAW: 8756 case RISCVISD::SRLW: 8757 case RISCVISD::DIVW: 8758 case RISCVISD::DIVUW: 8759 case RISCVISD::REMUW: 8760 case RISCVISD::ROLW: 8761 case RISCVISD::RORW: 8762 case RISCVISD::GREVW: 8763 case RISCVISD::GORCW: 8764 case RISCVISD::FSLW: 8765 case RISCVISD::FSRW: 8766 case RISCVISD::SHFLW: 8767 case RISCVISD::UNSHFLW: 8768 case RISCVISD::BCOMPRESSW: 8769 case RISCVISD::BDECOMPRESSW: 8770 case RISCVISD::BFPW: 8771 case RISCVISD::FCVT_W_RV64: 8772 case RISCVISD::FCVT_WU_RV64: 8773 case RISCVISD::STRICT_FCVT_W_RV64: 8774 case RISCVISD::STRICT_FCVT_WU_RV64: 8775 // TODO: As the result is sign-extended, this is conservatively correct. A 8776 // more precise answer could be calculated for SRAW depending on known 8777 // bits in the shift amount. 8778 return 33; 8779 case RISCVISD::SHFL: 8780 case RISCVISD::UNSHFL: { 8781 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 8782 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 8783 // will stay within the upper 32 bits. If there were more than 32 sign bits 8784 // before there will be at least 33 sign bits after. 8785 if (Op.getValueType() == MVT::i64 && 8786 isa<ConstantSDNode>(Op.getOperand(1)) && 8787 (Op.getConstantOperandVal(1) & 0x10) == 0) { 8788 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 8789 if (Tmp > 32) 8790 return 33; 8791 } 8792 break; 8793 } 8794 case RISCVISD::VMV_X_S: { 8795 // The number of sign bits of the scalar result is computed by obtaining the 8796 // element type of the input vector operand, subtracting its width from the 8797 // XLEN, and then adding one (sign bit within the element type). If the 8798 // element type is wider than XLen, the least-significant XLEN bits are 8799 // taken. 8800 unsigned XLen = Subtarget.getXLen(); 8801 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 8802 if (EltBits <= XLen) 8803 return XLen - EltBits + 1; 8804 break; 8805 } 8806 } 8807 8808 return 1; 8809 } 8810 8811 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 8812 MachineBasicBlock *BB) { 8813 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 8814 8815 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 8816 // Should the count have wrapped while it was being read, we need to try 8817 // again. 8818 // ... 8819 // read: 8820 // rdcycleh x3 # load high word of cycle 8821 // rdcycle x2 # load low word of cycle 8822 // rdcycleh x4 # load high word of cycle 8823 // bne x3, x4, read # check if high word reads match, otherwise try again 8824 // ... 8825 8826 MachineFunction &MF = *BB->getParent(); 8827 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8828 MachineFunction::iterator It = ++BB->getIterator(); 8829 8830 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8831 MF.insert(It, LoopMBB); 8832 8833 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8834 MF.insert(It, DoneMBB); 8835 8836 // Transfer the remainder of BB and its successor edges to DoneMBB. 8837 DoneMBB->splice(DoneMBB->begin(), BB, 8838 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8839 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 8840 8841 BB->addSuccessor(LoopMBB); 8842 8843 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8844 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8845 Register LoReg = MI.getOperand(0).getReg(); 8846 Register HiReg = MI.getOperand(1).getReg(); 8847 DebugLoc DL = MI.getDebugLoc(); 8848 8849 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 8850 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 8851 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8852 .addReg(RISCV::X0); 8853 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 8854 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 8855 .addReg(RISCV::X0); 8856 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 8857 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8858 .addReg(RISCV::X0); 8859 8860 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 8861 .addReg(HiReg) 8862 .addReg(ReadAgainReg) 8863 .addMBB(LoopMBB); 8864 8865 LoopMBB->addSuccessor(LoopMBB); 8866 LoopMBB->addSuccessor(DoneMBB); 8867 8868 MI.eraseFromParent(); 8869 8870 return DoneMBB; 8871 } 8872 8873 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 8874 MachineBasicBlock *BB) { 8875 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 8876 8877 MachineFunction &MF = *BB->getParent(); 8878 DebugLoc DL = MI.getDebugLoc(); 8879 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8880 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8881 Register LoReg = MI.getOperand(0).getReg(); 8882 Register HiReg = MI.getOperand(1).getReg(); 8883 Register SrcReg = MI.getOperand(2).getReg(); 8884 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 8885 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8886 8887 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 8888 RI); 8889 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8890 MachineMemOperand *MMOLo = 8891 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 8892 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8893 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 8894 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 8895 .addFrameIndex(FI) 8896 .addImm(0) 8897 .addMemOperand(MMOLo); 8898 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 8899 .addFrameIndex(FI) 8900 .addImm(4) 8901 .addMemOperand(MMOHi); 8902 MI.eraseFromParent(); // The pseudo instruction is gone now. 8903 return BB; 8904 } 8905 8906 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 8907 MachineBasicBlock *BB) { 8908 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 8909 "Unexpected instruction"); 8910 8911 MachineFunction &MF = *BB->getParent(); 8912 DebugLoc DL = MI.getDebugLoc(); 8913 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8914 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8915 Register DstReg = MI.getOperand(0).getReg(); 8916 Register LoReg = MI.getOperand(1).getReg(); 8917 Register HiReg = MI.getOperand(2).getReg(); 8918 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 8919 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8920 8921 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8922 MachineMemOperand *MMOLo = 8923 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 8924 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8925 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 8926 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8927 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 8928 .addFrameIndex(FI) 8929 .addImm(0) 8930 .addMemOperand(MMOLo); 8931 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8932 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 8933 .addFrameIndex(FI) 8934 .addImm(4) 8935 .addMemOperand(MMOHi); 8936 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 8937 MI.eraseFromParent(); // The pseudo instruction is gone now. 8938 return BB; 8939 } 8940 8941 static bool isSelectPseudo(MachineInstr &MI) { 8942 switch (MI.getOpcode()) { 8943 default: 8944 return false; 8945 case RISCV::Select_GPR_Using_CC_GPR: 8946 case RISCV::Select_FPR16_Using_CC_GPR: 8947 case RISCV::Select_FPR32_Using_CC_GPR: 8948 case RISCV::Select_FPR64_Using_CC_GPR: 8949 return true; 8950 } 8951 } 8952 8953 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 8954 unsigned RelOpcode, unsigned EqOpcode, 8955 const RISCVSubtarget &Subtarget) { 8956 DebugLoc DL = MI.getDebugLoc(); 8957 Register DstReg = MI.getOperand(0).getReg(); 8958 Register Src1Reg = MI.getOperand(1).getReg(); 8959 Register Src2Reg = MI.getOperand(2).getReg(); 8960 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 8961 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 8962 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 8963 8964 // Save the current FFLAGS. 8965 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 8966 8967 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 8968 .addReg(Src1Reg) 8969 .addReg(Src2Reg); 8970 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8971 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 8972 8973 // Restore the FFLAGS. 8974 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 8975 .addReg(SavedFFlags, RegState::Kill); 8976 8977 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 8978 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 8979 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 8980 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 8981 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8982 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 8983 8984 // Erase the pseudoinstruction. 8985 MI.eraseFromParent(); 8986 return BB; 8987 } 8988 8989 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 8990 MachineBasicBlock *BB, 8991 const RISCVSubtarget &Subtarget) { 8992 // To "insert" Select_* instructions, we actually have to insert the triangle 8993 // control-flow pattern. The incoming instructions know the destination vreg 8994 // to set, the condition code register to branch on, the true/false values to 8995 // select between, and the condcode to use to select the appropriate branch. 8996 // 8997 // We produce the following control flow: 8998 // HeadMBB 8999 // | \ 9000 // | IfFalseMBB 9001 // | / 9002 // TailMBB 9003 // 9004 // When we find a sequence of selects we attempt to optimize their emission 9005 // by sharing the control flow. Currently we only handle cases where we have 9006 // multiple selects with the exact same condition (same LHS, RHS and CC). 9007 // The selects may be interleaved with other instructions if the other 9008 // instructions meet some requirements we deem safe: 9009 // - They are debug instructions. Otherwise, 9010 // - They do not have side-effects, do not access memory and their inputs do 9011 // not depend on the results of the select pseudo-instructions. 9012 // The TrueV/FalseV operands of the selects cannot depend on the result of 9013 // previous selects in the sequence. 9014 // These conditions could be further relaxed. See the X86 target for a 9015 // related approach and more information. 9016 Register LHS = MI.getOperand(1).getReg(); 9017 Register RHS = MI.getOperand(2).getReg(); 9018 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9019 9020 SmallVector<MachineInstr *, 4> SelectDebugValues; 9021 SmallSet<Register, 4> SelectDests; 9022 SelectDests.insert(MI.getOperand(0).getReg()); 9023 9024 MachineInstr *LastSelectPseudo = &MI; 9025 9026 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9027 SequenceMBBI != E; ++SequenceMBBI) { 9028 if (SequenceMBBI->isDebugInstr()) 9029 continue; 9030 else if (isSelectPseudo(*SequenceMBBI)) { 9031 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9032 SequenceMBBI->getOperand(2).getReg() != RHS || 9033 SequenceMBBI->getOperand(3).getImm() != CC || 9034 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9035 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9036 break; 9037 LastSelectPseudo = &*SequenceMBBI; 9038 SequenceMBBI->collectDebugValues(SelectDebugValues); 9039 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9040 } else { 9041 if (SequenceMBBI->hasUnmodeledSideEffects() || 9042 SequenceMBBI->mayLoadOrStore()) 9043 break; 9044 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9045 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9046 })) 9047 break; 9048 } 9049 } 9050 9051 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9052 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9053 DebugLoc DL = MI.getDebugLoc(); 9054 MachineFunction::iterator I = ++BB->getIterator(); 9055 9056 MachineBasicBlock *HeadMBB = BB; 9057 MachineFunction *F = BB->getParent(); 9058 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9059 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9060 9061 F->insert(I, IfFalseMBB); 9062 F->insert(I, TailMBB); 9063 9064 // Transfer debug instructions associated with the selects to TailMBB. 9065 for (MachineInstr *DebugInstr : SelectDebugValues) { 9066 TailMBB->push_back(DebugInstr->removeFromParent()); 9067 } 9068 9069 // Move all instructions after the sequence to TailMBB. 9070 TailMBB->splice(TailMBB->end(), HeadMBB, 9071 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9072 // Update machine-CFG edges by transferring all successors of the current 9073 // block to the new block which will contain the Phi nodes for the selects. 9074 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9075 // Set the successors for HeadMBB. 9076 HeadMBB->addSuccessor(IfFalseMBB); 9077 HeadMBB->addSuccessor(TailMBB); 9078 9079 // Insert appropriate branch. 9080 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9081 .addReg(LHS) 9082 .addReg(RHS) 9083 .addMBB(TailMBB); 9084 9085 // IfFalseMBB just falls through to TailMBB. 9086 IfFalseMBB->addSuccessor(TailMBB); 9087 9088 // Create PHIs for all of the select pseudo-instructions. 9089 auto SelectMBBI = MI.getIterator(); 9090 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9091 auto InsertionPoint = TailMBB->begin(); 9092 while (SelectMBBI != SelectEnd) { 9093 auto Next = std::next(SelectMBBI); 9094 if (isSelectPseudo(*SelectMBBI)) { 9095 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9096 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9097 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9098 .addReg(SelectMBBI->getOperand(4).getReg()) 9099 .addMBB(HeadMBB) 9100 .addReg(SelectMBBI->getOperand(5).getReg()) 9101 .addMBB(IfFalseMBB); 9102 SelectMBBI->eraseFromParent(); 9103 } 9104 SelectMBBI = Next; 9105 } 9106 9107 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9108 return TailMBB; 9109 } 9110 9111 MachineBasicBlock * 9112 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9113 MachineBasicBlock *BB) const { 9114 switch (MI.getOpcode()) { 9115 default: 9116 llvm_unreachable("Unexpected instr type to insert"); 9117 case RISCV::ReadCycleWide: 9118 assert(!Subtarget.is64Bit() && 9119 "ReadCycleWrite is only to be used on riscv32"); 9120 return emitReadCycleWidePseudo(MI, BB); 9121 case RISCV::Select_GPR_Using_CC_GPR: 9122 case RISCV::Select_FPR16_Using_CC_GPR: 9123 case RISCV::Select_FPR32_Using_CC_GPR: 9124 case RISCV::Select_FPR64_Using_CC_GPR: 9125 return emitSelectPseudo(MI, BB, Subtarget); 9126 case RISCV::BuildPairF64Pseudo: 9127 return emitBuildPairF64Pseudo(MI, BB); 9128 case RISCV::SplitF64Pseudo: 9129 return emitSplitF64Pseudo(MI, BB); 9130 case RISCV::PseudoQuietFLE_H: 9131 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9132 case RISCV::PseudoQuietFLT_H: 9133 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9134 case RISCV::PseudoQuietFLE_S: 9135 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9136 case RISCV::PseudoQuietFLT_S: 9137 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9138 case RISCV::PseudoQuietFLE_D: 9139 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9140 case RISCV::PseudoQuietFLT_D: 9141 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9142 } 9143 } 9144 9145 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9146 SDNode *Node) const { 9147 // Add FRM dependency to any instructions with dynamic rounding mode. 9148 unsigned Opc = MI.getOpcode(); 9149 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9150 if (Idx < 0) 9151 return; 9152 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9153 return; 9154 // If the instruction already reads FRM, don't add another read. 9155 if (MI.readsRegister(RISCV::FRM)) 9156 return; 9157 MI.addOperand( 9158 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9159 } 9160 9161 // Calling Convention Implementation. 9162 // The expectations for frontend ABI lowering vary from target to target. 9163 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9164 // details, but this is a longer term goal. For now, we simply try to keep the 9165 // role of the frontend as simple and well-defined as possible. The rules can 9166 // be summarised as: 9167 // * Never split up large scalar arguments. We handle them here. 9168 // * If a hardfloat calling convention is being used, and the struct may be 9169 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9170 // available, then pass as two separate arguments. If either the GPRs or FPRs 9171 // are exhausted, then pass according to the rule below. 9172 // * If a struct could never be passed in registers or directly in a stack 9173 // slot (as it is larger than 2*XLEN and the floating point rules don't 9174 // apply), then pass it using a pointer with the byval attribute. 9175 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9176 // word-sized array or a 2*XLEN scalar (depending on alignment). 9177 // * The frontend can determine whether a struct is returned by reference or 9178 // not based on its size and fields. If it will be returned by reference, the 9179 // frontend must modify the prototype so a pointer with the sret annotation is 9180 // passed as the first argument. This is not necessary for large scalar 9181 // returns. 9182 // * Struct return values and varargs should be coerced to structs containing 9183 // register-size fields in the same situations they would be for fixed 9184 // arguments. 9185 9186 static const MCPhysReg ArgGPRs[] = { 9187 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9188 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9189 }; 9190 static const MCPhysReg ArgFPR16s[] = { 9191 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9192 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9193 }; 9194 static const MCPhysReg ArgFPR32s[] = { 9195 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9196 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9197 }; 9198 static const MCPhysReg ArgFPR64s[] = { 9199 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9200 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9201 }; 9202 // This is an interim calling convention and it may be changed in the future. 9203 static const MCPhysReg ArgVRs[] = { 9204 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9205 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9206 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9207 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9208 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9209 RISCV::V20M2, RISCV::V22M2}; 9210 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9211 RISCV::V20M4}; 9212 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9213 9214 // Pass a 2*XLEN argument that has been split into two XLEN values through 9215 // registers or the stack as necessary. 9216 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9217 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9218 MVT ValVT2, MVT LocVT2, 9219 ISD::ArgFlagsTy ArgFlags2) { 9220 unsigned XLenInBytes = XLen / 8; 9221 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9222 // At least one half can be passed via register. 9223 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9224 VA1.getLocVT(), CCValAssign::Full)); 9225 } else { 9226 // Both halves must be passed on the stack, with proper alignment. 9227 Align StackAlign = 9228 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9229 State.addLoc( 9230 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9231 State.AllocateStack(XLenInBytes, StackAlign), 9232 VA1.getLocVT(), CCValAssign::Full)); 9233 State.addLoc(CCValAssign::getMem( 9234 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9235 LocVT2, CCValAssign::Full)); 9236 return false; 9237 } 9238 9239 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9240 // The second half can also be passed via register. 9241 State.addLoc( 9242 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9243 } else { 9244 // The second half is passed via the stack, without additional alignment. 9245 State.addLoc(CCValAssign::getMem( 9246 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9247 LocVT2, CCValAssign::Full)); 9248 } 9249 9250 return false; 9251 } 9252 9253 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9254 Optional<unsigned> FirstMaskArgument, 9255 CCState &State, const RISCVTargetLowering &TLI) { 9256 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9257 if (RC == &RISCV::VRRegClass) { 9258 // Assign the first mask argument to V0. 9259 // This is an interim calling convention and it may be changed in the 9260 // future. 9261 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9262 return State.AllocateReg(RISCV::V0); 9263 return State.AllocateReg(ArgVRs); 9264 } 9265 if (RC == &RISCV::VRM2RegClass) 9266 return State.AllocateReg(ArgVRM2s); 9267 if (RC == &RISCV::VRM4RegClass) 9268 return State.AllocateReg(ArgVRM4s); 9269 if (RC == &RISCV::VRM8RegClass) 9270 return State.AllocateReg(ArgVRM8s); 9271 llvm_unreachable("Unhandled register class for ValueType"); 9272 } 9273 9274 // Implements the RISC-V calling convention. Returns true upon failure. 9275 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9276 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9277 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9278 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9279 Optional<unsigned> FirstMaskArgument) { 9280 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9281 assert(XLen == 32 || XLen == 64); 9282 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9283 9284 // Any return value split in to more than two values can't be returned 9285 // directly. Vectors are returned via the available vector registers. 9286 if (!LocVT.isVector() && IsRet && ValNo > 1) 9287 return true; 9288 9289 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9290 // variadic argument, or if no F16/F32 argument registers are available. 9291 bool UseGPRForF16_F32 = true; 9292 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9293 // variadic argument, or if no F64 argument registers are available. 9294 bool UseGPRForF64 = true; 9295 9296 switch (ABI) { 9297 default: 9298 llvm_unreachable("Unexpected ABI"); 9299 case RISCVABI::ABI_ILP32: 9300 case RISCVABI::ABI_LP64: 9301 break; 9302 case RISCVABI::ABI_ILP32F: 9303 case RISCVABI::ABI_LP64F: 9304 UseGPRForF16_F32 = !IsFixed; 9305 break; 9306 case RISCVABI::ABI_ILP32D: 9307 case RISCVABI::ABI_LP64D: 9308 UseGPRForF16_F32 = !IsFixed; 9309 UseGPRForF64 = !IsFixed; 9310 break; 9311 } 9312 9313 // FPR16, FPR32, and FPR64 alias each other. 9314 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9315 UseGPRForF16_F32 = true; 9316 UseGPRForF64 = true; 9317 } 9318 9319 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9320 // similar local variables rather than directly checking against the target 9321 // ABI. 9322 9323 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9324 LocVT = XLenVT; 9325 LocInfo = CCValAssign::BCvt; 9326 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9327 LocVT = MVT::i64; 9328 LocInfo = CCValAssign::BCvt; 9329 } 9330 9331 // If this is a variadic argument, the RISC-V calling convention requires 9332 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9333 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9334 // be used regardless of whether the original argument was split during 9335 // legalisation or not. The argument will not be passed by registers if the 9336 // original type is larger than 2*XLEN, so the register alignment rule does 9337 // not apply. 9338 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9339 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9340 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9341 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9342 // Skip 'odd' register if necessary. 9343 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9344 State.AllocateReg(ArgGPRs); 9345 } 9346 9347 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9348 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9349 State.getPendingArgFlags(); 9350 9351 assert(PendingLocs.size() == PendingArgFlags.size() && 9352 "PendingLocs and PendingArgFlags out of sync"); 9353 9354 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9355 // registers are exhausted. 9356 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9357 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9358 "Can't lower f64 if it is split"); 9359 // Depending on available argument GPRS, f64 may be passed in a pair of 9360 // GPRs, split between a GPR and the stack, or passed completely on the 9361 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9362 // cases. 9363 Register Reg = State.AllocateReg(ArgGPRs); 9364 LocVT = MVT::i32; 9365 if (!Reg) { 9366 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9367 State.addLoc( 9368 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9369 return false; 9370 } 9371 if (!State.AllocateReg(ArgGPRs)) 9372 State.AllocateStack(4, Align(4)); 9373 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9374 return false; 9375 } 9376 9377 // Fixed-length vectors are located in the corresponding scalable-vector 9378 // container types. 9379 if (ValVT.isFixedLengthVector()) 9380 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9381 9382 // Split arguments might be passed indirectly, so keep track of the pending 9383 // values. Split vectors are passed via a mix of registers and indirectly, so 9384 // treat them as we would any other argument. 9385 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9386 LocVT = XLenVT; 9387 LocInfo = CCValAssign::Indirect; 9388 PendingLocs.push_back( 9389 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9390 PendingArgFlags.push_back(ArgFlags); 9391 if (!ArgFlags.isSplitEnd()) { 9392 return false; 9393 } 9394 } 9395 9396 // If the split argument only had two elements, it should be passed directly 9397 // in registers or on the stack. 9398 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9399 PendingLocs.size() <= 2) { 9400 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9401 // Apply the normal calling convention rules to the first half of the 9402 // split argument. 9403 CCValAssign VA = PendingLocs[0]; 9404 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9405 PendingLocs.clear(); 9406 PendingArgFlags.clear(); 9407 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9408 ArgFlags); 9409 } 9410 9411 // Allocate to a register if possible, or else a stack slot. 9412 Register Reg; 9413 unsigned StoreSizeBytes = XLen / 8; 9414 Align StackAlign = Align(XLen / 8); 9415 9416 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9417 Reg = State.AllocateReg(ArgFPR16s); 9418 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9419 Reg = State.AllocateReg(ArgFPR32s); 9420 else if (ValVT == MVT::f64 && !UseGPRForF64) 9421 Reg = State.AllocateReg(ArgFPR64s); 9422 else if (ValVT.isVector()) { 9423 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9424 if (!Reg) { 9425 // For return values, the vector must be passed fully via registers or 9426 // via the stack. 9427 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9428 // but we're using all of them. 9429 if (IsRet) 9430 return true; 9431 // Try using a GPR to pass the address 9432 if ((Reg = State.AllocateReg(ArgGPRs))) { 9433 LocVT = XLenVT; 9434 LocInfo = CCValAssign::Indirect; 9435 } else if (ValVT.isScalableVector()) { 9436 LocVT = XLenVT; 9437 LocInfo = CCValAssign::Indirect; 9438 } else { 9439 // Pass fixed-length vectors on the stack. 9440 LocVT = ValVT; 9441 StoreSizeBytes = ValVT.getStoreSize(); 9442 // Align vectors to their element sizes, being careful for vXi1 9443 // vectors. 9444 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9445 } 9446 } 9447 } else { 9448 Reg = State.AllocateReg(ArgGPRs); 9449 } 9450 9451 unsigned StackOffset = 9452 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9453 9454 // If we reach this point and PendingLocs is non-empty, we must be at the 9455 // end of a split argument that must be passed indirectly. 9456 if (!PendingLocs.empty()) { 9457 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9458 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9459 9460 for (auto &It : PendingLocs) { 9461 if (Reg) 9462 It.convertToReg(Reg); 9463 else 9464 It.convertToMem(StackOffset); 9465 State.addLoc(It); 9466 } 9467 PendingLocs.clear(); 9468 PendingArgFlags.clear(); 9469 return false; 9470 } 9471 9472 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9473 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9474 "Expected an XLenVT or vector types at this stage"); 9475 9476 if (Reg) { 9477 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9478 return false; 9479 } 9480 9481 // When a floating-point value is passed on the stack, no bit-conversion is 9482 // needed. 9483 if (ValVT.isFloatingPoint()) { 9484 LocVT = ValVT; 9485 LocInfo = CCValAssign::Full; 9486 } 9487 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9488 return false; 9489 } 9490 9491 template <typename ArgTy> 9492 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9493 for (const auto &ArgIdx : enumerate(Args)) { 9494 MVT ArgVT = ArgIdx.value().VT; 9495 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9496 return ArgIdx.index(); 9497 } 9498 return None; 9499 } 9500 9501 void RISCVTargetLowering::analyzeInputArgs( 9502 MachineFunction &MF, CCState &CCInfo, 9503 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9504 RISCVCCAssignFn Fn) const { 9505 unsigned NumArgs = Ins.size(); 9506 FunctionType *FType = MF.getFunction().getFunctionType(); 9507 9508 Optional<unsigned> FirstMaskArgument; 9509 if (Subtarget.hasVInstructions()) 9510 FirstMaskArgument = preAssignMask(Ins); 9511 9512 for (unsigned i = 0; i != NumArgs; ++i) { 9513 MVT ArgVT = Ins[i].VT; 9514 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9515 9516 Type *ArgTy = nullptr; 9517 if (IsRet) 9518 ArgTy = FType->getReturnType(); 9519 else if (Ins[i].isOrigArg()) 9520 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9521 9522 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9523 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9524 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9525 FirstMaskArgument)) { 9526 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9527 << EVT(ArgVT).getEVTString() << '\n'); 9528 llvm_unreachable(nullptr); 9529 } 9530 } 9531 } 9532 9533 void RISCVTargetLowering::analyzeOutputArgs( 9534 MachineFunction &MF, CCState &CCInfo, 9535 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9536 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9537 unsigned NumArgs = Outs.size(); 9538 9539 Optional<unsigned> FirstMaskArgument; 9540 if (Subtarget.hasVInstructions()) 9541 FirstMaskArgument = preAssignMask(Outs); 9542 9543 for (unsigned i = 0; i != NumArgs; i++) { 9544 MVT ArgVT = Outs[i].VT; 9545 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9546 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9547 9548 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9549 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9550 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9551 FirstMaskArgument)) { 9552 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9553 << EVT(ArgVT).getEVTString() << "\n"); 9554 llvm_unreachable(nullptr); 9555 } 9556 } 9557 } 9558 9559 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9560 // values. 9561 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9562 const CCValAssign &VA, const SDLoc &DL, 9563 const RISCVSubtarget &Subtarget) { 9564 switch (VA.getLocInfo()) { 9565 default: 9566 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9567 case CCValAssign::Full: 9568 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9569 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9570 break; 9571 case CCValAssign::BCvt: 9572 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9573 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9574 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9575 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9576 else 9577 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9578 break; 9579 } 9580 return Val; 9581 } 9582 9583 // The caller is responsible for loading the full value if the argument is 9584 // passed with CCValAssign::Indirect. 9585 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9586 const CCValAssign &VA, const SDLoc &DL, 9587 const RISCVTargetLowering &TLI) { 9588 MachineFunction &MF = DAG.getMachineFunction(); 9589 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9590 EVT LocVT = VA.getLocVT(); 9591 SDValue Val; 9592 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9593 Register VReg = RegInfo.createVirtualRegister(RC); 9594 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9595 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9596 9597 if (VA.getLocInfo() == CCValAssign::Indirect) 9598 return Val; 9599 9600 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9601 } 9602 9603 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9604 const CCValAssign &VA, const SDLoc &DL, 9605 const RISCVSubtarget &Subtarget) { 9606 EVT LocVT = VA.getLocVT(); 9607 9608 switch (VA.getLocInfo()) { 9609 default: 9610 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9611 case CCValAssign::Full: 9612 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9613 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9614 break; 9615 case CCValAssign::BCvt: 9616 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9617 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9618 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9619 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9620 else 9621 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9622 break; 9623 } 9624 return Val; 9625 } 9626 9627 // The caller is responsible for loading the full value if the argument is 9628 // passed with CCValAssign::Indirect. 9629 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9630 const CCValAssign &VA, const SDLoc &DL) { 9631 MachineFunction &MF = DAG.getMachineFunction(); 9632 MachineFrameInfo &MFI = MF.getFrameInfo(); 9633 EVT LocVT = VA.getLocVT(); 9634 EVT ValVT = VA.getValVT(); 9635 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9636 if (ValVT.isScalableVector()) { 9637 // When the value is a scalable vector, we save the pointer which points to 9638 // the scalable vector value in the stack. The ValVT will be the pointer 9639 // type, instead of the scalable vector type. 9640 ValVT = LocVT; 9641 } 9642 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9643 /*IsImmutable=*/true); 9644 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9645 SDValue Val; 9646 9647 ISD::LoadExtType ExtType; 9648 switch (VA.getLocInfo()) { 9649 default: 9650 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9651 case CCValAssign::Full: 9652 case CCValAssign::Indirect: 9653 case CCValAssign::BCvt: 9654 ExtType = ISD::NON_EXTLOAD; 9655 break; 9656 } 9657 Val = DAG.getExtLoad( 9658 ExtType, DL, LocVT, Chain, FIN, 9659 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9660 return Val; 9661 } 9662 9663 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9664 const CCValAssign &VA, const SDLoc &DL) { 9665 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9666 "Unexpected VA"); 9667 MachineFunction &MF = DAG.getMachineFunction(); 9668 MachineFrameInfo &MFI = MF.getFrameInfo(); 9669 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9670 9671 if (VA.isMemLoc()) { 9672 // f64 is passed on the stack. 9673 int FI = 9674 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9675 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9676 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9677 MachinePointerInfo::getFixedStack(MF, FI)); 9678 } 9679 9680 assert(VA.isRegLoc() && "Expected register VA assignment"); 9681 9682 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9683 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 9684 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 9685 SDValue Hi; 9686 if (VA.getLocReg() == RISCV::X17) { 9687 // Second half of f64 is passed on the stack. 9688 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 9689 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9690 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 9691 MachinePointerInfo::getFixedStack(MF, FI)); 9692 } else { 9693 // Second half of f64 is passed in another GPR. 9694 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9695 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 9696 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 9697 } 9698 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 9699 } 9700 9701 // FastCC has less than 1% performance improvement for some particular 9702 // benchmark. But theoretically, it may has benenfit for some cases. 9703 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 9704 unsigned ValNo, MVT ValVT, MVT LocVT, 9705 CCValAssign::LocInfo LocInfo, 9706 ISD::ArgFlagsTy ArgFlags, CCState &State, 9707 bool IsFixed, bool IsRet, Type *OrigTy, 9708 const RISCVTargetLowering &TLI, 9709 Optional<unsigned> FirstMaskArgument) { 9710 9711 // X5 and X6 might be used for save-restore libcall. 9712 static const MCPhysReg GPRList[] = { 9713 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 9714 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 9715 RISCV::X29, RISCV::X30, RISCV::X31}; 9716 9717 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9718 if (unsigned Reg = State.AllocateReg(GPRList)) { 9719 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9720 return false; 9721 } 9722 } 9723 9724 if (LocVT == MVT::f16) { 9725 static const MCPhysReg FPR16List[] = { 9726 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 9727 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 9728 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 9729 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 9730 if (unsigned Reg = State.AllocateReg(FPR16List)) { 9731 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9732 return false; 9733 } 9734 } 9735 9736 if (LocVT == MVT::f32) { 9737 static const MCPhysReg FPR32List[] = { 9738 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 9739 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 9740 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 9741 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 9742 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9743 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9744 return false; 9745 } 9746 } 9747 9748 if (LocVT == MVT::f64) { 9749 static const MCPhysReg FPR64List[] = { 9750 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 9751 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 9752 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 9753 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 9754 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9755 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9756 return false; 9757 } 9758 } 9759 9760 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 9761 unsigned Offset4 = State.AllocateStack(4, Align(4)); 9762 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 9763 return false; 9764 } 9765 9766 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 9767 unsigned Offset5 = State.AllocateStack(8, Align(8)); 9768 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 9769 return false; 9770 } 9771 9772 if (LocVT.isVector()) { 9773 if (unsigned Reg = 9774 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 9775 // Fixed-length vectors are located in the corresponding scalable-vector 9776 // container types. 9777 if (ValVT.isFixedLengthVector()) 9778 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9779 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9780 } else { 9781 // Try and pass the address via a "fast" GPR. 9782 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 9783 LocInfo = CCValAssign::Indirect; 9784 LocVT = TLI.getSubtarget().getXLenVT(); 9785 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 9786 } else if (ValVT.isFixedLengthVector()) { 9787 auto StackAlign = 9788 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9789 unsigned StackOffset = 9790 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 9791 State.addLoc( 9792 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9793 } else { 9794 // Can't pass scalable vectors on the stack. 9795 return true; 9796 } 9797 } 9798 9799 return false; 9800 } 9801 9802 return true; // CC didn't match. 9803 } 9804 9805 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9806 CCValAssign::LocInfo LocInfo, 9807 ISD::ArgFlagsTy ArgFlags, CCState &State) { 9808 9809 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9810 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 9811 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 9812 static const MCPhysReg GPRList[] = { 9813 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 9814 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 9815 if (unsigned Reg = State.AllocateReg(GPRList)) { 9816 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9817 return false; 9818 } 9819 } 9820 9821 if (LocVT == MVT::f32) { 9822 // Pass in STG registers: F1, ..., F6 9823 // fs0 ... fs5 9824 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 9825 RISCV::F18_F, RISCV::F19_F, 9826 RISCV::F20_F, RISCV::F21_F}; 9827 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9828 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9829 return false; 9830 } 9831 } 9832 9833 if (LocVT == MVT::f64) { 9834 // Pass in STG registers: D1, ..., D6 9835 // fs6 ... fs11 9836 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 9837 RISCV::F24_D, RISCV::F25_D, 9838 RISCV::F26_D, RISCV::F27_D}; 9839 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9840 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9841 return false; 9842 } 9843 } 9844 9845 report_fatal_error("No registers left in GHC calling convention"); 9846 return true; 9847 } 9848 9849 // Transform physical registers into virtual registers. 9850 SDValue RISCVTargetLowering::LowerFormalArguments( 9851 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 9852 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 9853 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 9854 9855 MachineFunction &MF = DAG.getMachineFunction(); 9856 9857 switch (CallConv) { 9858 default: 9859 report_fatal_error("Unsupported calling convention"); 9860 case CallingConv::C: 9861 case CallingConv::Fast: 9862 break; 9863 case CallingConv::GHC: 9864 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 9865 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 9866 report_fatal_error( 9867 "GHC calling convention requires the F and D instruction set extensions"); 9868 } 9869 9870 const Function &Func = MF.getFunction(); 9871 if (Func.hasFnAttribute("interrupt")) { 9872 if (!Func.arg_empty()) 9873 report_fatal_error( 9874 "Functions with the interrupt attribute cannot have arguments!"); 9875 9876 StringRef Kind = 9877 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9878 9879 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 9880 report_fatal_error( 9881 "Function interrupt attribute argument not supported!"); 9882 } 9883 9884 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9885 MVT XLenVT = Subtarget.getXLenVT(); 9886 unsigned XLenInBytes = Subtarget.getXLen() / 8; 9887 // Used with vargs to acumulate store chains. 9888 std::vector<SDValue> OutChains; 9889 9890 // Assign locations to all of the incoming arguments. 9891 SmallVector<CCValAssign, 16> ArgLocs; 9892 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9893 9894 if (CallConv == CallingConv::GHC) 9895 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 9896 else 9897 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 9898 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9899 : CC_RISCV); 9900 9901 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 9902 CCValAssign &VA = ArgLocs[i]; 9903 SDValue ArgValue; 9904 // Passing f64 on RV32D with a soft float ABI must be handled as a special 9905 // case. 9906 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 9907 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 9908 else if (VA.isRegLoc()) 9909 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 9910 else 9911 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 9912 9913 if (VA.getLocInfo() == CCValAssign::Indirect) { 9914 // If the original argument was split and passed by reference (e.g. i128 9915 // on RV32), we need to load all parts of it here (using the same 9916 // address). Vectors may be partly split to registers and partly to the 9917 // stack, in which case the base address is partly offset and subsequent 9918 // stores are relative to that. 9919 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 9920 MachinePointerInfo())); 9921 unsigned ArgIndex = Ins[i].OrigArgIndex; 9922 unsigned ArgPartOffset = Ins[i].PartOffset; 9923 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9924 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 9925 CCValAssign &PartVA = ArgLocs[i + 1]; 9926 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 9927 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9928 if (PartVA.getValVT().isScalableVector()) 9929 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9930 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 9931 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 9932 MachinePointerInfo())); 9933 ++i; 9934 } 9935 continue; 9936 } 9937 InVals.push_back(ArgValue); 9938 } 9939 9940 if (IsVarArg) { 9941 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 9942 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 9943 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 9944 MachineFrameInfo &MFI = MF.getFrameInfo(); 9945 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9946 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 9947 9948 // Offset of the first variable argument from stack pointer, and size of 9949 // the vararg save area. For now, the varargs save area is either zero or 9950 // large enough to hold a0-a7. 9951 int VaArgOffset, VarArgsSaveSize; 9952 9953 // If all registers are allocated, then all varargs must be passed on the 9954 // stack and we don't need to save any argregs. 9955 if (ArgRegs.size() == Idx) { 9956 VaArgOffset = CCInfo.getNextStackOffset(); 9957 VarArgsSaveSize = 0; 9958 } else { 9959 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 9960 VaArgOffset = -VarArgsSaveSize; 9961 } 9962 9963 // Record the frame index of the first variable argument 9964 // which is a value necessary to VASTART. 9965 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9966 RVFI->setVarArgsFrameIndex(FI); 9967 9968 // If saving an odd number of registers then create an extra stack slot to 9969 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 9970 // offsets to even-numbered registered remain 2*XLEN-aligned. 9971 if (Idx % 2) { 9972 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 9973 VarArgsSaveSize += XLenInBytes; 9974 } 9975 9976 // Copy the integer registers that may have been used for passing varargs 9977 // to the vararg save area. 9978 for (unsigned I = Idx; I < ArgRegs.size(); 9979 ++I, VaArgOffset += XLenInBytes) { 9980 const Register Reg = RegInfo.createVirtualRegister(RC); 9981 RegInfo.addLiveIn(ArgRegs[I], Reg); 9982 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 9983 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9984 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9985 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 9986 MachinePointerInfo::getFixedStack(MF, FI)); 9987 cast<StoreSDNode>(Store.getNode()) 9988 ->getMemOperand() 9989 ->setValue((Value *)nullptr); 9990 OutChains.push_back(Store); 9991 } 9992 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 9993 } 9994 9995 // All stores are grouped in one node to allow the matching between 9996 // the size of Ins and InVals. This only happens for vararg functions. 9997 if (!OutChains.empty()) { 9998 OutChains.push_back(Chain); 9999 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10000 } 10001 10002 return Chain; 10003 } 10004 10005 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10006 /// for tail call optimization. 10007 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10008 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10009 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10010 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10011 10012 auto &Callee = CLI.Callee; 10013 auto CalleeCC = CLI.CallConv; 10014 auto &Outs = CLI.Outs; 10015 auto &Caller = MF.getFunction(); 10016 auto CallerCC = Caller.getCallingConv(); 10017 10018 // Exception-handling functions need a special set of instructions to 10019 // indicate a return to the hardware. Tail-calling another function would 10020 // probably break this. 10021 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10022 // should be expanded as new function attributes are introduced. 10023 if (Caller.hasFnAttribute("interrupt")) 10024 return false; 10025 10026 // Do not tail call opt if the stack is used to pass parameters. 10027 if (CCInfo.getNextStackOffset() != 0) 10028 return false; 10029 10030 // Do not tail call opt if any parameters need to be passed indirectly. 10031 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10032 // passed indirectly. So the address of the value will be passed in a 10033 // register, or if not available, then the address is put on the stack. In 10034 // order to pass indirectly, space on the stack often needs to be allocated 10035 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10036 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10037 // are passed CCValAssign::Indirect. 10038 for (auto &VA : ArgLocs) 10039 if (VA.getLocInfo() == CCValAssign::Indirect) 10040 return false; 10041 10042 // Do not tail call opt if either caller or callee uses struct return 10043 // semantics. 10044 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10045 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10046 if (IsCallerStructRet || IsCalleeStructRet) 10047 return false; 10048 10049 // Externally-defined functions with weak linkage should not be 10050 // tail-called. The behaviour of branch instructions in this situation (as 10051 // used for tail calls) is implementation-defined, so we cannot rely on the 10052 // linker replacing the tail call with a return. 10053 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10054 const GlobalValue *GV = G->getGlobal(); 10055 if (GV->hasExternalWeakLinkage()) 10056 return false; 10057 } 10058 10059 // The callee has to preserve all registers the caller needs to preserve. 10060 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10061 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10062 if (CalleeCC != CallerCC) { 10063 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10064 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10065 return false; 10066 } 10067 10068 // Byval parameters hand the function a pointer directly into the stack area 10069 // we want to reuse during a tail call. Working around this *is* possible 10070 // but less efficient and uglier in LowerCall. 10071 for (auto &Arg : Outs) 10072 if (Arg.Flags.isByVal()) 10073 return false; 10074 10075 return true; 10076 } 10077 10078 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10079 return DAG.getDataLayout().getPrefTypeAlign( 10080 VT.getTypeForEVT(*DAG.getContext())); 10081 } 10082 10083 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10084 // and output parameter nodes. 10085 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10086 SmallVectorImpl<SDValue> &InVals) const { 10087 SelectionDAG &DAG = CLI.DAG; 10088 SDLoc &DL = CLI.DL; 10089 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10090 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10091 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10092 SDValue Chain = CLI.Chain; 10093 SDValue Callee = CLI.Callee; 10094 bool &IsTailCall = CLI.IsTailCall; 10095 CallingConv::ID CallConv = CLI.CallConv; 10096 bool IsVarArg = CLI.IsVarArg; 10097 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10098 MVT XLenVT = Subtarget.getXLenVT(); 10099 10100 MachineFunction &MF = DAG.getMachineFunction(); 10101 10102 // Analyze the operands of the call, assigning locations to each operand. 10103 SmallVector<CCValAssign, 16> ArgLocs; 10104 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10105 10106 if (CallConv == CallingConv::GHC) 10107 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10108 else 10109 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10110 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10111 : CC_RISCV); 10112 10113 // Check if it's really possible to do a tail call. 10114 if (IsTailCall) 10115 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10116 10117 if (IsTailCall) 10118 ++NumTailCalls; 10119 else if (CLI.CB && CLI.CB->isMustTailCall()) 10120 report_fatal_error("failed to perform tail call elimination on a call " 10121 "site marked musttail"); 10122 10123 // Get a count of how many bytes are to be pushed on the stack. 10124 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10125 10126 // Create local copies for byval args 10127 SmallVector<SDValue, 8> ByValArgs; 10128 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10129 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10130 if (!Flags.isByVal()) 10131 continue; 10132 10133 SDValue Arg = OutVals[i]; 10134 unsigned Size = Flags.getByValSize(); 10135 Align Alignment = Flags.getNonZeroByValAlign(); 10136 10137 int FI = 10138 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10139 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10140 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10141 10142 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10143 /*IsVolatile=*/false, 10144 /*AlwaysInline=*/false, IsTailCall, 10145 MachinePointerInfo(), MachinePointerInfo()); 10146 ByValArgs.push_back(FIPtr); 10147 } 10148 10149 if (!IsTailCall) 10150 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10151 10152 // Copy argument values to their designated locations. 10153 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10154 SmallVector<SDValue, 8> MemOpChains; 10155 SDValue StackPtr; 10156 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10157 CCValAssign &VA = ArgLocs[i]; 10158 SDValue ArgValue = OutVals[i]; 10159 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10160 10161 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10162 bool IsF64OnRV32DSoftABI = 10163 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10164 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10165 SDValue SplitF64 = DAG.getNode( 10166 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10167 SDValue Lo = SplitF64.getValue(0); 10168 SDValue Hi = SplitF64.getValue(1); 10169 10170 Register RegLo = VA.getLocReg(); 10171 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10172 10173 if (RegLo == RISCV::X17) { 10174 // Second half of f64 is passed on the stack. 10175 // Work out the address of the stack slot. 10176 if (!StackPtr.getNode()) 10177 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10178 // Emit the store. 10179 MemOpChains.push_back( 10180 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10181 } else { 10182 // Second half of f64 is passed in another GPR. 10183 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10184 Register RegHigh = RegLo + 1; 10185 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10186 } 10187 continue; 10188 } 10189 10190 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10191 // as any other MemLoc. 10192 10193 // Promote the value if needed. 10194 // For now, only handle fully promoted and indirect arguments. 10195 if (VA.getLocInfo() == CCValAssign::Indirect) { 10196 // Store the argument in a stack slot and pass its address. 10197 Align StackAlign = 10198 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10199 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10200 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10201 // If the original argument was split (e.g. i128), we need 10202 // to store the required parts of it here (and pass just one address). 10203 // Vectors may be partly split to registers and partly to the stack, in 10204 // which case the base address is partly offset and subsequent stores are 10205 // relative to that. 10206 unsigned ArgIndex = Outs[i].OrigArgIndex; 10207 unsigned ArgPartOffset = Outs[i].PartOffset; 10208 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10209 // Calculate the total size to store. We don't have access to what we're 10210 // actually storing other than performing the loop and collecting the 10211 // info. 10212 SmallVector<std::pair<SDValue, SDValue>> Parts; 10213 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10214 SDValue PartValue = OutVals[i + 1]; 10215 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10216 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10217 EVT PartVT = PartValue.getValueType(); 10218 if (PartVT.isScalableVector()) 10219 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10220 StoredSize += PartVT.getStoreSize(); 10221 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10222 Parts.push_back(std::make_pair(PartValue, Offset)); 10223 ++i; 10224 } 10225 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10226 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10227 MemOpChains.push_back( 10228 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10229 MachinePointerInfo::getFixedStack(MF, FI))); 10230 for (const auto &Part : Parts) { 10231 SDValue PartValue = Part.first; 10232 SDValue PartOffset = Part.second; 10233 SDValue Address = 10234 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10235 MemOpChains.push_back( 10236 DAG.getStore(Chain, DL, PartValue, Address, 10237 MachinePointerInfo::getFixedStack(MF, FI))); 10238 } 10239 ArgValue = SpillSlot; 10240 } else { 10241 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10242 } 10243 10244 // Use local copy if it is a byval arg. 10245 if (Flags.isByVal()) 10246 ArgValue = ByValArgs[j++]; 10247 10248 if (VA.isRegLoc()) { 10249 // Queue up the argument copies and emit them at the end. 10250 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10251 } else { 10252 assert(VA.isMemLoc() && "Argument not register or memory"); 10253 assert(!IsTailCall && "Tail call not allowed if stack is used " 10254 "for passing parameters"); 10255 10256 // Work out the address of the stack slot. 10257 if (!StackPtr.getNode()) 10258 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10259 SDValue Address = 10260 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10261 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10262 10263 // Emit the store. 10264 MemOpChains.push_back( 10265 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10266 } 10267 } 10268 10269 // Join the stores, which are independent of one another. 10270 if (!MemOpChains.empty()) 10271 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10272 10273 SDValue Glue; 10274 10275 // Build a sequence of copy-to-reg nodes, chained and glued together. 10276 for (auto &Reg : RegsToPass) { 10277 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10278 Glue = Chain.getValue(1); 10279 } 10280 10281 // Validate that none of the argument registers have been marked as 10282 // reserved, if so report an error. Do the same for the return address if this 10283 // is not a tailcall. 10284 validateCCReservedRegs(RegsToPass, MF); 10285 if (!IsTailCall && 10286 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10287 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10288 MF.getFunction(), 10289 "Return address register required, but has been reserved."}); 10290 10291 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10292 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10293 // split it and then direct call can be matched by PseudoCALL. 10294 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10295 const GlobalValue *GV = S->getGlobal(); 10296 10297 unsigned OpFlags = RISCVII::MO_CALL; 10298 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10299 OpFlags = RISCVII::MO_PLT; 10300 10301 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10302 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10303 unsigned OpFlags = RISCVII::MO_CALL; 10304 10305 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10306 nullptr)) 10307 OpFlags = RISCVII::MO_PLT; 10308 10309 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10310 } 10311 10312 // The first call operand is the chain and the second is the target address. 10313 SmallVector<SDValue, 8> Ops; 10314 Ops.push_back(Chain); 10315 Ops.push_back(Callee); 10316 10317 // Add argument registers to the end of the list so that they are 10318 // known live into the call. 10319 for (auto &Reg : RegsToPass) 10320 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10321 10322 if (!IsTailCall) { 10323 // Add a register mask operand representing the call-preserved registers. 10324 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10325 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10326 assert(Mask && "Missing call preserved mask for calling convention"); 10327 Ops.push_back(DAG.getRegisterMask(Mask)); 10328 } 10329 10330 // Glue the call to the argument copies, if any. 10331 if (Glue.getNode()) 10332 Ops.push_back(Glue); 10333 10334 // Emit the call. 10335 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10336 10337 if (IsTailCall) { 10338 MF.getFrameInfo().setHasTailCall(); 10339 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10340 } 10341 10342 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10343 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10344 Glue = Chain.getValue(1); 10345 10346 // Mark the end of the call, which is glued to the call itself. 10347 Chain = DAG.getCALLSEQ_END(Chain, 10348 DAG.getConstant(NumBytes, DL, PtrVT, true), 10349 DAG.getConstant(0, DL, PtrVT, true), 10350 Glue, DL); 10351 Glue = Chain.getValue(1); 10352 10353 // Assign locations to each value returned by this call. 10354 SmallVector<CCValAssign, 16> RVLocs; 10355 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10356 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10357 10358 // Copy all of the result registers out of their specified physreg. 10359 for (auto &VA : RVLocs) { 10360 // Copy the value out 10361 SDValue RetValue = 10362 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10363 // Glue the RetValue to the end of the call sequence 10364 Chain = RetValue.getValue(1); 10365 Glue = RetValue.getValue(2); 10366 10367 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10368 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10369 SDValue RetValue2 = 10370 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10371 Chain = RetValue2.getValue(1); 10372 Glue = RetValue2.getValue(2); 10373 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10374 RetValue2); 10375 } 10376 10377 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10378 10379 InVals.push_back(RetValue); 10380 } 10381 10382 return Chain; 10383 } 10384 10385 bool RISCVTargetLowering::CanLowerReturn( 10386 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10387 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10388 SmallVector<CCValAssign, 16> RVLocs; 10389 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10390 10391 Optional<unsigned> FirstMaskArgument; 10392 if (Subtarget.hasVInstructions()) 10393 FirstMaskArgument = preAssignMask(Outs); 10394 10395 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10396 MVT VT = Outs[i].VT; 10397 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10398 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10399 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10400 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10401 *this, FirstMaskArgument)) 10402 return false; 10403 } 10404 return true; 10405 } 10406 10407 SDValue 10408 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10409 bool IsVarArg, 10410 const SmallVectorImpl<ISD::OutputArg> &Outs, 10411 const SmallVectorImpl<SDValue> &OutVals, 10412 const SDLoc &DL, SelectionDAG &DAG) const { 10413 const MachineFunction &MF = DAG.getMachineFunction(); 10414 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10415 10416 // Stores the assignment of the return value to a location. 10417 SmallVector<CCValAssign, 16> RVLocs; 10418 10419 // Info about the registers and stack slot. 10420 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10421 *DAG.getContext()); 10422 10423 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10424 nullptr, CC_RISCV); 10425 10426 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10427 report_fatal_error("GHC functions return void only"); 10428 10429 SDValue Glue; 10430 SmallVector<SDValue, 4> RetOps(1, Chain); 10431 10432 // Copy the result values into the output registers. 10433 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10434 SDValue Val = OutVals[i]; 10435 CCValAssign &VA = RVLocs[i]; 10436 assert(VA.isRegLoc() && "Can only return in registers!"); 10437 10438 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10439 // Handle returning f64 on RV32D with a soft float ABI. 10440 assert(VA.isRegLoc() && "Expected return via registers"); 10441 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10442 DAG.getVTList(MVT::i32, MVT::i32), Val); 10443 SDValue Lo = SplitF64.getValue(0); 10444 SDValue Hi = SplitF64.getValue(1); 10445 Register RegLo = VA.getLocReg(); 10446 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10447 Register RegHi = RegLo + 1; 10448 10449 if (STI.isRegisterReservedByUser(RegLo) || 10450 STI.isRegisterReservedByUser(RegHi)) 10451 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10452 MF.getFunction(), 10453 "Return value register required, but has been reserved."}); 10454 10455 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10456 Glue = Chain.getValue(1); 10457 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10458 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10459 Glue = Chain.getValue(1); 10460 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10461 } else { 10462 // Handle a 'normal' return. 10463 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10464 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10465 10466 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10467 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10468 MF.getFunction(), 10469 "Return value register required, but has been reserved."}); 10470 10471 // Guarantee that all emitted copies are stuck together. 10472 Glue = Chain.getValue(1); 10473 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10474 } 10475 } 10476 10477 RetOps[0] = Chain; // Update chain. 10478 10479 // Add the glue node if we have it. 10480 if (Glue.getNode()) { 10481 RetOps.push_back(Glue); 10482 } 10483 10484 unsigned RetOpc = RISCVISD::RET_FLAG; 10485 // Interrupt service routines use different return instructions. 10486 const Function &Func = DAG.getMachineFunction().getFunction(); 10487 if (Func.hasFnAttribute("interrupt")) { 10488 if (!Func.getReturnType()->isVoidTy()) 10489 report_fatal_error( 10490 "Functions with the interrupt attribute must have void return type!"); 10491 10492 MachineFunction &MF = DAG.getMachineFunction(); 10493 StringRef Kind = 10494 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10495 10496 if (Kind == "user") 10497 RetOpc = RISCVISD::URET_FLAG; 10498 else if (Kind == "supervisor") 10499 RetOpc = RISCVISD::SRET_FLAG; 10500 else 10501 RetOpc = RISCVISD::MRET_FLAG; 10502 } 10503 10504 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10505 } 10506 10507 void RISCVTargetLowering::validateCCReservedRegs( 10508 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10509 MachineFunction &MF) const { 10510 const Function &F = MF.getFunction(); 10511 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10512 10513 if (llvm::any_of(Regs, [&STI](auto Reg) { 10514 return STI.isRegisterReservedByUser(Reg.first); 10515 })) 10516 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10517 F, "Argument register required, but has been reserved."}); 10518 } 10519 10520 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10521 return CI->isTailCall(); 10522 } 10523 10524 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10525 #define NODE_NAME_CASE(NODE) \ 10526 case RISCVISD::NODE: \ 10527 return "RISCVISD::" #NODE; 10528 // clang-format off 10529 switch ((RISCVISD::NodeType)Opcode) { 10530 case RISCVISD::FIRST_NUMBER: 10531 break; 10532 NODE_NAME_CASE(RET_FLAG) 10533 NODE_NAME_CASE(URET_FLAG) 10534 NODE_NAME_CASE(SRET_FLAG) 10535 NODE_NAME_CASE(MRET_FLAG) 10536 NODE_NAME_CASE(CALL) 10537 NODE_NAME_CASE(SELECT_CC) 10538 NODE_NAME_CASE(BR_CC) 10539 NODE_NAME_CASE(BuildPairF64) 10540 NODE_NAME_CASE(SplitF64) 10541 NODE_NAME_CASE(TAIL) 10542 NODE_NAME_CASE(MULHSU) 10543 NODE_NAME_CASE(SLLW) 10544 NODE_NAME_CASE(SRAW) 10545 NODE_NAME_CASE(SRLW) 10546 NODE_NAME_CASE(DIVW) 10547 NODE_NAME_CASE(DIVUW) 10548 NODE_NAME_CASE(REMUW) 10549 NODE_NAME_CASE(ROLW) 10550 NODE_NAME_CASE(RORW) 10551 NODE_NAME_CASE(CLZW) 10552 NODE_NAME_CASE(CTZW) 10553 NODE_NAME_CASE(FSLW) 10554 NODE_NAME_CASE(FSRW) 10555 NODE_NAME_CASE(FSL) 10556 NODE_NAME_CASE(FSR) 10557 NODE_NAME_CASE(FMV_H_X) 10558 NODE_NAME_CASE(FMV_X_ANYEXTH) 10559 NODE_NAME_CASE(FMV_X_SIGNEXTH) 10560 NODE_NAME_CASE(FMV_W_X_RV64) 10561 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10562 NODE_NAME_CASE(FCVT_X) 10563 NODE_NAME_CASE(FCVT_XU) 10564 NODE_NAME_CASE(FCVT_W_RV64) 10565 NODE_NAME_CASE(FCVT_WU_RV64) 10566 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10567 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10568 NODE_NAME_CASE(READ_CYCLE_WIDE) 10569 NODE_NAME_CASE(GREV) 10570 NODE_NAME_CASE(GREVW) 10571 NODE_NAME_CASE(GORC) 10572 NODE_NAME_CASE(GORCW) 10573 NODE_NAME_CASE(SHFL) 10574 NODE_NAME_CASE(SHFLW) 10575 NODE_NAME_CASE(UNSHFL) 10576 NODE_NAME_CASE(UNSHFLW) 10577 NODE_NAME_CASE(BFP) 10578 NODE_NAME_CASE(BFPW) 10579 NODE_NAME_CASE(BCOMPRESS) 10580 NODE_NAME_CASE(BCOMPRESSW) 10581 NODE_NAME_CASE(BDECOMPRESS) 10582 NODE_NAME_CASE(BDECOMPRESSW) 10583 NODE_NAME_CASE(VMV_V_X_VL) 10584 NODE_NAME_CASE(VFMV_V_F_VL) 10585 NODE_NAME_CASE(VMV_X_S) 10586 NODE_NAME_CASE(VMV_S_X_VL) 10587 NODE_NAME_CASE(VFMV_S_F_VL) 10588 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10589 NODE_NAME_CASE(READ_VLENB) 10590 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10591 NODE_NAME_CASE(VSLIDEUP_VL) 10592 NODE_NAME_CASE(VSLIDE1UP_VL) 10593 NODE_NAME_CASE(VSLIDEDOWN_VL) 10594 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10595 NODE_NAME_CASE(VID_VL) 10596 NODE_NAME_CASE(VFNCVT_ROD_VL) 10597 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10598 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10599 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10600 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10601 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10602 NODE_NAME_CASE(VECREDUCE_AND_VL) 10603 NODE_NAME_CASE(VECREDUCE_OR_VL) 10604 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10605 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10606 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10607 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10608 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10609 NODE_NAME_CASE(ADD_VL) 10610 NODE_NAME_CASE(AND_VL) 10611 NODE_NAME_CASE(MUL_VL) 10612 NODE_NAME_CASE(OR_VL) 10613 NODE_NAME_CASE(SDIV_VL) 10614 NODE_NAME_CASE(SHL_VL) 10615 NODE_NAME_CASE(SREM_VL) 10616 NODE_NAME_CASE(SRA_VL) 10617 NODE_NAME_CASE(SRL_VL) 10618 NODE_NAME_CASE(SUB_VL) 10619 NODE_NAME_CASE(UDIV_VL) 10620 NODE_NAME_CASE(UREM_VL) 10621 NODE_NAME_CASE(XOR_VL) 10622 NODE_NAME_CASE(SADDSAT_VL) 10623 NODE_NAME_CASE(UADDSAT_VL) 10624 NODE_NAME_CASE(SSUBSAT_VL) 10625 NODE_NAME_CASE(USUBSAT_VL) 10626 NODE_NAME_CASE(FADD_VL) 10627 NODE_NAME_CASE(FSUB_VL) 10628 NODE_NAME_CASE(FMUL_VL) 10629 NODE_NAME_CASE(FDIV_VL) 10630 NODE_NAME_CASE(FNEG_VL) 10631 NODE_NAME_CASE(FABS_VL) 10632 NODE_NAME_CASE(FSQRT_VL) 10633 NODE_NAME_CASE(FMA_VL) 10634 NODE_NAME_CASE(FCOPYSIGN_VL) 10635 NODE_NAME_CASE(SMIN_VL) 10636 NODE_NAME_CASE(SMAX_VL) 10637 NODE_NAME_CASE(UMIN_VL) 10638 NODE_NAME_CASE(UMAX_VL) 10639 NODE_NAME_CASE(FMINNUM_VL) 10640 NODE_NAME_CASE(FMAXNUM_VL) 10641 NODE_NAME_CASE(MULHS_VL) 10642 NODE_NAME_CASE(MULHU_VL) 10643 NODE_NAME_CASE(FP_TO_SINT_VL) 10644 NODE_NAME_CASE(FP_TO_UINT_VL) 10645 NODE_NAME_CASE(SINT_TO_FP_VL) 10646 NODE_NAME_CASE(UINT_TO_FP_VL) 10647 NODE_NAME_CASE(FP_EXTEND_VL) 10648 NODE_NAME_CASE(FP_ROUND_VL) 10649 NODE_NAME_CASE(VWMUL_VL) 10650 NODE_NAME_CASE(VWMULU_VL) 10651 NODE_NAME_CASE(VWMULSU_VL) 10652 NODE_NAME_CASE(VWADD_VL) 10653 NODE_NAME_CASE(VWADDU_VL) 10654 NODE_NAME_CASE(VWSUB_VL) 10655 NODE_NAME_CASE(VWSUBU_VL) 10656 NODE_NAME_CASE(VWADD_W_VL) 10657 NODE_NAME_CASE(VWADDU_W_VL) 10658 NODE_NAME_CASE(VWSUB_W_VL) 10659 NODE_NAME_CASE(VWSUBU_W_VL) 10660 NODE_NAME_CASE(SETCC_VL) 10661 NODE_NAME_CASE(VSELECT_VL) 10662 NODE_NAME_CASE(VP_MERGE_VL) 10663 NODE_NAME_CASE(VMAND_VL) 10664 NODE_NAME_CASE(VMOR_VL) 10665 NODE_NAME_CASE(VMXOR_VL) 10666 NODE_NAME_CASE(VMCLR_VL) 10667 NODE_NAME_CASE(VMSET_VL) 10668 NODE_NAME_CASE(VRGATHER_VX_VL) 10669 NODE_NAME_CASE(VRGATHER_VV_VL) 10670 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10671 NODE_NAME_CASE(VSEXT_VL) 10672 NODE_NAME_CASE(VZEXT_VL) 10673 NODE_NAME_CASE(VCPOP_VL) 10674 NODE_NAME_CASE(VLE_VL) 10675 NODE_NAME_CASE(VSE_VL) 10676 NODE_NAME_CASE(READ_CSR) 10677 NODE_NAME_CASE(WRITE_CSR) 10678 NODE_NAME_CASE(SWAP_CSR) 10679 } 10680 // clang-format on 10681 return nullptr; 10682 #undef NODE_NAME_CASE 10683 } 10684 10685 /// getConstraintType - Given a constraint letter, return the type of 10686 /// constraint it is for this target. 10687 RISCVTargetLowering::ConstraintType 10688 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 10689 if (Constraint.size() == 1) { 10690 switch (Constraint[0]) { 10691 default: 10692 break; 10693 case 'f': 10694 return C_RegisterClass; 10695 case 'I': 10696 case 'J': 10697 case 'K': 10698 return C_Immediate; 10699 case 'A': 10700 return C_Memory; 10701 case 'S': // A symbolic address 10702 return C_Other; 10703 } 10704 } else { 10705 if (Constraint == "vr" || Constraint == "vm") 10706 return C_RegisterClass; 10707 } 10708 return TargetLowering::getConstraintType(Constraint); 10709 } 10710 10711 std::pair<unsigned, const TargetRegisterClass *> 10712 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10713 StringRef Constraint, 10714 MVT VT) const { 10715 // First, see if this is a constraint that directly corresponds to a 10716 // RISCV register class. 10717 if (Constraint.size() == 1) { 10718 switch (Constraint[0]) { 10719 case 'r': 10720 // TODO: Support fixed vectors up to XLen for P extension? 10721 if (VT.isVector()) 10722 break; 10723 return std::make_pair(0U, &RISCV::GPRRegClass); 10724 case 'f': 10725 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 10726 return std::make_pair(0U, &RISCV::FPR16RegClass); 10727 if (Subtarget.hasStdExtF() && VT == MVT::f32) 10728 return std::make_pair(0U, &RISCV::FPR32RegClass); 10729 if (Subtarget.hasStdExtD() && VT == MVT::f64) 10730 return std::make_pair(0U, &RISCV::FPR64RegClass); 10731 break; 10732 default: 10733 break; 10734 } 10735 } else if (Constraint == "vr") { 10736 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 10737 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10738 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 10739 return std::make_pair(0U, RC); 10740 } 10741 } else if (Constraint == "vm") { 10742 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 10743 return std::make_pair(0U, &RISCV::VMV0RegClass); 10744 } 10745 10746 // Clang will correctly decode the usage of register name aliases into their 10747 // official names. However, other frontends like `rustc` do not. This allows 10748 // users of these frontends to use the ABI names for registers in LLVM-style 10749 // register constraints. 10750 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 10751 .Case("{zero}", RISCV::X0) 10752 .Case("{ra}", RISCV::X1) 10753 .Case("{sp}", RISCV::X2) 10754 .Case("{gp}", RISCV::X3) 10755 .Case("{tp}", RISCV::X4) 10756 .Case("{t0}", RISCV::X5) 10757 .Case("{t1}", RISCV::X6) 10758 .Case("{t2}", RISCV::X7) 10759 .Cases("{s0}", "{fp}", RISCV::X8) 10760 .Case("{s1}", RISCV::X9) 10761 .Case("{a0}", RISCV::X10) 10762 .Case("{a1}", RISCV::X11) 10763 .Case("{a2}", RISCV::X12) 10764 .Case("{a3}", RISCV::X13) 10765 .Case("{a4}", RISCV::X14) 10766 .Case("{a5}", RISCV::X15) 10767 .Case("{a6}", RISCV::X16) 10768 .Case("{a7}", RISCV::X17) 10769 .Case("{s2}", RISCV::X18) 10770 .Case("{s3}", RISCV::X19) 10771 .Case("{s4}", RISCV::X20) 10772 .Case("{s5}", RISCV::X21) 10773 .Case("{s6}", RISCV::X22) 10774 .Case("{s7}", RISCV::X23) 10775 .Case("{s8}", RISCV::X24) 10776 .Case("{s9}", RISCV::X25) 10777 .Case("{s10}", RISCV::X26) 10778 .Case("{s11}", RISCV::X27) 10779 .Case("{t3}", RISCV::X28) 10780 .Case("{t4}", RISCV::X29) 10781 .Case("{t5}", RISCV::X30) 10782 .Case("{t6}", RISCV::X31) 10783 .Default(RISCV::NoRegister); 10784 if (XRegFromAlias != RISCV::NoRegister) 10785 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 10786 10787 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 10788 // TableGen record rather than the AsmName to choose registers for InlineAsm 10789 // constraints, plus we want to match those names to the widest floating point 10790 // register type available, manually select floating point registers here. 10791 // 10792 // The second case is the ABI name of the register, so that frontends can also 10793 // use the ABI names in register constraint lists. 10794 if (Subtarget.hasStdExtF()) { 10795 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 10796 .Cases("{f0}", "{ft0}", RISCV::F0_F) 10797 .Cases("{f1}", "{ft1}", RISCV::F1_F) 10798 .Cases("{f2}", "{ft2}", RISCV::F2_F) 10799 .Cases("{f3}", "{ft3}", RISCV::F3_F) 10800 .Cases("{f4}", "{ft4}", RISCV::F4_F) 10801 .Cases("{f5}", "{ft5}", RISCV::F5_F) 10802 .Cases("{f6}", "{ft6}", RISCV::F6_F) 10803 .Cases("{f7}", "{ft7}", RISCV::F7_F) 10804 .Cases("{f8}", "{fs0}", RISCV::F8_F) 10805 .Cases("{f9}", "{fs1}", RISCV::F9_F) 10806 .Cases("{f10}", "{fa0}", RISCV::F10_F) 10807 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10808 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10809 .Cases("{f13}", "{fa3}", RISCV::F13_F) 10810 .Cases("{f14}", "{fa4}", RISCV::F14_F) 10811 .Cases("{f15}", "{fa5}", RISCV::F15_F) 10812 .Cases("{f16}", "{fa6}", RISCV::F16_F) 10813 .Cases("{f17}", "{fa7}", RISCV::F17_F) 10814 .Cases("{f18}", "{fs2}", RISCV::F18_F) 10815 .Cases("{f19}", "{fs3}", RISCV::F19_F) 10816 .Cases("{f20}", "{fs4}", RISCV::F20_F) 10817 .Cases("{f21}", "{fs5}", RISCV::F21_F) 10818 .Cases("{f22}", "{fs6}", RISCV::F22_F) 10819 .Cases("{f23}", "{fs7}", RISCV::F23_F) 10820 .Cases("{f24}", "{fs8}", RISCV::F24_F) 10821 .Cases("{f25}", "{fs9}", RISCV::F25_F) 10822 .Cases("{f26}", "{fs10}", RISCV::F26_F) 10823 .Cases("{f27}", "{fs11}", RISCV::F27_F) 10824 .Cases("{f28}", "{ft8}", RISCV::F28_F) 10825 .Cases("{f29}", "{ft9}", RISCV::F29_F) 10826 .Cases("{f30}", "{ft10}", RISCV::F30_F) 10827 .Cases("{f31}", "{ft11}", RISCV::F31_F) 10828 .Default(RISCV::NoRegister); 10829 if (FReg != RISCV::NoRegister) { 10830 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 10831 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 10832 unsigned RegNo = FReg - RISCV::F0_F; 10833 unsigned DReg = RISCV::F0_D + RegNo; 10834 return std::make_pair(DReg, &RISCV::FPR64RegClass); 10835 } 10836 if (VT == MVT::f32 || VT == MVT::Other) 10837 return std::make_pair(FReg, &RISCV::FPR32RegClass); 10838 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 10839 unsigned RegNo = FReg - RISCV::F0_F; 10840 unsigned HReg = RISCV::F0_H + RegNo; 10841 return std::make_pair(HReg, &RISCV::FPR16RegClass); 10842 } 10843 } 10844 } 10845 10846 if (Subtarget.hasVInstructions()) { 10847 Register VReg = StringSwitch<Register>(Constraint.lower()) 10848 .Case("{v0}", RISCV::V0) 10849 .Case("{v1}", RISCV::V1) 10850 .Case("{v2}", RISCV::V2) 10851 .Case("{v3}", RISCV::V3) 10852 .Case("{v4}", RISCV::V4) 10853 .Case("{v5}", RISCV::V5) 10854 .Case("{v6}", RISCV::V6) 10855 .Case("{v7}", RISCV::V7) 10856 .Case("{v8}", RISCV::V8) 10857 .Case("{v9}", RISCV::V9) 10858 .Case("{v10}", RISCV::V10) 10859 .Case("{v11}", RISCV::V11) 10860 .Case("{v12}", RISCV::V12) 10861 .Case("{v13}", RISCV::V13) 10862 .Case("{v14}", RISCV::V14) 10863 .Case("{v15}", RISCV::V15) 10864 .Case("{v16}", RISCV::V16) 10865 .Case("{v17}", RISCV::V17) 10866 .Case("{v18}", RISCV::V18) 10867 .Case("{v19}", RISCV::V19) 10868 .Case("{v20}", RISCV::V20) 10869 .Case("{v21}", RISCV::V21) 10870 .Case("{v22}", RISCV::V22) 10871 .Case("{v23}", RISCV::V23) 10872 .Case("{v24}", RISCV::V24) 10873 .Case("{v25}", RISCV::V25) 10874 .Case("{v26}", RISCV::V26) 10875 .Case("{v27}", RISCV::V27) 10876 .Case("{v28}", RISCV::V28) 10877 .Case("{v29}", RISCV::V29) 10878 .Case("{v30}", RISCV::V30) 10879 .Case("{v31}", RISCV::V31) 10880 .Default(RISCV::NoRegister); 10881 if (VReg != RISCV::NoRegister) { 10882 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 10883 return std::make_pair(VReg, &RISCV::VMRegClass); 10884 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 10885 return std::make_pair(VReg, &RISCV::VRRegClass); 10886 for (const auto *RC : 10887 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10888 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 10889 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 10890 return std::make_pair(VReg, RC); 10891 } 10892 } 10893 } 10894 } 10895 10896 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10897 } 10898 10899 unsigned 10900 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 10901 // Currently only support length 1 constraints. 10902 if (ConstraintCode.size() == 1) { 10903 switch (ConstraintCode[0]) { 10904 case 'A': 10905 return InlineAsm::Constraint_A; 10906 default: 10907 break; 10908 } 10909 } 10910 10911 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 10912 } 10913 10914 void RISCVTargetLowering::LowerAsmOperandForConstraint( 10915 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 10916 SelectionDAG &DAG) const { 10917 // Currently only support length 1 constraints. 10918 if (Constraint.length() == 1) { 10919 switch (Constraint[0]) { 10920 case 'I': 10921 // Validate & create a 12-bit signed immediate operand. 10922 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10923 uint64_t CVal = C->getSExtValue(); 10924 if (isInt<12>(CVal)) 10925 Ops.push_back( 10926 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10927 } 10928 return; 10929 case 'J': 10930 // Validate & create an integer zero operand. 10931 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 10932 if (C->getZExtValue() == 0) 10933 Ops.push_back( 10934 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 10935 return; 10936 case 'K': 10937 // Validate & create a 5-bit unsigned immediate operand. 10938 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10939 uint64_t CVal = C->getZExtValue(); 10940 if (isUInt<5>(CVal)) 10941 Ops.push_back( 10942 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10943 } 10944 return; 10945 case 'S': 10946 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 10947 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 10948 GA->getValueType(0))); 10949 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 10950 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 10951 BA->getValueType(0))); 10952 } 10953 return; 10954 default: 10955 break; 10956 } 10957 } 10958 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 10959 } 10960 10961 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 10962 Instruction *Inst, 10963 AtomicOrdering Ord) const { 10964 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 10965 return Builder.CreateFence(Ord); 10966 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 10967 return Builder.CreateFence(AtomicOrdering::Release); 10968 return nullptr; 10969 } 10970 10971 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 10972 Instruction *Inst, 10973 AtomicOrdering Ord) const { 10974 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 10975 return Builder.CreateFence(AtomicOrdering::Acquire); 10976 return nullptr; 10977 } 10978 10979 TargetLowering::AtomicExpansionKind 10980 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10981 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 10982 // point operations can't be used in an lr/sc sequence without breaking the 10983 // forward-progress guarantee. 10984 if (AI->isFloatingPointOperation()) 10985 return AtomicExpansionKind::CmpXChg; 10986 10987 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10988 if (Size == 8 || Size == 16) 10989 return AtomicExpansionKind::MaskedIntrinsic; 10990 return AtomicExpansionKind::None; 10991 } 10992 10993 static Intrinsic::ID 10994 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 10995 if (XLen == 32) { 10996 switch (BinOp) { 10997 default: 10998 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10999 case AtomicRMWInst::Xchg: 11000 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11001 case AtomicRMWInst::Add: 11002 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11003 case AtomicRMWInst::Sub: 11004 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11005 case AtomicRMWInst::Nand: 11006 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11007 case AtomicRMWInst::Max: 11008 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11009 case AtomicRMWInst::Min: 11010 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11011 case AtomicRMWInst::UMax: 11012 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11013 case AtomicRMWInst::UMin: 11014 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11015 } 11016 } 11017 11018 if (XLen == 64) { 11019 switch (BinOp) { 11020 default: 11021 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11022 case AtomicRMWInst::Xchg: 11023 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11024 case AtomicRMWInst::Add: 11025 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11026 case AtomicRMWInst::Sub: 11027 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11028 case AtomicRMWInst::Nand: 11029 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11030 case AtomicRMWInst::Max: 11031 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11032 case AtomicRMWInst::Min: 11033 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11034 case AtomicRMWInst::UMax: 11035 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11036 case AtomicRMWInst::UMin: 11037 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11038 } 11039 } 11040 11041 llvm_unreachable("Unexpected XLen\n"); 11042 } 11043 11044 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11045 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11046 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11047 unsigned XLen = Subtarget.getXLen(); 11048 Value *Ordering = 11049 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11050 Type *Tys[] = {AlignedAddr->getType()}; 11051 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11052 AI->getModule(), 11053 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11054 11055 if (XLen == 64) { 11056 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11057 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11058 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11059 } 11060 11061 Value *Result; 11062 11063 // Must pass the shift amount needed to sign extend the loaded value prior 11064 // to performing a signed comparison for min/max. ShiftAmt is the number of 11065 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11066 // is the number of bits to left+right shift the value in order to 11067 // sign-extend. 11068 if (AI->getOperation() == AtomicRMWInst::Min || 11069 AI->getOperation() == AtomicRMWInst::Max) { 11070 const DataLayout &DL = AI->getModule()->getDataLayout(); 11071 unsigned ValWidth = 11072 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11073 Value *SextShamt = 11074 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11075 Result = Builder.CreateCall(LrwOpScwLoop, 11076 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11077 } else { 11078 Result = 11079 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11080 } 11081 11082 if (XLen == 64) 11083 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11084 return Result; 11085 } 11086 11087 TargetLowering::AtomicExpansionKind 11088 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11089 AtomicCmpXchgInst *CI) const { 11090 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11091 if (Size == 8 || Size == 16) 11092 return AtomicExpansionKind::MaskedIntrinsic; 11093 return AtomicExpansionKind::None; 11094 } 11095 11096 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11097 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11098 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11099 unsigned XLen = Subtarget.getXLen(); 11100 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11101 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11102 if (XLen == 64) { 11103 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11104 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11105 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11106 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11107 } 11108 Type *Tys[] = {AlignedAddr->getType()}; 11109 Function *MaskedCmpXchg = 11110 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11111 Value *Result = Builder.CreateCall( 11112 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11113 if (XLen == 64) 11114 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11115 return Result; 11116 } 11117 11118 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11119 return false; 11120 } 11121 11122 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11123 EVT VT) const { 11124 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11125 return false; 11126 11127 switch (FPVT.getSimpleVT().SimpleTy) { 11128 case MVT::f16: 11129 return Subtarget.hasStdExtZfh(); 11130 case MVT::f32: 11131 return Subtarget.hasStdExtF(); 11132 case MVT::f64: 11133 return Subtarget.hasStdExtD(); 11134 default: 11135 return false; 11136 } 11137 } 11138 11139 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11140 // If we are using the small code model, we can reduce size of jump table 11141 // entry to 4 bytes. 11142 if (Subtarget.is64Bit() && !isPositionIndependent() && 11143 getTargetMachine().getCodeModel() == CodeModel::Small) { 11144 return MachineJumpTableInfo::EK_Custom32; 11145 } 11146 return TargetLowering::getJumpTableEncoding(); 11147 } 11148 11149 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11150 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11151 unsigned uid, MCContext &Ctx) const { 11152 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11153 getTargetMachine().getCodeModel() == CodeModel::Small); 11154 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11155 } 11156 11157 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11158 EVT VT) const { 11159 VT = VT.getScalarType(); 11160 11161 if (!VT.isSimple()) 11162 return false; 11163 11164 switch (VT.getSimpleVT().SimpleTy) { 11165 case MVT::f16: 11166 return Subtarget.hasStdExtZfh(); 11167 case MVT::f32: 11168 return Subtarget.hasStdExtF(); 11169 case MVT::f64: 11170 return Subtarget.hasStdExtD(); 11171 default: 11172 break; 11173 } 11174 11175 return false; 11176 } 11177 11178 Register RISCVTargetLowering::getExceptionPointerRegister( 11179 const Constant *PersonalityFn) const { 11180 return RISCV::X10; 11181 } 11182 11183 Register RISCVTargetLowering::getExceptionSelectorRegister( 11184 const Constant *PersonalityFn) const { 11185 return RISCV::X11; 11186 } 11187 11188 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11189 // Return false to suppress the unnecessary extensions if the LibCall 11190 // arguments or return value is f32 type for LP64 ABI. 11191 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11192 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11193 return false; 11194 11195 return true; 11196 } 11197 11198 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11199 if (Subtarget.is64Bit() && Type == MVT::i32) 11200 return true; 11201 11202 return IsSigned; 11203 } 11204 11205 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11206 SDValue C) const { 11207 // Check integral scalar types. 11208 if (VT.isScalarInteger()) { 11209 // Omit the optimization if the sub target has the M extension and the data 11210 // size exceeds XLen. 11211 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11212 return false; 11213 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11214 // Break the MUL to a SLLI and an ADD/SUB. 11215 const APInt &Imm = ConstNode->getAPIntValue(); 11216 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11217 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11218 return true; 11219 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11220 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11221 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11222 (Imm - 8).isPowerOf2())) 11223 return true; 11224 // Omit the following optimization if the sub target has the M extension 11225 // and the data size >= XLen. 11226 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11227 return false; 11228 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11229 // a pair of LUI/ADDI. 11230 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11231 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11232 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11233 (1 - ImmS).isPowerOf2()) 11234 return true; 11235 } 11236 } 11237 } 11238 11239 return false; 11240 } 11241 11242 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11243 SDValue ConstNode) const { 11244 // Let the DAGCombiner decide for vectors. 11245 EVT VT = AddNode.getValueType(); 11246 if (VT.isVector()) 11247 return true; 11248 11249 // Let the DAGCombiner decide for larger types. 11250 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11251 return true; 11252 11253 // It is worse if c1 is simm12 while c1*c2 is not. 11254 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11255 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11256 const APInt &C1 = C1Node->getAPIntValue(); 11257 const APInt &C2 = C2Node->getAPIntValue(); 11258 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11259 return false; 11260 11261 // Default to true and let the DAGCombiner decide. 11262 return true; 11263 } 11264 11265 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11266 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11267 bool *Fast) const { 11268 if (!VT.isVector()) 11269 return false; 11270 11271 EVT ElemVT = VT.getVectorElementType(); 11272 if (Alignment >= ElemVT.getStoreSize()) { 11273 if (Fast) 11274 *Fast = true; 11275 return true; 11276 } 11277 11278 return false; 11279 } 11280 11281 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11282 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11283 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11284 bool IsABIRegCopy = CC.hasValue(); 11285 EVT ValueVT = Val.getValueType(); 11286 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11287 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11288 // and cast to f32. 11289 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11290 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11291 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11292 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11293 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11294 Parts[0] = Val; 11295 return true; 11296 } 11297 11298 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11299 LLVMContext &Context = *DAG.getContext(); 11300 EVT ValueEltVT = ValueVT.getVectorElementType(); 11301 EVT PartEltVT = PartVT.getVectorElementType(); 11302 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11303 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11304 if (PartVTBitSize % ValueVTBitSize == 0) { 11305 assert(PartVTBitSize >= ValueVTBitSize); 11306 // If the element types are different, bitcast to the same element type of 11307 // PartVT first. 11308 // Give an example here, we want copy a <vscale x 1 x i8> value to 11309 // <vscale x 4 x i16>. 11310 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11311 // subvector, then we can bitcast to <vscale x 4 x i16>. 11312 if (ValueEltVT != PartEltVT) { 11313 if (PartVTBitSize > ValueVTBitSize) { 11314 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11315 assert(Count != 0 && "The number of element should not be zero."); 11316 EVT SameEltTypeVT = 11317 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11318 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11319 DAG.getUNDEF(SameEltTypeVT), Val, 11320 DAG.getVectorIdxConstant(0, DL)); 11321 } 11322 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11323 } else { 11324 Val = 11325 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11326 Val, DAG.getVectorIdxConstant(0, DL)); 11327 } 11328 Parts[0] = Val; 11329 return true; 11330 } 11331 } 11332 return false; 11333 } 11334 11335 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11336 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11337 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11338 bool IsABIRegCopy = CC.hasValue(); 11339 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11340 SDValue Val = Parts[0]; 11341 11342 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11343 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11344 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11345 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11346 return Val; 11347 } 11348 11349 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11350 LLVMContext &Context = *DAG.getContext(); 11351 SDValue Val = Parts[0]; 11352 EVT ValueEltVT = ValueVT.getVectorElementType(); 11353 EVT PartEltVT = PartVT.getVectorElementType(); 11354 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11355 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11356 if (PartVTBitSize % ValueVTBitSize == 0) { 11357 assert(PartVTBitSize >= ValueVTBitSize); 11358 EVT SameEltTypeVT = ValueVT; 11359 // If the element types are different, convert it to the same element type 11360 // of PartVT. 11361 // Give an example here, we want copy a <vscale x 1 x i8> value from 11362 // <vscale x 4 x i16>. 11363 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11364 // then we can extract <vscale x 1 x i8>. 11365 if (ValueEltVT != PartEltVT) { 11366 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11367 assert(Count != 0 && "The number of element should not be zero."); 11368 SameEltTypeVT = 11369 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11370 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11371 } 11372 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11373 DAG.getVectorIdxConstant(0, DL)); 11374 return Val; 11375 } 11376 } 11377 return SDValue(); 11378 } 11379 11380 SDValue 11381 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11382 SelectionDAG &DAG, 11383 SmallVectorImpl<SDNode *> &Created) const { 11384 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11385 if (isIntDivCheap(N->getValueType(0), Attr)) 11386 return SDValue(N, 0); // Lower SDIV as SDIV 11387 11388 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11389 "Unexpected divisor!"); 11390 11391 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11392 if (!Subtarget.hasStdExtZbt()) 11393 return SDValue(); 11394 11395 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11396 // Besides, more critical path instructions will be generated when dividing 11397 // by 2. So we keep using the original DAGs for these cases. 11398 unsigned Lg2 = Divisor.countTrailingZeros(); 11399 if (Lg2 == 1 || Lg2 >= 12) 11400 return SDValue(); 11401 11402 // fold (sdiv X, pow2) 11403 EVT VT = N->getValueType(0); 11404 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11405 return SDValue(); 11406 11407 SDLoc DL(N); 11408 SDValue N0 = N->getOperand(0); 11409 SDValue Zero = DAG.getConstant(0, DL, VT); 11410 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11411 11412 // Add (N0 < 0) ? Pow2 - 1 : 0; 11413 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11414 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11415 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11416 11417 Created.push_back(Cmp.getNode()); 11418 Created.push_back(Add.getNode()); 11419 Created.push_back(Sel.getNode()); 11420 11421 // Divide by pow2. 11422 SDValue SRA = 11423 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11424 11425 // If we're dividing by a positive value, we're done. Otherwise, we must 11426 // negate the result. 11427 if (Divisor.isNonNegative()) 11428 return SRA; 11429 11430 Created.push_back(SRA.getNode()); 11431 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11432 } 11433 11434 #define GET_REGISTER_MATCHER 11435 #include "RISCVGenAsmMatcher.inc" 11436 11437 Register 11438 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11439 const MachineFunction &MF) const { 11440 Register Reg = MatchRegisterAltName(RegName); 11441 if (Reg == RISCV::NoRegister) 11442 Reg = MatchRegisterName(RegName); 11443 if (Reg == RISCV::NoRegister) 11444 report_fatal_error( 11445 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11446 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11447 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11448 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11449 StringRef(RegName) + "\".")); 11450 return Reg; 11451 } 11452 11453 namespace llvm { 11454 namespace RISCVVIntrinsicsTable { 11455 11456 #define GET_RISCVVIntrinsicsTable_IMPL 11457 #include "RISCVGenSearchableTables.inc" 11458 11459 } // namespace RISCVVIntrinsicsTable 11460 11461 } // namespace llvm 11462