1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 116 assert(Size <= 512 && isPowerOf2_32(Size)); 117 const TargetRegisterClass *RC; 118 if (Size <= 64) 119 RC = &RISCV::VRRegClass; 120 else if (Size == 128) 121 RC = &RISCV::VRM2RegClass; 122 else if (Size == 256) 123 RC = &RISCV::VRM4RegClass; 124 else 125 RC = &RISCV::VRM8RegClass; 126 127 addRegisterClass(VT, RC); 128 }; 129 130 for (MVT VT : BoolVecVTs) 131 addRegClassForRVV(VT); 132 for (MVT VT : IntVecVTs) { 133 if (VT.getVectorElementType() == MVT::i64 && 134 !Subtarget.hasVInstructionsI64()) 135 continue; 136 addRegClassForRVV(VT); 137 } 138 139 if (Subtarget.hasVInstructionsF16()) 140 for (MVT VT : F16VecVTs) 141 addRegClassForRVV(VT); 142 143 if (Subtarget.hasVInstructionsF32()) 144 for (MVT VT : F32VecVTs) 145 addRegClassForRVV(VT); 146 147 if (Subtarget.hasVInstructionsF64()) 148 for (MVT VT : F64VecVTs) 149 addRegClassForRVV(VT); 150 151 if (Subtarget.useRVVForFixedLengthVectors()) { 152 auto addRegClassForFixedVectors = [this](MVT VT) { 153 MVT ContainerVT = getContainerForFixedLengthVector(VT); 154 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 155 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 156 addRegisterClass(VT, TRI.getRegClass(RCID)); 157 }; 158 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 159 if (useRVVForFixedLengthVectorVT(VT)) 160 addRegClassForFixedVectors(VT); 161 162 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 163 if (useRVVForFixedLengthVectorVT(VT)) 164 addRegClassForFixedVectors(VT); 165 } 166 } 167 168 // Compute derived properties from the register classes. 169 computeRegisterProperties(STI.getRegisterInfo()); 170 171 setStackPointerRegisterToSaveRestore(RISCV::X2); 172 173 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 174 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 175 176 // TODO: add all necessary setOperationAction calls. 177 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 178 179 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 180 setOperationAction(ISD::BR_CC, XLenVT, Expand); 181 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 182 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 183 184 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 185 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 186 187 setOperationAction(ISD::VASTART, MVT::Other, Custom); 188 setOperationAction(ISD::VAARG, MVT::Other, Expand); 189 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 190 setOperationAction(ISD::VAEND, MVT::Other, Expand); 191 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 193 if (!Subtarget.hasStdExtZbb()) { 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 196 } 197 198 if (Subtarget.is64Bit()) { 199 setOperationAction(ISD::ADD, MVT::i32, Custom); 200 setOperationAction(ISD::SUB, MVT::i32, Custom); 201 setOperationAction(ISD::SHL, MVT::i32, Custom); 202 setOperationAction(ISD::SRA, MVT::i32, Custom); 203 setOperationAction(ISD::SRL, MVT::i32, Custom); 204 205 setOperationAction(ISD::UADDO, MVT::i32, Custom); 206 setOperationAction(ISD::USUBO, MVT::i32, Custom); 207 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 208 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 209 } else { 210 setLibcallName(RTLIB::SHL_I128, nullptr); 211 setLibcallName(RTLIB::SRL_I128, nullptr); 212 setLibcallName(RTLIB::SRA_I128, nullptr); 213 setLibcallName(RTLIB::MUL_I128, nullptr); 214 setLibcallName(RTLIB::MULO_I64, nullptr); 215 } 216 217 if (!Subtarget.hasStdExtM()) { 218 setOperationAction(ISD::MUL, XLenVT, Expand); 219 setOperationAction(ISD::MULHS, XLenVT, Expand); 220 setOperationAction(ISD::MULHU, XLenVT, Expand); 221 setOperationAction(ISD::SDIV, XLenVT, Expand); 222 setOperationAction(ISD::UDIV, XLenVT, Expand); 223 setOperationAction(ISD::SREM, XLenVT, Expand); 224 setOperationAction(ISD::UREM, XLenVT, Expand); 225 } else { 226 if (Subtarget.is64Bit()) { 227 setOperationAction(ISD::MUL, MVT::i32, Custom); 228 setOperationAction(ISD::MUL, MVT::i128, Custom); 229 230 setOperationAction(ISD::SDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UDIV, MVT::i8, Custom); 232 setOperationAction(ISD::UREM, MVT::i8, Custom); 233 setOperationAction(ISD::SDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UDIV, MVT::i16, Custom); 235 setOperationAction(ISD::UREM, MVT::i16, Custom); 236 setOperationAction(ISD::SDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UDIV, MVT::i32, Custom); 238 setOperationAction(ISD::UREM, MVT::i32, Custom); 239 } else { 240 setOperationAction(ISD::MUL, MVT::i64, Custom); 241 } 242 } 243 244 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 246 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 247 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 248 249 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 251 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 252 253 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 254 Subtarget.hasStdExtZbkb()) { 255 if (Subtarget.is64Bit()) { 256 setOperationAction(ISD::ROTL, MVT::i32, Custom); 257 setOperationAction(ISD::ROTR, MVT::i32, Custom); 258 } 259 } else { 260 setOperationAction(ISD::ROTL, XLenVT, Expand); 261 setOperationAction(ISD::ROTR, XLenVT, Expand); 262 } 263 264 if (Subtarget.hasStdExtZbp()) { 265 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 266 // more combining. 267 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 268 setOperationAction(ISD::BSWAP, XLenVT, Custom); 269 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 270 // BSWAP i8 doesn't exist. 271 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 272 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 273 274 if (Subtarget.is64Bit()) { 275 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 276 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 277 } 278 } else { 279 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 280 // pattern match it directly in isel. 281 setOperationAction(ISD::BSWAP, XLenVT, 282 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 283 ? Legal 284 : Expand); 285 // Zbkb can use rev8+brev8 to implement bitreverse. 286 setOperationAction(ISD::BITREVERSE, XLenVT, 287 Subtarget.hasStdExtZbkb() ? Custom : Expand); 288 } 289 290 if (Subtarget.hasStdExtZbb()) { 291 setOperationAction(ISD::SMIN, XLenVT, Legal); 292 setOperationAction(ISD::SMAX, XLenVT, Legal); 293 setOperationAction(ISD::UMIN, XLenVT, Legal); 294 setOperationAction(ISD::UMAX, XLenVT, Legal); 295 296 if (Subtarget.is64Bit()) { 297 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 298 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 299 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 300 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 301 } 302 } else { 303 setOperationAction(ISD::CTTZ, XLenVT, Expand); 304 setOperationAction(ISD::CTLZ, XLenVT, Expand); 305 setOperationAction(ISD::CTPOP, XLenVT, Expand); 306 307 if (Subtarget.is64Bit()) 308 setOperationAction(ISD::ABS, MVT::i32, Custom); 309 } 310 311 if (Subtarget.hasStdExtZbt()) { 312 setOperationAction(ISD::FSHL, XLenVT, Custom); 313 setOperationAction(ISD::FSHR, XLenVT, Custom); 314 setOperationAction(ISD::SELECT, XLenVT, Legal); 315 316 if (Subtarget.is64Bit()) { 317 setOperationAction(ISD::FSHL, MVT::i32, Custom); 318 setOperationAction(ISD::FSHR, MVT::i32, Custom); 319 } 320 } else { 321 setOperationAction(ISD::SELECT, XLenVT, Custom); 322 } 323 324 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 325 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 326 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 327 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 328 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 329 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 330 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 331 332 static const ISD::CondCode FPCCToExpand[] = { 333 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 334 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 335 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 336 337 static const ISD::NodeType FPOpToExpand[] = { 338 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 339 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 340 341 if (Subtarget.hasStdExtZfh()) 342 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 343 344 if (Subtarget.hasStdExtZfh()) { 345 for (auto NT : FPLegalNodeTypes) 346 setOperationAction(NT, MVT::f16, Legal); 347 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 348 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 349 for (auto CC : FPCCToExpand) 350 setCondCodeAction(CC, MVT::f16, Expand); 351 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 352 setOperationAction(ISD::SELECT, MVT::f16, Custom); 353 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 354 355 setOperationAction(ISD::FREM, MVT::f16, Promote); 356 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 357 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 358 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 359 setOperationAction(ISD::FRINT, MVT::f16, Promote); 360 setOperationAction(ISD::FROUND, MVT::f16, Promote); 361 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 362 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 363 setOperationAction(ISD::FPOW, MVT::f16, Promote); 364 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 365 setOperationAction(ISD::FCOS, MVT::f16, Promote); 366 setOperationAction(ISD::FSIN, MVT::f16, Promote); 367 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 368 setOperationAction(ISD::FEXP, MVT::f16, Promote); 369 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 370 setOperationAction(ISD::FLOG, MVT::f16, Promote); 371 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 372 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 373 374 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 375 // complete support for all operations in LegalizeDAG. 376 377 // We need to custom promote this. 378 if (Subtarget.is64Bit()) 379 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 380 } 381 382 if (Subtarget.hasStdExtF()) { 383 for (auto NT : FPLegalNodeTypes) 384 setOperationAction(NT, MVT::f32, Legal); 385 for (auto CC : FPCCToExpand) 386 setCondCodeAction(CC, MVT::f32, Expand); 387 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 388 setOperationAction(ISD::SELECT, MVT::f32, Custom); 389 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 390 for (auto Op : FPOpToExpand) 391 setOperationAction(Op, MVT::f32, Expand); 392 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 393 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 394 } 395 396 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 397 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 398 399 if (Subtarget.hasStdExtD()) { 400 for (auto NT : FPLegalNodeTypes) 401 setOperationAction(NT, MVT::f64, Legal); 402 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 403 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 404 for (auto CC : FPCCToExpand) 405 setCondCodeAction(CC, MVT::f64, Expand); 406 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 407 setOperationAction(ISD::SELECT, MVT::f64, Custom); 408 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 409 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 410 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 411 for (auto Op : FPOpToExpand) 412 setOperationAction(Op, MVT::f64, Expand); 413 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 414 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 415 } 416 417 if (Subtarget.is64Bit()) { 418 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 419 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 420 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 421 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 422 } 423 424 if (Subtarget.hasStdExtF()) { 425 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 426 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 427 428 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 429 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 430 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 431 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 432 433 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 434 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 435 } 436 437 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 438 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 439 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 440 setOperationAction(ISD::JumpTable, XLenVT, Custom); 441 442 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 443 444 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 445 // Unfortunately this can't be determined just from the ISA naming string. 446 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 447 Subtarget.is64Bit() ? Legal : Custom); 448 449 setOperationAction(ISD::TRAP, MVT::Other, Legal); 450 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 451 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 452 if (Subtarget.is64Bit()) 453 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 454 455 if (Subtarget.hasStdExtA()) { 456 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 457 setMinCmpXchgSizeInBits(32); 458 } else { 459 setMaxAtomicSizeInBitsSupported(0); 460 } 461 462 setBooleanContents(ZeroOrOneBooleanContent); 463 464 if (Subtarget.hasVInstructions()) { 465 setBooleanVectorContents(ZeroOrOneBooleanContent); 466 467 setOperationAction(ISD::VSCALE, XLenVT, Custom); 468 469 // RVV intrinsics may have illegal operands. 470 // We also need to custom legalize vmv.x.s. 471 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 474 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 475 if (Subtarget.is64Bit()) { 476 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 477 } else { 478 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 479 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 480 } 481 482 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 483 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 484 485 static const unsigned IntegerVPOps[] = { 486 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 487 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 488 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 489 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 490 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 491 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 492 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 493 ISD::VP_MERGE, ISD::VP_SELECT}; 494 495 static const unsigned FloatingPointVPOps[] = { 496 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 497 ISD::VP_FDIV, ISD::VP_FNEG, ISD::VP_FMA, 498 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN, 499 ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, ISD::VP_SELECT}; 500 501 if (!Subtarget.is64Bit()) { 502 // We must custom-lower certain vXi64 operations on RV32 due to the vector 503 // element type being illegal. 504 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 505 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 506 507 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 508 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 509 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 510 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 511 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 512 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 513 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 514 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 515 516 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 517 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 518 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 519 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 520 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 521 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 522 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 523 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 524 } 525 526 for (MVT VT : BoolVecVTs) { 527 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 528 529 // Mask VTs are custom-expanded into a series of standard nodes 530 setOperationAction(ISD::TRUNCATE, VT, Custom); 531 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 532 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 533 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 534 535 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 536 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 537 538 setOperationAction(ISD::SELECT, VT, Custom); 539 setOperationAction(ISD::SELECT_CC, VT, Expand); 540 setOperationAction(ISD::VSELECT, VT, Expand); 541 setOperationAction(ISD::VP_MERGE, VT, Expand); 542 setOperationAction(ISD::VP_SELECT, VT, Expand); 543 544 setOperationAction(ISD::VP_AND, VT, Custom); 545 setOperationAction(ISD::VP_OR, VT, Custom); 546 setOperationAction(ISD::VP_XOR, VT, Custom); 547 548 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 549 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 550 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 551 552 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 553 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 554 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 555 556 // RVV has native int->float & float->int conversions where the 557 // element type sizes are within one power-of-two of each other. Any 558 // wider distances between type sizes have to be lowered as sequences 559 // which progressively narrow the gap in stages. 560 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 561 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 562 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 563 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 564 565 // Expand all extending loads to types larger than this, and truncating 566 // stores from types larger than this. 567 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 568 setTruncStoreAction(OtherVT, VT, Expand); 569 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 570 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 571 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 572 } 573 } 574 575 for (MVT VT : IntVecVTs) { 576 if (VT.getVectorElementType() == MVT::i64 && 577 !Subtarget.hasVInstructionsI64()) 578 continue; 579 580 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 581 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 582 583 // Vectors implement MULHS/MULHU. 584 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 585 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 586 587 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 588 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 589 setOperationAction(ISD::MULHU, VT, Expand); 590 setOperationAction(ISD::MULHS, VT, Expand); 591 } 592 593 setOperationAction(ISD::SMIN, VT, Legal); 594 setOperationAction(ISD::SMAX, VT, Legal); 595 setOperationAction(ISD::UMIN, VT, Legal); 596 setOperationAction(ISD::UMAX, VT, Legal); 597 598 setOperationAction(ISD::ROTL, VT, Expand); 599 setOperationAction(ISD::ROTR, VT, Expand); 600 601 setOperationAction(ISD::CTTZ, VT, Expand); 602 setOperationAction(ISD::CTLZ, VT, Expand); 603 setOperationAction(ISD::CTPOP, VT, Expand); 604 605 setOperationAction(ISD::BSWAP, VT, Expand); 606 607 // Custom-lower extensions and truncations from/to mask types. 608 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 609 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 610 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 611 612 // RVV has native int->float & float->int conversions where the 613 // element type sizes are within one power-of-two of each other. Any 614 // wider distances between type sizes have to be lowered as sequences 615 // which progressively narrow the gap in stages. 616 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 617 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 618 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 619 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 620 621 setOperationAction(ISD::SADDSAT, VT, Legal); 622 setOperationAction(ISD::UADDSAT, VT, Legal); 623 setOperationAction(ISD::SSUBSAT, VT, Legal); 624 setOperationAction(ISD::USUBSAT, VT, Legal); 625 626 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 627 // nodes which truncate by one power of two at a time. 628 setOperationAction(ISD::TRUNCATE, VT, Custom); 629 630 // Custom-lower insert/extract operations to simplify patterns. 631 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 632 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 633 634 // Custom-lower reduction operations to set up the corresponding custom 635 // nodes' operands. 636 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 637 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 638 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 639 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 640 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 641 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 642 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 643 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 644 645 for (unsigned VPOpc : IntegerVPOps) 646 setOperationAction(VPOpc, VT, Custom); 647 648 setOperationAction(ISD::LOAD, VT, Custom); 649 setOperationAction(ISD::STORE, VT, Custom); 650 651 setOperationAction(ISD::MLOAD, VT, Custom); 652 setOperationAction(ISD::MSTORE, VT, Custom); 653 setOperationAction(ISD::MGATHER, VT, Custom); 654 setOperationAction(ISD::MSCATTER, VT, Custom); 655 656 setOperationAction(ISD::VP_LOAD, VT, Custom); 657 setOperationAction(ISD::VP_STORE, VT, Custom); 658 setOperationAction(ISD::VP_GATHER, VT, Custom); 659 setOperationAction(ISD::VP_SCATTER, VT, Custom); 660 661 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 662 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 663 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 664 665 setOperationAction(ISD::SELECT, VT, Custom); 666 setOperationAction(ISD::SELECT_CC, VT, Expand); 667 668 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 669 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 670 671 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 672 setTruncStoreAction(VT, OtherVT, Expand); 673 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 674 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 675 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 676 } 677 678 // Splice 679 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 680 681 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 682 // type that can represent the value exactly. 683 if (VT.getVectorElementType() != MVT::i64) { 684 MVT FloatEltVT = 685 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 686 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 687 if (isTypeLegal(FloatVT)) { 688 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 689 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 690 } 691 } 692 } 693 694 // Expand various CCs to best match the RVV ISA, which natively supports UNE 695 // but no other unordered comparisons, and supports all ordered comparisons 696 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 697 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 698 // and we pattern-match those back to the "original", swapping operands once 699 // more. This way we catch both operations and both "vf" and "fv" forms with 700 // fewer patterns. 701 static const ISD::CondCode VFPCCToExpand[] = { 702 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 703 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 704 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 705 }; 706 707 // Sets common operation actions on RVV floating-point vector types. 708 const auto SetCommonVFPActions = [&](MVT VT) { 709 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 710 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 711 // sizes are within one power-of-two of each other. Therefore conversions 712 // between vXf16 and vXf64 must be lowered as sequences which convert via 713 // vXf32. 714 setOperationAction(ISD::FP_ROUND, VT, Custom); 715 setOperationAction(ISD::FP_EXTEND, VT, Custom); 716 // Custom-lower insert/extract operations to simplify patterns. 717 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 718 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 719 // Expand various condition codes (explained above). 720 for (auto CC : VFPCCToExpand) 721 setCondCodeAction(CC, VT, Expand); 722 723 setOperationAction(ISD::FMINNUM, VT, Legal); 724 setOperationAction(ISD::FMAXNUM, VT, Legal); 725 726 setOperationAction(ISD::FTRUNC, VT, Custom); 727 setOperationAction(ISD::FCEIL, VT, Custom); 728 setOperationAction(ISD::FFLOOR, VT, Custom); 729 setOperationAction(ISD::FROUND, VT, Custom); 730 731 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 732 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 733 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 734 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 735 736 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 737 738 setOperationAction(ISD::LOAD, VT, Custom); 739 setOperationAction(ISD::STORE, VT, Custom); 740 741 setOperationAction(ISD::MLOAD, VT, Custom); 742 setOperationAction(ISD::MSTORE, VT, Custom); 743 setOperationAction(ISD::MGATHER, VT, Custom); 744 setOperationAction(ISD::MSCATTER, VT, Custom); 745 746 setOperationAction(ISD::VP_LOAD, VT, Custom); 747 setOperationAction(ISD::VP_STORE, VT, Custom); 748 setOperationAction(ISD::VP_GATHER, VT, Custom); 749 setOperationAction(ISD::VP_SCATTER, VT, Custom); 750 751 setOperationAction(ISD::SELECT, VT, Custom); 752 setOperationAction(ISD::SELECT_CC, VT, Expand); 753 754 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 755 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 756 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 757 758 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 759 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 760 761 for (unsigned VPOpc : FloatingPointVPOps) 762 setOperationAction(VPOpc, VT, Custom); 763 }; 764 765 // Sets common extload/truncstore actions on RVV floating-point vector 766 // types. 767 const auto SetCommonVFPExtLoadTruncStoreActions = 768 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 769 for (auto SmallVT : SmallerVTs) { 770 setTruncStoreAction(VT, SmallVT, Expand); 771 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 772 } 773 }; 774 775 if (Subtarget.hasVInstructionsF16()) 776 for (MVT VT : F16VecVTs) 777 SetCommonVFPActions(VT); 778 779 for (MVT VT : F32VecVTs) { 780 if (Subtarget.hasVInstructionsF32()) 781 SetCommonVFPActions(VT); 782 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 783 } 784 785 for (MVT VT : F64VecVTs) { 786 if (Subtarget.hasVInstructionsF64()) 787 SetCommonVFPActions(VT); 788 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 789 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 790 } 791 792 if (Subtarget.useRVVForFixedLengthVectors()) { 793 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 794 if (!useRVVForFixedLengthVectorVT(VT)) 795 continue; 796 797 // By default everything must be expanded. 798 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 799 setOperationAction(Op, VT, Expand); 800 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 801 setTruncStoreAction(VT, OtherVT, Expand); 802 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 803 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 804 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 805 } 806 807 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 808 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 809 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 810 811 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 812 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 813 814 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 815 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 816 817 setOperationAction(ISD::LOAD, VT, Custom); 818 setOperationAction(ISD::STORE, VT, Custom); 819 820 setOperationAction(ISD::SETCC, VT, Custom); 821 822 setOperationAction(ISD::SELECT, VT, Custom); 823 824 setOperationAction(ISD::TRUNCATE, VT, Custom); 825 826 setOperationAction(ISD::BITCAST, VT, Custom); 827 828 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 829 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 830 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 831 832 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 833 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 834 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 835 836 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 837 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 838 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 839 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 840 841 // Operations below are different for between masks and other vectors. 842 if (VT.getVectorElementType() == MVT::i1) { 843 setOperationAction(ISD::VP_AND, VT, Custom); 844 setOperationAction(ISD::VP_OR, VT, Custom); 845 setOperationAction(ISD::VP_XOR, VT, Custom); 846 setOperationAction(ISD::AND, VT, Custom); 847 setOperationAction(ISD::OR, VT, Custom); 848 setOperationAction(ISD::XOR, VT, Custom); 849 continue; 850 } 851 852 // Use SPLAT_VECTOR to prevent type legalization from destroying the 853 // splats when type legalizing i64 scalar on RV32. 854 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 855 // improvements first. 856 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 857 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 858 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 859 } 860 861 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 862 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 863 864 setOperationAction(ISD::MLOAD, VT, Custom); 865 setOperationAction(ISD::MSTORE, VT, Custom); 866 setOperationAction(ISD::MGATHER, VT, Custom); 867 setOperationAction(ISD::MSCATTER, VT, Custom); 868 869 setOperationAction(ISD::VP_LOAD, VT, Custom); 870 setOperationAction(ISD::VP_STORE, VT, Custom); 871 setOperationAction(ISD::VP_GATHER, VT, Custom); 872 setOperationAction(ISD::VP_SCATTER, VT, Custom); 873 874 setOperationAction(ISD::ADD, VT, Custom); 875 setOperationAction(ISD::MUL, VT, Custom); 876 setOperationAction(ISD::SUB, VT, Custom); 877 setOperationAction(ISD::AND, VT, Custom); 878 setOperationAction(ISD::OR, VT, Custom); 879 setOperationAction(ISD::XOR, VT, Custom); 880 setOperationAction(ISD::SDIV, VT, Custom); 881 setOperationAction(ISD::SREM, VT, Custom); 882 setOperationAction(ISD::UDIV, VT, Custom); 883 setOperationAction(ISD::UREM, VT, Custom); 884 setOperationAction(ISD::SHL, VT, Custom); 885 setOperationAction(ISD::SRA, VT, Custom); 886 setOperationAction(ISD::SRL, VT, Custom); 887 888 setOperationAction(ISD::SMIN, VT, Custom); 889 setOperationAction(ISD::SMAX, VT, Custom); 890 setOperationAction(ISD::UMIN, VT, Custom); 891 setOperationAction(ISD::UMAX, VT, Custom); 892 setOperationAction(ISD::ABS, VT, Custom); 893 894 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 895 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 896 setOperationAction(ISD::MULHS, VT, Custom); 897 setOperationAction(ISD::MULHU, VT, Custom); 898 } 899 900 setOperationAction(ISD::SADDSAT, VT, Custom); 901 setOperationAction(ISD::UADDSAT, VT, Custom); 902 setOperationAction(ISD::SSUBSAT, VT, Custom); 903 setOperationAction(ISD::USUBSAT, VT, Custom); 904 905 setOperationAction(ISD::VSELECT, VT, Custom); 906 setOperationAction(ISD::SELECT_CC, VT, Expand); 907 908 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 909 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 910 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 911 912 // Custom-lower reduction operations to set up the corresponding custom 913 // nodes' operands. 914 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 915 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 916 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 917 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 918 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 919 920 for (unsigned VPOpc : IntegerVPOps) 921 setOperationAction(VPOpc, VT, Custom); 922 923 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 924 // type that can represent the value exactly. 925 if (VT.getVectorElementType() != MVT::i64) { 926 MVT FloatEltVT = 927 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 928 EVT FloatVT = 929 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 930 if (isTypeLegal(FloatVT)) { 931 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 932 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 933 } 934 } 935 } 936 937 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 938 if (!useRVVForFixedLengthVectorVT(VT)) 939 continue; 940 941 // By default everything must be expanded. 942 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 943 setOperationAction(Op, VT, Expand); 944 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 945 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 946 setTruncStoreAction(VT, OtherVT, Expand); 947 } 948 949 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 950 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 951 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 952 953 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 954 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 955 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 956 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 957 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 958 959 setOperationAction(ISD::LOAD, VT, Custom); 960 setOperationAction(ISD::STORE, VT, Custom); 961 setOperationAction(ISD::MLOAD, VT, Custom); 962 setOperationAction(ISD::MSTORE, VT, Custom); 963 setOperationAction(ISD::MGATHER, VT, Custom); 964 setOperationAction(ISD::MSCATTER, VT, Custom); 965 966 setOperationAction(ISD::VP_LOAD, VT, Custom); 967 setOperationAction(ISD::VP_STORE, VT, Custom); 968 setOperationAction(ISD::VP_GATHER, VT, Custom); 969 setOperationAction(ISD::VP_SCATTER, VT, Custom); 970 971 setOperationAction(ISD::FADD, VT, Custom); 972 setOperationAction(ISD::FSUB, VT, Custom); 973 setOperationAction(ISD::FMUL, VT, Custom); 974 setOperationAction(ISD::FDIV, VT, Custom); 975 setOperationAction(ISD::FNEG, VT, Custom); 976 setOperationAction(ISD::FABS, VT, Custom); 977 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 978 setOperationAction(ISD::FSQRT, VT, Custom); 979 setOperationAction(ISD::FMA, VT, Custom); 980 setOperationAction(ISD::FMINNUM, VT, Custom); 981 setOperationAction(ISD::FMAXNUM, VT, Custom); 982 983 setOperationAction(ISD::FP_ROUND, VT, Custom); 984 setOperationAction(ISD::FP_EXTEND, VT, Custom); 985 986 setOperationAction(ISD::FTRUNC, VT, Custom); 987 setOperationAction(ISD::FCEIL, VT, Custom); 988 setOperationAction(ISD::FFLOOR, VT, Custom); 989 setOperationAction(ISD::FROUND, VT, Custom); 990 991 for (auto CC : VFPCCToExpand) 992 setCondCodeAction(CC, VT, Expand); 993 994 setOperationAction(ISD::VSELECT, VT, Custom); 995 setOperationAction(ISD::SELECT, VT, Custom); 996 setOperationAction(ISD::SELECT_CC, VT, Expand); 997 998 setOperationAction(ISD::BITCAST, VT, Custom); 999 1000 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1001 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1002 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1003 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1004 1005 for (unsigned VPOpc : FloatingPointVPOps) 1006 setOperationAction(VPOpc, VT, Custom); 1007 } 1008 1009 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1010 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1011 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1012 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1013 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1014 if (Subtarget.hasStdExtZfh()) 1015 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1016 if (Subtarget.hasStdExtF()) 1017 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1018 if (Subtarget.hasStdExtD()) 1019 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1020 } 1021 } 1022 1023 // Function alignments. 1024 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1025 setMinFunctionAlignment(FunctionAlignment); 1026 setPrefFunctionAlignment(FunctionAlignment); 1027 1028 setMinimumJumpTableEntries(5); 1029 1030 // Jumps are expensive, compared to logic 1031 setJumpIsExpensive(); 1032 1033 setTargetDAGCombine(ISD::ADD); 1034 setTargetDAGCombine(ISD::SUB); 1035 setTargetDAGCombine(ISD::AND); 1036 setTargetDAGCombine(ISD::OR); 1037 setTargetDAGCombine(ISD::XOR); 1038 if (Subtarget.hasStdExtZbp()) { 1039 setTargetDAGCombine(ISD::ROTL); 1040 setTargetDAGCombine(ISD::ROTR); 1041 } 1042 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1043 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 1044 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 1045 if (Subtarget.hasStdExtF()) { 1046 setTargetDAGCombine(ISD::ZERO_EXTEND); 1047 setTargetDAGCombine(ISD::FP_TO_SINT); 1048 setTargetDAGCombine(ISD::FP_TO_UINT); 1049 setTargetDAGCombine(ISD::FP_TO_SINT_SAT); 1050 setTargetDAGCombine(ISD::FP_TO_UINT_SAT); 1051 } 1052 if (Subtarget.hasVInstructions()) { 1053 setTargetDAGCombine(ISD::FCOPYSIGN); 1054 setTargetDAGCombine(ISD::MGATHER); 1055 setTargetDAGCombine(ISD::MSCATTER); 1056 setTargetDAGCombine(ISD::VP_GATHER); 1057 setTargetDAGCombine(ISD::VP_SCATTER); 1058 setTargetDAGCombine(ISD::SRA); 1059 setTargetDAGCombine(ISD::SRL); 1060 setTargetDAGCombine(ISD::SHL); 1061 setTargetDAGCombine(ISD::STORE); 1062 setTargetDAGCombine(ISD::SPLAT_VECTOR); 1063 } 1064 1065 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1066 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1067 } 1068 1069 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1070 LLVMContext &Context, 1071 EVT VT) const { 1072 if (!VT.isVector()) 1073 return getPointerTy(DL); 1074 if (Subtarget.hasVInstructions() && 1075 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1076 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1077 return VT.changeVectorElementTypeToInteger(); 1078 } 1079 1080 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1081 return Subtarget.getXLenVT(); 1082 } 1083 1084 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1085 const CallInst &I, 1086 MachineFunction &MF, 1087 unsigned Intrinsic) const { 1088 auto &DL = I.getModule()->getDataLayout(); 1089 switch (Intrinsic) { 1090 default: 1091 return false; 1092 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1093 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1094 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1095 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1096 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1097 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1098 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1099 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1100 case Intrinsic::riscv_masked_cmpxchg_i32: 1101 Info.opc = ISD::INTRINSIC_W_CHAIN; 1102 Info.memVT = MVT::i32; 1103 Info.ptrVal = I.getArgOperand(0); 1104 Info.offset = 0; 1105 Info.align = Align(4); 1106 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1107 MachineMemOperand::MOVolatile; 1108 return true; 1109 case Intrinsic::riscv_masked_strided_load: 1110 Info.opc = ISD::INTRINSIC_W_CHAIN; 1111 Info.ptrVal = I.getArgOperand(1); 1112 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1113 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1114 Info.size = MemoryLocation::UnknownSize; 1115 Info.flags |= MachineMemOperand::MOLoad; 1116 return true; 1117 case Intrinsic::riscv_masked_strided_store: 1118 Info.opc = ISD::INTRINSIC_VOID; 1119 Info.ptrVal = I.getArgOperand(1); 1120 Info.memVT = 1121 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1122 Info.align = Align( 1123 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1124 8); 1125 Info.size = MemoryLocation::UnknownSize; 1126 Info.flags |= MachineMemOperand::MOStore; 1127 return true; 1128 case Intrinsic::riscv_seg2_load: 1129 case Intrinsic::riscv_seg3_load: 1130 case Intrinsic::riscv_seg4_load: 1131 case Intrinsic::riscv_seg5_load: 1132 case Intrinsic::riscv_seg6_load: 1133 case Intrinsic::riscv_seg7_load: 1134 case Intrinsic::riscv_seg8_load: 1135 Info.opc = ISD::INTRINSIC_W_CHAIN; 1136 Info.ptrVal = I.getArgOperand(0); 1137 Info.memVT = 1138 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1139 Info.align = 1140 Align(DL.getTypeSizeInBits( 1141 I.getType()->getStructElementType(0)->getScalarType()) / 1142 8); 1143 Info.size = MemoryLocation::UnknownSize; 1144 Info.flags |= MachineMemOperand::MOLoad; 1145 return true; 1146 } 1147 } 1148 1149 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1150 const AddrMode &AM, Type *Ty, 1151 unsigned AS, 1152 Instruction *I) const { 1153 // No global is ever allowed as a base. 1154 if (AM.BaseGV) 1155 return false; 1156 1157 // Require a 12-bit signed offset. 1158 if (!isInt<12>(AM.BaseOffs)) 1159 return false; 1160 1161 switch (AM.Scale) { 1162 case 0: // "r+i" or just "i", depending on HasBaseReg. 1163 break; 1164 case 1: 1165 if (!AM.HasBaseReg) // allow "r+i". 1166 break; 1167 return false; // disallow "r+r" or "r+r+i". 1168 default: 1169 return false; 1170 } 1171 1172 return true; 1173 } 1174 1175 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1176 return isInt<12>(Imm); 1177 } 1178 1179 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1180 return isInt<12>(Imm); 1181 } 1182 1183 // On RV32, 64-bit integers are split into their high and low parts and held 1184 // in two different registers, so the trunc is free since the low register can 1185 // just be used. 1186 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1187 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1188 return false; 1189 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1190 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1191 return (SrcBits == 64 && DestBits == 32); 1192 } 1193 1194 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1195 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1196 !SrcVT.isInteger() || !DstVT.isInteger()) 1197 return false; 1198 unsigned SrcBits = SrcVT.getSizeInBits(); 1199 unsigned DestBits = DstVT.getSizeInBits(); 1200 return (SrcBits == 64 && DestBits == 32); 1201 } 1202 1203 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1204 // Zexts are free if they can be combined with a load. 1205 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1206 // poorly with type legalization of compares preferring sext. 1207 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1208 EVT MemVT = LD->getMemoryVT(); 1209 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1210 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1211 LD->getExtensionType() == ISD::ZEXTLOAD)) 1212 return true; 1213 } 1214 1215 return TargetLowering::isZExtFree(Val, VT2); 1216 } 1217 1218 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1219 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1220 } 1221 1222 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1223 return Subtarget.hasStdExtZbb(); 1224 } 1225 1226 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1227 return Subtarget.hasStdExtZbb(); 1228 } 1229 1230 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1231 EVT VT = Y.getValueType(); 1232 1233 // FIXME: Support vectors once we have tests. 1234 if (VT.isVector()) 1235 return false; 1236 1237 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1238 Subtarget.hasStdExtZbkb()) && 1239 !isa<ConstantSDNode>(Y); 1240 } 1241 1242 /// Check if sinking \p I's operands to I's basic block is profitable, because 1243 /// the operands can be folded into a target instruction, e.g. 1244 /// splats of scalars can fold into vector instructions. 1245 bool RISCVTargetLowering::shouldSinkOperands( 1246 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1247 using namespace llvm::PatternMatch; 1248 1249 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1250 return false; 1251 1252 auto IsSinker = [&](Instruction *I, int Operand) { 1253 switch (I->getOpcode()) { 1254 case Instruction::Add: 1255 case Instruction::Sub: 1256 case Instruction::Mul: 1257 case Instruction::And: 1258 case Instruction::Or: 1259 case Instruction::Xor: 1260 case Instruction::FAdd: 1261 case Instruction::FSub: 1262 case Instruction::FMul: 1263 case Instruction::FDiv: 1264 case Instruction::ICmp: 1265 case Instruction::FCmp: 1266 return true; 1267 case Instruction::Shl: 1268 case Instruction::LShr: 1269 case Instruction::AShr: 1270 case Instruction::UDiv: 1271 case Instruction::SDiv: 1272 case Instruction::URem: 1273 case Instruction::SRem: 1274 return Operand == 1; 1275 case Instruction::Call: 1276 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1277 switch (II->getIntrinsicID()) { 1278 case Intrinsic::fma: 1279 case Intrinsic::vp_fma: 1280 return Operand == 0 || Operand == 1; 1281 // FIXME: Our patterns can only match vx/vf instructions when the splat 1282 // it on the RHS, because TableGen doesn't recognize our VP operations 1283 // as commutative. 1284 case Intrinsic::vp_add: 1285 case Intrinsic::vp_mul: 1286 case Intrinsic::vp_and: 1287 case Intrinsic::vp_or: 1288 case Intrinsic::vp_xor: 1289 case Intrinsic::vp_fadd: 1290 case Intrinsic::vp_fmul: 1291 case Intrinsic::vp_shl: 1292 case Intrinsic::vp_lshr: 1293 case Intrinsic::vp_ashr: 1294 case Intrinsic::vp_udiv: 1295 case Intrinsic::vp_sdiv: 1296 case Intrinsic::vp_urem: 1297 case Intrinsic::vp_srem: 1298 return Operand == 1; 1299 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1300 // explicit patterns for both LHS and RHS (as 'vr' versions). 1301 case Intrinsic::vp_sub: 1302 case Intrinsic::vp_fsub: 1303 case Intrinsic::vp_fdiv: 1304 return Operand == 0 || Operand == 1; 1305 default: 1306 return false; 1307 } 1308 } 1309 return false; 1310 default: 1311 return false; 1312 } 1313 }; 1314 1315 for (auto OpIdx : enumerate(I->operands())) { 1316 if (!IsSinker(I, OpIdx.index())) 1317 continue; 1318 1319 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1320 // Make sure we are not already sinking this operand 1321 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1322 continue; 1323 1324 // We are looking for a splat that can be sunk. 1325 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1326 m_Undef(), m_ZeroMask()))) 1327 continue; 1328 1329 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1330 // and vector registers 1331 for (Use &U : Op->uses()) { 1332 Instruction *Insn = cast<Instruction>(U.getUser()); 1333 if (!IsSinker(Insn, U.getOperandNo())) 1334 return false; 1335 } 1336 1337 Ops.push_back(&Op->getOperandUse(0)); 1338 Ops.push_back(&OpIdx.value()); 1339 } 1340 return true; 1341 } 1342 1343 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1344 bool ForCodeSize) const { 1345 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1346 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1347 return false; 1348 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1349 return false; 1350 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1351 return false; 1352 return Imm.isZero(); 1353 } 1354 1355 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1356 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1357 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1358 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1359 } 1360 1361 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1362 CallingConv::ID CC, 1363 EVT VT) const { 1364 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1365 // We might still end up using a GPR but that will be decided based on ABI. 1366 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1367 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1368 return MVT::f32; 1369 1370 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1371 } 1372 1373 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1374 CallingConv::ID CC, 1375 EVT VT) const { 1376 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1377 // We might still end up using a GPR but that will be decided based on ABI. 1378 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1379 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1380 return 1; 1381 1382 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1383 } 1384 1385 // Changes the condition code and swaps operands if necessary, so the SetCC 1386 // operation matches one of the comparisons supported directly by branches 1387 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1388 // with 1/-1. 1389 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1390 ISD::CondCode &CC, SelectionDAG &DAG) { 1391 // Convert X > -1 to X >= 0. 1392 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1393 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1394 CC = ISD::SETGE; 1395 return; 1396 } 1397 // Convert X < 1 to 0 >= X. 1398 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1399 RHS = LHS; 1400 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1401 CC = ISD::SETGE; 1402 return; 1403 } 1404 1405 switch (CC) { 1406 default: 1407 break; 1408 case ISD::SETGT: 1409 case ISD::SETLE: 1410 case ISD::SETUGT: 1411 case ISD::SETULE: 1412 CC = ISD::getSetCCSwappedOperands(CC); 1413 std::swap(LHS, RHS); 1414 break; 1415 } 1416 } 1417 1418 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1419 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1420 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1421 if (VT.getVectorElementType() == MVT::i1) 1422 KnownSize *= 8; 1423 1424 switch (KnownSize) { 1425 default: 1426 llvm_unreachable("Invalid LMUL."); 1427 case 8: 1428 return RISCVII::VLMUL::LMUL_F8; 1429 case 16: 1430 return RISCVII::VLMUL::LMUL_F4; 1431 case 32: 1432 return RISCVII::VLMUL::LMUL_F2; 1433 case 64: 1434 return RISCVII::VLMUL::LMUL_1; 1435 case 128: 1436 return RISCVII::VLMUL::LMUL_2; 1437 case 256: 1438 return RISCVII::VLMUL::LMUL_4; 1439 case 512: 1440 return RISCVII::VLMUL::LMUL_8; 1441 } 1442 } 1443 1444 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1445 switch (LMul) { 1446 default: 1447 llvm_unreachable("Invalid LMUL."); 1448 case RISCVII::VLMUL::LMUL_F8: 1449 case RISCVII::VLMUL::LMUL_F4: 1450 case RISCVII::VLMUL::LMUL_F2: 1451 case RISCVII::VLMUL::LMUL_1: 1452 return RISCV::VRRegClassID; 1453 case RISCVII::VLMUL::LMUL_2: 1454 return RISCV::VRM2RegClassID; 1455 case RISCVII::VLMUL::LMUL_4: 1456 return RISCV::VRM4RegClassID; 1457 case RISCVII::VLMUL::LMUL_8: 1458 return RISCV::VRM8RegClassID; 1459 } 1460 } 1461 1462 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1463 RISCVII::VLMUL LMUL = getLMUL(VT); 1464 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1465 LMUL == RISCVII::VLMUL::LMUL_F4 || 1466 LMUL == RISCVII::VLMUL::LMUL_F2 || 1467 LMUL == RISCVII::VLMUL::LMUL_1) { 1468 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1469 "Unexpected subreg numbering"); 1470 return RISCV::sub_vrm1_0 + Index; 1471 } 1472 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1473 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1474 "Unexpected subreg numbering"); 1475 return RISCV::sub_vrm2_0 + Index; 1476 } 1477 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1478 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1479 "Unexpected subreg numbering"); 1480 return RISCV::sub_vrm4_0 + Index; 1481 } 1482 llvm_unreachable("Invalid vector type."); 1483 } 1484 1485 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1486 if (VT.getVectorElementType() == MVT::i1) 1487 return RISCV::VRRegClassID; 1488 return getRegClassIDForLMUL(getLMUL(VT)); 1489 } 1490 1491 // Attempt to decompose a subvector insert/extract between VecVT and 1492 // SubVecVT via subregister indices. Returns the subregister index that 1493 // can perform the subvector insert/extract with the given element index, as 1494 // well as the index corresponding to any leftover subvectors that must be 1495 // further inserted/extracted within the register class for SubVecVT. 1496 std::pair<unsigned, unsigned> 1497 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1498 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1499 const RISCVRegisterInfo *TRI) { 1500 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1501 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1502 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1503 "Register classes not ordered"); 1504 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1505 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1506 // Try to compose a subregister index that takes us from the incoming 1507 // LMUL>1 register class down to the outgoing one. At each step we half 1508 // the LMUL: 1509 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1510 // Note that this is not guaranteed to find a subregister index, such as 1511 // when we are extracting from one VR type to another. 1512 unsigned SubRegIdx = RISCV::NoSubRegister; 1513 for (const unsigned RCID : 1514 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1515 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1516 VecVT = VecVT.getHalfNumVectorElementsVT(); 1517 bool IsHi = 1518 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1519 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1520 getSubregIndexByMVT(VecVT, IsHi)); 1521 if (IsHi) 1522 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1523 } 1524 return {SubRegIdx, InsertExtractIdx}; 1525 } 1526 1527 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1528 // stores for those types. 1529 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1530 return !Subtarget.useRVVForFixedLengthVectors() || 1531 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1532 } 1533 1534 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1535 if (ScalarTy->isPointerTy()) 1536 return true; 1537 1538 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1539 ScalarTy->isIntegerTy(32)) 1540 return true; 1541 1542 if (ScalarTy->isIntegerTy(64)) 1543 return Subtarget.hasVInstructionsI64(); 1544 1545 if (ScalarTy->isHalfTy()) 1546 return Subtarget.hasVInstructionsF16(); 1547 if (ScalarTy->isFloatTy()) 1548 return Subtarget.hasVInstructionsF32(); 1549 if (ScalarTy->isDoubleTy()) 1550 return Subtarget.hasVInstructionsF64(); 1551 1552 return false; 1553 } 1554 1555 static SDValue getVLOperand(SDValue Op) { 1556 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1557 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1558 "Unexpected opcode"); 1559 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1560 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1561 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1562 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1563 if (!II) 1564 return SDValue(); 1565 return Op.getOperand(II->VLOperand + 1 + HasChain); 1566 } 1567 1568 static bool useRVVForFixedLengthVectorVT(MVT VT, 1569 const RISCVSubtarget &Subtarget) { 1570 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1571 if (!Subtarget.useRVVForFixedLengthVectors()) 1572 return false; 1573 1574 // We only support a set of vector types with a consistent maximum fixed size 1575 // across all supported vector element types to avoid legalization issues. 1576 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1577 // fixed-length vector type we support is 1024 bytes. 1578 if (VT.getFixedSizeInBits() > 1024 * 8) 1579 return false; 1580 1581 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1582 1583 MVT EltVT = VT.getVectorElementType(); 1584 1585 // Don't use RVV for vectors we cannot scalarize if required. 1586 switch (EltVT.SimpleTy) { 1587 // i1 is supported but has different rules. 1588 default: 1589 return false; 1590 case MVT::i1: 1591 // Masks can only use a single register. 1592 if (VT.getVectorNumElements() > MinVLen) 1593 return false; 1594 MinVLen /= 8; 1595 break; 1596 case MVT::i8: 1597 case MVT::i16: 1598 case MVT::i32: 1599 break; 1600 case MVT::i64: 1601 if (!Subtarget.hasVInstructionsI64()) 1602 return false; 1603 break; 1604 case MVT::f16: 1605 if (!Subtarget.hasVInstructionsF16()) 1606 return false; 1607 break; 1608 case MVT::f32: 1609 if (!Subtarget.hasVInstructionsF32()) 1610 return false; 1611 break; 1612 case MVT::f64: 1613 if (!Subtarget.hasVInstructionsF64()) 1614 return false; 1615 break; 1616 } 1617 1618 // Reject elements larger than ELEN. 1619 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1620 return false; 1621 1622 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1623 // Don't use RVV for types that don't fit. 1624 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1625 return false; 1626 1627 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1628 // the base fixed length RVV support in place. 1629 if (!VT.isPow2VectorType()) 1630 return false; 1631 1632 return true; 1633 } 1634 1635 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1636 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1637 } 1638 1639 // Return the largest legal scalable vector type that matches VT's element type. 1640 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1641 const RISCVSubtarget &Subtarget) { 1642 // This may be called before legal types are setup. 1643 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1644 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1645 "Expected legal fixed length vector!"); 1646 1647 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1648 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1649 1650 MVT EltVT = VT.getVectorElementType(); 1651 switch (EltVT.SimpleTy) { 1652 default: 1653 llvm_unreachable("unexpected element type for RVV container"); 1654 case MVT::i1: 1655 case MVT::i8: 1656 case MVT::i16: 1657 case MVT::i32: 1658 case MVT::i64: 1659 case MVT::f16: 1660 case MVT::f32: 1661 case MVT::f64: { 1662 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1663 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1664 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1665 unsigned NumElts = 1666 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1667 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1668 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1669 return MVT::getScalableVectorVT(EltVT, NumElts); 1670 } 1671 } 1672 } 1673 1674 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1675 const RISCVSubtarget &Subtarget) { 1676 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1677 Subtarget); 1678 } 1679 1680 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1681 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1682 } 1683 1684 // Grow V to consume an entire RVV register. 1685 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1686 const RISCVSubtarget &Subtarget) { 1687 assert(VT.isScalableVector() && 1688 "Expected to convert into a scalable vector!"); 1689 assert(V.getValueType().isFixedLengthVector() && 1690 "Expected a fixed length vector operand!"); 1691 SDLoc DL(V); 1692 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1693 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1694 } 1695 1696 // Shrink V so it's just big enough to maintain a VT's worth of data. 1697 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1698 const RISCVSubtarget &Subtarget) { 1699 assert(VT.isFixedLengthVector() && 1700 "Expected to convert into a fixed length vector!"); 1701 assert(V.getValueType().isScalableVector() && 1702 "Expected a scalable vector operand!"); 1703 SDLoc DL(V); 1704 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1705 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1706 } 1707 1708 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1709 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1710 // the vector type that it is contained in. 1711 static std::pair<SDValue, SDValue> 1712 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1713 const RISCVSubtarget &Subtarget) { 1714 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1715 MVT XLenVT = Subtarget.getXLenVT(); 1716 SDValue VL = VecVT.isFixedLengthVector() 1717 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1718 : DAG.getRegister(RISCV::X0, XLenVT); 1719 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1720 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1721 return {Mask, VL}; 1722 } 1723 1724 // As above but assuming the given type is a scalable vector type. 1725 static std::pair<SDValue, SDValue> 1726 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1727 const RISCVSubtarget &Subtarget) { 1728 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1729 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1730 } 1731 1732 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1733 // of either is (currently) supported. This can get us into an infinite loop 1734 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1735 // as a ..., etc. 1736 // Until either (or both) of these can reliably lower any node, reporting that 1737 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1738 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1739 // which is not desirable. 1740 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1741 EVT VT, unsigned DefinedValues) const { 1742 return false; 1743 } 1744 1745 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1746 const RISCVSubtarget &Subtarget) { 1747 // RISCV FP-to-int conversions saturate to the destination register size, but 1748 // don't produce 0 for nan. We can use a conversion instruction and fix the 1749 // nan case with a compare and a select. 1750 SDValue Src = Op.getOperand(0); 1751 1752 EVT DstVT = Op.getValueType(); 1753 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1754 1755 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1756 unsigned Opc; 1757 if (SatVT == DstVT) 1758 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1759 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1760 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1761 else 1762 return SDValue(); 1763 // FIXME: Support other SatVTs by clamping before or after the conversion. 1764 1765 SDLoc DL(Op); 1766 SDValue FpToInt = DAG.getNode( 1767 Opc, DL, DstVT, Src, 1768 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1769 1770 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1771 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1772 } 1773 1774 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1775 // and back. Taking care to avoid converting values that are nan or already 1776 // correct. 1777 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1778 // have FRM dependencies modeled yet. 1779 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1780 MVT VT = Op.getSimpleValueType(); 1781 assert(VT.isVector() && "Unexpected type"); 1782 1783 SDLoc DL(Op); 1784 1785 // Freeze the source since we are increasing the number of uses. 1786 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1787 1788 // Truncate to integer and convert back to FP. 1789 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1790 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1791 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1792 1793 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1794 1795 if (Op.getOpcode() == ISD::FCEIL) { 1796 // If the truncated value is the greater than or equal to the original 1797 // value, we've computed the ceil. Otherwise, we went the wrong way and 1798 // need to increase by 1. 1799 // FIXME: This should use a masked operation. Handle here or in isel? 1800 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1801 DAG.getConstantFP(1.0, DL, VT)); 1802 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1803 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1804 } else if (Op.getOpcode() == ISD::FFLOOR) { 1805 // If the truncated value is the less than or equal to the original value, 1806 // we've computed the floor. Otherwise, we went the wrong way and need to 1807 // decrease by 1. 1808 // FIXME: This should use a masked operation. Handle here or in isel? 1809 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1810 DAG.getConstantFP(1.0, DL, VT)); 1811 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1812 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1813 } 1814 1815 // Restore the original sign so that -0.0 is preserved. 1816 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1817 1818 // Determine the largest integer that can be represented exactly. This and 1819 // values larger than it don't have any fractional bits so don't need to 1820 // be converted. 1821 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1822 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1823 APFloat MaxVal = APFloat(FltSem); 1824 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1825 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1826 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1827 1828 // If abs(Src) was larger than MaxVal or nan, keep it. 1829 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1830 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1831 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1832 } 1833 1834 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1835 // This mode isn't supported in vector hardware on RISCV. But as long as we 1836 // aren't compiling with trapping math, we can emulate this with 1837 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1838 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1839 // dependencies modeled yet. 1840 // FIXME: Use masked operations to avoid final merge. 1841 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1842 MVT VT = Op.getSimpleValueType(); 1843 assert(VT.isVector() && "Unexpected type"); 1844 1845 SDLoc DL(Op); 1846 1847 // Freeze the source since we are increasing the number of uses. 1848 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1849 1850 // We do the conversion on the absolute value and fix the sign at the end. 1851 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1852 1853 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1854 bool Ignored; 1855 APFloat Point5Pred = APFloat(0.5f); 1856 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1857 Point5Pred.next(/*nextDown*/ true); 1858 1859 // Add the adjustment. 1860 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1861 DAG.getConstantFP(Point5Pred, DL, VT)); 1862 1863 // Truncate to integer and convert back to fp. 1864 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1865 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1866 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1867 1868 // Restore the original sign. 1869 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1870 1871 // Determine the largest integer that can be represented exactly. This and 1872 // values larger than it don't have any fractional bits so don't need to 1873 // be converted. 1874 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1875 APFloat MaxVal = APFloat(FltSem); 1876 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1877 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1878 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1879 1880 // If abs(Src) was larger than MaxVal or nan, keep it. 1881 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1882 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1883 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1884 } 1885 1886 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1887 const RISCVSubtarget &Subtarget) { 1888 MVT VT = Op.getSimpleValueType(); 1889 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1890 1891 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1892 1893 SDLoc DL(Op); 1894 SDValue Mask, VL; 1895 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1896 1897 unsigned Opc = 1898 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1899 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 1900 Op.getOperand(0), VL); 1901 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1902 } 1903 1904 struct VIDSequence { 1905 int64_t StepNumerator; 1906 unsigned StepDenominator; 1907 int64_t Addend; 1908 }; 1909 1910 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1911 // to the (non-zero) step S and start value X. This can be then lowered as the 1912 // RVV sequence (VID * S) + X, for example. 1913 // The step S is represented as an integer numerator divided by a positive 1914 // denominator. Note that the implementation currently only identifies 1915 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1916 // cannot detect 2/3, for example. 1917 // Note that this method will also match potentially unappealing index 1918 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1919 // determine whether this is worth generating code for. 1920 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1921 unsigned NumElts = Op.getNumOperands(); 1922 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1923 if (!Op.getValueType().isInteger()) 1924 return None; 1925 1926 Optional<unsigned> SeqStepDenom; 1927 Optional<int64_t> SeqStepNum, SeqAddend; 1928 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1929 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1930 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1931 // Assume undef elements match the sequence; we just have to be careful 1932 // when interpolating across them. 1933 if (Op.getOperand(Idx).isUndef()) 1934 continue; 1935 // The BUILD_VECTOR must be all constants. 1936 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1937 return None; 1938 1939 uint64_t Val = Op.getConstantOperandVal(Idx) & 1940 maskTrailingOnes<uint64_t>(EltSizeInBits); 1941 1942 if (PrevElt) { 1943 // Calculate the step since the last non-undef element, and ensure 1944 // it's consistent across the entire sequence. 1945 unsigned IdxDiff = Idx - PrevElt->second; 1946 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1947 1948 // A zero-value value difference means that we're somewhere in the middle 1949 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1950 // step change before evaluating the sequence. 1951 if (ValDiff != 0) { 1952 int64_t Remainder = ValDiff % IdxDiff; 1953 // Normalize the step if it's greater than 1. 1954 if (Remainder != ValDiff) { 1955 // The difference must cleanly divide the element span. 1956 if (Remainder != 0) 1957 return None; 1958 ValDiff /= IdxDiff; 1959 IdxDiff = 1; 1960 } 1961 1962 if (!SeqStepNum) 1963 SeqStepNum = ValDiff; 1964 else if (ValDiff != SeqStepNum) 1965 return None; 1966 1967 if (!SeqStepDenom) 1968 SeqStepDenom = IdxDiff; 1969 else if (IdxDiff != *SeqStepDenom) 1970 return None; 1971 } 1972 } 1973 1974 // Record and/or check any addend. 1975 if (SeqStepNum && SeqStepDenom) { 1976 uint64_t ExpectedVal = 1977 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1978 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1979 if (!SeqAddend) 1980 SeqAddend = Addend; 1981 else if (SeqAddend != Addend) 1982 return None; 1983 } 1984 1985 // Record this non-undef element for later. 1986 if (!PrevElt || PrevElt->first != Val) 1987 PrevElt = std::make_pair(Val, Idx); 1988 } 1989 // We need to have logged both a step and an addend for this to count as 1990 // a legal index sequence. 1991 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1992 return None; 1993 1994 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1995 } 1996 1997 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1998 // and lower it as a VRGATHER_VX_VL from the source vector. 1999 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 2000 SelectionDAG &DAG, 2001 const RISCVSubtarget &Subtarget) { 2002 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 2003 return SDValue(); 2004 SDValue Vec = SplatVal.getOperand(0); 2005 // Only perform this optimization on vectors of the same size for simplicity. 2006 if (Vec.getValueType() != VT) 2007 return SDValue(); 2008 SDValue Idx = SplatVal.getOperand(1); 2009 // The index must be a legal type. 2010 if (Idx.getValueType() != Subtarget.getXLenVT()) 2011 return SDValue(); 2012 2013 MVT ContainerVT = VT; 2014 if (VT.isFixedLengthVector()) { 2015 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2016 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2017 } 2018 2019 SDValue Mask, VL; 2020 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2021 2022 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2023 Idx, Mask, VL); 2024 2025 if (!VT.isFixedLengthVector()) 2026 return Gather; 2027 2028 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2029 } 2030 2031 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2032 const RISCVSubtarget &Subtarget) { 2033 MVT VT = Op.getSimpleValueType(); 2034 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2035 2036 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2037 2038 SDLoc DL(Op); 2039 SDValue Mask, VL; 2040 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2041 2042 MVT XLenVT = Subtarget.getXLenVT(); 2043 unsigned NumElts = Op.getNumOperands(); 2044 2045 if (VT.getVectorElementType() == MVT::i1) { 2046 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2047 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2048 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2049 } 2050 2051 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2052 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2053 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2054 } 2055 2056 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2057 // scalar integer chunks whose bit-width depends on the number of mask 2058 // bits and XLEN. 2059 // First, determine the most appropriate scalar integer type to use. This 2060 // is at most XLenVT, but may be shrunk to a smaller vector element type 2061 // according to the size of the final vector - use i8 chunks rather than 2062 // XLenVT if we're producing a v8i1. This results in more consistent 2063 // codegen across RV32 and RV64. 2064 unsigned NumViaIntegerBits = 2065 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2066 NumViaIntegerBits = std::min(NumViaIntegerBits, 2067 Subtarget.getMaxELENForFixedLengthVectors()); 2068 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2069 // If we have to use more than one INSERT_VECTOR_ELT then this 2070 // optimization is likely to increase code size; avoid peforming it in 2071 // such a case. We can use a load from a constant pool in this case. 2072 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2073 return SDValue(); 2074 // Now we can create our integer vector type. Note that it may be larger 2075 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2076 MVT IntegerViaVecVT = 2077 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2078 divideCeil(NumElts, NumViaIntegerBits)); 2079 2080 uint64_t Bits = 0; 2081 unsigned BitPos = 0, IntegerEltIdx = 0; 2082 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2083 2084 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2085 // Once we accumulate enough bits to fill our scalar type, insert into 2086 // our vector and clear our accumulated data. 2087 if (I != 0 && I % NumViaIntegerBits == 0) { 2088 if (NumViaIntegerBits <= 32) 2089 Bits = SignExtend64(Bits, 32); 2090 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2091 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2092 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2093 Bits = 0; 2094 BitPos = 0; 2095 IntegerEltIdx++; 2096 } 2097 SDValue V = Op.getOperand(I); 2098 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2099 Bits |= ((uint64_t)BitValue << BitPos); 2100 } 2101 2102 // Insert the (remaining) scalar value into position in our integer 2103 // vector type. 2104 if (NumViaIntegerBits <= 32) 2105 Bits = SignExtend64(Bits, 32); 2106 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2107 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2108 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2109 2110 if (NumElts < NumViaIntegerBits) { 2111 // If we're producing a smaller vector than our minimum legal integer 2112 // type, bitcast to the equivalent (known-legal) mask type, and extract 2113 // our final mask. 2114 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2115 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2116 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2117 DAG.getConstant(0, DL, XLenVT)); 2118 } else { 2119 // Else we must have produced an integer type with the same size as the 2120 // mask type; bitcast for the final result. 2121 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2122 Vec = DAG.getBitcast(VT, Vec); 2123 } 2124 2125 return Vec; 2126 } 2127 2128 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2129 // vector type, we have a legal equivalently-sized i8 type, so we can use 2130 // that. 2131 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2132 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2133 2134 SDValue WideVec; 2135 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2136 // For a splat, perform a scalar truncate before creating the wider 2137 // vector. 2138 assert(Splat.getValueType() == XLenVT && 2139 "Unexpected type for i1 splat value"); 2140 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2141 DAG.getConstant(1, DL, XLenVT)); 2142 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2143 } else { 2144 SmallVector<SDValue, 8> Ops(Op->op_values()); 2145 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2146 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2147 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2148 } 2149 2150 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2151 } 2152 2153 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2154 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2155 return Gather; 2156 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2157 : RISCVISD::VMV_V_X_VL; 2158 Splat = 2159 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2160 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2161 } 2162 2163 // Try and match index sequences, which we can lower to the vid instruction 2164 // with optional modifications. An all-undef vector is matched by 2165 // getSplatValue, above. 2166 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2167 int64_t StepNumerator = SimpleVID->StepNumerator; 2168 unsigned StepDenominator = SimpleVID->StepDenominator; 2169 int64_t Addend = SimpleVID->Addend; 2170 2171 assert(StepNumerator != 0 && "Invalid step"); 2172 bool Negate = false; 2173 int64_t SplatStepVal = StepNumerator; 2174 unsigned StepOpcode = ISD::MUL; 2175 if (StepNumerator != 1) { 2176 if (isPowerOf2_64(std::abs(StepNumerator))) { 2177 Negate = StepNumerator < 0; 2178 StepOpcode = ISD::SHL; 2179 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2180 } 2181 } 2182 2183 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2184 // threshold since it's the immediate value many RVV instructions accept. 2185 // There is no vmul.vi instruction so ensure multiply constant can fit in 2186 // a single addi instruction. 2187 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2188 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2189 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2190 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2191 // Convert right out of the scalable type so we can use standard ISD 2192 // nodes for the rest of the computation. If we used scalable types with 2193 // these, we'd lose the fixed-length vector info and generate worse 2194 // vsetvli code. 2195 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2196 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2197 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2198 SDValue SplatStep = DAG.getSplatVector( 2199 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2200 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2201 } 2202 if (StepDenominator != 1) { 2203 SDValue SplatStep = DAG.getSplatVector( 2204 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2205 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2206 } 2207 if (Addend != 0 || Negate) { 2208 SDValue SplatAddend = 2209 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2210 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2211 } 2212 return VID; 2213 } 2214 } 2215 2216 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2217 // when re-interpreted as a vector with a larger element type. For example, 2218 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2219 // could be instead splat as 2220 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2221 // TODO: This optimization could also work on non-constant splats, but it 2222 // would require bit-manipulation instructions to construct the splat value. 2223 SmallVector<SDValue> Sequence; 2224 unsigned EltBitSize = VT.getScalarSizeInBits(); 2225 const auto *BV = cast<BuildVectorSDNode>(Op); 2226 if (VT.isInteger() && EltBitSize < 64 && 2227 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2228 BV->getRepeatedSequence(Sequence) && 2229 (Sequence.size() * EltBitSize) <= 64) { 2230 unsigned SeqLen = Sequence.size(); 2231 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2232 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2233 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2234 ViaIntVT == MVT::i64) && 2235 "Unexpected sequence type"); 2236 2237 unsigned EltIdx = 0; 2238 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2239 uint64_t SplatValue = 0; 2240 // Construct the amalgamated value which can be splatted as this larger 2241 // vector type. 2242 for (const auto &SeqV : Sequence) { 2243 if (!SeqV.isUndef()) 2244 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2245 << (EltIdx * EltBitSize)); 2246 EltIdx++; 2247 } 2248 2249 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2250 // achieve better constant materializion. 2251 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2252 SplatValue = SignExtend64(SplatValue, 32); 2253 2254 // Since we can't introduce illegal i64 types at this stage, we can only 2255 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2256 // way we can use RVV instructions to splat. 2257 assert((ViaIntVT.bitsLE(XLenVT) || 2258 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2259 "Unexpected bitcast sequence"); 2260 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2261 SDValue ViaVL = 2262 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2263 MVT ViaContainerVT = 2264 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2265 SDValue Splat = 2266 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2267 DAG.getUNDEF(ViaContainerVT), 2268 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2269 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2270 return DAG.getBitcast(VT, Splat); 2271 } 2272 } 2273 2274 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2275 // which constitute a large proportion of the elements. In such cases we can 2276 // splat a vector with the dominant element and make up the shortfall with 2277 // INSERT_VECTOR_ELTs. 2278 // Note that this includes vectors of 2 elements by association. The 2279 // upper-most element is the "dominant" one, allowing us to use a splat to 2280 // "insert" the upper element, and an insert of the lower element at position 2281 // 0, which improves codegen. 2282 SDValue DominantValue; 2283 unsigned MostCommonCount = 0; 2284 DenseMap<SDValue, unsigned> ValueCounts; 2285 unsigned NumUndefElts = 2286 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2287 2288 // Track the number of scalar loads we know we'd be inserting, estimated as 2289 // any non-zero floating-point constant. Other kinds of element are either 2290 // already in registers or are materialized on demand. The threshold at which 2291 // a vector load is more desirable than several scalar materializion and 2292 // vector-insertion instructions is not known. 2293 unsigned NumScalarLoads = 0; 2294 2295 for (SDValue V : Op->op_values()) { 2296 if (V.isUndef()) 2297 continue; 2298 2299 ValueCounts.insert(std::make_pair(V, 0)); 2300 unsigned &Count = ValueCounts[V]; 2301 2302 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2303 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2304 2305 // Is this value dominant? In case of a tie, prefer the highest element as 2306 // it's cheaper to insert near the beginning of a vector than it is at the 2307 // end. 2308 if (++Count >= MostCommonCount) { 2309 DominantValue = V; 2310 MostCommonCount = Count; 2311 } 2312 } 2313 2314 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2315 unsigned NumDefElts = NumElts - NumUndefElts; 2316 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2317 2318 // Don't perform this optimization when optimizing for size, since 2319 // materializing elements and inserting them tends to cause code bloat. 2320 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2321 ((MostCommonCount > DominantValueCountThreshold) || 2322 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2323 // Start by splatting the most common element. 2324 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2325 2326 DenseSet<SDValue> Processed{DominantValue}; 2327 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2328 for (const auto &OpIdx : enumerate(Op->ops())) { 2329 const SDValue &V = OpIdx.value(); 2330 if (V.isUndef() || !Processed.insert(V).second) 2331 continue; 2332 if (ValueCounts[V] == 1) { 2333 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2334 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2335 } else { 2336 // Blend in all instances of this value using a VSELECT, using a 2337 // mask where each bit signals whether that element is the one 2338 // we're after. 2339 SmallVector<SDValue> Ops; 2340 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2341 return DAG.getConstant(V == V1, DL, XLenVT); 2342 }); 2343 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2344 DAG.getBuildVector(SelMaskTy, DL, Ops), 2345 DAG.getSplatBuildVector(VT, DL, V), Vec); 2346 } 2347 } 2348 2349 return Vec; 2350 } 2351 2352 return SDValue(); 2353 } 2354 2355 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2356 SDValue Lo, SDValue Hi, SDValue VL, 2357 SelectionDAG &DAG) { 2358 bool HasPassthru = Passthru && !Passthru.isUndef(); 2359 if (!HasPassthru && !Passthru) 2360 Passthru = DAG.getUNDEF(VT); 2361 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2362 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2363 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2364 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2365 // node in order to try and match RVV vector/scalar instructions. 2366 if ((LoC >> 31) == HiC) 2367 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2368 2369 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2370 // vmv.v.x whose EEW = 32 to lower it. 2371 auto *Const = dyn_cast<ConstantSDNode>(VL); 2372 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2373 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2374 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2375 // access the subtarget here now. 2376 auto InterVec = DAG.getNode( 2377 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2378 DAG.getRegister(RISCV::X0, MVT::i32)); 2379 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2380 } 2381 } 2382 2383 // Fall back to a stack store and stride x0 vector load. 2384 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2385 Hi, VL); 2386 } 2387 2388 // Called by type legalization to handle splat of i64 on RV32. 2389 // FIXME: We can optimize this when the type has sign or zero bits in one 2390 // of the halves. 2391 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2392 SDValue Scalar, SDValue VL, 2393 SelectionDAG &DAG) { 2394 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2395 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2396 DAG.getConstant(0, DL, MVT::i32)); 2397 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2398 DAG.getConstant(1, DL, MVT::i32)); 2399 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2400 } 2401 2402 // This function lowers a splat of a scalar operand Splat with the vector 2403 // length VL. It ensures the final sequence is type legal, which is useful when 2404 // lowering a splat after type legalization. 2405 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2406 MVT VT, SDLoc DL, SelectionDAG &DAG, 2407 const RISCVSubtarget &Subtarget) { 2408 bool HasPassthru = Passthru && !Passthru.isUndef(); 2409 if (!HasPassthru && !Passthru) 2410 Passthru = DAG.getUNDEF(VT); 2411 if (VT.isFloatingPoint()) { 2412 // If VL is 1, we could use vfmv.s.f. 2413 if (isOneConstant(VL)) 2414 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2415 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2416 } 2417 2418 MVT XLenVT = Subtarget.getXLenVT(); 2419 2420 // Simplest case is that the operand needs to be promoted to XLenVT. 2421 if (Scalar.getValueType().bitsLE(XLenVT)) { 2422 // If the operand is a constant, sign extend to increase our chances 2423 // of being able to use a .vi instruction. ANY_EXTEND would become a 2424 // a zero extend and the simm5 check in isel would fail. 2425 // FIXME: Should we ignore the upper bits in isel instead? 2426 unsigned ExtOpc = 2427 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2428 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2429 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2430 // If VL is 1 and the scalar value won't benefit from immediate, we could 2431 // use vmv.s.x. 2432 if (isOneConstant(VL) && 2433 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2434 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2435 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2436 } 2437 2438 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2439 "Unexpected scalar for splat lowering!"); 2440 2441 if (isOneConstant(VL) && isNullConstant(Scalar)) 2442 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2443 DAG.getConstant(0, DL, XLenVT), VL); 2444 2445 // Otherwise use the more complicated splatting algorithm. 2446 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2447 } 2448 2449 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2450 const RISCVSubtarget &Subtarget) { 2451 // We need to be able to widen elements to the next larger integer type. 2452 if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors()) 2453 return false; 2454 2455 int Size = Mask.size(); 2456 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2457 2458 int Srcs[] = {-1, -1}; 2459 for (int i = 0; i != Size; ++i) { 2460 // Ignore undef elements. 2461 if (Mask[i] < 0) 2462 continue; 2463 2464 // Is this an even or odd element. 2465 int Pol = i % 2; 2466 2467 // Ensure we consistently use the same source for this element polarity. 2468 int Src = Mask[i] / Size; 2469 if (Srcs[Pol] < 0) 2470 Srcs[Pol] = Src; 2471 if (Srcs[Pol] != Src) 2472 return false; 2473 2474 // Make sure the element within the source is appropriate for this element 2475 // in the destination. 2476 int Elt = Mask[i] % Size; 2477 if (Elt != i / 2) 2478 return false; 2479 } 2480 2481 // We need to find a source for each polarity and they can't be the same. 2482 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2483 return false; 2484 2485 // Swap the sources if the second source was in the even polarity. 2486 SwapSources = Srcs[0] > Srcs[1]; 2487 2488 return true; 2489 } 2490 2491 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2492 /// and then extract the original number of elements from the rotated result. 2493 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2494 /// returned rotation amount is for a rotate right, where elements move from 2495 /// higher elements to lower elements. \p LoSrc indicates the first source 2496 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2497 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2498 /// 0 or 1 if a rotation is found. 2499 /// 2500 /// NOTE: We talk about rotate to the right which matches how bit shift and 2501 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2502 /// and the table below write vectors with the lowest elements on the left. 2503 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2504 int Size = Mask.size(); 2505 2506 // We need to detect various ways of spelling a rotation: 2507 // [11, 12, 13, 14, 15, 0, 1, 2] 2508 // [-1, 12, 13, 14, -1, -1, 1, -1] 2509 // [-1, -1, -1, -1, -1, -1, 1, 2] 2510 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2511 // [-1, 4, 5, 6, -1, -1, 9, -1] 2512 // [-1, 4, 5, 6, -1, -1, -1, -1] 2513 int Rotation = 0; 2514 LoSrc = -1; 2515 HiSrc = -1; 2516 for (int i = 0; i != Size; ++i) { 2517 int M = Mask[i]; 2518 if (M < 0) 2519 continue; 2520 2521 // Determine where a rotate vector would have started. 2522 int StartIdx = i - (M % Size); 2523 // The identity rotation isn't interesting, stop. 2524 if (StartIdx == 0) 2525 return -1; 2526 2527 // If we found the tail of a vector the rotation must be the missing 2528 // front. If we found the head of a vector, it must be how much of the 2529 // head. 2530 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2531 2532 if (Rotation == 0) 2533 Rotation = CandidateRotation; 2534 else if (Rotation != CandidateRotation) 2535 // The rotations don't match, so we can't match this mask. 2536 return -1; 2537 2538 // Compute which value this mask is pointing at. 2539 int MaskSrc = M < Size ? 0 : 1; 2540 2541 // Compute which of the two target values this index should be assigned to. 2542 // This reflects whether the high elements are remaining or the low elemnts 2543 // are remaining. 2544 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2545 2546 // Either set up this value if we've not encountered it before, or check 2547 // that it remains consistent. 2548 if (TargetSrc < 0) 2549 TargetSrc = MaskSrc; 2550 else if (TargetSrc != MaskSrc) 2551 // This may be a rotation, but it pulls from the inputs in some 2552 // unsupported interleaving. 2553 return -1; 2554 } 2555 2556 // Check that we successfully analyzed the mask, and normalize the results. 2557 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2558 assert((LoSrc >= 0 || HiSrc >= 0) && 2559 "Failed to find a rotated input vector!"); 2560 2561 return Rotation; 2562 } 2563 2564 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2565 const RISCVSubtarget &Subtarget) { 2566 SDValue V1 = Op.getOperand(0); 2567 SDValue V2 = Op.getOperand(1); 2568 SDLoc DL(Op); 2569 MVT XLenVT = Subtarget.getXLenVT(); 2570 MVT VT = Op.getSimpleValueType(); 2571 unsigned NumElts = VT.getVectorNumElements(); 2572 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2573 2574 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2575 2576 SDValue TrueMask, VL; 2577 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2578 2579 if (SVN->isSplat()) { 2580 const int Lane = SVN->getSplatIndex(); 2581 if (Lane >= 0) { 2582 MVT SVT = VT.getVectorElementType(); 2583 2584 // Turn splatted vector load into a strided load with an X0 stride. 2585 SDValue V = V1; 2586 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2587 // with undef. 2588 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2589 int Offset = Lane; 2590 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2591 int OpElements = 2592 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2593 V = V.getOperand(Offset / OpElements); 2594 Offset %= OpElements; 2595 } 2596 2597 // We need to ensure the load isn't atomic or volatile. 2598 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2599 auto *Ld = cast<LoadSDNode>(V); 2600 Offset *= SVT.getStoreSize(); 2601 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2602 TypeSize::Fixed(Offset), DL); 2603 2604 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2605 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2606 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2607 SDValue IntID = 2608 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2609 SDValue Ops[] = {Ld->getChain(), 2610 IntID, 2611 DAG.getUNDEF(ContainerVT), 2612 NewAddr, 2613 DAG.getRegister(RISCV::X0, XLenVT), 2614 VL}; 2615 SDValue NewLoad = DAG.getMemIntrinsicNode( 2616 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2617 DAG.getMachineFunction().getMachineMemOperand( 2618 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2619 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2620 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2621 } 2622 2623 // Otherwise use a scalar load and splat. This will give the best 2624 // opportunity to fold a splat into the operation. ISel can turn it into 2625 // the x0 strided load if we aren't able to fold away the select. 2626 if (SVT.isFloatingPoint()) 2627 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2628 Ld->getPointerInfo().getWithOffset(Offset), 2629 Ld->getOriginalAlign(), 2630 Ld->getMemOperand()->getFlags()); 2631 else 2632 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2633 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2634 Ld->getOriginalAlign(), 2635 Ld->getMemOperand()->getFlags()); 2636 DAG.makeEquivalentMemoryOrdering(Ld, V); 2637 2638 unsigned Opc = 2639 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2640 SDValue Splat = 2641 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2642 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2643 } 2644 2645 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2646 assert(Lane < (int)NumElts && "Unexpected lane!"); 2647 SDValue Gather = 2648 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2649 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2650 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2651 } 2652 } 2653 2654 ArrayRef<int> Mask = SVN->getMask(); 2655 2656 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2657 // be undef which can be handled with a single SLIDEDOWN/UP. 2658 int LoSrc, HiSrc; 2659 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2660 if (Rotation > 0) { 2661 SDValue LoV, HiV; 2662 if (LoSrc >= 0) { 2663 LoV = LoSrc == 0 ? V1 : V2; 2664 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2665 } 2666 if (HiSrc >= 0) { 2667 HiV = HiSrc == 0 ? V1 : V2; 2668 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2669 } 2670 2671 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2672 // to slide LoV up by (NumElts - Rotation). 2673 unsigned InvRotate = NumElts - Rotation; 2674 2675 SDValue Res = DAG.getUNDEF(ContainerVT); 2676 if (HiV) { 2677 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2678 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2679 // causes multiple vsetvlis in some test cases such as lowering 2680 // reduce.mul 2681 SDValue DownVL = VL; 2682 if (LoV) 2683 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2684 Res = 2685 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2686 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2687 } 2688 if (LoV) 2689 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2690 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2691 2692 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2693 } 2694 2695 // Detect an interleave shuffle and lower to 2696 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2697 bool SwapSources; 2698 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2699 // Swap sources if needed. 2700 if (SwapSources) 2701 std::swap(V1, V2); 2702 2703 // Extract the lower half of the vectors. 2704 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2705 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2706 DAG.getConstant(0, DL, XLenVT)); 2707 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2708 DAG.getConstant(0, DL, XLenVT)); 2709 2710 // Double the element width and halve the number of elements in an int type. 2711 unsigned EltBits = VT.getScalarSizeInBits(); 2712 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2713 MVT WideIntVT = 2714 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2715 // Convert this to a scalable vector. We need to base this on the 2716 // destination size to ensure there's always a type with a smaller LMUL. 2717 MVT WideIntContainerVT = 2718 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2719 2720 // Convert sources to scalable vectors with the same element count as the 2721 // larger type. 2722 MVT HalfContainerVT = MVT::getVectorVT( 2723 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2724 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2725 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2726 2727 // Cast sources to integer. 2728 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2729 MVT IntHalfVT = 2730 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2731 V1 = DAG.getBitcast(IntHalfVT, V1); 2732 V2 = DAG.getBitcast(IntHalfVT, V2); 2733 2734 // Freeze V2 since we use it twice and we need to be sure that the add and 2735 // multiply see the same value. 2736 V2 = DAG.getFreeze(V2); 2737 2738 // Recreate TrueMask using the widened type's element count. 2739 MVT MaskVT = 2740 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2741 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2742 2743 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2744 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2745 V2, TrueMask, VL); 2746 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2747 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2748 DAG.getUNDEF(IntHalfVT), 2749 DAG.getAllOnesConstant(DL, XLenVT)); 2750 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2751 V2, Multiplier, TrueMask, VL); 2752 // Add the new copies to our previous addition giving us 2^eltbits copies of 2753 // V2. This is equivalent to shifting V2 left by eltbits. This should 2754 // combine with the vwmulu.vv above to form vwmaccu.vv. 2755 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2756 TrueMask, VL); 2757 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2758 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2759 // vector VT. 2760 ContainerVT = 2761 MVT::getVectorVT(VT.getVectorElementType(), 2762 WideIntContainerVT.getVectorElementCount() * 2); 2763 Add = DAG.getBitcast(ContainerVT, Add); 2764 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2765 } 2766 2767 // Detect shuffles which can be re-expressed as vector selects; these are 2768 // shuffles in which each element in the destination is taken from an element 2769 // at the corresponding index in either source vectors. 2770 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2771 int MaskIndex = MaskIdx.value(); 2772 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2773 }); 2774 2775 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2776 2777 SmallVector<SDValue> MaskVals; 2778 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2779 // merged with a second vrgather. 2780 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2781 2782 // By default we preserve the original operand order, and use a mask to 2783 // select LHS as true and RHS as false. However, since RVV vector selects may 2784 // feature splats but only on the LHS, we may choose to invert our mask and 2785 // instead select between RHS and LHS. 2786 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2787 bool InvertMask = IsSelect == SwapOps; 2788 2789 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2790 // half. 2791 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2792 2793 // Now construct the mask that will be used by the vselect or blended 2794 // vrgather operation. For vrgathers, construct the appropriate indices into 2795 // each vector. 2796 for (int MaskIndex : Mask) { 2797 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2798 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2799 if (!IsSelect) { 2800 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2801 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2802 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2803 : DAG.getUNDEF(XLenVT)); 2804 GatherIndicesRHS.push_back( 2805 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2806 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2807 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2808 ++LHSIndexCounts[MaskIndex]; 2809 if (!IsLHSOrUndefIndex) 2810 ++RHSIndexCounts[MaskIndex - NumElts]; 2811 } 2812 } 2813 2814 if (SwapOps) { 2815 std::swap(V1, V2); 2816 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2817 } 2818 2819 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2820 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2821 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2822 2823 if (IsSelect) 2824 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2825 2826 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2827 // On such a large vector we're unable to use i8 as the index type. 2828 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2829 // may involve vector splitting if we're already at LMUL=8, or our 2830 // user-supplied maximum fixed-length LMUL. 2831 return SDValue(); 2832 } 2833 2834 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2835 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2836 MVT IndexVT = VT.changeTypeToInteger(); 2837 // Since we can't introduce illegal index types at this stage, use i16 and 2838 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2839 // than XLenVT. 2840 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2841 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2842 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2843 } 2844 2845 MVT IndexContainerVT = 2846 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2847 2848 SDValue Gather; 2849 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2850 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2851 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2852 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2853 Subtarget); 2854 } else { 2855 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2856 // If only one index is used, we can use a "splat" vrgather. 2857 // TODO: We can splat the most-common index and fix-up any stragglers, if 2858 // that's beneficial. 2859 if (LHSIndexCounts.size() == 1) { 2860 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2861 Gather = 2862 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2863 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2864 } else { 2865 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2866 LHSIndices = 2867 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2868 2869 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2870 TrueMask, VL); 2871 } 2872 } 2873 2874 // If a second vector operand is used by this shuffle, blend it in with an 2875 // additional vrgather. 2876 if (!V2.isUndef()) { 2877 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2878 // If only one index is used, we can use a "splat" vrgather. 2879 // TODO: We can splat the most-common index and fix-up any stragglers, if 2880 // that's beneficial. 2881 if (RHSIndexCounts.size() == 1) { 2882 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2883 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2884 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2885 } else { 2886 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2887 RHSIndices = 2888 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2889 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2890 VL); 2891 } 2892 2893 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2894 SelectMask = 2895 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2896 2897 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2898 Gather, VL); 2899 } 2900 2901 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2902 } 2903 2904 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2905 // Support splats for any type. These should type legalize well. 2906 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2907 return true; 2908 2909 // Only support legal VTs for other shuffles for now. 2910 if (!isTypeLegal(VT)) 2911 return false; 2912 2913 MVT SVT = VT.getSimpleVT(); 2914 2915 bool SwapSources; 2916 int LoSrc, HiSrc; 2917 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2918 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2919 } 2920 2921 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2922 SDLoc DL, SelectionDAG &DAG, 2923 const RISCVSubtarget &Subtarget) { 2924 if (VT.isScalableVector()) 2925 return DAG.getFPExtendOrRound(Op, DL, VT); 2926 assert(VT.isFixedLengthVector() && 2927 "Unexpected value type for RVV FP extend/round lowering"); 2928 SDValue Mask, VL; 2929 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2930 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2931 ? RISCVISD::FP_EXTEND_VL 2932 : RISCVISD::FP_ROUND_VL; 2933 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2934 } 2935 2936 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2937 // the exponent. 2938 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2939 MVT VT = Op.getSimpleValueType(); 2940 unsigned EltSize = VT.getScalarSizeInBits(); 2941 SDValue Src = Op.getOperand(0); 2942 SDLoc DL(Op); 2943 2944 // We need a FP type that can represent the value. 2945 // TODO: Use f16 for i8 when possible? 2946 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2947 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2948 2949 // Legal types should have been checked in the RISCVTargetLowering 2950 // constructor. 2951 // TODO: Splitting may make sense in some cases. 2952 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2953 "Expected legal float type!"); 2954 2955 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2956 // The trailing zero count is equal to log2 of this single bit value. 2957 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2958 SDValue Neg = 2959 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2960 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2961 } 2962 2963 // We have a legal FP type, convert to it. 2964 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2965 // Bitcast to integer and shift the exponent to the LSB. 2966 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2967 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2968 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2969 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2970 DAG.getConstant(ShiftAmt, DL, IntVT)); 2971 // Truncate back to original type to allow vnsrl. 2972 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2973 // The exponent contains log2 of the value in biased form. 2974 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2975 2976 // For trailing zeros, we just need to subtract the bias. 2977 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2978 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2979 DAG.getConstant(ExponentBias, DL, VT)); 2980 2981 // For leading zeros, we need to remove the bias and convert from log2 to 2982 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2983 unsigned Adjust = ExponentBias + (EltSize - 1); 2984 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2985 } 2986 2987 // While RVV has alignment restrictions, we should always be able to load as a 2988 // legal equivalently-sized byte-typed vector instead. This method is 2989 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2990 // the load is already correctly-aligned, it returns SDValue(). 2991 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2992 SelectionDAG &DAG) const { 2993 auto *Load = cast<LoadSDNode>(Op); 2994 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2995 2996 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2997 Load->getMemoryVT(), 2998 *Load->getMemOperand())) 2999 return SDValue(); 3000 3001 SDLoc DL(Op); 3002 MVT VT = Op.getSimpleValueType(); 3003 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3004 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3005 "Unexpected unaligned RVV load type"); 3006 MVT NewVT = 3007 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3008 assert(NewVT.isValid() && 3009 "Expecting equally-sized RVV vector types to be legal"); 3010 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 3011 Load->getPointerInfo(), Load->getOriginalAlign(), 3012 Load->getMemOperand()->getFlags()); 3013 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 3014 } 3015 3016 // While RVV has alignment restrictions, we should always be able to store as a 3017 // legal equivalently-sized byte-typed vector instead. This method is 3018 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 3019 // returns SDValue() if the store is already correctly aligned. 3020 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 3021 SelectionDAG &DAG) const { 3022 auto *Store = cast<StoreSDNode>(Op); 3023 assert(Store && Store->getValue().getValueType().isVector() && 3024 "Expected vector store"); 3025 3026 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3027 Store->getMemoryVT(), 3028 *Store->getMemOperand())) 3029 return SDValue(); 3030 3031 SDLoc DL(Op); 3032 SDValue StoredVal = Store->getValue(); 3033 MVT VT = StoredVal.getSimpleValueType(); 3034 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3035 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3036 "Unexpected unaligned RVV store type"); 3037 MVT NewVT = 3038 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3039 assert(NewVT.isValid() && 3040 "Expecting equally-sized RVV vector types to be legal"); 3041 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3042 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3043 Store->getPointerInfo(), Store->getOriginalAlign(), 3044 Store->getMemOperand()->getFlags()); 3045 } 3046 3047 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3048 SelectionDAG &DAG) const { 3049 switch (Op.getOpcode()) { 3050 default: 3051 report_fatal_error("unimplemented operand"); 3052 case ISD::GlobalAddress: 3053 return lowerGlobalAddress(Op, DAG); 3054 case ISD::BlockAddress: 3055 return lowerBlockAddress(Op, DAG); 3056 case ISD::ConstantPool: 3057 return lowerConstantPool(Op, DAG); 3058 case ISD::JumpTable: 3059 return lowerJumpTable(Op, DAG); 3060 case ISD::GlobalTLSAddress: 3061 return lowerGlobalTLSAddress(Op, DAG); 3062 case ISD::SELECT: 3063 return lowerSELECT(Op, DAG); 3064 case ISD::BRCOND: 3065 return lowerBRCOND(Op, DAG); 3066 case ISD::VASTART: 3067 return lowerVASTART(Op, DAG); 3068 case ISD::FRAMEADDR: 3069 return lowerFRAMEADDR(Op, DAG); 3070 case ISD::RETURNADDR: 3071 return lowerRETURNADDR(Op, DAG); 3072 case ISD::SHL_PARTS: 3073 return lowerShiftLeftParts(Op, DAG); 3074 case ISD::SRA_PARTS: 3075 return lowerShiftRightParts(Op, DAG, true); 3076 case ISD::SRL_PARTS: 3077 return lowerShiftRightParts(Op, DAG, false); 3078 case ISD::BITCAST: { 3079 SDLoc DL(Op); 3080 EVT VT = Op.getValueType(); 3081 SDValue Op0 = Op.getOperand(0); 3082 EVT Op0VT = Op0.getValueType(); 3083 MVT XLenVT = Subtarget.getXLenVT(); 3084 if (VT.isFixedLengthVector()) { 3085 // We can handle fixed length vector bitcasts with a simple replacement 3086 // in isel. 3087 if (Op0VT.isFixedLengthVector()) 3088 return Op; 3089 // When bitcasting from scalar to fixed-length vector, insert the scalar 3090 // into a one-element vector of the result type, and perform a vector 3091 // bitcast. 3092 if (!Op0VT.isVector()) { 3093 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3094 if (!isTypeLegal(BVT)) 3095 return SDValue(); 3096 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3097 DAG.getUNDEF(BVT), Op0, 3098 DAG.getConstant(0, DL, XLenVT))); 3099 } 3100 return SDValue(); 3101 } 3102 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3103 // thus: bitcast the vector to a one-element vector type whose element type 3104 // is the same as the result type, and extract the first element. 3105 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3106 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3107 if (!isTypeLegal(BVT)) 3108 return SDValue(); 3109 SDValue BVec = DAG.getBitcast(BVT, Op0); 3110 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3111 DAG.getConstant(0, DL, XLenVT)); 3112 } 3113 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3114 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3115 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3116 return FPConv; 3117 } 3118 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3119 Subtarget.hasStdExtF()) { 3120 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3121 SDValue FPConv = 3122 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3123 return FPConv; 3124 } 3125 return SDValue(); 3126 } 3127 case ISD::INTRINSIC_WO_CHAIN: 3128 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3129 case ISD::INTRINSIC_W_CHAIN: 3130 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3131 case ISD::INTRINSIC_VOID: 3132 return LowerINTRINSIC_VOID(Op, DAG); 3133 case ISD::BSWAP: 3134 case ISD::BITREVERSE: { 3135 MVT VT = Op.getSimpleValueType(); 3136 SDLoc DL(Op); 3137 if (Subtarget.hasStdExtZbp()) { 3138 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3139 // Start with the maximum immediate value which is the bitwidth - 1. 3140 unsigned Imm = VT.getSizeInBits() - 1; 3141 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3142 if (Op.getOpcode() == ISD::BSWAP) 3143 Imm &= ~0x7U; 3144 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3145 DAG.getConstant(Imm, DL, VT)); 3146 } 3147 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3148 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3149 // Expand bitreverse to a bswap(rev8) followed by brev8. 3150 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3151 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3152 // as brev8 by an isel pattern. 3153 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3154 DAG.getConstant(7, DL, VT)); 3155 } 3156 case ISD::FSHL: 3157 case ISD::FSHR: { 3158 MVT VT = Op.getSimpleValueType(); 3159 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3160 SDLoc DL(Op); 3161 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3162 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3163 // accidentally setting the extra bit. 3164 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3165 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3166 DAG.getConstant(ShAmtWidth, DL, VT)); 3167 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3168 // instruction use different orders. fshl will return its first operand for 3169 // shift of zero, fshr will return its second operand. fsl and fsr both 3170 // return rs1 so the ISD nodes need to have different operand orders. 3171 // Shift amount is in rs2. 3172 SDValue Op0 = Op.getOperand(0); 3173 SDValue Op1 = Op.getOperand(1); 3174 unsigned Opc = RISCVISD::FSL; 3175 if (Op.getOpcode() == ISD::FSHR) { 3176 std::swap(Op0, Op1); 3177 Opc = RISCVISD::FSR; 3178 } 3179 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3180 } 3181 case ISD::TRUNCATE: { 3182 SDLoc DL(Op); 3183 MVT VT = Op.getSimpleValueType(); 3184 // Only custom-lower vector truncates 3185 if (!VT.isVector()) 3186 return Op; 3187 3188 // Truncates to mask types are handled differently 3189 if (VT.getVectorElementType() == MVT::i1) 3190 return lowerVectorMaskTrunc(Op, DAG); 3191 3192 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3193 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3194 // truncate by one power of two at a time. 3195 MVT DstEltVT = VT.getVectorElementType(); 3196 3197 SDValue Src = Op.getOperand(0); 3198 MVT SrcVT = Src.getSimpleValueType(); 3199 MVT SrcEltVT = SrcVT.getVectorElementType(); 3200 3201 assert(DstEltVT.bitsLT(SrcEltVT) && 3202 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3203 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3204 "Unexpected vector truncate lowering"); 3205 3206 MVT ContainerVT = SrcVT; 3207 if (SrcVT.isFixedLengthVector()) { 3208 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3209 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3210 } 3211 3212 SDValue Result = Src; 3213 SDValue Mask, VL; 3214 std::tie(Mask, VL) = 3215 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3216 LLVMContext &Context = *DAG.getContext(); 3217 const ElementCount Count = ContainerVT.getVectorElementCount(); 3218 do { 3219 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3220 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3221 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3222 Mask, VL); 3223 } while (SrcEltVT != DstEltVT); 3224 3225 if (SrcVT.isFixedLengthVector()) 3226 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3227 3228 return Result; 3229 } 3230 case ISD::ANY_EXTEND: 3231 case ISD::ZERO_EXTEND: 3232 if (Op.getOperand(0).getValueType().isVector() && 3233 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3234 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3235 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3236 case ISD::SIGN_EXTEND: 3237 if (Op.getOperand(0).getValueType().isVector() && 3238 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3239 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3240 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3241 case ISD::SPLAT_VECTOR_PARTS: 3242 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3243 case ISD::INSERT_VECTOR_ELT: 3244 return lowerINSERT_VECTOR_ELT(Op, DAG); 3245 case ISD::EXTRACT_VECTOR_ELT: 3246 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3247 case ISD::VSCALE: { 3248 MVT VT = Op.getSimpleValueType(); 3249 SDLoc DL(Op); 3250 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3251 // We define our scalable vector types for lmul=1 to use a 64 bit known 3252 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3253 // vscale as VLENB / 8. 3254 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3255 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3256 report_fatal_error("Support for VLEN==32 is incomplete."); 3257 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3258 // We assume VLENB is a multiple of 8. We manually choose the best shift 3259 // here because SimplifyDemandedBits isn't always able to simplify it. 3260 uint64_t Val = Op.getConstantOperandVal(0); 3261 if (isPowerOf2_64(Val)) { 3262 uint64_t Log2 = Log2_64(Val); 3263 if (Log2 < 3) 3264 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3265 DAG.getConstant(3 - Log2, DL, VT)); 3266 if (Log2 > 3) 3267 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3268 DAG.getConstant(Log2 - 3, DL, VT)); 3269 return VLENB; 3270 } 3271 // If the multiplier is a multiple of 8, scale it down to avoid needing 3272 // to shift the VLENB value. 3273 if ((Val % 8) == 0) 3274 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3275 DAG.getConstant(Val / 8, DL, VT)); 3276 } 3277 3278 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3279 DAG.getConstant(3, DL, VT)); 3280 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3281 } 3282 case ISD::FPOWI: { 3283 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3284 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3285 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3286 Op.getOperand(1).getValueType() == MVT::i32) { 3287 SDLoc DL(Op); 3288 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3289 SDValue Powi = 3290 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3291 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3292 DAG.getIntPtrConstant(0, DL)); 3293 } 3294 return SDValue(); 3295 } 3296 case ISD::FP_EXTEND: { 3297 // RVV can only do fp_extend to types double the size as the source. We 3298 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3299 // via f32. 3300 SDLoc DL(Op); 3301 MVT VT = Op.getSimpleValueType(); 3302 SDValue Src = Op.getOperand(0); 3303 MVT SrcVT = Src.getSimpleValueType(); 3304 3305 // Prepare any fixed-length vector operands. 3306 MVT ContainerVT = VT; 3307 if (SrcVT.isFixedLengthVector()) { 3308 ContainerVT = getContainerForFixedLengthVector(VT); 3309 MVT SrcContainerVT = 3310 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3311 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3312 } 3313 3314 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3315 SrcVT.getVectorElementType() != MVT::f16) { 3316 // For scalable vectors, we only need to close the gap between 3317 // vXf16->vXf64. 3318 if (!VT.isFixedLengthVector()) 3319 return Op; 3320 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3321 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3322 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3323 } 3324 3325 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3326 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3327 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3328 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3329 3330 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3331 DL, DAG, Subtarget); 3332 if (VT.isFixedLengthVector()) 3333 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3334 return Extend; 3335 } 3336 case ISD::FP_ROUND: { 3337 // RVV can only do fp_round to types half the size as the source. We 3338 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3339 // conversion instruction. 3340 SDLoc DL(Op); 3341 MVT VT = Op.getSimpleValueType(); 3342 SDValue Src = Op.getOperand(0); 3343 MVT SrcVT = Src.getSimpleValueType(); 3344 3345 // Prepare any fixed-length vector operands. 3346 MVT ContainerVT = VT; 3347 if (VT.isFixedLengthVector()) { 3348 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3349 ContainerVT = 3350 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3351 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3352 } 3353 3354 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3355 SrcVT.getVectorElementType() != MVT::f64) { 3356 // For scalable vectors, we only need to close the gap between 3357 // vXf64<->vXf16. 3358 if (!VT.isFixedLengthVector()) 3359 return Op; 3360 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3361 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3362 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3363 } 3364 3365 SDValue Mask, VL; 3366 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3367 3368 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3369 SDValue IntermediateRound = 3370 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3371 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3372 DL, DAG, Subtarget); 3373 3374 if (VT.isFixedLengthVector()) 3375 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3376 return Round; 3377 } 3378 case ISD::FP_TO_SINT: 3379 case ISD::FP_TO_UINT: 3380 case ISD::SINT_TO_FP: 3381 case ISD::UINT_TO_FP: { 3382 // RVV can only do fp<->int conversions to types half/double the size as 3383 // the source. We custom-lower any conversions that do two hops into 3384 // sequences. 3385 MVT VT = Op.getSimpleValueType(); 3386 if (!VT.isVector()) 3387 return Op; 3388 SDLoc DL(Op); 3389 SDValue Src = Op.getOperand(0); 3390 MVT EltVT = VT.getVectorElementType(); 3391 MVT SrcVT = Src.getSimpleValueType(); 3392 MVT SrcEltVT = SrcVT.getVectorElementType(); 3393 unsigned EltSize = EltVT.getSizeInBits(); 3394 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3395 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3396 "Unexpected vector element types"); 3397 3398 bool IsInt2FP = SrcEltVT.isInteger(); 3399 // Widening conversions 3400 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 3401 if (IsInt2FP) { 3402 // Do a regular integer sign/zero extension then convert to float. 3403 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 3404 VT.getVectorElementCount()); 3405 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3406 ? ISD::ZERO_EXTEND 3407 : ISD::SIGN_EXTEND; 3408 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3409 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3410 } 3411 // FP2Int 3412 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3413 // Do one doubling fp_extend then complete the operation by converting 3414 // to int. 3415 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3416 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3417 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3418 } 3419 3420 // Narrowing conversions 3421 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 3422 if (IsInt2FP) { 3423 // One narrowing int_to_fp, then an fp_round. 3424 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3425 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3426 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3427 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3428 } 3429 // FP2Int 3430 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3431 // representable by the integer, the result is poison. 3432 MVT IVecVT = 3433 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3434 VT.getVectorElementCount()); 3435 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3436 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3437 } 3438 3439 // Scalable vectors can exit here. Patterns will handle equally-sized 3440 // conversions halving/doubling ones. 3441 if (!VT.isFixedLengthVector()) 3442 return Op; 3443 3444 // For fixed-length vectors we lower to a custom "VL" node. 3445 unsigned RVVOpc = 0; 3446 switch (Op.getOpcode()) { 3447 default: 3448 llvm_unreachable("Impossible opcode"); 3449 case ISD::FP_TO_SINT: 3450 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3451 break; 3452 case ISD::FP_TO_UINT: 3453 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3454 break; 3455 case ISD::SINT_TO_FP: 3456 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3457 break; 3458 case ISD::UINT_TO_FP: 3459 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3460 break; 3461 } 3462 3463 MVT ContainerVT, SrcContainerVT; 3464 // Derive the reference container type from the larger vector type. 3465 if (SrcEltSize > EltSize) { 3466 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3467 ContainerVT = 3468 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3469 } else { 3470 ContainerVT = getContainerForFixedLengthVector(VT); 3471 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3472 } 3473 3474 SDValue Mask, VL; 3475 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3476 3477 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3478 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3479 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3480 } 3481 case ISD::FP_TO_SINT_SAT: 3482 case ISD::FP_TO_UINT_SAT: 3483 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3484 case ISD::FTRUNC: 3485 case ISD::FCEIL: 3486 case ISD::FFLOOR: 3487 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3488 case ISD::FROUND: 3489 return lowerFROUND(Op, DAG); 3490 case ISD::VECREDUCE_ADD: 3491 case ISD::VECREDUCE_UMAX: 3492 case ISD::VECREDUCE_SMAX: 3493 case ISD::VECREDUCE_UMIN: 3494 case ISD::VECREDUCE_SMIN: 3495 return lowerVECREDUCE(Op, DAG); 3496 case ISD::VECREDUCE_AND: 3497 case ISD::VECREDUCE_OR: 3498 case ISD::VECREDUCE_XOR: 3499 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3500 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3501 return lowerVECREDUCE(Op, DAG); 3502 case ISD::VECREDUCE_FADD: 3503 case ISD::VECREDUCE_SEQ_FADD: 3504 case ISD::VECREDUCE_FMIN: 3505 case ISD::VECREDUCE_FMAX: 3506 return lowerFPVECREDUCE(Op, DAG); 3507 case ISD::VP_REDUCE_ADD: 3508 case ISD::VP_REDUCE_UMAX: 3509 case ISD::VP_REDUCE_SMAX: 3510 case ISD::VP_REDUCE_UMIN: 3511 case ISD::VP_REDUCE_SMIN: 3512 case ISD::VP_REDUCE_FADD: 3513 case ISD::VP_REDUCE_SEQ_FADD: 3514 case ISD::VP_REDUCE_FMIN: 3515 case ISD::VP_REDUCE_FMAX: 3516 return lowerVPREDUCE(Op, DAG); 3517 case ISD::VP_REDUCE_AND: 3518 case ISD::VP_REDUCE_OR: 3519 case ISD::VP_REDUCE_XOR: 3520 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3521 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3522 return lowerVPREDUCE(Op, DAG); 3523 case ISD::INSERT_SUBVECTOR: 3524 return lowerINSERT_SUBVECTOR(Op, DAG); 3525 case ISD::EXTRACT_SUBVECTOR: 3526 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3527 case ISD::STEP_VECTOR: 3528 return lowerSTEP_VECTOR(Op, DAG); 3529 case ISD::VECTOR_REVERSE: 3530 return lowerVECTOR_REVERSE(Op, DAG); 3531 case ISD::VECTOR_SPLICE: 3532 return lowerVECTOR_SPLICE(Op, DAG); 3533 case ISD::BUILD_VECTOR: 3534 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3535 case ISD::SPLAT_VECTOR: 3536 if (Op.getValueType().getVectorElementType() == MVT::i1) 3537 return lowerVectorMaskSplat(Op, DAG); 3538 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3539 case ISD::VECTOR_SHUFFLE: 3540 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3541 case ISD::CONCAT_VECTORS: { 3542 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3543 // better than going through the stack, as the default expansion does. 3544 SDLoc DL(Op); 3545 MVT VT = Op.getSimpleValueType(); 3546 unsigned NumOpElts = 3547 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3548 SDValue Vec = DAG.getUNDEF(VT); 3549 for (const auto &OpIdx : enumerate(Op->ops())) { 3550 SDValue SubVec = OpIdx.value(); 3551 // Don't insert undef subvectors. 3552 if (SubVec.isUndef()) 3553 continue; 3554 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3555 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3556 } 3557 return Vec; 3558 } 3559 case ISD::LOAD: 3560 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3561 return V; 3562 if (Op.getValueType().isFixedLengthVector()) 3563 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3564 return Op; 3565 case ISD::STORE: 3566 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3567 return V; 3568 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3569 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3570 return Op; 3571 case ISD::MLOAD: 3572 case ISD::VP_LOAD: 3573 return lowerMaskedLoad(Op, DAG); 3574 case ISD::MSTORE: 3575 case ISD::VP_STORE: 3576 return lowerMaskedStore(Op, DAG); 3577 case ISD::SETCC: 3578 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3579 case ISD::ADD: 3580 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3581 case ISD::SUB: 3582 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3583 case ISD::MUL: 3584 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3585 case ISD::MULHS: 3586 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3587 case ISD::MULHU: 3588 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3589 case ISD::AND: 3590 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3591 RISCVISD::AND_VL); 3592 case ISD::OR: 3593 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3594 RISCVISD::OR_VL); 3595 case ISD::XOR: 3596 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3597 RISCVISD::XOR_VL); 3598 case ISD::SDIV: 3599 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3600 case ISD::SREM: 3601 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3602 case ISD::UDIV: 3603 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3604 case ISD::UREM: 3605 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3606 case ISD::SHL: 3607 case ISD::SRA: 3608 case ISD::SRL: 3609 if (Op.getSimpleValueType().isFixedLengthVector()) 3610 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3611 // This can be called for an i32 shift amount that needs to be promoted. 3612 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3613 "Unexpected custom legalisation"); 3614 return SDValue(); 3615 case ISD::SADDSAT: 3616 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3617 case ISD::UADDSAT: 3618 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3619 case ISD::SSUBSAT: 3620 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3621 case ISD::USUBSAT: 3622 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3623 case ISD::FADD: 3624 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3625 case ISD::FSUB: 3626 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3627 case ISD::FMUL: 3628 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3629 case ISD::FDIV: 3630 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3631 case ISD::FNEG: 3632 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3633 case ISD::FABS: 3634 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3635 case ISD::FSQRT: 3636 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3637 case ISD::FMA: 3638 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3639 case ISD::SMIN: 3640 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3641 case ISD::SMAX: 3642 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3643 case ISD::UMIN: 3644 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3645 case ISD::UMAX: 3646 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3647 case ISD::FMINNUM: 3648 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3649 case ISD::FMAXNUM: 3650 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3651 case ISD::ABS: 3652 return lowerABS(Op, DAG); 3653 case ISD::CTLZ_ZERO_UNDEF: 3654 case ISD::CTTZ_ZERO_UNDEF: 3655 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3656 case ISD::VSELECT: 3657 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3658 case ISD::FCOPYSIGN: 3659 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3660 case ISD::MGATHER: 3661 case ISD::VP_GATHER: 3662 return lowerMaskedGather(Op, DAG); 3663 case ISD::MSCATTER: 3664 case ISD::VP_SCATTER: 3665 return lowerMaskedScatter(Op, DAG); 3666 case ISD::FLT_ROUNDS_: 3667 return lowerGET_ROUNDING(Op, DAG); 3668 case ISD::SET_ROUNDING: 3669 return lowerSET_ROUNDING(Op, DAG); 3670 case ISD::VP_SELECT: 3671 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3672 case ISD::VP_MERGE: 3673 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3674 case ISD::VP_ADD: 3675 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3676 case ISD::VP_SUB: 3677 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3678 case ISD::VP_MUL: 3679 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3680 case ISD::VP_SDIV: 3681 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3682 case ISD::VP_UDIV: 3683 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3684 case ISD::VP_SREM: 3685 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3686 case ISD::VP_UREM: 3687 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3688 case ISD::VP_AND: 3689 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3690 case ISD::VP_OR: 3691 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3692 case ISD::VP_XOR: 3693 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3694 case ISD::VP_ASHR: 3695 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3696 case ISD::VP_LSHR: 3697 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3698 case ISD::VP_SHL: 3699 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3700 case ISD::VP_FADD: 3701 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3702 case ISD::VP_FSUB: 3703 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3704 case ISD::VP_FMUL: 3705 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3706 case ISD::VP_FDIV: 3707 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3708 case ISD::VP_FNEG: 3709 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3710 case ISD::VP_FMA: 3711 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3712 } 3713 } 3714 3715 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3716 SelectionDAG &DAG, unsigned Flags) { 3717 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3718 } 3719 3720 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3721 SelectionDAG &DAG, unsigned Flags) { 3722 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3723 Flags); 3724 } 3725 3726 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3727 SelectionDAG &DAG, unsigned Flags) { 3728 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3729 N->getOffset(), Flags); 3730 } 3731 3732 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3733 SelectionDAG &DAG, unsigned Flags) { 3734 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3735 } 3736 3737 template <class NodeTy> 3738 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3739 bool IsLocal) const { 3740 SDLoc DL(N); 3741 EVT Ty = getPointerTy(DAG.getDataLayout()); 3742 3743 if (isPositionIndependent()) { 3744 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3745 if (IsLocal) 3746 // Use PC-relative addressing to access the symbol. This generates the 3747 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3748 // %pcrel_lo(auipc)). 3749 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3750 3751 // Use PC-relative addressing to access the GOT for this symbol, then load 3752 // the address from the GOT. This generates the pattern (PseudoLA sym), 3753 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3754 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3755 } 3756 3757 switch (getTargetMachine().getCodeModel()) { 3758 default: 3759 report_fatal_error("Unsupported code model for lowering"); 3760 case CodeModel::Small: { 3761 // Generate a sequence for accessing addresses within the first 2 GiB of 3762 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3763 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3764 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3765 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3766 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3767 } 3768 case CodeModel::Medium: { 3769 // Generate a sequence for accessing addresses within any 2GiB range within 3770 // the address space. This generates the pattern (PseudoLLA sym), which 3771 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3772 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3773 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3774 } 3775 } 3776 } 3777 3778 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3779 SelectionDAG &DAG) const { 3780 SDLoc DL(Op); 3781 EVT Ty = Op.getValueType(); 3782 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3783 int64_t Offset = N->getOffset(); 3784 MVT XLenVT = Subtarget.getXLenVT(); 3785 3786 const GlobalValue *GV = N->getGlobal(); 3787 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3788 SDValue Addr = getAddr(N, DAG, IsLocal); 3789 3790 // In order to maximise the opportunity for common subexpression elimination, 3791 // emit a separate ADD node for the global address offset instead of folding 3792 // it in the global address node. Later peephole optimisations may choose to 3793 // fold it back in when profitable. 3794 if (Offset != 0) 3795 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3796 DAG.getConstant(Offset, DL, XLenVT)); 3797 return Addr; 3798 } 3799 3800 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3801 SelectionDAG &DAG) const { 3802 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3803 3804 return getAddr(N, DAG); 3805 } 3806 3807 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3808 SelectionDAG &DAG) const { 3809 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3810 3811 return getAddr(N, DAG); 3812 } 3813 3814 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3815 SelectionDAG &DAG) const { 3816 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3817 3818 return getAddr(N, DAG); 3819 } 3820 3821 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3822 SelectionDAG &DAG, 3823 bool UseGOT) const { 3824 SDLoc DL(N); 3825 EVT Ty = getPointerTy(DAG.getDataLayout()); 3826 const GlobalValue *GV = N->getGlobal(); 3827 MVT XLenVT = Subtarget.getXLenVT(); 3828 3829 if (UseGOT) { 3830 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3831 // load the address from the GOT and add the thread pointer. This generates 3832 // the pattern (PseudoLA_TLS_IE sym), which expands to 3833 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3834 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3835 SDValue Load = 3836 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3837 3838 // Add the thread pointer. 3839 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3840 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3841 } 3842 3843 // Generate a sequence for accessing the address relative to the thread 3844 // pointer, with the appropriate adjustment for the thread pointer offset. 3845 // This generates the pattern 3846 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3847 SDValue AddrHi = 3848 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3849 SDValue AddrAdd = 3850 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3851 SDValue AddrLo = 3852 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3853 3854 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3855 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3856 SDValue MNAdd = SDValue( 3857 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3858 0); 3859 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3860 } 3861 3862 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3863 SelectionDAG &DAG) const { 3864 SDLoc DL(N); 3865 EVT Ty = getPointerTy(DAG.getDataLayout()); 3866 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3867 const GlobalValue *GV = N->getGlobal(); 3868 3869 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3870 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3871 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3872 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3873 SDValue Load = 3874 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3875 3876 // Prepare argument list to generate call. 3877 ArgListTy Args; 3878 ArgListEntry Entry; 3879 Entry.Node = Load; 3880 Entry.Ty = CallTy; 3881 Args.push_back(Entry); 3882 3883 // Setup call to __tls_get_addr. 3884 TargetLowering::CallLoweringInfo CLI(DAG); 3885 CLI.setDebugLoc(DL) 3886 .setChain(DAG.getEntryNode()) 3887 .setLibCallee(CallingConv::C, CallTy, 3888 DAG.getExternalSymbol("__tls_get_addr", Ty), 3889 std::move(Args)); 3890 3891 return LowerCallTo(CLI).first; 3892 } 3893 3894 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3895 SelectionDAG &DAG) const { 3896 SDLoc DL(Op); 3897 EVT Ty = Op.getValueType(); 3898 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3899 int64_t Offset = N->getOffset(); 3900 MVT XLenVT = Subtarget.getXLenVT(); 3901 3902 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3903 3904 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3905 CallingConv::GHC) 3906 report_fatal_error("In GHC calling convention TLS is not supported"); 3907 3908 SDValue Addr; 3909 switch (Model) { 3910 case TLSModel::LocalExec: 3911 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3912 break; 3913 case TLSModel::InitialExec: 3914 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3915 break; 3916 case TLSModel::LocalDynamic: 3917 case TLSModel::GeneralDynamic: 3918 Addr = getDynamicTLSAddr(N, DAG); 3919 break; 3920 } 3921 3922 // In order to maximise the opportunity for common subexpression elimination, 3923 // emit a separate ADD node for the global address offset instead of folding 3924 // it in the global address node. Later peephole optimisations may choose to 3925 // fold it back in when profitable. 3926 if (Offset != 0) 3927 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3928 DAG.getConstant(Offset, DL, XLenVT)); 3929 return Addr; 3930 } 3931 3932 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3933 SDValue CondV = Op.getOperand(0); 3934 SDValue TrueV = Op.getOperand(1); 3935 SDValue FalseV = Op.getOperand(2); 3936 SDLoc DL(Op); 3937 MVT VT = Op.getSimpleValueType(); 3938 MVT XLenVT = Subtarget.getXLenVT(); 3939 3940 // Lower vector SELECTs to VSELECTs by splatting the condition. 3941 if (VT.isVector()) { 3942 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3943 SDValue CondSplat = VT.isScalableVector() 3944 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3945 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3946 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3947 } 3948 3949 // If the result type is XLenVT and CondV is the output of a SETCC node 3950 // which also operated on XLenVT inputs, then merge the SETCC node into the 3951 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3952 // compare+branch instructions. i.e.: 3953 // (select (setcc lhs, rhs, cc), truev, falsev) 3954 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3955 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3956 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3957 SDValue LHS = CondV.getOperand(0); 3958 SDValue RHS = CondV.getOperand(1); 3959 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3960 ISD::CondCode CCVal = CC->get(); 3961 3962 // Special case for a select of 2 constants that have a diffence of 1. 3963 // Normally this is done by DAGCombine, but if the select is introduced by 3964 // type legalization or op legalization, we miss it. Restricting to SETLT 3965 // case for now because that is what signed saturating add/sub need. 3966 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3967 // but we would probably want to swap the true/false values if the condition 3968 // is SETGE/SETLE to avoid an XORI. 3969 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3970 CCVal == ISD::SETLT) { 3971 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3972 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3973 if (TrueVal - 1 == FalseVal) 3974 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3975 if (TrueVal + 1 == FalseVal) 3976 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3977 } 3978 3979 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3980 3981 SDValue TargetCC = DAG.getCondCode(CCVal); 3982 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3983 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3984 } 3985 3986 // Otherwise: 3987 // (select condv, truev, falsev) 3988 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3989 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3990 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3991 3992 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3993 3994 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3995 } 3996 3997 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3998 SDValue CondV = Op.getOperand(1); 3999 SDLoc DL(Op); 4000 MVT XLenVT = Subtarget.getXLenVT(); 4001 4002 if (CondV.getOpcode() == ISD::SETCC && 4003 CondV.getOperand(0).getValueType() == XLenVT) { 4004 SDValue LHS = CondV.getOperand(0); 4005 SDValue RHS = CondV.getOperand(1); 4006 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 4007 4008 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 4009 4010 SDValue TargetCC = DAG.getCondCode(CCVal); 4011 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 4012 LHS, RHS, TargetCC, Op.getOperand(2)); 4013 } 4014 4015 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 4016 CondV, DAG.getConstant(0, DL, XLenVT), 4017 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 4018 } 4019 4020 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 4021 MachineFunction &MF = DAG.getMachineFunction(); 4022 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 4023 4024 SDLoc DL(Op); 4025 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 4026 getPointerTy(MF.getDataLayout())); 4027 4028 // vastart just stores the address of the VarArgsFrameIndex slot into the 4029 // memory location argument. 4030 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4031 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 4032 MachinePointerInfo(SV)); 4033 } 4034 4035 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 4036 SelectionDAG &DAG) const { 4037 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4038 MachineFunction &MF = DAG.getMachineFunction(); 4039 MachineFrameInfo &MFI = MF.getFrameInfo(); 4040 MFI.setFrameAddressIsTaken(true); 4041 Register FrameReg = RI.getFrameRegister(MF); 4042 int XLenInBytes = Subtarget.getXLen() / 8; 4043 4044 EVT VT = Op.getValueType(); 4045 SDLoc DL(Op); 4046 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 4047 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4048 while (Depth--) { 4049 int Offset = -(XLenInBytes * 2); 4050 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 4051 DAG.getIntPtrConstant(Offset, DL)); 4052 FrameAddr = 4053 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 4054 } 4055 return FrameAddr; 4056 } 4057 4058 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 4059 SelectionDAG &DAG) const { 4060 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4061 MachineFunction &MF = DAG.getMachineFunction(); 4062 MachineFrameInfo &MFI = MF.getFrameInfo(); 4063 MFI.setReturnAddressIsTaken(true); 4064 MVT XLenVT = Subtarget.getXLenVT(); 4065 int XLenInBytes = Subtarget.getXLen() / 8; 4066 4067 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4068 return SDValue(); 4069 4070 EVT VT = Op.getValueType(); 4071 SDLoc DL(Op); 4072 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4073 if (Depth) { 4074 int Off = -XLenInBytes; 4075 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 4076 SDValue Offset = DAG.getConstant(Off, DL, VT); 4077 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4078 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4079 MachinePointerInfo()); 4080 } 4081 4082 // Return the value of the return address register, marking it an implicit 4083 // live-in. 4084 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 4085 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 4086 } 4087 4088 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4089 SelectionDAG &DAG) const { 4090 SDLoc DL(Op); 4091 SDValue Lo = Op.getOperand(0); 4092 SDValue Hi = Op.getOperand(1); 4093 SDValue Shamt = Op.getOperand(2); 4094 EVT VT = Lo.getValueType(); 4095 4096 // if Shamt-XLEN < 0: // Shamt < XLEN 4097 // Lo = Lo << Shamt 4098 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4099 // else: 4100 // Lo = 0 4101 // Hi = Lo << (Shamt-XLEN) 4102 4103 SDValue Zero = DAG.getConstant(0, DL, VT); 4104 SDValue One = DAG.getConstant(1, DL, VT); 4105 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4106 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4107 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4108 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4109 4110 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4111 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4112 SDValue ShiftRightLo = 4113 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4114 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4115 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4116 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4117 4118 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4119 4120 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4121 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4122 4123 SDValue Parts[2] = {Lo, Hi}; 4124 return DAG.getMergeValues(Parts, DL); 4125 } 4126 4127 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4128 bool IsSRA) const { 4129 SDLoc DL(Op); 4130 SDValue Lo = Op.getOperand(0); 4131 SDValue Hi = Op.getOperand(1); 4132 SDValue Shamt = Op.getOperand(2); 4133 EVT VT = Lo.getValueType(); 4134 4135 // SRA expansion: 4136 // if Shamt-XLEN < 0: // Shamt < XLEN 4137 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4138 // Hi = Hi >>s Shamt 4139 // else: 4140 // Lo = Hi >>s (Shamt-XLEN); 4141 // Hi = Hi >>s (XLEN-1) 4142 // 4143 // SRL expansion: 4144 // if Shamt-XLEN < 0: // Shamt < XLEN 4145 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4146 // Hi = Hi >>u Shamt 4147 // else: 4148 // Lo = Hi >>u (Shamt-XLEN); 4149 // Hi = 0; 4150 4151 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4152 4153 SDValue Zero = DAG.getConstant(0, DL, VT); 4154 SDValue One = DAG.getConstant(1, DL, VT); 4155 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4156 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4157 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4158 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4159 4160 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4161 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4162 SDValue ShiftLeftHi = 4163 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4164 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4165 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4166 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4167 SDValue HiFalse = 4168 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4169 4170 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4171 4172 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4173 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4174 4175 SDValue Parts[2] = {Lo, Hi}; 4176 return DAG.getMergeValues(Parts, DL); 4177 } 4178 4179 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4180 // legal equivalently-sized i8 type, so we can use that as a go-between. 4181 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4182 SelectionDAG &DAG) const { 4183 SDLoc DL(Op); 4184 MVT VT = Op.getSimpleValueType(); 4185 SDValue SplatVal = Op.getOperand(0); 4186 // All-zeros or all-ones splats are handled specially. 4187 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4188 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4189 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4190 } 4191 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4192 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4193 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4194 } 4195 MVT XLenVT = Subtarget.getXLenVT(); 4196 assert(SplatVal.getValueType() == XLenVT && 4197 "Unexpected type for i1 splat value"); 4198 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4199 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4200 DAG.getConstant(1, DL, XLenVT)); 4201 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4202 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4203 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4204 } 4205 4206 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4207 // illegal (currently only vXi64 RV32). 4208 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4209 // them to VMV_V_X_VL. 4210 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4211 SelectionDAG &DAG) const { 4212 SDLoc DL(Op); 4213 MVT VecVT = Op.getSimpleValueType(); 4214 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4215 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4216 4217 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4218 SDValue Lo = Op.getOperand(0); 4219 SDValue Hi = Op.getOperand(1); 4220 4221 if (VecVT.isFixedLengthVector()) { 4222 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4223 SDLoc DL(Op); 4224 SDValue Mask, VL; 4225 std::tie(Mask, VL) = 4226 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4227 4228 SDValue Res = 4229 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4230 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4231 } 4232 4233 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4234 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4235 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4236 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4237 // node in order to try and match RVV vector/scalar instructions. 4238 if ((LoC >> 31) == HiC) 4239 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4240 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4241 } 4242 4243 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4244 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4245 isa<ConstantSDNode>(Hi.getOperand(1)) && 4246 Hi.getConstantOperandVal(1) == 31) 4247 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4248 DAG.getRegister(RISCV::X0, MVT::i32)); 4249 4250 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4251 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4252 DAG.getUNDEF(VecVT), Lo, Hi, 4253 DAG.getRegister(RISCV::X0, MVT::i32)); 4254 } 4255 4256 // Custom-lower extensions from mask vectors by using a vselect either with 1 4257 // for zero/any-extension or -1 for sign-extension: 4258 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4259 // Note that any-extension is lowered identically to zero-extension. 4260 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4261 int64_t ExtTrueVal) const { 4262 SDLoc DL(Op); 4263 MVT VecVT = Op.getSimpleValueType(); 4264 SDValue Src = Op.getOperand(0); 4265 // Only custom-lower extensions from mask types 4266 assert(Src.getValueType().isVector() && 4267 Src.getValueType().getVectorElementType() == MVT::i1); 4268 4269 MVT XLenVT = Subtarget.getXLenVT(); 4270 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4271 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4272 4273 if (VecVT.isScalableVector()) { 4274 // Be careful not to introduce illegal scalar types at this stage, and be 4275 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 4276 // illegal and must be expanded. Since we know that the constants are 4277 // sign-extended 32-bit values, we use VMV_V_X_VL directly. 4278 bool IsRV32E64 = 4279 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 4280 4281 if (!IsRV32E64) { 4282 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 4283 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 4284 } else { 4285 SplatZero = 4286 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4287 SplatZero, DAG.getRegister(RISCV::X0, XLenVT)); 4288 SplatTrueVal = 4289 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4290 SplatTrueVal, DAG.getRegister(RISCV::X0, XLenVT)); 4291 } 4292 4293 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4294 } 4295 4296 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4297 MVT I1ContainerVT = 4298 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4299 4300 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4301 4302 SDValue Mask, VL; 4303 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4304 4305 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4306 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4307 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4308 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4309 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4310 SplatTrueVal, SplatZero, VL); 4311 4312 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4313 } 4314 4315 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4316 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4317 MVT ExtVT = Op.getSimpleValueType(); 4318 // Only custom-lower extensions from fixed-length vector types. 4319 if (!ExtVT.isFixedLengthVector()) 4320 return Op; 4321 MVT VT = Op.getOperand(0).getSimpleValueType(); 4322 // Grab the canonical container type for the extended type. Infer the smaller 4323 // type from that to ensure the same number of vector elements, as we know 4324 // the LMUL will be sufficient to hold the smaller type. 4325 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4326 // Get the extended container type manually to ensure the same number of 4327 // vector elements between source and dest. 4328 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4329 ContainerExtVT.getVectorElementCount()); 4330 4331 SDValue Op1 = 4332 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4333 4334 SDLoc DL(Op); 4335 SDValue Mask, VL; 4336 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4337 4338 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4339 4340 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4341 } 4342 4343 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4344 // setcc operation: 4345 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4346 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 4347 SelectionDAG &DAG) const { 4348 SDLoc DL(Op); 4349 EVT MaskVT = Op.getValueType(); 4350 // Only expect to custom-lower truncations to mask types 4351 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4352 "Unexpected type for vector mask lowering"); 4353 SDValue Src = Op.getOperand(0); 4354 MVT VecVT = Src.getSimpleValueType(); 4355 4356 // If this is a fixed vector, we need to convert it to a scalable vector. 4357 MVT ContainerVT = VecVT; 4358 if (VecVT.isFixedLengthVector()) { 4359 ContainerVT = getContainerForFixedLengthVector(VecVT); 4360 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4361 } 4362 4363 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4364 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4365 4366 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4367 DAG.getUNDEF(ContainerVT), SplatOne); 4368 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4369 DAG.getUNDEF(ContainerVT), SplatZero); 4370 4371 if (VecVT.isScalableVector()) { 4372 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 4373 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 4374 } 4375 4376 SDValue Mask, VL; 4377 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4378 4379 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4380 SDValue Trunc = 4381 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4382 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4383 DAG.getCondCode(ISD::SETNE), Mask, VL); 4384 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4385 } 4386 4387 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4388 // first position of a vector, and that vector is slid up to the insert index. 4389 // By limiting the active vector length to index+1 and merging with the 4390 // original vector (with an undisturbed tail policy for elements >= VL), we 4391 // achieve the desired result of leaving all elements untouched except the one 4392 // at VL-1, which is replaced with the desired value. 4393 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4394 SelectionDAG &DAG) const { 4395 SDLoc DL(Op); 4396 MVT VecVT = Op.getSimpleValueType(); 4397 SDValue Vec = Op.getOperand(0); 4398 SDValue Val = Op.getOperand(1); 4399 SDValue Idx = Op.getOperand(2); 4400 4401 if (VecVT.getVectorElementType() == MVT::i1) { 4402 // FIXME: For now we just promote to an i8 vector and insert into that, 4403 // but this is probably not optimal. 4404 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4405 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4406 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4407 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4408 } 4409 4410 MVT ContainerVT = VecVT; 4411 // If the operand is a fixed-length vector, convert to a scalable one. 4412 if (VecVT.isFixedLengthVector()) { 4413 ContainerVT = getContainerForFixedLengthVector(VecVT); 4414 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4415 } 4416 4417 MVT XLenVT = Subtarget.getXLenVT(); 4418 4419 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4420 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4421 // Even i64-element vectors on RV32 can be lowered without scalar 4422 // legalization if the most-significant 32 bits of the value are not affected 4423 // by the sign-extension of the lower 32 bits. 4424 // TODO: We could also catch sign extensions of a 32-bit value. 4425 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4426 const auto *CVal = cast<ConstantSDNode>(Val); 4427 if (isInt<32>(CVal->getSExtValue())) { 4428 IsLegalInsert = true; 4429 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4430 } 4431 } 4432 4433 SDValue Mask, VL; 4434 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4435 4436 SDValue ValInVec; 4437 4438 if (IsLegalInsert) { 4439 unsigned Opc = 4440 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4441 if (isNullConstant(Idx)) { 4442 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4443 if (!VecVT.isFixedLengthVector()) 4444 return Vec; 4445 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4446 } 4447 ValInVec = 4448 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4449 } else { 4450 // On RV32, i64-element vectors must be specially handled to place the 4451 // value at element 0, by using two vslide1up instructions in sequence on 4452 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4453 // this. 4454 SDValue One = DAG.getConstant(1, DL, XLenVT); 4455 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4456 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4457 MVT I32ContainerVT = 4458 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4459 SDValue I32Mask = 4460 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4461 // Limit the active VL to two. 4462 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4463 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4464 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4465 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4466 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4467 // First slide in the hi value, then the lo in underneath it. 4468 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4469 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4470 I32Mask, InsertI64VL); 4471 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4472 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4473 I32Mask, InsertI64VL); 4474 // Bitcast back to the right container type. 4475 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4476 } 4477 4478 // Now that the value is in a vector, slide it into position. 4479 SDValue InsertVL = 4480 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4481 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4482 ValInVec, Idx, Mask, InsertVL); 4483 if (!VecVT.isFixedLengthVector()) 4484 return Slideup; 4485 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4486 } 4487 4488 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4489 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4490 // types this is done using VMV_X_S to allow us to glean information about the 4491 // sign bits of the result. 4492 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4493 SelectionDAG &DAG) const { 4494 SDLoc DL(Op); 4495 SDValue Idx = Op.getOperand(1); 4496 SDValue Vec = Op.getOperand(0); 4497 EVT EltVT = Op.getValueType(); 4498 MVT VecVT = Vec.getSimpleValueType(); 4499 MVT XLenVT = Subtarget.getXLenVT(); 4500 4501 if (VecVT.getVectorElementType() == MVT::i1) { 4502 if (VecVT.isFixedLengthVector()) { 4503 unsigned NumElts = VecVT.getVectorNumElements(); 4504 if (NumElts >= 8) { 4505 MVT WideEltVT; 4506 unsigned WidenVecLen; 4507 SDValue ExtractElementIdx; 4508 SDValue ExtractBitIdx; 4509 unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors(); 4510 MVT LargestEltVT = MVT::getIntegerVT( 4511 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4512 if (NumElts <= LargestEltVT.getSizeInBits()) { 4513 assert(isPowerOf2_32(NumElts) && 4514 "the number of elements should be power of 2"); 4515 WideEltVT = MVT::getIntegerVT(NumElts); 4516 WidenVecLen = 1; 4517 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4518 ExtractBitIdx = Idx; 4519 } else { 4520 WideEltVT = LargestEltVT; 4521 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4522 // extract element index = index / element width 4523 ExtractElementIdx = DAG.getNode( 4524 ISD::SRL, DL, XLenVT, Idx, 4525 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4526 // mask bit index = index % element width 4527 ExtractBitIdx = DAG.getNode( 4528 ISD::AND, DL, XLenVT, Idx, 4529 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4530 } 4531 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4532 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4533 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4534 Vec, ExtractElementIdx); 4535 // Extract the bit from GPR. 4536 SDValue ShiftRight = 4537 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4538 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4539 DAG.getConstant(1, DL, XLenVT)); 4540 } 4541 } 4542 // Otherwise, promote to an i8 vector and extract from that. 4543 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4544 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4545 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4546 } 4547 4548 // If this is a fixed vector, we need to convert it to a scalable vector. 4549 MVT ContainerVT = VecVT; 4550 if (VecVT.isFixedLengthVector()) { 4551 ContainerVT = getContainerForFixedLengthVector(VecVT); 4552 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4553 } 4554 4555 // If the index is 0, the vector is already in the right position. 4556 if (!isNullConstant(Idx)) { 4557 // Use a VL of 1 to avoid processing more elements than we need. 4558 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4559 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4560 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4561 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4562 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4563 } 4564 4565 if (!EltVT.isInteger()) { 4566 // Floating-point extracts are handled in TableGen. 4567 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4568 DAG.getConstant(0, DL, XLenVT)); 4569 } 4570 4571 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4572 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4573 } 4574 4575 // Some RVV intrinsics may claim that they want an integer operand to be 4576 // promoted or expanded. 4577 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4578 const RISCVSubtarget &Subtarget) { 4579 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4580 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4581 "Unexpected opcode"); 4582 4583 if (!Subtarget.hasVInstructions()) 4584 return SDValue(); 4585 4586 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4587 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4588 SDLoc DL(Op); 4589 4590 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4591 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4592 if (!II || !II->hasScalarOperand()) 4593 return SDValue(); 4594 4595 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4596 assert(SplatOp < Op.getNumOperands()); 4597 4598 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4599 SDValue &ScalarOp = Operands[SplatOp]; 4600 MVT OpVT = ScalarOp.getSimpleValueType(); 4601 MVT XLenVT = Subtarget.getXLenVT(); 4602 4603 // If this isn't a scalar, or its type is XLenVT we're done. 4604 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4605 return SDValue(); 4606 4607 // Simplest case is that the operand needs to be promoted to XLenVT. 4608 if (OpVT.bitsLT(XLenVT)) { 4609 // If the operand is a constant, sign extend to increase our chances 4610 // of being able to use a .vi instruction. ANY_EXTEND would become a 4611 // a zero extend and the simm5 check in isel would fail. 4612 // FIXME: Should we ignore the upper bits in isel instead? 4613 unsigned ExtOpc = 4614 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4615 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4616 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4617 } 4618 4619 // Use the previous operand to get the vXi64 VT. The result might be a mask 4620 // VT for compares. Using the previous operand assumes that the previous 4621 // operand will never have a smaller element size than a scalar operand and 4622 // that a widening operation never uses SEW=64. 4623 // NOTE: If this fails the below assert, we can probably just find the 4624 // element count from any operand or result and use it to construct the VT. 4625 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4626 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4627 4628 // The more complex case is when the scalar is larger than XLenVT. 4629 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4630 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4631 4632 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4633 // on the instruction to sign-extend since SEW>XLEN. 4634 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4635 if (isInt<32>(CVal->getSExtValue())) { 4636 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4637 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4638 } 4639 } 4640 4641 switch (IntNo) { 4642 case Intrinsic::riscv_vslide1up: 4643 case Intrinsic::riscv_vslide1down: 4644 case Intrinsic::riscv_vslide1up_mask: 4645 case Intrinsic::riscv_vslide1down_mask: { 4646 // We need to special case these when the scalar is larger than XLen. 4647 unsigned NumOps = Op.getNumOperands(); 4648 bool IsMasked = NumOps == 7; 4649 4650 // Convert the vector source to the equivalent nxvXi32 vector. 4651 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4652 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4653 4654 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4655 DAG.getConstant(0, DL, XLenVT)); 4656 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4657 DAG.getConstant(1, DL, XLenVT)); 4658 4659 // Double the VL since we halved SEW. 4660 SDValue VL = getVLOperand(Op); 4661 SDValue I32VL = 4662 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4663 4664 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4665 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4666 4667 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4668 // instructions. 4669 SDValue Passthru; 4670 if (IsMasked) 4671 Passthru = DAG.getUNDEF(I32VT); 4672 else 4673 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4674 4675 if (IntNo == Intrinsic::riscv_vslide1up || 4676 IntNo == Intrinsic::riscv_vslide1up_mask) { 4677 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4678 ScalarHi, I32Mask, I32VL); 4679 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4680 ScalarLo, I32Mask, I32VL); 4681 } else { 4682 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4683 ScalarLo, I32Mask, I32VL); 4684 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4685 ScalarHi, I32Mask, I32VL); 4686 } 4687 4688 // Convert back to nxvXi64. 4689 Vec = DAG.getBitcast(VT, Vec); 4690 4691 if (!IsMasked) 4692 return Vec; 4693 // Apply mask after the operation. 4694 SDValue Mask = Operands[NumOps - 3]; 4695 SDValue MaskedOff = Operands[1]; 4696 // Assume Policy operand is the last operand. 4697 uint64_t Policy = 4698 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4699 // We don't need to select maskedoff if it's undef. 4700 if (MaskedOff.isUndef()) 4701 return Vec; 4702 // TAMU 4703 if (Policy == RISCVII::TAIL_AGNOSTIC) 4704 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4705 VL); 4706 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4707 // It's fine because vmerge does not care mask policy. 4708 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4709 } 4710 } 4711 4712 // We need to convert the scalar to a splat vector. 4713 // FIXME: Can we implicitly truncate the scalar if it is known to 4714 // be sign extended? 4715 SDValue VL = getVLOperand(Op); 4716 assert(VL.getValueType() == XLenVT); 4717 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4718 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4719 } 4720 4721 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4722 SelectionDAG &DAG) const { 4723 unsigned IntNo = Op.getConstantOperandVal(0); 4724 SDLoc DL(Op); 4725 MVT XLenVT = Subtarget.getXLenVT(); 4726 4727 switch (IntNo) { 4728 default: 4729 break; // Don't custom lower most intrinsics. 4730 case Intrinsic::thread_pointer: { 4731 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4732 return DAG.getRegister(RISCV::X4, PtrVT); 4733 } 4734 case Intrinsic::riscv_orc_b: 4735 case Intrinsic::riscv_brev8: { 4736 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4737 unsigned Opc = 4738 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4739 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4740 DAG.getConstant(7, DL, XLenVT)); 4741 } 4742 case Intrinsic::riscv_grev: 4743 case Intrinsic::riscv_gorc: { 4744 unsigned Opc = 4745 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4746 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4747 } 4748 case Intrinsic::riscv_zip: 4749 case Intrinsic::riscv_unzip: { 4750 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4751 // For i32 the immediate is 15. For i64 the immediate is 31. 4752 unsigned Opc = 4753 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4754 unsigned BitWidth = Op.getValueSizeInBits(); 4755 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4756 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4757 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4758 } 4759 case Intrinsic::riscv_shfl: 4760 case Intrinsic::riscv_unshfl: { 4761 unsigned Opc = 4762 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4763 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4764 } 4765 case Intrinsic::riscv_bcompress: 4766 case Intrinsic::riscv_bdecompress: { 4767 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4768 : RISCVISD::BDECOMPRESS; 4769 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4770 } 4771 case Intrinsic::riscv_bfp: 4772 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4773 Op.getOperand(2)); 4774 case Intrinsic::riscv_fsl: 4775 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4776 Op.getOperand(2), Op.getOperand(3)); 4777 case Intrinsic::riscv_fsr: 4778 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4779 Op.getOperand(2), Op.getOperand(3)); 4780 case Intrinsic::riscv_vmv_x_s: 4781 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4782 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4783 Op.getOperand(1)); 4784 case Intrinsic::riscv_vmv_v_x: 4785 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4786 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4787 Subtarget); 4788 case Intrinsic::riscv_vfmv_v_f: 4789 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4790 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4791 case Intrinsic::riscv_vmv_s_x: { 4792 SDValue Scalar = Op.getOperand(2); 4793 4794 if (Scalar.getValueType().bitsLE(XLenVT)) { 4795 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4796 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4797 Op.getOperand(1), Scalar, Op.getOperand(3)); 4798 } 4799 4800 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4801 4802 // This is an i64 value that lives in two scalar registers. We have to 4803 // insert this in a convoluted way. First we build vXi64 splat containing 4804 // the/ two values that we assemble using some bit math. Next we'll use 4805 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4806 // to merge element 0 from our splat into the source vector. 4807 // FIXME: This is probably not the best way to do this, but it is 4808 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4809 // point. 4810 // sw lo, (a0) 4811 // sw hi, 4(a0) 4812 // vlse vX, (a0) 4813 // 4814 // vid.v vVid 4815 // vmseq.vx mMask, vVid, 0 4816 // vmerge.vvm vDest, vSrc, vVal, mMask 4817 MVT VT = Op.getSimpleValueType(); 4818 SDValue Vec = Op.getOperand(1); 4819 SDValue VL = getVLOperand(Op); 4820 4821 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4822 if (Op.getOperand(1).isUndef()) 4823 return SplattedVal; 4824 SDValue SplattedIdx = 4825 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4826 DAG.getConstant(0, DL, MVT::i32), VL); 4827 4828 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4829 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4830 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4831 SDValue SelectCond = 4832 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4833 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4834 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4835 Vec, VL); 4836 } 4837 } 4838 4839 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4840 } 4841 4842 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4843 SelectionDAG &DAG) const { 4844 unsigned IntNo = Op.getConstantOperandVal(1); 4845 switch (IntNo) { 4846 default: 4847 break; 4848 case Intrinsic::riscv_masked_strided_load: { 4849 SDLoc DL(Op); 4850 MVT XLenVT = Subtarget.getXLenVT(); 4851 4852 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4853 // the selection of the masked intrinsics doesn't do this for us. 4854 SDValue Mask = Op.getOperand(5); 4855 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4856 4857 MVT VT = Op->getSimpleValueType(0); 4858 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4859 4860 SDValue PassThru = Op.getOperand(2); 4861 if (!IsUnmasked) { 4862 MVT MaskVT = 4863 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4864 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4865 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4866 } 4867 4868 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4869 4870 SDValue IntID = DAG.getTargetConstant( 4871 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4872 XLenVT); 4873 4874 auto *Load = cast<MemIntrinsicSDNode>(Op); 4875 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4876 if (IsUnmasked) 4877 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4878 else 4879 Ops.push_back(PassThru); 4880 Ops.push_back(Op.getOperand(3)); // Ptr 4881 Ops.push_back(Op.getOperand(4)); // Stride 4882 if (!IsUnmasked) 4883 Ops.push_back(Mask); 4884 Ops.push_back(VL); 4885 if (!IsUnmasked) { 4886 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4887 Ops.push_back(Policy); 4888 } 4889 4890 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4891 SDValue Result = 4892 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4893 Load->getMemoryVT(), Load->getMemOperand()); 4894 SDValue Chain = Result.getValue(1); 4895 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4896 return DAG.getMergeValues({Result, Chain}, DL); 4897 } 4898 case Intrinsic::riscv_seg2_load: 4899 case Intrinsic::riscv_seg3_load: 4900 case Intrinsic::riscv_seg4_load: 4901 case Intrinsic::riscv_seg5_load: 4902 case Intrinsic::riscv_seg6_load: 4903 case Intrinsic::riscv_seg7_load: 4904 case Intrinsic::riscv_seg8_load: { 4905 SDLoc DL(Op); 4906 static const Intrinsic::ID VlsegInts[7] = { 4907 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4908 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4909 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4910 Intrinsic::riscv_vlseg8}; 4911 unsigned NF = Op->getNumValues() - 1; 4912 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4913 MVT XLenVT = Subtarget.getXLenVT(); 4914 MVT VT = Op->getSimpleValueType(0); 4915 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4916 4917 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4918 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4919 auto *Load = cast<MemIntrinsicSDNode>(Op); 4920 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4921 ContainerVTs.push_back(MVT::Other); 4922 SDVTList VTs = DAG.getVTList(ContainerVTs); 4923 SDValue Result = 4924 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, 4925 {Load->getChain(), IntID, Op.getOperand(2), VL}, 4926 Load->getMemoryVT(), Load->getMemOperand()); 4927 SmallVector<SDValue, 9> Results; 4928 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4929 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4930 DAG, Subtarget)); 4931 Results.push_back(Result.getValue(NF)); 4932 return DAG.getMergeValues(Results, DL); 4933 } 4934 } 4935 4936 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4937 } 4938 4939 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4940 SelectionDAG &DAG) const { 4941 unsigned IntNo = Op.getConstantOperandVal(1); 4942 switch (IntNo) { 4943 default: 4944 break; 4945 case Intrinsic::riscv_masked_strided_store: { 4946 SDLoc DL(Op); 4947 MVT XLenVT = Subtarget.getXLenVT(); 4948 4949 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4950 // the selection of the masked intrinsics doesn't do this for us. 4951 SDValue Mask = Op.getOperand(5); 4952 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4953 4954 SDValue Val = Op.getOperand(2); 4955 MVT VT = Val.getSimpleValueType(); 4956 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4957 4958 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4959 if (!IsUnmasked) { 4960 MVT MaskVT = 4961 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4962 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4963 } 4964 4965 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4966 4967 SDValue IntID = DAG.getTargetConstant( 4968 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4969 XLenVT); 4970 4971 auto *Store = cast<MemIntrinsicSDNode>(Op); 4972 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4973 Ops.push_back(Val); 4974 Ops.push_back(Op.getOperand(3)); // Ptr 4975 Ops.push_back(Op.getOperand(4)); // Stride 4976 if (!IsUnmasked) 4977 Ops.push_back(Mask); 4978 Ops.push_back(VL); 4979 4980 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4981 Ops, Store->getMemoryVT(), 4982 Store->getMemOperand()); 4983 } 4984 } 4985 4986 return SDValue(); 4987 } 4988 4989 static MVT getLMUL1VT(MVT VT) { 4990 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4991 "Unexpected vector MVT"); 4992 return MVT::getScalableVectorVT( 4993 VT.getVectorElementType(), 4994 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4995 } 4996 4997 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4998 switch (ISDOpcode) { 4999 default: 5000 llvm_unreachable("Unhandled reduction"); 5001 case ISD::VECREDUCE_ADD: 5002 return RISCVISD::VECREDUCE_ADD_VL; 5003 case ISD::VECREDUCE_UMAX: 5004 return RISCVISD::VECREDUCE_UMAX_VL; 5005 case ISD::VECREDUCE_SMAX: 5006 return RISCVISD::VECREDUCE_SMAX_VL; 5007 case ISD::VECREDUCE_UMIN: 5008 return RISCVISD::VECREDUCE_UMIN_VL; 5009 case ISD::VECREDUCE_SMIN: 5010 return RISCVISD::VECREDUCE_SMIN_VL; 5011 case ISD::VECREDUCE_AND: 5012 return RISCVISD::VECREDUCE_AND_VL; 5013 case ISD::VECREDUCE_OR: 5014 return RISCVISD::VECREDUCE_OR_VL; 5015 case ISD::VECREDUCE_XOR: 5016 return RISCVISD::VECREDUCE_XOR_VL; 5017 } 5018 } 5019 5020 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5021 SelectionDAG &DAG, 5022 bool IsVP) const { 5023 SDLoc DL(Op); 5024 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5025 MVT VecVT = Vec.getSimpleValueType(); 5026 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5027 Op.getOpcode() == ISD::VECREDUCE_OR || 5028 Op.getOpcode() == ISD::VECREDUCE_XOR || 5029 Op.getOpcode() == ISD::VP_REDUCE_AND || 5030 Op.getOpcode() == ISD::VP_REDUCE_OR || 5031 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5032 "Unexpected reduction lowering"); 5033 5034 MVT XLenVT = Subtarget.getXLenVT(); 5035 assert(Op.getValueType() == XLenVT && 5036 "Expected reduction output to be legalized to XLenVT"); 5037 5038 MVT ContainerVT = VecVT; 5039 if (VecVT.isFixedLengthVector()) { 5040 ContainerVT = getContainerForFixedLengthVector(VecVT); 5041 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5042 } 5043 5044 SDValue Mask, VL; 5045 if (IsVP) { 5046 Mask = Op.getOperand(2); 5047 VL = Op.getOperand(3); 5048 } else { 5049 std::tie(Mask, VL) = 5050 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5051 } 5052 5053 unsigned BaseOpc; 5054 ISD::CondCode CC; 5055 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5056 5057 switch (Op.getOpcode()) { 5058 default: 5059 llvm_unreachable("Unhandled reduction"); 5060 case ISD::VECREDUCE_AND: 5061 case ISD::VP_REDUCE_AND: { 5062 // vcpop ~x == 0 5063 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5064 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5065 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5066 CC = ISD::SETEQ; 5067 BaseOpc = ISD::AND; 5068 break; 5069 } 5070 case ISD::VECREDUCE_OR: 5071 case ISD::VP_REDUCE_OR: 5072 // vcpop x != 0 5073 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5074 CC = ISD::SETNE; 5075 BaseOpc = ISD::OR; 5076 break; 5077 case ISD::VECREDUCE_XOR: 5078 case ISD::VP_REDUCE_XOR: { 5079 // ((vcpop x) & 1) != 0 5080 SDValue One = DAG.getConstant(1, DL, XLenVT); 5081 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5082 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5083 CC = ISD::SETNE; 5084 BaseOpc = ISD::XOR; 5085 break; 5086 } 5087 } 5088 5089 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5090 5091 if (!IsVP) 5092 return SetCC; 5093 5094 // Now include the start value in the operation. 5095 // Note that we must return the start value when no elements are operated 5096 // upon. The vcpop instructions we've emitted in each case above will return 5097 // 0 for an inactive vector, and so we've already received the neutral value: 5098 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5099 // can simply include the start value. 5100 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5101 } 5102 5103 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5104 SelectionDAG &DAG) const { 5105 SDLoc DL(Op); 5106 SDValue Vec = Op.getOperand(0); 5107 EVT VecEVT = Vec.getValueType(); 5108 5109 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5110 5111 // Due to ordering in legalize types we may have a vector type that needs to 5112 // be split. Do that manually so we can get down to a legal type. 5113 while (getTypeAction(*DAG.getContext(), VecEVT) == 5114 TargetLowering::TypeSplitVector) { 5115 SDValue Lo, Hi; 5116 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5117 VecEVT = Lo.getValueType(); 5118 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5119 } 5120 5121 // TODO: The type may need to be widened rather than split. Or widened before 5122 // it can be split. 5123 if (!isTypeLegal(VecEVT)) 5124 return SDValue(); 5125 5126 MVT VecVT = VecEVT.getSimpleVT(); 5127 MVT VecEltVT = VecVT.getVectorElementType(); 5128 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5129 5130 MVT ContainerVT = VecVT; 5131 if (VecVT.isFixedLengthVector()) { 5132 ContainerVT = getContainerForFixedLengthVector(VecVT); 5133 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5134 } 5135 5136 MVT M1VT = getLMUL1VT(ContainerVT); 5137 MVT XLenVT = Subtarget.getXLenVT(); 5138 5139 SDValue Mask, VL; 5140 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5141 5142 SDValue NeutralElem = 5143 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5144 SDValue IdentitySplat = 5145 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5146 M1VT, DL, DAG, Subtarget); 5147 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5148 IdentitySplat, Mask, VL); 5149 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5150 DAG.getConstant(0, DL, XLenVT)); 5151 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5152 } 5153 5154 // Given a reduction op, this function returns the matching reduction opcode, 5155 // the vector SDValue and the scalar SDValue required to lower this to a 5156 // RISCVISD node. 5157 static std::tuple<unsigned, SDValue, SDValue> 5158 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5159 SDLoc DL(Op); 5160 auto Flags = Op->getFlags(); 5161 unsigned Opcode = Op.getOpcode(); 5162 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5163 switch (Opcode) { 5164 default: 5165 llvm_unreachable("Unhandled reduction"); 5166 case ISD::VECREDUCE_FADD: { 5167 // Use positive zero if we can. It is cheaper to materialize. 5168 SDValue Zero = 5169 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5170 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5171 } 5172 case ISD::VECREDUCE_SEQ_FADD: 5173 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5174 Op.getOperand(0)); 5175 case ISD::VECREDUCE_FMIN: 5176 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5177 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5178 case ISD::VECREDUCE_FMAX: 5179 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5180 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5181 } 5182 } 5183 5184 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5185 SelectionDAG &DAG) const { 5186 SDLoc DL(Op); 5187 MVT VecEltVT = Op.getSimpleValueType(); 5188 5189 unsigned RVVOpcode; 5190 SDValue VectorVal, ScalarVal; 5191 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5192 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5193 MVT VecVT = VectorVal.getSimpleValueType(); 5194 5195 MVT ContainerVT = VecVT; 5196 if (VecVT.isFixedLengthVector()) { 5197 ContainerVT = getContainerForFixedLengthVector(VecVT); 5198 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5199 } 5200 5201 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5202 MVT XLenVT = Subtarget.getXLenVT(); 5203 5204 SDValue Mask, VL; 5205 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5206 5207 SDValue ScalarSplat = 5208 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5209 M1VT, DL, DAG, Subtarget); 5210 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5211 VectorVal, ScalarSplat, Mask, VL); 5212 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5213 DAG.getConstant(0, DL, XLenVT)); 5214 } 5215 5216 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5217 switch (ISDOpcode) { 5218 default: 5219 llvm_unreachable("Unhandled reduction"); 5220 case ISD::VP_REDUCE_ADD: 5221 return RISCVISD::VECREDUCE_ADD_VL; 5222 case ISD::VP_REDUCE_UMAX: 5223 return RISCVISD::VECREDUCE_UMAX_VL; 5224 case ISD::VP_REDUCE_SMAX: 5225 return RISCVISD::VECREDUCE_SMAX_VL; 5226 case ISD::VP_REDUCE_UMIN: 5227 return RISCVISD::VECREDUCE_UMIN_VL; 5228 case ISD::VP_REDUCE_SMIN: 5229 return RISCVISD::VECREDUCE_SMIN_VL; 5230 case ISD::VP_REDUCE_AND: 5231 return RISCVISD::VECREDUCE_AND_VL; 5232 case ISD::VP_REDUCE_OR: 5233 return RISCVISD::VECREDUCE_OR_VL; 5234 case ISD::VP_REDUCE_XOR: 5235 return RISCVISD::VECREDUCE_XOR_VL; 5236 case ISD::VP_REDUCE_FADD: 5237 return RISCVISD::VECREDUCE_FADD_VL; 5238 case ISD::VP_REDUCE_SEQ_FADD: 5239 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5240 case ISD::VP_REDUCE_FMAX: 5241 return RISCVISD::VECREDUCE_FMAX_VL; 5242 case ISD::VP_REDUCE_FMIN: 5243 return RISCVISD::VECREDUCE_FMIN_VL; 5244 } 5245 } 5246 5247 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5248 SelectionDAG &DAG) const { 5249 SDLoc DL(Op); 5250 SDValue Vec = Op.getOperand(1); 5251 EVT VecEVT = Vec.getValueType(); 5252 5253 // TODO: The type may need to be widened rather than split. Or widened before 5254 // it can be split. 5255 if (!isTypeLegal(VecEVT)) 5256 return SDValue(); 5257 5258 MVT VecVT = VecEVT.getSimpleVT(); 5259 MVT VecEltVT = VecVT.getVectorElementType(); 5260 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5261 5262 MVT ContainerVT = VecVT; 5263 if (VecVT.isFixedLengthVector()) { 5264 ContainerVT = getContainerForFixedLengthVector(VecVT); 5265 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5266 } 5267 5268 SDValue VL = Op.getOperand(3); 5269 SDValue Mask = Op.getOperand(2); 5270 5271 MVT M1VT = getLMUL1VT(ContainerVT); 5272 MVT XLenVT = Subtarget.getXLenVT(); 5273 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5274 5275 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5276 DAG.getConstant(1, DL, XLenVT), M1VT, 5277 DL, DAG, Subtarget); 5278 SDValue Reduction = 5279 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5280 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5281 DAG.getConstant(0, DL, XLenVT)); 5282 if (!VecVT.isInteger()) 5283 return Elt0; 5284 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5285 } 5286 5287 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5288 SelectionDAG &DAG) const { 5289 SDValue Vec = Op.getOperand(0); 5290 SDValue SubVec = Op.getOperand(1); 5291 MVT VecVT = Vec.getSimpleValueType(); 5292 MVT SubVecVT = SubVec.getSimpleValueType(); 5293 5294 SDLoc DL(Op); 5295 MVT XLenVT = Subtarget.getXLenVT(); 5296 unsigned OrigIdx = Op.getConstantOperandVal(2); 5297 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5298 5299 // We don't have the ability to slide mask vectors up indexed by their i1 5300 // elements; the smallest we can do is i8. Often we are able to bitcast to 5301 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5302 // into a scalable one, we might not necessarily have enough scalable 5303 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5304 if (SubVecVT.getVectorElementType() == MVT::i1 && 5305 (OrigIdx != 0 || !Vec.isUndef())) { 5306 if (VecVT.getVectorMinNumElements() >= 8 && 5307 SubVecVT.getVectorMinNumElements() >= 8) { 5308 assert(OrigIdx % 8 == 0 && "Invalid index"); 5309 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5310 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5311 "Unexpected mask vector lowering"); 5312 OrigIdx /= 8; 5313 SubVecVT = 5314 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5315 SubVecVT.isScalableVector()); 5316 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5317 VecVT.isScalableVector()); 5318 Vec = DAG.getBitcast(VecVT, Vec); 5319 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5320 } else { 5321 // We can't slide this mask vector up indexed by its i1 elements. 5322 // This poses a problem when we wish to insert a scalable vector which 5323 // can't be re-expressed as a larger type. Just choose the slow path and 5324 // extend to a larger type, then truncate back down. 5325 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5326 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5327 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5328 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5329 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5330 Op.getOperand(2)); 5331 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5332 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5333 } 5334 } 5335 5336 // If the subvector vector is a fixed-length type, we cannot use subregister 5337 // manipulation to simplify the codegen; we don't know which register of a 5338 // LMUL group contains the specific subvector as we only know the minimum 5339 // register size. Therefore we must slide the vector group up the full 5340 // amount. 5341 if (SubVecVT.isFixedLengthVector()) { 5342 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5343 return Op; 5344 MVT ContainerVT = VecVT; 5345 if (VecVT.isFixedLengthVector()) { 5346 ContainerVT = getContainerForFixedLengthVector(VecVT); 5347 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5348 } 5349 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5350 DAG.getUNDEF(ContainerVT), SubVec, 5351 DAG.getConstant(0, DL, XLenVT)); 5352 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5353 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5354 return DAG.getBitcast(Op.getValueType(), SubVec); 5355 } 5356 SDValue Mask = 5357 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5358 // Set the vector length to only the number of elements we care about. Note 5359 // that for slideup this includes the offset. 5360 SDValue VL = 5361 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5362 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5363 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5364 SubVec, SlideupAmt, Mask, VL); 5365 if (VecVT.isFixedLengthVector()) 5366 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5367 return DAG.getBitcast(Op.getValueType(), Slideup); 5368 } 5369 5370 unsigned SubRegIdx, RemIdx; 5371 std::tie(SubRegIdx, RemIdx) = 5372 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5373 VecVT, SubVecVT, OrigIdx, TRI); 5374 5375 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5376 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5377 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5378 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5379 5380 // 1. If the Idx has been completely eliminated and this subvector's size is 5381 // a vector register or a multiple thereof, or the surrounding elements are 5382 // undef, then this is a subvector insert which naturally aligns to a vector 5383 // register. These can easily be handled using subregister manipulation. 5384 // 2. If the subvector is smaller than a vector register, then the insertion 5385 // must preserve the undisturbed elements of the register. We do this by 5386 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5387 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5388 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5389 // LMUL=1 type back into the larger vector (resolving to another subregister 5390 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5391 // to avoid allocating a large register group to hold our subvector. 5392 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5393 return Op; 5394 5395 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5396 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5397 // (in our case undisturbed). This means we can set up a subvector insertion 5398 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5399 // size of the subvector. 5400 MVT InterSubVT = VecVT; 5401 SDValue AlignedExtract = Vec; 5402 unsigned AlignedIdx = OrigIdx - RemIdx; 5403 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5404 InterSubVT = getLMUL1VT(VecVT); 5405 // Extract a subvector equal to the nearest full vector register type. This 5406 // should resolve to a EXTRACT_SUBREG instruction. 5407 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5408 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5409 } 5410 5411 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5412 // For scalable vectors this must be further multiplied by vscale. 5413 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5414 5415 SDValue Mask, VL; 5416 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5417 5418 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5419 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5420 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5421 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5422 5423 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5424 DAG.getUNDEF(InterSubVT), SubVec, 5425 DAG.getConstant(0, DL, XLenVT)); 5426 5427 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5428 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5429 5430 // If required, insert this subvector back into the correct vector register. 5431 // This should resolve to an INSERT_SUBREG instruction. 5432 if (VecVT.bitsGT(InterSubVT)) 5433 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5434 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5435 5436 // We might have bitcast from a mask type: cast back to the original type if 5437 // required. 5438 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5439 } 5440 5441 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5442 SelectionDAG &DAG) const { 5443 SDValue Vec = Op.getOperand(0); 5444 MVT SubVecVT = Op.getSimpleValueType(); 5445 MVT VecVT = Vec.getSimpleValueType(); 5446 5447 SDLoc DL(Op); 5448 MVT XLenVT = Subtarget.getXLenVT(); 5449 unsigned OrigIdx = Op.getConstantOperandVal(1); 5450 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5451 5452 // We don't have the ability to slide mask vectors down indexed by their i1 5453 // elements; the smallest we can do is i8. Often we are able to bitcast to 5454 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5455 // from a scalable one, we might not necessarily have enough scalable 5456 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5457 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5458 if (VecVT.getVectorMinNumElements() >= 8 && 5459 SubVecVT.getVectorMinNumElements() >= 8) { 5460 assert(OrigIdx % 8 == 0 && "Invalid index"); 5461 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5462 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5463 "Unexpected mask vector lowering"); 5464 OrigIdx /= 8; 5465 SubVecVT = 5466 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5467 SubVecVT.isScalableVector()); 5468 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5469 VecVT.isScalableVector()); 5470 Vec = DAG.getBitcast(VecVT, Vec); 5471 } else { 5472 // We can't slide this mask vector down, indexed by its i1 elements. 5473 // This poses a problem when we wish to extract a scalable vector which 5474 // can't be re-expressed as a larger type. Just choose the slow path and 5475 // extend to a larger type, then truncate back down. 5476 // TODO: We could probably improve this when extracting certain fixed 5477 // from fixed, where we can extract as i8 and shift the correct element 5478 // right to reach the desired subvector? 5479 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5480 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5481 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5482 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5483 Op.getOperand(1)); 5484 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5485 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5486 } 5487 } 5488 5489 // If the subvector vector is a fixed-length type, we cannot use subregister 5490 // manipulation to simplify the codegen; we don't know which register of a 5491 // LMUL group contains the specific subvector as we only know the minimum 5492 // register size. Therefore we must slide the vector group down the full 5493 // amount. 5494 if (SubVecVT.isFixedLengthVector()) { 5495 // With an index of 0 this is a cast-like subvector, which can be performed 5496 // with subregister operations. 5497 if (OrigIdx == 0) 5498 return Op; 5499 MVT ContainerVT = VecVT; 5500 if (VecVT.isFixedLengthVector()) { 5501 ContainerVT = getContainerForFixedLengthVector(VecVT); 5502 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5503 } 5504 SDValue Mask = 5505 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5506 // Set the vector length to only the number of elements we care about. This 5507 // avoids sliding down elements we're going to discard straight away. 5508 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5509 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5510 SDValue Slidedown = 5511 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5512 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5513 // Now we can use a cast-like subvector extract to get the result. 5514 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5515 DAG.getConstant(0, DL, XLenVT)); 5516 return DAG.getBitcast(Op.getValueType(), Slidedown); 5517 } 5518 5519 unsigned SubRegIdx, RemIdx; 5520 std::tie(SubRegIdx, RemIdx) = 5521 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5522 VecVT, SubVecVT, OrigIdx, TRI); 5523 5524 // If the Idx has been completely eliminated then this is a subvector extract 5525 // which naturally aligns to a vector register. These can easily be handled 5526 // using subregister manipulation. 5527 if (RemIdx == 0) 5528 return Op; 5529 5530 // Else we must shift our vector register directly to extract the subvector. 5531 // Do this using VSLIDEDOWN. 5532 5533 // If the vector type is an LMUL-group type, extract a subvector equal to the 5534 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5535 // instruction. 5536 MVT InterSubVT = VecVT; 5537 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5538 InterSubVT = getLMUL1VT(VecVT); 5539 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5540 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5541 } 5542 5543 // Slide this vector register down by the desired number of elements in order 5544 // to place the desired subvector starting at element 0. 5545 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5546 // For scalable vectors this must be further multiplied by vscale. 5547 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5548 5549 SDValue Mask, VL; 5550 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5551 SDValue Slidedown = 5552 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5553 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5554 5555 // Now the vector is in the right position, extract our final subvector. This 5556 // should resolve to a COPY. 5557 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5558 DAG.getConstant(0, DL, XLenVT)); 5559 5560 // We might have bitcast from a mask type: cast back to the original type if 5561 // required. 5562 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5563 } 5564 5565 // Lower step_vector to the vid instruction. Any non-identity step value must 5566 // be accounted for my manual expansion. 5567 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5568 SelectionDAG &DAG) const { 5569 SDLoc DL(Op); 5570 MVT VT = Op.getSimpleValueType(); 5571 MVT XLenVT = Subtarget.getXLenVT(); 5572 SDValue Mask, VL; 5573 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5574 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5575 uint64_t StepValImm = Op.getConstantOperandVal(0); 5576 if (StepValImm != 1) { 5577 if (isPowerOf2_64(StepValImm)) { 5578 SDValue StepVal = 5579 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5580 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5581 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5582 } else { 5583 SDValue StepVal = lowerScalarSplat( 5584 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5585 VL, VT, DL, DAG, Subtarget); 5586 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5587 } 5588 } 5589 return StepVec; 5590 } 5591 5592 // Implement vector_reverse using vrgather.vv with indices determined by 5593 // subtracting the id of each element from (VLMAX-1). This will convert 5594 // the indices like so: 5595 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5596 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5597 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5598 SelectionDAG &DAG) const { 5599 SDLoc DL(Op); 5600 MVT VecVT = Op.getSimpleValueType(); 5601 unsigned EltSize = VecVT.getScalarSizeInBits(); 5602 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5603 5604 unsigned MaxVLMAX = 0; 5605 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5606 if (VectorBitsMax != 0) 5607 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5608 5609 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5610 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5611 5612 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5613 // to use vrgatherei16.vv. 5614 // TODO: It's also possible to use vrgatherei16.vv for other types to 5615 // decrease register width for the index calculation. 5616 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5617 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5618 // Reverse each half, then reassemble them in reverse order. 5619 // NOTE: It's also possible that after splitting that VLMAX no longer 5620 // requires vrgatherei16.vv. 5621 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5622 SDValue Lo, Hi; 5623 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5624 EVT LoVT, HiVT; 5625 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5626 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5627 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5628 // Reassemble the low and high pieces reversed. 5629 // FIXME: This is a CONCAT_VECTORS. 5630 SDValue Res = 5631 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5632 DAG.getIntPtrConstant(0, DL)); 5633 return DAG.getNode( 5634 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5635 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5636 } 5637 5638 // Just promote the int type to i16 which will double the LMUL. 5639 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5640 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5641 } 5642 5643 MVT XLenVT = Subtarget.getXLenVT(); 5644 SDValue Mask, VL; 5645 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5646 5647 // Calculate VLMAX-1 for the desired SEW. 5648 unsigned MinElts = VecVT.getVectorMinNumElements(); 5649 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5650 DAG.getConstant(MinElts, DL, XLenVT)); 5651 SDValue VLMinus1 = 5652 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5653 5654 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5655 bool IsRV32E64 = 5656 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5657 SDValue SplatVL; 5658 if (!IsRV32E64) 5659 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5660 else 5661 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5662 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5663 5664 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5665 SDValue Indices = 5666 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5667 5668 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5669 } 5670 5671 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5672 SelectionDAG &DAG) const { 5673 SDLoc DL(Op); 5674 SDValue V1 = Op.getOperand(0); 5675 SDValue V2 = Op.getOperand(1); 5676 MVT XLenVT = Subtarget.getXLenVT(); 5677 MVT VecVT = Op.getSimpleValueType(); 5678 5679 unsigned MinElts = VecVT.getVectorMinNumElements(); 5680 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5681 DAG.getConstant(MinElts, DL, XLenVT)); 5682 5683 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5684 SDValue DownOffset, UpOffset; 5685 if (ImmValue >= 0) { 5686 // The operand is a TargetConstant, we need to rebuild it as a regular 5687 // constant. 5688 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5689 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5690 } else { 5691 // The operand is a TargetConstant, we need to rebuild it as a regular 5692 // constant rather than negating the original operand. 5693 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5694 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5695 } 5696 5697 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5698 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax); 5699 5700 SDValue SlideDown = 5701 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5702 DownOffset, TrueMask, UpOffset); 5703 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5704 TrueMask, 5705 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5706 } 5707 5708 SDValue 5709 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5710 SelectionDAG &DAG) const { 5711 SDLoc DL(Op); 5712 auto *Load = cast<LoadSDNode>(Op); 5713 5714 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5715 Load->getMemoryVT(), 5716 *Load->getMemOperand()) && 5717 "Expecting a correctly-aligned load"); 5718 5719 MVT VT = Op.getSimpleValueType(); 5720 MVT XLenVT = Subtarget.getXLenVT(); 5721 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5722 5723 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5724 5725 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5726 SDValue IntID = DAG.getTargetConstant( 5727 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5728 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5729 if (!IsMaskOp) 5730 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5731 Ops.push_back(Load->getBasePtr()); 5732 Ops.push_back(VL); 5733 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5734 SDValue NewLoad = 5735 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5736 Load->getMemoryVT(), Load->getMemOperand()); 5737 5738 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5739 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5740 } 5741 5742 SDValue 5743 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5744 SelectionDAG &DAG) const { 5745 SDLoc DL(Op); 5746 auto *Store = cast<StoreSDNode>(Op); 5747 5748 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5749 Store->getMemoryVT(), 5750 *Store->getMemOperand()) && 5751 "Expecting a correctly-aligned store"); 5752 5753 SDValue StoreVal = Store->getValue(); 5754 MVT VT = StoreVal.getSimpleValueType(); 5755 MVT XLenVT = Subtarget.getXLenVT(); 5756 5757 // If the size less than a byte, we need to pad with zeros to make a byte. 5758 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5759 VT = MVT::v8i1; 5760 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5761 DAG.getConstant(0, DL, VT), StoreVal, 5762 DAG.getIntPtrConstant(0, DL)); 5763 } 5764 5765 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5766 5767 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5768 5769 SDValue NewValue = 5770 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5771 5772 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5773 SDValue IntID = DAG.getTargetConstant( 5774 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5775 return DAG.getMemIntrinsicNode( 5776 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5777 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5778 Store->getMemoryVT(), Store->getMemOperand()); 5779 } 5780 5781 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5782 SelectionDAG &DAG) const { 5783 SDLoc DL(Op); 5784 MVT VT = Op.getSimpleValueType(); 5785 5786 const auto *MemSD = cast<MemSDNode>(Op); 5787 EVT MemVT = MemSD->getMemoryVT(); 5788 MachineMemOperand *MMO = MemSD->getMemOperand(); 5789 SDValue Chain = MemSD->getChain(); 5790 SDValue BasePtr = MemSD->getBasePtr(); 5791 5792 SDValue Mask, PassThru, VL; 5793 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5794 Mask = VPLoad->getMask(); 5795 PassThru = DAG.getUNDEF(VT); 5796 VL = VPLoad->getVectorLength(); 5797 } else { 5798 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5799 Mask = MLoad->getMask(); 5800 PassThru = MLoad->getPassThru(); 5801 } 5802 5803 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5804 5805 MVT XLenVT = Subtarget.getXLenVT(); 5806 5807 MVT ContainerVT = VT; 5808 if (VT.isFixedLengthVector()) { 5809 ContainerVT = getContainerForFixedLengthVector(VT); 5810 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5811 if (!IsUnmasked) { 5812 MVT MaskVT = 5813 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5814 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5815 } 5816 } 5817 5818 if (!VL) 5819 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5820 5821 unsigned IntID = 5822 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5823 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5824 if (IsUnmasked) 5825 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5826 else 5827 Ops.push_back(PassThru); 5828 Ops.push_back(BasePtr); 5829 if (!IsUnmasked) 5830 Ops.push_back(Mask); 5831 Ops.push_back(VL); 5832 if (!IsUnmasked) 5833 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5834 5835 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5836 5837 SDValue Result = 5838 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5839 Chain = Result.getValue(1); 5840 5841 if (VT.isFixedLengthVector()) 5842 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5843 5844 return DAG.getMergeValues({Result, Chain}, DL); 5845 } 5846 5847 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5848 SelectionDAG &DAG) const { 5849 SDLoc DL(Op); 5850 5851 const auto *MemSD = cast<MemSDNode>(Op); 5852 EVT MemVT = MemSD->getMemoryVT(); 5853 MachineMemOperand *MMO = MemSD->getMemOperand(); 5854 SDValue Chain = MemSD->getChain(); 5855 SDValue BasePtr = MemSD->getBasePtr(); 5856 SDValue Val, Mask, VL; 5857 5858 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5859 Val = VPStore->getValue(); 5860 Mask = VPStore->getMask(); 5861 VL = VPStore->getVectorLength(); 5862 } else { 5863 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5864 Val = MStore->getValue(); 5865 Mask = MStore->getMask(); 5866 } 5867 5868 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5869 5870 MVT VT = Val.getSimpleValueType(); 5871 MVT XLenVT = Subtarget.getXLenVT(); 5872 5873 MVT ContainerVT = VT; 5874 if (VT.isFixedLengthVector()) { 5875 ContainerVT = getContainerForFixedLengthVector(VT); 5876 5877 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5878 if (!IsUnmasked) { 5879 MVT MaskVT = 5880 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5881 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5882 } 5883 } 5884 5885 if (!VL) 5886 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5887 5888 unsigned IntID = 5889 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5890 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5891 Ops.push_back(Val); 5892 Ops.push_back(BasePtr); 5893 if (!IsUnmasked) 5894 Ops.push_back(Mask); 5895 Ops.push_back(VL); 5896 5897 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5898 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5899 } 5900 5901 SDValue 5902 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5903 SelectionDAG &DAG) const { 5904 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5905 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5906 5907 MVT VT = Op.getSimpleValueType(); 5908 5909 SDValue Op1 = 5910 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5911 SDValue Op2 = 5912 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5913 5914 SDLoc DL(Op); 5915 SDValue VL = 5916 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5917 5918 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5919 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5920 5921 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5922 Op.getOperand(2), Mask, VL); 5923 5924 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5925 } 5926 5927 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5928 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5929 MVT VT = Op.getSimpleValueType(); 5930 5931 if (VT.getVectorElementType() == MVT::i1) 5932 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5933 5934 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5935 } 5936 5937 SDValue 5938 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5939 SelectionDAG &DAG) const { 5940 unsigned Opc; 5941 switch (Op.getOpcode()) { 5942 default: llvm_unreachable("Unexpected opcode!"); 5943 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5944 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5945 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5946 } 5947 5948 return lowerToScalableOp(Op, DAG, Opc); 5949 } 5950 5951 // Lower vector ABS to smax(X, sub(0, X)). 5952 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5953 SDLoc DL(Op); 5954 MVT VT = Op.getSimpleValueType(); 5955 SDValue X = Op.getOperand(0); 5956 5957 assert(VT.isFixedLengthVector() && "Unexpected type"); 5958 5959 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5960 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5961 5962 SDValue Mask, VL; 5963 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5964 5965 SDValue SplatZero = DAG.getNode( 5966 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5967 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5968 SDValue NegX = 5969 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5970 SDValue Max = 5971 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5972 5973 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5974 } 5975 5976 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5977 SDValue Op, SelectionDAG &DAG) const { 5978 SDLoc DL(Op); 5979 MVT VT = Op.getSimpleValueType(); 5980 SDValue Mag = Op.getOperand(0); 5981 SDValue Sign = Op.getOperand(1); 5982 assert(Mag.getValueType() == Sign.getValueType() && 5983 "Can only handle COPYSIGN with matching types."); 5984 5985 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5986 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5987 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5988 5989 SDValue Mask, VL; 5990 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5991 5992 SDValue CopySign = 5993 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5994 5995 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5996 } 5997 5998 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5999 SDValue Op, SelectionDAG &DAG) const { 6000 MVT VT = Op.getSimpleValueType(); 6001 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6002 6003 MVT I1ContainerVT = 6004 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6005 6006 SDValue CC = 6007 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6008 SDValue Op1 = 6009 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6010 SDValue Op2 = 6011 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6012 6013 SDLoc DL(Op); 6014 SDValue Mask, VL; 6015 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6016 6017 SDValue Select = 6018 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6019 6020 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6021 } 6022 6023 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6024 unsigned NewOpc, 6025 bool HasMask) const { 6026 MVT VT = Op.getSimpleValueType(); 6027 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6028 6029 // Create list of operands by converting existing ones to scalable types. 6030 SmallVector<SDValue, 6> Ops; 6031 for (const SDValue &V : Op->op_values()) { 6032 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6033 6034 // Pass through non-vector operands. 6035 if (!V.getValueType().isVector()) { 6036 Ops.push_back(V); 6037 continue; 6038 } 6039 6040 // "cast" fixed length vector to a scalable vector. 6041 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6042 "Only fixed length vectors are supported!"); 6043 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6044 } 6045 6046 SDLoc DL(Op); 6047 SDValue Mask, VL; 6048 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6049 if (HasMask) 6050 Ops.push_back(Mask); 6051 Ops.push_back(VL); 6052 6053 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6054 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6055 } 6056 6057 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6058 // * Operands of each node are assumed to be in the same order. 6059 // * The EVL operand is promoted from i32 to i64 on RV64. 6060 // * Fixed-length vectors are converted to their scalable-vector container 6061 // types. 6062 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6063 unsigned RISCVISDOpc) const { 6064 SDLoc DL(Op); 6065 MVT VT = Op.getSimpleValueType(); 6066 SmallVector<SDValue, 4> Ops; 6067 6068 for (const auto &OpIdx : enumerate(Op->ops())) { 6069 SDValue V = OpIdx.value(); 6070 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6071 // Pass through operands which aren't fixed-length vectors. 6072 if (!V.getValueType().isFixedLengthVector()) { 6073 Ops.push_back(V); 6074 continue; 6075 } 6076 // "cast" fixed length vector to a scalable vector. 6077 MVT OpVT = V.getSimpleValueType(); 6078 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6079 assert(useRVVForFixedLengthVectorVT(OpVT) && 6080 "Only fixed length vectors are supported!"); 6081 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6082 } 6083 6084 if (!VT.isFixedLengthVector()) 6085 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6086 6087 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6088 6089 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6090 6091 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6092 } 6093 6094 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6095 unsigned MaskOpc, 6096 unsigned VecOpc) const { 6097 MVT VT = Op.getSimpleValueType(); 6098 if (VT.getVectorElementType() != MVT::i1) 6099 return lowerVPOp(Op, DAG, VecOpc); 6100 6101 // It is safe to drop mask parameter as masked-off elements are undef. 6102 SDValue Op1 = Op->getOperand(0); 6103 SDValue Op2 = Op->getOperand(1); 6104 SDValue VL = Op->getOperand(3); 6105 6106 MVT ContainerVT = VT; 6107 const bool IsFixed = VT.isFixedLengthVector(); 6108 if (IsFixed) { 6109 ContainerVT = getContainerForFixedLengthVector(VT); 6110 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6111 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6112 } 6113 6114 SDLoc DL(Op); 6115 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6116 if (!IsFixed) 6117 return Val; 6118 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6119 } 6120 6121 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6122 // matched to a RVV indexed load. The RVV indexed load instructions only 6123 // support the "unsigned unscaled" addressing mode; indices are implicitly 6124 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6125 // signed or scaled indexing is extended to the XLEN value type and scaled 6126 // accordingly. 6127 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6128 SelectionDAG &DAG) const { 6129 SDLoc DL(Op); 6130 MVT VT = Op.getSimpleValueType(); 6131 6132 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6133 EVT MemVT = MemSD->getMemoryVT(); 6134 MachineMemOperand *MMO = MemSD->getMemOperand(); 6135 SDValue Chain = MemSD->getChain(); 6136 SDValue BasePtr = MemSD->getBasePtr(); 6137 6138 ISD::LoadExtType LoadExtType; 6139 SDValue Index, Mask, PassThru, VL; 6140 6141 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6142 Index = VPGN->getIndex(); 6143 Mask = VPGN->getMask(); 6144 PassThru = DAG.getUNDEF(VT); 6145 VL = VPGN->getVectorLength(); 6146 // VP doesn't support extending loads. 6147 LoadExtType = ISD::NON_EXTLOAD; 6148 } else { 6149 // Else it must be a MGATHER. 6150 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6151 Index = MGN->getIndex(); 6152 Mask = MGN->getMask(); 6153 PassThru = MGN->getPassThru(); 6154 LoadExtType = MGN->getExtensionType(); 6155 } 6156 6157 MVT IndexVT = Index.getSimpleValueType(); 6158 MVT XLenVT = Subtarget.getXLenVT(); 6159 6160 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6161 "Unexpected VTs!"); 6162 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6163 // Targets have to explicitly opt-in for extending vector loads. 6164 assert(LoadExtType == ISD::NON_EXTLOAD && 6165 "Unexpected extending MGATHER/VP_GATHER"); 6166 (void)LoadExtType; 6167 6168 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6169 // the selection of the masked intrinsics doesn't do this for us. 6170 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6171 6172 MVT ContainerVT = VT; 6173 if (VT.isFixedLengthVector()) { 6174 // We need to use the larger of the result and index type to determine the 6175 // scalable type to use so we don't increase LMUL for any operand/result. 6176 if (VT.bitsGE(IndexVT)) { 6177 ContainerVT = getContainerForFixedLengthVector(VT); 6178 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6179 ContainerVT.getVectorElementCount()); 6180 } else { 6181 IndexVT = getContainerForFixedLengthVector(IndexVT); 6182 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6183 IndexVT.getVectorElementCount()); 6184 } 6185 6186 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6187 6188 if (!IsUnmasked) { 6189 MVT MaskVT = 6190 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6191 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6192 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6193 } 6194 } 6195 6196 if (!VL) 6197 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6198 6199 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6200 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6201 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6202 VL); 6203 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6204 TrueMask, VL); 6205 } 6206 6207 unsigned IntID = 6208 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6209 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6210 if (IsUnmasked) 6211 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6212 else 6213 Ops.push_back(PassThru); 6214 Ops.push_back(BasePtr); 6215 Ops.push_back(Index); 6216 if (!IsUnmasked) 6217 Ops.push_back(Mask); 6218 Ops.push_back(VL); 6219 if (!IsUnmasked) 6220 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6221 6222 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6223 SDValue Result = 6224 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6225 Chain = Result.getValue(1); 6226 6227 if (VT.isFixedLengthVector()) 6228 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6229 6230 return DAG.getMergeValues({Result, Chain}, DL); 6231 } 6232 6233 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6234 // matched to a RVV indexed store. The RVV indexed store instructions only 6235 // support the "unsigned unscaled" addressing mode; indices are implicitly 6236 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6237 // signed or scaled indexing is extended to the XLEN value type and scaled 6238 // accordingly. 6239 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6240 SelectionDAG &DAG) const { 6241 SDLoc DL(Op); 6242 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6243 EVT MemVT = MemSD->getMemoryVT(); 6244 MachineMemOperand *MMO = MemSD->getMemOperand(); 6245 SDValue Chain = MemSD->getChain(); 6246 SDValue BasePtr = MemSD->getBasePtr(); 6247 6248 bool IsTruncatingStore = false; 6249 SDValue Index, Mask, Val, VL; 6250 6251 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6252 Index = VPSN->getIndex(); 6253 Mask = VPSN->getMask(); 6254 Val = VPSN->getValue(); 6255 VL = VPSN->getVectorLength(); 6256 // VP doesn't support truncating stores. 6257 IsTruncatingStore = false; 6258 } else { 6259 // Else it must be a MSCATTER. 6260 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6261 Index = MSN->getIndex(); 6262 Mask = MSN->getMask(); 6263 Val = MSN->getValue(); 6264 IsTruncatingStore = MSN->isTruncatingStore(); 6265 } 6266 6267 MVT VT = Val.getSimpleValueType(); 6268 MVT IndexVT = Index.getSimpleValueType(); 6269 MVT XLenVT = Subtarget.getXLenVT(); 6270 6271 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6272 "Unexpected VTs!"); 6273 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6274 // Targets have to explicitly opt-in for extending vector loads and 6275 // truncating vector stores. 6276 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6277 (void)IsTruncatingStore; 6278 6279 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6280 // the selection of the masked intrinsics doesn't do this for us. 6281 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6282 6283 MVT ContainerVT = VT; 6284 if (VT.isFixedLengthVector()) { 6285 // We need to use the larger of the value and index type to determine the 6286 // scalable type to use so we don't increase LMUL for any operand/result. 6287 if (VT.bitsGE(IndexVT)) { 6288 ContainerVT = getContainerForFixedLengthVector(VT); 6289 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6290 ContainerVT.getVectorElementCount()); 6291 } else { 6292 IndexVT = getContainerForFixedLengthVector(IndexVT); 6293 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6294 IndexVT.getVectorElementCount()); 6295 } 6296 6297 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6298 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6299 6300 if (!IsUnmasked) { 6301 MVT MaskVT = 6302 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6303 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6304 } 6305 } 6306 6307 if (!VL) 6308 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6309 6310 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6311 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6312 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6313 VL); 6314 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6315 TrueMask, VL); 6316 } 6317 6318 unsigned IntID = 6319 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6320 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6321 Ops.push_back(Val); 6322 Ops.push_back(BasePtr); 6323 Ops.push_back(Index); 6324 if (!IsUnmasked) 6325 Ops.push_back(Mask); 6326 Ops.push_back(VL); 6327 6328 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6329 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6330 } 6331 6332 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6333 SelectionDAG &DAG) const { 6334 const MVT XLenVT = Subtarget.getXLenVT(); 6335 SDLoc DL(Op); 6336 SDValue Chain = Op->getOperand(0); 6337 SDValue SysRegNo = DAG.getTargetConstant( 6338 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6339 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6340 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6341 6342 // Encoding used for rounding mode in RISCV differs from that used in 6343 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6344 // table, which consists of a sequence of 4-bit fields, each representing 6345 // corresponding FLT_ROUNDS mode. 6346 static const int Table = 6347 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6348 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6349 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6350 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6351 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6352 6353 SDValue Shift = 6354 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6355 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6356 DAG.getConstant(Table, DL, XLenVT), Shift); 6357 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6358 DAG.getConstant(7, DL, XLenVT)); 6359 6360 return DAG.getMergeValues({Masked, Chain}, DL); 6361 } 6362 6363 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6364 SelectionDAG &DAG) const { 6365 const MVT XLenVT = Subtarget.getXLenVT(); 6366 SDLoc DL(Op); 6367 SDValue Chain = Op->getOperand(0); 6368 SDValue RMValue = Op->getOperand(1); 6369 SDValue SysRegNo = DAG.getTargetConstant( 6370 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6371 6372 // Encoding used for rounding mode in RISCV differs from that used in 6373 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6374 // a table, which consists of a sequence of 4-bit fields, each representing 6375 // corresponding RISCV mode. 6376 static const unsigned Table = 6377 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6378 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6379 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6380 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6381 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6382 6383 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6384 DAG.getConstant(2, DL, XLenVT)); 6385 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6386 DAG.getConstant(Table, DL, XLenVT), Shift); 6387 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6388 DAG.getConstant(0x7, DL, XLenVT)); 6389 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6390 RMValue); 6391 } 6392 6393 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6394 switch (IntNo) { 6395 default: 6396 llvm_unreachable("Unexpected Intrinsic"); 6397 case Intrinsic::riscv_bcompress: 6398 return RISCVISD::BCOMPRESSW; 6399 case Intrinsic::riscv_bdecompress: 6400 return RISCVISD::BDECOMPRESSW; 6401 case Intrinsic::riscv_bfp: 6402 return RISCVISD::BFPW; 6403 case Intrinsic::riscv_fsl: 6404 return RISCVISD::FSLW; 6405 case Intrinsic::riscv_fsr: 6406 return RISCVISD::FSRW; 6407 } 6408 } 6409 6410 // Converts the given intrinsic to a i64 operation with any extension. 6411 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6412 unsigned IntNo) { 6413 SDLoc DL(N); 6414 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6415 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6416 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6417 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6418 // ReplaceNodeResults requires we maintain the same type for the return value. 6419 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6420 } 6421 6422 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6423 // form of the given Opcode. 6424 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6425 switch (Opcode) { 6426 default: 6427 llvm_unreachable("Unexpected opcode"); 6428 case ISD::SHL: 6429 return RISCVISD::SLLW; 6430 case ISD::SRA: 6431 return RISCVISD::SRAW; 6432 case ISD::SRL: 6433 return RISCVISD::SRLW; 6434 case ISD::SDIV: 6435 return RISCVISD::DIVW; 6436 case ISD::UDIV: 6437 return RISCVISD::DIVUW; 6438 case ISD::UREM: 6439 return RISCVISD::REMUW; 6440 case ISD::ROTL: 6441 return RISCVISD::ROLW; 6442 case ISD::ROTR: 6443 return RISCVISD::RORW; 6444 } 6445 } 6446 6447 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6448 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6449 // otherwise be promoted to i64, making it difficult to select the 6450 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6451 // type i8/i16/i32 is lost. 6452 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6453 unsigned ExtOpc = ISD::ANY_EXTEND) { 6454 SDLoc DL(N); 6455 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6456 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6457 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6458 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6459 // ReplaceNodeResults requires we maintain the same type for the return value. 6460 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6461 } 6462 6463 // Converts the given 32-bit operation to a i64 operation with signed extension 6464 // semantic to reduce the signed extension instructions. 6465 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6466 SDLoc DL(N); 6467 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6468 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6469 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6470 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6471 DAG.getValueType(MVT::i32)); 6472 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6473 } 6474 6475 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6476 SmallVectorImpl<SDValue> &Results, 6477 SelectionDAG &DAG) const { 6478 SDLoc DL(N); 6479 switch (N->getOpcode()) { 6480 default: 6481 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6482 case ISD::STRICT_FP_TO_SINT: 6483 case ISD::STRICT_FP_TO_UINT: 6484 case ISD::FP_TO_SINT: 6485 case ISD::FP_TO_UINT: { 6486 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6487 "Unexpected custom legalisation"); 6488 bool IsStrict = N->isStrictFPOpcode(); 6489 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6490 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6491 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6492 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6493 TargetLowering::TypeSoftenFloat) { 6494 if (!isTypeLegal(Op0.getValueType())) 6495 return; 6496 if (IsStrict) { 6497 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6498 : RISCVISD::STRICT_FCVT_WU_RV64; 6499 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6500 SDValue Res = DAG.getNode( 6501 Opc, DL, VTs, N->getOperand(0), Op0, 6502 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6503 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6504 Results.push_back(Res.getValue(1)); 6505 return; 6506 } 6507 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6508 SDValue Res = 6509 DAG.getNode(Opc, DL, MVT::i64, Op0, 6510 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6511 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6512 return; 6513 } 6514 // If the FP type needs to be softened, emit a library call using the 'si' 6515 // version. If we left it to default legalization we'd end up with 'di'. If 6516 // the FP type doesn't need to be softened just let generic type 6517 // legalization promote the result type. 6518 RTLIB::Libcall LC; 6519 if (IsSigned) 6520 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6521 else 6522 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6523 MakeLibCallOptions CallOptions; 6524 EVT OpVT = Op0.getValueType(); 6525 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6526 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6527 SDValue Result; 6528 std::tie(Result, Chain) = 6529 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6530 Results.push_back(Result); 6531 if (IsStrict) 6532 Results.push_back(Chain); 6533 break; 6534 } 6535 case ISD::READCYCLECOUNTER: { 6536 assert(!Subtarget.is64Bit() && 6537 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6538 6539 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6540 SDValue RCW = 6541 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6542 6543 Results.push_back( 6544 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6545 Results.push_back(RCW.getValue(2)); 6546 break; 6547 } 6548 case ISD::MUL: { 6549 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6550 unsigned XLen = Subtarget.getXLen(); 6551 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6552 if (Size > XLen) { 6553 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6554 SDValue LHS = N->getOperand(0); 6555 SDValue RHS = N->getOperand(1); 6556 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6557 6558 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6559 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6560 // We need exactly one side to be unsigned. 6561 if (LHSIsU == RHSIsU) 6562 return; 6563 6564 auto MakeMULPair = [&](SDValue S, SDValue U) { 6565 MVT XLenVT = Subtarget.getXLenVT(); 6566 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6567 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6568 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6569 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6570 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6571 }; 6572 6573 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6574 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6575 6576 // The other operand should be signed, but still prefer MULH when 6577 // possible. 6578 if (RHSIsU && LHSIsS && !RHSIsS) 6579 Results.push_back(MakeMULPair(LHS, RHS)); 6580 else if (LHSIsU && RHSIsS && !LHSIsS) 6581 Results.push_back(MakeMULPair(RHS, LHS)); 6582 6583 return; 6584 } 6585 LLVM_FALLTHROUGH; 6586 } 6587 case ISD::ADD: 6588 case ISD::SUB: 6589 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6590 "Unexpected custom legalisation"); 6591 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6592 break; 6593 case ISD::SHL: 6594 case ISD::SRA: 6595 case ISD::SRL: 6596 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6597 "Unexpected custom legalisation"); 6598 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6599 Results.push_back(customLegalizeToWOp(N, DAG)); 6600 break; 6601 } 6602 6603 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6604 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6605 // shift amount. 6606 if (N->getOpcode() == ISD::SHL) { 6607 SDLoc DL(N); 6608 SDValue NewOp0 = 6609 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6610 SDValue NewOp1 = 6611 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6612 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6613 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6614 DAG.getValueType(MVT::i32)); 6615 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6616 } 6617 6618 break; 6619 case ISD::ROTL: 6620 case ISD::ROTR: 6621 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6622 "Unexpected custom legalisation"); 6623 Results.push_back(customLegalizeToWOp(N, DAG)); 6624 break; 6625 case ISD::CTTZ: 6626 case ISD::CTTZ_ZERO_UNDEF: 6627 case ISD::CTLZ: 6628 case ISD::CTLZ_ZERO_UNDEF: { 6629 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6630 "Unexpected custom legalisation"); 6631 6632 SDValue NewOp0 = 6633 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6634 bool IsCTZ = 6635 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6636 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6637 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6638 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6639 return; 6640 } 6641 case ISD::SDIV: 6642 case ISD::UDIV: 6643 case ISD::UREM: { 6644 MVT VT = N->getSimpleValueType(0); 6645 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6646 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6647 "Unexpected custom legalisation"); 6648 // Don't promote division/remainder by constant since we should expand those 6649 // to multiply by magic constant. 6650 // FIXME: What if the expansion is disabled for minsize. 6651 if (N->getOperand(1).getOpcode() == ISD::Constant) 6652 return; 6653 6654 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6655 // the upper 32 bits. For other types we need to sign or zero extend 6656 // based on the opcode. 6657 unsigned ExtOpc = ISD::ANY_EXTEND; 6658 if (VT != MVT::i32) 6659 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6660 : ISD::ZERO_EXTEND; 6661 6662 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6663 break; 6664 } 6665 case ISD::UADDO: 6666 case ISD::USUBO: { 6667 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6668 "Unexpected custom legalisation"); 6669 bool IsAdd = N->getOpcode() == ISD::UADDO; 6670 // Create an ADDW or SUBW. 6671 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6672 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6673 SDValue Res = 6674 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6675 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6676 DAG.getValueType(MVT::i32)); 6677 6678 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6679 // Since the inputs are sign extended from i32, this is equivalent to 6680 // comparing the lower 32 bits. 6681 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6682 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6683 IsAdd ? ISD::SETULT : ISD::SETUGT); 6684 6685 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6686 Results.push_back(Overflow); 6687 return; 6688 } 6689 case ISD::UADDSAT: 6690 case ISD::USUBSAT: { 6691 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6692 "Unexpected custom legalisation"); 6693 if (Subtarget.hasStdExtZbb()) { 6694 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6695 // sign extend allows overflow of the lower 32 bits to be detected on 6696 // the promoted size. 6697 SDValue LHS = 6698 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6699 SDValue RHS = 6700 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6701 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6702 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6703 return; 6704 } 6705 6706 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6707 // promotion for UADDO/USUBO. 6708 Results.push_back(expandAddSubSat(N, DAG)); 6709 return; 6710 } 6711 case ISD::ABS: { 6712 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6713 "Unexpected custom legalisation"); 6714 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6715 6716 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6717 6718 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6719 6720 // Freeze the source so we can increase it's use count. 6721 Src = DAG.getFreeze(Src); 6722 6723 // Copy sign bit to all bits using the sraiw pattern. 6724 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6725 DAG.getValueType(MVT::i32)); 6726 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6727 DAG.getConstant(31, DL, MVT::i64)); 6728 6729 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6730 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6731 6732 // NOTE: The result is only required to be anyextended, but sext is 6733 // consistent with type legalization of sub. 6734 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6735 DAG.getValueType(MVT::i32)); 6736 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6737 return; 6738 } 6739 case ISD::BITCAST: { 6740 EVT VT = N->getValueType(0); 6741 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6742 SDValue Op0 = N->getOperand(0); 6743 EVT Op0VT = Op0.getValueType(); 6744 MVT XLenVT = Subtarget.getXLenVT(); 6745 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6746 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6747 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6748 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6749 Subtarget.hasStdExtF()) { 6750 SDValue FPConv = 6751 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6752 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6753 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6754 isTypeLegal(Op0VT)) { 6755 // Custom-legalize bitcasts from fixed-length vector types to illegal 6756 // scalar types in order to improve codegen. Bitcast the vector to a 6757 // one-element vector type whose element type is the same as the result 6758 // type, and extract the first element. 6759 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6760 if (isTypeLegal(BVT)) { 6761 SDValue BVec = DAG.getBitcast(BVT, Op0); 6762 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6763 DAG.getConstant(0, DL, XLenVT))); 6764 } 6765 } 6766 break; 6767 } 6768 case RISCVISD::GREV: 6769 case RISCVISD::GORC: { 6770 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6771 "Unexpected custom legalisation"); 6772 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6773 SDValue NewOp0 = 6774 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6775 SDValue NewOp1 = 6776 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6777 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6778 // ReplaceNodeResults requires we maintain the same type for the return 6779 // value. 6780 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6781 break; 6782 } 6783 case RISCVISD::SHFL: { 6784 // There is no SHFLIW instruction, but we can just promote the operation. 6785 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6786 "Unexpected custom legalisation"); 6787 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6788 SDValue NewOp0 = 6789 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6790 SDValue NewOp1 = 6791 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6792 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6793 // ReplaceNodeResults requires we maintain the same type for the return 6794 // value. 6795 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6796 break; 6797 } 6798 case ISD::BSWAP: 6799 case ISD::BITREVERSE: { 6800 MVT VT = N->getSimpleValueType(0); 6801 MVT XLenVT = Subtarget.getXLenVT(); 6802 assert((VT == MVT::i8 || VT == MVT::i16 || 6803 (VT == MVT::i32 && Subtarget.is64Bit())) && 6804 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6805 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6806 unsigned Imm = VT.getSizeInBits() - 1; 6807 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6808 if (N->getOpcode() == ISD::BSWAP) 6809 Imm &= ~0x7U; 6810 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 6811 DAG.getConstant(Imm, DL, XLenVT)); 6812 // ReplaceNodeResults requires we maintain the same type for the return 6813 // value. 6814 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6815 break; 6816 } 6817 case ISD::FSHL: 6818 case ISD::FSHR: { 6819 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6820 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6821 SDValue NewOp0 = 6822 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6823 SDValue NewOp1 = 6824 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6825 SDValue NewShAmt = 6826 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6827 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6828 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6829 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6830 DAG.getConstant(0x1f, DL, MVT::i64)); 6831 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6832 // instruction use different orders. fshl will return its first operand for 6833 // shift of zero, fshr will return its second operand. fsl and fsr both 6834 // return rs1 so the ISD nodes need to have different operand orders. 6835 // Shift amount is in rs2. 6836 unsigned Opc = RISCVISD::FSLW; 6837 if (N->getOpcode() == ISD::FSHR) { 6838 std::swap(NewOp0, NewOp1); 6839 Opc = RISCVISD::FSRW; 6840 } 6841 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6842 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6843 break; 6844 } 6845 case ISD::EXTRACT_VECTOR_ELT: { 6846 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6847 // type is illegal (currently only vXi64 RV32). 6848 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6849 // transferred to the destination register. We issue two of these from the 6850 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6851 // first element. 6852 SDValue Vec = N->getOperand(0); 6853 SDValue Idx = N->getOperand(1); 6854 6855 // The vector type hasn't been legalized yet so we can't issue target 6856 // specific nodes if it needs legalization. 6857 // FIXME: We would manually legalize if it's important. 6858 if (!isTypeLegal(Vec.getValueType())) 6859 return; 6860 6861 MVT VecVT = Vec.getSimpleValueType(); 6862 6863 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6864 VecVT.getVectorElementType() == MVT::i64 && 6865 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6866 6867 // If this is a fixed vector, we need to convert it to a scalable vector. 6868 MVT ContainerVT = VecVT; 6869 if (VecVT.isFixedLengthVector()) { 6870 ContainerVT = getContainerForFixedLengthVector(VecVT); 6871 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6872 } 6873 6874 MVT XLenVT = Subtarget.getXLenVT(); 6875 6876 // Use a VL of 1 to avoid processing more elements than we need. 6877 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6878 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6879 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6880 6881 // Unless the index is known to be 0, we must slide the vector down to get 6882 // the desired element into index 0. 6883 if (!isNullConstant(Idx)) { 6884 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6885 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6886 } 6887 6888 // Extract the lower XLEN bits of the correct vector element. 6889 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6890 6891 // To extract the upper XLEN bits of the vector element, shift the first 6892 // element right by 32 bits and re-extract the lower XLEN bits. 6893 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6894 DAG.getUNDEF(ContainerVT), 6895 DAG.getConstant(32, DL, XLenVT), VL); 6896 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6897 ThirtyTwoV, Mask, VL); 6898 6899 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6900 6901 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6902 break; 6903 } 6904 case ISD::INTRINSIC_WO_CHAIN: { 6905 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6906 switch (IntNo) { 6907 default: 6908 llvm_unreachable( 6909 "Don't know how to custom type legalize this intrinsic!"); 6910 case Intrinsic::riscv_grev: 6911 case Intrinsic::riscv_gorc: { 6912 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6913 "Unexpected custom legalisation"); 6914 SDValue NewOp1 = 6915 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6916 SDValue NewOp2 = 6917 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6918 unsigned Opc = 6919 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 6920 // If the control is a constant, promote the node by clearing any extra 6921 // bits bits in the control. isel will form greviw/gorciw if the result is 6922 // sign extended. 6923 if (isa<ConstantSDNode>(NewOp2)) { 6924 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6925 DAG.getConstant(0x1f, DL, MVT::i64)); 6926 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 6927 } 6928 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6929 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6930 break; 6931 } 6932 case Intrinsic::riscv_bcompress: 6933 case Intrinsic::riscv_bdecompress: 6934 case Intrinsic::riscv_bfp: { 6935 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6936 "Unexpected custom legalisation"); 6937 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6938 break; 6939 } 6940 case Intrinsic::riscv_fsl: 6941 case Intrinsic::riscv_fsr: { 6942 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6943 "Unexpected custom legalisation"); 6944 SDValue NewOp1 = 6945 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6946 SDValue NewOp2 = 6947 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6948 SDValue NewOp3 = 6949 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 6950 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 6951 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 6952 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6953 break; 6954 } 6955 case Intrinsic::riscv_orc_b: { 6956 // Lower to the GORCI encoding for orc.b with the operand extended. 6957 SDValue NewOp = 6958 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6959 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 6960 DAG.getConstant(7, DL, MVT::i64)); 6961 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6962 return; 6963 } 6964 case Intrinsic::riscv_shfl: 6965 case Intrinsic::riscv_unshfl: { 6966 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6967 "Unexpected custom legalisation"); 6968 SDValue NewOp1 = 6969 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6970 SDValue NewOp2 = 6971 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6972 unsigned Opc = 6973 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6974 // There is no (UN)SHFLIW. If the control word is a constant, we can use 6975 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 6976 // will be shuffled the same way as the lower 32 bit half, but the two 6977 // halves won't cross. 6978 if (isa<ConstantSDNode>(NewOp2)) { 6979 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6980 DAG.getConstant(0xf, DL, MVT::i64)); 6981 Opc = 6982 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6983 } 6984 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6985 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6986 break; 6987 } 6988 case Intrinsic::riscv_vmv_x_s: { 6989 EVT VT = N->getValueType(0); 6990 MVT XLenVT = Subtarget.getXLenVT(); 6991 if (VT.bitsLT(XLenVT)) { 6992 // Simple case just extract using vmv.x.s and truncate. 6993 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6994 Subtarget.getXLenVT(), N->getOperand(1)); 6995 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6996 return; 6997 } 6998 6999 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7000 "Unexpected custom legalization"); 7001 7002 // We need to do the move in two steps. 7003 SDValue Vec = N->getOperand(1); 7004 MVT VecVT = Vec.getSimpleValueType(); 7005 7006 // First extract the lower XLEN bits of the element. 7007 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7008 7009 // To extract the upper XLEN bits of the vector element, shift the first 7010 // element right by 32 bits and re-extract the lower XLEN bits. 7011 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7012 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7013 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 7014 SDValue ThirtyTwoV = 7015 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7016 DAG.getConstant(32, DL, XLenVT), VL); 7017 SDValue LShr32 = 7018 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7019 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7020 7021 Results.push_back( 7022 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7023 break; 7024 } 7025 } 7026 break; 7027 } 7028 case ISD::VECREDUCE_ADD: 7029 case ISD::VECREDUCE_AND: 7030 case ISD::VECREDUCE_OR: 7031 case ISD::VECREDUCE_XOR: 7032 case ISD::VECREDUCE_SMAX: 7033 case ISD::VECREDUCE_UMAX: 7034 case ISD::VECREDUCE_SMIN: 7035 case ISD::VECREDUCE_UMIN: 7036 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7037 Results.push_back(V); 7038 break; 7039 case ISD::VP_REDUCE_ADD: 7040 case ISD::VP_REDUCE_AND: 7041 case ISD::VP_REDUCE_OR: 7042 case ISD::VP_REDUCE_XOR: 7043 case ISD::VP_REDUCE_SMAX: 7044 case ISD::VP_REDUCE_UMAX: 7045 case ISD::VP_REDUCE_SMIN: 7046 case ISD::VP_REDUCE_UMIN: 7047 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7048 Results.push_back(V); 7049 break; 7050 case ISD::FLT_ROUNDS_: { 7051 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7052 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7053 Results.push_back(Res.getValue(0)); 7054 Results.push_back(Res.getValue(1)); 7055 break; 7056 } 7057 } 7058 } 7059 7060 // A structure to hold one of the bit-manipulation patterns below. Together, a 7061 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7062 // (or (and (shl x, 1), 0xAAAAAAAA), 7063 // (and (srl x, 1), 0x55555555)) 7064 struct RISCVBitmanipPat { 7065 SDValue Op; 7066 unsigned ShAmt; 7067 bool IsSHL; 7068 7069 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7070 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7071 } 7072 }; 7073 7074 // Matches patterns of the form 7075 // (and (shl x, C2), (C1 << C2)) 7076 // (and (srl x, C2), C1) 7077 // (shl (and x, C1), C2) 7078 // (srl (and x, (C1 << C2)), C2) 7079 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7080 // The expected masks for each shift amount are specified in BitmanipMasks where 7081 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7082 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7083 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7084 // XLen is 64. 7085 static Optional<RISCVBitmanipPat> 7086 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7087 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7088 "Unexpected number of masks"); 7089 Optional<uint64_t> Mask; 7090 // Optionally consume a mask around the shift operation. 7091 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7092 Mask = Op.getConstantOperandVal(1); 7093 Op = Op.getOperand(0); 7094 } 7095 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7096 return None; 7097 bool IsSHL = Op.getOpcode() == ISD::SHL; 7098 7099 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7100 return None; 7101 uint64_t ShAmt = Op.getConstantOperandVal(1); 7102 7103 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7104 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7105 return None; 7106 // If we don't have enough masks for 64 bit, then we must be trying to 7107 // match SHFL so we're only allowed to shift 1/4 of the width. 7108 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7109 return None; 7110 7111 SDValue Src = Op.getOperand(0); 7112 7113 // The expected mask is shifted left when the AND is found around SHL 7114 // patterns. 7115 // ((x >> 1) & 0x55555555) 7116 // ((x << 1) & 0xAAAAAAAA) 7117 bool SHLExpMask = IsSHL; 7118 7119 if (!Mask) { 7120 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7121 // the mask is all ones: consume that now. 7122 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7123 Mask = Src.getConstantOperandVal(1); 7124 Src = Src.getOperand(0); 7125 // The expected mask is now in fact shifted left for SRL, so reverse the 7126 // decision. 7127 // ((x & 0xAAAAAAAA) >> 1) 7128 // ((x & 0x55555555) << 1) 7129 SHLExpMask = !SHLExpMask; 7130 } else { 7131 // Use a default shifted mask of all-ones if there's no AND, truncated 7132 // down to the expected width. This simplifies the logic later on. 7133 Mask = maskTrailingOnes<uint64_t>(Width); 7134 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7135 } 7136 } 7137 7138 unsigned MaskIdx = Log2_32(ShAmt); 7139 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7140 7141 if (SHLExpMask) 7142 ExpMask <<= ShAmt; 7143 7144 if (Mask != ExpMask) 7145 return None; 7146 7147 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7148 } 7149 7150 // Matches any of the following bit-manipulation patterns: 7151 // (and (shl x, 1), (0x55555555 << 1)) 7152 // (and (srl x, 1), 0x55555555) 7153 // (shl (and x, 0x55555555), 1) 7154 // (srl (and x, (0x55555555 << 1)), 1) 7155 // where the shift amount and mask may vary thus: 7156 // [1] = 0x55555555 / 0xAAAAAAAA 7157 // [2] = 0x33333333 / 0xCCCCCCCC 7158 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7159 // [8] = 0x00FF00FF / 0xFF00FF00 7160 // [16] = 0x0000FFFF / 0xFFFFFFFF 7161 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7162 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7163 // These are the unshifted masks which we use to match bit-manipulation 7164 // patterns. They may be shifted left in certain circumstances. 7165 static const uint64_t BitmanipMasks[] = { 7166 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7167 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7168 7169 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7170 } 7171 7172 // Match the following pattern as a GREVI(W) operation 7173 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7174 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7175 const RISCVSubtarget &Subtarget) { 7176 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7177 EVT VT = Op.getValueType(); 7178 7179 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7180 auto LHS = matchGREVIPat(Op.getOperand(0)); 7181 auto RHS = matchGREVIPat(Op.getOperand(1)); 7182 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7183 SDLoc DL(Op); 7184 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7185 DAG.getConstant(LHS->ShAmt, DL, VT)); 7186 } 7187 } 7188 return SDValue(); 7189 } 7190 7191 // Matches any the following pattern as a GORCI(W) operation 7192 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7193 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7194 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7195 // Note that with the variant of 3., 7196 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7197 // the inner pattern will first be matched as GREVI and then the outer 7198 // pattern will be matched to GORC via the first rule above. 7199 // 4. (or (rotl/rotr x, bitwidth/2), x) 7200 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7201 const RISCVSubtarget &Subtarget) { 7202 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7203 EVT VT = Op.getValueType(); 7204 7205 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7206 SDLoc DL(Op); 7207 SDValue Op0 = Op.getOperand(0); 7208 SDValue Op1 = Op.getOperand(1); 7209 7210 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7211 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7212 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7213 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7214 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7215 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7216 if ((Reverse.getOpcode() == ISD::ROTL || 7217 Reverse.getOpcode() == ISD::ROTR) && 7218 Reverse.getOperand(0) == X && 7219 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7220 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7221 if (RotAmt == (VT.getSizeInBits() / 2)) 7222 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7223 DAG.getConstant(RotAmt, DL, VT)); 7224 } 7225 return SDValue(); 7226 }; 7227 7228 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7229 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7230 return V; 7231 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7232 return V; 7233 7234 // OR is commutable so canonicalize its OR operand to the left 7235 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7236 std::swap(Op0, Op1); 7237 if (Op0.getOpcode() != ISD::OR) 7238 return SDValue(); 7239 SDValue OrOp0 = Op0.getOperand(0); 7240 SDValue OrOp1 = Op0.getOperand(1); 7241 auto LHS = matchGREVIPat(OrOp0); 7242 // OR is commutable so swap the operands and try again: x might have been 7243 // on the left 7244 if (!LHS) { 7245 std::swap(OrOp0, OrOp1); 7246 LHS = matchGREVIPat(OrOp0); 7247 } 7248 auto RHS = matchGREVIPat(Op1); 7249 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7250 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7251 DAG.getConstant(LHS->ShAmt, DL, VT)); 7252 } 7253 } 7254 return SDValue(); 7255 } 7256 7257 // Matches any of the following bit-manipulation patterns: 7258 // (and (shl x, 1), (0x22222222 << 1)) 7259 // (and (srl x, 1), 0x22222222) 7260 // (shl (and x, 0x22222222), 1) 7261 // (srl (and x, (0x22222222 << 1)), 1) 7262 // where the shift amount and mask may vary thus: 7263 // [1] = 0x22222222 / 0x44444444 7264 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7265 // [4] = 0x00F000F0 / 0x0F000F00 7266 // [8] = 0x0000FF00 / 0x00FF0000 7267 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7268 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7269 // These are the unshifted masks which we use to match bit-manipulation 7270 // patterns. They may be shifted left in certain circumstances. 7271 static const uint64_t BitmanipMasks[] = { 7272 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7273 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7274 7275 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7276 } 7277 7278 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7279 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7280 const RISCVSubtarget &Subtarget) { 7281 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7282 EVT VT = Op.getValueType(); 7283 7284 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7285 return SDValue(); 7286 7287 SDValue Op0 = Op.getOperand(0); 7288 SDValue Op1 = Op.getOperand(1); 7289 7290 // Or is commutable so canonicalize the second OR to the LHS. 7291 if (Op0.getOpcode() != ISD::OR) 7292 std::swap(Op0, Op1); 7293 if (Op0.getOpcode() != ISD::OR) 7294 return SDValue(); 7295 7296 // We found an inner OR, so our operands are the operands of the inner OR 7297 // and the other operand of the outer OR. 7298 SDValue A = Op0.getOperand(0); 7299 SDValue B = Op0.getOperand(1); 7300 SDValue C = Op1; 7301 7302 auto Match1 = matchSHFLPat(A); 7303 auto Match2 = matchSHFLPat(B); 7304 7305 // If neither matched, we failed. 7306 if (!Match1 && !Match2) 7307 return SDValue(); 7308 7309 // We had at least one match. if one failed, try the remaining C operand. 7310 if (!Match1) { 7311 std::swap(A, C); 7312 Match1 = matchSHFLPat(A); 7313 if (!Match1) 7314 return SDValue(); 7315 } else if (!Match2) { 7316 std::swap(B, C); 7317 Match2 = matchSHFLPat(B); 7318 if (!Match2) 7319 return SDValue(); 7320 } 7321 assert(Match1 && Match2); 7322 7323 // Make sure our matches pair up. 7324 if (!Match1->formsPairWith(*Match2)) 7325 return SDValue(); 7326 7327 // All the remains is to make sure C is an AND with the same input, that masks 7328 // out the bits that are being shuffled. 7329 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7330 C.getOperand(0) != Match1->Op) 7331 return SDValue(); 7332 7333 uint64_t Mask = C.getConstantOperandVal(1); 7334 7335 static const uint64_t BitmanipMasks[] = { 7336 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7337 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7338 }; 7339 7340 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7341 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7342 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7343 7344 if (Mask != ExpMask) 7345 return SDValue(); 7346 7347 SDLoc DL(Op); 7348 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7349 DAG.getConstant(Match1->ShAmt, DL, VT)); 7350 } 7351 7352 // Optimize (add (shl x, c0), (shl y, c1)) -> 7353 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7354 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7355 const RISCVSubtarget &Subtarget) { 7356 // Perform this optimization only in the zba extension. 7357 if (!Subtarget.hasStdExtZba()) 7358 return SDValue(); 7359 7360 // Skip for vector types and larger types. 7361 EVT VT = N->getValueType(0); 7362 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7363 return SDValue(); 7364 7365 // The two operand nodes must be SHL and have no other use. 7366 SDValue N0 = N->getOperand(0); 7367 SDValue N1 = N->getOperand(1); 7368 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7369 !N0->hasOneUse() || !N1->hasOneUse()) 7370 return SDValue(); 7371 7372 // Check c0 and c1. 7373 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7374 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7375 if (!N0C || !N1C) 7376 return SDValue(); 7377 int64_t C0 = N0C->getSExtValue(); 7378 int64_t C1 = N1C->getSExtValue(); 7379 if (C0 <= 0 || C1 <= 0) 7380 return SDValue(); 7381 7382 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7383 int64_t Bits = std::min(C0, C1); 7384 int64_t Diff = std::abs(C0 - C1); 7385 if (Diff != 1 && Diff != 2 && Diff != 3) 7386 return SDValue(); 7387 7388 // Build nodes. 7389 SDLoc DL(N); 7390 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7391 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7392 SDValue NA0 = 7393 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7394 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7395 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7396 } 7397 7398 // Combine 7399 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7400 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7401 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7402 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7403 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7404 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7405 // The grev patterns represents BSWAP. 7406 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7407 // off the grev. 7408 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7409 const RISCVSubtarget &Subtarget) { 7410 bool IsWInstruction = 7411 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7412 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7413 IsWInstruction) && 7414 "Unexpected opcode!"); 7415 SDValue Src = N->getOperand(0); 7416 EVT VT = N->getValueType(0); 7417 SDLoc DL(N); 7418 7419 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7420 return SDValue(); 7421 7422 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7423 !isa<ConstantSDNode>(Src.getOperand(1))) 7424 return SDValue(); 7425 7426 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7427 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7428 7429 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7430 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7431 unsigned ShAmt1 = N->getConstantOperandVal(1); 7432 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7433 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7434 return SDValue(); 7435 7436 Src = Src.getOperand(0); 7437 7438 // Toggle bit the MSB of the shift. 7439 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7440 if (CombinedShAmt == 0) 7441 return Src; 7442 7443 SDValue Res = DAG.getNode( 7444 RISCVISD::GREV, DL, VT, Src, 7445 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7446 if (!IsWInstruction) 7447 return Res; 7448 7449 // Sign extend the result to match the behavior of the rotate. This will be 7450 // selected to GREVIW in isel. 7451 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7452 DAG.getValueType(MVT::i32)); 7453 } 7454 7455 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7456 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7457 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7458 // not undo itself, but they are redundant. 7459 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7460 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7461 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7462 SDValue Src = N->getOperand(0); 7463 7464 if (Src.getOpcode() != N->getOpcode()) 7465 return SDValue(); 7466 7467 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7468 !isa<ConstantSDNode>(Src.getOperand(1))) 7469 return SDValue(); 7470 7471 unsigned ShAmt1 = N->getConstantOperandVal(1); 7472 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7473 Src = Src.getOperand(0); 7474 7475 unsigned CombinedShAmt; 7476 if (IsGORC) 7477 CombinedShAmt = ShAmt1 | ShAmt2; 7478 else 7479 CombinedShAmt = ShAmt1 ^ ShAmt2; 7480 7481 if (CombinedShAmt == 0) 7482 return Src; 7483 7484 SDLoc DL(N); 7485 return DAG.getNode( 7486 N->getOpcode(), DL, N->getValueType(0), Src, 7487 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7488 } 7489 7490 // Combine a constant select operand into its use: 7491 // 7492 // (and (select cond, -1, c), x) 7493 // -> (select cond, x, (and x, c)) [AllOnes=1] 7494 // (or (select cond, 0, c), x) 7495 // -> (select cond, x, (or x, c)) [AllOnes=0] 7496 // (xor (select cond, 0, c), x) 7497 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7498 // (add (select cond, 0, c), x) 7499 // -> (select cond, x, (add x, c)) [AllOnes=0] 7500 // (sub x, (select cond, 0, c)) 7501 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7502 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7503 SelectionDAG &DAG, bool AllOnes) { 7504 EVT VT = N->getValueType(0); 7505 7506 // Skip vectors. 7507 if (VT.isVector()) 7508 return SDValue(); 7509 7510 if ((Slct.getOpcode() != ISD::SELECT && 7511 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7512 !Slct.hasOneUse()) 7513 return SDValue(); 7514 7515 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7516 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7517 }; 7518 7519 bool SwapSelectOps; 7520 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7521 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7522 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7523 SDValue NonConstantVal; 7524 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7525 SwapSelectOps = false; 7526 NonConstantVal = FalseVal; 7527 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7528 SwapSelectOps = true; 7529 NonConstantVal = TrueVal; 7530 } else 7531 return SDValue(); 7532 7533 // Slct is now know to be the desired identity constant when CC is true. 7534 TrueVal = OtherOp; 7535 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7536 // Unless SwapSelectOps says the condition should be false. 7537 if (SwapSelectOps) 7538 std::swap(TrueVal, FalseVal); 7539 7540 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7541 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7542 {Slct.getOperand(0), Slct.getOperand(1), 7543 Slct.getOperand(2), TrueVal, FalseVal}); 7544 7545 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7546 {Slct.getOperand(0), TrueVal, FalseVal}); 7547 } 7548 7549 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7550 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7551 bool AllOnes) { 7552 SDValue N0 = N->getOperand(0); 7553 SDValue N1 = N->getOperand(1); 7554 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7555 return Result; 7556 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7557 return Result; 7558 return SDValue(); 7559 } 7560 7561 // Transform (add (mul x, c0), c1) -> 7562 // (add (mul (add x, c1/c0), c0), c1%c0). 7563 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7564 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7565 // to an infinite loop in DAGCombine if transformed. 7566 // Or transform (add (mul x, c0), c1) -> 7567 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7568 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7569 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7570 // lead to an infinite loop in DAGCombine if transformed. 7571 // Or transform (add (mul x, c0), c1) -> 7572 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7573 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7574 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7575 // lead to an infinite loop in DAGCombine if transformed. 7576 // Or transform (add (mul x, c0), c1) -> 7577 // (mul (add x, c1/c0), c0). 7578 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7579 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7580 const RISCVSubtarget &Subtarget) { 7581 // Skip for vector types and larger types. 7582 EVT VT = N->getValueType(0); 7583 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7584 return SDValue(); 7585 // The first operand node must be a MUL and has no other use. 7586 SDValue N0 = N->getOperand(0); 7587 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7588 return SDValue(); 7589 // Check if c0 and c1 match above conditions. 7590 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7591 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7592 if (!N0C || !N1C) 7593 return SDValue(); 7594 // If N0C has multiple uses it's possible one of the cases in 7595 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7596 // in an infinite loop. 7597 if (!N0C->hasOneUse()) 7598 return SDValue(); 7599 int64_t C0 = N0C->getSExtValue(); 7600 int64_t C1 = N1C->getSExtValue(); 7601 int64_t CA, CB; 7602 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7603 return SDValue(); 7604 // Search for proper CA (non-zero) and CB that both are simm12. 7605 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7606 !isInt<12>(C0 * (C1 / C0))) { 7607 CA = C1 / C0; 7608 CB = C1 % C0; 7609 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7610 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7611 CA = C1 / C0 + 1; 7612 CB = C1 % C0 - C0; 7613 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7614 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7615 CA = C1 / C0 - 1; 7616 CB = C1 % C0 + C0; 7617 } else 7618 return SDValue(); 7619 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7620 SDLoc DL(N); 7621 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7622 DAG.getConstant(CA, DL, VT)); 7623 SDValue New1 = 7624 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7625 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7626 } 7627 7628 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7629 const RISCVSubtarget &Subtarget) { 7630 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7631 return V; 7632 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7633 return V; 7634 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7635 // (select lhs, rhs, cc, x, (add x, y)) 7636 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7637 } 7638 7639 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7640 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7641 // (select lhs, rhs, cc, x, (sub x, y)) 7642 SDValue N0 = N->getOperand(0); 7643 SDValue N1 = N->getOperand(1); 7644 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7645 } 7646 7647 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7648 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7649 // (select lhs, rhs, cc, x, (and x, y)) 7650 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7651 } 7652 7653 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7654 const RISCVSubtarget &Subtarget) { 7655 if (Subtarget.hasStdExtZbp()) { 7656 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7657 return GREV; 7658 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7659 return GORC; 7660 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7661 return SHFL; 7662 } 7663 7664 // fold (or (select cond, 0, y), x) -> 7665 // (select cond, x, (or x, y)) 7666 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7667 } 7668 7669 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7670 // fold (xor (select cond, 0, y), x) -> 7671 // (select cond, x, (xor x, y)) 7672 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7673 } 7674 7675 static SDValue 7676 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 7677 const RISCVSubtarget &Subtarget) { 7678 SDValue Src = N->getOperand(0); 7679 EVT VT = N->getValueType(0); 7680 7681 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 7682 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7683 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 7684 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 7685 Src.getOperand(0)); 7686 7687 // Fold (i64 (sext_inreg (abs X), i32)) -> 7688 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 7689 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 7690 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 7691 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 7692 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 7693 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 7694 // may get combined into an earlier operation so we need to use 7695 // ComputeNumSignBits. 7696 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 7697 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 7698 // we can't assume that X has 33 sign bits. We must check. 7699 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 7700 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 7701 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 7702 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 7703 SDLoc DL(N); 7704 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 7705 SDValue Neg = 7706 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 7707 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 7708 DAG.getValueType(MVT::i32)); 7709 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 7710 } 7711 7712 return SDValue(); 7713 } 7714 7715 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7716 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7717 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7718 bool Commute = false) { 7719 assert((N->getOpcode() == RISCVISD::ADD_VL || 7720 N->getOpcode() == RISCVISD::SUB_VL) && 7721 "Unexpected opcode"); 7722 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7723 SDValue Op0 = N->getOperand(0); 7724 SDValue Op1 = N->getOperand(1); 7725 if (Commute) 7726 std::swap(Op0, Op1); 7727 7728 MVT VT = N->getSimpleValueType(0); 7729 7730 // Determine the narrow size for a widening add/sub. 7731 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7732 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7733 VT.getVectorElementCount()); 7734 7735 SDValue Mask = N->getOperand(2); 7736 SDValue VL = N->getOperand(3); 7737 7738 SDLoc DL(N); 7739 7740 // If the RHS is a sext or zext, we can form a widening op. 7741 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7742 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7743 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7744 unsigned ExtOpc = Op1.getOpcode(); 7745 Op1 = Op1.getOperand(0); 7746 // Re-introduce narrower extends if needed. 7747 if (Op1.getValueType() != NarrowVT) 7748 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7749 7750 unsigned WOpc; 7751 if (ExtOpc == RISCVISD::VSEXT_VL) 7752 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7753 else 7754 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7755 7756 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7757 } 7758 7759 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7760 // sext/zext? 7761 7762 return SDValue(); 7763 } 7764 7765 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7766 // vwsub(u).vv/vx. 7767 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7768 SDValue Op0 = N->getOperand(0); 7769 SDValue Op1 = N->getOperand(1); 7770 SDValue Mask = N->getOperand(2); 7771 SDValue VL = N->getOperand(3); 7772 7773 MVT VT = N->getSimpleValueType(0); 7774 MVT NarrowVT = Op1.getSimpleValueType(); 7775 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 7776 7777 unsigned VOpc; 7778 switch (N->getOpcode()) { 7779 default: llvm_unreachable("Unexpected opcode"); 7780 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 7781 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 7782 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 7783 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 7784 } 7785 7786 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 7787 N->getOpcode() == RISCVISD::VWSUB_W_VL; 7788 7789 SDLoc DL(N); 7790 7791 // If the LHS is a sext or zext, we can narrow this op to the same size as 7792 // the RHS. 7793 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 7794 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 7795 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 7796 unsigned ExtOpc = Op0.getOpcode(); 7797 Op0 = Op0.getOperand(0); 7798 // Re-introduce narrower extends if needed. 7799 if (Op0.getValueType() != NarrowVT) 7800 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7801 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 7802 } 7803 7804 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 7805 N->getOpcode() == RISCVISD::VWADDU_W_VL; 7806 7807 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 7808 // to commute and use a vwadd(u).vx instead. 7809 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 7810 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 7811 Op0 = Op0.getOperand(1); 7812 7813 // See if have enough sign bits or zero bits in the scalar to use a 7814 // widening add/sub by splatting to smaller element size. 7815 unsigned EltBits = VT.getScalarSizeInBits(); 7816 unsigned ScalarBits = Op0.getValueSizeInBits(); 7817 // Make sure we're getting all element bits from the scalar register. 7818 // FIXME: Support implicit sign extension of vmv.v.x? 7819 if (ScalarBits < EltBits) 7820 return SDValue(); 7821 7822 if (IsSigned) { 7823 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 7824 return SDValue(); 7825 } else { 7826 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7827 if (!DAG.MaskedValueIsZero(Op0, Mask)) 7828 return SDValue(); 7829 } 7830 7831 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7832 DAG.getUNDEF(NarrowVT), Op0, VL); 7833 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 7834 } 7835 7836 return SDValue(); 7837 } 7838 7839 // Try to form VWMUL, VWMULU or VWMULSU. 7840 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 7841 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 7842 bool Commute) { 7843 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7844 SDValue Op0 = N->getOperand(0); 7845 SDValue Op1 = N->getOperand(1); 7846 if (Commute) 7847 std::swap(Op0, Op1); 7848 7849 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7850 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7851 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 7852 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7853 return SDValue(); 7854 7855 SDValue Mask = N->getOperand(2); 7856 SDValue VL = N->getOperand(3); 7857 7858 // Make sure the mask and VL match. 7859 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7860 return SDValue(); 7861 7862 MVT VT = N->getSimpleValueType(0); 7863 7864 // Determine the narrow size for a widening multiply. 7865 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7866 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7867 VT.getVectorElementCount()); 7868 7869 SDLoc DL(N); 7870 7871 // See if the other operand is the same opcode. 7872 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 7873 if (!Op1.hasOneUse()) 7874 return SDValue(); 7875 7876 // Make sure the mask and VL match. 7877 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7878 return SDValue(); 7879 7880 Op1 = Op1.getOperand(0); 7881 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7882 // The operand is a splat of a scalar. 7883 7884 // The pasthru must be undef for tail agnostic 7885 if (!Op1.getOperand(0).isUndef()) 7886 return SDValue(); 7887 // The VL must be the same. 7888 if (Op1.getOperand(2) != VL) 7889 return SDValue(); 7890 7891 // Get the scalar value. 7892 Op1 = Op1.getOperand(1); 7893 7894 // See if have enough sign bits or zero bits in the scalar to use a 7895 // widening multiply by splatting to smaller element size. 7896 unsigned EltBits = VT.getScalarSizeInBits(); 7897 unsigned ScalarBits = Op1.getValueSizeInBits(); 7898 // Make sure we're getting all element bits from the scalar register. 7899 // FIXME: Support implicit sign extension of vmv.v.x? 7900 if (ScalarBits < EltBits) 7901 return SDValue(); 7902 7903 // If the LHS is a sign extend, try to use vwmul. 7904 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 7905 // Can use vwmul. 7906 } else { 7907 // Otherwise try to use vwmulu or vwmulsu. 7908 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7909 if (DAG.MaskedValueIsZero(Op1, Mask)) 7910 IsVWMULSU = IsSignExt; 7911 else 7912 return SDValue(); 7913 } 7914 7915 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7916 DAG.getUNDEF(NarrowVT), Op1, VL); 7917 } else 7918 return SDValue(); 7919 7920 Op0 = Op0.getOperand(0); 7921 7922 // Re-introduce narrower extends if needed. 7923 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7924 if (Op0.getValueType() != NarrowVT) 7925 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7926 // vwmulsu requires second operand to be zero extended. 7927 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 7928 if (Op1.getValueType() != NarrowVT) 7929 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7930 7931 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 7932 if (!IsVWMULSU) 7933 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7934 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7935 } 7936 7937 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 7938 switch (Op.getOpcode()) { 7939 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 7940 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 7941 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 7942 case ISD::FCEIL: return RISCVFPRndMode::RUP; 7943 case ISD::FROUND: return RISCVFPRndMode::RMM; 7944 } 7945 7946 return RISCVFPRndMode::Invalid; 7947 } 7948 7949 // Fold 7950 // (fp_to_int (froundeven X)) -> fcvt X, rne 7951 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7952 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7953 // (fp_to_int (fceil X)) -> fcvt X, rup 7954 // (fp_to_int (fround X)) -> fcvt X, rmm 7955 static SDValue performFP_TO_INTCombine(SDNode *N, 7956 TargetLowering::DAGCombinerInfo &DCI, 7957 const RISCVSubtarget &Subtarget) { 7958 SelectionDAG &DAG = DCI.DAG; 7959 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7960 MVT XLenVT = Subtarget.getXLenVT(); 7961 7962 // Only handle XLen or i32 types. Other types narrower than XLen will 7963 // eventually be legalized to XLenVT. 7964 EVT VT = N->getValueType(0); 7965 if (VT != MVT::i32 && VT != XLenVT) 7966 return SDValue(); 7967 7968 SDValue Src = N->getOperand(0); 7969 7970 // Ensure the FP type is also legal. 7971 if (!TLI.isTypeLegal(Src.getValueType())) 7972 return SDValue(); 7973 7974 // Don't do this for f16 with Zfhmin and not Zfh. 7975 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7976 return SDValue(); 7977 7978 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7979 if (FRM == RISCVFPRndMode::Invalid) 7980 return SDValue(); 7981 7982 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7983 7984 unsigned Opc; 7985 if (VT == XLenVT) 7986 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7987 else 7988 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7989 7990 SDLoc DL(N); 7991 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 7992 DAG.getTargetConstant(FRM, DL, XLenVT)); 7993 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 7994 } 7995 7996 // Fold 7997 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 7998 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 7999 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8000 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8001 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8002 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8003 TargetLowering::DAGCombinerInfo &DCI, 8004 const RISCVSubtarget &Subtarget) { 8005 SelectionDAG &DAG = DCI.DAG; 8006 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8007 MVT XLenVT = Subtarget.getXLenVT(); 8008 8009 // Only handle XLen types. Other types narrower than XLen will eventually be 8010 // legalized to XLenVT. 8011 EVT DstVT = N->getValueType(0); 8012 if (DstVT != XLenVT) 8013 return SDValue(); 8014 8015 SDValue Src = N->getOperand(0); 8016 8017 // Ensure the FP type is also legal. 8018 if (!TLI.isTypeLegal(Src.getValueType())) 8019 return SDValue(); 8020 8021 // Don't do this for f16 with Zfhmin and not Zfh. 8022 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8023 return SDValue(); 8024 8025 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8026 8027 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8028 if (FRM == RISCVFPRndMode::Invalid) 8029 return SDValue(); 8030 8031 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8032 8033 unsigned Opc; 8034 if (SatVT == DstVT) 8035 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8036 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8037 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8038 else 8039 return SDValue(); 8040 // FIXME: Support other SatVTs by clamping before or after the conversion. 8041 8042 Src = Src.getOperand(0); 8043 8044 SDLoc DL(N); 8045 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8046 DAG.getTargetConstant(FRM, DL, XLenVT)); 8047 8048 // RISCV FP-to-int conversions saturate to the destination register size, but 8049 // don't produce 0 for nan. 8050 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8051 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8052 } 8053 8054 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8055 DAGCombinerInfo &DCI) const { 8056 SelectionDAG &DAG = DCI.DAG; 8057 8058 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8059 // bits are demanded. N will be added to the Worklist if it was not deleted. 8060 // Caller should return SDValue(N, 0) if this returns true. 8061 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8062 SDValue Op = N->getOperand(OpNo); 8063 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8064 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8065 return false; 8066 8067 if (N->getOpcode() != ISD::DELETED_NODE) 8068 DCI.AddToWorklist(N); 8069 return true; 8070 }; 8071 8072 switch (N->getOpcode()) { 8073 default: 8074 break; 8075 case RISCVISD::SplitF64: { 8076 SDValue Op0 = N->getOperand(0); 8077 // If the input to SplitF64 is just BuildPairF64 then the operation is 8078 // redundant. Instead, use BuildPairF64's operands directly. 8079 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8080 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8081 8082 if (Op0->isUndef()) { 8083 SDValue Lo = DAG.getUNDEF(MVT::i32); 8084 SDValue Hi = DAG.getUNDEF(MVT::i32); 8085 return DCI.CombineTo(N, Lo, Hi); 8086 } 8087 8088 SDLoc DL(N); 8089 8090 // It's cheaper to materialise two 32-bit integers than to load a double 8091 // from the constant pool and transfer it to integer registers through the 8092 // stack. 8093 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8094 APInt V = C->getValueAPF().bitcastToAPInt(); 8095 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8096 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8097 return DCI.CombineTo(N, Lo, Hi); 8098 } 8099 8100 // This is a target-specific version of a DAGCombine performed in 8101 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8102 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8103 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8104 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8105 !Op0.getNode()->hasOneUse()) 8106 break; 8107 SDValue NewSplitF64 = 8108 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8109 Op0.getOperand(0)); 8110 SDValue Lo = NewSplitF64.getValue(0); 8111 SDValue Hi = NewSplitF64.getValue(1); 8112 APInt SignBit = APInt::getSignMask(32); 8113 if (Op0.getOpcode() == ISD::FNEG) { 8114 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8115 DAG.getConstant(SignBit, DL, MVT::i32)); 8116 return DCI.CombineTo(N, Lo, NewHi); 8117 } 8118 assert(Op0.getOpcode() == ISD::FABS); 8119 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8120 DAG.getConstant(~SignBit, DL, MVT::i32)); 8121 return DCI.CombineTo(N, Lo, NewHi); 8122 } 8123 case RISCVISD::SLLW: 8124 case RISCVISD::SRAW: 8125 case RISCVISD::SRLW: { 8126 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8127 if (SimplifyDemandedLowBitsHelper(0, 32) || 8128 SimplifyDemandedLowBitsHelper(1, 5)) 8129 return SDValue(N, 0); 8130 8131 break; 8132 } 8133 case ISD::ROTR: 8134 case ISD::ROTL: 8135 case RISCVISD::RORW: 8136 case RISCVISD::ROLW: { 8137 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8138 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8139 if (SimplifyDemandedLowBitsHelper(0, 32) || 8140 SimplifyDemandedLowBitsHelper(1, 5)) 8141 return SDValue(N, 0); 8142 } 8143 8144 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8145 } 8146 case RISCVISD::CLZW: 8147 case RISCVISD::CTZW: { 8148 // Only the lower 32 bits of the first operand are read 8149 if (SimplifyDemandedLowBitsHelper(0, 32)) 8150 return SDValue(N, 0); 8151 break; 8152 } 8153 case RISCVISD::GREV: 8154 case RISCVISD::GORC: { 8155 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8156 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8157 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8158 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8159 return SDValue(N, 0); 8160 8161 return combineGREVI_GORCI(N, DAG); 8162 } 8163 case RISCVISD::GREVW: 8164 case RISCVISD::GORCW: { 8165 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8166 if (SimplifyDemandedLowBitsHelper(0, 32) || 8167 SimplifyDemandedLowBitsHelper(1, 5)) 8168 return SDValue(N, 0); 8169 8170 break; 8171 } 8172 case RISCVISD::SHFL: 8173 case RISCVISD::UNSHFL: { 8174 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8175 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8176 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8177 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8178 return SDValue(N, 0); 8179 8180 break; 8181 } 8182 case RISCVISD::SHFLW: 8183 case RISCVISD::UNSHFLW: { 8184 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8185 if (SimplifyDemandedLowBitsHelper(0, 32) || 8186 SimplifyDemandedLowBitsHelper(1, 4)) 8187 return SDValue(N, 0); 8188 8189 break; 8190 } 8191 case RISCVISD::BCOMPRESSW: 8192 case RISCVISD::BDECOMPRESSW: { 8193 // Only the lower 32 bits of LHS and RHS are read. 8194 if (SimplifyDemandedLowBitsHelper(0, 32) || 8195 SimplifyDemandedLowBitsHelper(1, 32)) 8196 return SDValue(N, 0); 8197 8198 break; 8199 } 8200 case RISCVISD::FSR: 8201 case RISCVISD::FSL: 8202 case RISCVISD::FSRW: 8203 case RISCVISD::FSLW: { 8204 bool IsWInstruction = 8205 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8206 unsigned BitWidth = 8207 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8208 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8209 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8210 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8211 return SDValue(N, 0); 8212 8213 break; 8214 } 8215 case RISCVISD::FMV_X_ANYEXTH: 8216 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8217 SDLoc DL(N); 8218 SDValue Op0 = N->getOperand(0); 8219 MVT VT = N->getSimpleValueType(0); 8220 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8221 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8222 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8223 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8224 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8225 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8226 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8227 assert(Op0.getOperand(0).getValueType() == VT && 8228 "Unexpected value type!"); 8229 return Op0.getOperand(0); 8230 } 8231 8232 // This is a target-specific version of a DAGCombine performed in 8233 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8234 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8235 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8236 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8237 !Op0.getNode()->hasOneUse()) 8238 break; 8239 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8240 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8241 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8242 if (Op0.getOpcode() == ISD::FNEG) 8243 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8244 DAG.getConstant(SignBit, DL, VT)); 8245 8246 assert(Op0.getOpcode() == ISD::FABS); 8247 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8248 DAG.getConstant(~SignBit, DL, VT)); 8249 } 8250 case ISD::ADD: 8251 return performADDCombine(N, DAG, Subtarget); 8252 case ISD::SUB: 8253 return performSUBCombine(N, DAG); 8254 case ISD::AND: 8255 return performANDCombine(N, DAG); 8256 case ISD::OR: 8257 return performORCombine(N, DAG, Subtarget); 8258 case ISD::XOR: 8259 return performXORCombine(N, DAG); 8260 case ISD::SIGN_EXTEND_INREG: 8261 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8262 case ISD::ZERO_EXTEND: 8263 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8264 // type legalization. This is safe because fp_to_uint produces poison if 8265 // it overflows. 8266 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8267 SDValue Src = N->getOperand(0); 8268 if (Src.getOpcode() == ISD::FP_TO_UINT && 8269 isTypeLegal(Src.getOperand(0).getValueType())) 8270 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8271 Src.getOperand(0)); 8272 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8273 isTypeLegal(Src.getOperand(1).getValueType())) { 8274 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8275 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8276 Src.getOperand(0), Src.getOperand(1)); 8277 DCI.CombineTo(N, Res); 8278 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8279 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8280 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8281 } 8282 } 8283 return SDValue(); 8284 case RISCVISD::SELECT_CC: { 8285 // Transform 8286 SDValue LHS = N->getOperand(0); 8287 SDValue RHS = N->getOperand(1); 8288 SDValue TrueV = N->getOperand(3); 8289 SDValue FalseV = N->getOperand(4); 8290 8291 // If the True and False values are the same, we don't need a select_cc. 8292 if (TrueV == FalseV) 8293 return TrueV; 8294 8295 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8296 if (!ISD::isIntEqualitySetCC(CCVal)) 8297 break; 8298 8299 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8300 // (select_cc X, Y, lt, trueV, falseV) 8301 // Sometimes the setcc is introduced after select_cc has been formed. 8302 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8303 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8304 // If we're looking for eq 0 instead of ne 0, we need to invert the 8305 // condition. 8306 bool Invert = CCVal == ISD::SETEQ; 8307 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8308 if (Invert) 8309 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8310 8311 SDLoc DL(N); 8312 RHS = LHS.getOperand(1); 8313 LHS = LHS.getOperand(0); 8314 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8315 8316 SDValue TargetCC = DAG.getCondCode(CCVal); 8317 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8318 {LHS, RHS, TargetCC, TrueV, FalseV}); 8319 } 8320 8321 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8322 // (select_cc X, Y, eq/ne, trueV, falseV) 8323 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8324 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8325 {LHS.getOperand(0), LHS.getOperand(1), 8326 N->getOperand(2), TrueV, FalseV}); 8327 // (select_cc X, 1, setne, trueV, falseV) -> 8328 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8329 // This can occur when legalizing some floating point comparisons. 8330 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8331 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8332 SDLoc DL(N); 8333 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8334 SDValue TargetCC = DAG.getCondCode(CCVal); 8335 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8336 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8337 {LHS, RHS, TargetCC, TrueV, FalseV}); 8338 } 8339 8340 break; 8341 } 8342 case RISCVISD::BR_CC: { 8343 SDValue LHS = N->getOperand(1); 8344 SDValue RHS = N->getOperand(2); 8345 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8346 if (!ISD::isIntEqualitySetCC(CCVal)) 8347 break; 8348 8349 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8350 // (br_cc X, Y, lt, dest) 8351 // Sometimes the setcc is introduced after br_cc has been formed. 8352 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8353 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8354 // If we're looking for eq 0 instead of ne 0, we need to invert the 8355 // condition. 8356 bool Invert = CCVal == ISD::SETEQ; 8357 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8358 if (Invert) 8359 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8360 8361 SDLoc DL(N); 8362 RHS = LHS.getOperand(1); 8363 LHS = LHS.getOperand(0); 8364 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8365 8366 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8367 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8368 N->getOperand(4)); 8369 } 8370 8371 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8372 // (br_cc X, Y, eq/ne, trueV, falseV) 8373 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8374 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8375 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8376 N->getOperand(3), N->getOperand(4)); 8377 8378 // (br_cc X, 1, setne, br_cc) -> 8379 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8380 // This can occur when legalizing some floating point comparisons. 8381 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8382 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8383 SDLoc DL(N); 8384 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8385 SDValue TargetCC = DAG.getCondCode(CCVal); 8386 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8387 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8388 N->getOperand(0), LHS, RHS, TargetCC, 8389 N->getOperand(4)); 8390 } 8391 break; 8392 } 8393 case ISD::FP_TO_SINT: 8394 case ISD::FP_TO_UINT: 8395 return performFP_TO_INTCombine(N, DCI, Subtarget); 8396 case ISD::FP_TO_SINT_SAT: 8397 case ISD::FP_TO_UINT_SAT: 8398 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8399 case ISD::FCOPYSIGN: { 8400 EVT VT = N->getValueType(0); 8401 if (!VT.isVector()) 8402 break; 8403 // There is a form of VFSGNJ which injects the negated sign of its second 8404 // operand. Try and bubble any FNEG up after the extend/round to produce 8405 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8406 // TRUNC=1. 8407 SDValue In2 = N->getOperand(1); 8408 // Avoid cases where the extend/round has multiple uses, as duplicating 8409 // those is typically more expensive than removing a fneg. 8410 if (!In2.hasOneUse()) 8411 break; 8412 if (In2.getOpcode() != ISD::FP_EXTEND && 8413 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8414 break; 8415 In2 = In2.getOperand(0); 8416 if (In2.getOpcode() != ISD::FNEG) 8417 break; 8418 SDLoc DL(N); 8419 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8420 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8421 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8422 } 8423 case ISD::MGATHER: 8424 case ISD::MSCATTER: 8425 case ISD::VP_GATHER: 8426 case ISD::VP_SCATTER: { 8427 if (!DCI.isBeforeLegalize()) 8428 break; 8429 SDValue Index, ScaleOp; 8430 bool IsIndexScaled = false; 8431 bool IsIndexSigned = false; 8432 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8433 Index = VPGSN->getIndex(); 8434 ScaleOp = VPGSN->getScale(); 8435 IsIndexScaled = VPGSN->isIndexScaled(); 8436 IsIndexSigned = VPGSN->isIndexSigned(); 8437 } else { 8438 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8439 Index = MGSN->getIndex(); 8440 ScaleOp = MGSN->getScale(); 8441 IsIndexScaled = MGSN->isIndexScaled(); 8442 IsIndexSigned = MGSN->isIndexSigned(); 8443 } 8444 EVT IndexVT = Index.getValueType(); 8445 MVT XLenVT = Subtarget.getXLenVT(); 8446 // RISCV indexed loads only support the "unsigned unscaled" addressing 8447 // mode, so anything else must be manually legalized. 8448 bool NeedsIdxLegalization = 8449 IsIndexScaled || 8450 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8451 if (!NeedsIdxLegalization) 8452 break; 8453 8454 SDLoc DL(N); 8455 8456 // Any index legalization should first promote to XLenVT, so we don't lose 8457 // bits when scaling. This may create an illegal index type so we let 8458 // LLVM's legalization take care of the splitting. 8459 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8460 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8461 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8462 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8463 DL, IndexVT, Index); 8464 } 8465 8466 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8467 if (IsIndexScaled && Scale != 1) { 8468 // Manually scale the indices by the element size. 8469 // TODO: Sanitize the scale operand here? 8470 // TODO: For VP nodes, should we use VP_SHL here? 8471 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8472 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8473 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8474 } 8475 8476 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8477 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8478 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8479 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8480 VPGN->getScale(), VPGN->getMask(), 8481 VPGN->getVectorLength()}, 8482 VPGN->getMemOperand(), NewIndexTy); 8483 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8484 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8485 {VPSN->getChain(), VPSN->getValue(), 8486 VPSN->getBasePtr(), Index, VPSN->getScale(), 8487 VPSN->getMask(), VPSN->getVectorLength()}, 8488 VPSN->getMemOperand(), NewIndexTy); 8489 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8490 return DAG.getMaskedGather( 8491 N->getVTList(), MGN->getMemoryVT(), DL, 8492 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8493 MGN->getBasePtr(), Index, MGN->getScale()}, 8494 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8495 const auto *MSN = cast<MaskedScatterSDNode>(N); 8496 return DAG.getMaskedScatter( 8497 N->getVTList(), MSN->getMemoryVT(), DL, 8498 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8499 Index, MSN->getScale()}, 8500 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8501 } 8502 case RISCVISD::SRA_VL: 8503 case RISCVISD::SRL_VL: 8504 case RISCVISD::SHL_VL: { 8505 SDValue ShAmt = N->getOperand(1); 8506 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8507 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8508 SDLoc DL(N); 8509 SDValue VL = N->getOperand(3); 8510 EVT VT = N->getValueType(0); 8511 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8512 ShAmt.getOperand(1), VL); 8513 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8514 N->getOperand(2), N->getOperand(3)); 8515 } 8516 break; 8517 } 8518 case ISD::SRA: 8519 case ISD::SRL: 8520 case ISD::SHL: { 8521 SDValue ShAmt = N->getOperand(1); 8522 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8523 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8524 SDLoc DL(N); 8525 EVT VT = N->getValueType(0); 8526 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8527 ShAmt.getOperand(1), 8528 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8529 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8530 } 8531 break; 8532 } 8533 case RISCVISD::ADD_VL: 8534 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8535 return V; 8536 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8537 case RISCVISD::SUB_VL: 8538 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8539 case RISCVISD::VWADD_W_VL: 8540 case RISCVISD::VWADDU_W_VL: 8541 case RISCVISD::VWSUB_W_VL: 8542 case RISCVISD::VWSUBU_W_VL: 8543 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8544 case RISCVISD::MUL_VL: 8545 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8546 return V; 8547 // Mul is commutative. 8548 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8549 case ISD::STORE: { 8550 auto *Store = cast<StoreSDNode>(N); 8551 SDValue Val = Store->getValue(); 8552 // Combine store of vmv.x.s to vse with VL of 1. 8553 // FIXME: Support FP. 8554 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8555 SDValue Src = Val.getOperand(0); 8556 EVT VecVT = Src.getValueType(); 8557 EVT MemVT = Store->getMemoryVT(); 8558 // The memory VT and the element type must match. 8559 if (VecVT.getVectorElementType() == MemVT) { 8560 SDLoc DL(N); 8561 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8562 return DAG.getStoreVP( 8563 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8564 DAG.getConstant(1, DL, MaskVT), 8565 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8566 Store->getMemOperand(), Store->getAddressingMode(), 8567 Store->isTruncatingStore(), /*IsCompress*/ false); 8568 } 8569 } 8570 8571 break; 8572 } 8573 case ISD::SPLAT_VECTOR: { 8574 EVT VT = N->getValueType(0); 8575 // Only perform this combine on legal MVT types. 8576 if (!isTypeLegal(VT)) 8577 break; 8578 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8579 DAG, Subtarget)) 8580 return Gather; 8581 break; 8582 } 8583 case RISCVISD::VMV_V_X_VL: { 8584 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8585 // scalar input. 8586 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8587 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8588 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8589 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8590 return SDValue(N, 0); 8591 8592 break; 8593 } 8594 case ISD::INTRINSIC_WO_CHAIN: { 8595 unsigned IntNo = N->getConstantOperandVal(0); 8596 switch (IntNo) { 8597 // By default we do not combine any intrinsic. 8598 default: 8599 return SDValue(); 8600 case Intrinsic::riscv_vcpop: 8601 case Intrinsic::riscv_vcpop_mask: 8602 case Intrinsic::riscv_vfirst: 8603 case Intrinsic::riscv_vfirst_mask: { 8604 SDValue VL = N->getOperand(2); 8605 if (IntNo == Intrinsic::riscv_vcpop_mask || 8606 IntNo == Intrinsic::riscv_vfirst_mask) 8607 VL = N->getOperand(3); 8608 if (!isNullConstant(VL)) 8609 return SDValue(); 8610 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8611 SDLoc DL(N); 8612 EVT VT = N->getValueType(0); 8613 if (IntNo == Intrinsic::riscv_vfirst || 8614 IntNo == Intrinsic::riscv_vfirst_mask) 8615 return DAG.getConstant(-1, DL, VT); 8616 return DAG.getConstant(0, DL, VT); 8617 } 8618 } 8619 } 8620 } 8621 8622 return SDValue(); 8623 } 8624 8625 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8626 const SDNode *N, CombineLevel Level) const { 8627 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8628 // materialised in fewer instructions than `(OP _, c1)`: 8629 // 8630 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8631 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8632 SDValue N0 = N->getOperand(0); 8633 EVT Ty = N0.getValueType(); 8634 if (Ty.isScalarInteger() && 8635 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8636 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8637 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8638 if (C1 && C2) { 8639 const APInt &C1Int = C1->getAPIntValue(); 8640 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8641 8642 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8643 // and the combine should happen, to potentially allow further combines 8644 // later. 8645 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8646 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8647 return true; 8648 8649 // We can materialise `c1` in an add immediate, so it's "free", and the 8650 // combine should be prevented. 8651 if (C1Int.getMinSignedBits() <= 64 && 8652 isLegalAddImmediate(C1Int.getSExtValue())) 8653 return false; 8654 8655 // Neither constant will fit into an immediate, so find materialisation 8656 // costs. 8657 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8658 Subtarget.getFeatureBits(), 8659 /*CompressionCost*/true); 8660 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8661 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8662 /*CompressionCost*/true); 8663 8664 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8665 // combine should be prevented. 8666 if (C1Cost < ShiftedC1Cost) 8667 return false; 8668 } 8669 } 8670 return true; 8671 } 8672 8673 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8674 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8675 TargetLoweringOpt &TLO) const { 8676 // Delay this optimization as late as possible. 8677 if (!TLO.LegalOps) 8678 return false; 8679 8680 EVT VT = Op.getValueType(); 8681 if (VT.isVector()) 8682 return false; 8683 8684 // Only handle AND for now. 8685 if (Op.getOpcode() != ISD::AND) 8686 return false; 8687 8688 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8689 if (!C) 8690 return false; 8691 8692 const APInt &Mask = C->getAPIntValue(); 8693 8694 // Clear all non-demanded bits initially. 8695 APInt ShrunkMask = Mask & DemandedBits; 8696 8697 // Try to make a smaller immediate by setting undemanded bits. 8698 8699 APInt ExpandedMask = Mask | ~DemandedBits; 8700 8701 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8702 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8703 }; 8704 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8705 if (NewMask == Mask) 8706 return true; 8707 SDLoc DL(Op); 8708 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8709 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8710 return TLO.CombineTo(Op, NewOp); 8711 }; 8712 8713 // If the shrunk mask fits in sign extended 12 bits, let the target 8714 // independent code apply it. 8715 if (ShrunkMask.isSignedIntN(12)) 8716 return false; 8717 8718 // Preserve (and X, 0xffff) when zext.h is supported. 8719 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8720 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8721 if (IsLegalMask(NewMask)) 8722 return UseMask(NewMask); 8723 } 8724 8725 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8726 if (VT == MVT::i64) { 8727 APInt NewMask = APInt(64, 0xffffffff); 8728 if (IsLegalMask(NewMask)) 8729 return UseMask(NewMask); 8730 } 8731 8732 // For the remaining optimizations, we need to be able to make a negative 8733 // number through a combination of mask and undemanded bits. 8734 if (!ExpandedMask.isNegative()) 8735 return false; 8736 8737 // What is the fewest number of bits we need to represent the negative number. 8738 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8739 8740 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8741 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8742 APInt NewMask = ShrunkMask; 8743 if (MinSignedBits <= 12) 8744 NewMask.setBitsFrom(11); 8745 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8746 NewMask.setBitsFrom(31); 8747 else 8748 return false; 8749 8750 // Check that our new mask is a subset of the demanded mask. 8751 assert(IsLegalMask(NewMask)); 8752 return UseMask(NewMask); 8753 } 8754 8755 static void computeGREV(APInt &Src, unsigned ShAmt) { 8756 ShAmt &= Src.getBitWidth() - 1; 8757 uint64_t x = Src.getZExtValue(); 8758 if (ShAmt & 1) 8759 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 8760 if (ShAmt & 2) 8761 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 8762 if (ShAmt & 4) 8763 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 8764 if (ShAmt & 8) 8765 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 8766 if (ShAmt & 16) 8767 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 8768 if (ShAmt & 32) 8769 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 8770 Src = x; 8771 } 8772 8773 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8774 KnownBits &Known, 8775 const APInt &DemandedElts, 8776 const SelectionDAG &DAG, 8777 unsigned Depth) const { 8778 unsigned BitWidth = Known.getBitWidth(); 8779 unsigned Opc = Op.getOpcode(); 8780 assert((Opc >= ISD::BUILTIN_OP_END || 8781 Opc == ISD::INTRINSIC_WO_CHAIN || 8782 Opc == ISD::INTRINSIC_W_CHAIN || 8783 Opc == ISD::INTRINSIC_VOID) && 8784 "Should use MaskedValueIsZero if you don't know whether Op" 8785 " is a target node!"); 8786 8787 Known.resetAll(); 8788 switch (Opc) { 8789 default: break; 8790 case RISCVISD::SELECT_CC: { 8791 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8792 // If we don't know any bits, early out. 8793 if (Known.isUnknown()) 8794 break; 8795 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8796 8797 // Only known if known in both the LHS and RHS. 8798 Known = KnownBits::commonBits(Known, Known2); 8799 break; 8800 } 8801 case RISCVISD::REMUW: { 8802 KnownBits Known2; 8803 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8804 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8805 // We only care about the lower 32 bits. 8806 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8807 // Restore the original width by sign extending. 8808 Known = Known.sext(BitWidth); 8809 break; 8810 } 8811 case RISCVISD::DIVUW: { 8812 KnownBits Known2; 8813 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8814 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8815 // We only care about the lower 32 bits. 8816 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8817 // Restore the original width by sign extending. 8818 Known = Known.sext(BitWidth); 8819 break; 8820 } 8821 case RISCVISD::CTZW: { 8822 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8823 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 8824 unsigned LowBits = Log2_32(PossibleTZ) + 1; 8825 Known.Zero.setBitsFrom(LowBits); 8826 break; 8827 } 8828 case RISCVISD::CLZW: { 8829 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8830 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 8831 unsigned LowBits = Log2_32(PossibleLZ) + 1; 8832 Known.Zero.setBitsFrom(LowBits); 8833 break; 8834 } 8835 case RISCVISD::GREV: { 8836 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8837 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8838 unsigned ShAmt = C->getZExtValue(); 8839 computeGREV(Known.Zero, ShAmt); 8840 computeGREV(Known.One, ShAmt); 8841 } 8842 break; 8843 } 8844 case RISCVISD::READ_VLENB: { 8845 // If we know the minimum VLen from Zvl extensions, we can use that to 8846 // determine the trailing zeros of VLENB. 8847 // FIXME: Limit to 128 bit vectors until we have more testing. 8848 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 8849 if (MinVLenB > 0) 8850 Known.Zero.setLowBits(Log2_32(MinVLenB)); 8851 // We assume VLENB is no more than 65536 / 8 bytes. 8852 Known.Zero.setBitsFrom(14); 8853 break; 8854 } 8855 case ISD::INTRINSIC_W_CHAIN: 8856 case ISD::INTRINSIC_WO_CHAIN: { 8857 unsigned IntNo = 8858 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 8859 switch (IntNo) { 8860 default: 8861 // We can't do anything for most intrinsics. 8862 break; 8863 case Intrinsic::riscv_vsetvli: 8864 case Intrinsic::riscv_vsetvlimax: 8865 case Intrinsic::riscv_vsetvli_opt: 8866 case Intrinsic::riscv_vsetvlimax_opt: 8867 // Assume that VL output is positive and would fit in an int32_t. 8868 // TODO: VLEN might be capped at 16 bits in a future V spec update. 8869 if (BitWidth >= 32) 8870 Known.Zero.setBitsFrom(31); 8871 break; 8872 } 8873 break; 8874 } 8875 } 8876 } 8877 8878 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 8879 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 8880 unsigned Depth) const { 8881 switch (Op.getOpcode()) { 8882 default: 8883 break; 8884 case RISCVISD::SELECT_CC: { 8885 unsigned Tmp = 8886 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 8887 if (Tmp == 1) return 1; // Early out. 8888 unsigned Tmp2 = 8889 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 8890 return std::min(Tmp, Tmp2); 8891 } 8892 case RISCVISD::SLLW: 8893 case RISCVISD::SRAW: 8894 case RISCVISD::SRLW: 8895 case RISCVISD::DIVW: 8896 case RISCVISD::DIVUW: 8897 case RISCVISD::REMUW: 8898 case RISCVISD::ROLW: 8899 case RISCVISD::RORW: 8900 case RISCVISD::GREVW: 8901 case RISCVISD::GORCW: 8902 case RISCVISD::FSLW: 8903 case RISCVISD::FSRW: 8904 case RISCVISD::SHFLW: 8905 case RISCVISD::UNSHFLW: 8906 case RISCVISD::BCOMPRESSW: 8907 case RISCVISD::BDECOMPRESSW: 8908 case RISCVISD::BFPW: 8909 case RISCVISD::FCVT_W_RV64: 8910 case RISCVISD::FCVT_WU_RV64: 8911 case RISCVISD::STRICT_FCVT_W_RV64: 8912 case RISCVISD::STRICT_FCVT_WU_RV64: 8913 // TODO: As the result is sign-extended, this is conservatively correct. A 8914 // more precise answer could be calculated for SRAW depending on known 8915 // bits in the shift amount. 8916 return 33; 8917 case RISCVISD::SHFL: 8918 case RISCVISD::UNSHFL: { 8919 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 8920 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 8921 // will stay within the upper 32 bits. If there were more than 32 sign bits 8922 // before there will be at least 33 sign bits after. 8923 if (Op.getValueType() == MVT::i64 && 8924 isa<ConstantSDNode>(Op.getOperand(1)) && 8925 (Op.getConstantOperandVal(1) & 0x10) == 0) { 8926 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 8927 if (Tmp > 32) 8928 return 33; 8929 } 8930 break; 8931 } 8932 case RISCVISD::VMV_X_S: { 8933 // The number of sign bits of the scalar result is computed by obtaining the 8934 // element type of the input vector operand, subtracting its width from the 8935 // XLEN, and then adding one (sign bit within the element type). If the 8936 // element type is wider than XLen, the least-significant XLEN bits are 8937 // taken. 8938 unsigned XLen = Subtarget.getXLen(); 8939 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 8940 if (EltBits <= XLen) 8941 return XLen - EltBits + 1; 8942 break; 8943 } 8944 } 8945 8946 return 1; 8947 } 8948 8949 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 8950 MachineBasicBlock *BB) { 8951 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 8952 8953 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 8954 // Should the count have wrapped while it was being read, we need to try 8955 // again. 8956 // ... 8957 // read: 8958 // rdcycleh x3 # load high word of cycle 8959 // rdcycle x2 # load low word of cycle 8960 // rdcycleh x4 # load high word of cycle 8961 // bne x3, x4, read # check if high word reads match, otherwise try again 8962 // ... 8963 8964 MachineFunction &MF = *BB->getParent(); 8965 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8966 MachineFunction::iterator It = ++BB->getIterator(); 8967 8968 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8969 MF.insert(It, LoopMBB); 8970 8971 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8972 MF.insert(It, DoneMBB); 8973 8974 // Transfer the remainder of BB and its successor edges to DoneMBB. 8975 DoneMBB->splice(DoneMBB->begin(), BB, 8976 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8977 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 8978 8979 BB->addSuccessor(LoopMBB); 8980 8981 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8982 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8983 Register LoReg = MI.getOperand(0).getReg(); 8984 Register HiReg = MI.getOperand(1).getReg(); 8985 DebugLoc DL = MI.getDebugLoc(); 8986 8987 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 8988 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 8989 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8990 .addReg(RISCV::X0); 8991 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 8992 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 8993 .addReg(RISCV::X0); 8994 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 8995 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8996 .addReg(RISCV::X0); 8997 8998 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 8999 .addReg(HiReg) 9000 .addReg(ReadAgainReg) 9001 .addMBB(LoopMBB); 9002 9003 LoopMBB->addSuccessor(LoopMBB); 9004 LoopMBB->addSuccessor(DoneMBB); 9005 9006 MI.eraseFromParent(); 9007 9008 return DoneMBB; 9009 } 9010 9011 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9012 MachineBasicBlock *BB) { 9013 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9014 9015 MachineFunction &MF = *BB->getParent(); 9016 DebugLoc DL = MI.getDebugLoc(); 9017 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9018 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9019 Register LoReg = MI.getOperand(0).getReg(); 9020 Register HiReg = MI.getOperand(1).getReg(); 9021 Register SrcReg = MI.getOperand(2).getReg(); 9022 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9023 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9024 9025 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9026 RI); 9027 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9028 MachineMemOperand *MMOLo = 9029 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9030 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9031 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9032 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9033 .addFrameIndex(FI) 9034 .addImm(0) 9035 .addMemOperand(MMOLo); 9036 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9037 .addFrameIndex(FI) 9038 .addImm(4) 9039 .addMemOperand(MMOHi); 9040 MI.eraseFromParent(); // The pseudo instruction is gone now. 9041 return BB; 9042 } 9043 9044 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9045 MachineBasicBlock *BB) { 9046 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9047 "Unexpected instruction"); 9048 9049 MachineFunction &MF = *BB->getParent(); 9050 DebugLoc DL = MI.getDebugLoc(); 9051 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9052 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9053 Register DstReg = MI.getOperand(0).getReg(); 9054 Register LoReg = MI.getOperand(1).getReg(); 9055 Register HiReg = MI.getOperand(2).getReg(); 9056 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9057 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9058 9059 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9060 MachineMemOperand *MMOLo = 9061 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9062 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9063 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9064 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9065 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9066 .addFrameIndex(FI) 9067 .addImm(0) 9068 .addMemOperand(MMOLo); 9069 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9070 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9071 .addFrameIndex(FI) 9072 .addImm(4) 9073 .addMemOperand(MMOHi); 9074 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9075 MI.eraseFromParent(); // The pseudo instruction is gone now. 9076 return BB; 9077 } 9078 9079 static bool isSelectPseudo(MachineInstr &MI) { 9080 switch (MI.getOpcode()) { 9081 default: 9082 return false; 9083 case RISCV::Select_GPR_Using_CC_GPR: 9084 case RISCV::Select_FPR16_Using_CC_GPR: 9085 case RISCV::Select_FPR32_Using_CC_GPR: 9086 case RISCV::Select_FPR64_Using_CC_GPR: 9087 return true; 9088 } 9089 } 9090 9091 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9092 unsigned RelOpcode, unsigned EqOpcode, 9093 const RISCVSubtarget &Subtarget) { 9094 DebugLoc DL = MI.getDebugLoc(); 9095 Register DstReg = MI.getOperand(0).getReg(); 9096 Register Src1Reg = MI.getOperand(1).getReg(); 9097 Register Src2Reg = MI.getOperand(2).getReg(); 9098 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9099 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9100 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9101 9102 // Save the current FFLAGS. 9103 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9104 9105 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9106 .addReg(Src1Reg) 9107 .addReg(Src2Reg); 9108 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9109 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9110 9111 // Restore the FFLAGS. 9112 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9113 .addReg(SavedFFlags, RegState::Kill); 9114 9115 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9116 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9117 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9118 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9119 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9120 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9121 9122 // Erase the pseudoinstruction. 9123 MI.eraseFromParent(); 9124 return BB; 9125 } 9126 9127 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9128 MachineBasicBlock *BB, 9129 const RISCVSubtarget &Subtarget) { 9130 // To "insert" Select_* instructions, we actually have to insert the triangle 9131 // control-flow pattern. The incoming instructions know the destination vreg 9132 // to set, the condition code register to branch on, the true/false values to 9133 // select between, and the condcode to use to select the appropriate branch. 9134 // 9135 // We produce the following control flow: 9136 // HeadMBB 9137 // | \ 9138 // | IfFalseMBB 9139 // | / 9140 // TailMBB 9141 // 9142 // When we find a sequence of selects we attempt to optimize their emission 9143 // by sharing the control flow. Currently we only handle cases where we have 9144 // multiple selects with the exact same condition (same LHS, RHS and CC). 9145 // The selects may be interleaved with other instructions if the other 9146 // instructions meet some requirements we deem safe: 9147 // - They are debug instructions. Otherwise, 9148 // - They do not have side-effects, do not access memory and their inputs do 9149 // not depend on the results of the select pseudo-instructions. 9150 // The TrueV/FalseV operands of the selects cannot depend on the result of 9151 // previous selects in the sequence. 9152 // These conditions could be further relaxed. See the X86 target for a 9153 // related approach and more information. 9154 Register LHS = MI.getOperand(1).getReg(); 9155 Register RHS = MI.getOperand(2).getReg(); 9156 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9157 9158 SmallVector<MachineInstr *, 4> SelectDebugValues; 9159 SmallSet<Register, 4> SelectDests; 9160 SelectDests.insert(MI.getOperand(0).getReg()); 9161 9162 MachineInstr *LastSelectPseudo = &MI; 9163 9164 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9165 SequenceMBBI != E; ++SequenceMBBI) { 9166 if (SequenceMBBI->isDebugInstr()) 9167 continue; 9168 else if (isSelectPseudo(*SequenceMBBI)) { 9169 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9170 SequenceMBBI->getOperand(2).getReg() != RHS || 9171 SequenceMBBI->getOperand(3).getImm() != CC || 9172 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9173 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9174 break; 9175 LastSelectPseudo = &*SequenceMBBI; 9176 SequenceMBBI->collectDebugValues(SelectDebugValues); 9177 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9178 } else { 9179 if (SequenceMBBI->hasUnmodeledSideEffects() || 9180 SequenceMBBI->mayLoadOrStore()) 9181 break; 9182 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9183 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9184 })) 9185 break; 9186 } 9187 } 9188 9189 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9190 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9191 DebugLoc DL = MI.getDebugLoc(); 9192 MachineFunction::iterator I = ++BB->getIterator(); 9193 9194 MachineBasicBlock *HeadMBB = BB; 9195 MachineFunction *F = BB->getParent(); 9196 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9197 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9198 9199 F->insert(I, IfFalseMBB); 9200 F->insert(I, TailMBB); 9201 9202 // Transfer debug instructions associated with the selects to TailMBB. 9203 for (MachineInstr *DebugInstr : SelectDebugValues) { 9204 TailMBB->push_back(DebugInstr->removeFromParent()); 9205 } 9206 9207 // Move all instructions after the sequence to TailMBB. 9208 TailMBB->splice(TailMBB->end(), HeadMBB, 9209 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9210 // Update machine-CFG edges by transferring all successors of the current 9211 // block to the new block which will contain the Phi nodes for the selects. 9212 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9213 // Set the successors for HeadMBB. 9214 HeadMBB->addSuccessor(IfFalseMBB); 9215 HeadMBB->addSuccessor(TailMBB); 9216 9217 // Insert appropriate branch. 9218 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9219 .addReg(LHS) 9220 .addReg(RHS) 9221 .addMBB(TailMBB); 9222 9223 // IfFalseMBB just falls through to TailMBB. 9224 IfFalseMBB->addSuccessor(TailMBB); 9225 9226 // Create PHIs for all of the select pseudo-instructions. 9227 auto SelectMBBI = MI.getIterator(); 9228 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9229 auto InsertionPoint = TailMBB->begin(); 9230 while (SelectMBBI != SelectEnd) { 9231 auto Next = std::next(SelectMBBI); 9232 if (isSelectPseudo(*SelectMBBI)) { 9233 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9234 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9235 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9236 .addReg(SelectMBBI->getOperand(4).getReg()) 9237 .addMBB(HeadMBB) 9238 .addReg(SelectMBBI->getOperand(5).getReg()) 9239 .addMBB(IfFalseMBB); 9240 SelectMBBI->eraseFromParent(); 9241 } 9242 SelectMBBI = Next; 9243 } 9244 9245 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9246 return TailMBB; 9247 } 9248 9249 MachineBasicBlock * 9250 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9251 MachineBasicBlock *BB) const { 9252 switch (MI.getOpcode()) { 9253 default: 9254 llvm_unreachable("Unexpected instr type to insert"); 9255 case RISCV::ReadCycleWide: 9256 assert(!Subtarget.is64Bit() && 9257 "ReadCycleWrite is only to be used on riscv32"); 9258 return emitReadCycleWidePseudo(MI, BB); 9259 case RISCV::Select_GPR_Using_CC_GPR: 9260 case RISCV::Select_FPR16_Using_CC_GPR: 9261 case RISCV::Select_FPR32_Using_CC_GPR: 9262 case RISCV::Select_FPR64_Using_CC_GPR: 9263 return emitSelectPseudo(MI, BB, Subtarget); 9264 case RISCV::BuildPairF64Pseudo: 9265 return emitBuildPairF64Pseudo(MI, BB); 9266 case RISCV::SplitF64Pseudo: 9267 return emitSplitF64Pseudo(MI, BB); 9268 case RISCV::PseudoQuietFLE_H: 9269 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9270 case RISCV::PseudoQuietFLT_H: 9271 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9272 case RISCV::PseudoQuietFLE_S: 9273 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9274 case RISCV::PseudoQuietFLT_S: 9275 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9276 case RISCV::PseudoQuietFLE_D: 9277 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9278 case RISCV::PseudoQuietFLT_D: 9279 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9280 } 9281 } 9282 9283 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9284 SDNode *Node) const { 9285 // Add FRM dependency to any instructions with dynamic rounding mode. 9286 unsigned Opc = MI.getOpcode(); 9287 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9288 if (Idx < 0) 9289 return; 9290 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9291 return; 9292 // If the instruction already reads FRM, don't add another read. 9293 if (MI.readsRegister(RISCV::FRM)) 9294 return; 9295 MI.addOperand( 9296 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9297 } 9298 9299 // Calling Convention Implementation. 9300 // The expectations for frontend ABI lowering vary from target to target. 9301 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9302 // details, but this is a longer term goal. For now, we simply try to keep the 9303 // role of the frontend as simple and well-defined as possible. The rules can 9304 // be summarised as: 9305 // * Never split up large scalar arguments. We handle them here. 9306 // * If a hardfloat calling convention is being used, and the struct may be 9307 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9308 // available, then pass as two separate arguments. If either the GPRs or FPRs 9309 // are exhausted, then pass according to the rule below. 9310 // * If a struct could never be passed in registers or directly in a stack 9311 // slot (as it is larger than 2*XLEN and the floating point rules don't 9312 // apply), then pass it using a pointer with the byval attribute. 9313 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9314 // word-sized array or a 2*XLEN scalar (depending on alignment). 9315 // * The frontend can determine whether a struct is returned by reference or 9316 // not based on its size and fields. If it will be returned by reference, the 9317 // frontend must modify the prototype so a pointer with the sret annotation is 9318 // passed as the first argument. This is not necessary for large scalar 9319 // returns. 9320 // * Struct return values and varargs should be coerced to structs containing 9321 // register-size fields in the same situations they would be for fixed 9322 // arguments. 9323 9324 static const MCPhysReg ArgGPRs[] = { 9325 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9326 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9327 }; 9328 static const MCPhysReg ArgFPR16s[] = { 9329 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9330 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9331 }; 9332 static const MCPhysReg ArgFPR32s[] = { 9333 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9334 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9335 }; 9336 static const MCPhysReg ArgFPR64s[] = { 9337 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9338 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9339 }; 9340 // This is an interim calling convention and it may be changed in the future. 9341 static const MCPhysReg ArgVRs[] = { 9342 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9343 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9344 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9345 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9346 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9347 RISCV::V20M2, RISCV::V22M2}; 9348 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9349 RISCV::V20M4}; 9350 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9351 9352 // Pass a 2*XLEN argument that has been split into two XLEN values through 9353 // registers or the stack as necessary. 9354 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9355 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9356 MVT ValVT2, MVT LocVT2, 9357 ISD::ArgFlagsTy ArgFlags2) { 9358 unsigned XLenInBytes = XLen / 8; 9359 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9360 // At least one half can be passed via register. 9361 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9362 VA1.getLocVT(), CCValAssign::Full)); 9363 } else { 9364 // Both halves must be passed on the stack, with proper alignment. 9365 Align StackAlign = 9366 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9367 State.addLoc( 9368 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9369 State.AllocateStack(XLenInBytes, StackAlign), 9370 VA1.getLocVT(), CCValAssign::Full)); 9371 State.addLoc(CCValAssign::getMem( 9372 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9373 LocVT2, CCValAssign::Full)); 9374 return false; 9375 } 9376 9377 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9378 // The second half can also be passed via register. 9379 State.addLoc( 9380 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9381 } else { 9382 // The second half is passed via the stack, without additional alignment. 9383 State.addLoc(CCValAssign::getMem( 9384 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9385 LocVT2, CCValAssign::Full)); 9386 } 9387 9388 return false; 9389 } 9390 9391 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9392 Optional<unsigned> FirstMaskArgument, 9393 CCState &State, const RISCVTargetLowering &TLI) { 9394 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9395 if (RC == &RISCV::VRRegClass) { 9396 // Assign the first mask argument to V0. 9397 // This is an interim calling convention and it may be changed in the 9398 // future. 9399 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9400 return State.AllocateReg(RISCV::V0); 9401 return State.AllocateReg(ArgVRs); 9402 } 9403 if (RC == &RISCV::VRM2RegClass) 9404 return State.AllocateReg(ArgVRM2s); 9405 if (RC == &RISCV::VRM4RegClass) 9406 return State.AllocateReg(ArgVRM4s); 9407 if (RC == &RISCV::VRM8RegClass) 9408 return State.AllocateReg(ArgVRM8s); 9409 llvm_unreachable("Unhandled register class for ValueType"); 9410 } 9411 9412 // Implements the RISC-V calling convention. Returns true upon failure. 9413 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9414 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9415 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9416 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9417 Optional<unsigned> FirstMaskArgument) { 9418 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9419 assert(XLen == 32 || XLen == 64); 9420 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9421 9422 // Any return value split in to more than two values can't be returned 9423 // directly. Vectors are returned via the available vector registers. 9424 if (!LocVT.isVector() && IsRet && ValNo > 1) 9425 return true; 9426 9427 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9428 // variadic argument, or if no F16/F32 argument registers are available. 9429 bool UseGPRForF16_F32 = true; 9430 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9431 // variadic argument, or if no F64 argument registers are available. 9432 bool UseGPRForF64 = true; 9433 9434 switch (ABI) { 9435 default: 9436 llvm_unreachable("Unexpected ABI"); 9437 case RISCVABI::ABI_ILP32: 9438 case RISCVABI::ABI_LP64: 9439 break; 9440 case RISCVABI::ABI_ILP32F: 9441 case RISCVABI::ABI_LP64F: 9442 UseGPRForF16_F32 = !IsFixed; 9443 break; 9444 case RISCVABI::ABI_ILP32D: 9445 case RISCVABI::ABI_LP64D: 9446 UseGPRForF16_F32 = !IsFixed; 9447 UseGPRForF64 = !IsFixed; 9448 break; 9449 } 9450 9451 // FPR16, FPR32, and FPR64 alias each other. 9452 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9453 UseGPRForF16_F32 = true; 9454 UseGPRForF64 = true; 9455 } 9456 9457 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9458 // similar local variables rather than directly checking against the target 9459 // ABI. 9460 9461 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9462 LocVT = XLenVT; 9463 LocInfo = CCValAssign::BCvt; 9464 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9465 LocVT = MVT::i64; 9466 LocInfo = CCValAssign::BCvt; 9467 } 9468 9469 // If this is a variadic argument, the RISC-V calling convention requires 9470 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9471 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9472 // be used regardless of whether the original argument was split during 9473 // legalisation or not. The argument will not be passed by registers if the 9474 // original type is larger than 2*XLEN, so the register alignment rule does 9475 // not apply. 9476 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9477 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9478 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9479 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9480 // Skip 'odd' register if necessary. 9481 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9482 State.AllocateReg(ArgGPRs); 9483 } 9484 9485 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9486 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9487 State.getPendingArgFlags(); 9488 9489 assert(PendingLocs.size() == PendingArgFlags.size() && 9490 "PendingLocs and PendingArgFlags out of sync"); 9491 9492 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9493 // registers are exhausted. 9494 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9495 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9496 "Can't lower f64 if it is split"); 9497 // Depending on available argument GPRS, f64 may be passed in a pair of 9498 // GPRs, split between a GPR and the stack, or passed completely on the 9499 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9500 // cases. 9501 Register Reg = State.AllocateReg(ArgGPRs); 9502 LocVT = MVT::i32; 9503 if (!Reg) { 9504 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9505 State.addLoc( 9506 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9507 return false; 9508 } 9509 if (!State.AllocateReg(ArgGPRs)) 9510 State.AllocateStack(4, Align(4)); 9511 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9512 return false; 9513 } 9514 9515 // Fixed-length vectors are located in the corresponding scalable-vector 9516 // container types. 9517 if (ValVT.isFixedLengthVector()) 9518 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9519 9520 // Split arguments might be passed indirectly, so keep track of the pending 9521 // values. Split vectors are passed via a mix of registers and indirectly, so 9522 // treat them as we would any other argument. 9523 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9524 LocVT = XLenVT; 9525 LocInfo = CCValAssign::Indirect; 9526 PendingLocs.push_back( 9527 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9528 PendingArgFlags.push_back(ArgFlags); 9529 if (!ArgFlags.isSplitEnd()) { 9530 return false; 9531 } 9532 } 9533 9534 // If the split argument only had two elements, it should be passed directly 9535 // in registers or on the stack. 9536 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9537 PendingLocs.size() <= 2) { 9538 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9539 // Apply the normal calling convention rules to the first half of the 9540 // split argument. 9541 CCValAssign VA = PendingLocs[0]; 9542 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9543 PendingLocs.clear(); 9544 PendingArgFlags.clear(); 9545 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9546 ArgFlags); 9547 } 9548 9549 // Allocate to a register if possible, or else a stack slot. 9550 Register Reg; 9551 unsigned StoreSizeBytes = XLen / 8; 9552 Align StackAlign = Align(XLen / 8); 9553 9554 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9555 Reg = State.AllocateReg(ArgFPR16s); 9556 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9557 Reg = State.AllocateReg(ArgFPR32s); 9558 else if (ValVT == MVT::f64 && !UseGPRForF64) 9559 Reg = State.AllocateReg(ArgFPR64s); 9560 else if (ValVT.isVector()) { 9561 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9562 if (!Reg) { 9563 // For return values, the vector must be passed fully via registers or 9564 // via the stack. 9565 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9566 // but we're using all of them. 9567 if (IsRet) 9568 return true; 9569 // Try using a GPR to pass the address 9570 if ((Reg = State.AllocateReg(ArgGPRs))) { 9571 LocVT = XLenVT; 9572 LocInfo = CCValAssign::Indirect; 9573 } else if (ValVT.isScalableVector()) { 9574 LocVT = XLenVT; 9575 LocInfo = CCValAssign::Indirect; 9576 } else { 9577 // Pass fixed-length vectors on the stack. 9578 LocVT = ValVT; 9579 StoreSizeBytes = ValVT.getStoreSize(); 9580 // Align vectors to their element sizes, being careful for vXi1 9581 // vectors. 9582 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9583 } 9584 } 9585 } else { 9586 Reg = State.AllocateReg(ArgGPRs); 9587 } 9588 9589 unsigned StackOffset = 9590 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9591 9592 // If we reach this point and PendingLocs is non-empty, we must be at the 9593 // end of a split argument that must be passed indirectly. 9594 if (!PendingLocs.empty()) { 9595 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9596 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9597 9598 for (auto &It : PendingLocs) { 9599 if (Reg) 9600 It.convertToReg(Reg); 9601 else 9602 It.convertToMem(StackOffset); 9603 State.addLoc(It); 9604 } 9605 PendingLocs.clear(); 9606 PendingArgFlags.clear(); 9607 return false; 9608 } 9609 9610 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9611 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9612 "Expected an XLenVT or vector types at this stage"); 9613 9614 if (Reg) { 9615 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9616 return false; 9617 } 9618 9619 // When a floating-point value is passed on the stack, no bit-conversion is 9620 // needed. 9621 if (ValVT.isFloatingPoint()) { 9622 LocVT = ValVT; 9623 LocInfo = CCValAssign::Full; 9624 } 9625 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9626 return false; 9627 } 9628 9629 template <typename ArgTy> 9630 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9631 for (const auto &ArgIdx : enumerate(Args)) { 9632 MVT ArgVT = ArgIdx.value().VT; 9633 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9634 return ArgIdx.index(); 9635 } 9636 return None; 9637 } 9638 9639 void RISCVTargetLowering::analyzeInputArgs( 9640 MachineFunction &MF, CCState &CCInfo, 9641 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9642 RISCVCCAssignFn Fn) const { 9643 unsigned NumArgs = Ins.size(); 9644 FunctionType *FType = MF.getFunction().getFunctionType(); 9645 9646 Optional<unsigned> FirstMaskArgument; 9647 if (Subtarget.hasVInstructions()) 9648 FirstMaskArgument = preAssignMask(Ins); 9649 9650 for (unsigned i = 0; i != NumArgs; ++i) { 9651 MVT ArgVT = Ins[i].VT; 9652 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9653 9654 Type *ArgTy = nullptr; 9655 if (IsRet) 9656 ArgTy = FType->getReturnType(); 9657 else if (Ins[i].isOrigArg()) 9658 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9659 9660 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9661 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9662 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9663 FirstMaskArgument)) { 9664 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9665 << EVT(ArgVT).getEVTString() << '\n'); 9666 llvm_unreachable(nullptr); 9667 } 9668 } 9669 } 9670 9671 void RISCVTargetLowering::analyzeOutputArgs( 9672 MachineFunction &MF, CCState &CCInfo, 9673 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9674 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9675 unsigned NumArgs = Outs.size(); 9676 9677 Optional<unsigned> FirstMaskArgument; 9678 if (Subtarget.hasVInstructions()) 9679 FirstMaskArgument = preAssignMask(Outs); 9680 9681 for (unsigned i = 0; i != NumArgs; i++) { 9682 MVT ArgVT = Outs[i].VT; 9683 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9684 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9685 9686 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9687 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9688 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9689 FirstMaskArgument)) { 9690 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9691 << EVT(ArgVT).getEVTString() << "\n"); 9692 llvm_unreachable(nullptr); 9693 } 9694 } 9695 } 9696 9697 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9698 // values. 9699 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9700 const CCValAssign &VA, const SDLoc &DL, 9701 const RISCVSubtarget &Subtarget) { 9702 switch (VA.getLocInfo()) { 9703 default: 9704 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9705 case CCValAssign::Full: 9706 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9707 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9708 break; 9709 case CCValAssign::BCvt: 9710 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9711 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9712 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9713 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9714 else 9715 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9716 break; 9717 } 9718 return Val; 9719 } 9720 9721 // The caller is responsible for loading the full value if the argument is 9722 // passed with CCValAssign::Indirect. 9723 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9724 const CCValAssign &VA, const SDLoc &DL, 9725 const RISCVTargetLowering &TLI) { 9726 MachineFunction &MF = DAG.getMachineFunction(); 9727 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9728 EVT LocVT = VA.getLocVT(); 9729 SDValue Val; 9730 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9731 Register VReg = RegInfo.createVirtualRegister(RC); 9732 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9733 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9734 9735 if (VA.getLocInfo() == CCValAssign::Indirect) 9736 return Val; 9737 9738 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9739 } 9740 9741 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9742 const CCValAssign &VA, const SDLoc &DL, 9743 const RISCVSubtarget &Subtarget) { 9744 EVT LocVT = VA.getLocVT(); 9745 9746 switch (VA.getLocInfo()) { 9747 default: 9748 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9749 case CCValAssign::Full: 9750 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9751 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9752 break; 9753 case CCValAssign::BCvt: 9754 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9755 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9756 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9757 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9758 else 9759 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9760 break; 9761 } 9762 return Val; 9763 } 9764 9765 // The caller is responsible for loading the full value if the argument is 9766 // passed with CCValAssign::Indirect. 9767 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9768 const CCValAssign &VA, const SDLoc &DL) { 9769 MachineFunction &MF = DAG.getMachineFunction(); 9770 MachineFrameInfo &MFI = MF.getFrameInfo(); 9771 EVT LocVT = VA.getLocVT(); 9772 EVT ValVT = VA.getValVT(); 9773 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9774 if (ValVT.isScalableVector()) { 9775 // When the value is a scalable vector, we save the pointer which points to 9776 // the scalable vector value in the stack. The ValVT will be the pointer 9777 // type, instead of the scalable vector type. 9778 ValVT = LocVT; 9779 } 9780 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9781 /*IsImmutable=*/true); 9782 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9783 SDValue Val; 9784 9785 ISD::LoadExtType ExtType; 9786 switch (VA.getLocInfo()) { 9787 default: 9788 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9789 case CCValAssign::Full: 9790 case CCValAssign::Indirect: 9791 case CCValAssign::BCvt: 9792 ExtType = ISD::NON_EXTLOAD; 9793 break; 9794 } 9795 Val = DAG.getExtLoad( 9796 ExtType, DL, LocVT, Chain, FIN, 9797 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9798 return Val; 9799 } 9800 9801 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9802 const CCValAssign &VA, const SDLoc &DL) { 9803 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9804 "Unexpected VA"); 9805 MachineFunction &MF = DAG.getMachineFunction(); 9806 MachineFrameInfo &MFI = MF.getFrameInfo(); 9807 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9808 9809 if (VA.isMemLoc()) { 9810 // f64 is passed on the stack. 9811 int FI = 9812 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9813 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9814 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9815 MachinePointerInfo::getFixedStack(MF, FI)); 9816 } 9817 9818 assert(VA.isRegLoc() && "Expected register VA assignment"); 9819 9820 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9821 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 9822 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 9823 SDValue Hi; 9824 if (VA.getLocReg() == RISCV::X17) { 9825 // Second half of f64 is passed on the stack. 9826 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 9827 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9828 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 9829 MachinePointerInfo::getFixedStack(MF, FI)); 9830 } else { 9831 // Second half of f64 is passed in another GPR. 9832 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9833 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 9834 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 9835 } 9836 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 9837 } 9838 9839 // FastCC has less than 1% performance improvement for some particular 9840 // benchmark. But theoretically, it may has benenfit for some cases. 9841 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 9842 unsigned ValNo, MVT ValVT, MVT LocVT, 9843 CCValAssign::LocInfo LocInfo, 9844 ISD::ArgFlagsTy ArgFlags, CCState &State, 9845 bool IsFixed, bool IsRet, Type *OrigTy, 9846 const RISCVTargetLowering &TLI, 9847 Optional<unsigned> FirstMaskArgument) { 9848 9849 // X5 and X6 might be used for save-restore libcall. 9850 static const MCPhysReg GPRList[] = { 9851 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 9852 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 9853 RISCV::X29, RISCV::X30, RISCV::X31}; 9854 9855 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9856 if (unsigned Reg = State.AllocateReg(GPRList)) { 9857 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9858 return false; 9859 } 9860 } 9861 9862 if (LocVT == MVT::f16) { 9863 static const MCPhysReg FPR16List[] = { 9864 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 9865 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 9866 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 9867 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 9868 if (unsigned Reg = State.AllocateReg(FPR16List)) { 9869 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9870 return false; 9871 } 9872 } 9873 9874 if (LocVT == MVT::f32) { 9875 static const MCPhysReg FPR32List[] = { 9876 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 9877 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 9878 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 9879 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 9880 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9881 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9882 return false; 9883 } 9884 } 9885 9886 if (LocVT == MVT::f64) { 9887 static const MCPhysReg FPR64List[] = { 9888 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 9889 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 9890 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 9891 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 9892 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9893 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9894 return false; 9895 } 9896 } 9897 9898 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 9899 unsigned Offset4 = State.AllocateStack(4, Align(4)); 9900 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 9901 return false; 9902 } 9903 9904 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 9905 unsigned Offset5 = State.AllocateStack(8, Align(8)); 9906 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 9907 return false; 9908 } 9909 9910 if (LocVT.isVector()) { 9911 if (unsigned Reg = 9912 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 9913 // Fixed-length vectors are located in the corresponding scalable-vector 9914 // container types. 9915 if (ValVT.isFixedLengthVector()) 9916 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9917 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9918 } else { 9919 // Try and pass the address via a "fast" GPR. 9920 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 9921 LocInfo = CCValAssign::Indirect; 9922 LocVT = TLI.getSubtarget().getXLenVT(); 9923 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 9924 } else if (ValVT.isFixedLengthVector()) { 9925 auto StackAlign = 9926 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9927 unsigned StackOffset = 9928 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 9929 State.addLoc( 9930 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9931 } else { 9932 // Can't pass scalable vectors on the stack. 9933 return true; 9934 } 9935 } 9936 9937 return false; 9938 } 9939 9940 return true; // CC didn't match. 9941 } 9942 9943 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9944 CCValAssign::LocInfo LocInfo, 9945 ISD::ArgFlagsTy ArgFlags, CCState &State) { 9946 9947 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9948 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 9949 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 9950 static const MCPhysReg GPRList[] = { 9951 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 9952 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 9953 if (unsigned Reg = State.AllocateReg(GPRList)) { 9954 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9955 return false; 9956 } 9957 } 9958 9959 if (LocVT == MVT::f32) { 9960 // Pass in STG registers: F1, ..., F6 9961 // fs0 ... fs5 9962 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 9963 RISCV::F18_F, RISCV::F19_F, 9964 RISCV::F20_F, RISCV::F21_F}; 9965 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9966 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9967 return false; 9968 } 9969 } 9970 9971 if (LocVT == MVT::f64) { 9972 // Pass in STG registers: D1, ..., D6 9973 // fs6 ... fs11 9974 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 9975 RISCV::F24_D, RISCV::F25_D, 9976 RISCV::F26_D, RISCV::F27_D}; 9977 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9978 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9979 return false; 9980 } 9981 } 9982 9983 report_fatal_error("No registers left in GHC calling convention"); 9984 return true; 9985 } 9986 9987 // Transform physical registers into virtual registers. 9988 SDValue RISCVTargetLowering::LowerFormalArguments( 9989 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 9990 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 9991 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 9992 9993 MachineFunction &MF = DAG.getMachineFunction(); 9994 9995 switch (CallConv) { 9996 default: 9997 report_fatal_error("Unsupported calling convention"); 9998 case CallingConv::C: 9999 case CallingConv::Fast: 10000 break; 10001 case CallingConv::GHC: 10002 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10003 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10004 report_fatal_error( 10005 "GHC calling convention requires the F and D instruction set extensions"); 10006 } 10007 10008 const Function &Func = MF.getFunction(); 10009 if (Func.hasFnAttribute("interrupt")) { 10010 if (!Func.arg_empty()) 10011 report_fatal_error( 10012 "Functions with the interrupt attribute cannot have arguments!"); 10013 10014 StringRef Kind = 10015 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10016 10017 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10018 report_fatal_error( 10019 "Function interrupt attribute argument not supported!"); 10020 } 10021 10022 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10023 MVT XLenVT = Subtarget.getXLenVT(); 10024 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10025 // Used with vargs to acumulate store chains. 10026 std::vector<SDValue> OutChains; 10027 10028 // Assign locations to all of the incoming arguments. 10029 SmallVector<CCValAssign, 16> ArgLocs; 10030 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10031 10032 if (CallConv == CallingConv::GHC) 10033 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10034 else 10035 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10036 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10037 : CC_RISCV); 10038 10039 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10040 CCValAssign &VA = ArgLocs[i]; 10041 SDValue ArgValue; 10042 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10043 // case. 10044 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10045 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10046 else if (VA.isRegLoc()) 10047 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10048 else 10049 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10050 10051 if (VA.getLocInfo() == CCValAssign::Indirect) { 10052 // If the original argument was split and passed by reference (e.g. i128 10053 // on RV32), we need to load all parts of it here (using the same 10054 // address). Vectors may be partly split to registers and partly to the 10055 // stack, in which case the base address is partly offset and subsequent 10056 // stores are relative to that. 10057 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10058 MachinePointerInfo())); 10059 unsigned ArgIndex = Ins[i].OrigArgIndex; 10060 unsigned ArgPartOffset = Ins[i].PartOffset; 10061 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10062 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10063 CCValAssign &PartVA = ArgLocs[i + 1]; 10064 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10065 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10066 if (PartVA.getValVT().isScalableVector()) 10067 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10068 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10069 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10070 MachinePointerInfo())); 10071 ++i; 10072 } 10073 continue; 10074 } 10075 InVals.push_back(ArgValue); 10076 } 10077 10078 if (IsVarArg) { 10079 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10080 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10081 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10082 MachineFrameInfo &MFI = MF.getFrameInfo(); 10083 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10084 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10085 10086 // Offset of the first variable argument from stack pointer, and size of 10087 // the vararg save area. For now, the varargs save area is either zero or 10088 // large enough to hold a0-a7. 10089 int VaArgOffset, VarArgsSaveSize; 10090 10091 // If all registers are allocated, then all varargs must be passed on the 10092 // stack and we don't need to save any argregs. 10093 if (ArgRegs.size() == Idx) { 10094 VaArgOffset = CCInfo.getNextStackOffset(); 10095 VarArgsSaveSize = 0; 10096 } else { 10097 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10098 VaArgOffset = -VarArgsSaveSize; 10099 } 10100 10101 // Record the frame index of the first variable argument 10102 // which is a value necessary to VASTART. 10103 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10104 RVFI->setVarArgsFrameIndex(FI); 10105 10106 // If saving an odd number of registers then create an extra stack slot to 10107 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10108 // offsets to even-numbered registered remain 2*XLEN-aligned. 10109 if (Idx % 2) { 10110 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10111 VarArgsSaveSize += XLenInBytes; 10112 } 10113 10114 // Copy the integer registers that may have been used for passing varargs 10115 // to the vararg save area. 10116 for (unsigned I = Idx; I < ArgRegs.size(); 10117 ++I, VaArgOffset += XLenInBytes) { 10118 const Register Reg = RegInfo.createVirtualRegister(RC); 10119 RegInfo.addLiveIn(ArgRegs[I], Reg); 10120 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10121 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10122 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10123 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10124 MachinePointerInfo::getFixedStack(MF, FI)); 10125 cast<StoreSDNode>(Store.getNode()) 10126 ->getMemOperand() 10127 ->setValue((Value *)nullptr); 10128 OutChains.push_back(Store); 10129 } 10130 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10131 } 10132 10133 // All stores are grouped in one node to allow the matching between 10134 // the size of Ins and InVals. This only happens for vararg functions. 10135 if (!OutChains.empty()) { 10136 OutChains.push_back(Chain); 10137 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10138 } 10139 10140 return Chain; 10141 } 10142 10143 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10144 /// for tail call optimization. 10145 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10146 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10147 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10148 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10149 10150 auto &Callee = CLI.Callee; 10151 auto CalleeCC = CLI.CallConv; 10152 auto &Outs = CLI.Outs; 10153 auto &Caller = MF.getFunction(); 10154 auto CallerCC = Caller.getCallingConv(); 10155 10156 // Exception-handling functions need a special set of instructions to 10157 // indicate a return to the hardware. Tail-calling another function would 10158 // probably break this. 10159 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10160 // should be expanded as new function attributes are introduced. 10161 if (Caller.hasFnAttribute("interrupt")) 10162 return false; 10163 10164 // Do not tail call opt if the stack is used to pass parameters. 10165 if (CCInfo.getNextStackOffset() != 0) 10166 return false; 10167 10168 // Do not tail call opt if any parameters need to be passed indirectly. 10169 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10170 // passed indirectly. So the address of the value will be passed in a 10171 // register, or if not available, then the address is put on the stack. In 10172 // order to pass indirectly, space on the stack often needs to be allocated 10173 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10174 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10175 // are passed CCValAssign::Indirect. 10176 for (auto &VA : ArgLocs) 10177 if (VA.getLocInfo() == CCValAssign::Indirect) 10178 return false; 10179 10180 // Do not tail call opt if either caller or callee uses struct return 10181 // semantics. 10182 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10183 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10184 if (IsCallerStructRet || IsCalleeStructRet) 10185 return false; 10186 10187 // Externally-defined functions with weak linkage should not be 10188 // tail-called. The behaviour of branch instructions in this situation (as 10189 // used for tail calls) is implementation-defined, so we cannot rely on the 10190 // linker replacing the tail call with a return. 10191 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10192 const GlobalValue *GV = G->getGlobal(); 10193 if (GV->hasExternalWeakLinkage()) 10194 return false; 10195 } 10196 10197 // The callee has to preserve all registers the caller needs to preserve. 10198 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10199 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10200 if (CalleeCC != CallerCC) { 10201 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10202 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10203 return false; 10204 } 10205 10206 // Byval parameters hand the function a pointer directly into the stack area 10207 // we want to reuse during a tail call. Working around this *is* possible 10208 // but less efficient and uglier in LowerCall. 10209 for (auto &Arg : Outs) 10210 if (Arg.Flags.isByVal()) 10211 return false; 10212 10213 return true; 10214 } 10215 10216 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10217 return DAG.getDataLayout().getPrefTypeAlign( 10218 VT.getTypeForEVT(*DAG.getContext())); 10219 } 10220 10221 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10222 // and output parameter nodes. 10223 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10224 SmallVectorImpl<SDValue> &InVals) const { 10225 SelectionDAG &DAG = CLI.DAG; 10226 SDLoc &DL = CLI.DL; 10227 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10228 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10229 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10230 SDValue Chain = CLI.Chain; 10231 SDValue Callee = CLI.Callee; 10232 bool &IsTailCall = CLI.IsTailCall; 10233 CallingConv::ID CallConv = CLI.CallConv; 10234 bool IsVarArg = CLI.IsVarArg; 10235 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10236 MVT XLenVT = Subtarget.getXLenVT(); 10237 10238 MachineFunction &MF = DAG.getMachineFunction(); 10239 10240 // Analyze the operands of the call, assigning locations to each operand. 10241 SmallVector<CCValAssign, 16> ArgLocs; 10242 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10243 10244 if (CallConv == CallingConv::GHC) 10245 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10246 else 10247 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10248 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10249 : CC_RISCV); 10250 10251 // Check if it's really possible to do a tail call. 10252 if (IsTailCall) 10253 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10254 10255 if (IsTailCall) 10256 ++NumTailCalls; 10257 else if (CLI.CB && CLI.CB->isMustTailCall()) 10258 report_fatal_error("failed to perform tail call elimination on a call " 10259 "site marked musttail"); 10260 10261 // Get a count of how many bytes are to be pushed on the stack. 10262 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10263 10264 // Create local copies for byval args 10265 SmallVector<SDValue, 8> ByValArgs; 10266 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10267 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10268 if (!Flags.isByVal()) 10269 continue; 10270 10271 SDValue Arg = OutVals[i]; 10272 unsigned Size = Flags.getByValSize(); 10273 Align Alignment = Flags.getNonZeroByValAlign(); 10274 10275 int FI = 10276 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10277 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10278 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10279 10280 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10281 /*IsVolatile=*/false, 10282 /*AlwaysInline=*/false, IsTailCall, 10283 MachinePointerInfo(), MachinePointerInfo()); 10284 ByValArgs.push_back(FIPtr); 10285 } 10286 10287 if (!IsTailCall) 10288 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10289 10290 // Copy argument values to their designated locations. 10291 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10292 SmallVector<SDValue, 8> MemOpChains; 10293 SDValue StackPtr; 10294 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10295 CCValAssign &VA = ArgLocs[i]; 10296 SDValue ArgValue = OutVals[i]; 10297 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10298 10299 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10300 bool IsF64OnRV32DSoftABI = 10301 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10302 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10303 SDValue SplitF64 = DAG.getNode( 10304 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10305 SDValue Lo = SplitF64.getValue(0); 10306 SDValue Hi = SplitF64.getValue(1); 10307 10308 Register RegLo = VA.getLocReg(); 10309 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10310 10311 if (RegLo == RISCV::X17) { 10312 // Second half of f64 is passed on the stack. 10313 // Work out the address of the stack slot. 10314 if (!StackPtr.getNode()) 10315 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10316 // Emit the store. 10317 MemOpChains.push_back( 10318 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10319 } else { 10320 // Second half of f64 is passed in another GPR. 10321 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10322 Register RegHigh = RegLo + 1; 10323 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10324 } 10325 continue; 10326 } 10327 10328 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10329 // as any other MemLoc. 10330 10331 // Promote the value if needed. 10332 // For now, only handle fully promoted and indirect arguments. 10333 if (VA.getLocInfo() == CCValAssign::Indirect) { 10334 // Store the argument in a stack slot and pass its address. 10335 Align StackAlign = 10336 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10337 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10338 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10339 // If the original argument was split (e.g. i128), we need 10340 // to store the required parts of it here (and pass just one address). 10341 // Vectors may be partly split to registers and partly to the stack, in 10342 // which case the base address is partly offset and subsequent stores are 10343 // relative to that. 10344 unsigned ArgIndex = Outs[i].OrigArgIndex; 10345 unsigned ArgPartOffset = Outs[i].PartOffset; 10346 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10347 // Calculate the total size to store. We don't have access to what we're 10348 // actually storing other than performing the loop and collecting the 10349 // info. 10350 SmallVector<std::pair<SDValue, SDValue>> Parts; 10351 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10352 SDValue PartValue = OutVals[i + 1]; 10353 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10354 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10355 EVT PartVT = PartValue.getValueType(); 10356 if (PartVT.isScalableVector()) 10357 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10358 StoredSize += PartVT.getStoreSize(); 10359 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10360 Parts.push_back(std::make_pair(PartValue, Offset)); 10361 ++i; 10362 } 10363 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10364 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10365 MemOpChains.push_back( 10366 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10367 MachinePointerInfo::getFixedStack(MF, FI))); 10368 for (const auto &Part : Parts) { 10369 SDValue PartValue = Part.first; 10370 SDValue PartOffset = Part.second; 10371 SDValue Address = 10372 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10373 MemOpChains.push_back( 10374 DAG.getStore(Chain, DL, PartValue, Address, 10375 MachinePointerInfo::getFixedStack(MF, FI))); 10376 } 10377 ArgValue = SpillSlot; 10378 } else { 10379 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10380 } 10381 10382 // Use local copy if it is a byval arg. 10383 if (Flags.isByVal()) 10384 ArgValue = ByValArgs[j++]; 10385 10386 if (VA.isRegLoc()) { 10387 // Queue up the argument copies and emit them at the end. 10388 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10389 } else { 10390 assert(VA.isMemLoc() && "Argument not register or memory"); 10391 assert(!IsTailCall && "Tail call not allowed if stack is used " 10392 "for passing parameters"); 10393 10394 // Work out the address of the stack slot. 10395 if (!StackPtr.getNode()) 10396 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10397 SDValue Address = 10398 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10399 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10400 10401 // Emit the store. 10402 MemOpChains.push_back( 10403 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10404 } 10405 } 10406 10407 // Join the stores, which are independent of one another. 10408 if (!MemOpChains.empty()) 10409 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10410 10411 SDValue Glue; 10412 10413 // Build a sequence of copy-to-reg nodes, chained and glued together. 10414 for (auto &Reg : RegsToPass) { 10415 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10416 Glue = Chain.getValue(1); 10417 } 10418 10419 // Validate that none of the argument registers have been marked as 10420 // reserved, if so report an error. Do the same for the return address if this 10421 // is not a tailcall. 10422 validateCCReservedRegs(RegsToPass, MF); 10423 if (!IsTailCall && 10424 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10425 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10426 MF.getFunction(), 10427 "Return address register required, but has been reserved."}); 10428 10429 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10430 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10431 // split it and then direct call can be matched by PseudoCALL. 10432 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10433 const GlobalValue *GV = S->getGlobal(); 10434 10435 unsigned OpFlags = RISCVII::MO_CALL; 10436 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10437 OpFlags = RISCVII::MO_PLT; 10438 10439 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10440 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10441 unsigned OpFlags = RISCVII::MO_CALL; 10442 10443 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10444 nullptr)) 10445 OpFlags = RISCVII::MO_PLT; 10446 10447 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10448 } 10449 10450 // The first call operand is the chain and the second is the target address. 10451 SmallVector<SDValue, 8> Ops; 10452 Ops.push_back(Chain); 10453 Ops.push_back(Callee); 10454 10455 // Add argument registers to the end of the list so that they are 10456 // known live into the call. 10457 for (auto &Reg : RegsToPass) 10458 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10459 10460 if (!IsTailCall) { 10461 // Add a register mask operand representing the call-preserved registers. 10462 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10463 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10464 assert(Mask && "Missing call preserved mask for calling convention"); 10465 Ops.push_back(DAG.getRegisterMask(Mask)); 10466 } 10467 10468 // Glue the call to the argument copies, if any. 10469 if (Glue.getNode()) 10470 Ops.push_back(Glue); 10471 10472 // Emit the call. 10473 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10474 10475 if (IsTailCall) { 10476 MF.getFrameInfo().setHasTailCall(); 10477 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10478 } 10479 10480 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10481 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10482 Glue = Chain.getValue(1); 10483 10484 // Mark the end of the call, which is glued to the call itself. 10485 Chain = DAG.getCALLSEQ_END(Chain, 10486 DAG.getConstant(NumBytes, DL, PtrVT, true), 10487 DAG.getConstant(0, DL, PtrVT, true), 10488 Glue, DL); 10489 Glue = Chain.getValue(1); 10490 10491 // Assign locations to each value returned by this call. 10492 SmallVector<CCValAssign, 16> RVLocs; 10493 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10494 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10495 10496 // Copy all of the result registers out of their specified physreg. 10497 for (auto &VA : RVLocs) { 10498 // Copy the value out 10499 SDValue RetValue = 10500 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10501 // Glue the RetValue to the end of the call sequence 10502 Chain = RetValue.getValue(1); 10503 Glue = RetValue.getValue(2); 10504 10505 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10506 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10507 SDValue RetValue2 = 10508 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10509 Chain = RetValue2.getValue(1); 10510 Glue = RetValue2.getValue(2); 10511 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10512 RetValue2); 10513 } 10514 10515 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10516 10517 InVals.push_back(RetValue); 10518 } 10519 10520 return Chain; 10521 } 10522 10523 bool RISCVTargetLowering::CanLowerReturn( 10524 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10525 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10526 SmallVector<CCValAssign, 16> RVLocs; 10527 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10528 10529 Optional<unsigned> FirstMaskArgument; 10530 if (Subtarget.hasVInstructions()) 10531 FirstMaskArgument = preAssignMask(Outs); 10532 10533 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10534 MVT VT = Outs[i].VT; 10535 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10536 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10537 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10538 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10539 *this, FirstMaskArgument)) 10540 return false; 10541 } 10542 return true; 10543 } 10544 10545 SDValue 10546 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10547 bool IsVarArg, 10548 const SmallVectorImpl<ISD::OutputArg> &Outs, 10549 const SmallVectorImpl<SDValue> &OutVals, 10550 const SDLoc &DL, SelectionDAG &DAG) const { 10551 const MachineFunction &MF = DAG.getMachineFunction(); 10552 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10553 10554 // Stores the assignment of the return value to a location. 10555 SmallVector<CCValAssign, 16> RVLocs; 10556 10557 // Info about the registers and stack slot. 10558 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10559 *DAG.getContext()); 10560 10561 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10562 nullptr, CC_RISCV); 10563 10564 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10565 report_fatal_error("GHC functions return void only"); 10566 10567 SDValue Glue; 10568 SmallVector<SDValue, 4> RetOps(1, Chain); 10569 10570 // Copy the result values into the output registers. 10571 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10572 SDValue Val = OutVals[i]; 10573 CCValAssign &VA = RVLocs[i]; 10574 assert(VA.isRegLoc() && "Can only return in registers!"); 10575 10576 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10577 // Handle returning f64 on RV32D with a soft float ABI. 10578 assert(VA.isRegLoc() && "Expected return via registers"); 10579 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10580 DAG.getVTList(MVT::i32, MVT::i32), Val); 10581 SDValue Lo = SplitF64.getValue(0); 10582 SDValue Hi = SplitF64.getValue(1); 10583 Register RegLo = VA.getLocReg(); 10584 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10585 Register RegHi = RegLo + 1; 10586 10587 if (STI.isRegisterReservedByUser(RegLo) || 10588 STI.isRegisterReservedByUser(RegHi)) 10589 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10590 MF.getFunction(), 10591 "Return value register required, but has been reserved."}); 10592 10593 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10594 Glue = Chain.getValue(1); 10595 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10596 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10597 Glue = Chain.getValue(1); 10598 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10599 } else { 10600 // Handle a 'normal' return. 10601 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10602 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10603 10604 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10605 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10606 MF.getFunction(), 10607 "Return value register required, but has been reserved."}); 10608 10609 // Guarantee that all emitted copies are stuck together. 10610 Glue = Chain.getValue(1); 10611 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10612 } 10613 } 10614 10615 RetOps[0] = Chain; // Update chain. 10616 10617 // Add the glue node if we have it. 10618 if (Glue.getNode()) { 10619 RetOps.push_back(Glue); 10620 } 10621 10622 unsigned RetOpc = RISCVISD::RET_FLAG; 10623 // Interrupt service routines use different return instructions. 10624 const Function &Func = DAG.getMachineFunction().getFunction(); 10625 if (Func.hasFnAttribute("interrupt")) { 10626 if (!Func.getReturnType()->isVoidTy()) 10627 report_fatal_error( 10628 "Functions with the interrupt attribute must have void return type!"); 10629 10630 MachineFunction &MF = DAG.getMachineFunction(); 10631 StringRef Kind = 10632 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10633 10634 if (Kind == "user") 10635 RetOpc = RISCVISD::URET_FLAG; 10636 else if (Kind == "supervisor") 10637 RetOpc = RISCVISD::SRET_FLAG; 10638 else 10639 RetOpc = RISCVISD::MRET_FLAG; 10640 } 10641 10642 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10643 } 10644 10645 void RISCVTargetLowering::validateCCReservedRegs( 10646 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10647 MachineFunction &MF) const { 10648 const Function &F = MF.getFunction(); 10649 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10650 10651 if (llvm::any_of(Regs, [&STI](auto Reg) { 10652 return STI.isRegisterReservedByUser(Reg.first); 10653 })) 10654 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10655 F, "Argument register required, but has been reserved."}); 10656 } 10657 10658 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10659 return CI->isTailCall(); 10660 } 10661 10662 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10663 #define NODE_NAME_CASE(NODE) \ 10664 case RISCVISD::NODE: \ 10665 return "RISCVISD::" #NODE; 10666 // clang-format off 10667 switch ((RISCVISD::NodeType)Opcode) { 10668 case RISCVISD::FIRST_NUMBER: 10669 break; 10670 NODE_NAME_CASE(RET_FLAG) 10671 NODE_NAME_CASE(URET_FLAG) 10672 NODE_NAME_CASE(SRET_FLAG) 10673 NODE_NAME_CASE(MRET_FLAG) 10674 NODE_NAME_CASE(CALL) 10675 NODE_NAME_CASE(SELECT_CC) 10676 NODE_NAME_CASE(BR_CC) 10677 NODE_NAME_CASE(BuildPairF64) 10678 NODE_NAME_CASE(SplitF64) 10679 NODE_NAME_CASE(TAIL) 10680 NODE_NAME_CASE(MULHSU) 10681 NODE_NAME_CASE(SLLW) 10682 NODE_NAME_CASE(SRAW) 10683 NODE_NAME_CASE(SRLW) 10684 NODE_NAME_CASE(DIVW) 10685 NODE_NAME_CASE(DIVUW) 10686 NODE_NAME_CASE(REMUW) 10687 NODE_NAME_CASE(ROLW) 10688 NODE_NAME_CASE(RORW) 10689 NODE_NAME_CASE(CLZW) 10690 NODE_NAME_CASE(CTZW) 10691 NODE_NAME_CASE(FSLW) 10692 NODE_NAME_CASE(FSRW) 10693 NODE_NAME_CASE(FSL) 10694 NODE_NAME_CASE(FSR) 10695 NODE_NAME_CASE(FMV_H_X) 10696 NODE_NAME_CASE(FMV_X_ANYEXTH) 10697 NODE_NAME_CASE(FMV_X_SIGNEXTH) 10698 NODE_NAME_CASE(FMV_W_X_RV64) 10699 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10700 NODE_NAME_CASE(FCVT_X) 10701 NODE_NAME_CASE(FCVT_XU) 10702 NODE_NAME_CASE(FCVT_W_RV64) 10703 NODE_NAME_CASE(FCVT_WU_RV64) 10704 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10705 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10706 NODE_NAME_CASE(READ_CYCLE_WIDE) 10707 NODE_NAME_CASE(GREV) 10708 NODE_NAME_CASE(GREVW) 10709 NODE_NAME_CASE(GORC) 10710 NODE_NAME_CASE(GORCW) 10711 NODE_NAME_CASE(SHFL) 10712 NODE_NAME_CASE(SHFLW) 10713 NODE_NAME_CASE(UNSHFL) 10714 NODE_NAME_CASE(UNSHFLW) 10715 NODE_NAME_CASE(BFP) 10716 NODE_NAME_CASE(BFPW) 10717 NODE_NAME_CASE(BCOMPRESS) 10718 NODE_NAME_CASE(BCOMPRESSW) 10719 NODE_NAME_CASE(BDECOMPRESS) 10720 NODE_NAME_CASE(BDECOMPRESSW) 10721 NODE_NAME_CASE(VMV_V_X_VL) 10722 NODE_NAME_CASE(VFMV_V_F_VL) 10723 NODE_NAME_CASE(VMV_X_S) 10724 NODE_NAME_CASE(VMV_S_X_VL) 10725 NODE_NAME_CASE(VFMV_S_F_VL) 10726 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10727 NODE_NAME_CASE(READ_VLENB) 10728 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10729 NODE_NAME_CASE(VSLIDEUP_VL) 10730 NODE_NAME_CASE(VSLIDE1UP_VL) 10731 NODE_NAME_CASE(VSLIDEDOWN_VL) 10732 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10733 NODE_NAME_CASE(VID_VL) 10734 NODE_NAME_CASE(VFNCVT_ROD_VL) 10735 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10736 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10737 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10738 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10739 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10740 NODE_NAME_CASE(VECREDUCE_AND_VL) 10741 NODE_NAME_CASE(VECREDUCE_OR_VL) 10742 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10743 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10744 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10745 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10746 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10747 NODE_NAME_CASE(ADD_VL) 10748 NODE_NAME_CASE(AND_VL) 10749 NODE_NAME_CASE(MUL_VL) 10750 NODE_NAME_CASE(OR_VL) 10751 NODE_NAME_CASE(SDIV_VL) 10752 NODE_NAME_CASE(SHL_VL) 10753 NODE_NAME_CASE(SREM_VL) 10754 NODE_NAME_CASE(SRA_VL) 10755 NODE_NAME_CASE(SRL_VL) 10756 NODE_NAME_CASE(SUB_VL) 10757 NODE_NAME_CASE(UDIV_VL) 10758 NODE_NAME_CASE(UREM_VL) 10759 NODE_NAME_CASE(XOR_VL) 10760 NODE_NAME_CASE(SADDSAT_VL) 10761 NODE_NAME_CASE(UADDSAT_VL) 10762 NODE_NAME_CASE(SSUBSAT_VL) 10763 NODE_NAME_CASE(USUBSAT_VL) 10764 NODE_NAME_CASE(FADD_VL) 10765 NODE_NAME_CASE(FSUB_VL) 10766 NODE_NAME_CASE(FMUL_VL) 10767 NODE_NAME_CASE(FDIV_VL) 10768 NODE_NAME_CASE(FNEG_VL) 10769 NODE_NAME_CASE(FABS_VL) 10770 NODE_NAME_CASE(FSQRT_VL) 10771 NODE_NAME_CASE(FMA_VL) 10772 NODE_NAME_CASE(FCOPYSIGN_VL) 10773 NODE_NAME_CASE(SMIN_VL) 10774 NODE_NAME_CASE(SMAX_VL) 10775 NODE_NAME_CASE(UMIN_VL) 10776 NODE_NAME_CASE(UMAX_VL) 10777 NODE_NAME_CASE(FMINNUM_VL) 10778 NODE_NAME_CASE(FMAXNUM_VL) 10779 NODE_NAME_CASE(MULHS_VL) 10780 NODE_NAME_CASE(MULHU_VL) 10781 NODE_NAME_CASE(FP_TO_SINT_VL) 10782 NODE_NAME_CASE(FP_TO_UINT_VL) 10783 NODE_NAME_CASE(SINT_TO_FP_VL) 10784 NODE_NAME_CASE(UINT_TO_FP_VL) 10785 NODE_NAME_CASE(FP_EXTEND_VL) 10786 NODE_NAME_CASE(FP_ROUND_VL) 10787 NODE_NAME_CASE(VWMUL_VL) 10788 NODE_NAME_CASE(VWMULU_VL) 10789 NODE_NAME_CASE(VWMULSU_VL) 10790 NODE_NAME_CASE(VWADD_VL) 10791 NODE_NAME_CASE(VWADDU_VL) 10792 NODE_NAME_CASE(VWSUB_VL) 10793 NODE_NAME_CASE(VWSUBU_VL) 10794 NODE_NAME_CASE(VWADD_W_VL) 10795 NODE_NAME_CASE(VWADDU_W_VL) 10796 NODE_NAME_CASE(VWSUB_W_VL) 10797 NODE_NAME_CASE(VWSUBU_W_VL) 10798 NODE_NAME_CASE(SETCC_VL) 10799 NODE_NAME_CASE(VSELECT_VL) 10800 NODE_NAME_CASE(VP_MERGE_VL) 10801 NODE_NAME_CASE(VMAND_VL) 10802 NODE_NAME_CASE(VMOR_VL) 10803 NODE_NAME_CASE(VMXOR_VL) 10804 NODE_NAME_CASE(VMCLR_VL) 10805 NODE_NAME_CASE(VMSET_VL) 10806 NODE_NAME_CASE(VRGATHER_VX_VL) 10807 NODE_NAME_CASE(VRGATHER_VV_VL) 10808 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10809 NODE_NAME_CASE(VSEXT_VL) 10810 NODE_NAME_CASE(VZEXT_VL) 10811 NODE_NAME_CASE(VCPOP_VL) 10812 NODE_NAME_CASE(READ_CSR) 10813 NODE_NAME_CASE(WRITE_CSR) 10814 NODE_NAME_CASE(SWAP_CSR) 10815 } 10816 // clang-format on 10817 return nullptr; 10818 #undef NODE_NAME_CASE 10819 } 10820 10821 /// getConstraintType - Given a constraint letter, return the type of 10822 /// constraint it is for this target. 10823 RISCVTargetLowering::ConstraintType 10824 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 10825 if (Constraint.size() == 1) { 10826 switch (Constraint[0]) { 10827 default: 10828 break; 10829 case 'f': 10830 return C_RegisterClass; 10831 case 'I': 10832 case 'J': 10833 case 'K': 10834 return C_Immediate; 10835 case 'A': 10836 return C_Memory; 10837 case 'S': // A symbolic address 10838 return C_Other; 10839 } 10840 } else { 10841 if (Constraint == "vr" || Constraint == "vm") 10842 return C_RegisterClass; 10843 } 10844 return TargetLowering::getConstraintType(Constraint); 10845 } 10846 10847 std::pair<unsigned, const TargetRegisterClass *> 10848 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10849 StringRef Constraint, 10850 MVT VT) const { 10851 // First, see if this is a constraint that directly corresponds to a 10852 // RISCV register class. 10853 if (Constraint.size() == 1) { 10854 switch (Constraint[0]) { 10855 case 'r': 10856 // TODO: Support fixed vectors up to XLen for P extension? 10857 if (VT.isVector()) 10858 break; 10859 return std::make_pair(0U, &RISCV::GPRRegClass); 10860 case 'f': 10861 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 10862 return std::make_pair(0U, &RISCV::FPR16RegClass); 10863 if (Subtarget.hasStdExtF() && VT == MVT::f32) 10864 return std::make_pair(0U, &RISCV::FPR32RegClass); 10865 if (Subtarget.hasStdExtD() && VT == MVT::f64) 10866 return std::make_pair(0U, &RISCV::FPR64RegClass); 10867 break; 10868 default: 10869 break; 10870 } 10871 } else if (Constraint == "vr") { 10872 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 10873 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10874 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 10875 return std::make_pair(0U, RC); 10876 } 10877 } else if (Constraint == "vm") { 10878 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 10879 return std::make_pair(0U, &RISCV::VMV0RegClass); 10880 } 10881 10882 // Clang will correctly decode the usage of register name aliases into their 10883 // official names. However, other frontends like `rustc` do not. This allows 10884 // users of these frontends to use the ABI names for registers in LLVM-style 10885 // register constraints. 10886 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 10887 .Case("{zero}", RISCV::X0) 10888 .Case("{ra}", RISCV::X1) 10889 .Case("{sp}", RISCV::X2) 10890 .Case("{gp}", RISCV::X3) 10891 .Case("{tp}", RISCV::X4) 10892 .Case("{t0}", RISCV::X5) 10893 .Case("{t1}", RISCV::X6) 10894 .Case("{t2}", RISCV::X7) 10895 .Cases("{s0}", "{fp}", RISCV::X8) 10896 .Case("{s1}", RISCV::X9) 10897 .Case("{a0}", RISCV::X10) 10898 .Case("{a1}", RISCV::X11) 10899 .Case("{a2}", RISCV::X12) 10900 .Case("{a3}", RISCV::X13) 10901 .Case("{a4}", RISCV::X14) 10902 .Case("{a5}", RISCV::X15) 10903 .Case("{a6}", RISCV::X16) 10904 .Case("{a7}", RISCV::X17) 10905 .Case("{s2}", RISCV::X18) 10906 .Case("{s3}", RISCV::X19) 10907 .Case("{s4}", RISCV::X20) 10908 .Case("{s5}", RISCV::X21) 10909 .Case("{s6}", RISCV::X22) 10910 .Case("{s7}", RISCV::X23) 10911 .Case("{s8}", RISCV::X24) 10912 .Case("{s9}", RISCV::X25) 10913 .Case("{s10}", RISCV::X26) 10914 .Case("{s11}", RISCV::X27) 10915 .Case("{t3}", RISCV::X28) 10916 .Case("{t4}", RISCV::X29) 10917 .Case("{t5}", RISCV::X30) 10918 .Case("{t6}", RISCV::X31) 10919 .Default(RISCV::NoRegister); 10920 if (XRegFromAlias != RISCV::NoRegister) 10921 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 10922 10923 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 10924 // TableGen record rather than the AsmName to choose registers for InlineAsm 10925 // constraints, plus we want to match those names to the widest floating point 10926 // register type available, manually select floating point registers here. 10927 // 10928 // The second case is the ABI name of the register, so that frontends can also 10929 // use the ABI names in register constraint lists. 10930 if (Subtarget.hasStdExtF()) { 10931 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 10932 .Cases("{f0}", "{ft0}", RISCV::F0_F) 10933 .Cases("{f1}", "{ft1}", RISCV::F1_F) 10934 .Cases("{f2}", "{ft2}", RISCV::F2_F) 10935 .Cases("{f3}", "{ft3}", RISCV::F3_F) 10936 .Cases("{f4}", "{ft4}", RISCV::F4_F) 10937 .Cases("{f5}", "{ft5}", RISCV::F5_F) 10938 .Cases("{f6}", "{ft6}", RISCV::F6_F) 10939 .Cases("{f7}", "{ft7}", RISCV::F7_F) 10940 .Cases("{f8}", "{fs0}", RISCV::F8_F) 10941 .Cases("{f9}", "{fs1}", RISCV::F9_F) 10942 .Cases("{f10}", "{fa0}", RISCV::F10_F) 10943 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10944 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10945 .Cases("{f13}", "{fa3}", RISCV::F13_F) 10946 .Cases("{f14}", "{fa4}", RISCV::F14_F) 10947 .Cases("{f15}", "{fa5}", RISCV::F15_F) 10948 .Cases("{f16}", "{fa6}", RISCV::F16_F) 10949 .Cases("{f17}", "{fa7}", RISCV::F17_F) 10950 .Cases("{f18}", "{fs2}", RISCV::F18_F) 10951 .Cases("{f19}", "{fs3}", RISCV::F19_F) 10952 .Cases("{f20}", "{fs4}", RISCV::F20_F) 10953 .Cases("{f21}", "{fs5}", RISCV::F21_F) 10954 .Cases("{f22}", "{fs6}", RISCV::F22_F) 10955 .Cases("{f23}", "{fs7}", RISCV::F23_F) 10956 .Cases("{f24}", "{fs8}", RISCV::F24_F) 10957 .Cases("{f25}", "{fs9}", RISCV::F25_F) 10958 .Cases("{f26}", "{fs10}", RISCV::F26_F) 10959 .Cases("{f27}", "{fs11}", RISCV::F27_F) 10960 .Cases("{f28}", "{ft8}", RISCV::F28_F) 10961 .Cases("{f29}", "{ft9}", RISCV::F29_F) 10962 .Cases("{f30}", "{ft10}", RISCV::F30_F) 10963 .Cases("{f31}", "{ft11}", RISCV::F31_F) 10964 .Default(RISCV::NoRegister); 10965 if (FReg != RISCV::NoRegister) { 10966 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 10967 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 10968 unsigned RegNo = FReg - RISCV::F0_F; 10969 unsigned DReg = RISCV::F0_D + RegNo; 10970 return std::make_pair(DReg, &RISCV::FPR64RegClass); 10971 } 10972 if (VT == MVT::f32 || VT == MVT::Other) 10973 return std::make_pair(FReg, &RISCV::FPR32RegClass); 10974 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 10975 unsigned RegNo = FReg - RISCV::F0_F; 10976 unsigned HReg = RISCV::F0_H + RegNo; 10977 return std::make_pair(HReg, &RISCV::FPR16RegClass); 10978 } 10979 } 10980 } 10981 10982 if (Subtarget.hasVInstructions()) { 10983 Register VReg = StringSwitch<Register>(Constraint.lower()) 10984 .Case("{v0}", RISCV::V0) 10985 .Case("{v1}", RISCV::V1) 10986 .Case("{v2}", RISCV::V2) 10987 .Case("{v3}", RISCV::V3) 10988 .Case("{v4}", RISCV::V4) 10989 .Case("{v5}", RISCV::V5) 10990 .Case("{v6}", RISCV::V6) 10991 .Case("{v7}", RISCV::V7) 10992 .Case("{v8}", RISCV::V8) 10993 .Case("{v9}", RISCV::V9) 10994 .Case("{v10}", RISCV::V10) 10995 .Case("{v11}", RISCV::V11) 10996 .Case("{v12}", RISCV::V12) 10997 .Case("{v13}", RISCV::V13) 10998 .Case("{v14}", RISCV::V14) 10999 .Case("{v15}", RISCV::V15) 11000 .Case("{v16}", RISCV::V16) 11001 .Case("{v17}", RISCV::V17) 11002 .Case("{v18}", RISCV::V18) 11003 .Case("{v19}", RISCV::V19) 11004 .Case("{v20}", RISCV::V20) 11005 .Case("{v21}", RISCV::V21) 11006 .Case("{v22}", RISCV::V22) 11007 .Case("{v23}", RISCV::V23) 11008 .Case("{v24}", RISCV::V24) 11009 .Case("{v25}", RISCV::V25) 11010 .Case("{v26}", RISCV::V26) 11011 .Case("{v27}", RISCV::V27) 11012 .Case("{v28}", RISCV::V28) 11013 .Case("{v29}", RISCV::V29) 11014 .Case("{v30}", RISCV::V30) 11015 .Case("{v31}", RISCV::V31) 11016 .Default(RISCV::NoRegister); 11017 if (VReg != RISCV::NoRegister) { 11018 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11019 return std::make_pair(VReg, &RISCV::VMRegClass); 11020 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11021 return std::make_pair(VReg, &RISCV::VRRegClass); 11022 for (const auto *RC : 11023 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11024 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11025 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11026 return std::make_pair(VReg, RC); 11027 } 11028 } 11029 } 11030 } 11031 11032 std::pair<Register, const TargetRegisterClass *> Res = 11033 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11034 11035 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11036 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11037 // Subtarget into account. 11038 if (Res.second == &RISCV::GPRF16RegClass || 11039 Res.second == &RISCV::GPRF32RegClass || 11040 Res.second == &RISCV::GPRF64RegClass) 11041 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11042 11043 return Res; 11044 } 11045 11046 unsigned 11047 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11048 // Currently only support length 1 constraints. 11049 if (ConstraintCode.size() == 1) { 11050 switch (ConstraintCode[0]) { 11051 case 'A': 11052 return InlineAsm::Constraint_A; 11053 default: 11054 break; 11055 } 11056 } 11057 11058 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11059 } 11060 11061 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11062 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11063 SelectionDAG &DAG) const { 11064 // Currently only support length 1 constraints. 11065 if (Constraint.length() == 1) { 11066 switch (Constraint[0]) { 11067 case 'I': 11068 // Validate & create a 12-bit signed immediate operand. 11069 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11070 uint64_t CVal = C->getSExtValue(); 11071 if (isInt<12>(CVal)) 11072 Ops.push_back( 11073 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11074 } 11075 return; 11076 case 'J': 11077 // Validate & create an integer zero operand. 11078 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11079 if (C->getZExtValue() == 0) 11080 Ops.push_back( 11081 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11082 return; 11083 case 'K': 11084 // Validate & create a 5-bit unsigned immediate operand. 11085 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11086 uint64_t CVal = C->getZExtValue(); 11087 if (isUInt<5>(CVal)) 11088 Ops.push_back( 11089 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11090 } 11091 return; 11092 case 'S': 11093 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11094 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11095 GA->getValueType(0))); 11096 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11097 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11098 BA->getValueType(0))); 11099 } 11100 return; 11101 default: 11102 break; 11103 } 11104 } 11105 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11106 } 11107 11108 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11109 Instruction *Inst, 11110 AtomicOrdering Ord) const { 11111 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11112 return Builder.CreateFence(Ord); 11113 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11114 return Builder.CreateFence(AtomicOrdering::Release); 11115 return nullptr; 11116 } 11117 11118 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11119 Instruction *Inst, 11120 AtomicOrdering Ord) const { 11121 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11122 return Builder.CreateFence(AtomicOrdering::Acquire); 11123 return nullptr; 11124 } 11125 11126 TargetLowering::AtomicExpansionKind 11127 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11128 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11129 // point operations can't be used in an lr/sc sequence without breaking the 11130 // forward-progress guarantee. 11131 if (AI->isFloatingPointOperation()) 11132 return AtomicExpansionKind::CmpXChg; 11133 11134 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11135 if (Size == 8 || Size == 16) 11136 return AtomicExpansionKind::MaskedIntrinsic; 11137 return AtomicExpansionKind::None; 11138 } 11139 11140 static Intrinsic::ID 11141 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11142 if (XLen == 32) { 11143 switch (BinOp) { 11144 default: 11145 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11146 case AtomicRMWInst::Xchg: 11147 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11148 case AtomicRMWInst::Add: 11149 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11150 case AtomicRMWInst::Sub: 11151 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11152 case AtomicRMWInst::Nand: 11153 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11154 case AtomicRMWInst::Max: 11155 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11156 case AtomicRMWInst::Min: 11157 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11158 case AtomicRMWInst::UMax: 11159 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11160 case AtomicRMWInst::UMin: 11161 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11162 } 11163 } 11164 11165 if (XLen == 64) { 11166 switch (BinOp) { 11167 default: 11168 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11169 case AtomicRMWInst::Xchg: 11170 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11171 case AtomicRMWInst::Add: 11172 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11173 case AtomicRMWInst::Sub: 11174 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11175 case AtomicRMWInst::Nand: 11176 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11177 case AtomicRMWInst::Max: 11178 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11179 case AtomicRMWInst::Min: 11180 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11181 case AtomicRMWInst::UMax: 11182 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11183 case AtomicRMWInst::UMin: 11184 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11185 } 11186 } 11187 11188 llvm_unreachable("Unexpected XLen\n"); 11189 } 11190 11191 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11192 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11193 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11194 unsigned XLen = Subtarget.getXLen(); 11195 Value *Ordering = 11196 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11197 Type *Tys[] = {AlignedAddr->getType()}; 11198 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11199 AI->getModule(), 11200 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11201 11202 if (XLen == 64) { 11203 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11204 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11205 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11206 } 11207 11208 Value *Result; 11209 11210 // Must pass the shift amount needed to sign extend the loaded value prior 11211 // to performing a signed comparison for min/max. ShiftAmt is the number of 11212 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11213 // is the number of bits to left+right shift the value in order to 11214 // sign-extend. 11215 if (AI->getOperation() == AtomicRMWInst::Min || 11216 AI->getOperation() == AtomicRMWInst::Max) { 11217 const DataLayout &DL = AI->getModule()->getDataLayout(); 11218 unsigned ValWidth = 11219 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11220 Value *SextShamt = 11221 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11222 Result = Builder.CreateCall(LrwOpScwLoop, 11223 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11224 } else { 11225 Result = 11226 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11227 } 11228 11229 if (XLen == 64) 11230 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11231 return Result; 11232 } 11233 11234 TargetLowering::AtomicExpansionKind 11235 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11236 AtomicCmpXchgInst *CI) const { 11237 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11238 if (Size == 8 || Size == 16) 11239 return AtomicExpansionKind::MaskedIntrinsic; 11240 return AtomicExpansionKind::None; 11241 } 11242 11243 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11244 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11245 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11246 unsigned XLen = Subtarget.getXLen(); 11247 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11248 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11249 if (XLen == 64) { 11250 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11251 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11252 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11253 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11254 } 11255 Type *Tys[] = {AlignedAddr->getType()}; 11256 Function *MaskedCmpXchg = 11257 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11258 Value *Result = Builder.CreateCall( 11259 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11260 if (XLen == 64) 11261 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11262 return Result; 11263 } 11264 11265 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11266 return false; 11267 } 11268 11269 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11270 EVT VT) const { 11271 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11272 return false; 11273 11274 switch (FPVT.getSimpleVT().SimpleTy) { 11275 case MVT::f16: 11276 return Subtarget.hasStdExtZfh(); 11277 case MVT::f32: 11278 return Subtarget.hasStdExtF(); 11279 case MVT::f64: 11280 return Subtarget.hasStdExtD(); 11281 default: 11282 return false; 11283 } 11284 } 11285 11286 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11287 // If we are using the small code model, we can reduce size of jump table 11288 // entry to 4 bytes. 11289 if (Subtarget.is64Bit() && !isPositionIndependent() && 11290 getTargetMachine().getCodeModel() == CodeModel::Small) { 11291 return MachineJumpTableInfo::EK_Custom32; 11292 } 11293 return TargetLowering::getJumpTableEncoding(); 11294 } 11295 11296 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11297 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11298 unsigned uid, MCContext &Ctx) const { 11299 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11300 getTargetMachine().getCodeModel() == CodeModel::Small); 11301 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11302 } 11303 11304 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11305 EVT VT) const { 11306 VT = VT.getScalarType(); 11307 11308 if (!VT.isSimple()) 11309 return false; 11310 11311 switch (VT.getSimpleVT().SimpleTy) { 11312 case MVT::f16: 11313 return Subtarget.hasStdExtZfh(); 11314 case MVT::f32: 11315 return Subtarget.hasStdExtF(); 11316 case MVT::f64: 11317 return Subtarget.hasStdExtD(); 11318 default: 11319 break; 11320 } 11321 11322 return false; 11323 } 11324 11325 Register RISCVTargetLowering::getExceptionPointerRegister( 11326 const Constant *PersonalityFn) const { 11327 return RISCV::X10; 11328 } 11329 11330 Register RISCVTargetLowering::getExceptionSelectorRegister( 11331 const Constant *PersonalityFn) const { 11332 return RISCV::X11; 11333 } 11334 11335 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11336 // Return false to suppress the unnecessary extensions if the LibCall 11337 // arguments or return value is f32 type for LP64 ABI. 11338 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11339 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11340 return false; 11341 11342 return true; 11343 } 11344 11345 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11346 if (Subtarget.is64Bit() && Type == MVT::i32) 11347 return true; 11348 11349 return IsSigned; 11350 } 11351 11352 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11353 SDValue C) const { 11354 // Check integral scalar types. 11355 if (VT.isScalarInteger()) { 11356 // Omit the optimization if the sub target has the M extension and the data 11357 // size exceeds XLen. 11358 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11359 return false; 11360 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11361 // Break the MUL to a SLLI and an ADD/SUB. 11362 const APInt &Imm = ConstNode->getAPIntValue(); 11363 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11364 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11365 return true; 11366 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11367 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11368 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11369 (Imm - 8).isPowerOf2())) 11370 return true; 11371 // Omit the following optimization if the sub target has the M extension 11372 // and the data size >= XLen. 11373 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11374 return false; 11375 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11376 // a pair of LUI/ADDI. 11377 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11378 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11379 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11380 (1 - ImmS).isPowerOf2()) 11381 return true; 11382 } 11383 } 11384 } 11385 11386 return false; 11387 } 11388 11389 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11390 SDValue ConstNode) const { 11391 // Let the DAGCombiner decide for vectors. 11392 EVT VT = AddNode.getValueType(); 11393 if (VT.isVector()) 11394 return true; 11395 11396 // Let the DAGCombiner decide for larger types. 11397 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11398 return true; 11399 11400 // It is worse if c1 is simm12 while c1*c2 is not. 11401 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11402 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11403 const APInt &C1 = C1Node->getAPIntValue(); 11404 const APInt &C2 = C2Node->getAPIntValue(); 11405 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11406 return false; 11407 11408 // Default to true and let the DAGCombiner decide. 11409 return true; 11410 } 11411 11412 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11413 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11414 bool *Fast) const { 11415 if (!VT.isVector()) 11416 return false; 11417 11418 EVT ElemVT = VT.getVectorElementType(); 11419 if (Alignment >= ElemVT.getStoreSize()) { 11420 if (Fast) 11421 *Fast = true; 11422 return true; 11423 } 11424 11425 return false; 11426 } 11427 11428 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11429 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11430 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11431 bool IsABIRegCopy = CC.hasValue(); 11432 EVT ValueVT = Val.getValueType(); 11433 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11434 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11435 // and cast to f32. 11436 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11437 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11438 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11439 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11440 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11441 Parts[0] = Val; 11442 return true; 11443 } 11444 11445 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11446 LLVMContext &Context = *DAG.getContext(); 11447 EVT ValueEltVT = ValueVT.getVectorElementType(); 11448 EVT PartEltVT = PartVT.getVectorElementType(); 11449 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11450 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11451 if (PartVTBitSize % ValueVTBitSize == 0) { 11452 assert(PartVTBitSize >= ValueVTBitSize); 11453 // If the element types are different, bitcast to the same element type of 11454 // PartVT first. 11455 // Give an example here, we want copy a <vscale x 1 x i8> value to 11456 // <vscale x 4 x i16>. 11457 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11458 // subvector, then we can bitcast to <vscale x 4 x i16>. 11459 if (ValueEltVT != PartEltVT) { 11460 if (PartVTBitSize > ValueVTBitSize) { 11461 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11462 assert(Count != 0 && "The number of element should not be zero."); 11463 EVT SameEltTypeVT = 11464 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11465 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11466 DAG.getUNDEF(SameEltTypeVT), Val, 11467 DAG.getVectorIdxConstant(0, DL)); 11468 } 11469 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11470 } else { 11471 Val = 11472 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11473 Val, DAG.getVectorIdxConstant(0, DL)); 11474 } 11475 Parts[0] = Val; 11476 return true; 11477 } 11478 } 11479 return false; 11480 } 11481 11482 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11483 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11484 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11485 bool IsABIRegCopy = CC.hasValue(); 11486 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11487 SDValue Val = Parts[0]; 11488 11489 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11490 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11491 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11492 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11493 return Val; 11494 } 11495 11496 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11497 LLVMContext &Context = *DAG.getContext(); 11498 SDValue Val = Parts[0]; 11499 EVT ValueEltVT = ValueVT.getVectorElementType(); 11500 EVT PartEltVT = PartVT.getVectorElementType(); 11501 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11502 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11503 if (PartVTBitSize % ValueVTBitSize == 0) { 11504 assert(PartVTBitSize >= ValueVTBitSize); 11505 EVT SameEltTypeVT = ValueVT; 11506 // If the element types are different, convert it to the same element type 11507 // of PartVT. 11508 // Give an example here, we want copy a <vscale x 1 x i8> value from 11509 // <vscale x 4 x i16>. 11510 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11511 // then we can extract <vscale x 1 x i8>. 11512 if (ValueEltVT != PartEltVT) { 11513 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11514 assert(Count != 0 && "The number of element should not be zero."); 11515 SameEltTypeVT = 11516 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11517 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11518 } 11519 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11520 DAG.getVectorIdxConstant(0, DL)); 11521 return Val; 11522 } 11523 } 11524 return SDValue(); 11525 } 11526 11527 SDValue 11528 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11529 SelectionDAG &DAG, 11530 SmallVectorImpl<SDNode *> &Created) const { 11531 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11532 if (isIntDivCheap(N->getValueType(0), Attr)) 11533 return SDValue(N, 0); // Lower SDIV as SDIV 11534 11535 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11536 "Unexpected divisor!"); 11537 11538 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11539 if (!Subtarget.hasStdExtZbt()) 11540 return SDValue(); 11541 11542 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11543 // Besides, more critical path instructions will be generated when dividing 11544 // by 2. So we keep using the original DAGs for these cases. 11545 unsigned Lg2 = Divisor.countTrailingZeros(); 11546 if (Lg2 == 1 || Lg2 >= 12) 11547 return SDValue(); 11548 11549 // fold (sdiv X, pow2) 11550 EVT VT = N->getValueType(0); 11551 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11552 return SDValue(); 11553 11554 SDLoc DL(N); 11555 SDValue N0 = N->getOperand(0); 11556 SDValue Zero = DAG.getConstant(0, DL, VT); 11557 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11558 11559 // Add (N0 < 0) ? Pow2 - 1 : 0; 11560 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11561 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11562 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11563 11564 Created.push_back(Cmp.getNode()); 11565 Created.push_back(Add.getNode()); 11566 Created.push_back(Sel.getNode()); 11567 11568 // Divide by pow2. 11569 SDValue SRA = 11570 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11571 11572 // If we're dividing by a positive value, we're done. Otherwise, we must 11573 // negate the result. 11574 if (Divisor.isNonNegative()) 11575 return SRA; 11576 11577 Created.push_back(SRA.getNode()); 11578 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11579 } 11580 11581 #define GET_REGISTER_MATCHER 11582 #include "RISCVGenAsmMatcher.inc" 11583 11584 Register 11585 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11586 const MachineFunction &MF) const { 11587 Register Reg = MatchRegisterAltName(RegName); 11588 if (Reg == RISCV::NoRegister) 11589 Reg = MatchRegisterName(RegName); 11590 if (Reg == RISCV::NoRegister) 11591 report_fatal_error( 11592 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11593 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11594 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11595 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11596 StringRef(RegName) + "\".")); 11597 return Reg; 11598 } 11599 11600 namespace llvm { 11601 namespace RISCVVIntrinsicsTable { 11602 11603 #define GET_RISCVVIntrinsicsTable_IMPL 11604 #include "RISCVGenSearchableTables.inc" 11605 11606 } // namespace RISCVVIntrinsicsTable 11607 11608 } // namespace llvm 11609