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/MachineRegisterInfo.h" 28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 29 #include "llvm/CodeGen/ValueTypes.h" 30 #include "llvm/IR/DiagnosticInfo.h" 31 #include "llvm/IR/DiagnosticPrinter.h" 32 #include "llvm/IR/IRBuilder.h" 33 #include "llvm/IR/IntrinsicsRISCV.h" 34 #include "llvm/IR/PatternMatch.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/KnownBits.h" 38 #include "llvm/Support/MathExtras.h" 39 #include "llvm/Support/raw_ostream.h" 40 41 using namespace llvm; 42 43 #define DEBUG_TYPE "riscv-lower" 44 45 STATISTIC(NumTailCalls, "Number of tail calls"); 46 47 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 48 const RISCVSubtarget &STI) 49 : TargetLowering(TM), Subtarget(STI) { 50 51 if (Subtarget.isRV32E()) 52 report_fatal_error("Codegen not yet implemented for RV32E"); 53 54 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 55 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 56 57 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 58 !Subtarget.hasStdExtF()) { 59 errs() << "Hard-float 'f' ABI can't be used for a target that " 60 "doesn't support the F instruction set extension (ignoring " 61 "target-abi)\n"; 62 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 63 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 64 !Subtarget.hasStdExtD()) { 65 errs() << "Hard-float 'd' ABI can't be used for a target that " 66 "doesn't support the D instruction set extension (ignoring " 67 "target-abi)\n"; 68 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 69 } 70 71 switch (ABI) { 72 default: 73 report_fatal_error("Don't know how to lower this ABI"); 74 case RISCVABI::ABI_ILP32: 75 case RISCVABI::ABI_ILP32F: 76 case RISCVABI::ABI_ILP32D: 77 case RISCVABI::ABI_LP64: 78 case RISCVABI::ABI_LP64F: 79 case RISCVABI::ABI_LP64D: 80 break; 81 } 82 83 MVT XLenVT = Subtarget.getXLenVT(); 84 85 // Set up the register classes. 86 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 87 88 if (Subtarget.hasStdExtZfh()) 89 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 90 if (Subtarget.hasStdExtF()) 91 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 92 if (Subtarget.hasStdExtD()) 93 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 94 95 static const MVT::SimpleValueType BoolVecVTs[] = { 96 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 97 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 98 static const MVT::SimpleValueType IntVecVTs[] = { 99 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 100 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 101 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 102 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 103 MVT::nxv4i64, MVT::nxv8i64}; 104 static const MVT::SimpleValueType F16VecVTs[] = { 105 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 106 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 107 static const MVT::SimpleValueType F32VecVTs[] = { 108 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 109 static const MVT::SimpleValueType F64VecVTs[] = { 110 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 111 112 if (Subtarget.hasVInstructions()) { 113 auto addRegClassForRVV = [this](MVT VT) { 114 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 115 assert(Size <= 512 && isPowerOf2_32(Size)); 116 const TargetRegisterClass *RC; 117 if (Size <= 64) 118 RC = &RISCV::VRRegClass; 119 else if (Size == 128) 120 RC = &RISCV::VRM2RegClass; 121 else if (Size == 256) 122 RC = &RISCV::VRM4RegClass; 123 else 124 RC = &RISCV::VRM8RegClass; 125 126 addRegisterClass(VT, RC); 127 }; 128 129 for (MVT VT : BoolVecVTs) 130 addRegClassForRVV(VT); 131 for (MVT VT : IntVecVTs) { 132 if (VT.getVectorElementType() == MVT::i64 && 133 !Subtarget.hasVInstructionsI64()) 134 continue; 135 addRegClassForRVV(VT); 136 } 137 138 if (Subtarget.hasVInstructionsF16()) 139 for (MVT VT : F16VecVTs) 140 addRegClassForRVV(VT); 141 142 if (Subtarget.hasVInstructionsF32()) 143 for (MVT VT : F32VecVTs) 144 addRegClassForRVV(VT); 145 146 if (Subtarget.hasVInstructionsF64()) 147 for (MVT VT : F64VecVTs) 148 addRegClassForRVV(VT); 149 150 if (Subtarget.useRVVForFixedLengthVectors()) { 151 auto addRegClassForFixedVectors = [this](MVT VT) { 152 MVT ContainerVT = getContainerForFixedLengthVector(VT); 153 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 154 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 155 addRegisterClass(VT, TRI.getRegClass(RCID)); 156 }; 157 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 158 if (useRVVForFixedLengthVectorVT(VT)) 159 addRegClassForFixedVectors(VT); 160 161 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 162 if (useRVVForFixedLengthVectorVT(VT)) 163 addRegClassForFixedVectors(VT); 164 } 165 } 166 167 // Compute derived properties from the register classes. 168 computeRegisterProperties(STI.getRegisterInfo()); 169 170 setStackPointerRegisterToSaveRestore(RISCV::X2); 171 172 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 173 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 174 175 // TODO: add all necessary setOperationAction calls. 176 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 177 178 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 179 setOperationAction(ISD::BR_CC, XLenVT, Expand); 180 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 181 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 182 183 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 184 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 185 186 setOperationAction(ISD::VASTART, MVT::Other, Custom); 187 setOperationAction(ISD::VAARG, MVT::Other, Expand); 188 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 189 setOperationAction(ISD::VAEND, MVT::Other, Expand); 190 191 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 192 if (!Subtarget.hasStdExtZbb()) { 193 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 195 } 196 197 if (Subtarget.is64Bit()) { 198 setOperationAction(ISD::ADD, MVT::i32, Custom); 199 setOperationAction(ISD::SUB, MVT::i32, Custom); 200 setOperationAction(ISD::SHL, MVT::i32, Custom); 201 setOperationAction(ISD::SRA, MVT::i32, Custom); 202 setOperationAction(ISD::SRL, MVT::i32, Custom); 203 204 setOperationAction(ISD::UADDO, MVT::i32, Custom); 205 setOperationAction(ISD::USUBO, MVT::i32, Custom); 206 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 207 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 208 } else { 209 setLibcallName(RTLIB::SHL_I128, nullptr); 210 setLibcallName(RTLIB::SRL_I128, nullptr); 211 setLibcallName(RTLIB::SRA_I128, nullptr); 212 setLibcallName(RTLIB::MUL_I128, nullptr); 213 setLibcallName(RTLIB::MULO_I64, nullptr); 214 } 215 216 if (!Subtarget.hasStdExtM()) { 217 setOperationAction(ISD::MUL, XLenVT, Expand); 218 setOperationAction(ISD::MULHS, XLenVT, Expand); 219 setOperationAction(ISD::MULHU, XLenVT, Expand); 220 setOperationAction(ISD::SDIV, XLenVT, Expand); 221 setOperationAction(ISD::UDIV, XLenVT, Expand); 222 setOperationAction(ISD::SREM, XLenVT, Expand); 223 setOperationAction(ISD::UREM, XLenVT, Expand); 224 } else { 225 if (Subtarget.is64Bit()) { 226 setOperationAction(ISD::MUL, MVT::i32, Custom); 227 setOperationAction(ISD::MUL, MVT::i128, Custom); 228 229 setOperationAction(ISD::SDIV, MVT::i8, Custom); 230 setOperationAction(ISD::UDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UREM, MVT::i8, Custom); 232 setOperationAction(ISD::SDIV, MVT::i16, Custom); 233 setOperationAction(ISD::UDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UREM, MVT::i16, Custom); 235 setOperationAction(ISD::SDIV, MVT::i32, Custom); 236 setOperationAction(ISD::UDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UREM, MVT::i32, Custom); 238 } else { 239 setOperationAction(ISD::MUL, MVT::i64, Custom); 240 } 241 } 242 243 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 244 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 246 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 247 248 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 249 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 251 252 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 253 if (Subtarget.is64Bit()) { 254 setOperationAction(ISD::ROTL, MVT::i32, Custom); 255 setOperationAction(ISD::ROTR, MVT::i32, Custom); 256 } 257 } else { 258 setOperationAction(ISD::ROTL, XLenVT, Expand); 259 setOperationAction(ISD::ROTR, XLenVT, Expand); 260 } 261 262 if (Subtarget.hasStdExtZbp()) { 263 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 264 // more combining. 265 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 266 setOperationAction(ISD::BSWAP, XLenVT, Custom); 267 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 268 // BSWAP i8 doesn't exist. 269 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 270 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 271 272 if (Subtarget.is64Bit()) { 273 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 274 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 275 } 276 } else { 277 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 278 // pattern match it directly in isel. 279 setOperationAction(ISD::BSWAP, XLenVT, 280 Subtarget.hasStdExtZbb() ? Legal : Expand); 281 } 282 283 if (Subtarget.hasStdExtZbb()) { 284 setOperationAction(ISD::SMIN, XLenVT, Legal); 285 setOperationAction(ISD::SMAX, XLenVT, Legal); 286 setOperationAction(ISD::UMIN, XLenVT, Legal); 287 setOperationAction(ISD::UMAX, XLenVT, Legal); 288 289 if (Subtarget.is64Bit()) { 290 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 291 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 292 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 293 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 294 } 295 } else { 296 setOperationAction(ISD::CTTZ, XLenVT, Expand); 297 setOperationAction(ISD::CTLZ, XLenVT, Expand); 298 setOperationAction(ISD::CTPOP, XLenVT, Expand); 299 } 300 301 if (Subtarget.hasStdExtZbt()) { 302 setOperationAction(ISD::FSHL, XLenVT, Custom); 303 setOperationAction(ISD::FSHR, XLenVT, Custom); 304 setOperationAction(ISD::SELECT, XLenVT, Legal); 305 306 if (Subtarget.is64Bit()) { 307 setOperationAction(ISD::FSHL, MVT::i32, Custom); 308 setOperationAction(ISD::FSHR, MVT::i32, Custom); 309 } 310 } else { 311 setOperationAction(ISD::SELECT, XLenVT, Custom); 312 } 313 314 static const ISD::CondCode FPCCToExpand[] = { 315 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 316 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 317 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 318 319 static const ISD::NodeType FPOpToExpand[] = { 320 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 321 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 322 323 if (Subtarget.hasStdExtZfh()) 324 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 325 326 if (Subtarget.hasStdExtZfh()) { 327 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 328 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 329 setOperationAction(ISD::LRINT, MVT::f16, Legal); 330 setOperationAction(ISD::LLRINT, MVT::f16, Legal); 331 setOperationAction(ISD::LROUND, MVT::f16, Legal); 332 setOperationAction(ISD::LLROUND, MVT::f16, Legal); 333 for (auto CC : FPCCToExpand) 334 setCondCodeAction(CC, MVT::f16, Expand); 335 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 336 setOperationAction(ISD::SELECT, MVT::f16, Custom); 337 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 338 for (auto Op : FPOpToExpand) 339 setOperationAction(Op, MVT::f16, Expand); 340 341 setOperationAction(ISD::FREM, MVT::f16, Promote); 342 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 343 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 344 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 345 setOperationAction(ISD::FRINT, MVT::f16, Promote); 346 setOperationAction(ISD::FROUND, MVT::f16, Promote); 347 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 348 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 349 } 350 351 if (Subtarget.hasStdExtF()) { 352 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 353 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 354 setOperationAction(ISD::LRINT, MVT::f32, Legal); 355 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 356 setOperationAction(ISD::LROUND, MVT::f32, Legal); 357 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 358 for (auto CC : FPCCToExpand) 359 setCondCodeAction(CC, MVT::f32, Expand); 360 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 361 setOperationAction(ISD::SELECT, MVT::f32, Custom); 362 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 363 for (auto Op : FPOpToExpand) 364 setOperationAction(Op, MVT::f32, Expand); 365 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 366 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 367 } 368 369 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 370 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 371 372 if (Subtarget.hasStdExtD()) { 373 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 374 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 375 setOperationAction(ISD::LRINT, MVT::f64, Legal); 376 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 377 setOperationAction(ISD::LROUND, MVT::f64, Legal); 378 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 379 for (auto CC : FPCCToExpand) 380 setCondCodeAction(CC, MVT::f64, Expand); 381 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 382 setOperationAction(ISD::SELECT, MVT::f64, Custom); 383 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 384 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 385 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 386 for (auto Op : FPOpToExpand) 387 setOperationAction(Op, MVT::f64, Expand); 388 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 389 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 390 } 391 392 if (Subtarget.is64Bit()) { 393 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 394 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 395 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 396 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 397 } 398 399 if (Subtarget.hasStdExtF()) { 400 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 401 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 402 403 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 404 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 405 } 406 407 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 408 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 409 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 410 setOperationAction(ISD::JumpTable, XLenVT, Custom); 411 412 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 413 414 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 415 // Unfortunately this can't be determined just from the ISA naming string. 416 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 417 Subtarget.is64Bit() ? Legal : Custom); 418 419 setOperationAction(ISD::TRAP, MVT::Other, Legal); 420 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 421 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 422 if (Subtarget.is64Bit()) 423 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 424 425 if (Subtarget.hasStdExtA()) { 426 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 427 setMinCmpXchgSizeInBits(32); 428 } else { 429 setMaxAtomicSizeInBitsSupported(0); 430 } 431 432 setBooleanContents(ZeroOrOneBooleanContent); 433 434 if (Subtarget.hasVInstructions()) { 435 setBooleanVectorContents(ZeroOrOneBooleanContent); 436 437 setOperationAction(ISD::VSCALE, XLenVT, Custom); 438 439 // RVV intrinsics may have illegal operands. 440 // We also need to custom legalize vmv.x.s. 441 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 442 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 443 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 444 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 445 if (Subtarget.is64Bit()) { 446 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 447 } else { 448 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 449 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 450 } 451 452 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 453 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 454 455 static const unsigned IntegerVPOps[] = { 456 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 457 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 458 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 459 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 460 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 461 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 462 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}; 463 464 static const unsigned FloatingPointVPOps[] = { 465 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 466 ISD::VP_FDIV, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 467 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX}; 468 469 if (!Subtarget.is64Bit()) { 470 // We must custom-lower certain vXi64 operations on RV32 due to the vector 471 // element type being illegal. 472 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 473 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 474 475 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 476 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 477 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 478 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 479 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 480 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 481 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 482 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 483 484 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 485 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 486 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 487 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 488 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 489 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 490 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 491 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 492 } 493 494 for (MVT VT : BoolVecVTs) { 495 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 496 497 // Mask VTs are custom-expanded into a series of standard nodes 498 setOperationAction(ISD::TRUNCATE, VT, Custom); 499 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 500 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 501 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 502 503 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 504 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 505 506 setOperationAction(ISD::SELECT, VT, Custom); 507 setOperationAction(ISD::SELECT_CC, VT, Expand); 508 setOperationAction(ISD::VSELECT, VT, Expand); 509 510 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 511 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 512 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 513 514 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 515 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 516 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 517 518 // RVV has native int->float & float->int conversions where the 519 // element type sizes are within one power-of-two of each other. Any 520 // wider distances between type sizes have to be lowered as sequences 521 // which progressively narrow the gap in stages. 522 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 523 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 524 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 525 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 526 527 // Expand all extending loads to types larger than this, and truncating 528 // stores from types larger than this. 529 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 530 setTruncStoreAction(OtherVT, VT, Expand); 531 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 532 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 533 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 534 } 535 } 536 537 for (MVT VT : IntVecVTs) { 538 if (VT.getVectorElementType() == MVT::i64 && 539 !Subtarget.hasVInstructionsI64()) 540 continue; 541 542 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 543 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 544 545 // Vectors implement MULHS/MULHU. 546 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 547 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 548 549 setOperationAction(ISD::SMIN, VT, Legal); 550 setOperationAction(ISD::SMAX, VT, Legal); 551 setOperationAction(ISD::UMIN, VT, Legal); 552 setOperationAction(ISD::UMAX, VT, Legal); 553 554 setOperationAction(ISD::ROTL, VT, Expand); 555 setOperationAction(ISD::ROTR, VT, Expand); 556 557 setOperationAction(ISD::CTTZ, VT, Expand); 558 setOperationAction(ISD::CTLZ, VT, Expand); 559 setOperationAction(ISD::CTPOP, VT, Expand); 560 561 setOperationAction(ISD::BSWAP, VT, Expand); 562 563 // Custom-lower extensions and truncations from/to mask types. 564 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 565 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 566 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 567 568 // RVV has native int->float & float->int conversions where the 569 // element type sizes are within one power-of-two of each other. Any 570 // wider distances between type sizes have to be lowered as sequences 571 // which progressively narrow the gap in stages. 572 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 573 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 574 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 575 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 576 577 setOperationAction(ISD::SADDSAT, VT, Legal); 578 setOperationAction(ISD::UADDSAT, VT, Legal); 579 setOperationAction(ISD::SSUBSAT, VT, Legal); 580 setOperationAction(ISD::USUBSAT, VT, Legal); 581 582 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 583 // nodes which truncate by one power of two at a time. 584 setOperationAction(ISD::TRUNCATE, VT, Custom); 585 586 // Custom-lower insert/extract operations to simplify patterns. 587 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 588 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 589 590 // Custom-lower reduction operations to set up the corresponding custom 591 // nodes' operands. 592 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 593 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 594 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 595 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 596 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 597 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 598 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 599 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 600 601 for (unsigned VPOpc : IntegerVPOps) 602 setOperationAction(VPOpc, VT, Custom); 603 604 setOperationAction(ISD::LOAD, VT, Custom); 605 setOperationAction(ISD::STORE, VT, Custom); 606 607 setOperationAction(ISD::MLOAD, VT, Custom); 608 setOperationAction(ISD::MSTORE, VT, Custom); 609 setOperationAction(ISD::MGATHER, VT, Custom); 610 setOperationAction(ISD::MSCATTER, VT, Custom); 611 612 setOperationAction(ISD::VP_LOAD, VT, Custom); 613 setOperationAction(ISD::VP_STORE, VT, Custom); 614 setOperationAction(ISD::VP_GATHER, VT, Custom); 615 setOperationAction(ISD::VP_SCATTER, VT, Custom); 616 617 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 618 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 619 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 620 621 setOperationAction(ISD::SELECT, VT, Custom); 622 setOperationAction(ISD::SELECT_CC, VT, Expand); 623 624 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 625 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 626 627 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 628 setTruncStoreAction(VT, OtherVT, Expand); 629 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 630 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 631 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 632 } 633 634 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 635 // type that can represent the value exactly. 636 if (VT.getVectorElementType() != MVT::i64) { 637 MVT FloatEltVT = 638 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 639 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 640 if (isTypeLegal(FloatVT)) { 641 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 642 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 643 } 644 } 645 } 646 647 // Expand various CCs to best match the RVV ISA, which natively supports UNE 648 // but no other unordered comparisons, and supports all ordered comparisons 649 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 650 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 651 // and we pattern-match those back to the "original", swapping operands once 652 // more. This way we catch both operations and both "vf" and "fv" forms with 653 // fewer patterns. 654 static const ISD::CondCode VFPCCToExpand[] = { 655 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 656 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 657 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 658 }; 659 660 // Sets common operation actions on RVV floating-point vector types. 661 const auto SetCommonVFPActions = [&](MVT VT) { 662 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 663 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 664 // sizes are within one power-of-two of each other. Therefore conversions 665 // between vXf16 and vXf64 must be lowered as sequences which convert via 666 // vXf32. 667 setOperationAction(ISD::FP_ROUND, VT, Custom); 668 setOperationAction(ISD::FP_EXTEND, VT, Custom); 669 // Custom-lower insert/extract operations to simplify patterns. 670 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 671 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 672 // Expand various condition codes (explained above). 673 for (auto CC : VFPCCToExpand) 674 setCondCodeAction(CC, VT, Expand); 675 676 setOperationAction(ISD::FMINNUM, VT, Legal); 677 setOperationAction(ISD::FMAXNUM, VT, Legal); 678 679 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 680 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 681 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 682 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 683 684 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 685 686 setOperationAction(ISD::LOAD, VT, Custom); 687 setOperationAction(ISD::STORE, VT, Custom); 688 689 setOperationAction(ISD::MLOAD, VT, Custom); 690 setOperationAction(ISD::MSTORE, VT, Custom); 691 setOperationAction(ISD::MGATHER, VT, Custom); 692 setOperationAction(ISD::MSCATTER, VT, Custom); 693 694 setOperationAction(ISD::VP_LOAD, VT, Custom); 695 setOperationAction(ISD::VP_STORE, VT, Custom); 696 setOperationAction(ISD::VP_GATHER, VT, Custom); 697 setOperationAction(ISD::VP_SCATTER, VT, Custom); 698 699 setOperationAction(ISD::SELECT, VT, Custom); 700 setOperationAction(ISD::SELECT_CC, VT, Expand); 701 702 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 703 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 704 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 705 706 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 707 708 for (unsigned VPOpc : FloatingPointVPOps) 709 setOperationAction(VPOpc, VT, Custom); 710 }; 711 712 // Sets common extload/truncstore actions on RVV floating-point vector 713 // types. 714 const auto SetCommonVFPExtLoadTruncStoreActions = 715 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 716 for (auto SmallVT : SmallerVTs) { 717 setTruncStoreAction(VT, SmallVT, Expand); 718 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 719 } 720 }; 721 722 if (Subtarget.hasVInstructionsF16()) 723 for (MVT VT : F16VecVTs) 724 SetCommonVFPActions(VT); 725 726 for (MVT VT : F32VecVTs) { 727 if (Subtarget.hasVInstructionsF32()) 728 SetCommonVFPActions(VT); 729 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 730 } 731 732 for (MVT VT : F64VecVTs) { 733 if (Subtarget.hasVInstructionsF64()) 734 SetCommonVFPActions(VT); 735 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 736 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 737 } 738 739 if (Subtarget.useRVVForFixedLengthVectors()) { 740 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 741 if (!useRVVForFixedLengthVectorVT(VT)) 742 continue; 743 744 // By default everything must be expanded. 745 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 746 setOperationAction(Op, VT, Expand); 747 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 748 setTruncStoreAction(VT, OtherVT, Expand); 749 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 750 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 751 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 752 } 753 754 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 755 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 756 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 757 758 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 759 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 760 761 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 762 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 763 764 setOperationAction(ISD::LOAD, VT, Custom); 765 setOperationAction(ISD::STORE, VT, Custom); 766 767 setOperationAction(ISD::SETCC, VT, Custom); 768 769 setOperationAction(ISD::SELECT, VT, Custom); 770 771 setOperationAction(ISD::TRUNCATE, VT, Custom); 772 773 setOperationAction(ISD::BITCAST, VT, Custom); 774 775 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 776 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 777 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 778 779 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 780 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 781 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 782 783 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 784 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 785 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 786 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 787 788 // Operations below are different for between masks and other vectors. 789 if (VT.getVectorElementType() == MVT::i1) { 790 setOperationAction(ISD::AND, VT, Custom); 791 setOperationAction(ISD::OR, VT, Custom); 792 setOperationAction(ISD::XOR, VT, Custom); 793 continue; 794 } 795 796 // Use SPLAT_VECTOR to prevent type legalization from destroying the 797 // splats when type legalizing i64 scalar on RV32. 798 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 799 // improvements first. 800 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 801 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 802 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 803 } 804 805 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 806 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 807 808 setOperationAction(ISD::MLOAD, VT, Custom); 809 setOperationAction(ISD::MSTORE, VT, Custom); 810 setOperationAction(ISD::MGATHER, VT, Custom); 811 setOperationAction(ISD::MSCATTER, VT, Custom); 812 813 setOperationAction(ISD::VP_LOAD, VT, Custom); 814 setOperationAction(ISD::VP_STORE, VT, Custom); 815 setOperationAction(ISD::VP_GATHER, VT, Custom); 816 setOperationAction(ISD::VP_SCATTER, VT, Custom); 817 818 setOperationAction(ISD::ADD, VT, Custom); 819 setOperationAction(ISD::MUL, VT, Custom); 820 setOperationAction(ISD::SUB, VT, Custom); 821 setOperationAction(ISD::AND, VT, Custom); 822 setOperationAction(ISD::OR, VT, Custom); 823 setOperationAction(ISD::XOR, VT, Custom); 824 setOperationAction(ISD::SDIV, VT, Custom); 825 setOperationAction(ISD::SREM, VT, Custom); 826 setOperationAction(ISD::UDIV, VT, Custom); 827 setOperationAction(ISD::UREM, VT, Custom); 828 setOperationAction(ISD::SHL, VT, Custom); 829 setOperationAction(ISD::SRA, VT, Custom); 830 setOperationAction(ISD::SRL, VT, Custom); 831 832 setOperationAction(ISD::SMIN, VT, Custom); 833 setOperationAction(ISD::SMAX, VT, Custom); 834 setOperationAction(ISD::UMIN, VT, Custom); 835 setOperationAction(ISD::UMAX, VT, Custom); 836 setOperationAction(ISD::ABS, VT, Custom); 837 838 setOperationAction(ISD::MULHS, VT, Custom); 839 setOperationAction(ISD::MULHU, VT, Custom); 840 841 setOperationAction(ISD::SADDSAT, VT, Custom); 842 setOperationAction(ISD::UADDSAT, VT, Custom); 843 setOperationAction(ISD::SSUBSAT, VT, Custom); 844 setOperationAction(ISD::USUBSAT, VT, Custom); 845 846 setOperationAction(ISD::VSELECT, VT, Custom); 847 setOperationAction(ISD::SELECT_CC, VT, Expand); 848 849 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 850 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 851 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 852 853 // Custom-lower reduction operations to set up the corresponding custom 854 // nodes' operands. 855 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 856 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 857 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 858 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 859 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 860 861 for (unsigned VPOpc : IntegerVPOps) 862 setOperationAction(VPOpc, VT, Custom); 863 864 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 865 // type that can represent the value exactly. 866 if (VT.getVectorElementType() != MVT::i64) { 867 MVT FloatEltVT = 868 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 869 EVT FloatVT = 870 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 871 if (isTypeLegal(FloatVT)) { 872 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 873 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 874 } 875 } 876 } 877 878 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 879 if (!useRVVForFixedLengthVectorVT(VT)) 880 continue; 881 882 // By default everything must be expanded. 883 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 884 setOperationAction(Op, VT, Expand); 885 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 886 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 887 setTruncStoreAction(VT, OtherVT, Expand); 888 } 889 890 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 891 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 892 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 893 894 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 895 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 896 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 897 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 898 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 899 900 setOperationAction(ISD::LOAD, VT, Custom); 901 setOperationAction(ISD::STORE, VT, Custom); 902 setOperationAction(ISD::MLOAD, VT, Custom); 903 setOperationAction(ISD::MSTORE, VT, Custom); 904 setOperationAction(ISD::MGATHER, VT, Custom); 905 setOperationAction(ISD::MSCATTER, VT, Custom); 906 907 setOperationAction(ISD::VP_LOAD, VT, Custom); 908 setOperationAction(ISD::VP_STORE, VT, Custom); 909 setOperationAction(ISD::VP_GATHER, VT, Custom); 910 setOperationAction(ISD::VP_SCATTER, VT, Custom); 911 912 setOperationAction(ISD::FADD, VT, Custom); 913 setOperationAction(ISD::FSUB, VT, Custom); 914 setOperationAction(ISD::FMUL, VT, Custom); 915 setOperationAction(ISD::FDIV, VT, Custom); 916 setOperationAction(ISD::FNEG, VT, Custom); 917 setOperationAction(ISD::FABS, VT, Custom); 918 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 919 setOperationAction(ISD::FSQRT, VT, Custom); 920 setOperationAction(ISD::FMA, VT, Custom); 921 setOperationAction(ISD::FMINNUM, VT, Custom); 922 setOperationAction(ISD::FMAXNUM, VT, Custom); 923 924 setOperationAction(ISD::FP_ROUND, VT, Custom); 925 setOperationAction(ISD::FP_EXTEND, VT, Custom); 926 927 for (auto CC : VFPCCToExpand) 928 setCondCodeAction(CC, VT, Expand); 929 930 setOperationAction(ISD::VSELECT, VT, Custom); 931 setOperationAction(ISD::SELECT, VT, Custom); 932 setOperationAction(ISD::SELECT_CC, VT, Expand); 933 934 setOperationAction(ISD::BITCAST, VT, Custom); 935 936 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 937 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 938 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 939 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 940 941 for (unsigned VPOpc : FloatingPointVPOps) 942 setOperationAction(VPOpc, VT, Custom); 943 } 944 945 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 946 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 947 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 948 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 949 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 950 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 951 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 952 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 953 } 954 } 955 956 // Function alignments. 957 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 958 setMinFunctionAlignment(FunctionAlignment); 959 setPrefFunctionAlignment(FunctionAlignment); 960 961 setMinimumJumpTableEntries(5); 962 963 // Jumps are expensive, compared to logic 964 setJumpIsExpensive(); 965 966 setTargetDAGCombine(ISD::ADD); 967 setTargetDAGCombine(ISD::SUB); 968 setTargetDAGCombine(ISD::AND); 969 setTargetDAGCombine(ISD::OR); 970 setTargetDAGCombine(ISD::XOR); 971 setTargetDAGCombine(ISD::ANY_EXTEND); 972 setTargetDAGCombine(ISD::ZERO_EXTEND); 973 if (Subtarget.hasVInstructions()) { 974 setTargetDAGCombine(ISD::FCOPYSIGN); 975 setTargetDAGCombine(ISD::MGATHER); 976 setTargetDAGCombine(ISD::MSCATTER); 977 setTargetDAGCombine(ISD::VP_GATHER); 978 setTargetDAGCombine(ISD::VP_SCATTER); 979 setTargetDAGCombine(ISD::SRA); 980 setTargetDAGCombine(ISD::SRL); 981 setTargetDAGCombine(ISD::SHL); 982 setTargetDAGCombine(ISD::STORE); 983 } 984 } 985 986 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 987 LLVMContext &Context, 988 EVT VT) const { 989 if (!VT.isVector()) 990 return getPointerTy(DL); 991 if (Subtarget.hasVInstructions() && 992 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 993 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 994 return VT.changeVectorElementTypeToInteger(); 995 } 996 997 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 998 return Subtarget.getXLenVT(); 999 } 1000 1001 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1002 const CallInst &I, 1003 MachineFunction &MF, 1004 unsigned Intrinsic) const { 1005 auto &DL = I.getModule()->getDataLayout(); 1006 switch (Intrinsic) { 1007 default: 1008 return false; 1009 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1010 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1011 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1012 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1013 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1014 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1015 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1016 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1017 case Intrinsic::riscv_masked_cmpxchg_i32: { 1018 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 1019 Info.opc = ISD::INTRINSIC_W_CHAIN; 1020 Info.memVT = MVT::getVT(PtrTy->getElementType()); 1021 Info.ptrVal = I.getArgOperand(0); 1022 Info.offset = 0; 1023 Info.align = Align(4); 1024 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1025 MachineMemOperand::MOVolatile; 1026 return true; 1027 } 1028 case Intrinsic::riscv_masked_strided_load: 1029 Info.opc = ISD::INTRINSIC_W_CHAIN; 1030 Info.ptrVal = I.getArgOperand(1); 1031 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1032 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1033 Info.size = MemoryLocation::UnknownSize; 1034 Info.flags |= MachineMemOperand::MOLoad; 1035 return true; 1036 case Intrinsic::riscv_masked_strided_store: 1037 Info.opc = ISD::INTRINSIC_VOID; 1038 Info.ptrVal = I.getArgOperand(1); 1039 Info.memVT = 1040 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1041 Info.align = Align( 1042 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1043 8); 1044 Info.size = MemoryLocation::UnknownSize; 1045 Info.flags |= MachineMemOperand::MOStore; 1046 return true; 1047 } 1048 } 1049 1050 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1051 const AddrMode &AM, Type *Ty, 1052 unsigned AS, 1053 Instruction *I) const { 1054 // No global is ever allowed as a base. 1055 if (AM.BaseGV) 1056 return false; 1057 1058 // Require a 12-bit signed offset. 1059 if (!isInt<12>(AM.BaseOffs)) 1060 return false; 1061 1062 switch (AM.Scale) { 1063 case 0: // "r+i" or just "i", depending on HasBaseReg. 1064 break; 1065 case 1: 1066 if (!AM.HasBaseReg) // allow "r+i". 1067 break; 1068 return false; // disallow "r+r" or "r+r+i". 1069 default: 1070 return false; 1071 } 1072 1073 return true; 1074 } 1075 1076 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1077 return isInt<12>(Imm); 1078 } 1079 1080 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1081 return isInt<12>(Imm); 1082 } 1083 1084 // On RV32, 64-bit integers are split into their high and low parts and held 1085 // in two different registers, so the trunc is free since the low register can 1086 // just be used. 1087 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1088 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1089 return false; 1090 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1091 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1092 return (SrcBits == 64 && DestBits == 32); 1093 } 1094 1095 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1096 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1097 !SrcVT.isInteger() || !DstVT.isInteger()) 1098 return false; 1099 unsigned SrcBits = SrcVT.getSizeInBits(); 1100 unsigned DestBits = DstVT.getSizeInBits(); 1101 return (SrcBits == 64 && DestBits == 32); 1102 } 1103 1104 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1105 // Zexts are free if they can be combined with a load. 1106 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1107 EVT MemVT = LD->getMemoryVT(); 1108 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 1109 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 1110 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1111 LD->getExtensionType() == ISD::ZEXTLOAD)) 1112 return true; 1113 } 1114 1115 return TargetLowering::isZExtFree(Val, VT2); 1116 } 1117 1118 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1119 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1120 } 1121 1122 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1123 return Subtarget.hasStdExtZbb(); 1124 } 1125 1126 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1127 return Subtarget.hasStdExtZbb(); 1128 } 1129 1130 bool RISCVTargetLowering::hasAndNot(SDValue Y) const { 1131 EVT VT = Y.getValueType(); 1132 1133 // FIXME: Support vectors once we have tests. 1134 if (VT.isVector()) 1135 return false; 1136 1137 return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y); 1138 } 1139 1140 /// Check if sinking \p I's operands to I's basic block is profitable, because 1141 /// the operands can be folded into a target instruction, e.g. 1142 /// splats of scalars can fold into vector instructions. 1143 bool RISCVTargetLowering::shouldSinkOperands( 1144 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1145 using namespace llvm::PatternMatch; 1146 1147 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1148 return false; 1149 1150 auto IsSinker = [&](Instruction *I, int Operand) { 1151 switch (I->getOpcode()) { 1152 case Instruction::Add: 1153 case Instruction::Sub: 1154 case Instruction::Mul: 1155 case Instruction::And: 1156 case Instruction::Or: 1157 case Instruction::Xor: 1158 case Instruction::FAdd: 1159 case Instruction::FSub: 1160 case Instruction::FMul: 1161 case Instruction::FDiv: 1162 case Instruction::ICmp: 1163 case Instruction::FCmp: 1164 return true; 1165 case Instruction::Shl: 1166 case Instruction::LShr: 1167 case Instruction::AShr: 1168 return Operand == 1; 1169 case Instruction::Call: 1170 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1171 switch (II->getIntrinsicID()) { 1172 case Intrinsic::fma: 1173 return Operand == 0 || Operand == 1; 1174 default: 1175 return false; 1176 } 1177 } 1178 return false; 1179 default: 1180 return false; 1181 } 1182 }; 1183 1184 for (auto OpIdx : enumerate(I->operands())) { 1185 if (!IsSinker(I, OpIdx.index())) 1186 continue; 1187 1188 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1189 // Make sure we are not already sinking this operand 1190 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1191 continue; 1192 1193 // We are looking for a splat that can be sunk. 1194 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1195 m_Undef(), m_ZeroMask()))) 1196 continue; 1197 1198 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1199 // and vector registers 1200 for (Use &U : Op->uses()) { 1201 Instruction *Insn = cast<Instruction>(U.getUser()); 1202 if (!IsSinker(Insn, U.getOperandNo())) 1203 return false; 1204 } 1205 1206 Ops.push_back(&Op->getOperandUse(0)); 1207 Ops.push_back(&OpIdx.value()); 1208 } 1209 return true; 1210 } 1211 1212 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1213 bool ForCodeSize) const { 1214 if (VT == MVT::f16 && !Subtarget.hasStdExtZfhmin()) 1215 return false; 1216 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1217 return false; 1218 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1219 return false; 1220 if (Imm.isNegZero()) 1221 return false; 1222 return Imm.isZero(); 1223 } 1224 1225 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1226 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1227 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1228 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1229 } 1230 1231 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1232 CallingConv::ID CC, 1233 EVT VT) const { 1234 // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled. 1235 // We might still end up using a GPR but that will be decided based on ABI. 1236 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin()) 1237 return MVT::f32; 1238 1239 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1240 } 1241 1242 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1243 CallingConv::ID CC, 1244 EVT VT) const { 1245 // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled. 1246 // We might still end up using a GPR but that will be decided based on ABI. 1247 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin()) 1248 return 1; 1249 1250 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1251 } 1252 1253 // Changes the condition code and swaps operands if necessary, so the SetCC 1254 // operation matches one of the comparisons supported directly by branches 1255 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1256 // with 1/-1. 1257 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1258 ISD::CondCode &CC, SelectionDAG &DAG) { 1259 // Convert X > -1 to X >= 0. 1260 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1261 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1262 CC = ISD::SETGE; 1263 return; 1264 } 1265 // Convert X < 1 to 0 >= X. 1266 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1267 RHS = LHS; 1268 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1269 CC = ISD::SETGE; 1270 return; 1271 } 1272 1273 switch (CC) { 1274 default: 1275 break; 1276 case ISD::SETGT: 1277 case ISD::SETLE: 1278 case ISD::SETUGT: 1279 case ISD::SETULE: 1280 CC = ISD::getSetCCSwappedOperands(CC); 1281 std::swap(LHS, RHS); 1282 break; 1283 } 1284 } 1285 1286 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1287 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1288 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1289 if (VT.getVectorElementType() == MVT::i1) 1290 KnownSize *= 8; 1291 1292 switch (KnownSize) { 1293 default: 1294 llvm_unreachable("Invalid LMUL."); 1295 case 8: 1296 return RISCVII::VLMUL::LMUL_F8; 1297 case 16: 1298 return RISCVII::VLMUL::LMUL_F4; 1299 case 32: 1300 return RISCVII::VLMUL::LMUL_F2; 1301 case 64: 1302 return RISCVII::VLMUL::LMUL_1; 1303 case 128: 1304 return RISCVII::VLMUL::LMUL_2; 1305 case 256: 1306 return RISCVII::VLMUL::LMUL_4; 1307 case 512: 1308 return RISCVII::VLMUL::LMUL_8; 1309 } 1310 } 1311 1312 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1313 switch (LMul) { 1314 default: 1315 llvm_unreachable("Invalid LMUL."); 1316 case RISCVII::VLMUL::LMUL_F8: 1317 case RISCVII::VLMUL::LMUL_F4: 1318 case RISCVII::VLMUL::LMUL_F2: 1319 case RISCVII::VLMUL::LMUL_1: 1320 return RISCV::VRRegClassID; 1321 case RISCVII::VLMUL::LMUL_2: 1322 return RISCV::VRM2RegClassID; 1323 case RISCVII::VLMUL::LMUL_4: 1324 return RISCV::VRM4RegClassID; 1325 case RISCVII::VLMUL::LMUL_8: 1326 return RISCV::VRM8RegClassID; 1327 } 1328 } 1329 1330 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1331 RISCVII::VLMUL LMUL = getLMUL(VT); 1332 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1333 LMUL == RISCVII::VLMUL::LMUL_F4 || 1334 LMUL == RISCVII::VLMUL::LMUL_F2 || 1335 LMUL == RISCVII::VLMUL::LMUL_1) { 1336 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1337 "Unexpected subreg numbering"); 1338 return RISCV::sub_vrm1_0 + Index; 1339 } 1340 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1341 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1342 "Unexpected subreg numbering"); 1343 return RISCV::sub_vrm2_0 + Index; 1344 } 1345 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1346 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1347 "Unexpected subreg numbering"); 1348 return RISCV::sub_vrm4_0 + Index; 1349 } 1350 llvm_unreachable("Invalid vector type."); 1351 } 1352 1353 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1354 if (VT.getVectorElementType() == MVT::i1) 1355 return RISCV::VRRegClassID; 1356 return getRegClassIDForLMUL(getLMUL(VT)); 1357 } 1358 1359 // Attempt to decompose a subvector insert/extract between VecVT and 1360 // SubVecVT via subregister indices. Returns the subregister index that 1361 // can perform the subvector insert/extract with the given element index, as 1362 // well as the index corresponding to any leftover subvectors that must be 1363 // further inserted/extracted within the register class for SubVecVT. 1364 std::pair<unsigned, unsigned> 1365 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1366 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1367 const RISCVRegisterInfo *TRI) { 1368 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1369 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1370 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1371 "Register classes not ordered"); 1372 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1373 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1374 // Try to compose a subregister index that takes us from the incoming 1375 // LMUL>1 register class down to the outgoing one. At each step we half 1376 // the LMUL: 1377 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1378 // Note that this is not guaranteed to find a subregister index, such as 1379 // when we are extracting from one VR type to another. 1380 unsigned SubRegIdx = RISCV::NoSubRegister; 1381 for (const unsigned RCID : 1382 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1383 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1384 VecVT = VecVT.getHalfNumVectorElementsVT(); 1385 bool IsHi = 1386 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1387 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1388 getSubregIndexByMVT(VecVT, IsHi)); 1389 if (IsHi) 1390 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1391 } 1392 return {SubRegIdx, InsertExtractIdx}; 1393 } 1394 1395 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1396 // stores for those types. 1397 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1398 return !Subtarget.useRVVForFixedLengthVectors() || 1399 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1400 } 1401 1402 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1403 if (ScalarTy->isPointerTy()) 1404 return true; 1405 1406 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1407 ScalarTy->isIntegerTy(32)) 1408 return true; 1409 1410 if (ScalarTy->isIntegerTy(64)) 1411 return Subtarget.hasVInstructionsI64(); 1412 1413 if (ScalarTy->isHalfTy()) 1414 return Subtarget.hasVInstructionsF16(); 1415 if (ScalarTy->isFloatTy()) 1416 return Subtarget.hasVInstructionsF32(); 1417 if (ScalarTy->isDoubleTy()) 1418 return Subtarget.hasVInstructionsF64(); 1419 1420 return false; 1421 } 1422 1423 static bool useRVVForFixedLengthVectorVT(MVT VT, 1424 const RISCVSubtarget &Subtarget) { 1425 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1426 if (!Subtarget.useRVVForFixedLengthVectors()) 1427 return false; 1428 1429 // We only support a set of vector types with a consistent maximum fixed size 1430 // across all supported vector element types to avoid legalization issues. 1431 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1432 // fixed-length vector type we support is 1024 bytes. 1433 if (VT.getFixedSizeInBits() > 1024 * 8) 1434 return false; 1435 1436 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1437 1438 MVT EltVT = VT.getVectorElementType(); 1439 1440 // Don't use RVV for vectors we cannot scalarize if required. 1441 switch (EltVT.SimpleTy) { 1442 // i1 is supported but has different rules. 1443 default: 1444 return false; 1445 case MVT::i1: 1446 // Masks can only use a single register. 1447 if (VT.getVectorNumElements() > MinVLen) 1448 return false; 1449 MinVLen /= 8; 1450 break; 1451 case MVT::i8: 1452 case MVT::i16: 1453 case MVT::i32: 1454 break; 1455 case MVT::i64: 1456 if (!Subtarget.hasVInstructionsI64()) 1457 return false; 1458 break; 1459 case MVT::f16: 1460 if (!Subtarget.hasVInstructionsF16()) 1461 return false; 1462 break; 1463 case MVT::f32: 1464 if (!Subtarget.hasVInstructionsF32()) 1465 return false; 1466 break; 1467 case MVT::f64: 1468 if (!Subtarget.hasVInstructionsF64()) 1469 return false; 1470 break; 1471 } 1472 1473 // Reject elements larger than ELEN. 1474 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1475 return false; 1476 1477 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1478 // Don't use RVV for types that don't fit. 1479 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1480 return false; 1481 1482 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1483 // the base fixed length RVV support in place. 1484 if (!VT.isPow2VectorType()) 1485 return false; 1486 1487 return true; 1488 } 1489 1490 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1491 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1492 } 1493 1494 // Return the largest legal scalable vector type that matches VT's element type. 1495 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1496 const RISCVSubtarget &Subtarget) { 1497 // This may be called before legal types are setup. 1498 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1499 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1500 "Expected legal fixed length vector!"); 1501 1502 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1503 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1504 1505 MVT EltVT = VT.getVectorElementType(); 1506 switch (EltVT.SimpleTy) { 1507 default: 1508 llvm_unreachable("unexpected element type for RVV container"); 1509 case MVT::i1: 1510 case MVT::i8: 1511 case MVT::i16: 1512 case MVT::i32: 1513 case MVT::i64: 1514 case MVT::f16: 1515 case MVT::f32: 1516 case MVT::f64: { 1517 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1518 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1519 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1520 unsigned NumElts = 1521 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1522 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1523 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1524 return MVT::getScalableVectorVT(EltVT, NumElts); 1525 } 1526 } 1527 } 1528 1529 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1530 const RISCVSubtarget &Subtarget) { 1531 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1532 Subtarget); 1533 } 1534 1535 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1536 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1537 } 1538 1539 // Grow V to consume an entire RVV register. 1540 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1541 const RISCVSubtarget &Subtarget) { 1542 assert(VT.isScalableVector() && 1543 "Expected to convert into a scalable vector!"); 1544 assert(V.getValueType().isFixedLengthVector() && 1545 "Expected a fixed length vector operand!"); 1546 SDLoc DL(V); 1547 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1548 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1549 } 1550 1551 // Shrink V so it's just big enough to maintain a VT's worth of data. 1552 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1553 const RISCVSubtarget &Subtarget) { 1554 assert(VT.isFixedLengthVector() && 1555 "Expected to convert into a fixed length vector!"); 1556 assert(V.getValueType().isScalableVector() && 1557 "Expected a scalable vector operand!"); 1558 SDLoc DL(V); 1559 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1560 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1561 } 1562 1563 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1564 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1565 // the vector type that it is contained in. 1566 static std::pair<SDValue, SDValue> 1567 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1568 const RISCVSubtarget &Subtarget) { 1569 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1570 MVT XLenVT = Subtarget.getXLenVT(); 1571 SDValue VL = VecVT.isFixedLengthVector() 1572 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1573 : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT); 1574 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1575 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1576 return {Mask, VL}; 1577 } 1578 1579 // As above but assuming the given type is a scalable vector type. 1580 static std::pair<SDValue, SDValue> 1581 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1582 const RISCVSubtarget &Subtarget) { 1583 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1584 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1585 } 1586 1587 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1588 // of either is (currently) supported. This can get us into an infinite loop 1589 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1590 // as a ..., etc. 1591 // Until either (or both) of these can reliably lower any node, reporting that 1592 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1593 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1594 // which is not desirable. 1595 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1596 EVT VT, unsigned DefinedValues) const { 1597 return false; 1598 } 1599 1600 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1601 // Only splats are currently supported. 1602 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1603 return true; 1604 1605 return false; 1606 } 1607 1608 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) { 1609 // RISCV FP-to-int conversions saturate to the destination register size, but 1610 // don't produce 0 for nan. We can use a conversion instruction and fix the 1611 // nan case with a compare and a select. 1612 SDValue Src = Op.getOperand(0); 1613 1614 EVT DstVT = Op.getValueType(); 1615 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1616 1617 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1618 unsigned Opc; 1619 if (SatVT == DstVT) 1620 Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ; 1621 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1622 Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 1623 else 1624 return SDValue(); 1625 // FIXME: Support other SatVTs by clamping before or after the conversion. 1626 1627 SDLoc DL(Op); 1628 SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src); 1629 1630 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1631 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1632 } 1633 1634 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1635 const RISCVSubtarget &Subtarget) { 1636 MVT VT = Op.getSimpleValueType(); 1637 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1638 1639 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1640 1641 SDLoc DL(Op); 1642 SDValue Mask, VL; 1643 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1644 1645 unsigned Opc = 1646 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1647 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1648 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1649 } 1650 1651 struct VIDSequence { 1652 int64_t StepNumerator; 1653 unsigned StepDenominator; 1654 int64_t Addend; 1655 }; 1656 1657 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1658 // to the (non-zero) step S and start value X. This can be then lowered as the 1659 // RVV sequence (VID * S) + X, for example. 1660 // The step S is represented as an integer numerator divided by a positive 1661 // denominator. Note that the implementation currently only identifies 1662 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1663 // cannot detect 2/3, for example. 1664 // Note that this method will also match potentially unappealing index 1665 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1666 // determine whether this is worth generating code for. 1667 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1668 unsigned NumElts = Op.getNumOperands(); 1669 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1670 if (!Op.getValueType().isInteger()) 1671 return None; 1672 1673 Optional<unsigned> SeqStepDenom; 1674 Optional<int64_t> SeqStepNum, SeqAddend; 1675 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1676 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1677 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1678 // Assume undef elements match the sequence; we just have to be careful 1679 // when interpolating across them. 1680 if (Op.getOperand(Idx).isUndef()) 1681 continue; 1682 // The BUILD_VECTOR must be all constants. 1683 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1684 return None; 1685 1686 uint64_t Val = Op.getConstantOperandVal(Idx) & 1687 maskTrailingOnes<uint64_t>(EltSizeInBits); 1688 1689 if (PrevElt) { 1690 // Calculate the step since the last non-undef element, and ensure 1691 // it's consistent across the entire sequence. 1692 unsigned IdxDiff = Idx - PrevElt->second; 1693 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1694 1695 // A zero-value value difference means that we're somewhere in the middle 1696 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1697 // step change before evaluating the sequence. 1698 if (ValDiff != 0) { 1699 int64_t Remainder = ValDiff % IdxDiff; 1700 // Normalize the step if it's greater than 1. 1701 if (Remainder != ValDiff) { 1702 // The difference must cleanly divide the element span. 1703 if (Remainder != 0) 1704 return None; 1705 ValDiff /= IdxDiff; 1706 IdxDiff = 1; 1707 } 1708 1709 if (!SeqStepNum) 1710 SeqStepNum = ValDiff; 1711 else if (ValDiff != SeqStepNum) 1712 return None; 1713 1714 if (!SeqStepDenom) 1715 SeqStepDenom = IdxDiff; 1716 else if (IdxDiff != *SeqStepDenom) 1717 return None; 1718 } 1719 } 1720 1721 // Record and/or check any addend. 1722 if (SeqStepNum && SeqStepDenom) { 1723 uint64_t ExpectedVal = 1724 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1725 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1726 if (!SeqAddend) 1727 SeqAddend = Addend; 1728 else if (SeqAddend != Addend) 1729 return None; 1730 } 1731 1732 // Record this non-undef element for later. 1733 if (!PrevElt || PrevElt->first != Val) 1734 PrevElt = std::make_pair(Val, Idx); 1735 } 1736 // We need to have logged both a step and an addend for this to count as 1737 // a legal index sequence. 1738 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1739 return None; 1740 1741 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1742 } 1743 1744 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1745 const RISCVSubtarget &Subtarget) { 1746 MVT VT = Op.getSimpleValueType(); 1747 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1748 1749 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1750 1751 SDLoc DL(Op); 1752 SDValue Mask, VL; 1753 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1754 1755 MVT XLenVT = Subtarget.getXLenVT(); 1756 unsigned NumElts = Op.getNumOperands(); 1757 1758 if (VT.getVectorElementType() == MVT::i1) { 1759 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1760 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1761 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1762 } 1763 1764 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1765 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1766 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1767 } 1768 1769 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1770 // scalar integer chunks whose bit-width depends on the number of mask 1771 // bits and XLEN. 1772 // First, determine the most appropriate scalar integer type to use. This 1773 // is at most XLenVT, but may be shrunk to a smaller vector element type 1774 // according to the size of the final vector - use i8 chunks rather than 1775 // XLenVT if we're producing a v8i1. This results in more consistent 1776 // codegen across RV32 and RV64. 1777 unsigned NumViaIntegerBits = 1778 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1779 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1780 // If we have to use more than one INSERT_VECTOR_ELT then this 1781 // optimization is likely to increase code size; avoid peforming it in 1782 // such a case. We can use a load from a constant pool in this case. 1783 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1784 return SDValue(); 1785 // Now we can create our integer vector type. Note that it may be larger 1786 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1787 MVT IntegerViaVecVT = 1788 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1789 divideCeil(NumElts, NumViaIntegerBits)); 1790 1791 uint64_t Bits = 0; 1792 unsigned BitPos = 0, IntegerEltIdx = 0; 1793 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1794 1795 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1796 // Once we accumulate enough bits to fill our scalar type, insert into 1797 // our vector and clear our accumulated data. 1798 if (I != 0 && I % NumViaIntegerBits == 0) { 1799 if (NumViaIntegerBits <= 32) 1800 Bits = SignExtend64(Bits, 32); 1801 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1802 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1803 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1804 Bits = 0; 1805 BitPos = 0; 1806 IntegerEltIdx++; 1807 } 1808 SDValue V = Op.getOperand(I); 1809 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1810 Bits |= ((uint64_t)BitValue << BitPos); 1811 } 1812 1813 // Insert the (remaining) scalar value into position in our integer 1814 // vector type. 1815 if (NumViaIntegerBits <= 32) 1816 Bits = SignExtend64(Bits, 32); 1817 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1818 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1819 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1820 1821 if (NumElts < NumViaIntegerBits) { 1822 // If we're producing a smaller vector than our minimum legal integer 1823 // type, bitcast to the equivalent (known-legal) mask type, and extract 1824 // our final mask. 1825 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1826 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1827 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1828 DAG.getConstant(0, DL, XLenVT)); 1829 } else { 1830 // Else we must have produced an integer type with the same size as the 1831 // mask type; bitcast for the final result. 1832 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1833 Vec = DAG.getBitcast(VT, Vec); 1834 } 1835 1836 return Vec; 1837 } 1838 1839 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 1840 // vector type, we have a legal equivalently-sized i8 type, so we can use 1841 // that. 1842 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 1843 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 1844 1845 SDValue WideVec; 1846 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1847 // For a splat, perform a scalar truncate before creating the wider 1848 // vector. 1849 assert(Splat.getValueType() == XLenVT && 1850 "Unexpected type for i1 splat value"); 1851 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 1852 DAG.getConstant(1, DL, XLenVT)); 1853 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 1854 } else { 1855 SmallVector<SDValue, 8> Ops(Op->op_values()); 1856 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 1857 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 1858 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 1859 } 1860 1861 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 1862 } 1863 1864 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1865 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 1866 : RISCVISD::VMV_V_X_VL; 1867 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 1868 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1869 } 1870 1871 // Try and match index sequences, which we can lower to the vid instruction 1872 // with optional modifications. An all-undef vector is matched by 1873 // getSplatValue, above. 1874 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 1875 int64_t StepNumerator = SimpleVID->StepNumerator; 1876 unsigned StepDenominator = SimpleVID->StepDenominator; 1877 int64_t Addend = SimpleVID->Addend; 1878 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 1879 // threshold since it's the immediate value many RVV instructions accept. 1880 if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) && 1881 isInt<5>(Addend)) { 1882 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 1883 // Convert right out of the scalable type so we can use standard ISD 1884 // nodes for the rest of the computation. If we used scalable types with 1885 // these, we'd lose the fixed-length vector info and generate worse 1886 // vsetvli code. 1887 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 1888 assert(StepNumerator != 0 && "Invalid step"); 1889 bool Negate = false; 1890 if (StepNumerator != 1) { 1891 int64_t SplatStepVal = StepNumerator; 1892 unsigned Opcode = ISD::MUL; 1893 if (isPowerOf2_64(std::abs(StepNumerator))) { 1894 Negate = StepNumerator < 0; 1895 Opcode = ISD::SHL; 1896 SplatStepVal = Log2_64(std::abs(StepNumerator)); 1897 } 1898 SDValue SplatStep = DAG.getSplatVector( 1899 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 1900 VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep); 1901 } 1902 if (StepDenominator != 1) { 1903 SDValue SplatStep = DAG.getSplatVector( 1904 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 1905 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 1906 } 1907 if (Addend != 0 || Negate) { 1908 SDValue SplatAddend = 1909 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 1910 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 1911 } 1912 return VID; 1913 } 1914 } 1915 1916 // Attempt to detect "hidden" splats, which only reveal themselves as splats 1917 // when re-interpreted as a vector with a larger element type. For example, 1918 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 1919 // could be instead splat as 1920 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 1921 // TODO: This optimization could also work on non-constant splats, but it 1922 // would require bit-manipulation instructions to construct the splat value. 1923 SmallVector<SDValue> Sequence; 1924 unsigned EltBitSize = VT.getScalarSizeInBits(); 1925 const auto *BV = cast<BuildVectorSDNode>(Op); 1926 if (VT.isInteger() && EltBitSize < 64 && 1927 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 1928 BV->getRepeatedSequence(Sequence) && 1929 (Sequence.size() * EltBitSize) <= 64) { 1930 unsigned SeqLen = Sequence.size(); 1931 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 1932 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 1933 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 1934 ViaIntVT == MVT::i64) && 1935 "Unexpected sequence type"); 1936 1937 unsigned EltIdx = 0; 1938 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 1939 uint64_t SplatValue = 0; 1940 // Construct the amalgamated value which can be splatted as this larger 1941 // vector type. 1942 for (const auto &SeqV : Sequence) { 1943 if (!SeqV.isUndef()) 1944 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 1945 << (EltIdx * EltBitSize)); 1946 EltIdx++; 1947 } 1948 1949 // On RV64, sign-extend from 32 to 64 bits where possible in order to 1950 // achieve better constant materializion. 1951 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 1952 SplatValue = SignExtend64(SplatValue, 32); 1953 1954 // Since we can't introduce illegal i64 types at this stage, we can only 1955 // perform an i64 splat on RV32 if it is its own sign-extended value. That 1956 // way we can use RVV instructions to splat. 1957 assert((ViaIntVT.bitsLE(XLenVT) || 1958 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 1959 "Unexpected bitcast sequence"); 1960 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 1961 SDValue ViaVL = 1962 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 1963 MVT ViaContainerVT = 1964 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 1965 SDValue Splat = 1966 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 1967 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 1968 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 1969 return DAG.getBitcast(VT, Splat); 1970 } 1971 } 1972 1973 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 1974 // which constitute a large proportion of the elements. In such cases we can 1975 // splat a vector with the dominant element and make up the shortfall with 1976 // INSERT_VECTOR_ELTs. 1977 // Note that this includes vectors of 2 elements by association. The 1978 // upper-most element is the "dominant" one, allowing us to use a splat to 1979 // "insert" the upper element, and an insert of the lower element at position 1980 // 0, which improves codegen. 1981 SDValue DominantValue; 1982 unsigned MostCommonCount = 0; 1983 DenseMap<SDValue, unsigned> ValueCounts; 1984 unsigned NumUndefElts = 1985 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 1986 1987 // Track the number of scalar loads we know we'd be inserting, estimated as 1988 // any non-zero floating-point constant. Other kinds of element are either 1989 // already in registers or are materialized on demand. The threshold at which 1990 // a vector load is more desirable than several scalar materializion and 1991 // vector-insertion instructions is not known. 1992 unsigned NumScalarLoads = 0; 1993 1994 for (SDValue V : Op->op_values()) { 1995 if (V.isUndef()) 1996 continue; 1997 1998 ValueCounts.insert(std::make_pair(V, 0)); 1999 unsigned &Count = ValueCounts[V]; 2000 2001 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2002 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2003 2004 // Is this value dominant? In case of a tie, prefer the highest element as 2005 // it's cheaper to insert near the beginning of a vector than it is at the 2006 // end. 2007 if (++Count >= MostCommonCount) { 2008 DominantValue = V; 2009 MostCommonCount = Count; 2010 } 2011 } 2012 2013 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2014 unsigned NumDefElts = NumElts - NumUndefElts; 2015 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2016 2017 // Don't perform this optimization when optimizing for size, since 2018 // materializing elements and inserting them tends to cause code bloat. 2019 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2020 ((MostCommonCount > DominantValueCountThreshold) || 2021 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2022 // Start by splatting the most common element. 2023 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2024 2025 DenseSet<SDValue> Processed{DominantValue}; 2026 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2027 for (const auto &OpIdx : enumerate(Op->ops())) { 2028 const SDValue &V = OpIdx.value(); 2029 if (V.isUndef() || !Processed.insert(V).second) 2030 continue; 2031 if (ValueCounts[V] == 1) { 2032 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2033 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2034 } else { 2035 // Blend in all instances of this value using a VSELECT, using a 2036 // mask where each bit signals whether that element is the one 2037 // we're after. 2038 SmallVector<SDValue> Ops; 2039 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2040 return DAG.getConstant(V == V1, DL, XLenVT); 2041 }); 2042 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2043 DAG.getBuildVector(SelMaskTy, DL, Ops), 2044 DAG.getSplatBuildVector(VT, DL, V), Vec); 2045 } 2046 } 2047 2048 return Vec; 2049 } 2050 2051 return SDValue(); 2052 } 2053 2054 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 2055 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 2056 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2057 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2058 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2059 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2060 // node in order to try and match RVV vector/scalar instructions. 2061 if ((LoC >> 31) == HiC) 2062 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2063 } 2064 2065 // Fall back to a stack store and stride x0 vector load. 2066 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2067 } 2068 2069 // Called by type legalization to handle splat of i64 on RV32. 2070 // FIXME: We can optimize this when the type has sign or zero bits in one 2071 // of the halves. 2072 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2073 SDValue VL, SelectionDAG &DAG) { 2074 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2075 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2076 DAG.getConstant(0, DL, MVT::i32)); 2077 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2078 DAG.getConstant(1, DL, MVT::i32)); 2079 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2080 } 2081 2082 // This function lowers a splat of a scalar operand Splat with the vector 2083 // length VL. It ensures the final sequence is type legal, which is useful when 2084 // lowering a splat after type legalization. 2085 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2086 SelectionDAG &DAG, 2087 const RISCVSubtarget &Subtarget) { 2088 if (VT.isFloatingPoint()) 2089 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2090 2091 MVT XLenVT = Subtarget.getXLenVT(); 2092 2093 // Simplest case is that the operand needs to be promoted to XLenVT. 2094 if (Scalar.getValueType().bitsLE(XLenVT)) { 2095 // If the operand is a constant, sign extend to increase our chances 2096 // of being able to use a .vi instruction. ANY_EXTEND would become a 2097 // a zero extend and the simm5 check in isel would fail. 2098 // FIXME: Should we ignore the upper bits in isel instead? 2099 unsigned ExtOpc = 2100 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2101 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2102 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2103 } 2104 2105 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2106 "Unexpected scalar for splat lowering!"); 2107 2108 // Otherwise use the more complicated splatting algorithm. 2109 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2110 } 2111 2112 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2113 const RISCVSubtarget &Subtarget) { 2114 SDValue V1 = Op.getOperand(0); 2115 SDValue V2 = Op.getOperand(1); 2116 SDLoc DL(Op); 2117 MVT XLenVT = Subtarget.getXLenVT(); 2118 MVT VT = Op.getSimpleValueType(); 2119 unsigned NumElts = VT.getVectorNumElements(); 2120 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2121 2122 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2123 2124 SDValue TrueMask, VL; 2125 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2126 2127 if (SVN->isSplat()) { 2128 const int Lane = SVN->getSplatIndex(); 2129 if (Lane >= 0) { 2130 MVT SVT = VT.getVectorElementType(); 2131 2132 // Turn splatted vector load into a strided load with an X0 stride. 2133 SDValue V = V1; 2134 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2135 // with undef. 2136 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2137 int Offset = Lane; 2138 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2139 int OpElements = 2140 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2141 V = V.getOperand(Offset / OpElements); 2142 Offset %= OpElements; 2143 } 2144 2145 // We need to ensure the load isn't atomic or volatile. 2146 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2147 auto *Ld = cast<LoadSDNode>(V); 2148 Offset *= SVT.getStoreSize(); 2149 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2150 TypeSize::Fixed(Offset), DL); 2151 2152 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2153 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2154 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2155 SDValue IntID = 2156 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2157 SDValue Ops[] = {Ld->getChain(), IntID, NewAddr, 2158 DAG.getRegister(RISCV::X0, XLenVT), VL}; 2159 SDValue NewLoad = DAG.getMemIntrinsicNode( 2160 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2161 DAG.getMachineFunction().getMachineMemOperand( 2162 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2163 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2164 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2165 } 2166 2167 // Otherwise use a scalar load and splat. This will give the best 2168 // opportunity to fold a splat into the operation. ISel can turn it into 2169 // the x0 strided load if we aren't able to fold away the select. 2170 if (SVT.isFloatingPoint()) 2171 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2172 Ld->getPointerInfo().getWithOffset(Offset), 2173 Ld->getOriginalAlign(), 2174 Ld->getMemOperand()->getFlags()); 2175 else 2176 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2177 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2178 Ld->getOriginalAlign(), 2179 Ld->getMemOperand()->getFlags()); 2180 DAG.makeEquivalentMemoryOrdering(Ld, V); 2181 2182 unsigned Opc = 2183 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2184 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2185 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2186 } 2187 2188 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2189 assert(Lane < (int)NumElts && "Unexpected lane!"); 2190 SDValue Gather = 2191 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2192 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2193 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2194 } 2195 } 2196 2197 // Detect shuffles which can be re-expressed as vector selects; these are 2198 // shuffles in which each element in the destination is taken from an element 2199 // at the corresponding index in either source vectors. 2200 bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) { 2201 int MaskIndex = MaskIdx.value(); 2202 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2203 }); 2204 2205 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2206 2207 SmallVector<SDValue> MaskVals; 2208 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2209 // merged with a second vrgather. 2210 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2211 2212 // By default we preserve the original operand order, and use a mask to 2213 // select LHS as true and RHS as false. However, since RVV vector selects may 2214 // feature splats but only on the LHS, we may choose to invert our mask and 2215 // instead select between RHS and LHS. 2216 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2217 bool InvertMask = IsSelect == SwapOps; 2218 2219 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2220 // half. 2221 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2222 2223 // Now construct the mask that will be used by the vselect or blended 2224 // vrgather operation. For vrgathers, construct the appropriate indices into 2225 // each vector. 2226 for (int MaskIndex : SVN->getMask()) { 2227 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2228 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2229 if (!IsSelect) { 2230 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2231 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2232 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2233 : DAG.getUNDEF(XLenVT)); 2234 GatherIndicesRHS.push_back( 2235 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2236 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2237 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2238 ++LHSIndexCounts[MaskIndex]; 2239 if (!IsLHSOrUndefIndex) 2240 ++RHSIndexCounts[MaskIndex - NumElts]; 2241 } 2242 } 2243 2244 if (SwapOps) { 2245 std::swap(V1, V2); 2246 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2247 } 2248 2249 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2250 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2251 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2252 2253 if (IsSelect) 2254 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2255 2256 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2257 // On such a large vector we're unable to use i8 as the index type. 2258 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2259 // may involve vector splitting if we're already at LMUL=8, or our 2260 // user-supplied maximum fixed-length LMUL. 2261 return SDValue(); 2262 } 2263 2264 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2265 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2266 MVT IndexVT = VT.changeTypeToInteger(); 2267 // Since we can't introduce illegal index types at this stage, use i16 and 2268 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2269 // than XLenVT. 2270 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2271 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2272 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2273 } 2274 2275 MVT IndexContainerVT = 2276 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2277 2278 SDValue Gather; 2279 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2280 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2281 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2282 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2283 } else { 2284 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2285 // If only one index is used, we can use a "splat" vrgather. 2286 // TODO: We can splat the most-common index and fix-up any stragglers, if 2287 // that's beneficial. 2288 if (LHSIndexCounts.size() == 1) { 2289 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2290 Gather = 2291 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2292 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2293 } else { 2294 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2295 LHSIndices = 2296 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2297 2298 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2299 TrueMask, VL); 2300 } 2301 } 2302 2303 // If a second vector operand is used by this shuffle, blend it in with an 2304 // additional vrgather. 2305 if (!V2.isUndef()) { 2306 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2307 // If only one index is used, we can use a "splat" vrgather. 2308 // TODO: We can splat the most-common index and fix-up any stragglers, if 2309 // that's beneficial. 2310 if (RHSIndexCounts.size() == 1) { 2311 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2312 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2313 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2314 } else { 2315 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2316 RHSIndices = 2317 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2318 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2319 VL); 2320 } 2321 2322 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2323 SelectMask = 2324 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2325 2326 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2327 Gather, VL); 2328 } 2329 2330 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2331 } 2332 2333 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2334 SDLoc DL, SelectionDAG &DAG, 2335 const RISCVSubtarget &Subtarget) { 2336 if (VT.isScalableVector()) 2337 return DAG.getFPExtendOrRound(Op, DL, VT); 2338 assert(VT.isFixedLengthVector() && 2339 "Unexpected value type for RVV FP extend/round lowering"); 2340 SDValue Mask, VL; 2341 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2342 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2343 ? RISCVISD::FP_EXTEND_VL 2344 : RISCVISD::FP_ROUND_VL; 2345 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2346 } 2347 2348 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2349 // the exponent. 2350 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2351 MVT VT = Op.getSimpleValueType(); 2352 unsigned EltSize = VT.getScalarSizeInBits(); 2353 SDValue Src = Op.getOperand(0); 2354 SDLoc DL(Op); 2355 2356 // We need a FP type that can represent the value. 2357 // TODO: Use f16 for i8 when possible? 2358 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2359 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2360 2361 // Legal types should have been checked in the RISCVTargetLowering 2362 // constructor. 2363 // TODO: Splitting may make sense in some cases. 2364 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2365 "Expected legal float type!"); 2366 2367 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2368 // The trailing zero count is equal to log2 of this single bit value. 2369 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2370 SDValue Neg = 2371 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2372 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2373 } 2374 2375 // We have a legal FP type, convert to it. 2376 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2377 // Bitcast to integer and shift the exponent to the LSB. 2378 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2379 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2380 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2381 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2382 DAG.getConstant(ShiftAmt, DL, IntVT)); 2383 // Truncate back to original type to allow vnsrl. 2384 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2385 // The exponent contains log2 of the value in biased form. 2386 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2387 2388 // For trailing zeros, we just need to subtract the bias. 2389 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2390 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2391 DAG.getConstant(ExponentBias, DL, VT)); 2392 2393 // For leading zeros, we need to remove the bias and convert from log2 to 2394 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2395 unsigned Adjust = ExponentBias + (EltSize - 1); 2396 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2397 } 2398 2399 // While RVV has alignment restrictions, we should always be able to load as a 2400 // legal equivalently-sized byte-typed vector instead. This method is 2401 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2402 // the load is already correctly-aligned, it returns SDValue(). 2403 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2404 SelectionDAG &DAG) const { 2405 auto *Load = cast<LoadSDNode>(Op); 2406 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2407 2408 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2409 Load->getMemoryVT(), 2410 *Load->getMemOperand())) 2411 return SDValue(); 2412 2413 SDLoc DL(Op); 2414 MVT VT = Op.getSimpleValueType(); 2415 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2416 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2417 "Unexpected unaligned RVV load type"); 2418 MVT NewVT = 2419 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2420 assert(NewVT.isValid() && 2421 "Expecting equally-sized RVV vector types to be legal"); 2422 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2423 Load->getPointerInfo(), Load->getOriginalAlign(), 2424 Load->getMemOperand()->getFlags()); 2425 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2426 } 2427 2428 // While RVV has alignment restrictions, we should always be able to store as a 2429 // legal equivalently-sized byte-typed vector instead. This method is 2430 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2431 // returns SDValue() if the store is already correctly aligned. 2432 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2433 SelectionDAG &DAG) const { 2434 auto *Store = cast<StoreSDNode>(Op); 2435 assert(Store && Store->getValue().getValueType().isVector() && 2436 "Expected vector store"); 2437 2438 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2439 Store->getMemoryVT(), 2440 *Store->getMemOperand())) 2441 return SDValue(); 2442 2443 SDLoc DL(Op); 2444 SDValue StoredVal = Store->getValue(); 2445 MVT VT = StoredVal.getSimpleValueType(); 2446 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2447 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2448 "Unexpected unaligned RVV store type"); 2449 MVT NewVT = 2450 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2451 assert(NewVT.isValid() && 2452 "Expecting equally-sized RVV vector types to be legal"); 2453 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2454 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2455 Store->getPointerInfo(), Store->getOriginalAlign(), 2456 Store->getMemOperand()->getFlags()); 2457 } 2458 2459 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2460 SelectionDAG &DAG) const { 2461 switch (Op.getOpcode()) { 2462 default: 2463 report_fatal_error("unimplemented operand"); 2464 case ISD::GlobalAddress: 2465 return lowerGlobalAddress(Op, DAG); 2466 case ISD::BlockAddress: 2467 return lowerBlockAddress(Op, DAG); 2468 case ISD::ConstantPool: 2469 return lowerConstantPool(Op, DAG); 2470 case ISD::JumpTable: 2471 return lowerJumpTable(Op, DAG); 2472 case ISD::GlobalTLSAddress: 2473 return lowerGlobalTLSAddress(Op, DAG); 2474 case ISD::SELECT: 2475 return lowerSELECT(Op, DAG); 2476 case ISD::BRCOND: 2477 return lowerBRCOND(Op, DAG); 2478 case ISD::VASTART: 2479 return lowerVASTART(Op, DAG); 2480 case ISD::FRAMEADDR: 2481 return lowerFRAMEADDR(Op, DAG); 2482 case ISD::RETURNADDR: 2483 return lowerRETURNADDR(Op, DAG); 2484 case ISD::SHL_PARTS: 2485 return lowerShiftLeftParts(Op, DAG); 2486 case ISD::SRA_PARTS: 2487 return lowerShiftRightParts(Op, DAG, true); 2488 case ISD::SRL_PARTS: 2489 return lowerShiftRightParts(Op, DAG, false); 2490 case ISD::BITCAST: { 2491 SDLoc DL(Op); 2492 EVT VT = Op.getValueType(); 2493 SDValue Op0 = Op.getOperand(0); 2494 EVT Op0VT = Op0.getValueType(); 2495 MVT XLenVT = Subtarget.getXLenVT(); 2496 if (VT.isFixedLengthVector()) { 2497 // We can handle fixed length vector bitcasts with a simple replacement 2498 // in isel. 2499 if (Op0VT.isFixedLengthVector()) 2500 return Op; 2501 // When bitcasting from scalar to fixed-length vector, insert the scalar 2502 // into a one-element vector of the result type, and perform a vector 2503 // bitcast. 2504 if (!Op0VT.isVector()) { 2505 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2506 if (!isTypeLegal(BVT)) 2507 return SDValue(); 2508 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2509 DAG.getUNDEF(BVT), Op0, 2510 DAG.getConstant(0, DL, XLenVT))); 2511 } 2512 return SDValue(); 2513 } 2514 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2515 // thus: bitcast the vector to a one-element vector type whose element type 2516 // is the same as the result type, and extract the first element. 2517 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2518 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2519 if (!isTypeLegal(BVT)) 2520 return SDValue(); 2521 SDValue BVec = DAG.getBitcast(BVT, Op0); 2522 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2523 DAG.getConstant(0, DL, XLenVT)); 2524 } 2525 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2526 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2527 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2528 return FPConv; 2529 } 2530 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2531 Subtarget.hasStdExtF()) { 2532 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2533 SDValue FPConv = 2534 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2535 return FPConv; 2536 } 2537 return SDValue(); 2538 } 2539 case ISD::INTRINSIC_WO_CHAIN: 2540 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2541 case ISD::INTRINSIC_W_CHAIN: 2542 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2543 case ISD::INTRINSIC_VOID: 2544 return LowerINTRINSIC_VOID(Op, DAG); 2545 case ISD::BSWAP: 2546 case ISD::BITREVERSE: { 2547 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2548 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 2549 MVT VT = Op.getSimpleValueType(); 2550 SDLoc DL(Op); 2551 // Start with the maximum immediate value which is the bitwidth - 1. 2552 unsigned Imm = VT.getSizeInBits() - 1; 2553 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2554 if (Op.getOpcode() == ISD::BSWAP) 2555 Imm &= ~0x7U; 2556 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2557 DAG.getConstant(Imm, DL, VT)); 2558 } 2559 case ISD::FSHL: 2560 case ISD::FSHR: { 2561 MVT VT = Op.getSimpleValueType(); 2562 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2563 SDLoc DL(Op); 2564 if (Op.getOperand(2).getOpcode() == ISD::Constant) 2565 return Op; 2566 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2567 // use log(XLen) bits. Mask the shift amount accordingly. 2568 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2569 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2570 DAG.getConstant(ShAmtWidth, DL, VT)); 2571 unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR; 2572 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt); 2573 } 2574 case ISD::TRUNCATE: { 2575 SDLoc DL(Op); 2576 MVT VT = Op.getSimpleValueType(); 2577 // Only custom-lower vector truncates 2578 if (!VT.isVector()) 2579 return Op; 2580 2581 // Truncates to mask types are handled differently 2582 if (VT.getVectorElementType() == MVT::i1) 2583 return lowerVectorMaskTrunc(Op, DAG); 2584 2585 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 2586 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 2587 // truncate by one power of two at a time. 2588 MVT DstEltVT = VT.getVectorElementType(); 2589 2590 SDValue Src = Op.getOperand(0); 2591 MVT SrcVT = Src.getSimpleValueType(); 2592 MVT SrcEltVT = SrcVT.getVectorElementType(); 2593 2594 assert(DstEltVT.bitsLT(SrcEltVT) && 2595 isPowerOf2_64(DstEltVT.getSizeInBits()) && 2596 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 2597 "Unexpected vector truncate lowering"); 2598 2599 MVT ContainerVT = SrcVT; 2600 if (SrcVT.isFixedLengthVector()) { 2601 ContainerVT = getContainerForFixedLengthVector(SrcVT); 2602 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 2603 } 2604 2605 SDValue Result = Src; 2606 SDValue Mask, VL; 2607 std::tie(Mask, VL) = 2608 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 2609 LLVMContext &Context = *DAG.getContext(); 2610 const ElementCount Count = ContainerVT.getVectorElementCount(); 2611 do { 2612 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 2613 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 2614 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 2615 Mask, VL); 2616 } while (SrcEltVT != DstEltVT); 2617 2618 if (SrcVT.isFixedLengthVector()) 2619 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 2620 2621 return Result; 2622 } 2623 case ISD::ANY_EXTEND: 2624 case ISD::ZERO_EXTEND: 2625 if (Op.getOperand(0).getValueType().isVector() && 2626 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2627 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 2628 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 2629 case ISD::SIGN_EXTEND: 2630 if (Op.getOperand(0).getValueType().isVector() && 2631 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2632 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 2633 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 2634 case ISD::SPLAT_VECTOR_PARTS: 2635 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 2636 case ISD::INSERT_VECTOR_ELT: 2637 return lowerINSERT_VECTOR_ELT(Op, DAG); 2638 case ISD::EXTRACT_VECTOR_ELT: 2639 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 2640 case ISD::VSCALE: { 2641 MVT VT = Op.getSimpleValueType(); 2642 SDLoc DL(Op); 2643 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 2644 // We define our scalable vector types for lmul=1 to use a 64 bit known 2645 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 2646 // vscale as VLENB / 8. 2647 assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!"); 2648 if (isa<ConstantSDNode>(Op.getOperand(0))) { 2649 // We assume VLENB is a multiple of 8. We manually choose the best shift 2650 // here because SimplifyDemandedBits isn't always able to simplify it. 2651 uint64_t Val = Op.getConstantOperandVal(0); 2652 if (isPowerOf2_64(Val)) { 2653 uint64_t Log2 = Log2_64(Val); 2654 if (Log2 < 3) 2655 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 2656 DAG.getConstant(3 - Log2, DL, VT)); 2657 if (Log2 > 3) 2658 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 2659 DAG.getConstant(Log2 - 3, DL, VT)); 2660 return VLENB; 2661 } 2662 // If the multiplier is a multiple of 8, scale it down to avoid needing 2663 // to shift the VLENB value. 2664 if ((Val % 8) == 0) 2665 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 2666 DAG.getConstant(Val / 8, DL, VT)); 2667 } 2668 2669 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 2670 DAG.getConstant(3, DL, VT)); 2671 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 2672 } 2673 case ISD::FP_EXTEND: { 2674 // RVV can only do fp_extend to types double the size as the source. We 2675 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 2676 // via f32. 2677 SDLoc DL(Op); 2678 MVT VT = Op.getSimpleValueType(); 2679 SDValue Src = Op.getOperand(0); 2680 MVT SrcVT = Src.getSimpleValueType(); 2681 2682 // Prepare any fixed-length vector operands. 2683 MVT ContainerVT = VT; 2684 if (SrcVT.isFixedLengthVector()) { 2685 ContainerVT = getContainerForFixedLengthVector(VT); 2686 MVT SrcContainerVT = 2687 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 2688 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2689 } 2690 2691 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 2692 SrcVT.getVectorElementType() != MVT::f16) { 2693 // For scalable vectors, we only need to close the gap between 2694 // vXf16->vXf64. 2695 if (!VT.isFixedLengthVector()) 2696 return Op; 2697 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 2698 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2699 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2700 } 2701 2702 MVT InterVT = VT.changeVectorElementType(MVT::f32); 2703 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 2704 SDValue IntermediateExtend = getRVVFPExtendOrRound( 2705 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 2706 2707 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 2708 DL, DAG, Subtarget); 2709 if (VT.isFixedLengthVector()) 2710 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 2711 return Extend; 2712 } 2713 case ISD::FP_ROUND: { 2714 // RVV can only do fp_round to types half the size as the source. We 2715 // custom-lower f64->f16 rounds via RVV's round-to-odd float 2716 // conversion instruction. 2717 SDLoc DL(Op); 2718 MVT VT = Op.getSimpleValueType(); 2719 SDValue Src = Op.getOperand(0); 2720 MVT SrcVT = Src.getSimpleValueType(); 2721 2722 // Prepare any fixed-length vector operands. 2723 MVT ContainerVT = VT; 2724 if (VT.isFixedLengthVector()) { 2725 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2726 ContainerVT = 2727 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2728 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2729 } 2730 2731 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 2732 SrcVT.getVectorElementType() != MVT::f64) { 2733 // For scalable vectors, we only need to close the gap between 2734 // vXf64<->vXf16. 2735 if (!VT.isFixedLengthVector()) 2736 return Op; 2737 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 2738 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2739 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2740 } 2741 2742 SDValue Mask, VL; 2743 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2744 2745 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 2746 SDValue IntermediateRound = 2747 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 2748 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 2749 DL, DAG, Subtarget); 2750 2751 if (VT.isFixedLengthVector()) 2752 return convertFromScalableVector(VT, Round, DAG, Subtarget); 2753 return Round; 2754 } 2755 case ISD::FP_TO_SINT: 2756 case ISD::FP_TO_UINT: 2757 case ISD::SINT_TO_FP: 2758 case ISD::UINT_TO_FP: { 2759 // RVV can only do fp<->int conversions to types half/double the size as 2760 // the source. We custom-lower any conversions that do two hops into 2761 // sequences. 2762 MVT VT = Op.getSimpleValueType(); 2763 if (!VT.isVector()) 2764 return Op; 2765 SDLoc DL(Op); 2766 SDValue Src = Op.getOperand(0); 2767 MVT EltVT = VT.getVectorElementType(); 2768 MVT SrcVT = Src.getSimpleValueType(); 2769 MVT SrcEltVT = SrcVT.getVectorElementType(); 2770 unsigned EltSize = EltVT.getSizeInBits(); 2771 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 2772 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 2773 "Unexpected vector element types"); 2774 2775 bool IsInt2FP = SrcEltVT.isInteger(); 2776 // Widening conversions 2777 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 2778 if (IsInt2FP) { 2779 // Do a regular integer sign/zero extension then convert to float. 2780 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 2781 VT.getVectorElementCount()); 2782 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 2783 ? ISD::ZERO_EXTEND 2784 : ISD::SIGN_EXTEND; 2785 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 2786 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 2787 } 2788 // FP2Int 2789 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 2790 // Do one doubling fp_extend then complete the operation by converting 2791 // to int. 2792 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2793 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 2794 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 2795 } 2796 2797 // Narrowing conversions 2798 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 2799 if (IsInt2FP) { 2800 // One narrowing int_to_fp, then an fp_round. 2801 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 2802 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2803 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 2804 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 2805 } 2806 // FP2Int 2807 // One narrowing fp_to_int, then truncate the integer. If the float isn't 2808 // representable by the integer, the result is poison. 2809 MVT IVecVT = 2810 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 2811 VT.getVectorElementCount()); 2812 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 2813 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 2814 } 2815 2816 // Scalable vectors can exit here. Patterns will handle equally-sized 2817 // conversions halving/doubling ones. 2818 if (!VT.isFixedLengthVector()) 2819 return Op; 2820 2821 // For fixed-length vectors we lower to a custom "VL" node. 2822 unsigned RVVOpc = 0; 2823 switch (Op.getOpcode()) { 2824 default: 2825 llvm_unreachable("Impossible opcode"); 2826 case ISD::FP_TO_SINT: 2827 RVVOpc = RISCVISD::FP_TO_SINT_VL; 2828 break; 2829 case ISD::FP_TO_UINT: 2830 RVVOpc = RISCVISD::FP_TO_UINT_VL; 2831 break; 2832 case ISD::SINT_TO_FP: 2833 RVVOpc = RISCVISD::SINT_TO_FP_VL; 2834 break; 2835 case ISD::UINT_TO_FP: 2836 RVVOpc = RISCVISD::UINT_TO_FP_VL; 2837 break; 2838 } 2839 2840 MVT ContainerVT, SrcContainerVT; 2841 // Derive the reference container type from the larger vector type. 2842 if (SrcEltSize > EltSize) { 2843 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2844 ContainerVT = 2845 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2846 } else { 2847 ContainerVT = getContainerForFixedLengthVector(VT); 2848 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 2849 } 2850 2851 SDValue Mask, VL; 2852 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2853 2854 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2855 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 2856 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2857 } 2858 case ISD::FP_TO_SINT_SAT: 2859 case ISD::FP_TO_UINT_SAT: 2860 return lowerFP_TO_INT_SAT(Op, DAG); 2861 case ISD::VECREDUCE_ADD: 2862 case ISD::VECREDUCE_UMAX: 2863 case ISD::VECREDUCE_SMAX: 2864 case ISD::VECREDUCE_UMIN: 2865 case ISD::VECREDUCE_SMIN: 2866 return lowerVECREDUCE(Op, DAG); 2867 case ISD::VECREDUCE_AND: 2868 case ISD::VECREDUCE_OR: 2869 case ISD::VECREDUCE_XOR: 2870 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2871 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 2872 return lowerVECREDUCE(Op, DAG); 2873 case ISD::VECREDUCE_FADD: 2874 case ISD::VECREDUCE_SEQ_FADD: 2875 case ISD::VECREDUCE_FMIN: 2876 case ISD::VECREDUCE_FMAX: 2877 return lowerFPVECREDUCE(Op, DAG); 2878 case ISD::VP_REDUCE_ADD: 2879 case ISD::VP_REDUCE_UMAX: 2880 case ISD::VP_REDUCE_SMAX: 2881 case ISD::VP_REDUCE_UMIN: 2882 case ISD::VP_REDUCE_SMIN: 2883 case ISD::VP_REDUCE_FADD: 2884 case ISD::VP_REDUCE_SEQ_FADD: 2885 case ISD::VP_REDUCE_FMIN: 2886 case ISD::VP_REDUCE_FMAX: 2887 return lowerVPREDUCE(Op, DAG); 2888 case ISD::VP_REDUCE_AND: 2889 case ISD::VP_REDUCE_OR: 2890 case ISD::VP_REDUCE_XOR: 2891 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 2892 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 2893 return lowerVPREDUCE(Op, DAG); 2894 case ISD::INSERT_SUBVECTOR: 2895 return lowerINSERT_SUBVECTOR(Op, DAG); 2896 case ISD::EXTRACT_SUBVECTOR: 2897 return lowerEXTRACT_SUBVECTOR(Op, DAG); 2898 case ISD::STEP_VECTOR: 2899 return lowerSTEP_VECTOR(Op, DAG); 2900 case ISD::VECTOR_REVERSE: 2901 return lowerVECTOR_REVERSE(Op, DAG); 2902 case ISD::BUILD_VECTOR: 2903 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 2904 case ISD::SPLAT_VECTOR: 2905 if (Op.getValueType().getVectorElementType() == MVT::i1) 2906 return lowerVectorMaskSplat(Op, DAG); 2907 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 2908 case ISD::VECTOR_SHUFFLE: 2909 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 2910 case ISD::CONCAT_VECTORS: { 2911 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 2912 // better than going through the stack, as the default expansion does. 2913 SDLoc DL(Op); 2914 MVT VT = Op.getSimpleValueType(); 2915 unsigned NumOpElts = 2916 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 2917 SDValue Vec = DAG.getUNDEF(VT); 2918 for (const auto &OpIdx : enumerate(Op->ops())) 2919 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(), 2920 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 2921 return Vec; 2922 } 2923 case ISD::LOAD: 2924 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 2925 return V; 2926 if (Op.getValueType().isFixedLengthVector()) 2927 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 2928 return Op; 2929 case ISD::STORE: 2930 if (auto V = expandUnalignedRVVStore(Op, DAG)) 2931 return V; 2932 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 2933 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 2934 return Op; 2935 case ISD::MLOAD: 2936 case ISD::VP_LOAD: 2937 return lowerMaskedLoad(Op, DAG); 2938 case ISD::MSTORE: 2939 case ISD::VP_STORE: 2940 return lowerMaskedStore(Op, DAG); 2941 case ISD::SETCC: 2942 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 2943 case ISD::ADD: 2944 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 2945 case ISD::SUB: 2946 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 2947 case ISD::MUL: 2948 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 2949 case ISD::MULHS: 2950 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 2951 case ISD::MULHU: 2952 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 2953 case ISD::AND: 2954 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 2955 RISCVISD::AND_VL); 2956 case ISD::OR: 2957 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 2958 RISCVISD::OR_VL); 2959 case ISD::XOR: 2960 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 2961 RISCVISD::XOR_VL); 2962 case ISD::SDIV: 2963 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 2964 case ISD::SREM: 2965 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 2966 case ISD::UDIV: 2967 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 2968 case ISD::UREM: 2969 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 2970 case ISD::SHL: 2971 case ISD::SRA: 2972 case ISD::SRL: 2973 if (Op.getSimpleValueType().isFixedLengthVector()) 2974 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 2975 // This can be called for an i32 shift amount that needs to be promoted. 2976 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 2977 "Unexpected custom legalisation"); 2978 return SDValue(); 2979 case ISD::SADDSAT: 2980 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 2981 case ISD::UADDSAT: 2982 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 2983 case ISD::SSUBSAT: 2984 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 2985 case ISD::USUBSAT: 2986 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 2987 case ISD::FADD: 2988 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 2989 case ISD::FSUB: 2990 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 2991 case ISD::FMUL: 2992 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 2993 case ISD::FDIV: 2994 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 2995 case ISD::FNEG: 2996 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 2997 case ISD::FABS: 2998 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 2999 case ISD::FSQRT: 3000 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3001 case ISD::FMA: 3002 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3003 case ISD::SMIN: 3004 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3005 case ISD::SMAX: 3006 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3007 case ISD::UMIN: 3008 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3009 case ISD::UMAX: 3010 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3011 case ISD::FMINNUM: 3012 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3013 case ISD::FMAXNUM: 3014 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3015 case ISD::ABS: 3016 return lowerABS(Op, DAG); 3017 case ISD::CTLZ_ZERO_UNDEF: 3018 case ISD::CTTZ_ZERO_UNDEF: 3019 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3020 case ISD::VSELECT: 3021 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3022 case ISD::FCOPYSIGN: 3023 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3024 case ISD::MGATHER: 3025 case ISD::VP_GATHER: 3026 return lowerMaskedGather(Op, DAG); 3027 case ISD::MSCATTER: 3028 case ISD::VP_SCATTER: 3029 return lowerMaskedScatter(Op, DAG); 3030 case ISD::FLT_ROUNDS_: 3031 return lowerGET_ROUNDING(Op, DAG); 3032 case ISD::SET_ROUNDING: 3033 return lowerSET_ROUNDING(Op, DAG); 3034 case ISD::VP_ADD: 3035 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3036 case ISD::VP_SUB: 3037 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3038 case ISD::VP_MUL: 3039 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3040 case ISD::VP_SDIV: 3041 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3042 case ISD::VP_UDIV: 3043 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3044 case ISD::VP_SREM: 3045 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3046 case ISD::VP_UREM: 3047 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3048 case ISD::VP_AND: 3049 return lowerVPOp(Op, DAG, RISCVISD::AND_VL); 3050 case ISD::VP_OR: 3051 return lowerVPOp(Op, DAG, RISCVISD::OR_VL); 3052 case ISD::VP_XOR: 3053 return lowerVPOp(Op, DAG, RISCVISD::XOR_VL); 3054 case ISD::VP_ASHR: 3055 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3056 case ISD::VP_LSHR: 3057 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3058 case ISD::VP_SHL: 3059 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3060 case ISD::VP_FADD: 3061 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3062 case ISD::VP_FSUB: 3063 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3064 case ISD::VP_FMUL: 3065 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3066 case ISD::VP_FDIV: 3067 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3068 } 3069 } 3070 3071 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3072 SelectionDAG &DAG, unsigned Flags) { 3073 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3074 } 3075 3076 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3077 SelectionDAG &DAG, unsigned Flags) { 3078 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3079 Flags); 3080 } 3081 3082 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3083 SelectionDAG &DAG, unsigned Flags) { 3084 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3085 N->getOffset(), Flags); 3086 } 3087 3088 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3089 SelectionDAG &DAG, unsigned Flags) { 3090 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3091 } 3092 3093 template <class NodeTy> 3094 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3095 bool IsLocal) const { 3096 SDLoc DL(N); 3097 EVT Ty = getPointerTy(DAG.getDataLayout()); 3098 3099 if (isPositionIndependent()) { 3100 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3101 if (IsLocal) 3102 // Use PC-relative addressing to access the symbol. This generates the 3103 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3104 // %pcrel_lo(auipc)). 3105 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3106 3107 // Use PC-relative addressing to access the GOT for this symbol, then load 3108 // the address from the GOT. This generates the pattern (PseudoLA sym), 3109 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3110 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3111 } 3112 3113 switch (getTargetMachine().getCodeModel()) { 3114 default: 3115 report_fatal_error("Unsupported code model for lowering"); 3116 case CodeModel::Small: { 3117 // Generate a sequence for accessing addresses within the first 2 GiB of 3118 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3119 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3120 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3121 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3122 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3123 } 3124 case CodeModel::Medium: { 3125 // Generate a sequence for accessing addresses within any 2GiB range within 3126 // the address space. This generates the pattern (PseudoLLA sym), which 3127 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3128 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3129 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3130 } 3131 } 3132 } 3133 3134 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3135 SelectionDAG &DAG) const { 3136 SDLoc DL(Op); 3137 EVT Ty = Op.getValueType(); 3138 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3139 int64_t Offset = N->getOffset(); 3140 MVT XLenVT = Subtarget.getXLenVT(); 3141 3142 const GlobalValue *GV = N->getGlobal(); 3143 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3144 SDValue Addr = getAddr(N, DAG, IsLocal); 3145 3146 // In order to maximise the opportunity for common subexpression elimination, 3147 // emit a separate ADD node for the global address offset instead of folding 3148 // it in the global address node. Later peephole optimisations may choose to 3149 // fold it back in when profitable. 3150 if (Offset != 0) 3151 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3152 DAG.getConstant(Offset, DL, XLenVT)); 3153 return Addr; 3154 } 3155 3156 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3157 SelectionDAG &DAG) const { 3158 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3159 3160 return getAddr(N, DAG); 3161 } 3162 3163 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3164 SelectionDAG &DAG) const { 3165 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3166 3167 return getAddr(N, DAG); 3168 } 3169 3170 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3171 SelectionDAG &DAG) const { 3172 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3173 3174 return getAddr(N, DAG); 3175 } 3176 3177 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3178 SelectionDAG &DAG, 3179 bool UseGOT) const { 3180 SDLoc DL(N); 3181 EVT Ty = getPointerTy(DAG.getDataLayout()); 3182 const GlobalValue *GV = N->getGlobal(); 3183 MVT XLenVT = Subtarget.getXLenVT(); 3184 3185 if (UseGOT) { 3186 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3187 // load the address from the GOT and add the thread pointer. This generates 3188 // the pattern (PseudoLA_TLS_IE sym), which expands to 3189 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3190 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3191 SDValue Load = 3192 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3193 3194 // Add the thread pointer. 3195 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3196 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3197 } 3198 3199 // Generate a sequence for accessing the address relative to the thread 3200 // pointer, with the appropriate adjustment for the thread pointer offset. 3201 // This generates the pattern 3202 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3203 SDValue AddrHi = 3204 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3205 SDValue AddrAdd = 3206 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3207 SDValue AddrLo = 3208 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3209 3210 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3211 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3212 SDValue MNAdd = SDValue( 3213 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3214 0); 3215 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3216 } 3217 3218 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3219 SelectionDAG &DAG) const { 3220 SDLoc DL(N); 3221 EVT Ty = getPointerTy(DAG.getDataLayout()); 3222 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3223 const GlobalValue *GV = N->getGlobal(); 3224 3225 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3226 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3227 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3228 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3229 SDValue Load = 3230 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3231 3232 // Prepare argument list to generate call. 3233 ArgListTy Args; 3234 ArgListEntry Entry; 3235 Entry.Node = Load; 3236 Entry.Ty = CallTy; 3237 Args.push_back(Entry); 3238 3239 // Setup call to __tls_get_addr. 3240 TargetLowering::CallLoweringInfo CLI(DAG); 3241 CLI.setDebugLoc(DL) 3242 .setChain(DAG.getEntryNode()) 3243 .setLibCallee(CallingConv::C, CallTy, 3244 DAG.getExternalSymbol("__tls_get_addr", Ty), 3245 std::move(Args)); 3246 3247 return LowerCallTo(CLI).first; 3248 } 3249 3250 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3251 SelectionDAG &DAG) const { 3252 SDLoc DL(Op); 3253 EVT Ty = Op.getValueType(); 3254 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3255 int64_t Offset = N->getOffset(); 3256 MVT XLenVT = Subtarget.getXLenVT(); 3257 3258 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3259 3260 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3261 CallingConv::GHC) 3262 report_fatal_error("In GHC calling convention TLS is not supported"); 3263 3264 SDValue Addr; 3265 switch (Model) { 3266 case TLSModel::LocalExec: 3267 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3268 break; 3269 case TLSModel::InitialExec: 3270 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3271 break; 3272 case TLSModel::LocalDynamic: 3273 case TLSModel::GeneralDynamic: 3274 Addr = getDynamicTLSAddr(N, DAG); 3275 break; 3276 } 3277 3278 // In order to maximise the opportunity for common subexpression elimination, 3279 // emit a separate ADD node for the global address offset instead of folding 3280 // it in the global address node. Later peephole optimisations may choose to 3281 // fold it back in when profitable. 3282 if (Offset != 0) 3283 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3284 DAG.getConstant(Offset, DL, XLenVT)); 3285 return Addr; 3286 } 3287 3288 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3289 SDValue CondV = Op.getOperand(0); 3290 SDValue TrueV = Op.getOperand(1); 3291 SDValue FalseV = Op.getOperand(2); 3292 SDLoc DL(Op); 3293 MVT VT = Op.getSimpleValueType(); 3294 MVT XLenVT = Subtarget.getXLenVT(); 3295 3296 // Lower vector SELECTs to VSELECTs by splatting the condition. 3297 if (VT.isVector()) { 3298 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3299 SDValue CondSplat = VT.isScalableVector() 3300 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3301 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3302 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3303 } 3304 3305 // If the result type is XLenVT and CondV is the output of a SETCC node 3306 // which also operated on XLenVT inputs, then merge the SETCC node into the 3307 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3308 // compare+branch instructions. i.e.: 3309 // (select (setcc lhs, rhs, cc), truev, falsev) 3310 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3311 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3312 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3313 SDValue LHS = CondV.getOperand(0); 3314 SDValue RHS = CondV.getOperand(1); 3315 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3316 ISD::CondCode CCVal = CC->get(); 3317 3318 // Special case for a select of 2 constants that have a diffence of 1. 3319 // Normally this is done by DAGCombine, but if the select is introduced by 3320 // type legalization or op legalization, we miss it. Restricting to SETLT 3321 // case for now because that is what signed saturating add/sub need. 3322 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3323 // but we would probably want to swap the true/false values if the condition 3324 // is SETGE/SETLE to avoid an XORI. 3325 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3326 CCVal == ISD::SETLT) { 3327 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3328 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3329 if (TrueVal - 1 == FalseVal) 3330 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3331 if (TrueVal + 1 == FalseVal) 3332 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3333 } 3334 3335 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3336 3337 SDValue TargetCC = DAG.getCondCode(CCVal); 3338 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3339 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3340 } 3341 3342 // Otherwise: 3343 // (select condv, truev, falsev) 3344 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3345 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3346 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3347 3348 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3349 3350 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3351 } 3352 3353 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3354 SDValue CondV = Op.getOperand(1); 3355 SDLoc DL(Op); 3356 MVT XLenVT = Subtarget.getXLenVT(); 3357 3358 if (CondV.getOpcode() == ISD::SETCC && 3359 CondV.getOperand(0).getValueType() == XLenVT) { 3360 SDValue LHS = CondV.getOperand(0); 3361 SDValue RHS = CondV.getOperand(1); 3362 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3363 3364 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3365 3366 SDValue TargetCC = DAG.getCondCode(CCVal); 3367 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3368 LHS, RHS, TargetCC, Op.getOperand(2)); 3369 } 3370 3371 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3372 CondV, DAG.getConstant(0, DL, XLenVT), 3373 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3374 } 3375 3376 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3377 MachineFunction &MF = DAG.getMachineFunction(); 3378 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3379 3380 SDLoc DL(Op); 3381 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3382 getPointerTy(MF.getDataLayout())); 3383 3384 // vastart just stores the address of the VarArgsFrameIndex slot into the 3385 // memory location argument. 3386 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3387 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3388 MachinePointerInfo(SV)); 3389 } 3390 3391 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3392 SelectionDAG &DAG) const { 3393 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3394 MachineFunction &MF = DAG.getMachineFunction(); 3395 MachineFrameInfo &MFI = MF.getFrameInfo(); 3396 MFI.setFrameAddressIsTaken(true); 3397 Register FrameReg = RI.getFrameRegister(MF); 3398 int XLenInBytes = Subtarget.getXLen() / 8; 3399 3400 EVT VT = Op.getValueType(); 3401 SDLoc DL(Op); 3402 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3403 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3404 while (Depth--) { 3405 int Offset = -(XLenInBytes * 2); 3406 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3407 DAG.getIntPtrConstant(Offset, DL)); 3408 FrameAddr = 3409 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3410 } 3411 return FrameAddr; 3412 } 3413 3414 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3415 SelectionDAG &DAG) const { 3416 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3417 MachineFunction &MF = DAG.getMachineFunction(); 3418 MachineFrameInfo &MFI = MF.getFrameInfo(); 3419 MFI.setReturnAddressIsTaken(true); 3420 MVT XLenVT = Subtarget.getXLenVT(); 3421 int XLenInBytes = Subtarget.getXLen() / 8; 3422 3423 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3424 return SDValue(); 3425 3426 EVT VT = Op.getValueType(); 3427 SDLoc DL(Op); 3428 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3429 if (Depth) { 3430 int Off = -XLenInBytes; 3431 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3432 SDValue Offset = DAG.getConstant(Off, DL, VT); 3433 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3434 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3435 MachinePointerInfo()); 3436 } 3437 3438 // Return the value of the return address register, marking it an implicit 3439 // live-in. 3440 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3441 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3442 } 3443 3444 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3445 SelectionDAG &DAG) const { 3446 SDLoc DL(Op); 3447 SDValue Lo = Op.getOperand(0); 3448 SDValue Hi = Op.getOperand(1); 3449 SDValue Shamt = Op.getOperand(2); 3450 EVT VT = Lo.getValueType(); 3451 3452 // if Shamt-XLEN < 0: // Shamt < XLEN 3453 // Lo = Lo << Shamt 3454 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3455 // else: 3456 // Lo = 0 3457 // Hi = Lo << (Shamt-XLEN) 3458 3459 SDValue Zero = DAG.getConstant(0, DL, VT); 3460 SDValue One = DAG.getConstant(1, DL, VT); 3461 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3462 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3463 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3464 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3465 3466 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3467 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3468 SDValue ShiftRightLo = 3469 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3470 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3471 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3472 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3473 3474 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3475 3476 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3477 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3478 3479 SDValue Parts[2] = {Lo, Hi}; 3480 return DAG.getMergeValues(Parts, DL); 3481 } 3482 3483 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3484 bool IsSRA) const { 3485 SDLoc DL(Op); 3486 SDValue Lo = Op.getOperand(0); 3487 SDValue Hi = Op.getOperand(1); 3488 SDValue Shamt = Op.getOperand(2); 3489 EVT VT = Lo.getValueType(); 3490 3491 // SRA expansion: 3492 // if Shamt-XLEN < 0: // Shamt < XLEN 3493 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3494 // Hi = Hi >>s Shamt 3495 // else: 3496 // Lo = Hi >>s (Shamt-XLEN); 3497 // Hi = Hi >>s (XLEN-1) 3498 // 3499 // SRL expansion: 3500 // if Shamt-XLEN < 0: // Shamt < XLEN 3501 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3502 // Hi = Hi >>u Shamt 3503 // else: 3504 // Lo = Hi >>u (Shamt-XLEN); 3505 // Hi = 0; 3506 3507 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3508 3509 SDValue Zero = DAG.getConstant(0, DL, VT); 3510 SDValue One = DAG.getConstant(1, DL, VT); 3511 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3512 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3513 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3514 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3515 3516 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3517 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3518 SDValue ShiftLeftHi = 3519 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3520 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3521 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3522 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3523 SDValue HiFalse = 3524 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3525 3526 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3527 3528 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3529 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3530 3531 SDValue Parts[2] = {Lo, Hi}; 3532 return DAG.getMergeValues(Parts, DL); 3533 } 3534 3535 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3536 // legal equivalently-sized i8 type, so we can use that as a go-between. 3537 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3538 SelectionDAG &DAG) const { 3539 SDLoc DL(Op); 3540 MVT VT = Op.getSimpleValueType(); 3541 SDValue SplatVal = Op.getOperand(0); 3542 // All-zeros or all-ones splats are handled specially. 3543 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3544 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3545 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3546 } 3547 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3548 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3549 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3550 } 3551 MVT XLenVT = Subtarget.getXLenVT(); 3552 assert(SplatVal.getValueType() == XLenVT && 3553 "Unexpected type for i1 splat value"); 3554 MVT InterVT = VT.changeVectorElementType(MVT::i8); 3555 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 3556 DAG.getConstant(1, DL, XLenVT)); 3557 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 3558 SDValue Zero = DAG.getConstant(0, DL, InterVT); 3559 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 3560 } 3561 3562 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 3563 // illegal (currently only vXi64 RV32). 3564 // FIXME: We could also catch non-constant sign-extended i32 values and lower 3565 // them to SPLAT_VECTOR_I64 3566 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 3567 SelectionDAG &DAG) const { 3568 SDLoc DL(Op); 3569 MVT VecVT = Op.getSimpleValueType(); 3570 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 3571 "Unexpected SPLAT_VECTOR_PARTS lowering"); 3572 3573 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 3574 SDValue Lo = Op.getOperand(0); 3575 SDValue Hi = Op.getOperand(1); 3576 3577 if (VecVT.isFixedLengthVector()) { 3578 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3579 SDLoc DL(Op); 3580 SDValue Mask, VL; 3581 std::tie(Mask, VL) = 3582 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3583 3584 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 3585 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 3586 } 3587 3588 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 3589 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 3590 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 3591 // If Hi constant is all the same sign bit as Lo, lower this as a custom 3592 // node in order to try and match RVV vector/scalar instructions. 3593 if ((LoC >> 31) == HiC) 3594 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3595 } 3596 3597 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 3598 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 3599 isa<ConstantSDNode>(Hi.getOperand(1)) && 3600 Hi.getConstantOperandVal(1) == 31) 3601 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3602 3603 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 3604 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 3605 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64)); 3606 } 3607 3608 // Custom-lower extensions from mask vectors by using a vselect either with 1 3609 // for zero/any-extension or -1 for sign-extension: 3610 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 3611 // Note that any-extension is lowered identically to zero-extension. 3612 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 3613 int64_t ExtTrueVal) const { 3614 SDLoc DL(Op); 3615 MVT VecVT = Op.getSimpleValueType(); 3616 SDValue Src = Op.getOperand(0); 3617 // Only custom-lower extensions from mask types 3618 assert(Src.getValueType().isVector() && 3619 Src.getValueType().getVectorElementType() == MVT::i1); 3620 3621 MVT XLenVT = Subtarget.getXLenVT(); 3622 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 3623 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 3624 3625 if (VecVT.isScalableVector()) { 3626 // Be careful not to introduce illegal scalar types at this stage, and be 3627 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 3628 // illegal and must be expanded. Since we know that the constants are 3629 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 3630 bool IsRV32E64 = 3631 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 3632 3633 if (!IsRV32E64) { 3634 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 3635 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 3636 } else { 3637 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 3638 SplatTrueVal = 3639 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 3640 } 3641 3642 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 3643 } 3644 3645 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3646 MVT I1ContainerVT = 3647 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3648 3649 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 3650 3651 SDValue Mask, VL; 3652 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3653 3654 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 3655 SplatTrueVal = 3656 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 3657 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 3658 SplatTrueVal, SplatZero, VL); 3659 3660 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 3661 } 3662 3663 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 3664 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 3665 MVT ExtVT = Op.getSimpleValueType(); 3666 // Only custom-lower extensions from fixed-length vector types. 3667 if (!ExtVT.isFixedLengthVector()) 3668 return Op; 3669 MVT VT = Op.getOperand(0).getSimpleValueType(); 3670 // Grab the canonical container type for the extended type. Infer the smaller 3671 // type from that to ensure the same number of vector elements, as we know 3672 // the LMUL will be sufficient to hold the smaller type. 3673 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 3674 // Get the extended container type manually to ensure the same number of 3675 // vector elements between source and dest. 3676 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 3677 ContainerExtVT.getVectorElementCount()); 3678 3679 SDValue Op1 = 3680 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 3681 3682 SDLoc DL(Op); 3683 SDValue Mask, VL; 3684 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3685 3686 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 3687 3688 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 3689 } 3690 3691 // Custom-lower truncations from vectors to mask vectors by using a mask and a 3692 // setcc operation: 3693 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 3694 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 3695 SelectionDAG &DAG) const { 3696 SDLoc DL(Op); 3697 EVT MaskVT = Op.getValueType(); 3698 // Only expect to custom-lower truncations to mask types 3699 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 3700 "Unexpected type for vector mask lowering"); 3701 SDValue Src = Op.getOperand(0); 3702 MVT VecVT = Src.getSimpleValueType(); 3703 3704 // If this is a fixed vector, we need to convert it to a scalable vector. 3705 MVT ContainerVT = VecVT; 3706 if (VecVT.isFixedLengthVector()) { 3707 ContainerVT = getContainerForFixedLengthVector(VecVT); 3708 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3709 } 3710 3711 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 3712 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 3713 3714 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 3715 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 3716 3717 if (VecVT.isScalableVector()) { 3718 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 3719 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 3720 } 3721 3722 SDValue Mask, VL; 3723 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3724 3725 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 3726 SDValue Trunc = 3727 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 3728 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 3729 DAG.getCondCode(ISD::SETNE), Mask, VL); 3730 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 3731 } 3732 3733 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 3734 // first position of a vector, and that vector is slid up to the insert index. 3735 // By limiting the active vector length to index+1 and merging with the 3736 // original vector (with an undisturbed tail policy for elements >= VL), we 3737 // achieve the desired result of leaving all elements untouched except the one 3738 // at VL-1, which is replaced with the desired value. 3739 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3740 SelectionDAG &DAG) const { 3741 SDLoc DL(Op); 3742 MVT VecVT = Op.getSimpleValueType(); 3743 SDValue Vec = Op.getOperand(0); 3744 SDValue Val = Op.getOperand(1); 3745 SDValue Idx = Op.getOperand(2); 3746 3747 if (VecVT.getVectorElementType() == MVT::i1) { 3748 // FIXME: For now we just promote to an i8 vector and insert into that, 3749 // but this is probably not optimal. 3750 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3751 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3752 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 3753 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 3754 } 3755 3756 MVT ContainerVT = VecVT; 3757 // If the operand is a fixed-length vector, convert to a scalable one. 3758 if (VecVT.isFixedLengthVector()) { 3759 ContainerVT = getContainerForFixedLengthVector(VecVT); 3760 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3761 } 3762 3763 MVT XLenVT = Subtarget.getXLenVT(); 3764 3765 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3766 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 3767 // Even i64-element vectors on RV32 can be lowered without scalar 3768 // legalization if the most-significant 32 bits of the value are not affected 3769 // by the sign-extension of the lower 32 bits. 3770 // TODO: We could also catch sign extensions of a 32-bit value. 3771 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 3772 const auto *CVal = cast<ConstantSDNode>(Val); 3773 if (isInt<32>(CVal->getSExtValue())) { 3774 IsLegalInsert = true; 3775 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3776 } 3777 } 3778 3779 SDValue Mask, VL; 3780 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3781 3782 SDValue ValInVec; 3783 3784 if (IsLegalInsert) { 3785 unsigned Opc = 3786 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 3787 if (isNullConstant(Idx)) { 3788 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 3789 if (!VecVT.isFixedLengthVector()) 3790 return Vec; 3791 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 3792 } 3793 ValInVec = 3794 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 3795 } else { 3796 // On RV32, i64-element vectors must be specially handled to place the 3797 // value at element 0, by using two vslide1up instructions in sequence on 3798 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 3799 // this. 3800 SDValue One = DAG.getConstant(1, DL, XLenVT); 3801 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 3802 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 3803 MVT I32ContainerVT = 3804 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 3805 SDValue I32Mask = 3806 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 3807 // Limit the active VL to two. 3808 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 3809 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 3810 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 3811 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 3812 InsertI64VL); 3813 // First slide in the hi value, then the lo in underneath it. 3814 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3815 ValHi, I32Mask, InsertI64VL); 3816 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3817 ValLo, I32Mask, InsertI64VL); 3818 // Bitcast back to the right container type. 3819 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 3820 } 3821 3822 // Now that the value is in a vector, slide it into position. 3823 SDValue InsertVL = 3824 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 3825 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 3826 ValInVec, Idx, Mask, InsertVL); 3827 if (!VecVT.isFixedLengthVector()) 3828 return Slideup; 3829 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 3830 } 3831 3832 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 3833 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 3834 // types this is done using VMV_X_S to allow us to glean information about the 3835 // sign bits of the result. 3836 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 3837 SelectionDAG &DAG) const { 3838 SDLoc DL(Op); 3839 SDValue Idx = Op.getOperand(1); 3840 SDValue Vec = Op.getOperand(0); 3841 EVT EltVT = Op.getValueType(); 3842 MVT VecVT = Vec.getSimpleValueType(); 3843 MVT XLenVT = Subtarget.getXLenVT(); 3844 3845 if (VecVT.getVectorElementType() == MVT::i1) { 3846 // FIXME: For now we just promote to an i8 vector and extract from that, 3847 // but this is probably not optimal. 3848 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3849 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3850 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 3851 } 3852 3853 // If this is a fixed vector, we need to convert it to a scalable vector. 3854 MVT ContainerVT = VecVT; 3855 if (VecVT.isFixedLengthVector()) { 3856 ContainerVT = getContainerForFixedLengthVector(VecVT); 3857 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3858 } 3859 3860 // If the index is 0, the vector is already in the right position. 3861 if (!isNullConstant(Idx)) { 3862 // Use a VL of 1 to avoid processing more elements than we need. 3863 SDValue VL = DAG.getConstant(1, DL, XLenVT); 3864 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3865 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 3866 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 3867 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 3868 } 3869 3870 if (!EltVT.isInteger()) { 3871 // Floating-point extracts are handled in TableGen. 3872 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 3873 DAG.getConstant(0, DL, XLenVT)); 3874 } 3875 3876 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 3877 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 3878 } 3879 3880 // Some RVV intrinsics may claim that they want an integer operand to be 3881 // promoted or expanded. 3882 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 3883 const RISCVSubtarget &Subtarget) { 3884 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3885 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 3886 "Unexpected opcode"); 3887 3888 if (!Subtarget.hasVInstructions()) 3889 return SDValue(); 3890 3891 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 3892 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 3893 SDLoc DL(Op); 3894 3895 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 3896 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 3897 if (!II || !II->SplatOperand) 3898 return SDValue(); 3899 3900 unsigned SplatOp = II->SplatOperand + HasChain; 3901 assert(SplatOp < Op.getNumOperands()); 3902 3903 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 3904 SDValue &ScalarOp = Operands[SplatOp]; 3905 MVT OpVT = ScalarOp.getSimpleValueType(); 3906 MVT XLenVT = Subtarget.getXLenVT(); 3907 3908 // If this isn't a scalar, or its type is XLenVT we're done. 3909 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 3910 return SDValue(); 3911 3912 // Simplest case is that the operand needs to be promoted to XLenVT. 3913 if (OpVT.bitsLT(XLenVT)) { 3914 // If the operand is a constant, sign extend to increase our chances 3915 // of being able to use a .vi instruction. ANY_EXTEND would become a 3916 // a zero extend and the simm5 check in isel would fail. 3917 // FIXME: Should we ignore the upper bits in isel instead? 3918 unsigned ExtOpc = 3919 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 3920 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 3921 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3922 } 3923 3924 // Use the previous operand to get the vXi64 VT. The result might be a mask 3925 // VT for compares. Using the previous operand assumes that the previous 3926 // operand will never have a smaller element size than a scalar operand and 3927 // that a widening operation never uses SEW=64. 3928 // NOTE: If this fails the below assert, we can probably just find the 3929 // element count from any operand or result and use it to construct the VT. 3930 assert(II->SplatOperand > 1 && "Unexpected splat operand!"); 3931 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 3932 3933 // The more complex case is when the scalar is larger than XLenVT. 3934 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 3935 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 3936 3937 // If this is a sign-extended 32-bit constant, we can truncate it and rely 3938 // on the instruction to sign-extend since SEW>XLEN. 3939 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 3940 if (isInt<32>(CVal->getSExtValue())) { 3941 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3942 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3943 } 3944 } 3945 3946 // We need to convert the scalar to a splat vector. 3947 // FIXME: Can we implicitly truncate the scalar if it is known to 3948 // be sign extended? 3949 // VL should be the last operand. 3950 SDValue VL = Op.getOperand(Op.getNumOperands() - 1); 3951 assert(VL.getValueType() == XLenVT); 3952 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 3953 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3954 } 3955 3956 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3957 SelectionDAG &DAG) const { 3958 unsigned IntNo = Op.getConstantOperandVal(0); 3959 SDLoc DL(Op); 3960 MVT XLenVT = Subtarget.getXLenVT(); 3961 3962 switch (IntNo) { 3963 default: 3964 break; // Don't custom lower most intrinsics. 3965 case Intrinsic::thread_pointer: { 3966 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3967 return DAG.getRegister(RISCV::X4, PtrVT); 3968 } 3969 case Intrinsic::riscv_orc_b: 3970 // Lower to the GORCI encoding for orc.b. 3971 return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1), 3972 DAG.getConstant(7, DL, XLenVT)); 3973 case Intrinsic::riscv_grev: 3974 case Intrinsic::riscv_gorc: { 3975 unsigned Opc = 3976 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 3977 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3978 } 3979 case Intrinsic::riscv_shfl: 3980 case Intrinsic::riscv_unshfl: { 3981 unsigned Opc = 3982 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 3983 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3984 } 3985 case Intrinsic::riscv_bcompress: 3986 case Intrinsic::riscv_bdecompress: { 3987 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 3988 : RISCVISD::BDECOMPRESS; 3989 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3990 } 3991 case Intrinsic::riscv_vmv_x_s: 3992 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 3993 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 3994 Op.getOperand(1)); 3995 case Intrinsic::riscv_vmv_v_x: 3996 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 3997 Op.getSimpleValueType(), DL, DAG, Subtarget); 3998 case Intrinsic::riscv_vfmv_v_f: 3999 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4000 Op.getOperand(1), Op.getOperand(2)); 4001 case Intrinsic::riscv_vmv_s_x: { 4002 SDValue Scalar = Op.getOperand(2); 4003 4004 if (Scalar.getValueType().bitsLE(XLenVT)) { 4005 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4006 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4007 Op.getOperand(1), Scalar, Op.getOperand(3)); 4008 } 4009 4010 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4011 4012 // This is an i64 value that lives in two scalar registers. We have to 4013 // insert this in a convoluted way. First we build vXi64 splat containing 4014 // the/ two values that we assemble using some bit math. Next we'll use 4015 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4016 // to merge element 0 from our splat into the source vector. 4017 // FIXME: This is probably not the best way to do this, but it is 4018 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4019 // point. 4020 // sw lo, (a0) 4021 // sw hi, 4(a0) 4022 // vlse vX, (a0) 4023 // 4024 // vid.v vVid 4025 // vmseq.vx mMask, vVid, 0 4026 // vmerge.vvm vDest, vSrc, vVal, mMask 4027 MVT VT = Op.getSimpleValueType(); 4028 SDValue Vec = Op.getOperand(1); 4029 SDValue VL = Op.getOperand(3); 4030 4031 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 4032 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4033 DAG.getConstant(0, DL, MVT::i32), VL); 4034 4035 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4036 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4037 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4038 SDValue SelectCond = 4039 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4040 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4041 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4042 Vec, VL); 4043 } 4044 case Intrinsic::riscv_vslide1up: 4045 case Intrinsic::riscv_vslide1down: 4046 case Intrinsic::riscv_vslide1up_mask: 4047 case Intrinsic::riscv_vslide1down_mask: { 4048 // We need to special case these when the scalar is larger than XLen. 4049 unsigned NumOps = Op.getNumOperands(); 4050 bool IsMasked = NumOps == 7; 4051 unsigned OpOffset = IsMasked ? 1 : 0; 4052 SDValue Scalar = Op.getOperand(2 + OpOffset); 4053 if (Scalar.getValueType().bitsLE(XLenVT)) 4054 break; 4055 4056 // Splatting a sign extended constant is fine. 4057 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4058 if (isInt<32>(CVal->getSExtValue())) 4059 break; 4060 4061 MVT VT = Op.getSimpleValueType(); 4062 assert(VT.getVectorElementType() == MVT::i64 && 4063 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4064 4065 // Convert the vector source to the equivalent nxvXi32 vector. 4066 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4067 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 4068 4069 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4070 DAG.getConstant(0, DL, XLenVT)); 4071 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4072 DAG.getConstant(1, DL, XLenVT)); 4073 4074 // Double the VL since we halved SEW. 4075 SDValue VL = Op.getOperand(NumOps - (1 + OpOffset)); 4076 SDValue I32VL = 4077 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4078 4079 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4080 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4081 4082 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4083 // instructions. 4084 if (IntNo == Intrinsic::riscv_vslide1up || 4085 IntNo == Intrinsic::riscv_vslide1up_mask) { 4086 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 4087 I32Mask, I32VL); 4088 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 4089 I32Mask, I32VL); 4090 } else { 4091 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 4092 I32Mask, I32VL); 4093 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 4094 I32Mask, I32VL); 4095 } 4096 4097 // Convert back to nxvXi64. 4098 Vec = DAG.getBitcast(VT, Vec); 4099 4100 if (!IsMasked) 4101 return Vec; 4102 4103 // Apply mask after the operation. 4104 SDValue Mask = Op.getOperand(NumOps - 3); 4105 SDValue MaskedOff = Op.getOperand(1); 4106 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4107 } 4108 } 4109 4110 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4111 } 4112 4113 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4114 SelectionDAG &DAG) const { 4115 unsigned IntNo = Op.getConstantOperandVal(1); 4116 switch (IntNo) { 4117 default: 4118 break; 4119 case Intrinsic::riscv_masked_strided_load: { 4120 SDLoc DL(Op); 4121 MVT XLenVT = Subtarget.getXLenVT(); 4122 4123 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4124 // the selection of the masked intrinsics doesn't do this for us. 4125 SDValue Mask = Op.getOperand(5); 4126 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4127 4128 MVT VT = Op->getSimpleValueType(0); 4129 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4130 4131 SDValue PassThru = Op.getOperand(2); 4132 if (!IsUnmasked) { 4133 MVT MaskVT = 4134 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4135 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4136 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4137 } 4138 4139 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4140 4141 SDValue IntID = DAG.getTargetConstant( 4142 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4143 XLenVT); 4144 4145 auto *Load = cast<MemIntrinsicSDNode>(Op); 4146 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4147 if (!IsUnmasked) 4148 Ops.push_back(PassThru); 4149 Ops.push_back(Op.getOperand(3)); // Ptr 4150 Ops.push_back(Op.getOperand(4)); // Stride 4151 if (!IsUnmasked) 4152 Ops.push_back(Mask); 4153 Ops.push_back(VL); 4154 if (!IsUnmasked) { 4155 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4156 Ops.push_back(Policy); 4157 } 4158 4159 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4160 SDValue Result = 4161 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4162 Load->getMemoryVT(), Load->getMemOperand()); 4163 SDValue Chain = Result.getValue(1); 4164 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4165 return DAG.getMergeValues({Result, Chain}, DL); 4166 } 4167 } 4168 4169 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4170 } 4171 4172 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4173 SelectionDAG &DAG) const { 4174 unsigned IntNo = Op.getConstantOperandVal(1); 4175 switch (IntNo) { 4176 default: 4177 break; 4178 case Intrinsic::riscv_masked_strided_store: { 4179 SDLoc DL(Op); 4180 MVT XLenVT = Subtarget.getXLenVT(); 4181 4182 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4183 // the selection of the masked intrinsics doesn't do this for us. 4184 SDValue Mask = Op.getOperand(5); 4185 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4186 4187 SDValue Val = Op.getOperand(2); 4188 MVT VT = Val.getSimpleValueType(); 4189 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4190 4191 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4192 if (!IsUnmasked) { 4193 MVT MaskVT = 4194 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4195 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4196 } 4197 4198 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4199 4200 SDValue IntID = DAG.getTargetConstant( 4201 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4202 XLenVT); 4203 4204 auto *Store = cast<MemIntrinsicSDNode>(Op); 4205 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4206 Ops.push_back(Val); 4207 Ops.push_back(Op.getOperand(3)); // Ptr 4208 Ops.push_back(Op.getOperand(4)); // Stride 4209 if (!IsUnmasked) 4210 Ops.push_back(Mask); 4211 Ops.push_back(VL); 4212 4213 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4214 Ops, Store->getMemoryVT(), 4215 Store->getMemOperand()); 4216 } 4217 } 4218 4219 return SDValue(); 4220 } 4221 4222 static MVT getLMUL1VT(MVT VT) { 4223 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4224 "Unexpected vector MVT"); 4225 return MVT::getScalableVectorVT( 4226 VT.getVectorElementType(), 4227 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4228 } 4229 4230 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4231 switch (ISDOpcode) { 4232 default: 4233 llvm_unreachable("Unhandled reduction"); 4234 case ISD::VECREDUCE_ADD: 4235 return RISCVISD::VECREDUCE_ADD_VL; 4236 case ISD::VECREDUCE_UMAX: 4237 return RISCVISD::VECREDUCE_UMAX_VL; 4238 case ISD::VECREDUCE_SMAX: 4239 return RISCVISD::VECREDUCE_SMAX_VL; 4240 case ISD::VECREDUCE_UMIN: 4241 return RISCVISD::VECREDUCE_UMIN_VL; 4242 case ISD::VECREDUCE_SMIN: 4243 return RISCVISD::VECREDUCE_SMIN_VL; 4244 case ISD::VECREDUCE_AND: 4245 return RISCVISD::VECREDUCE_AND_VL; 4246 case ISD::VECREDUCE_OR: 4247 return RISCVISD::VECREDUCE_OR_VL; 4248 case ISD::VECREDUCE_XOR: 4249 return RISCVISD::VECREDUCE_XOR_VL; 4250 } 4251 } 4252 4253 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4254 SelectionDAG &DAG, 4255 bool IsVP) const { 4256 SDLoc DL(Op); 4257 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4258 MVT VecVT = Vec.getSimpleValueType(); 4259 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4260 Op.getOpcode() == ISD::VECREDUCE_OR || 4261 Op.getOpcode() == ISD::VECREDUCE_XOR || 4262 Op.getOpcode() == ISD::VP_REDUCE_AND || 4263 Op.getOpcode() == ISD::VP_REDUCE_OR || 4264 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4265 "Unexpected reduction lowering"); 4266 4267 MVT XLenVT = Subtarget.getXLenVT(); 4268 assert(Op.getValueType() == XLenVT && 4269 "Expected reduction output to be legalized to XLenVT"); 4270 4271 MVT ContainerVT = VecVT; 4272 if (VecVT.isFixedLengthVector()) { 4273 ContainerVT = getContainerForFixedLengthVector(VecVT); 4274 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4275 } 4276 4277 SDValue Mask, VL; 4278 if (IsVP) { 4279 Mask = Op.getOperand(2); 4280 VL = Op.getOperand(3); 4281 } else { 4282 std::tie(Mask, VL) = 4283 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4284 } 4285 4286 unsigned BaseOpc; 4287 ISD::CondCode CC; 4288 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4289 4290 switch (Op.getOpcode()) { 4291 default: 4292 llvm_unreachable("Unhandled reduction"); 4293 case ISD::VECREDUCE_AND: 4294 case ISD::VP_REDUCE_AND: { 4295 // vcpop ~x == 0 4296 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4297 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4298 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4299 CC = ISD::SETEQ; 4300 BaseOpc = ISD::AND; 4301 break; 4302 } 4303 case ISD::VECREDUCE_OR: 4304 case ISD::VP_REDUCE_OR: 4305 // vcpop x != 0 4306 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4307 CC = ISD::SETNE; 4308 BaseOpc = ISD::OR; 4309 break; 4310 case ISD::VECREDUCE_XOR: 4311 case ISD::VP_REDUCE_XOR: { 4312 // ((vcpop x) & 1) != 0 4313 SDValue One = DAG.getConstant(1, DL, XLenVT); 4314 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4315 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4316 CC = ISD::SETNE; 4317 BaseOpc = ISD::XOR; 4318 break; 4319 } 4320 } 4321 4322 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4323 4324 if (!IsVP) 4325 return SetCC; 4326 4327 // Now include the start value in the operation. 4328 // Note that we must return the start value when no elements are operated 4329 // upon. The vcpop instructions we've emitted in each case above will return 4330 // 0 for an inactive vector, and so we've already received the neutral value: 4331 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4332 // can simply include the start value. 4333 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4334 } 4335 4336 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4337 SelectionDAG &DAG) const { 4338 SDLoc DL(Op); 4339 SDValue Vec = Op.getOperand(0); 4340 EVT VecEVT = Vec.getValueType(); 4341 4342 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4343 4344 // Due to ordering in legalize types we may have a vector type that needs to 4345 // be split. Do that manually so we can get down to a legal type. 4346 while (getTypeAction(*DAG.getContext(), VecEVT) == 4347 TargetLowering::TypeSplitVector) { 4348 SDValue Lo, Hi; 4349 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4350 VecEVT = Lo.getValueType(); 4351 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4352 } 4353 4354 // TODO: The type may need to be widened rather than split. Or widened before 4355 // it can be split. 4356 if (!isTypeLegal(VecEVT)) 4357 return SDValue(); 4358 4359 MVT VecVT = VecEVT.getSimpleVT(); 4360 MVT VecEltVT = VecVT.getVectorElementType(); 4361 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4362 4363 MVT ContainerVT = VecVT; 4364 if (VecVT.isFixedLengthVector()) { 4365 ContainerVT = getContainerForFixedLengthVector(VecVT); 4366 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4367 } 4368 4369 MVT M1VT = getLMUL1VT(ContainerVT); 4370 4371 SDValue Mask, VL; 4372 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4373 4374 // FIXME: This is a VLMAX splat which might be too large and can prevent 4375 // vsetvli removal. 4376 SDValue NeutralElem = 4377 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4378 SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem); 4379 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4380 IdentitySplat, Mask, VL); 4381 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4382 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4383 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4384 } 4385 4386 // Given a reduction op, this function returns the matching reduction opcode, 4387 // the vector SDValue and the scalar SDValue required to lower this to a 4388 // RISCVISD node. 4389 static std::tuple<unsigned, SDValue, SDValue> 4390 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4391 SDLoc DL(Op); 4392 auto Flags = Op->getFlags(); 4393 unsigned Opcode = Op.getOpcode(); 4394 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4395 switch (Opcode) { 4396 default: 4397 llvm_unreachable("Unhandled reduction"); 4398 case ISD::VECREDUCE_FADD: 4399 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), 4400 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4401 case ISD::VECREDUCE_SEQ_FADD: 4402 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4403 Op.getOperand(0)); 4404 case ISD::VECREDUCE_FMIN: 4405 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4406 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4407 case ISD::VECREDUCE_FMAX: 4408 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4409 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4410 } 4411 } 4412 4413 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4414 SelectionDAG &DAG) const { 4415 SDLoc DL(Op); 4416 MVT VecEltVT = Op.getSimpleValueType(); 4417 4418 unsigned RVVOpcode; 4419 SDValue VectorVal, ScalarVal; 4420 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4421 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4422 MVT VecVT = VectorVal.getSimpleValueType(); 4423 4424 MVT ContainerVT = VecVT; 4425 if (VecVT.isFixedLengthVector()) { 4426 ContainerVT = getContainerForFixedLengthVector(VecVT); 4427 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4428 } 4429 4430 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4431 4432 SDValue Mask, VL; 4433 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4434 4435 // FIXME: This is a VLMAX splat which might be too large and can prevent 4436 // vsetvli removal. 4437 SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal); 4438 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4439 VectorVal, ScalarSplat, Mask, VL); 4440 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4441 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4442 } 4443 4444 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4445 switch (ISDOpcode) { 4446 default: 4447 llvm_unreachable("Unhandled reduction"); 4448 case ISD::VP_REDUCE_ADD: 4449 return RISCVISD::VECREDUCE_ADD_VL; 4450 case ISD::VP_REDUCE_UMAX: 4451 return RISCVISD::VECREDUCE_UMAX_VL; 4452 case ISD::VP_REDUCE_SMAX: 4453 return RISCVISD::VECREDUCE_SMAX_VL; 4454 case ISD::VP_REDUCE_UMIN: 4455 return RISCVISD::VECREDUCE_UMIN_VL; 4456 case ISD::VP_REDUCE_SMIN: 4457 return RISCVISD::VECREDUCE_SMIN_VL; 4458 case ISD::VP_REDUCE_AND: 4459 return RISCVISD::VECREDUCE_AND_VL; 4460 case ISD::VP_REDUCE_OR: 4461 return RISCVISD::VECREDUCE_OR_VL; 4462 case ISD::VP_REDUCE_XOR: 4463 return RISCVISD::VECREDUCE_XOR_VL; 4464 case ISD::VP_REDUCE_FADD: 4465 return RISCVISD::VECREDUCE_FADD_VL; 4466 case ISD::VP_REDUCE_SEQ_FADD: 4467 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 4468 case ISD::VP_REDUCE_FMAX: 4469 return RISCVISD::VECREDUCE_FMAX_VL; 4470 case ISD::VP_REDUCE_FMIN: 4471 return RISCVISD::VECREDUCE_FMIN_VL; 4472 } 4473 } 4474 4475 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 4476 SelectionDAG &DAG) const { 4477 SDLoc DL(Op); 4478 SDValue Vec = Op.getOperand(1); 4479 EVT VecEVT = Vec.getValueType(); 4480 4481 // TODO: The type may need to be widened rather than split. Or widened before 4482 // it can be split. 4483 if (!isTypeLegal(VecEVT)) 4484 return SDValue(); 4485 4486 MVT VecVT = VecEVT.getSimpleVT(); 4487 MVT VecEltVT = VecVT.getVectorElementType(); 4488 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 4489 4490 MVT ContainerVT = VecVT; 4491 if (VecVT.isFixedLengthVector()) { 4492 ContainerVT = getContainerForFixedLengthVector(VecVT); 4493 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4494 } 4495 4496 SDValue VL = Op.getOperand(3); 4497 SDValue Mask = Op.getOperand(2); 4498 4499 MVT M1VT = getLMUL1VT(ContainerVT); 4500 MVT XLenVT = Subtarget.getXLenVT(); 4501 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 4502 4503 // FIXME: This is a VLMAX splat which might be too large and can prevent 4504 // vsetvli removal. 4505 SDValue StartSplat = DAG.getSplatVector(M1VT, DL, Op.getOperand(0)); 4506 SDValue Reduction = 4507 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 4508 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 4509 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4510 if (!VecVT.isInteger()) 4511 return Elt0; 4512 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4513 } 4514 4515 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4516 SelectionDAG &DAG) const { 4517 SDValue Vec = Op.getOperand(0); 4518 SDValue SubVec = Op.getOperand(1); 4519 MVT VecVT = Vec.getSimpleValueType(); 4520 MVT SubVecVT = SubVec.getSimpleValueType(); 4521 4522 SDLoc DL(Op); 4523 MVT XLenVT = Subtarget.getXLenVT(); 4524 unsigned OrigIdx = Op.getConstantOperandVal(2); 4525 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4526 4527 // We don't have the ability to slide mask vectors up indexed by their i1 4528 // elements; the smallest we can do is i8. Often we are able to bitcast to 4529 // equivalent i8 vectors. Note that when inserting a fixed-length vector 4530 // into a scalable one, we might not necessarily have enough scalable 4531 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 4532 if (SubVecVT.getVectorElementType() == MVT::i1 && 4533 (OrigIdx != 0 || !Vec.isUndef())) { 4534 if (VecVT.getVectorMinNumElements() >= 8 && 4535 SubVecVT.getVectorMinNumElements() >= 8) { 4536 assert(OrigIdx % 8 == 0 && "Invalid index"); 4537 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4538 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4539 "Unexpected mask vector lowering"); 4540 OrigIdx /= 8; 4541 SubVecVT = 4542 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4543 SubVecVT.isScalableVector()); 4544 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4545 VecVT.isScalableVector()); 4546 Vec = DAG.getBitcast(VecVT, Vec); 4547 SubVec = DAG.getBitcast(SubVecVT, SubVec); 4548 } else { 4549 // We can't slide this mask vector up indexed by its i1 elements. 4550 // This poses a problem when we wish to insert a scalable vector which 4551 // can't be re-expressed as a larger type. Just choose the slow path and 4552 // extend to a larger type, then truncate back down. 4553 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4554 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4555 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4556 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 4557 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 4558 Op.getOperand(2)); 4559 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 4560 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 4561 } 4562 } 4563 4564 // If the subvector vector is a fixed-length type, we cannot use subregister 4565 // manipulation to simplify the codegen; we don't know which register of a 4566 // LMUL group contains the specific subvector as we only know the minimum 4567 // register size. Therefore we must slide the vector group up the full 4568 // amount. 4569 if (SubVecVT.isFixedLengthVector()) { 4570 if (OrigIdx == 0 && Vec.isUndef()) 4571 return Op; 4572 MVT ContainerVT = VecVT; 4573 if (VecVT.isFixedLengthVector()) { 4574 ContainerVT = getContainerForFixedLengthVector(VecVT); 4575 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4576 } 4577 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 4578 DAG.getUNDEF(ContainerVT), SubVec, 4579 DAG.getConstant(0, DL, XLenVT)); 4580 SDValue Mask = 4581 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4582 // Set the vector length to only the number of elements we care about. Note 4583 // that for slideup this includes the offset. 4584 SDValue VL = 4585 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 4586 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4587 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4588 SubVec, SlideupAmt, Mask, VL); 4589 if (VecVT.isFixedLengthVector()) 4590 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4591 return DAG.getBitcast(Op.getValueType(), Slideup); 4592 } 4593 4594 unsigned SubRegIdx, RemIdx; 4595 std::tie(SubRegIdx, RemIdx) = 4596 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4597 VecVT, SubVecVT, OrigIdx, TRI); 4598 4599 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 4600 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 4601 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 4602 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 4603 4604 // 1. If the Idx has been completely eliminated and this subvector's size is 4605 // a vector register or a multiple thereof, or the surrounding elements are 4606 // undef, then this is a subvector insert which naturally aligns to a vector 4607 // register. These can easily be handled using subregister manipulation. 4608 // 2. If the subvector is smaller than a vector register, then the insertion 4609 // must preserve the undisturbed elements of the register. We do this by 4610 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 4611 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 4612 // subvector within the vector register, and an INSERT_SUBVECTOR of that 4613 // LMUL=1 type back into the larger vector (resolving to another subregister 4614 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 4615 // to avoid allocating a large register group to hold our subvector. 4616 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 4617 return Op; 4618 4619 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 4620 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 4621 // (in our case undisturbed). This means we can set up a subvector insertion 4622 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 4623 // size of the subvector. 4624 MVT InterSubVT = VecVT; 4625 SDValue AlignedExtract = Vec; 4626 unsigned AlignedIdx = OrigIdx - RemIdx; 4627 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4628 InterSubVT = getLMUL1VT(VecVT); 4629 // Extract a subvector equal to the nearest full vector register type. This 4630 // should resolve to a EXTRACT_SUBREG instruction. 4631 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4632 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4633 } 4634 4635 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4636 // For scalable vectors this must be further multiplied by vscale. 4637 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 4638 4639 SDValue Mask, VL; 4640 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4641 4642 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 4643 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 4644 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 4645 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 4646 4647 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 4648 DAG.getUNDEF(InterSubVT), SubVec, 4649 DAG.getConstant(0, DL, XLenVT)); 4650 4651 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 4652 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 4653 4654 // If required, insert this subvector back into the correct vector register. 4655 // This should resolve to an INSERT_SUBREG instruction. 4656 if (VecVT.bitsGT(InterSubVT)) 4657 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 4658 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4659 4660 // We might have bitcast from a mask type: cast back to the original type if 4661 // required. 4662 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 4663 } 4664 4665 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 4666 SelectionDAG &DAG) const { 4667 SDValue Vec = Op.getOperand(0); 4668 MVT SubVecVT = Op.getSimpleValueType(); 4669 MVT VecVT = Vec.getSimpleValueType(); 4670 4671 SDLoc DL(Op); 4672 MVT XLenVT = Subtarget.getXLenVT(); 4673 unsigned OrigIdx = Op.getConstantOperandVal(1); 4674 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4675 4676 // We don't have the ability to slide mask vectors down indexed by their i1 4677 // elements; the smallest we can do is i8. Often we are able to bitcast to 4678 // equivalent i8 vectors. Note that when extracting a fixed-length vector 4679 // from a scalable one, we might not necessarily have enough scalable 4680 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 4681 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 4682 if (VecVT.getVectorMinNumElements() >= 8 && 4683 SubVecVT.getVectorMinNumElements() >= 8) { 4684 assert(OrigIdx % 8 == 0 && "Invalid index"); 4685 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4686 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4687 "Unexpected mask vector lowering"); 4688 OrigIdx /= 8; 4689 SubVecVT = 4690 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4691 SubVecVT.isScalableVector()); 4692 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4693 VecVT.isScalableVector()); 4694 Vec = DAG.getBitcast(VecVT, Vec); 4695 } else { 4696 // We can't slide this mask vector down, indexed by its i1 elements. 4697 // This poses a problem when we wish to extract a scalable vector which 4698 // can't be re-expressed as a larger type. Just choose the slow path and 4699 // extend to a larger type, then truncate back down. 4700 // TODO: We could probably improve this when extracting certain fixed 4701 // from fixed, where we can extract as i8 and shift the correct element 4702 // right to reach the desired subvector? 4703 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4704 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4705 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4706 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 4707 Op.getOperand(1)); 4708 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 4709 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 4710 } 4711 } 4712 4713 // If the subvector vector is a fixed-length type, we cannot use subregister 4714 // manipulation to simplify the codegen; we don't know which register of a 4715 // LMUL group contains the specific subvector as we only know the minimum 4716 // register size. Therefore we must slide the vector group down the full 4717 // amount. 4718 if (SubVecVT.isFixedLengthVector()) { 4719 // With an index of 0 this is a cast-like subvector, which can be performed 4720 // with subregister operations. 4721 if (OrigIdx == 0) 4722 return Op; 4723 MVT ContainerVT = VecVT; 4724 if (VecVT.isFixedLengthVector()) { 4725 ContainerVT = getContainerForFixedLengthVector(VecVT); 4726 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4727 } 4728 SDValue Mask = 4729 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4730 // Set the vector length to only the number of elements we care about. This 4731 // avoids sliding down elements we're going to discard straight away. 4732 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 4733 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4734 SDValue Slidedown = 4735 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4736 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 4737 // Now we can use a cast-like subvector extract to get the result. 4738 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4739 DAG.getConstant(0, DL, XLenVT)); 4740 return DAG.getBitcast(Op.getValueType(), Slidedown); 4741 } 4742 4743 unsigned SubRegIdx, RemIdx; 4744 std::tie(SubRegIdx, RemIdx) = 4745 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4746 VecVT, SubVecVT, OrigIdx, TRI); 4747 4748 // If the Idx has been completely eliminated then this is a subvector extract 4749 // which naturally aligns to a vector register. These can easily be handled 4750 // using subregister manipulation. 4751 if (RemIdx == 0) 4752 return Op; 4753 4754 // Else we must shift our vector register directly to extract the subvector. 4755 // Do this using VSLIDEDOWN. 4756 4757 // If the vector type is an LMUL-group type, extract a subvector equal to the 4758 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 4759 // instruction. 4760 MVT InterSubVT = VecVT; 4761 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4762 InterSubVT = getLMUL1VT(VecVT); 4763 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4764 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 4765 } 4766 4767 // Slide this vector register down by the desired number of elements in order 4768 // to place the desired subvector starting at element 0. 4769 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4770 // For scalable vectors this must be further multiplied by vscale. 4771 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 4772 4773 SDValue Mask, VL; 4774 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 4775 SDValue Slidedown = 4776 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 4777 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 4778 4779 // Now the vector is in the right position, extract our final subvector. This 4780 // should resolve to a COPY. 4781 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4782 DAG.getConstant(0, DL, XLenVT)); 4783 4784 // We might have bitcast from a mask type: cast back to the original type if 4785 // required. 4786 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 4787 } 4788 4789 // Lower step_vector to the vid instruction. Any non-identity step value must 4790 // be accounted for my manual expansion. 4791 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 4792 SelectionDAG &DAG) const { 4793 SDLoc DL(Op); 4794 MVT VT = Op.getSimpleValueType(); 4795 MVT XLenVT = Subtarget.getXLenVT(); 4796 SDValue Mask, VL; 4797 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 4798 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4799 uint64_t StepValImm = Op.getConstantOperandVal(0); 4800 if (StepValImm != 1) { 4801 if (isPowerOf2_64(StepValImm)) { 4802 SDValue StepVal = 4803 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4804 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 4805 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 4806 } else { 4807 SDValue StepVal = lowerScalarSplat( 4808 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 4809 DL, DAG, Subtarget); 4810 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 4811 } 4812 } 4813 return StepVec; 4814 } 4815 4816 // Implement vector_reverse using vrgather.vv with indices determined by 4817 // subtracting the id of each element from (VLMAX-1). This will convert 4818 // the indices like so: 4819 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 4820 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 4821 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 4822 SelectionDAG &DAG) const { 4823 SDLoc DL(Op); 4824 MVT VecVT = Op.getSimpleValueType(); 4825 unsigned EltSize = VecVT.getScalarSizeInBits(); 4826 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 4827 4828 unsigned MaxVLMAX = 0; 4829 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 4830 if (VectorBitsMax != 0) 4831 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 4832 4833 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 4834 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 4835 4836 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 4837 // to use vrgatherei16.vv. 4838 // TODO: It's also possible to use vrgatherei16.vv for other types to 4839 // decrease register width for the index calculation. 4840 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 4841 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 4842 // Reverse each half, then reassemble them in reverse order. 4843 // NOTE: It's also possible that after splitting that VLMAX no longer 4844 // requires vrgatherei16.vv. 4845 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 4846 SDValue Lo, Hi; 4847 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4848 EVT LoVT, HiVT; 4849 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 4850 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 4851 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 4852 // Reassemble the low and high pieces reversed. 4853 // FIXME: This is a CONCAT_VECTORS. 4854 SDValue Res = 4855 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 4856 DAG.getIntPtrConstant(0, DL)); 4857 return DAG.getNode( 4858 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 4859 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 4860 } 4861 4862 // Just promote the int type to i16 which will double the LMUL. 4863 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 4864 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 4865 } 4866 4867 MVT XLenVT = Subtarget.getXLenVT(); 4868 SDValue Mask, VL; 4869 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4870 4871 // Calculate VLMAX-1 for the desired SEW. 4872 unsigned MinElts = VecVT.getVectorMinNumElements(); 4873 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 4874 DAG.getConstant(MinElts, DL, XLenVT)); 4875 SDValue VLMinus1 = 4876 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 4877 4878 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 4879 bool IsRV32E64 = 4880 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 4881 SDValue SplatVL; 4882 if (!IsRV32E64) 4883 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 4884 else 4885 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 4886 4887 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 4888 SDValue Indices = 4889 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 4890 4891 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 4892 } 4893 4894 SDValue 4895 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 4896 SelectionDAG &DAG) const { 4897 SDLoc DL(Op); 4898 auto *Load = cast<LoadSDNode>(Op); 4899 4900 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 4901 Load->getMemoryVT(), 4902 *Load->getMemOperand()) && 4903 "Expecting a correctly-aligned load"); 4904 4905 MVT VT = Op.getSimpleValueType(); 4906 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4907 4908 SDValue VL = 4909 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4910 4911 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4912 SDValue NewLoad = DAG.getMemIntrinsicNode( 4913 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 4914 Load->getMemoryVT(), Load->getMemOperand()); 4915 4916 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 4917 return DAG.getMergeValues({Result, Load->getChain()}, DL); 4918 } 4919 4920 SDValue 4921 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 4922 SelectionDAG &DAG) const { 4923 SDLoc DL(Op); 4924 auto *Store = cast<StoreSDNode>(Op); 4925 4926 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 4927 Store->getMemoryVT(), 4928 *Store->getMemOperand()) && 4929 "Expecting a correctly-aligned store"); 4930 4931 SDValue StoreVal = Store->getValue(); 4932 MVT VT = StoreVal.getSimpleValueType(); 4933 4934 // If the size less than a byte, we need to pad with zeros to make a byte. 4935 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 4936 VT = MVT::v8i1; 4937 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 4938 DAG.getConstant(0, DL, VT), StoreVal, 4939 DAG.getIntPtrConstant(0, DL)); 4940 } 4941 4942 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4943 4944 SDValue VL = 4945 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4946 4947 SDValue NewValue = 4948 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 4949 return DAG.getMemIntrinsicNode( 4950 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 4951 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 4952 Store->getMemoryVT(), Store->getMemOperand()); 4953 } 4954 4955 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 4956 SelectionDAG &DAG) const { 4957 SDLoc DL(Op); 4958 MVT VT = Op.getSimpleValueType(); 4959 4960 const auto *MemSD = cast<MemSDNode>(Op); 4961 EVT MemVT = MemSD->getMemoryVT(); 4962 MachineMemOperand *MMO = MemSD->getMemOperand(); 4963 SDValue Chain = MemSD->getChain(); 4964 SDValue BasePtr = MemSD->getBasePtr(); 4965 4966 SDValue Mask, PassThru, VL; 4967 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 4968 Mask = VPLoad->getMask(); 4969 PassThru = DAG.getUNDEF(VT); 4970 VL = VPLoad->getVectorLength(); 4971 } else { 4972 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 4973 Mask = MLoad->getMask(); 4974 PassThru = MLoad->getPassThru(); 4975 } 4976 4977 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4978 4979 MVT XLenVT = Subtarget.getXLenVT(); 4980 4981 MVT ContainerVT = VT; 4982 if (VT.isFixedLengthVector()) { 4983 ContainerVT = getContainerForFixedLengthVector(VT); 4984 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4985 if (!IsUnmasked) { 4986 MVT MaskVT = 4987 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4988 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4989 } 4990 } 4991 4992 if (!VL) 4993 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 4994 4995 unsigned IntID = 4996 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 4997 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 4998 if (!IsUnmasked) 4999 Ops.push_back(PassThru); 5000 Ops.push_back(BasePtr); 5001 if (!IsUnmasked) 5002 Ops.push_back(Mask); 5003 Ops.push_back(VL); 5004 if (!IsUnmasked) 5005 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5006 5007 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5008 5009 SDValue Result = 5010 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5011 Chain = Result.getValue(1); 5012 5013 if (VT.isFixedLengthVector()) 5014 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5015 5016 return DAG.getMergeValues({Result, Chain}, DL); 5017 } 5018 5019 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5020 SelectionDAG &DAG) const { 5021 SDLoc DL(Op); 5022 5023 const auto *MemSD = cast<MemSDNode>(Op); 5024 EVT MemVT = MemSD->getMemoryVT(); 5025 MachineMemOperand *MMO = MemSD->getMemOperand(); 5026 SDValue Chain = MemSD->getChain(); 5027 SDValue BasePtr = MemSD->getBasePtr(); 5028 SDValue Val, Mask, VL; 5029 5030 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5031 Val = VPStore->getValue(); 5032 Mask = VPStore->getMask(); 5033 VL = VPStore->getVectorLength(); 5034 } else { 5035 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5036 Val = MStore->getValue(); 5037 Mask = MStore->getMask(); 5038 } 5039 5040 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5041 5042 MVT VT = Val.getSimpleValueType(); 5043 MVT XLenVT = Subtarget.getXLenVT(); 5044 5045 MVT ContainerVT = VT; 5046 if (VT.isFixedLengthVector()) { 5047 ContainerVT = getContainerForFixedLengthVector(VT); 5048 5049 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5050 if (!IsUnmasked) { 5051 MVT MaskVT = 5052 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5053 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5054 } 5055 } 5056 5057 if (!VL) 5058 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5059 5060 unsigned IntID = 5061 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5062 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5063 Ops.push_back(Val); 5064 Ops.push_back(BasePtr); 5065 if (!IsUnmasked) 5066 Ops.push_back(Mask); 5067 Ops.push_back(VL); 5068 5069 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5070 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5071 } 5072 5073 SDValue 5074 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5075 SelectionDAG &DAG) const { 5076 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5077 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5078 5079 MVT VT = Op.getSimpleValueType(); 5080 5081 SDValue Op1 = 5082 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5083 SDValue Op2 = 5084 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5085 5086 SDLoc DL(Op); 5087 SDValue VL = 5088 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5089 5090 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5091 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5092 5093 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5094 Op.getOperand(2), Mask, VL); 5095 5096 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5097 } 5098 5099 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5100 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5101 MVT VT = Op.getSimpleValueType(); 5102 5103 if (VT.getVectorElementType() == MVT::i1) 5104 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5105 5106 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5107 } 5108 5109 SDValue 5110 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5111 SelectionDAG &DAG) const { 5112 unsigned Opc; 5113 switch (Op.getOpcode()) { 5114 default: llvm_unreachable("Unexpected opcode!"); 5115 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5116 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5117 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5118 } 5119 5120 return lowerToScalableOp(Op, DAG, Opc); 5121 } 5122 5123 // Lower vector ABS to smax(X, sub(0, X)). 5124 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5125 SDLoc DL(Op); 5126 MVT VT = Op.getSimpleValueType(); 5127 SDValue X = Op.getOperand(0); 5128 5129 assert(VT.isFixedLengthVector() && "Unexpected type"); 5130 5131 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5132 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5133 5134 SDValue Mask, VL; 5135 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5136 5137 SDValue SplatZero = 5138 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5139 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5140 SDValue NegX = 5141 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5142 SDValue Max = 5143 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5144 5145 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5146 } 5147 5148 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5149 SDValue Op, SelectionDAG &DAG) const { 5150 SDLoc DL(Op); 5151 MVT VT = Op.getSimpleValueType(); 5152 SDValue Mag = Op.getOperand(0); 5153 SDValue Sign = Op.getOperand(1); 5154 assert(Mag.getValueType() == Sign.getValueType() && 5155 "Can only handle COPYSIGN with matching types."); 5156 5157 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5158 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5159 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5160 5161 SDValue Mask, VL; 5162 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5163 5164 SDValue CopySign = 5165 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5166 5167 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5168 } 5169 5170 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5171 SDValue Op, SelectionDAG &DAG) const { 5172 MVT VT = Op.getSimpleValueType(); 5173 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5174 5175 MVT I1ContainerVT = 5176 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5177 5178 SDValue CC = 5179 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5180 SDValue Op1 = 5181 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5182 SDValue Op2 = 5183 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5184 5185 SDLoc DL(Op); 5186 SDValue Mask, VL; 5187 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5188 5189 SDValue Select = 5190 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5191 5192 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5193 } 5194 5195 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5196 unsigned NewOpc, 5197 bool HasMask) const { 5198 MVT VT = Op.getSimpleValueType(); 5199 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5200 5201 // Create list of operands by converting existing ones to scalable types. 5202 SmallVector<SDValue, 6> Ops; 5203 for (const SDValue &V : Op->op_values()) { 5204 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5205 5206 // Pass through non-vector operands. 5207 if (!V.getValueType().isVector()) { 5208 Ops.push_back(V); 5209 continue; 5210 } 5211 5212 // "cast" fixed length vector to a scalable vector. 5213 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5214 "Only fixed length vectors are supported!"); 5215 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5216 } 5217 5218 SDLoc DL(Op); 5219 SDValue Mask, VL; 5220 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5221 if (HasMask) 5222 Ops.push_back(Mask); 5223 Ops.push_back(VL); 5224 5225 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5226 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5227 } 5228 5229 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5230 // * Operands of each node are assumed to be in the same order. 5231 // * The EVL operand is promoted from i32 to i64 on RV64. 5232 // * Fixed-length vectors are converted to their scalable-vector container 5233 // types. 5234 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5235 unsigned RISCVISDOpc) const { 5236 SDLoc DL(Op); 5237 MVT VT = Op.getSimpleValueType(); 5238 SmallVector<SDValue, 4> Ops; 5239 5240 for (const auto &OpIdx : enumerate(Op->ops())) { 5241 SDValue V = OpIdx.value(); 5242 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5243 // Pass through operands which aren't fixed-length vectors. 5244 if (!V.getValueType().isFixedLengthVector()) { 5245 Ops.push_back(V); 5246 continue; 5247 } 5248 // "cast" fixed length vector to a scalable vector. 5249 MVT OpVT = V.getSimpleValueType(); 5250 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5251 assert(useRVVForFixedLengthVectorVT(OpVT) && 5252 "Only fixed length vectors are supported!"); 5253 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5254 } 5255 5256 if (!VT.isFixedLengthVector()) 5257 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5258 5259 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5260 5261 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5262 5263 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5264 } 5265 5266 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5267 // matched to a RVV indexed load. The RVV indexed load instructions only 5268 // support the "unsigned unscaled" addressing mode; indices are implicitly 5269 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5270 // signed or scaled indexing is extended to the XLEN value type and scaled 5271 // accordingly. 5272 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5273 SelectionDAG &DAG) const { 5274 SDLoc DL(Op); 5275 MVT VT = Op.getSimpleValueType(); 5276 5277 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5278 EVT MemVT = MemSD->getMemoryVT(); 5279 MachineMemOperand *MMO = MemSD->getMemOperand(); 5280 SDValue Chain = MemSD->getChain(); 5281 SDValue BasePtr = MemSD->getBasePtr(); 5282 5283 ISD::LoadExtType LoadExtType; 5284 SDValue Index, Mask, PassThru, VL; 5285 5286 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5287 Index = VPGN->getIndex(); 5288 Mask = VPGN->getMask(); 5289 PassThru = DAG.getUNDEF(VT); 5290 VL = VPGN->getVectorLength(); 5291 // VP doesn't support extending loads. 5292 LoadExtType = ISD::NON_EXTLOAD; 5293 } else { 5294 // Else it must be a MGATHER. 5295 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5296 Index = MGN->getIndex(); 5297 Mask = MGN->getMask(); 5298 PassThru = MGN->getPassThru(); 5299 LoadExtType = MGN->getExtensionType(); 5300 } 5301 5302 MVT IndexVT = Index.getSimpleValueType(); 5303 MVT XLenVT = Subtarget.getXLenVT(); 5304 5305 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5306 "Unexpected VTs!"); 5307 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5308 // Targets have to explicitly opt-in for extending vector loads. 5309 assert(LoadExtType == ISD::NON_EXTLOAD && 5310 "Unexpected extending MGATHER/VP_GATHER"); 5311 (void)LoadExtType; 5312 5313 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5314 // the selection of the masked intrinsics doesn't do this for us. 5315 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5316 5317 MVT ContainerVT = VT; 5318 if (VT.isFixedLengthVector()) { 5319 // We need to use the larger of the result and index type to determine the 5320 // scalable type to use so we don't increase LMUL for any operand/result. 5321 if (VT.bitsGE(IndexVT)) { 5322 ContainerVT = getContainerForFixedLengthVector(VT); 5323 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5324 ContainerVT.getVectorElementCount()); 5325 } else { 5326 IndexVT = getContainerForFixedLengthVector(IndexVT); 5327 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5328 IndexVT.getVectorElementCount()); 5329 } 5330 5331 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5332 5333 if (!IsUnmasked) { 5334 MVT MaskVT = 5335 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5336 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5337 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5338 } 5339 } 5340 5341 if (!VL) 5342 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5343 5344 unsigned IntID = 5345 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5346 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5347 if (!IsUnmasked) 5348 Ops.push_back(PassThru); 5349 Ops.push_back(BasePtr); 5350 Ops.push_back(Index); 5351 if (!IsUnmasked) 5352 Ops.push_back(Mask); 5353 Ops.push_back(VL); 5354 if (!IsUnmasked) 5355 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5356 5357 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5358 SDValue Result = 5359 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5360 Chain = Result.getValue(1); 5361 5362 if (VT.isFixedLengthVector()) 5363 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5364 5365 return DAG.getMergeValues({Result, Chain}, DL); 5366 } 5367 5368 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5369 // matched to a RVV indexed store. The RVV indexed store instructions only 5370 // support the "unsigned unscaled" addressing mode; indices are implicitly 5371 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5372 // signed or scaled indexing is extended to the XLEN value type and scaled 5373 // accordingly. 5374 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5375 SelectionDAG &DAG) const { 5376 SDLoc DL(Op); 5377 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5378 EVT MemVT = MemSD->getMemoryVT(); 5379 MachineMemOperand *MMO = MemSD->getMemOperand(); 5380 SDValue Chain = MemSD->getChain(); 5381 SDValue BasePtr = MemSD->getBasePtr(); 5382 5383 bool IsTruncatingStore = false; 5384 SDValue Index, Mask, Val, VL; 5385 5386 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5387 Index = VPSN->getIndex(); 5388 Mask = VPSN->getMask(); 5389 Val = VPSN->getValue(); 5390 VL = VPSN->getVectorLength(); 5391 // VP doesn't support truncating stores. 5392 IsTruncatingStore = false; 5393 } else { 5394 // Else it must be a MSCATTER. 5395 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5396 Index = MSN->getIndex(); 5397 Mask = MSN->getMask(); 5398 Val = MSN->getValue(); 5399 IsTruncatingStore = MSN->isTruncatingStore(); 5400 } 5401 5402 MVT VT = Val.getSimpleValueType(); 5403 MVT IndexVT = Index.getSimpleValueType(); 5404 MVT XLenVT = Subtarget.getXLenVT(); 5405 5406 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5407 "Unexpected VTs!"); 5408 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5409 // Targets have to explicitly opt-in for extending vector loads and 5410 // truncating vector stores. 5411 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5412 (void)IsTruncatingStore; 5413 5414 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5415 // the selection of the masked intrinsics doesn't do this for us. 5416 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5417 5418 MVT ContainerVT = VT; 5419 if (VT.isFixedLengthVector()) { 5420 // We need to use the larger of the value and index type to determine the 5421 // scalable type to use so we don't increase LMUL for any operand/result. 5422 if (VT.bitsGE(IndexVT)) { 5423 ContainerVT = getContainerForFixedLengthVector(VT); 5424 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5425 ContainerVT.getVectorElementCount()); 5426 } else { 5427 IndexVT = getContainerForFixedLengthVector(IndexVT); 5428 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 5429 IndexVT.getVectorElementCount()); 5430 } 5431 5432 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5433 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5434 5435 if (!IsUnmasked) { 5436 MVT MaskVT = 5437 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5438 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5439 } 5440 } 5441 5442 if (!VL) 5443 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5444 5445 unsigned IntID = 5446 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 5447 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5448 Ops.push_back(Val); 5449 Ops.push_back(BasePtr); 5450 Ops.push_back(Index); 5451 if (!IsUnmasked) 5452 Ops.push_back(Mask); 5453 Ops.push_back(VL); 5454 5455 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5456 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5457 } 5458 5459 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 5460 SelectionDAG &DAG) const { 5461 const MVT XLenVT = Subtarget.getXLenVT(); 5462 SDLoc DL(Op); 5463 SDValue Chain = Op->getOperand(0); 5464 SDValue SysRegNo = DAG.getTargetConstant( 5465 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5466 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 5467 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 5468 5469 // Encoding used for rounding mode in RISCV differs from that used in 5470 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 5471 // table, which consists of a sequence of 4-bit fields, each representing 5472 // corresponding FLT_ROUNDS mode. 5473 static const int Table = 5474 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 5475 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 5476 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 5477 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 5478 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 5479 5480 SDValue Shift = 5481 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 5482 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5483 DAG.getConstant(Table, DL, XLenVT), Shift); 5484 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5485 DAG.getConstant(7, DL, XLenVT)); 5486 5487 return DAG.getMergeValues({Masked, Chain}, DL); 5488 } 5489 5490 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 5491 SelectionDAG &DAG) const { 5492 const MVT XLenVT = Subtarget.getXLenVT(); 5493 SDLoc DL(Op); 5494 SDValue Chain = Op->getOperand(0); 5495 SDValue RMValue = Op->getOperand(1); 5496 SDValue SysRegNo = DAG.getTargetConstant( 5497 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5498 5499 // Encoding used for rounding mode in RISCV differs from that used in 5500 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 5501 // a table, which consists of a sequence of 4-bit fields, each representing 5502 // corresponding RISCV mode. 5503 static const unsigned Table = 5504 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 5505 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 5506 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 5507 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 5508 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 5509 5510 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 5511 DAG.getConstant(2, DL, XLenVT)); 5512 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5513 DAG.getConstant(Table, DL, XLenVT), Shift); 5514 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5515 DAG.getConstant(0x7, DL, XLenVT)); 5516 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 5517 RMValue); 5518 } 5519 5520 // Returns the opcode of the target-specific SDNode that implements the 32-bit 5521 // form of the given Opcode. 5522 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 5523 switch (Opcode) { 5524 default: 5525 llvm_unreachable("Unexpected opcode"); 5526 case ISD::SHL: 5527 return RISCVISD::SLLW; 5528 case ISD::SRA: 5529 return RISCVISD::SRAW; 5530 case ISD::SRL: 5531 return RISCVISD::SRLW; 5532 case ISD::SDIV: 5533 return RISCVISD::DIVW; 5534 case ISD::UDIV: 5535 return RISCVISD::DIVUW; 5536 case ISD::UREM: 5537 return RISCVISD::REMUW; 5538 case ISD::ROTL: 5539 return RISCVISD::ROLW; 5540 case ISD::ROTR: 5541 return RISCVISD::RORW; 5542 case RISCVISD::GREV: 5543 return RISCVISD::GREVW; 5544 case RISCVISD::GORC: 5545 return RISCVISD::GORCW; 5546 } 5547 } 5548 5549 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 5550 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 5551 // otherwise be promoted to i64, making it difficult to select the 5552 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 5553 // type i8/i16/i32 is lost. 5554 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 5555 unsigned ExtOpc = ISD::ANY_EXTEND) { 5556 SDLoc DL(N); 5557 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5558 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 5559 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 5560 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5561 // ReplaceNodeResults requires we maintain the same type for the return value. 5562 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 5563 } 5564 5565 // Converts the given 32-bit operation to a i64 operation with signed extension 5566 // semantic to reduce the signed extension instructions. 5567 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 5568 SDLoc DL(N); 5569 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5570 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5571 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 5572 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5573 DAG.getValueType(MVT::i32)); 5574 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 5575 } 5576 5577 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 5578 SmallVectorImpl<SDValue> &Results, 5579 SelectionDAG &DAG) const { 5580 SDLoc DL(N); 5581 switch (N->getOpcode()) { 5582 default: 5583 llvm_unreachable("Don't know how to custom type legalize this operation!"); 5584 case ISD::STRICT_FP_TO_SINT: 5585 case ISD::STRICT_FP_TO_UINT: 5586 case ISD::FP_TO_SINT: 5587 case ISD::FP_TO_UINT: { 5588 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5589 "Unexpected custom legalisation"); 5590 bool IsStrict = N->isStrictFPOpcode(); 5591 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 5592 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 5593 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 5594 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 5595 TargetLowering::TypeSoftenFloat) { 5596 // FIXME: Support strict FP. 5597 if (IsStrict) 5598 return; 5599 if (!isTypeLegal(Op0.getValueType())) 5600 return; 5601 unsigned Opc = 5602 IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 5603 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0); 5604 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5605 return; 5606 } 5607 // If the FP type needs to be softened, emit a library call using the 'si' 5608 // version. If we left it to default legalization we'd end up with 'di'. If 5609 // the FP type doesn't need to be softened just let generic type 5610 // legalization promote the result type. 5611 RTLIB::Libcall LC; 5612 if (IsSigned) 5613 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 5614 else 5615 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 5616 MakeLibCallOptions CallOptions; 5617 EVT OpVT = Op0.getValueType(); 5618 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 5619 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 5620 SDValue Result; 5621 std::tie(Result, Chain) = 5622 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 5623 Results.push_back(Result); 5624 if (IsStrict) 5625 Results.push_back(Chain); 5626 break; 5627 } 5628 case ISD::READCYCLECOUNTER: { 5629 assert(!Subtarget.is64Bit() && 5630 "READCYCLECOUNTER only has custom type legalization on riscv32"); 5631 5632 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 5633 SDValue RCW = 5634 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 5635 5636 Results.push_back( 5637 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 5638 Results.push_back(RCW.getValue(2)); 5639 break; 5640 } 5641 case ISD::MUL: { 5642 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 5643 unsigned XLen = Subtarget.getXLen(); 5644 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 5645 if (Size > XLen) { 5646 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 5647 SDValue LHS = N->getOperand(0); 5648 SDValue RHS = N->getOperand(1); 5649 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 5650 5651 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 5652 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 5653 // We need exactly one side to be unsigned. 5654 if (LHSIsU == RHSIsU) 5655 return; 5656 5657 auto MakeMULPair = [&](SDValue S, SDValue U) { 5658 MVT XLenVT = Subtarget.getXLenVT(); 5659 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 5660 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 5661 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 5662 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 5663 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 5664 }; 5665 5666 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 5667 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 5668 5669 // The other operand should be signed, but still prefer MULH when 5670 // possible. 5671 if (RHSIsU && LHSIsS && !RHSIsS) 5672 Results.push_back(MakeMULPair(LHS, RHS)); 5673 else if (LHSIsU && RHSIsS && !LHSIsS) 5674 Results.push_back(MakeMULPair(RHS, LHS)); 5675 5676 return; 5677 } 5678 LLVM_FALLTHROUGH; 5679 } 5680 case ISD::ADD: 5681 case ISD::SUB: 5682 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5683 "Unexpected custom legalisation"); 5684 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 5685 break; 5686 case ISD::SHL: 5687 case ISD::SRA: 5688 case ISD::SRL: 5689 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5690 "Unexpected custom legalisation"); 5691 if (N->getOperand(1).getOpcode() != ISD::Constant) { 5692 Results.push_back(customLegalizeToWOp(N, DAG)); 5693 break; 5694 } 5695 5696 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 5697 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 5698 // shift amount. 5699 if (N->getOpcode() == ISD::SHL) { 5700 SDLoc DL(N); 5701 SDValue NewOp0 = 5702 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5703 SDValue NewOp1 = 5704 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 5705 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 5706 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5707 DAG.getValueType(MVT::i32)); 5708 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5709 } 5710 5711 break; 5712 case ISD::ROTL: 5713 case ISD::ROTR: 5714 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5715 "Unexpected custom legalisation"); 5716 Results.push_back(customLegalizeToWOp(N, DAG)); 5717 break; 5718 case ISD::CTTZ: 5719 case ISD::CTTZ_ZERO_UNDEF: 5720 case ISD::CTLZ: 5721 case ISD::CTLZ_ZERO_UNDEF: { 5722 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5723 "Unexpected custom legalisation"); 5724 5725 SDValue NewOp0 = 5726 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5727 bool IsCTZ = 5728 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 5729 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 5730 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 5731 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5732 return; 5733 } 5734 case ISD::SDIV: 5735 case ISD::UDIV: 5736 case ISD::UREM: { 5737 MVT VT = N->getSimpleValueType(0); 5738 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 5739 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 5740 "Unexpected custom legalisation"); 5741 // Don't promote division/remainder by constant since we should expand those 5742 // to multiply by magic constant. 5743 // FIXME: What if the expansion is disabled for minsize. 5744 if (N->getOperand(1).getOpcode() == ISD::Constant) 5745 return; 5746 5747 // If the input is i32, use ANY_EXTEND since the W instructions don't read 5748 // the upper 32 bits. For other types we need to sign or zero extend 5749 // based on the opcode. 5750 unsigned ExtOpc = ISD::ANY_EXTEND; 5751 if (VT != MVT::i32) 5752 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 5753 : ISD::ZERO_EXTEND; 5754 5755 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 5756 break; 5757 } 5758 case ISD::UADDO: 5759 case ISD::USUBO: { 5760 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5761 "Unexpected custom legalisation"); 5762 bool IsAdd = N->getOpcode() == ISD::UADDO; 5763 // Create an ADDW or SUBW. 5764 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5765 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5766 SDValue Res = 5767 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 5768 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 5769 DAG.getValueType(MVT::i32)); 5770 5771 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 5772 // Since the inputs are sign extended from i32, this is equivalent to 5773 // comparing the lower 32 bits. 5774 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5775 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 5776 IsAdd ? ISD::SETULT : ISD::SETUGT); 5777 5778 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5779 Results.push_back(Overflow); 5780 return; 5781 } 5782 case ISD::UADDSAT: 5783 case ISD::USUBSAT: { 5784 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5785 "Unexpected custom legalisation"); 5786 if (Subtarget.hasStdExtZbb()) { 5787 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 5788 // sign extend allows overflow of the lower 32 bits to be detected on 5789 // the promoted size. 5790 SDValue LHS = 5791 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5792 SDValue RHS = 5793 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 5794 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 5795 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5796 return; 5797 } 5798 5799 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 5800 // promotion for UADDO/USUBO. 5801 Results.push_back(expandAddSubSat(N, DAG)); 5802 return; 5803 } 5804 case ISD::BITCAST: { 5805 EVT VT = N->getValueType(0); 5806 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 5807 SDValue Op0 = N->getOperand(0); 5808 EVT Op0VT = Op0.getValueType(); 5809 MVT XLenVT = Subtarget.getXLenVT(); 5810 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 5811 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 5812 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 5813 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 5814 Subtarget.hasStdExtF()) { 5815 SDValue FPConv = 5816 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 5817 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 5818 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 5819 isTypeLegal(Op0VT)) { 5820 // Custom-legalize bitcasts from fixed-length vector types to illegal 5821 // scalar types in order to improve codegen. Bitcast the vector to a 5822 // one-element vector type whose element type is the same as the result 5823 // type, and extract the first element. 5824 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 5825 if (isTypeLegal(BVT)) { 5826 SDValue BVec = DAG.getBitcast(BVT, Op0); 5827 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 5828 DAG.getConstant(0, DL, XLenVT))); 5829 } 5830 } 5831 break; 5832 } 5833 case RISCVISD::GREV: 5834 case RISCVISD::GORC: { 5835 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5836 "Unexpected custom legalisation"); 5837 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 5838 // This is similar to customLegalizeToWOp, except that we pass the second 5839 // operand (a TargetConstant) straight through: it is already of type 5840 // XLenVT. 5841 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5842 SDValue NewOp0 = 5843 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5844 SDValue NewOp1 = 5845 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5846 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5847 // ReplaceNodeResults requires we maintain the same type for the return 5848 // value. 5849 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5850 break; 5851 } 5852 case RISCVISD::SHFL: { 5853 // There is no SHFLIW instruction, but we can just promote the operation. 5854 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5855 "Unexpected custom legalisation"); 5856 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 5857 SDValue NewOp0 = 5858 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5859 SDValue NewOp1 = 5860 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5861 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 5862 // ReplaceNodeResults requires we maintain the same type for the return 5863 // value. 5864 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5865 break; 5866 } 5867 case ISD::BSWAP: 5868 case ISD::BITREVERSE: { 5869 MVT VT = N->getSimpleValueType(0); 5870 MVT XLenVT = Subtarget.getXLenVT(); 5871 assert((VT == MVT::i8 || VT == MVT::i16 || 5872 (VT == MVT::i32 && Subtarget.is64Bit())) && 5873 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 5874 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 5875 unsigned Imm = VT.getSizeInBits() - 1; 5876 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 5877 if (N->getOpcode() == ISD::BSWAP) 5878 Imm &= ~0x7U; 5879 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 5880 SDValue GREVI = 5881 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 5882 // ReplaceNodeResults requires we maintain the same type for the return 5883 // value. 5884 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 5885 break; 5886 } 5887 case ISD::FSHL: 5888 case ISD::FSHR: { 5889 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5890 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 5891 SDValue NewOp0 = 5892 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5893 SDValue NewOp1 = 5894 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5895 SDValue NewOp2 = 5896 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5897 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 5898 // Mask the shift amount to 5 bits. 5899 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 5900 DAG.getConstant(0x1f, DL, MVT::i64)); 5901 unsigned Opc = 5902 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 5903 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 5904 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 5905 break; 5906 } 5907 case ISD::EXTRACT_VECTOR_ELT: { 5908 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 5909 // type is illegal (currently only vXi64 RV32). 5910 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 5911 // transferred to the destination register. We issue two of these from the 5912 // upper- and lower- halves of the SEW-bit vector element, slid down to the 5913 // first element. 5914 SDValue Vec = N->getOperand(0); 5915 SDValue Idx = N->getOperand(1); 5916 5917 // The vector type hasn't been legalized yet so we can't issue target 5918 // specific nodes if it needs legalization. 5919 // FIXME: We would manually legalize if it's important. 5920 if (!isTypeLegal(Vec.getValueType())) 5921 return; 5922 5923 MVT VecVT = Vec.getSimpleValueType(); 5924 5925 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 5926 VecVT.getVectorElementType() == MVT::i64 && 5927 "Unexpected EXTRACT_VECTOR_ELT legalization"); 5928 5929 // If this is a fixed vector, we need to convert it to a scalable vector. 5930 MVT ContainerVT = VecVT; 5931 if (VecVT.isFixedLengthVector()) { 5932 ContainerVT = getContainerForFixedLengthVector(VecVT); 5933 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5934 } 5935 5936 MVT XLenVT = Subtarget.getXLenVT(); 5937 5938 // Use a VL of 1 to avoid processing more elements than we need. 5939 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5940 SDValue VL = DAG.getConstant(1, DL, XLenVT); 5941 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5942 5943 // Unless the index is known to be 0, we must slide the vector down to get 5944 // the desired element into index 0. 5945 if (!isNullConstant(Idx)) { 5946 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5947 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 5948 } 5949 5950 // Extract the lower XLEN bits of the correct vector element. 5951 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 5952 5953 // To extract the upper XLEN bits of the vector element, shift the first 5954 // element right by 32 bits and re-extract the lower XLEN bits. 5955 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5956 DAG.getConstant(32, DL, XLenVT), VL); 5957 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 5958 ThirtyTwoV, Mask, VL); 5959 5960 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 5961 5962 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 5963 break; 5964 } 5965 case ISD::INTRINSIC_WO_CHAIN: { 5966 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5967 switch (IntNo) { 5968 default: 5969 llvm_unreachable( 5970 "Don't know how to custom type legalize this intrinsic!"); 5971 case Intrinsic::riscv_orc_b: { 5972 // Lower to the GORCI encoding for orc.b with the operand extended. 5973 SDValue NewOp = 5974 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5975 // If Zbp is enabled, use GORCIW which will sign extend the result. 5976 unsigned Opc = 5977 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 5978 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 5979 DAG.getConstant(7, DL, MVT::i64)); 5980 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5981 return; 5982 } 5983 case Intrinsic::riscv_grev: 5984 case Intrinsic::riscv_gorc: { 5985 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5986 "Unexpected custom legalisation"); 5987 SDValue NewOp1 = 5988 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5989 SDValue NewOp2 = 5990 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5991 unsigned Opc = 5992 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 5993 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5994 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5995 break; 5996 } 5997 case Intrinsic::riscv_shfl: 5998 case Intrinsic::riscv_unshfl: { 5999 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6000 "Unexpected custom legalisation"); 6001 SDValue NewOp1 = 6002 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6003 SDValue NewOp2 = 6004 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6005 unsigned Opc = 6006 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6007 if (isa<ConstantSDNode>(N->getOperand(2))) { 6008 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6009 DAG.getConstant(0xf, DL, MVT::i64)); 6010 Opc = 6011 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6012 } 6013 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6014 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6015 break; 6016 } 6017 case Intrinsic::riscv_bcompress: 6018 case Intrinsic::riscv_bdecompress: { 6019 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6020 "Unexpected custom legalisation"); 6021 SDValue NewOp1 = 6022 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6023 SDValue NewOp2 = 6024 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6025 unsigned Opc = IntNo == Intrinsic::riscv_bcompress 6026 ? RISCVISD::BCOMPRESSW 6027 : RISCVISD::BDECOMPRESSW; 6028 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6029 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6030 break; 6031 } 6032 case Intrinsic::riscv_vmv_x_s: { 6033 EVT VT = N->getValueType(0); 6034 MVT XLenVT = Subtarget.getXLenVT(); 6035 if (VT.bitsLT(XLenVT)) { 6036 // Simple case just extract using vmv.x.s and truncate. 6037 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6038 Subtarget.getXLenVT(), N->getOperand(1)); 6039 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6040 return; 6041 } 6042 6043 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6044 "Unexpected custom legalization"); 6045 6046 // We need to do the move in two steps. 6047 SDValue Vec = N->getOperand(1); 6048 MVT VecVT = Vec.getSimpleValueType(); 6049 6050 // First extract the lower XLEN bits of the element. 6051 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6052 6053 // To extract the upper XLEN bits of the vector element, shift the first 6054 // element right by 32 bits and re-extract the lower XLEN bits. 6055 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6056 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6057 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6058 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 6059 DAG.getConstant(32, DL, XLenVT), VL); 6060 SDValue LShr32 = 6061 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6062 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6063 6064 Results.push_back( 6065 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6066 break; 6067 } 6068 } 6069 break; 6070 } 6071 case ISD::VECREDUCE_ADD: 6072 case ISD::VECREDUCE_AND: 6073 case ISD::VECREDUCE_OR: 6074 case ISD::VECREDUCE_XOR: 6075 case ISD::VECREDUCE_SMAX: 6076 case ISD::VECREDUCE_UMAX: 6077 case ISD::VECREDUCE_SMIN: 6078 case ISD::VECREDUCE_UMIN: 6079 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6080 Results.push_back(V); 6081 break; 6082 case ISD::VP_REDUCE_ADD: 6083 case ISD::VP_REDUCE_AND: 6084 case ISD::VP_REDUCE_OR: 6085 case ISD::VP_REDUCE_XOR: 6086 case ISD::VP_REDUCE_SMAX: 6087 case ISD::VP_REDUCE_UMAX: 6088 case ISD::VP_REDUCE_SMIN: 6089 case ISD::VP_REDUCE_UMIN: 6090 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6091 Results.push_back(V); 6092 break; 6093 case ISD::FLT_ROUNDS_: { 6094 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6095 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6096 Results.push_back(Res.getValue(0)); 6097 Results.push_back(Res.getValue(1)); 6098 break; 6099 } 6100 } 6101 } 6102 6103 // A structure to hold one of the bit-manipulation patterns below. Together, a 6104 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6105 // (or (and (shl x, 1), 0xAAAAAAAA), 6106 // (and (srl x, 1), 0x55555555)) 6107 struct RISCVBitmanipPat { 6108 SDValue Op; 6109 unsigned ShAmt; 6110 bool IsSHL; 6111 6112 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6113 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6114 } 6115 }; 6116 6117 // Matches patterns of the form 6118 // (and (shl x, C2), (C1 << C2)) 6119 // (and (srl x, C2), C1) 6120 // (shl (and x, C1), C2) 6121 // (srl (and x, (C1 << C2)), C2) 6122 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6123 // The expected masks for each shift amount are specified in BitmanipMasks where 6124 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6125 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6126 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6127 // XLen is 64. 6128 static Optional<RISCVBitmanipPat> 6129 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6130 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6131 "Unexpected number of masks"); 6132 Optional<uint64_t> Mask; 6133 // Optionally consume a mask around the shift operation. 6134 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6135 Mask = Op.getConstantOperandVal(1); 6136 Op = Op.getOperand(0); 6137 } 6138 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6139 return None; 6140 bool IsSHL = Op.getOpcode() == ISD::SHL; 6141 6142 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6143 return None; 6144 uint64_t ShAmt = Op.getConstantOperandVal(1); 6145 6146 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6147 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6148 return None; 6149 // If we don't have enough masks for 64 bit, then we must be trying to 6150 // match SHFL so we're only allowed to shift 1/4 of the width. 6151 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6152 return None; 6153 6154 SDValue Src = Op.getOperand(0); 6155 6156 // The expected mask is shifted left when the AND is found around SHL 6157 // patterns. 6158 // ((x >> 1) & 0x55555555) 6159 // ((x << 1) & 0xAAAAAAAA) 6160 bool SHLExpMask = IsSHL; 6161 6162 if (!Mask) { 6163 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6164 // the mask is all ones: consume that now. 6165 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6166 Mask = Src.getConstantOperandVal(1); 6167 Src = Src.getOperand(0); 6168 // The expected mask is now in fact shifted left for SRL, so reverse the 6169 // decision. 6170 // ((x & 0xAAAAAAAA) >> 1) 6171 // ((x & 0x55555555) << 1) 6172 SHLExpMask = !SHLExpMask; 6173 } else { 6174 // Use a default shifted mask of all-ones if there's no AND, truncated 6175 // down to the expected width. This simplifies the logic later on. 6176 Mask = maskTrailingOnes<uint64_t>(Width); 6177 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6178 } 6179 } 6180 6181 unsigned MaskIdx = Log2_32(ShAmt); 6182 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6183 6184 if (SHLExpMask) 6185 ExpMask <<= ShAmt; 6186 6187 if (Mask != ExpMask) 6188 return None; 6189 6190 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6191 } 6192 6193 // Matches any of the following bit-manipulation patterns: 6194 // (and (shl x, 1), (0x55555555 << 1)) 6195 // (and (srl x, 1), 0x55555555) 6196 // (shl (and x, 0x55555555), 1) 6197 // (srl (and x, (0x55555555 << 1)), 1) 6198 // where the shift amount and mask may vary thus: 6199 // [1] = 0x55555555 / 0xAAAAAAAA 6200 // [2] = 0x33333333 / 0xCCCCCCCC 6201 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6202 // [8] = 0x00FF00FF / 0xFF00FF00 6203 // [16] = 0x0000FFFF / 0xFFFFFFFF 6204 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6205 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6206 // These are the unshifted masks which we use to match bit-manipulation 6207 // patterns. They may be shifted left in certain circumstances. 6208 static const uint64_t BitmanipMasks[] = { 6209 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6210 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6211 6212 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6213 } 6214 6215 // Match the following pattern as a GREVI(W) operation 6216 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6217 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6218 const RISCVSubtarget &Subtarget) { 6219 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6220 EVT VT = Op.getValueType(); 6221 6222 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6223 auto LHS = matchGREVIPat(Op.getOperand(0)); 6224 auto RHS = matchGREVIPat(Op.getOperand(1)); 6225 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6226 SDLoc DL(Op); 6227 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6228 DAG.getConstant(LHS->ShAmt, DL, VT)); 6229 } 6230 } 6231 return SDValue(); 6232 } 6233 6234 // Matches any the following pattern as a GORCI(W) operation 6235 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6236 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6237 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6238 // Note that with the variant of 3., 6239 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6240 // the inner pattern will first be matched as GREVI and then the outer 6241 // pattern will be matched to GORC via the first rule above. 6242 // 4. (or (rotl/rotr x, bitwidth/2), x) 6243 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6244 const RISCVSubtarget &Subtarget) { 6245 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6246 EVT VT = Op.getValueType(); 6247 6248 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6249 SDLoc DL(Op); 6250 SDValue Op0 = Op.getOperand(0); 6251 SDValue Op1 = Op.getOperand(1); 6252 6253 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6254 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6255 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6256 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6257 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6258 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6259 if ((Reverse.getOpcode() == ISD::ROTL || 6260 Reverse.getOpcode() == ISD::ROTR) && 6261 Reverse.getOperand(0) == X && 6262 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6263 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6264 if (RotAmt == (VT.getSizeInBits() / 2)) 6265 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6266 DAG.getConstant(RotAmt, DL, VT)); 6267 } 6268 return SDValue(); 6269 }; 6270 6271 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6272 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6273 return V; 6274 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6275 return V; 6276 6277 // OR is commutable so canonicalize its OR operand to the left 6278 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6279 std::swap(Op0, Op1); 6280 if (Op0.getOpcode() != ISD::OR) 6281 return SDValue(); 6282 SDValue OrOp0 = Op0.getOperand(0); 6283 SDValue OrOp1 = Op0.getOperand(1); 6284 auto LHS = matchGREVIPat(OrOp0); 6285 // OR is commutable so swap the operands and try again: x might have been 6286 // on the left 6287 if (!LHS) { 6288 std::swap(OrOp0, OrOp1); 6289 LHS = matchGREVIPat(OrOp0); 6290 } 6291 auto RHS = matchGREVIPat(Op1); 6292 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6293 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6294 DAG.getConstant(LHS->ShAmt, DL, VT)); 6295 } 6296 } 6297 return SDValue(); 6298 } 6299 6300 // Matches any of the following bit-manipulation patterns: 6301 // (and (shl x, 1), (0x22222222 << 1)) 6302 // (and (srl x, 1), 0x22222222) 6303 // (shl (and x, 0x22222222), 1) 6304 // (srl (and x, (0x22222222 << 1)), 1) 6305 // where the shift amount and mask may vary thus: 6306 // [1] = 0x22222222 / 0x44444444 6307 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6308 // [4] = 0x00F000F0 / 0x0F000F00 6309 // [8] = 0x0000FF00 / 0x00FF0000 6310 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6311 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6312 // These are the unshifted masks which we use to match bit-manipulation 6313 // patterns. They may be shifted left in certain circumstances. 6314 static const uint64_t BitmanipMasks[] = { 6315 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6316 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6317 6318 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6319 } 6320 6321 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6322 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6323 const RISCVSubtarget &Subtarget) { 6324 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6325 EVT VT = Op.getValueType(); 6326 6327 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6328 return SDValue(); 6329 6330 SDValue Op0 = Op.getOperand(0); 6331 SDValue Op1 = Op.getOperand(1); 6332 6333 // Or is commutable so canonicalize the second OR to the LHS. 6334 if (Op0.getOpcode() != ISD::OR) 6335 std::swap(Op0, Op1); 6336 if (Op0.getOpcode() != ISD::OR) 6337 return SDValue(); 6338 6339 // We found an inner OR, so our operands are the operands of the inner OR 6340 // and the other operand of the outer OR. 6341 SDValue A = Op0.getOperand(0); 6342 SDValue B = Op0.getOperand(1); 6343 SDValue C = Op1; 6344 6345 auto Match1 = matchSHFLPat(A); 6346 auto Match2 = matchSHFLPat(B); 6347 6348 // If neither matched, we failed. 6349 if (!Match1 && !Match2) 6350 return SDValue(); 6351 6352 // We had at least one match. if one failed, try the remaining C operand. 6353 if (!Match1) { 6354 std::swap(A, C); 6355 Match1 = matchSHFLPat(A); 6356 if (!Match1) 6357 return SDValue(); 6358 } else if (!Match2) { 6359 std::swap(B, C); 6360 Match2 = matchSHFLPat(B); 6361 if (!Match2) 6362 return SDValue(); 6363 } 6364 assert(Match1 && Match2); 6365 6366 // Make sure our matches pair up. 6367 if (!Match1->formsPairWith(*Match2)) 6368 return SDValue(); 6369 6370 // All the remains is to make sure C is an AND with the same input, that masks 6371 // out the bits that are being shuffled. 6372 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 6373 C.getOperand(0) != Match1->Op) 6374 return SDValue(); 6375 6376 uint64_t Mask = C.getConstantOperandVal(1); 6377 6378 static const uint64_t BitmanipMasks[] = { 6379 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 6380 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 6381 }; 6382 6383 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6384 unsigned MaskIdx = Log2_32(Match1->ShAmt); 6385 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6386 6387 if (Mask != ExpMask) 6388 return SDValue(); 6389 6390 SDLoc DL(Op); 6391 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 6392 DAG.getConstant(Match1->ShAmt, DL, VT)); 6393 } 6394 6395 // Optimize (add (shl x, c0), (shl y, c1)) -> 6396 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 6397 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 6398 const RISCVSubtarget &Subtarget) { 6399 // Perform this optimization only in the zba extension. 6400 if (!Subtarget.hasStdExtZba()) 6401 return SDValue(); 6402 6403 // Skip for vector types and larger types. 6404 EVT VT = N->getValueType(0); 6405 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6406 return SDValue(); 6407 6408 // The two operand nodes must be SHL and have no other use. 6409 SDValue N0 = N->getOperand(0); 6410 SDValue N1 = N->getOperand(1); 6411 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 6412 !N0->hasOneUse() || !N1->hasOneUse()) 6413 return SDValue(); 6414 6415 // Check c0 and c1. 6416 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6417 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 6418 if (!N0C || !N1C) 6419 return SDValue(); 6420 int64_t C0 = N0C->getSExtValue(); 6421 int64_t C1 = N1C->getSExtValue(); 6422 if (C0 <= 0 || C1 <= 0) 6423 return SDValue(); 6424 6425 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 6426 int64_t Bits = std::min(C0, C1); 6427 int64_t Diff = std::abs(C0 - C1); 6428 if (Diff != 1 && Diff != 2 && Diff != 3) 6429 return SDValue(); 6430 6431 // Build nodes. 6432 SDLoc DL(N); 6433 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 6434 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 6435 SDValue NA0 = 6436 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 6437 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 6438 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 6439 } 6440 6441 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 6442 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 6443 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 6444 // not undo itself, but they are redundant. 6445 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 6446 SDValue Src = N->getOperand(0); 6447 6448 if (Src.getOpcode() != N->getOpcode()) 6449 return SDValue(); 6450 6451 if (!isa<ConstantSDNode>(N->getOperand(1)) || 6452 !isa<ConstantSDNode>(Src.getOperand(1))) 6453 return SDValue(); 6454 6455 unsigned ShAmt1 = N->getConstantOperandVal(1); 6456 unsigned ShAmt2 = Src.getConstantOperandVal(1); 6457 Src = Src.getOperand(0); 6458 6459 unsigned CombinedShAmt; 6460 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 6461 CombinedShAmt = ShAmt1 | ShAmt2; 6462 else 6463 CombinedShAmt = ShAmt1 ^ ShAmt2; 6464 6465 if (CombinedShAmt == 0) 6466 return Src; 6467 6468 SDLoc DL(N); 6469 return DAG.getNode( 6470 N->getOpcode(), DL, N->getValueType(0), Src, 6471 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 6472 } 6473 6474 // Combine a constant select operand into its use: 6475 // 6476 // (and (select cond, -1, c), x) 6477 // -> (select cond, x, (and x, c)) [AllOnes=1] 6478 // (or (select cond, 0, c), x) 6479 // -> (select cond, x, (or x, c)) [AllOnes=0] 6480 // (xor (select cond, 0, c), x) 6481 // -> (select cond, x, (xor x, c)) [AllOnes=0] 6482 // (add (select cond, 0, c), x) 6483 // -> (select cond, x, (add x, c)) [AllOnes=0] 6484 // (sub x, (select cond, 0, c)) 6485 // -> (select cond, x, (sub x, c)) [AllOnes=0] 6486 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 6487 SelectionDAG &DAG, bool AllOnes) { 6488 EVT VT = N->getValueType(0); 6489 6490 // Skip vectors. 6491 if (VT.isVector()) 6492 return SDValue(); 6493 6494 if ((Slct.getOpcode() != ISD::SELECT && 6495 Slct.getOpcode() != RISCVISD::SELECT_CC) || 6496 !Slct.hasOneUse()) 6497 return SDValue(); 6498 6499 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 6500 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 6501 }; 6502 6503 bool SwapSelectOps; 6504 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 6505 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 6506 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 6507 SDValue NonConstantVal; 6508 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 6509 SwapSelectOps = false; 6510 NonConstantVal = FalseVal; 6511 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 6512 SwapSelectOps = true; 6513 NonConstantVal = TrueVal; 6514 } else 6515 return SDValue(); 6516 6517 // Slct is now know to be the desired identity constant when CC is true. 6518 TrueVal = OtherOp; 6519 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 6520 // Unless SwapSelectOps says the condition should be false. 6521 if (SwapSelectOps) 6522 std::swap(TrueVal, FalseVal); 6523 6524 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 6525 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 6526 {Slct.getOperand(0), Slct.getOperand(1), 6527 Slct.getOperand(2), TrueVal, FalseVal}); 6528 6529 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 6530 {Slct.getOperand(0), TrueVal, FalseVal}); 6531 } 6532 6533 // Attempt combineSelectAndUse on each operand of a commutative operator N. 6534 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 6535 bool AllOnes) { 6536 SDValue N0 = N->getOperand(0); 6537 SDValue N1 = N->getOperand(1); 6538 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 6539 return Result; 6540 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 6541 return Result; 6542 return SDValue(); 6543 } 6544 6545 // Transform (add (mul x, c0), c1) -> 6546 // (add (mul (add x, c1/c0), c0), c1%c0). 6547 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 6548 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 6549 // to an infinite loop in DAGCombine if transformed. 6550 // Or transform (add (mul x, c0), c1) -> 6551 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 6552 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 6553 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 6554 // lead to an infinite loop in DAGCombine if transformed. 6555 // Or transform (add (mul x, c0), c1) -> 6556 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 6557 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 6558 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 6559 // lead to an infinite loop in DAGCombine if transformed. 6560 // Or transform (add (mul x, c0), c1) -> 6561 // (mul (add x, c1/c0), c0). 6562 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 6563 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 6564 const RISCVSubtarget &Subtarget) { 6565 // Skip for vector types and larger types. 6566 EVT VT = N->getValueType(0); 6567 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6568 return SDValue(); 6569 // The first operand node must be a MUL and has no other use. 6570 SDValue N0 = N->getOperand(0); 6571 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 6572 return SDValue(); 6573 // Check if c0 and c1 match above conditions. 6574 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6575 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6576 if (!N0C || !N1C) 6577 return SDValue(); 6578 int64_t C0 = N0C->getSExtValue(); 6579 int64_t C1 = N1C->getSExtValue(); 6580 int64_t CA, CB; 6581 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 6582 return SDValue(); 6583 // Search for proper CA (non-zero) and CB that both are simm12. 6584 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 6585 !isInt<12>(C0 * (C1 / C0))) { 6586 CA = C1 / C0; 6587 CB = C1 % C0; 6588 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 6589 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 6590 CA = C1 / C0 + 1; 6591 CB = C1 % C0 - C0; 6592 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 6593 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 6594 CA = C1 / C0 - 1; 6595 CB = C1 % C0 + C0; 6596 } else 6597 return SDValue(); 6598 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 6599 SDLoc DL(N); 6600 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 6601 DAG.getConstant(CA, DL, VT)); 6602 SDValue New1 = 6603 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 6604 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 6605 } 6606 6607 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 6608 const RISCVSubtarget &Subtarget) { 6609 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 6610 return V; 6611 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 6612 return V; 6613 // fold (add (select lhs, rhs, cc, 0, y), x) -> 6614 // (select lhs, rhs, cc, x, (add x, y)) 6615 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6616 } 6617 6618 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 6619 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 6620 // (select lhs, rhs, cc, x, (sub x, y)) 6621 SDValue N0 = N->getOperand(0); 6622 SDValue N1 = N->getOperand(1); 6623 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 6624 } 6625 6626 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 6627 // fold (and (select lhs, rhs, cc, -1, y), x) -> 6628 // (select lhs, rhs, cc, x, (and x, y)) 6629 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 6630 } 6631 6632 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 6633 const RISCVSubtarget &Subtarget) { 6634 if (Subtarget.hasStdExtZbp()) { 6635 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 6636 return GREV; 6637 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 6638 return GORC; 6639 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 6640 return SHFL; 6641 } 6642 6643 // fold (or (select cond, 0, y), x) -> 6644 // (select cond, x, (or x, y)) 6645 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6646 } 6647 6648 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 6649 // fold (xor (select cond, 0, y), x) -> 6650 // (select cond, x, (xor x, y)) 6651 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6652 } 6653 6654 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 6655 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 6656 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 6657 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 6658 // ADDW/SUBW/MULW. 6659 static SDValue performANY_EXTENDCombine(SDNode *N, 6660 TargetLowering::DAGCombinerInfo &DCI, 6661 const RISCVSubtarget &Subtarget) { 6662 if (!Subtarget.is64Bit()) 6663 return SDValue(); 6664 6665 SelectionDAG &DAG = DCI.DAG; 6666 6667 SDValue Src = N->getOperand(0); 6668 EVT VT = N->getValueType(0); 6669 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 6670 return SDValue(); 6671 6672 // The opcode must be one that can implicitly sign_extend. 6673 // FIXME: Additional opcodes. 6674 switch (Src.getOpcode()) { 6675 default: 6676 return SDValue(); 6677 case ISD::MUL: 6678 if (!Subtarget.hasStdExtM()) 6679 return SDValue(); 6680 LLVM_FALLTHROUGH; 6681 case ISD::ADD: 6682 case ISD::SUB: 6683 break; 6684 } 6685 6686 // Only handle cases where the result is used by a CopyToReg. That likely 6687 // means the value is a liveout of the basic block. This helps prevent 6688 // infinite combine loops like PR51206. 6689 if (none_of(N->uses(), 6690 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 6691 return SDValue(); 6692 6693 SmallVector<SDNode *, 4> SetCCs; 6694 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 6695 UE = Src.getNode()->use_end(); 6696 UI != UE; ++UI) { 6697 SDNode *User = *UI; 6698 if (User == N) 6699 continue; 6700 if (UI.getUse().getResNo() != Src.getResNo()) 6701 continue; 6702 // All i32 setccs are legalized by sign extending operands. 6703 if (User->getOpcode() == ISD::SETCC) { 6704 SetCCs.push_back(User); 6705 continue; 6706 } 6707 // We don't know if we can extend this user. 6708 break; 6709 } 6710 6711 // If we don't have any SetCCs, this isn't worthwhile. 6712 if (SetCCs.empty()) 6713 return SDValue(); 6714 6715 SDLoc DL(N); 6716 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 6717 DCI.CombineTo(N, SExt); 6718 6719 // Promote all the setccs. 6720 for (SDNode *SetCC : SetCCs) { 6721 SmallVector<SDValue, 4> Ops; 6722 6723 for (unsigned j = 0; j != 2; ++j) { 6724 SDValue SOp = SetCC->getOperand(j); 6725 if (SOp == Src) 6726 Ops.push_back(SExt); 6727 else 6728 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 6729 } 6730 6731 Ops.push_back(SetCC->getOperand(2)); 6732 DCI.CombineTo(SetCC, 6733 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6734 } 6735 return SDValue(N, 0); 6736 } 6737 6738 // Try to form VWMUL or VWMULU. 6739 // FIXME: Support VWMULSU. 6740 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1, 6741 SelectionDAG &DAG) { 6742 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 6743 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 6744 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 6745 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 6746 return SDValue(); 6747 6748 SDValue Mask = N->getOperand(2); 6749 SDValue VL = N->getOperand(3); 6750 6751 // Make sure the mask and VL match. 6752 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 6753 return SDValue(); 6754 6755 MVT VT = N->getSimpleValueType(0); 6756 6757 // Determine the narrow size for a widening multiply. 6758 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 6759 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 6760 VT.getVectorElementCount()); 6761 6762 SDLoc DL(N); 6763 6764 // See if the other operand is the same opcode. 6765 if (Op0.getOpcode() == Op1.getOpcode()) { 6766 if (!Op1.hasOneUse()) 6767 return SDValue(); 6768 6769 // Make sure the mask and VL match. 6770 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 6771 return SDValue(); 6772 6773 Op1 = Op1.getOperand(0); 6774 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 6775 // The operand is a splat of a scalar. 6776 6777 // The VL must be the same. 6778 if (Op1.getOperand(1) != VL) 6779 return SDValue(); 6780 6781 // Get the scalar value. 6782 Op1 = Op1.getOperand(0); 6783 6784 // See if have enough sign bits or zero bits in the scalar to use a 6785 // widening multiply by splatting to smaller element size. 6786 unsigned EltBits = VT.getScalarSizeInBits(); 6787 unsigned ScalarBits = Op1.getValueSizeInBits(); 6788 // Make sure we're getting all element bits from the scalar register. 6789 // FIXME: Support implicit sign extension of vmv.v.x? 6790 if (ScalarBits < EltBits) 6791 return SDValue(); 6792 6793 if (IsSignExt) { 6794 if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize)) 6795 return SDValue(); 6796 } else { 6797 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 6798 if (!DAG.MaskedValueIsZero(Op1, Mask)) 6799 return SDValue(); 6800 } 6801 6802 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 6803 } else 6804 return SDValue(); 6805 6806 Op0 = Op0.getOperand(0); 6807 6808 // Re-introduce narrower extends if needed. 6809 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 6810 if (Op0.getValueType() != NarrowVT) 6811 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 6812 if (Op1.getValueType() != NarrowVT) 6813 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 6814 6815 unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 6816 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 6817 } 6818 6819 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 6820 DAGCombinerInfo &DCI) const { 6821 SelectionDAG &DAG = DCI.DAG; 6822 6823 // Helper to call SimplifyDemandedBits on an operand of N where only some low 6824 // bits are demanded. N will be added to the Worklist if it was not deleted. 6825 // Caller should return SDValue(N, 0) if this returns true. 6826 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 6827 SDValue Op = N->getOperand(OpNo); 6828 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 6829 if (!SimplifyDemandedBits(Op, Mask, DCI)) 6830 return false; 6831 6832 if (N->getOpcode() != ISD::DELETED_NODE) 6833 DCI.AddToWorklist(N); 6834 return true; 6835 }; 6836 6837 switch (N->getOpcode()) { 6838 default: 6839 break; 6840 case RISCVISD::SplitF64: { 6841 SDValue Op0 = N->getOperand(0); 6842 // If the input to SplitF64 is just BuildPairF64 then the operation is 6843 // redundant. Instead, use BuildPairF64's operands directly. 6844 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 6845 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 6846 6847 SDLoc DL(N); 6848 6849 // It's cheaper to materialise two 32-bit integers than to load a double 6850 // from the constant pool and transfer it to integer registers through the 6851 // stack. 6852 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 6853 APInt V = C->getValueAPF().bitcastToAPInt(); 6854 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 6855 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 6856 return DCI.CombineTo(N, Lo, Hi); 6857 } 6858 6859 // This is a target-specific version of a DAGCombine performed in 6860 // DAGCombiner::visitBITCAST. It performs the equivalent of: 6861 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6862 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6863 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 6864 !Op0.getNode()->hasOneUse()) 6865 break; 6866 SDValue NewSplitF64 = 6867 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 6868 Op0.getOperand(0)); 6869 SDValue Lo = NewSplitF64.getValue(0); 6870 SDValue Hi = NewSplitF64.getValue(1); 6871 APInt SignBit = APInt::getSignMask(32); 6872 if (Op0.getOpcode() == ISD::FNEG) { 6873 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 6874 DAG.getConstant(SignBit, DL, MVT::i32)); 6875 return DCI.CombineTo(N, Lo, NewHi); 6876 } 6877 assert(Op0.getOpcode() == ISD::FABS); 6878 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 6879 DAG.getConstant(~SignBit, DL, MVT::i32)); 6880 return DCI.CombineTo(N, Lo, NewHi); 6881 } 6882 case RISCVISD::SLLW: 6883 case RISCVISD::SRAW: 6884 case RISCVISD::SRLW: 6885 case RISCVISD::ROLW: 6886 case RISCVISD::RORW: { 6887 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 6888 if (SimplifyDemandedLowBitsHelper(0, 32) || 6889 SimplifyDemandedLowBitsHelper(1, 5)) 6890 return SDValue(N, 0); 6891 break; 6892 } 6893 case RISCVISD::CLZW: 6894 case RISCVISD::CTZW: { 6895 // Only the lower 32 bits of the first operand are read 6896 if (SimplifyDemandedLowBitsHelper(0, 32)) 6897 return SDValue(N, 0); 6898 break; 6899 } 6900 case RISCVISD::FSL: 6901 case RISCVISD::FSR: { 6902 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 6903 unsigned BitWidth = N->getOperand(2).getValueSizeInBits(); 6904 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6905 if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1)) 6906 return SDValue(N, 0); 6907 break; 6908 } 6909 case RISCVISD::FSLW: 6910 case RISCVISD::FSRW: { 6911 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 6912 // read. 6913 if (SimplifyDemandedLowBitsHelper(0, 32) || 6914 SimplifyDemandedLowBitsHelper(1, 32) || 6915 SimplifyDemandedLowBitsHelper(2, 6)) 6916 return SDValue(N, 0); 6917 break; 6918 } 6919 case RISCVISD::GREV: 6920 case RISCVISD::GORC: { 6921 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 6922 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 6923 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6924 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 6925 return SDValue(N, 0); 6926 6927 return combineGREVI_GORCI(N, DCI.DAG); 6928 } 6929 case RISCVISD::GREVW: 6930 case RISCVISD::GORCW: { 6931 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 6932 if (SimplifyDemandedLowBitsHelper(0, 32) || 6933 SimplifyDemandedLowBitsHelper(1, 5)) 6934 return SDValue(N, 0); 6935 6936 return combineGREVI_GORCI(N, DCI.DAG); 6937 } 6938 case RISCVISD::SHFL: 6939 case RISCVISD::UNSHFL: { 6940 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 6941 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 6942 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6943 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 6944 return SDValue(N, 0); 6945 6946 break; 6947 } 6948 case RISCVISD::SHFLW: 6949 case RISCVISD::UNSHFLW: { 6950 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 6951 SDValue LHS = N->getOperand(0); 6952 SDValue RHS = N->getOperand(1); 6953 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 6954 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4); 6955 if (SimplifyDemandedLowBitsHelper(0, 32) || 6956 SimplifyDemandedLowBitsHelper(1, 4)) 6957 return SDValue(N, 0); 6958 6959 break; 6960 } 6961 case RISCVISD::BCOMPRESSW: 6962 case RISCVISD::BDECOMPRESSW: { 6963 // Only the lower 32 bits of LHS and RHS are read. 6964 if (SimplifyDemandedLowBitsHelper(0, 32) || 6965 SimplifyDemandedLowBitsHelper(1, 32)) 6966 return SDValue(N, 0); 6967 6968 break; 6969 } 6970 case RISCVISD::FMV_X_ANYEXTH: 6971 case RISCVISD::FMV_X_ANYEXTW_RV64: { 6972 SDLoc DL(N); 6973 SDValue Op0 = N->getOperand(0); 6974 MVT VT = N->getSimpleValueType(0); 6975 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 6976 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 6977 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 6978 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 6979 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 6980 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 6981 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 6982 assert(Op0.getOperand(0).getValueType() == VT && 6983 "Unexpected value type!"); 6984 return Op0.getOperand(0); 6985 } 6986 6987 // This is a target-specific version of a DAGCombine performed in 6988 // DAGCombiner::visitBITCAST. It performs the equivalent of: 6989 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6990 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6991 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 6992 !Op0.getNode()->hasOneUse()) 6993 break; 6994 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 6995 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 6996 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 6997 if (Op0.getOpcode() == ISD::FNEG) 6998 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 6999 DAG.getConstant(SignBit, DL, VT)); 7000 7001 assert(Op0.getOpcode() == ISD::FABS); 7002 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 7003 DAG.getConstant(~SignBit, DL, VT)); 7004 } 7005 case ISD::ADD: 7006 return performADDCombine(N, DAG, Subtarget); 7007 case ISD::SUB: 7008 return performSUBCombine(N, DAG); 7009 case ISD::AND: 7010 return performANDCombine(N, DAG); 7011 case ISD::OR: 7012 return performORCombine(N, DAG, Subtarget); 7013 case ISD::XOR: 7014 return performXORCombine(N, DAG); 7015 case ISD::ANY_EXTEND: 7016 return performANY_EXTENDCombine(N, DCI, Subtarget); 7017 case ISD::ZERO_EXTEND: 7018 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 7019 // type legalization. This is safe because fp_to_uint produces poison if 7020 // it overflows. 7021 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() && 7022 N->getOperand(0).getOpcode() == ISD::FP_TO_UINT && 7023 isTypeLegal(N->getOperand(0).getOperand(0).getValueType())) 7024 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 7025 N->getOperand(0).getOperand(0)); 7026 return SDValue(); 7027 case RISCVISD::SELECT_CC: { 7028 // Transform 7029 SDValue LHS = N->getOperand(0); 7030 SDValue RHS = N->getOperand(1); 7031 SDValue TrueV = N->getOperand(3); 7032 SDValue FalseV = N->getOperand(4); 7033 7034 // If the True and False values are the same, we don't need a select_cc. 7035 if (TrueV == FalseV) 7036 return TrueV; 7037 7038 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 7039 if (!ISD::isIntEqualitySetCC(CCVal)) 7040 break; 7041 7042 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 7043 // (select_cc X, Y, lt, trueV, falseV) 7044 // Sometimes the setcc is introduced after select_cc has been formed. 7045 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7046 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7047 // If we're looking for eq 0 instead of ne 0, we need to invert the 7048 // condition. 7049 bool Invert = CCVal == ISD::SETEQ; 7050 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7051 if (Invert) 7052 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7053 7054 SDLoc DL(N); 7055 RHS = LHS.getOperand(1); 7056 LHS = LHS.getOperand(0); 7057 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7058 7059 SDValue TargetCC = DAG.getCondCode(CCVal); 7060 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7061 {LHS, RHS, TargetCC, TrueV, FalseV}); 7062 } 7063 7064 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 7065 // (select_cc X, Y, eq/ne, trueV, falseV) 7066 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7067 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 7068 {LHS.getOperand(0), LHS.getOperand(1), 7069 N->getOperand(2), TrueV, FalseV}); 7070 // (select_cc X, 1, setne, trueV, falseV) -> 7071 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 7072 // This can occur when legalizing some floating point comparisons. 7073 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7074 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7075 SDLoc DL(N); 7076 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7077 SDValue TargetCC = DAG.getCondCode(CCVal); 7078 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7079 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7080 {LHS, RHS, TargetCC, TrueV, FalseV}); 7081 } 7082 7083 break; 7084 } 7085 case RISCVISD::BR_CC: { 7086 SDValue LHS = N->getOperand(1); 7087 SDValue RHS = N->getOperand(2); 7088 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 7089 if (!ISD::isIntEqualitySetCC(CCVal)) 7090 break; 7091 7092 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 7093 // (br_cc X, Y, lt, dest) 7094 // Sometimes the setcc is introduced after br_cc has been formed. 7095 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7096 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7097 // If we're looking for eq 0 instead of ne 0, we need to invert the 7098 // condition. 7099 bool Invert = CCVal == ISD::SETEQ; 7100 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7101 if (Invert) 7102 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7103 7104 SDLoc DL(N); 7105 RHS = LHS.getOperand(1); 7106 LHS = LHS.getOperand(0); 7107 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7108 7109 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7110 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 7111 N->getOperand(4)); 7112 } 7113 7114 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 7115 // (br_cc X, Y, eq/ne, trueV, falseV) 7116 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7117 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 7118 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 7119 N->getOperand(3), N->getOperand(4)); 7120 7121 // (br_cc X, 1, setne, br_cc) -> 7122 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 7123 // This can occur when legalizing some floating point comparisons. 7124 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7125 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7126 SDLoc DL(N); 7127 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7128 SDValue TargetCC = DAG.getCondCode(CCVal); 7129 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7130 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7131 N->getOperand(0), LHS, RHS, TargetCC, 7132 N->getOperand(4)); 7133 } 7134 break; 7135 } 7136 case ISD::FCOPYSIGN: { 7137 EVT VT = N->getValueType(0); 7138 if (!VT.isVector()) 7139 break; 7140 // There is a form of VFSGNJ which injects the negated sign of its second 7141 // operand. Try and bubble any FNEG up after the extend/round to produce 7142 // this optimized pattern. Avoid modifying cases where FP_ROUND and 7143 // TRUNC=1. 7144 SDValue In2 = N->getOperand(1); 7145 // Avoid cases where the extend/round has multiple uses, as duplicating 7146 // those is typically more expensive than removing a fneg. 7147 if (!In2.hasOneUse()) 7148 break; 7149 if (In2.getOpcode() != ISD::FP_EXTEND && 7150 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 7151 break; 7152 In2 = In2.getOperand(0); 7153 if (In2.getOpcode() != ISD::FNEG) 7154 break; 7155 SDLoc DL(N); 7156 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 7157 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 7158 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 7159 } 7160 case ISD::MGATHER: 7161 case ISD::MSCATTER: 7162 case ISD::VP_GATHER: 7163 case ISD::VP_SCATTER: { 7164 if (!DCI.isBeforeLegalize()) 7165 break; 7166 SDValue Index, ScaleOp; 7167 bool IsIndexScaled = false; 7168 bool IsIndexSigned = false; 7169 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 7170 Index = VPGSN->getIndex(); 7171 ScaleOp = VPGSN->getScale(); 7172 IsIndexScaled = VPGSN->isIndexScaled(); 7173 IsIndexSigned = VPGSN->isIndexSigned(); 7174 } else { 7175 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 7176 Index = MGSN->getIndex(); 7177 ScaleOp = MGSN->getScale(); 7178 IsIndexScaled = MGSN->isIndexScaled(); 7179 IsIndexSigned = MGSN->isIndexSigned(); 7180 } 7181 EVT IndexVT = Index.getValueType(); 7182 MVT XLenVT = Subtarget.getXLenVT(); 7183 // RISCV indexed loads only support the "unsigned unscaled" addressing 7184 // mode, so anything else must be manually legalized. 7185 bool NeedsIdxLegalization = 7186 IsIndexScaled || 7187 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 7188 if (!NeedsIdxLegalization) 7189 break; 7190 7191 SDLoc DL(N); 7192 7193 // Any index legalization should first promote to XLenVT, so we don't lose 7194 // bits when scaling. This may create an illegal index type so we let 7195 // LLVM's legalization take care of the splitting. 7196 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 7197 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 7198 IndexVT = IndexVT.changeVectorElementType(XLenVT); 7199 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 7200 DL, IndexVT, Index); 7201 } 7202 7203 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 7204 if (IsIndexScaled && Scale != 1) { 7205 // Manually scale the indices by the element size. 7206 // TODO: Sanitize the scale operand here? 7207 // TODO: For VP nodes, should we use VP_SHL here? 7208 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 7209 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 7210 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 7211 } 7212 7213 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 7214 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 7215 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 7216 {VPGN->getChain(), VPGN->getBasePtr(), Index, 7217 VPGN->getScale(), VPGN->getMask(), 7218 VPGN->getVectorLength()}, 7219 VPGN->getMemOperand(), NewIndexTy); 7220 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 7221 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 7222 {VPSN->getChain(), VPSN->getValue(), 7223 VPSN->getBasePtr(), Index, VPSN->getScale(), 7224 VPSN->getMask(), VPSN->getVectorLength()}, 7225 VPSN->getMemOperand(), NewIndexTy); 7226 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 7227 return DAG.getMaskedGather( 7228 N->getVTList(), MGN->getMemoryVT(), DL, 7229 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 7230 MGN->getBasePtr(), Index, MGN->getScale()}, 7231 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 7232 const auto *MSN = cast<MaskedScatterSDNode>(N); 7233 return DAG.getMaskedScatter( 7234 N->getVTList(), MSN->getMemoryVT(), DL, 7235 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 7236 Index, MSN->getScale()}, 7237 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 7238 } 7239 case RISCVISD::SRA_VL: 7240 case RISCVISD::SRL_VL: 7241 case RISCVISD::SHL_VL: { 7242 SDValue ShAmt = N->getOperand(1); 7243 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7244 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7245 SDLoc DL(N); 7246 SDValue VL = N->getOperand(3); 7247 EVT VT = N->getValueType(0); 7248 ShAmt = 7249 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 7250 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 7251 N->getOperand(2), N->getOperand(3)); 7252 } 7253 break; 7254 } 7255 case ISD::SRA: 7256 case ISD::SRL: 7257 case ISD::SHL: { 7258 SDValue ShAmt = N->getOperand(1); 7259 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7260 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7261 SDLoc DL(N); 7262 EVT VT = N->getValueType(0); 7263 ShAmt = 7264 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 7265 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 7266 } 7267 break; 7268 } 7269 case RISCVISD::MUL_VL: { 7270 SDValue Op0 = N->getOperand(0); 7271 SDValue Op1 = N->getOperand(1); 7272 if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG)) 7273 return V; 7274 if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG)) 7275 return V; 7276 return SDValue(); 7277 } 7278 case ISD::STORE: { 7279 auto *Store = cast<StoreSDNode>(N); 7280 SDValue Val = Store->getValue(); 7281 // Combine store of vmv.x.s to vse with VL of 1. 7282 // FIXME: Support FP. 7283 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 7284 SDValue Src = Val.getOperand(0); 7285 EVT VecVT = Src.getValueType(); 7286 EVT MemVT = Store->getMemoryVT(); 7287 // The memory VT and the element type must match. 7288 if (VecVT.getVectorElementType() == MemVT) { 7289 SDLoc DL(N); 7290 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7291 return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(), 7292 DAG.getConstant(1, DL, MaskVT), 7293 DAG.getConstant(1, DL, Subtarget.getXLenVT()), 7294 Store->getPointerInfo(), 7295 Store->getOriginalAlign(), 7296 Store->getMemOperand()->getFlags()); 7297 } 7298 } 7299 7300 break; 7301 } 7302 } 7303 7304 return SDValue(); 7305 } 7306 7307 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 7308 const SDNode *N, CombineLevel Level) const { 7309 // The following folds are only desirable if `(OP _, c1 << c2)` can be 7310 // materialised in fewer instructions than `(OP _, c1)`: 7311 // 7312 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 7313 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 7314 SDValue N0 = N->getOperand(0); 7315 EVT Ty = N0.getValueType(); 7316 if (Ty.isScalarInteger() && 7317 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 7318 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7319 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7320 if (C1 && C2) { 7321 const APInt &C1Int = C1->getAPIntValue(); 7322 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 7323 7324 // We can materialise `c1 << c2` into an add immediate, so it's "free", 7325 // and the combine should happen, to potentially allow further combines 7326 // later. 7327 if (ShiftedC1Int.getMinSignedBits() <= 64 && 7328 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 7329 return true; 7330 7331 // We can materialise `c1` in an add immediate, so it's "free", and the 7332 // combine should be prevented. 7333 if (C1Int.getMinSignedBits() <= 64 && 7334 isLegalAddImmediate(C1Int.getSExtValue())) 7335 return false; 7336 7337 // Neither constant will fit into an immediate, so find materialisation 7338 // costs. 7339 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 7340 Subtarget.getFeatureBits(), 7341 /*CompressionCost*/true); 7342 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 7343 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 7344 /*CompressionCost*/true); 7345 7346 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 7347 // combine should be prevented. 7348 if (C1Cost < ShiftedC1Cost) 7349 return false; 7350 } 7351 } 7352 return true; 7353 } 7354 7355 bool RISCVTargetLowering::targetShrinkDemandedConstant( 7356 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 7357 TargetLoweringOpt &TLO) const { 7358 // Delay this optimization as late as possible. 7359 if (!TLO.LegalOps) 7360 return false; 7361 7362 EVT VT = Op.getValueType(); 7363 if (VT.isVector()) 7364 return false; 7365 7366 // Only handle AND for now. 7367 if (Op.getOpcode() != ISD::AND) 7368 return false; 7369 7370 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7371 if (!C) 7372 return false; 7373 7374 const APInt &Mask = C->getAPIntValue(); 7375 7376 // Clear all non-demanded bits initially. 7377 APInt ShrunkMask = Mask & DemandedBits; 7378 7379 // Try to make a smaller immediate by setting undemanded bits. 7380 7381 APInt ExpandedMask = Mask | ~DemandedBits; 7382 7383 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 7384 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 7385 }; 7386 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 7387 if (NewMask == Mask) 7388 return true; 7389 SDLoc DL(Op); 7390 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 7391 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 7392 return TLO.CombineTo(Op, NewOp); 7393 }; 7394 7395 // If the shrunk mask fits in sign extended 12 bits, let the target 7396 // independent code apply it. 7397 if (ShrunkMask.isSignedIntN(12)) 7398 return false; 7399 7400 // Preserve (and X, 0xffff) when zext.h is supported. 7401 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 7402 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 7403 if (IsLegalMask(NewMask)) 7404 return UseMask(NewMask); 7405 } 7406 7407 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 7408 if (VT == MVT::i64) { 7409 APInt NewMask = APInt(64, 0xffffffff); 7410 if (IsLegalMask(NewMask)) 7411 return UseMask(NewMask); 7412 } 7413 7414 // For the remaining optimizations, we need to be able to make a negative 7415 // number through a combination of mask and undemanded bits. 7416 if (!ExpandedMask.isNegative()) 7417 return false; 7418 7419 // What is the fewest number of bits we need to represent the negative number. 7420 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 7421 7422 // Try to make a 12 bit negative immediate. If that fails try to make a 32 7423 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 7424 APInt NewMask = ShrunkMask; 7425 if (MinSignedBits <= 12) 7426 NewMask.setBitsFrom(11); 7427 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 7428 NewMask.setBitsFrom(31); 7429 else 7430 return false; 7431 7432 // Check that our new mask is a subset of the demanded mask. 7433 assert(IsLegalMask(NewMask)); 7434 return UseMask(NewMask); 7435 } 7436 7437 static void computeGREV(APInt &Src, unsigned ShAmt) { 7438 ShAmt &= Src.getBitWidth() - 1; 7439 uint64_t x = Src.getZExtValue(); 7440 if (ShAmt & 1) 7441 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 7442 if (ShAmt & 2) 7443 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 7444 if (ShAmt & 4) 7445 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 7446 if (ShAmt & 8) 7447 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 7448 if (ShAmt & 16) 7449 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 7450 if (ShAmt & 32) 7451 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 7452 Src = x; 7453 } 7454 7455 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 7456 KnownBits &Known, 7457 const APInt &DemandedElts, 7458 const SelectionDAG &DAG, 7459 unsigned Depth) const { 7460 unsigned BitWidth = Known.getBitWidth(); 7461 unsigned Opc = Op.getOpcode(); 7462 assert((Opc >= ISD::BUILTIN_OP_END || 7463 Opc == ISD::INTRINSIC_WO_CHAIN || 7464 Opc == ISD::INTRINSIC_W_CHAIN || 7465 Opc == ISD::INTRINSIC_VOID) && 7466 "Should use MaskedValueIsZero if you don't know whether Op" 7467 " is a target node!"); 7468 7469 Known.resetAll(); 7470 switch (Opc) { 7471 default: break; 7472 case RISCVISD::SELECT_CC: { 7473 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 7474 // If we don't know any bits, early out. 7475 if (Known.isUnknown()) 7476 break; 7477 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 7478 7479 // Only known if known in both the LHS and RHS. 7480 Known = KnownBits::commonBits(Known, Known2); 7481 break; 7482 } 7483 case RISCVISD::REMUW: { 7484 KnownBits Known2; 7485 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7486 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7487 // We only care about the lower 32 bits. 7488 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 7489 // Restore the original width by sign extending. 7490 Known = Known.sext(BitWidth); 7491 break; 7492 } 7493 case RISCVISD::DIVUW: { 7494 KnownBits Known2; 7495 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7496 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7497 // We only care about the lower 32 bits. 7498 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 7499 // Restore the original width by sign extending. 7500 Known = Known.sext(BitWidth); 7501 break; 7502 } 7503 case RISCVISD::CTZW: { 7504 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7505 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 7506 unsigned LowBits = Log2_32(PossibleTZ) + 1; 7507 Known.Zero.setBitsFrom(LowBits); 7508 break; 7509 } 7510 case RISCVISD::CLZW: { 7511 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7512 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 7513 unsigned LowBits = Log2_32(PossibleLZ) + 1; 7514 Known.Zero.setBitsFrom(LowBits); 7515 break; 7516 } 7517 case RISCVISD::GREV: 7518 case RISCVISD::GREVW: { 7519 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7520 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7521 if (Opc == RISCVISD::GREVW) 7522 Known = Known.trunc(32); 7523 unsigned ShAmt = C->getZExtValue(); 7524 computeGREV(Known.Zero, ShAmt); 7525 computeGREV(Known.One, ShAmt); 7526 if (Opc == RISCVISD::GREVW) 7527 Known = Known.sext(BitWidth); 7528 } 7529 break; 7530 } 7531 case RISCVISD::READ_VLENB: 7532 // We assume VLENB is at least 16 bytes. 7533 Known.Zero.setLowBits(4); 7534 // We assume VLENB is no more than 65536 / 8 bytes. 7535 Known.Zero.setBitsFrom(14); 7536 break; 7537 case ISD::INTRINSIC_W_CHAIN: { 7538 unsigned IntNo = Op.getConstantOperandVal(1); 7539 switch (IntNo) { 7540 default: 7541 // We can't do anything for most intrinsics. 7542 break; 7543 case Intrinsic::riscv_vsetvli: 7544 case Intrinsic::riscv_vsetvlimax: 7545 // Assume that VL output is positive and would fit in an int32_t. 7546 // TODO: VLEN might be capped at 16 bits in a future V spec update. 7547 if (BitWidth >= 32) 7548 Known.Zero.setBitsFrom(31); 7549 break; 7550 } 7551 break; 7552 } 7553 } 7554 } 7555 7556 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 7557 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 7558 unsigned Depth) const { 7559 switch (Op.getOpcode()) { 7560 default: 7561 break; 7562 case RISCVISD::SELECT_CC: { 7563 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 7564 if (Tmp == 1) return 1; // Early out. 7565 unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 7566 return std::min(Tmp, Tmp2); 7567 } 7568 case RISCVISD::SLLW: 7569 case RISCVISD::SRAW: 7570 case RISCVISD::SRLW: 7571 case RISCVISD::DIVW: 7572 case RISCVISD::DIVUW: 7573 case RISCVISD::REMUW: 7574 case RISCVISD::ROLW: 7575 case RISCVISD::RORW: 7576 case RISCVISD::GREVW: 7577 case RISCVISD::GORCW: 7578 case RISCVISD::FSLW: 7579 case RISCVISD::FSRW: 7580 case RISCVISD::SHFLW: 7581 case RISCVISD::UNSHFLW: 7582 case RISCVISD::BCOMPRESSW: 7583 case RISCVISD::BDECOMPRESSW: 7584 case RISCVISD::FCVT_W_RTZ_RV64: 7585 case RISCVISD::FCVT_WU_RTZ_RV64: 7586 // TODO: As the result is sign-extended, this is conservatively correct. A 7587 // more precise answer could be calculated for SRAW depending on known 7588 // bits in the shift amount. 7589 return 33; 7590 case RISCVISD::SHFL: 7591 case RISCVISD::UNSHFL: { 7592 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 7593 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 7594 // will stay within the upper 32 bits. If there were more than 32 sign bits 7595 // before there will be at least 33 sign bits after. 7596 if (Op.getValueType() == MVT::i64 && 7597 isa<ConstantSDNode>(Op.getOperand(1)) && 7598 (Op.getConstantOperandVal(1) & 0x10) == 0) { 7599 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 7600 if (Tmp > 32) 7601 return 33; 7602 } 7603 break; 7604 } 7605 case RISCVISD::VMV_X_S: 7606 // The number of sign bits of the scalar result is computed by obtaining the 7607 // element type of the input vector operand, subtracting its width from the 7608 // XLEN, and then adding one (sign bit within the element type). If the 7609 // element type is wider than XLen, the least-significant XLEN bits are 7610 // taken. 7611 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 7612 return 1; 7613 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 7614 } 7615 7616 return 1; 7617 } 7618 7619 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 7620 MachineBasicBlock *BB) { 7621 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 7622 7623 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 7624 // Should the count have wrapped while it was being read, we need to try 7625 // again. 7626 // ... 7627 // read: 7628 // rdcycleh x3 # load high word of cycle 7629 // rdcycle x2 # load low word of cycle 7630 // rdcycleh x4 # load high word of cycle 7631 // bne x3, x4, read # check if high word reads match, otherwise try again 7632 // ... 7633 7634 MachineFunction &MF = *BB->getParent(); 7635 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7636 MachineFunction::iterator It = ++BB->getIterator(); 7637 7638 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7639 MF.insert(It, LoopMBB); 7640 7641 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7642 MF.insert(It, DoneMBB); 7643 7644 // Transfer the remainder of BB and its successor edges to DoneMBB. 7645 DoneMBB->splice(DoneMBB->begin(), BB, 7646 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7647 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 7648 7649 BB->addSuccessor(LoopMBB); 7650 7651 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7652 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 7653 Register LoReg = MI.getOperand(0).getReg(); 7654 Register HiReg = MI.getOperand(1).getReg(); 7655 DebugLoc DL = MI.getDebugLoc(); 7656 7657 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 7658 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 7659 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7660 .addReg(RISCV::X0); 7661 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 7662 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 7663 .addReg(RISCV::X0); 7664 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 7665 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7666 .addReg(RISCV::X0); 7667 7668 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 7669 .addReg(HiReg) 7670 .addReg(ReadAgainReg) 7671 .addMBB(LoopMBB); 7672 7673 LoopMBB->addSuccessor(LoopMBB); 7674 LoopMBB->addSuccessor(DoneMBB); 7675 7676 MI.eraseFromParent(); 7677 7678 return DoneMBB; 7679 } 7680 7681 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 7682 MachineBasicBlock *BB) { 7683 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 7684 7685 MachineFunction &MF = *BB->getParent(); 7686 DebugLoc DL = MI.getDebugLoc(); 7687 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7688 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7689 Register LoReg = MI.getOperand(0).getReg(); 7690 Register HiReg = MI.getOperand(1).getReg(); 7691 Register SrcReg = MI.getOperand(2).getReg(); 7692 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 7693 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7694 7695 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 7696 RI); 7697 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7698 MachineMemOperand *MMOLo = 7699 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 7700 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7701 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 7702 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 7703 .addFrameIndex(FI) 7704 .addImm(0) 7705 .addMemOperand(MMOLo); 7706 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 7707 .addFrameIndex(FI) 7708 .addImm(4) 7709 .addMemOperand(MMOHi); 7710 MI.eraseFromParent(); // The pseudo instruction is gone now. 7711 return BB; 7712 } 7713 7714 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 7715 MachineBasicBlock *BB) { 7716 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 7717 "Unexpected instruction"); 7718 7719 MachineFunction &MF = *BB->getParent(); 7720 DebugLoc DL = MI.getDebugLoc(); 7721 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7722 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7723 Register DstReg = MI.getOperand(0).getReg(); 7724 Register LoReg = MI.getOperand(1).getReg(); 7725 Register HiReg = MI.getOperand(2).getReg(); 7726 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 7727 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7728 7729 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7730 MachineMemOperand *MMOLo = 7731 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 7732 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7733 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 7734 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7735 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 7736 .addFrameIndex(FI) 7737 .addImm(0) 7738 .addMemOperand(MMOLo); 7739 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7740 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 7741 .addFrameIndex(FI) 7742 .addImm(4) 7743 .addMemOperand(MMOHi); 7744 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 7745 MI.eraseFromParent(); // The pseudo instruction is gone now. 7746 return BB; 7747 } 7748 7749 static bool isSelectPseudo(MachineInstr &MI) { 7750 switch (MI.getOpcode()) { 7751 default: 7752 return false; 7753 case RISCV::Select_GPR_Using_CC_GPR: 7754 case RISCV::Select_FPR16_Using_CC_GPR: 7755 case RISCV::Select_FPR32_Using_CC_GPR: 7756 case RISCV::Select_FPR64_Using_CC_GPR: 7757 return true; 7758 } 7759 } 7760 7761 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 7762 MachineBasicBlock *BB, 7763 const RISCVSubtarget &Subtarget) { 7764 // To "insert" Select_* instructions, we actually have to insert the triangle 7765 // control-flow pattern. The incoming instructions know the destination vreg 7766 // to set, the condition code register to branch on, the true/false values to 7767 // select between, and the condcode to use to select the appropriate branch. 7768 // 7769 // We produce the following control flow: 7770 // HeadMBB 7771 // | \ 7772 // | IfFalseMBB 7773 // | / 7774 // TailMBB 7775 // 7776 // When we find a sequence of selects we attempt to optimize their emission 7777 // by sharing the control flow. Currently we only handle cases where we have 7778 // multiple selects with the exact same condition (same LHS, RHS and CC). 7779 // The selects may be interleaved with other instructions if the other 7780 // instructions meet some requirements we deem safe: 7781 // - They are debug instructions. Otherwise, 7782 // - They do not have side-effects, do not access memory and their inputs do 7783 // not depend on the results of the select pseudo-instructions. 7784 // The TrueV/FalseV operands of the selects cannot depend on the result of 7785 // previous selects in the sequence. 7786 // These conditions could be further relaxed. See the X86 target for a 7787 // related approach and more information. 7788 Register LHS = MI.getOperand(1).getReg(); 7789 Register RHS = MI.getOperand(2).getReg(); 7790 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 7791 7792 SmallVector<MachineInstr *, 4> SelectDebugValues; 7793 SmallSet<Register, 4> SelectDests; 7794 SelectDests.insert(MI.getOperand(0).getReg()); 7795 7796 MachineInstr *LastSelectPseudo = &MI; 7797 7798 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 7799 SequenceMBBI != E; ++SequenceMBBI) { 7800 if (SequenceMBBI->isDebugInstr()) 7801 continue; 7802 else if (isSelectPseudo(*SequenceMBBI)) { 7803 if (SequenceMBBI->getOperand(1).getReg() != LHS || 7804 SequenceMBBI->getOperand(2).getReg() != RHS || 7805 SequenceMBBI->getOperand(3).getImm() != CC || 7806 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 7807 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 7808 break; 7809 LastSelectPseudo = &*SequenceMBBI; 7810 SequenceMBBI->collectDebugValues(SelectDebugValues); 7811 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 7812 } else { 7813 if (SequenceMBBI->hasUnmodeledSideEffects() || 7814 SequenceMBBI->mayLoadOrStore()) 7815 break; 7816 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 7817 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 7818 })) 7819 break; 7820 } 7821 } 7822 7823 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 7824 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7825 DebugLoc DL = MI.getDebugLoc(); 7826 MachineFunction::iterator I = ++BB->getIterator(); 7827 7828 MachineBasicBlock *HeadMBB = BB; 7829 MachineFunction *F = BB->getParent(); 7830 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 7831 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 7832 7833 F->insert(I, IfFalseMBB); 7834 F->insert(I, TailMBB); 7835 7836 // Transfer debug instructions associated with the selects to TailMBB. 7837 for (MachineInstr *DebugInstr : SelectDebugValues) { 7838 TailMBB->push_back(DebugInstr->removeFromParent()); 7839 } 7840 7841 // Move all instructions after the sequence to TailMBB. 7842 TailMBB->splice(TailMBB->end(), HeadMBB, 7843 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 7844 // Update machine-CFG edges by transferring all successors of the current 7845 // block to the new block which will contain the Phi nodes for the selects. 7846 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 7847 // Set the successors for HeadMBB. 7848 HeadMBB->addSuccessor(IfFalseMBB); 7849 HeadMBB->addSuccessor(TailMBB); 7850 7851 // Insert appropriate branch. 7852 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 7853 .addReg(LHS) 7854 .addReg(RHS) 7855 .addMBB(TailMBB); 7856 7857 // IfFalseMBB just falls through to TailMBB. 7858 IfFalseMBB->addSuccessor(TailMBB); 7859 7860 // Create PHIs for all of the select pseudo-instructions. 7861 auto SelectMBBI = MI.getIterator(); 7862 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 7863 auto InsertionPoint = TailMBB->begin(); 7864 while (SelectMBBI != SelectEnd) { 7865 auto Next = std::next(SelectMBBI); 7866 if (isSelectPseudo(*SelectMBBI)) { 7867 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 7868 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 7869 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 7870 .addReg(SelectMBBI->getOperand(4).getReg()) 7871 .addMBB(HeadMBB) 7872 .addReg(SelectMBBI->getOperand(5).getReg()) 7873 .addMBB(IfFalseMBB); 7874 SelectMBBI->eraseFromParent(); 7875 } 7876 SelectMBBI = Next; 7877 } 7878 7879 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 7880 return TailMBB; 7881 } 7882 7883 MachineBasicBlock * 7884 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 7885 MachineBasicBlock *BB) const { 7886 switch (MI.getOpcode()) { 7887 default: 7888 llvm_unreachable("Unexpected instr type to insert"); 7889 case RISCV::ReadCycleWide: 7890 assert(!Subtarget.is64Bit() && 7891 "ReadCycleWrite is only to be used on riscv32"); 7892 return emitReadCycleWidePseudo(MI, BB); 7893 case RISCV::Select_GPR_Using_CC_GPR: 7894 case RISCV::Select_FPR16_Using_CC_GPR: 7895 case RISCV::Select_FPR32_Using_CC_GPR: 7896 case RISCV::Select_FPR64_Using_CC_GPR: 7897 return emitSelectPseudo(MI, BB, Subtarget); 7898 case RISCV::BuildPairF64Pseudo: 7899 return emitBuildPairF64Pseudo(MI, BB); 7900 case RISCV::SplitF64Pseudo: 7901 return emitSplitF64Pseudo(MI, BB); 7902 } 7903 } 7904 7905 // Calling Convention Implementation. 7906 // The expectations for frontend ABI lowering vary from target to target. 7907 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 7908 // details, but this is a longer term goal. For now, we simply try to keep the 7909 // role of the frontend as simple and well-defined as possible. The rules can 7910 // be summarised as: 7911 // * Never split up large scalar arguments. We handle them here. 7912 // * If a hardfloat calling convention is being used, and the struct may be 7913 // passed in a pair of registers (fp+fp, int+fp), and both registers are 7914 // available, then pass as two separate arguments. If either the GPRs or FPRs 7915 // are exhausted, then pass according to the rule below. 7916 // * If a struct could never be passed in registers or directly in a stack 7917 // slot (as it is larger than 2*XLEN and the floating point rules don't 7918 // apply), then pass it using a pointer with the byval attribute. 7919 // * If a struct is less than 2*XLEN, then coerce to either a two-element 7920 // word-sized array or a 2*XLEN scalar (depending on alignment). 7921 // * The frontend can determine whether a struct is returned by reference or 7922 // not based on its size and fields. If it will be returned by reference, the 7923 // frontend must modify the prototype so a pointer with the sret annotation is 7924 // passed as the first argument. This is not necessary for large scalar 7925 // returns. 7926 // * Struct return values and varargs should be coerced to structs containing 7927 // register-size fields in the same situations they would be for fixed 7928 // arguments. 7929 7930 static const MCPhysReg ArgGPRs[] = { 7931 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 7932 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 7933 }; 7934 static const MCPhysReg ArgFPR16s[] = { 7935 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 7936 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 7937 }; 7938 static const MCPhysReg ArgFPR32s[] = { 7939 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 7940 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 7941 }; 7942 static const MCPhysReg ArgFPR64s[] = { 7943 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 7944 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 7945 }; 7946 // This is an interim calling convention and it may be changed in the future. 7947 static const MCPhysReg ArgVRs[] = { 7948 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 7949 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 7950 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 7951 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 7952 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 7953 RISCV::V20M2, RISCV::V22M2}; 7954 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 7955 RISCV::V20M4}; 7956 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 7957 7958 // Pass a 2*XLEN argument that has been split into two XLEN values through 7959 // registers or the stack as necessary. 7960 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 7961 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 7962 MVT ValVT2, MVT LocVT2, 7963 ISD::ArgFlagsTy ArgFlags2) { 7964 unsigned XLenInBytes = XLen / 8; 7965 if (Register Reg = State.AllocateReg(ArgGPRs)) { 7966 // At least one half can be passed via register. 7967 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 7968 VA1.getLocVT(), CCValAssign::Full)); 7969 } else { 7970 // Both halves must be passed on the stack, with proper alignment. 7971 Align StackAlign = 7972 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 7973 State.addLoc( 7974 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 7975 State.AllocateStack(XLenInBytes, StackAlign), 7976 VA1.getLocVT(), CCValAssign::Full)); 7977 State.addLoc(CCValAssign::getMem( 7978 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 7979 LocVT2, CCValAssign::Full)); 7980 return false; 7981 } 7982 7983 if (Register Reg = State.AllocateReg(ArgGPRs)) { 7984 // The second half can also be passed via register. 7985 State.addLoc( 7986 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 7987 } else { 7988 // The second half is passed via the stack, without additional alignment. 7989 State.addLoc(CCValAssign::getMem( 7990 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 7991 LocVT2, CCValAssign::Full)); 7992 } 7993 7994 return false; 7995 } 7996 7997 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 7998 Optional<unsigned> FirstMaskArgument, 7999 CCState &State, const RISCVTargetLowering &TLI) { 8000 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 8001 if (RC == &RISCV::VRRegClass) { 8002 // Assign the first mask argument to V0. 8003 // This is an interim calling convention and it may be changed in the 8004 // future. 8005 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 8006 return State.AllocateReg(RISCV::V0); 8007 return State.AllocateReg(ArgVRs); 8008 } 8009 if (RC == &RISCV::VRM2RegClass) 8010 return State.AllocateReg(ArgVRM2s); 8011 if (RC == &RISCV::VRM4RegClass) 8012 return State.AllocateReg(ArgVRM4s); 8013 if (RC == &RISCV::VRM8RegClass) 8014 return State.AllocateReg(ArgVRM8s); 8015 llvm_unreachable("Unhandled register class for ValueType"); 8016 } 8017 8018 // Implements the RISC-V calling convention. Returns true upon failure. 8019 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 8020 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 8021 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 8022 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 8023 Optional<unsigned> FirstMaskArgument) { 8024 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 8025 assert(XLen == 32 || XLen == 64); 8026 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 8027 8028 // Any return value split in to more than two values can't be returned 8029 // directly. Vectors are returned via the available vector registers. 8030 if (!LocVT.isVector() && IsRet && ValNo > 1) 8031 return true; 8032 8033 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 8034 // variadic argument, or if no F16/F32 argument registers are available. 8035 bool UseGPRForF16_F32 = true; 8036 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 8037 // variadic argument, or if no F64 argument registers are available. 8038 bool UseGPRForF64 = true; 8039 8040 switch (ABI) { 8041 default: 8042 llvm_unreachable("Unexpected ABI"); 8043 case RISCVABI::ABI_ILP32: 8044 case RISCVABI::ABI_LP64: 8045 break; 8046 case RISCVABI::ABI_ILP32F: 8047 case RISCVABI::ABI_LP64F: 8048 UseGPRForF16_F32 = !IsFixed; 8049 break; 8050 case RISCVABI::ABI_ILP32D: 8051 case RISCVABI::ABI_LP64D: 8052 UseGPRForF16_F32 = !IsFixed; 8053 UseGPRForF64 = !IsFixed; 8054 break; 8055 } 8056 8057 // FPR16, FPR32, and FPR64 alias each other. 8058 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 8059 UseGPRForF16_F32 = true; 8060 UseGPRForF64 = true; 8061 } 8062 8063 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 8064 // similar local variables rather than directly checking against the target 8065 // ABI. 8066 8067 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 8068 LocVT = XLenVT; 8069 LocInfo = CCValAssign::BCvt; 8070 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 8071 LocVT = MVT::i64; 8072 LocInfo = CCValAssign::BCvt; 8073 } 8074 8075 // If this is a variadic argument, the RISC-V calling convention requires 8076 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 8077 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 8078 // be used regardless of whether the original argument was split during 8079 // legalisation or not. The argument will not be passed by registers if the 8080 // original type is larger than 2*XLEN, so the register alignment rule does 8081 // not apply. 8082 unsigned TwoXLenInBytes = (2 * XLen) / 8; 8083 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 8084 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 8085 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 8086 // Skip 'odd' register if necessary. 8087 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 8088 State.AllocateReg(ArgGPRs); 8089 } 8090 8091 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 8092 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 8093 State.getPendingArgFlags(); 8094 8095 assert(PendingLocs.size() == PendingArgFlags.size() && 8096 "PendingLocs and PendingArgFlags out of sync"); 8097 8098 // Handle passing f64 on RV32D with a soft float ABI or when floating point 8099 // registers are exhausted. 8100 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 8101 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 8102 "Can't lower f64 if it is split"); 8103 // Depending on available argument GPRS, f64 may be passed in a pair of 8104 // GPRs, split between a GPR and the stack, or passed completely on the 8105 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 8106 // cases. 8107 Register Reg = State.AllocateReg(ArgGPRs); 8108 LocVT = MVT::i32; 8109 if (!Reg) { 8110 unsigned StackOffset = State.AllocateStack(8, Align(8)); 8111 State.addLoc( 8112 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8113 return false; 8114 } 8115 if (!State.AllocateReg(ArgGPRs)) 8116 State.AllocateStack(4, Align(4)); 8117 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8118 return false; 8119 } 8120 8121 // Fixed-length vectors are located in the corresponding scalable-vector 8122 // container types. 8123 if (ValVT.isFixedLengthVector()) 8124 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8125 8126 // Split arguments might be passed indirectly, so keep track of the pending 8127 // values. Split vectors are passed via a mix of registers and indirectly, so 8128 // treat them as we would any other argument. 8129 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 8130 LocVT = XLenVT; 8131 LocInfo = CCValAssign::Indirect; 8132 PendingLocs.push_back( 8133 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 8134 PendingArgFlags.push_back(ArgFlags); 8135 if (!ArgFlags.isSplitEnd()) { 8136 return false; 8137 } 8138 } 8139 8140 // If the split argument only had two elements, it should be passed directly 8141 // in registers or on the stack. 8142 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 8143 PendingLocs.size() <= 2) { 8144 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 8145 // Apply the normal calling convention rules to the first half of the 8146 // split argument. 8147 CCValAssign VA = PendingLocs[0]; 8148 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 8149 PendingLocs.clear(); 8150 PendingArgFlags.clear(); 8151 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 8152 ArgFlags); 8153 } 8154 8155 // Allocate to a register if possible, or else a stack slot. 8156 Register Reg; 8157 unsigned StoreSizeBytes = XLen / 8; 8158 Align StackAlign = Align(XLen / 8); 8159 8160 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 8161 Reg = State.AllocateReg(ArgFPR16s); 8162 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 8163 Reg = State.AllocateReg(ArgFPR32s); 8164 else if (ValVT == MVT::f64 && !UseGPRForF64) 8165 Reg = State.AllocateReg(ArgFPR64s); 8166 else if (ValVT.isVector()) { 8167 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 8168 if (!Reg) { 8169 // For return values, the vector must be passed fully via registers or 8170 // via the stack. 8171 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 8172 // but we're using all of them. 8173 if (IsRet) 8174 return true; 8175 // Try using a GPR to pass the address 8176 if ((Reg = State.AllocateReg(ArgGPRs))) { 8177 LocVT = XLenVT; 8178 LocInfo = CCValAssign::Indirect; 8179 } else if (ValVT.isScalableVector()) { 8180 report_fatal_error("Unable to pass scalable vector types on the stack"); 8181 } else { 8182 // Pass fixed-length vectors on the stack. 8183 LocVT = ValVT; 8184 StoreSizeBytes = ValVT.getStoreSize(); 8185 // Align vectors to their element sizes, being careful for vXi1 8186 // vectors. 8187 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8188 } 8189 } 8190 } else { 8191 Reg = State.AllocateReg(ArgGPRs); 8192 } 8193 8194 unsigned StackOffset = 8195 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 8196 8197 // If we reach this point and PendingLocs is non-empty, we must be at the 8198 // end of a split argument that must be passed indirectly. 8199 if (!PendingLocs.empty()) { 8200 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 8201 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 8202 8203 for (auto &It : PendingLocs) { 8204 if (Reg) 8205 It.convertToReg(Reg); 8206 else 8207 It.convertToMem(StackOffset); 8208 State.addLoc(It); 8209 } 8210 PendingLocs.clear(); 8211 PendingArgFlags.clear(); 8212 return false; 8213 } 8214 8215 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 8216 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 8217 "Expected an XLenVT or vector types at this stage"); 8218 8219 if (Reg) { 8220 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8221 return false; 8222 } 8223 8224 // When a floating-point value is passed on the stack, no bit-conversion is 8225 // needed. 8226 if (ValVT.isFloatingPoint()) { 8227 LocVT = ValVT; 8228 LocInfo = CCValAssign::Full; 8229 } 8230 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8231 return false; 8232 } 8233 8234 template <typename ArgTy> 8235 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 8236 for (const auto &ArgIdx : enumerate(Args)) { 8237 MVT ArgVT = ArgIdx.value().VT; 8238 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 8239 return ArgIdx.index(); 8240 } 8241 return None; 8242 } 8243 8244 void RISCVTargetLowering::analyzeInputArgs( 8245 MachineFunction &MF, CCState &CCInfo, 8246 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 8247 RISCVCCAssignFn Fn) const { 8248 unsigned NumArgs = Ins.size(); 8249 FunctionType *FType = MF.getFunction().getFunctionType(); 8250 8251 Optional<unsigned> FirstMaskArgument; 8252 if (Subtarget.hasVInstructions()) 8253 FirstMaskArgument = preAssignMask(Ins); 8254 8255 for (unsigned i = 0; i != NumArgs; ++i) { 8256 MVT ArgVT = Ins[i].VT; 8257 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 8258 8259 Type *ArgTy = nullptr; 8260 if (IsRet) 8261 ArgTy = FType->getReturnType(); 8262 else if (Ins[i].isOrigArg()) 8263 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 8264 8265 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8266 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8267 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 8268 FirstMaskArgument)) { 8269 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 8270 << EVT(ArgVT).getEVTString() << '\n'); 8271 llvm_unreachable(nullptr); 8272 } 8273 } 8274 } 8275 8276 void RISCVTargetLowering::analyzeOutputArgs( 8277 MachineFunction &MF, CCState &CCInfo, 8278 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 8279 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 8280 unsigned NumArgs = Outs.size(); 8281 8282 Optional<unsigned> FirstMaskArgument; 8283 if (Subtarget.hasVInstructions()) 8284 FirstMaskArgument = preAssignMask(Outs); 8285 8286 for (unsigned i = 0; i != NumArgs; i++) { 8287 MVT ArgVT = Outs[i].VT; 8288 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 8289 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 8290 8291 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8292 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8293 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 8294 FirstMaskArgument)) { 8295 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 8296 << EVT(ArgVT).getEVTString() << "\n"); 8297 llvm_unreachable(nullptr); 8298 } 8299 } 8300 } 8301 8302 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 8303 // values. 8304 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 8305 const CCValAssign &VA, const SDLoc &DL, 8306 const RISCVSubtarget &Subtarget) { 8307 switch (VA.getLocInfo()) { 8308 default: 8309 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8310 case CCValAssign::Full: 8311 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 8312 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 8313 break; 8314 case CCValAssign::BCvt: 8315 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8316 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 8317 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8318 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 8319 else 8320 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 8321 break; 8322 } 8323 return Val; 8324 } 8325 8326 // The caller is responsible for loading the full value if the argument is 8327 // passed with CCValAssign::Indirect. 8328 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 8329 const CCValAssign &VA, const SDLoc &DL, 8330 const RISCVTargetLowering &TLI) { 8331 MachineFunction &MF = DAG.getMachineFunction(); 8332 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8333 EVT LocVT = VA.getLocVT(); 8334 SDValue Val; 8335 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 8336 Register VReg = RegInfo.createVirtualRegister(RC); 8337 RegInfo.addLiveIn(VA.getLocReg(), VReg); 8338 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 8339 8340 if (VA.getLocInfo() == CCValAssign::Indirect) 8341 return Val; 8342 8343 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 8344 } 8345 8346 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 8347 const CCValAssign &VA, const SDLoc &DL, 8348 const RISCVSubtarget &Subtarget) { 8349 EVT LocVT = VA.getLocVT(); 8350 8351 switch (VA.getLocInfo()) { 8352 default: 8353 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8354 case CCValAssign::Full: 8355 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 8356 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 8357 break; 8358 case CCValAssign::BCvt: 8359 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8360 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 8361 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8362 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 8363 else 8364 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 8365 break; 8366 } 8367 return Val; 8368 } 8369 8370 // The caller is responsible for loading the full value if the argument is 8371 // passed with CCValAssign::Indirect. 8372 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 8373 const CCValAssign &VA, const SDLoc &DL) { 8374 MachineFunction &MF = DAG.getMachineFunction(); 8375 MachineFrameInfo &MFI = MF.getFrameInfo(); 8376 EVT LocVT = VA.getLocVT(); 8377 EVT ValVT = VA.getValVT(); 8378 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 8379 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 8380 /*Immutable=*/true); 8381 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 8382 SDValue Val; 8383 8384 ISD::LoadExtType ExtType; 8385 switch (VA.getLocInfo()) { 8386 default: 8387 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8388 case CCValAssign::Full: 8389 case CCValAssign::Indirect: 8390 case CCValAssign::BCvt: 8391 ExtType = ISD::NON_EXTLOAD; 8392 break; 8393 } 8394 Val = DAG.getExtLoad( 8395 ExtType, DL, LocVT, Chain, FIN, 8396 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 8397 return Val; 8398 } 8399 8400 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 8401 const CCValAssign &VA, const SDLoc &DL) { 8402 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 8403 "Unexpected VA"); 8404 MachineFunction &MF = DAG.getMachineFunction(); 8405 MachineFrameInfo &MFI = MF.getFrameInfo(); 8406 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8407 8408 if (VA.isMemLoc()) { 8409 // f64 is passed on the stack. 8410 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 8411 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8412 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 8413 MachinePointerInfo::getFixedStack(MF, FI)); 8414 } 8415 8416 assert(VA.isRegLoc() && "Expected register VA assignment"); 8417 8418 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8419 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 8420 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 8421 SDValue Hi; 8422 if (VA.getLocReg() == RISCV::X17) { 8423 // Second half of f64 is passed on the stack. 8424 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 8425 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8426 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 8427 MachinePointerInfo::getFixedStack(MF, FI)); 8428 } else { 8429 // Second half of f64 is passed in another GPR. 8430 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8431 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 8432 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 8433 } 8434 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 8435 } 8436 8437 // FastCC has less than 1% performance improvement for some particular 8438 // benchmark. But theoretically, it may has benenfit for some cases. 8439 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 8440 unsigned ValNo, MVT ValVT, MVT LocVT, 8441 CCValAssign::LocInfo LocInfo, 8442 ISD::ArgFlagsTy ArgFlags, CCState &State, 8443 bool IsFixed, bool IsRet, Type *OrigTy, 8444 const RISCVTargetLowering &TLI, 8445 Optional<unsigned> FirstMaskArgument) { 8446 8447 // X5 and X6 might be used for save-restore libcall. 8448 static const MCPhysReg GPRList[] = { 8449 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 8450 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 8451 RISCV::X29, RISCV::X30, RISCV::X31}; 8452 8453 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8454 if (unsigned Reg = State.AllocateReg(GPRList)) { 8455 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8456 return false; 8457 } 8458 } 8459 8460 if (LocVT == MVT::f16) { 8461 static const MCPhysReg FPR16List[] = { 8462 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 8463 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 8464 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 8465 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 8466 if (unsigned Reg = State.AllocateReg(FPR16List)) { 8467 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8468 return false; 8469 } 8470 } 8471 8472 if (LocVT == MVT::f32) { 8473 static const MCPhysReg FPR32List[] = { 8474 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 8475 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 8476 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 8477 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 8478 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8479 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8480 return false; 8481 } 8482 } 8483 8484 if (LocVT == MVT::f64) { 8485 static const MCPhysReg FPR64List[] = { 8486 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 8487 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 8488 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 8489 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 8490 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8491 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8492 return false; 8493 } 8494 } 8495 8496 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 8497 unsigned Offset4 = State.AllocateStack(4, Align(4)); 8498 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 8499 return false; 8500 } 8501 8502 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 8503 unsigned Offset5 = State.AllocateStack(8, Align(8)); 8504 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 8505 return false; 8506 } 8507 8508 if (LocVT.isVector()) { 8509 if (unsigned Reg = 8510 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 8511 // Fixed-length vectors are located in the corresponding scalable-vector 8512 // container types. 8513 if (ValVT.isFixedLengthVector()) 8514 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8515 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8516 } else { 8517 // Try and pass the address via a "fast" GPR. 8518 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 8519 LocInfo = CCValAssign::Indirect; 8520 LocVT = TLI.getSubtarget().getXLenVT(); 8521 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 8522 } else if (ValVT.isFixedLengthVector()) { 8523 auto StackAlign = 8524 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8525 unsigned StackOffset = 8526 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 8527 State.addLoc( 8528 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8529 } else { 8530 // Can't pass scalable vectors on the stack. 8531 return true; 8532 } 8533 } 8534 8535 return false; 8536 } 8537 8538 return true; // CC didn't match. 8539 } 8540 8541 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 8542 CCValAssign::LocInfo LocInfo, 8543 ISD::ArgFlagsTy ArgFlags, CCState &State) { 8544 8545 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8546 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 8547 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 8548 static const MCPhysReg GPRList[] = { 8549 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 8550 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 8551 if (unsigned Reg = State.AllocateReg(GPRList)) { 8552 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8553 return false; 8554 } 8555 } 8556 8557 if (LocVT == MVT::f32) { 8558 // Pass in STG registers: F1, ..., F6 8559 // fs0 ... fs5 8560 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 8561 RISCV::F18_F, RISCV::F19_F, 8562 RISCV::F20_F, RISCV::F21_F}; 8563 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8564 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8565 return false; 8566 } 8567 } 8568 8569 if (LocVT == MVT::f64) { 8570 // Pass in STG registers: D1, ..., D6 8571 // fs6 ... fs11 8572 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 8573 RISCV::F24_D, RISCV::F25_D, 8574 RISCV::F26_D, RISCV::F27_D}; 8575 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8576 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8577 return false; 8578 } 8579 } 8580 8581 report_fatal_error("No registers left in GHC calling convention"); 8582 return true; 8583 } 8584 8585 // Transform physical registers into virtual registers. 8586 SDValue RISCVTargetLowering::LowerFormalArguments( 8587 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 8588 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 8589 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 8590 8591 MachineFunction &MF = DAG.getMachineFunction(); 8592 8593 switch (CallConv) { 8594 default: 8595 report_fatal_error("Unsupported calling convention"); 8596 case CallingConv::C: 8597 case CallingConv::Fast: 8598 break; 8599 case CallingConv::GHC: 8600 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 8601 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 8602 report_fatal_error( 8603 "GHC calling convention requires the F and D instruction set extensions"); 8604 } 8605 8606 const Function &Func = MF.getFunction(); 8607 if (Func.hasFnAttribute("interrupt")) { 8608 if (!Func.arg_empty()) 8609 report_fatal_error( 8610 "Functions with the interrupt attribute cannot have arguments!"); 8611 8612 StringRef Kind = 8613 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 8614 8615 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 8616 report_fatal_error( 8617 "Function interrupt attribute argument not supported!"); 8618 } 8619 8620 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8621 MVT XLenVT = Subtarget.getXLenVT(); 8622 unsigned XLenInBytes = Subtarget.getXLen() / 8; 8623 // Used with vargs to acumulate store chains. 8624 std::vector<SDValue> OutChains; 8625 8626 // Assign locations to all of the incoming arguments. 8627 SmallVector<CCValAssign, 16> ArgLocs; 8628 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 8629 8630 if (CallConv == CallingConv::GHC) 8631 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 8632 else 8633 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 8634 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 8635 : CC_RISCV); 8636 8637 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 8638 CCValAssign &VA = ArgLocs[i]; 8639 SDValue ArgValue; 8640 // Passing f64 on RV32D with a soft float ABI must be handled as a special 8641 // case. 8642 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 8643 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 8644 else if (VA.isRegLoc()) 8645 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 8646 else 8647 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 8648 8649 if (VA.getLocInfo() == CCValAssign::Indirect) { 8650 // If the original argument was split and passed by reference (e.g. i128 8651 // on RV32), we need to load all parts of it here (using the same 8652 // address). Vectors may be partly split to registers and partly to the 8653 // stack, in which case the base address is partly offset and subsequent 8654 // stores are relative to that. 8655 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 8656 MachinePointerInfo())); 8657 unsigned ArgIndex = Ins[i].OrigArgIndex; 8658 unsigned ArgPartOffset = Ins[i].PartOffset; 8659 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8660 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 8661 CCValAssign &PartVA = ArgLocs[i + 1]; 8662 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 8663 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8664 if (PartVA.getValVT().isScalableVector()) 8665 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8666 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 8667 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 8668 MachinePointerInfo())); 8669 ++i; 8670 } 8671 continue; 8672 } 8673 InVals.push_back(ArgValue); 8674 } 8675 8676 if (IsVarArg) { 8677 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 8678 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 8679 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 8680 MachineFrameInfo &MFI = MF.getFrameInfo(); 8681 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8682 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 8683 8684 // Offset of the first variable argument from stack pointer, and size of 8685 // the vararg save area. For now, the varargs save area is either zero or 8686 // large enough to hold a0-a7. 8687 int VaArgOffset, VarArgsSaveSize; 8688 8689 // If all registers are allocated, then all varargs must be passed on the 8690 // stack and we don't need to save any argregs. 8691 if (ArgRegs.size() == Idx) { 8692 VaArgOffset = CCInfo.getNextStackOffset(); 8693 VarArgsSaveSize = 0; 8694 } else { 8695 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 8696 VaArgOffset = -VarArgsSaveSize; 8697 } 8698 8699 // Record the frame index of the first variable argument 8700 // which is a value necessary to VASTART. 8701 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8702 RVFI->setVarArgsFrameIndex(FI); 8703 8704 // If saving an odd number of registers then create an extra stack slot to 8705 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 8706 // offsets to even-numbered registered remain 2*XLEN-aligned. 8707 if (Idx % 2) { 8708 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 8709 VarArgsSaveSize += XLenInBytes; 8710 } 8711 8712 // Copy the integer registers that may have been used for passing varargs 8713 // to the vararg save area. 8714 for (unsigned I = Idx; I < ArgRegs.size(); 8715 ++I, VaArgOffset += XLenInBytes) { 8716 const Register Reg = RegInfo.createVirtualRegister(RC); 8717 RegInfo.addLiveIn(ArgRegs[I], Reg); 8718 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 8719 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8720 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8721 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 8722 MachinePointerInfo::getFixedStack(MF, FI)); 8723 cast<StoreSDNode>(Store.getNode()) 8724 ->getMemOperand() 8725 ->setValue((Value *)nullptr); 8726 OutChains.push_back(Store); 8727 } 8728 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 8729 } 8730 8731 // All stores are grouped in one node to allow the matching between 8732 // the size of Ins and InVals. This only happens for vararg functions. 8733 if (!OutChains.empty()) { 8734 OutChains.push_back(Chain); 8735 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 8736 } 8737 8738 return Chain; 8739 } 8740 8741 /// isEligibleForTailCallOptimization - Check whether the call is eligible 8742 /// for tail call optimization. 8743 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 8744 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 8745 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 8746 const SmallVector<CCValAssign, 16> &ArgLocs) const { 8747 8748 auto &Callee = CLI.Callee; 8749 auto CalleeCC = CLI.CallConv; 8750 auto &Outs = CLI.Outs; 8751 auto &Caller = MF.getFunction(); 8752 auto CallerCC = Caller.getCallingConv(); 8753 8754 // Exception-handling functions need a special set of instructions to 8755 // indicate a return to the hardware. Tail-calling another function would 8756 // probably break this. 8757 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 8758 // should be expanded as new function attributes are introduced. 8759 if (Caller.hasFnAttribute("interrupt")) 8760 return false; 8761 8762 // Do not tail call opt if the stack is used to pass parameters. 8763 if (CCInfo.getNextStackOffset() != 0) 8764 return false; 8765 8766 // Do not tail call opt if any parameters need to be passed indirectly. 8767 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 8768 // passed indirectly. So the address of the value will be passed in a 8769 // register, or if not available, then the address is put on the stack. In 8770 // order to pass indirectly, space on the stack often needs to be allocated 8771 // in order to store the value. In this case the CCInfo.getNextStackOffset() 8772 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 8773 // are passed CCValAssign::Indirect. 8774 for (auto &VA : ArgLocs) 8775 if (VA.getLocInfo() == CCValAssign::Indirect) 8776 return false; 8777 8778 // Do not tail call opt if either caller or callee uses struct return 8779 // semantics. 8780 auto IsCallerStructRet = Caller.hasStructRetAttr(); 8781 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 8782 if (IsCallerStructRet || IsCalleeStructRet) 8783 return false; 8784 8785 // Externally-defined functions with weak linkage should not be 8786 // tail-called. The behaviour of branch instructions in this situation (as 8787 // used for tail calls) is implementation-defined, so we cannot rely on the 8788 // linker replacing the tail call with a return. 8789 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 8790 const GlobalValue *GV = G->getGlobal(); 8791 if (GV->hasExternalWeakLinkage()) 8792 return false; 8793 } 8794 8795 // The callee has to preserve all registers the caller needs to preserve. 8796 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 8797 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 8798 if (CalleeCC != CallerCC) { 8799 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 8800 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 8801 return false; 8802 } 8803 8804 // Byval parameters hand the function a pointer directly into the stack area 8805 // we want to reuse during a tail call. Working around this *is* possible 8806 // but less efficient and uglier in LowerCall. 8807 for (auto &Arg : Outs) 8808 if (Arg.Flags.isByVal()) 8809 return false; 8810 8811 return true; 8812 } 8813 8814 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 8815 return DAG.getDataLayout().getPrefTypeAlign( 8816 VT.getTypeForEVT(*DAG.getContext())); 8817 } 8818 8819 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 8820 // and output parameter nodes. 8821 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 8822 SmallVectorImpl<SDValue> &InVals) const { 8823 SelectionDAG &DAG = CLI.DAG; 8824 SDLoc &DL = CLI.DL; 8825 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 8826 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 8827 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 8828 SDValue Chain = CLI.Chain; 8829 SDValue Callee = CLI.Callee; 8830 bool &IsTailCall = CLI.IsTailCall; 8831 CallingConv::ID CallConv = CLI.CallConv; 8832 bool IsVarArg = CLI.IsVarArg; 8833 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8834 MVT XLenVT = Subtarget.getXLenVT(); 8835 8836 MachineFunction &MF = DAG.getMachineFunction(); 8837 8838 // Analyze the operands of the call, assigning locations to each operand. 8839 SmallVector<CCValAssign, 16> ArgLocs; 8840 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 8841 8842 if (CallConv == CallingConv::GHC) 8843 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 8844 else 8845 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 8846 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 8847 : CC_RISCV); 8848 8849 // Check if it's really possible to do a tail call. 8850 if (IsTailCall) 8851 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 8852 8853 if (IsTailCall) 8854 ++NumTailCalls; 8855 else if (CLI.CB && CLI.CB->isMustTailCall()) 8856 report_fatal_error("failed to perform tail call elimination on a call " 8857 "site marked musttail"); 8858 8859 // Get a count of how many bytes are to be pushed on the stack. 8860 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 8861 8862 // Create local copies for byval args 8863 SmallVector<SDValue, 8> ByValArgs; 8864 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 8865 ISD::ArgFlagsTy Flags = Outs[i].Flags; 8866 if (!Flags.isByVal()) 8867 continue; 8868 8869 SDValue Arg = OutVals[i]; 8870 unsigned Size = Flags.getByValSize(); 8871 Align Alignment = Flags.getNonZeroByValAlign(); 8872 8873 int FI = 8874 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 8875 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8876 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 8877 8878 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 8879 /*IsVolatile=*/false, 8880 /*AlwaysInline=*/false, IsTailCall, 8881 MachinePointerInfo(), MachinePointerInfo()); 8882 ByValArgs.push_back(FIPtr); 8883 } 8884 8885 if (!IsTailCall) 8886 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 8887 8888 // Copy argument values to their designated locations. 8889 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 8890 SmallVector<SDValue, 8> MemOpChains; 8891 SDValue StackPtr; 8892 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 8893 CCValAssign &VA = ArgLocs[i]; 8894 SDValue ArgValue = OutVals[i]; 8895 ISD::ArgFlagsTy Flags = Outs[i].Flags; 8896 8897 // Handle passing f64 on RV32D with a soft float ABI as a special case. 8898 bool IsF64OnRV32DSoftABI = 8899 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 8900 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 8901 SDValue SplitF64 = DAG.getNode( 8902 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 8903 SDValue Lo = SplitF64.getValue(0); 8904 SDValue Hi = SplitF64.getValue(1); 8905 8906 Register RegLo = VA.getLocReg(); 8907 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 8908 8909 if (RegLo == RISCV::X17) { 8910 // Second half of f64 is passed on the stack. 8911 // Work out the address of the stack slot. 8912 if (!StackPtr.getNode()) 8913 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 8914 // Emit the store. 8915 MemOpChains.push_back( 8916 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 8917 } else { 8918 // Second half of f64 is passed in another GPR. 8919 assert(RegLo < RISCV::X31 && "Invalid register pair"); 8920 Register RegHigh = RegLo + 1; 8921 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 8922 } 8923 continue; 8924 } 8925 8926 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 8927 // as any other MemLoc. 8928 8929 // Promote the value if needed. 8930 // For now, only handle fully promoted and indirect arguments. 8931 if (VA.getLocInfo() == CCValAssign::Indirect) { 8932 // Store the argument in a stack slot and pass its address. 8933 Align StackAlign = 8934 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 8935 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 8936 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 8937 // If the original argument was split (e.g. i128), we need 8938 // to store the required parts of it here (and pass just one address). 8939 // Vectors may be partly split to registers and partly to the stack, in 8940 // which case the base address is partly offset and subsequent stores are 8941 // relative to that. 8942 unsigned ArgIndex = Outs[i].OrigArgIndex; 8943 unsigned ArgPartOffset = Outs[i].PartOffset; 8944 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8945 // Calculate the total size to store. We don't have access to what we're 8946 // actually storing other than performing the loop and collecting the 8947 // info. 8948 SmallVector<std::pair<SDValue, SDValue>> Parts; 8949 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 8950 SDValue PartValue = OutVals[i + 1]; 8951 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 8952 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8953 EVT PartVT = PartValue.getValueType(); 8954 if (PartVT.isScalableVector()) 8955 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8956 StoredSize += PartVT.getStoreSize(); 8957 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 8958 Parts.push_back(std::make_pair(PartValue, Offset)); 8959 ++i; 8960 } 8961 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 8962 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 8963 MemOpChains.push_back( 8964 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 8965 MachinePointerInfo::getFixedStack(MF, FI))); 8966 for (const auto &Part : Parts) { 8967 SDValue PartValue = Part.first; 8968 SDValue PartOffset = Part.second; 8969 SDValue Address = 8970 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 8971 MemOpChains.push_back( 8972 DAG.getStore(Chain, DL, PartValue, Address, 8973 MachinePointerInfo::getFixedStack(MF, FI))); 8974 } 8975 ArgValue = SpillSlot; 8976 } else { 8977 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 8978 } 8979 8980 // Use local copy if it is a byval arg. 8981 if (Flags.isByVal()) 8982 ArgValue = ByValArgs[j++]; 8983 8984 if (VA.isRegLoc()) { 8985 // Queue up the argument copies and emit them at the end. 8986 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 8987 } else { 8988 assert(VA.isMemLoc() && "Argument not register or memory"); 8989 assert(!IsTailCall && "Tail call not allowed if stack is used " 8990 "for passing parameters"); 8991 8992 // Work out the address of the stack slot. 8993 if (!StackPtr.getNode()) 8994 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 8995 SDValue Address = 8996 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 8997 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 8998 8999 // Emit the store. 9000 MemOpChains.push_back( 9001 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 9002 } 9003 } 9004 9005 // Join the stores, which are independent of one another. 9006 if (!MemOpChains.empty()) 9007 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 9008 9009 SDValue Glue; 9010 9011 // Build a sequence of copy-to-reg nodes, chained and glued together. 9012 for (auto &Reg : RegsToPass) { 9013 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 9014 Glue = Chain.getValue(1); 9015 } 9016 9017 // Validate that none of the argument registers have been marked as 9018 // reserved, if so report an error. Do the same for the return address if this 9019 // is not a tailcall. 9020 validateCCReservedRegs(RegsToPass, MF); 9021 if (!IsTailCall && 9022 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 9023 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9024 MF.getFunction(), 9025 "Return address register required, but has been reserved."}); 9026 9027 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 9028 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 9029 // split it and then direct call can be matched by PseudoCALL. 9030 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 9031 const GlobalValue *GV = S->getGlobal(); 9032 9033 unsigned OpFlags = RISCVII::MO_CALL; 9034 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 9035 OpFlags = RISCVII::MO_PLT; 9036 9037 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 9038 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 9039 unsigned OpFlags = RISCVII::MO_CALL; 9040 9041 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 9042 nullptr)) 9043 OpFlags = RISCVII::MO_PLT; 9044 9045 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 9046 } 9047 9048 // The first call operand is the chain and the second is the target address. 9049 SmallVector<SDValue, 8> Ops; 9050 Ops.push_back(Chain); 9051 Ops.push_back(Callee); 9052 9053 // Add argument registers to the end of the list so that they are 9054 // known live into the call. 9055 for (auto &Reg : RegsToPass) 9056 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 9057 9058 if (!IsTailCall) { 9059 // Add a register mask operand representing the call-preserved registers. 9060 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9061 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 9062 assert(Mask && "Missing call preserved mask for calling convention"); 9063 Ops.push_back(DAG.getRegisterMask(Mask)); 9064 } 9065 9066 // Glue the call to the argument copies, if any. 9067 if (Glue.getNode()) 9068 Ops.push_back(Glue); 9069 9070 // Emit the call. 9071 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9072 9073 if (IsTailCall) { 9074 MF.getFrameInfo().setHasTailCall(); 9075 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 9076 } 9077 9078 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 9079 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 9080 Glue = Chain.getValue(1); 9081 9082 // Mark the end of the call, which is glued to the call itself. 9083 Chain = DAG.getCALLSEQ_END(Chain, 9084 DAG.getConstant(NumBytes, DL, PtrVT, true), 9085 DAG.getConstant(0, DL, PtrVT, true), 9086 Glue, DL); 9087 Glue = Chain.getValue(1); 9088 9089 // Assign locations to each value returned by this call. 9090 SmallVector<CCValAssign, 16> RVLocs; 9091 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 9092 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 9093 9094 // Copy all of the result registers out of their specified physreg. 9095 for (auto &VA : RVLocs) { 9096 // Copy the value out 9097 SDValue RetValue = 9098 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 9099 // Glue the RetValue to the end of the call sequence 9100 Chain = RetValue.getValue(1); 9101 Glue = RetValue.getValue(2); 9102 9103 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9104 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 9105 SDValue RetValue2 = 9106 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 9107 Chain = RetValue2.getValue(1); 9108 Glue = RetValue2.getValue(2); 9109 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 9110 RetValue2); 9111 } 9112 9113 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 9114 9115 InVals.push_back(RetValue); 9116 } 9117 9118 return Chain; 9119 } 9120 9121 bool RISCVTargetLowering::CanLowerReturn( 9122 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 9123 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 9124 SmallVector<CCValAssign, 16> RVLocs; 9125 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 9126 9127 Optional<unsigned> FirstMaskArgument; 9128 if (Subtarget.hasVInstructions()) 9129 FirstMaskArgument = preAssignMask(Outs); 9130 9131 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9132 MVT VT = Outs[i].VT; 9133 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9134 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9135 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 9136 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 9137 *this, FirstMaskArgument)) 9138 return false; 9139 } 9140 return true; 9141 } 9142 9143 SDValue 9144 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 9145 bool IsVarArg, 9146 const SmallVectorImpl<ISD::OutputArg> &Outs, 9147 const SmallVectorImpl<SDValue> &OutVals, 9148 const SDLoc &DL, SelectionDAG &DAG) const { 9149 const MachineFunction &MF = DAG.getMachineFunction(); 9150 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9151 9152 // Stores the assignment of the return value to a location. 9153 SmallVector<CCValAssign, 16> RVLocs; 9154 9155 // Info about the registers and stack slot. 9156 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 9157 *DAG.getContext()); 9158 9159 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 9160 nullptr, CC_RISCV); 9161 9162 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 9163 report_fatal_error("GHC functions return void only"); 9164 9165 SDValue Glue; 9166 SmallVector<SDValue, 4> RetOps(1, Chain); 9167 9168 // Copy the result values into the output registers. 9169 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 9170 SDValue Val = OutVals[i]; 9171 CCValAssign &VA = RVLocs[i]; 9172 assert(VA.isRegLoc() && "Can only return in registers!"); 9173 9174 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9175 // Handle returning f64 on RV32D with a soft float ABI. 9176 assert(VA.isRegLoc() && "Expected return via registers"); 9177 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 9178 DAG.getVTList(MVT::i32, MVT::i32), Val); 9179 SDValue Lo = SplitF64.getValue(0); 9180 SDValue Hi = SplitF64.getValue(1); 9181 Register RegLo = VA.getLocReg(); 9182 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9183 Register RegHi = RegLo + 1; 9184 9185 if (STI.isRegisterReservedByUser(RegLo) || 9186 STI.isRegisterReservedByUser(RegHi)) 9187 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9188 MF.getFunction(), 9189 "Return value register required, but has been reserved."}); 9190 9191 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 9192 Glue = Chain.getValue(1); 9193 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 9194 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 9195 Glue = Chain.getValue(1); 9196 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 9197 } else { 9198 // Handle a 'normal' return. 9199 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 9200 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 9201 9202 if (STI.isRegisterReservedByUser(VA.getLocReg())) 9203 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9204 MF.getFunction(), 9205 "Return value register required, but has been reserved."}); 9206 9207 // Guarantee that all emitted copies are stuck together. 9208 Glue = Chain.getValue(1); 9209 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 9210 } 9211 } 9212 9213 RetOps[0] = Chain; // Update chain. 9214 9215 // Add the glue node if we have it. 9216 if (Glue.getNode()) { 9217 RetOps.push_back(Glue); 9218 } 9219 9220 unsigned RetOpc = RISCVISD::RET_FLAG; 9221 // Interrupt service routines use different return instructions. 9222 const Function &Func = DAG.getMachineFunction().getFunction(); 9223 if (Func.hasFnAttribute("interrupt")) { 9224 if (!Func.getReturnType()->isVoidTy()) 9225 report_fatal_error( 9226 "Functions with the interrupt attribute must have void return type!"); 9227 9228 MachineFunction &MF = DAG.getMachineFunction(); 9229 StringRef Kind = 9230 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9231 9232 if (Kind == "user") 9233 RetOpc = RISCVISD::URET_FLAG; 9234 else if (Kind == "supervisor") 9235 RetOpc = RISCVISD::SRET_FLAG; 9236 else 9237 RetOpc = RISCVISD::MRET_FLAG; 9238 } 9239 9240 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 9241 } 9242 9243 void RISCVTargetLowering::validateCCReservedRegs( 9244 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 9245 MachineFunction &MF) const { 9246 const Function &F = MF.getFunction(); 9247 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9248 9249 if (llvm::any_of(Regs, [&STI](auto Reg) { 9250 return STI.isRegisterReservedByUser(Reg.first); 9251 })) 9252 F.getContext().diagnose(DiagnosticInfoUnsupported{ 9253 F, "Argument register required, but has been reserved."}); 9254 } 9255 9256 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 9257 return CI->isTailCall(); 9258 } 9259 9260 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 9261 #define NODE_NAME_CASE(NODE) \ 9262 case RISCVISD::NODE: \ 9263 return "RISCVISD::" #NODE; 9264 // clang-format off 9265 switch ((RISCVISD::NodeType)Opcode) { 9266 case RISCVISD::FIRST_NUMBER: 9267 break; 9268 NODE_NAME_CASE(RET_FLAG) 9269 NODE_NAME_CASE(URET_FLAG) 9270 NODE_NAME_CASE(SRET_FLAG) 9271 NODE_NAME_CASE(MRET_FLAG) 9272 NODE_NAME_CASE(CALL) 9273 NODE_NAME_CASE(SELECT_CC) 9274 NODE_NAME_CASE(BR_CC) 9275 NODE_NAME_CASE(BuildPairF64) 9276 NODE_NAME_CASE(SplitF64) 9277 NODE_NAME_CASE(TAIL) 9278 NODE_NAME_CASE(MULHSU) 9279 NODE_NAME_CASE(SLLW) 9280 NODE_NAME_CASE(SRAW) 9281 NODE_NAME_CASE(SRLW) 9282 NODE_NAME_CASE(DIVW) 9283 NODE_NAME_CASE(DIVUW) 9284 NODE_NAME_CASE(REMUW) 9285 NODE_NAME_CASE(ROLW) 9286 NODE_NAME_CASE(RORW) 9287 NODE_NAME_CASE(CLZW) 9288 NODE_NAME_CASE(CTZW) 9289 NODE_NAME_CASE(FSLW) 9290 NODE_NAME_CASE(FSRW) 9291 NODE_NAME_CASE(FSL) 9292 NODE_NAME_CASE(FSR) 9293 NODE_NAME_CASE(FMV_H_X) 9294 NODE_NAME_CASE(FMV_X_ANYEXTH) 9295 NODE_NAME_CASE(FMV_W_X_RV64) 9296 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 9297 NODE_NAME_CASE(FCVT_X_RTZ) 9298 NODE_NAME_CASE(FCVT_XU_RTZ) 9299 NODE_NAME_CASE(FCVT_W_RTZ_RV64) 9300 NODE_NAME_CASE(FCVT_WU_RTZ_RV64) 9301 NODE_NAME_CASE(READ_CYCLE_WIDE) 9302 NODE_NAME_CASE(GREV) 9303 NODE_NAME_CASE(GREVW) 9304 NODE_NAME_CASE(GORC) 9305 NODE_NAME_CASE(GORCW) 9306 NODE_NAME_CASE(SHFL) 9307 NODE_NAME_CASE(SHFLW) 9308 NODE_NAME_CASE(UNSHFL) 9309 NODE_NAME_CASE(UNSHFLW) 9310 NODE_NAME_CASE(BCOMPRESS) 9311 NODE_NAME_CASE(BCOMPRESSW) 9312 NODE_NAME_CASE(BDECOMPRESS) 9313 NODE_NAME_CASE(BDECOMPRESSW) 9314 NODE_NAME_CASE(VMV_V_X_VL) 9315 NODE_NAME_CASE(VFMV_V_F_VL) 9316 NODE_NAME_CASE(VMV_X_S) 9317 NODE_NAME_CASE(VMV_S_X_VL) 9318 NODE_NAME_CASE(VFMV_S_F_VL) 9319 NODE_NAME_CASE(SPLAT_VECTOR_I64) 9320 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 9321 NODE_NAME_CASE(READ_VLENB) 9322 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 9323 NODE_NAME_CASE(VSLIDEUP_VL) 9324 NODE_NAME_CASE(VSLIDE1UP_VL) 9325 NODE_NAME_CASE(VSLIDEDOWN_VL) 9326 NODE_NAME_CASE(VSLIDE1DOWN_VL) 9327 NODE_NAME_CASE(VID_VL) 9328 NODE_NAME_CASE(VFNCVT_ROD_VL) 9329 NODE_NAME_CASE(VECREDUCE_ADD_VL) 9330 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 9331 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 9332 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 9333 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 9334 NODE_NAME_CASE(VECREDUCE_AND_VL) 9335 NODE_NAME_CASE(VECREDUCE_OR_VL) 9336 NODE_NAME_CASE(VECREDUCE_XOR_VL) 9337 NODE_NAME_CASE(VECREDUCE_FADD_VL) 9338 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 9339 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 9340 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 9341 NODE_NAME_CASE(ADD_VL) 9342 NODE_NAME_CASE(AND_VL) 9343 NODE_NAME_CASE(MUL_VL) 9344 NODE_NAME_CASE(OR_VL) 9345 NODE_NAME_CASE(SDIV_VL) 9346 NODE_NAME_CASE(SHL_VL) 9347 NODE_NAME_CASE(SREM_VL) 9348 NODE_NAME_CASE(SRA_VL) 9349 NODE_NAME_CASE(SRL_VL) 9350 NODE_NAME_CASE(SUB_VL) 9351 NODE_NAME_CASE(UDIV_VL) 9352 NODE_NAME_CASE(UREM_VL) 9353 NODE_NAME_CASE(XOR_VL) 9354 NODE_NAME_CASE(SADDSAT_VL) 9355 NODE_NAME_CASE(UADDSAT_VL) 9356 NODE_NAME_CASE(SSUBSAT_VL) 9357 NODE_NAME_CASE(USUBSAT_VL) 9358 NODE_NAME_CASE(FADD_VL) 9359 NODE_NAME_CASE(FSUB_VL) 9360 NODE_NAME_CASE(FMUL_VL) 9361 NODE_NAME_CASE(FDIV_VL) 9362 NODE_NAME_CASE(FNEG_VL) 9363 NODE_NAME_CASE(FABS_VL) 9364 NODE_NAME_CASE(FSQRT_VL) 9365 NODE_NAME_CASE(FMA_VL) 9366 NODE_NAME_CASE(FCOPYSIGN_VL) 9367 NODE_NAME_CASE(SMIN_VL) 9368 NODE_NAME_CASE(SMAX_VL) 9369 NODE_NAME_CASE(UMIN_VL) 9370 NODE_NAME_CASE(UMAX_VL) 9371 NODE_NAME_CASE(FMINNUM_VL) 9372 NODE_NAME_CASE(FMAXNUM_VL) 9373 NODE_NAME_CASE(MULHS_VL) 9374 NODE_NAME_CASE(MULHU_VL) 9375 NODE_NAME_CASE(FP_TO_SINT_VL) 9376 NODE_NAME_CASE(FP_TO_UINT_VL) 9377 NODE_NAME_CASE(SINT_TO_FP_VL) 9378 NODE_NAME_CASE(UINT_TO_FP_VL) 9379 NODE_NAME_CASE(FP_EXTEND_VL) 9380 NODE_NAME_CASE(FP_ROUND_VL) 9381 NODE_NAME_CASE(VWMUL_VL) 9382 NODE_NAME_CASE(VWMULU_VL) 9383 NODE_NAME_CASE(SETCC_VL) 9384 NODE_NAME_CASE(VSELECT_VL) 9385 NODE_NAME_CASE(VMAND_VL) 9386 NODE_NAME_CASE(VMOR_VL) 9387 NODE_NAME_CASE(VMXOR_VL) 9388 NODE_NAME_CASE(VMCLR_VL) 9389 NODE_NAME_CASE(VMSET_VL) 9390 NODE_NAME_CASE(VRGATHER_VX_VL) 9391 NODE_NAME_CASE(VRGATHER_VV_VL) 9392 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 9393 NODE_NAME_CASE(VSEXT_VL) 9394 NODE_NAME_CASE(VZEXT_VL) 9395 NODE_NAME_CASE(VCPOP_VL) 9396 NODE_NAME_CASE(VLE_VL) 9397 NODE_NAME_CASE(VSE_VL) 9398 NODE_NAME_CASE(READ_CSR) 9399 NODE_NAME_CASE(WRITE_CSR) 9400 NODE_NAME_CASE(SWAP_CSR) 9401 } 9402 // clang-format on 9403 return nullptr; 9404 #undef NODE_NAME_CASE 9405 } 9406 9407 /// getConstraintType - Given a constraint letter, return the type of 9408 /// constraint it is for this target. 9409 RISCVTargetLowering::ConstraintType 9410 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 9411 if (Constraint.size() == 1) { 9412 switch (Constraint[0]) { 9413 default: 9414 break; 9415 case 'f': 9416 return C_RegisterClass; 9417 case 'I': 9418 case 'J': 9419 case 'K': 9420 return C_Immediate; 9421 case 'A': 9422 return C_Memory; 9423 case 'S': // A symbolic address 9424 return C_Other; 9425 } 9426 } else { 9427 if (Constraint == "vr" || Constraint == "vm") 9428 return C_RegisterClass; 9429 } 9430 return TargetLowering::getConstraintType(Constraint); 9431 } 9432 9433 std::pair<unsigned, const TargetRegisterClass *> 9434 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 9435 StringRef Constraint, 9436 MVT VT) const { 9437 // First, see if this is a constraint that directly corresponds to a 9438 // RISCV register class. 9439 if (Constraint.size() == 1) { 9440 switch (Constraint[0]) { 9441 case 'r': 9442 return std::make_pair(0U, &RISCV::GPRRegClass); 9443 case 'f': 9444 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 9445 return std::make_pair(0U, &RISCV::FPR16RegClass); 9446 if (Subtarget.hasStdExtF() && VT == MVT::f32) 9447 return std::make_pair(0U, &RISCV::FPR32RegClass); 9448 if (Subtarget.hasStdExtD() && VT == MVT::f64) 9449 return std::make_pair(0U, &RISCV::FPR64RegClass); 9450 break; 9451 default: 9452 break; 9453 } 9454 } else { 9455 if (Constraint == "vr") { 9456 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 9457 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9458 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 9459 return std::make_pair(0U, RC); 9460 } 9461 } else if (Constraint == "vm") { 9462 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9463 return std::make_pair(0U, &RISCV::VMRegClass); 9464 } 9465 } 9466 9467 // Clang will correctly decode the usage of register name aliases into their 9468 // official names. However, other frontends like `rustc` do not. This allows 9469 // users of these frontends to use the ABI names for registers in LLVM-style 9470 // register constraints. 9471 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 9472 .Case("{zero}", RISCV::X0) 9473 .Case("{ra}", RISCV::X1) 9474 .Case("{sp}", RISCV::X2) 9475 .Case("{gp}", RISCV::X3) 9476 .Case("{tp}", RISCV::X4) 9477 .Case("{t0}", RISCV::X5) 9478 .Case("{t1}", RISCV::X6) 9479 .Case("{t2}", RISCV::X7) 9480 .Cases("{s0}", "{fp}", RISCV::X8) 9481 .Case("{s1}", RISCV::X9) 9482 .Case("{a0}", RISCV::X10) 9483 .Case("{a1}", RISCV::X11) 9484 .Case("{a2}", RISCV::X12) 9485 .Case("{a3}", RISCV::X13) 9486 .Case("{a4}", RISCV::X14) 9487 .Case("{a5}", RISCV::X15) 9488 .Case("{a6}", RISCV::X16) 9489 .Case("{a7}", RISCV::X17) 9490 .Case("{s2}", RISCV::X18) 9491 .Case("{s3}", RISCV::X19) 9492 .Case("{s4}", RISCV::X20) 9493 .Case("{s5}", RISCV::X21) 9494 .Case("{s6}", RISCV::X22) 9495 .Case("{s7}", RISCV::X23) 9496 .Case("{s8}", RISCV::X24) 9497 .Case("{s9}", RISCV::X25) 9498 .Case("{s10}", RISCV::X26) 9499 .Case("{s11}", RISCV::X27) 9500 .Case("{t3}", RISCV::X28) 9501 .Case("{t4}", RISCV::X29) 9502 .Case("{t5}", RISCV::X30) 9503 .Case("{t6}", RISCV::X31) 9504 .Default(RISCV::NoRegister); 9505 if (XRegFromAlias != RISCV::NoRegister) 9506 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 9507 9508 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 9509 // TableGen record rather than the AsmName to choose registers for InlineAsm 9510 // constraints, plus we want to match those names to the widest floating point 9511 // register type available, manually select floating point registers here. 9512 // 9513 // The second case is the ABI name of the register, so that frontends can also 9514 // use the ABI names in register constraint lists. 9515 if (Subtarget.hasStdExtF()) { 9516 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 9517 .Cases("{f0}", "{ft0}", RISCV::F0_F) 9518 .Cases("{f1}", "{ft1}", RISCV::F1_F) 9519 .Cases("{f2}", "{ft2}", RISCV::F2_F) 9520 .Cases("{f3}", "{ft3}", RISCV::F3_F) 9521 .Cases("{f4}", "{ft4}", RISCV::F4_F) 9522 .Cases("{f5}", "{ft5}", RISCV::F5_F) 9523 .Cases("{f6}", "{ft6}", RISCV::F6_F) 9524 .Cases("{f7}", "{ft7}", RISCV::F7_F) 9525 .Cases("{f8}", "{fs0}", RISCV::F8_F) 9526 .Cases("{f9}", "{fs1}", RISCV::F9_F) 9527 .Cases("{f10}", "{fa0}", RISCV::F10_F) 9528 .Cases("{f11}", "{fa1}", RISCV::F11_F) 9529 .Cases("{f12}", "{fa2}", RISCV::F12_F) 9530 .Cases("{f13}", "{fa3}", RISCV::F13_F) 9531 .Cases("{f14}", "{fa4}", RISCV::F14_F) 9532 .Cases("{f15}", "{fa5}", RISCV::F15_F) 9533 .Cases("{f16}", "{fa6}", RISCV::F16_F) 9534 .Cases("{f17}", "{fa7}", RISCV::F17_F) 9535 .Cases("{f18}", "{fs2}", RISCV::F18_F) 9536 .Cases("{f19}", "{fs3}", RISCV::F19_F) 9537 .Cases("{f20}", "{fs4}", RISCV::F20_F) 9538 .Cases("{f21}", "{fs5}", RISCV::F21_F) 9539 .Cases("{f22}", "{fs6}", RISCV::F22_F) 9540 .Cases("{f23}", "{fs7}", RISCV::F23_F) 9541 .Cases("{f24}", "{fs8}", RISCV::F24_F) 9542 .Cases("{f25}", "{fs9}", RISCV::F25_F) 9543 .Cases("{f26}", "{fs10}", RISCV::F26_F) 9544 .Cases("{f27}", "{fs11}", RISCV::F27_F) 9545 .Cases("{f28}", "{ft8}", RISCV::F28_F) 9546 .Cases("{f29}", "{ft9}", RISCV::F29_F) 9547 .Cases("{f30}", "{ft10}", RISCV::F30_F) 9548 .Cases("{f31}", "{ft11}", RISCV::F31_F) 9549 .Default(RISCV::NoRegister); 9550 if (FReg != RISCV::NoRegister) { 9551 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 9552 if (Subtarget.hasStdExtD()) { 9553 unsigned RegNo = FReg - RISCV::F0_F; 9554 unsigned DReg = RISCV::F0_D + RegNo; 9555 return std::make_pair(DReg, &RISCV::FPR64RegClass); 9556 } 9557 return std::make_pair(FReg, &RISCV::FPR32RegClass); 9558 } 9559 } 9560 9561 if (Subtarget.hasVInstructions()) { 9562 Register VReg = StringSwitch<Register>(Constraint.lower()) 9563 .Case("{v0}", RISCV::V0) 9564 .Case("{v1}", RISCV::V1) 9565 .Case("{v2}", RISCV::V2) 9566 .Case("{v3}", RISCV::V3) 9567 .Case("{v4}", RISCV::V4) 9568 .Case("{v5}", RISCV::V5) 9569 .Case("{v6}", RISCV::V6) 9570 .Case("{v7}", RISCV::V7) 9571 .Case("{v8}", RISCV::V8) 9572 .Case("{v9}", RISCV::V9) 9573 .Case("{v10}", RISCV::V10) 9574 .Case("{v11}", RISCV::V11) 9575 .Case("{v12}", RISCV::V12) 9576 .Case("{v13}", RISCV::V13) 9577 .Case("{v14}", RISCV::V14) 9578 .Case("{v15}", RISCV::V15) 9579 .Case("{v16}", RISCV::V16) 9580 .Case("{v17}", RISCV::V17) 9581 .Case("{v18}", RISCV::V18) 9582 .Case("{v19}", RISCV::V19) 9583 .Case("{v20}", RISCV::V20) 9584 .Case("{v21}", RISCV::V21) 9585 .Case("{v22}", RISCV::V22) 9586 .Case("{v23}", RISCV::V23) 9587 .Case("{v24}", RISCV::V24) 9588 .Case("{v25}", RISCV::V25) 9589 .Case("{v26}", RISCV::V26) 9590 .Case("{v27}", RISCV::V27) 9591 .Case("{v28}", RISCV::V28) 9592 .Case("{v29}", RISCV::V29) 9593 .Case("{v30}", RISCV::V30) 9594 .Case("{v31}", RISCV::V31) 9595 .Default(RISCV::NoRegister); 9596 if (VReg != RISCV::NoRegister) { 9597 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9598 return std::make_pair(VReg, &RISCV::VMRegClass); 9599 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 9600 return std::make_pair(VReg, &RISCV::VRRegClass); 9601 for (const auto *RC : 9602 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9603 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 9604 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 9605 return std::make_pair(VReg, RC); 9606 } 9607 } 9608 } 9609 } 9610 9611 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 9612 } 9613 9614 unsigned 9615 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 9616 // Currently only support length 1 constraints. 9617 if (ConstraintCode.size() == 1) { 9618 switch (ConstraintCode[0]) { 9619 case 'A': 9620 return InlineAsm::Constraint_A; 9621 default: 9622 break; 9623 } 9624 } 9625 9626 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 9627 } 9628 9629 void RISCVTargetLowering::LowerAsmOperandForConstraint( 9630 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 9631 SelectionDAG &DAG) const { 9632 // Currently only support length 1 constraints. 9633 if (Constraint.length() == 1) { 9634 switch (Constraint[0]) { 9635 case 'I': 9636 // Validate & create a 12-bit signed immediate operand. 9637 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9638 uint64_t CVal = C->getSExtValue(); 9639 if (isInt<12>(CVal)) 9640 Ops.push_back( 9641 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9642 } 9643 return; 9644 case 'J': 9645 // Validate & create an integer zero operand. 9646 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 9647 if (C->getZExtValue() == 0) 9648 Ops.push_back( 9649 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 9650 return; 9651 case 'K': 9652 // Validate & create a 5-bit unsigned immediate operand. 9653 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9654 uint64_t CVal = C->getZExtValue(); 9655 if (isUInt<5>(CVal)) 9656 Ops.push_back( 9657 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9658 } 9659 return; 9660 case 'S': 9661 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9662 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 9663 GA->getValueType(0))); 9664 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 9665 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 9666 BA->getValueType(0))); 9667 } 9668 return; 9669 default: 9670 break; 9671 } 9672 } 9673 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 9674 } 9675 9676 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 9677 Instruction *Inst, 9678 AtomicOrdering Ord) const { 9679 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 9680 return Builder.CreateFence(Ord); 9681 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 9682 return Builder.CreateFence(AtomicOrdering::Release); 9683 return nullptr; 9684 } 9685 9686 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 9687 Instruction *Inst, 9688 AtomicOrdering Ord) const { 9689 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 9690 return Builder.CreateFence(AtomicOrdering::Acquire); 9691 return nullptr; 9692 } 9693 9694 TargetLowering::AtomicExpansionKind 9695 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 9696 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 9697 // point operations can't be used in an lr/sc sequence without breaking the 9698 // forward-progress guarantee. 9699 if (AI->isFloatingPointOperation()) 9700 return AtomicExpansionKind::CmpXChg; 9701 9702 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 9703 if (Size == 8 || Size == 16) 9704 return AtomicExpansionKind::MaskedIntrinsic; 9705 return AtomicExpansionKind::None; 9706 } 9707 9708 static Intrinsic::ID 9709 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 9710 if (XLen == 32) { 9711 switch (BinOp) { 9712 default: 9713 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9714 case AtomicRMWInst::Xchg: 9715 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 9716 case AtomicRMWInst::Add: 9717 return Intrinsic::riscv_masked_atomicrmw_add_i32; 9718 case AtomicRMWInst::Sub: 9719 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 9720 case AtomicRMWInst::Nand: 9721 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 9722 case AtomicRMWInst::Max: 9723 return Intrinsic::riscv_masked_atomicrmw_max_i32; 9724 case AtomicRMWInst::Min: 9725 return Intrinsic::riscv_masked_atomicrmw_min_i32; 9726 case AtomicRMWInst::UMax: 9727 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 9728 case AtomicRMWInst::UMin: 9729 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 9730 } 9731 } 9732 9733 if (XLen == 64) { 9734 switch (BinOp) { 9735 default: 9736 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9737 case AtomicRMWInst::Xchg: 9738 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 9739 case AtomicRMWInst::Add: 9740 return Intrinsic::riscv_masked_atomicrmw_add_i64; 9741 case AtomicRMWInst::Sub: 9742 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 9743 case AtomicRMWInst::Nand: 9744 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 9745 case AtomicRMWInst::Max: 9746 return Intrinsic::riscv_masked_atomicrmw_max_i64; 9747 case AtomicRMWInst::Min: 9748 return Intrinsic::riscv_masked_atomicrmw_min_i64; 9749 case AtomicRMWInst::UMax: 9750 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 9751 case AtomicRMWInst::UMin: 9752 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 9753 } 9754 } 9755 9756 llvm_unreachable("Unexpected XLen\n"); 9757 } 9758 9759 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 9760 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 9761 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 9762 unsigned XLen = Subtarget.getXLen(); 9763 Value *Ordering = 9764 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 9765 Type *Tys[] = {AlignedAddr->getType()}; 9766 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 9767 AI->getModule(), 9768 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 9769 9770 if (XLen == 64) { 9771 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 9772 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 9773 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 9774 } 9775 9776 Value *Result; 9777 9778 // Must pass the shift amount needed to sign extend the loaded value prior 9779 // to performing a signed comparison for min/max. ShiftAmt is the number of 9780 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 9781 // is the number of bits to left+right shift the value in order to 9782 // sign-extend. 9783 if (AI->getOperation() == AtomicRMWInst::Min || 9784 AI->getOperation() == AtomicRMWInst::Max) { 9785 const DataLayout &DL = AI->getModule()->getDataLayout(); 9786 unsigned ValWidth = 9787 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 9788 Value *SextShamt = 9789 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 9790 Result = Builder.CreateCall(LrwOpScwLoop, 9791 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 9792 } else { 9793 Result = 9794 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 9795 } 9796 9797 if (XLen == 64) 9798 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 9799 return Result; 9800 } 9801 9802 TargetLowering::AtomicExpansionKind 9803 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 9804 AtomicCmpXchgInst *CI) const { 9805 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 9806 if (Size == 8 || Size == 16) 9807 return AtomicExpansionKind::MaskedIntrinsic; 9808 return AtomicExpansionKind::None; 9809 } 9810 9811 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 9812 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 9813 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 9814 unsigned XLen = Subtarget.getXLen(); 9815 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 9816 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 9817 if (XLen == 64) { 9818 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 9819 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 9820 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 9821 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 9822 } 9823 Type *Tys[] = {AlignedAddr->getType()}; 9824 Function *MaskedCmpXchg = 9825 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 9826 Value *Result = Builder.CreateCall( 9827 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 9828 if (XLen == 64) 9829 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 9830 return Result; 9831 } 9832 9833 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 9834 return false; 9835 } 9836 9837 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 9838 EVT VT) const { 9839 VT = VT.getScalarType(); 9840 9841 if (!VT.isSimple()) 9842 return false; 9843 9844 switch (VT.getSimpleVT().SimpleTy) { 9845 case MVT::f16: 9846 return Subtarget.hasStdExtZfh(); 9847 case MVT::f32: 9848 return Subtarget.hasStdExtF(); 9849 case MVT::f64: 9850 return Subtarget.hasStdExtD(); 9851 default: 9852 break; 9853 } 9854 9855 return false; 9856 } 9857 9858 Register RISCVTargetLowering::getExceptionPointerRegister( 9859 const Constant *PersonalityFn) const { 9860 return RISCV::X10; 9861 } 9862 9863 Register RISCVTargetLowering::getExceptionSelectorRegister( 9864 const Constant *PersonalityFn) const { 9865 return RISCV::X11; 9866 } 9867 9868 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 9869 // Return false to suppress the unnecessary extensions if the LibCall 9870 // arguments or return value is f32 type for LP64 ABI. 9871 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 9872 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 9873 return false; 9874 9875 return true; 9876 } 9877 9878 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 9879 if (Subtarget.is64Bit() && Type == MVT::i32) 9880 return true; 9881 9882 return IsSigned; 9883 } 9884 9885 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 9886 SDValue C) const { 9887 // Check integral scalar types. 9888 if (VT.isScalarInteger()) { 9889 // Omit the optimization if the sub target has the M extension and the data 9890 // size exceeds XLen. 9891 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 9892 return false; 9893 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 9894 // Break the MUL to a SLLI and an ADD/SUB. 9895 const APInt &Imm = ConstNode->getAPIntValue(); 9896 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 9897 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 9898 return true; 9899 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 9900 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 9901 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 9902 (Imm - 8).isPowerOf2())) 9903 return true; 9904 // Omit the following optimization if the sub target has the M extension 9905 // and the data size >= XLen. 9906 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 9907 return false; 9908 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 9909 // a pair of LUI/ADDI. 9910 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 9911 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 9912 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 9913 (1 - ImmS).isPowerOf2()) 9914 return true; 9915 } 9916 } 9917 } 9918 9919 return false; 9920 } 9921 9922 bool RISCVTargetLowering::isMulAddWithConstProfitable( 9923 const SDValue &AddNode, const SDValue &ConstNode) const { 9924 // Let the DAGCombiner decide for vectors. 9925 EVT VT = AddNode.getValueType(); 9926 if (VT.isVector()) 9927 return true; 9928 9929 // Let the DAGCombiner decide for larger types. 9930 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 9931 return true; 9932 9933 // It is worse if c1 is simm12 while c1*c2 is not. 9934 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 9935 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 9936 const APInt &C1 = C1Node->getAPIntValue(); 9937 const APInt &C2 = C2Node->getAPIntValue(); 9938 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 9939 return false; 9940 9941 // Default to true and let the DAGCombiner decide. 9942 return true; 9943 } 9944 9945 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 9946 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 9947 bool *Fast) const { 9948 if (!VT.isVector()) 9949 return false; 9950 9951 EVT ElemVT = VT.getVectorElementType(); 9952 if (Alignment >= ElemVT.getStoreSize()) { 9953 if (Fast) 9954 *Fast = true; 9955 return true; 9956 } 9957 9958 return false; 9959 } 9960 9961 bool RISCVTargetLowering::splitValueIntoRegisterParts( 9962 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 9963 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 9964 bool IsABIRegCopy = CC.hasValue(); 9965 EVT ValueVT = Val.getValueType(); 9966 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 9967 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 9968 // and cast to f32. 9969 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 9970 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 9971 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 9972 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 9973 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 9974 Parts[0] = Val; 9975 return true; 9976 } 9977 9978 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 9979 LLVMContext &Context = *DAG.getContext(); 9980 EVT ValueEltVT = ValueVT.getVectorElementType(); 9981 EVT PartEltVT = PartVT.getVectorElementType(); 9982 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 9983 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 9984 if (PartVTBitSize % ValueVTBitSize == 0) { 9985 // If the element types are different, bitcast to the same element type of 9986 // PartVT first. 9987 if (ValueEltVT != PartEltVT) { 9988 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 9989 assert(Count != 0 && "The number of element should not be zero."); 9990 EVT SameEltTypeVT = 9991 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 9992 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 9993 } 9994 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 9995 Val, DAG.getConstant(0, DL, Subtarget.getXLenVT())); 9996 Parts[0] = Val; 9997 return true; 9998 } 9999 } 10000 return false; 10001 } 10002 10003 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 10004 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 10005 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 10006 bool IsABIRegCopy = CC.hasValue(); 10007 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10008 SDValue Val = Parts[0]; 10009 10010 // Cast the f32 to i32, truncate to i16, and cast back to f16. 10011 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 10012 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 10013 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 10014 return Val; 10015 } 10016 10017 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10018 LLVMContext &Context = *DAG.getContext(); 10019 SDValue Val = Parts[0]; 10020 EVT ValueEltVT = ValueVT.getVectorElementType(); 10021 EVT PartEltVT = PartVT.getVectorElementType(); 10022 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10023 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10024 if (PartVTBitSize % ValueVTBitSize == 0) { 10025 EVT SameEltTypeVT = ValueVT; 10026 // If the element types are different, convert it to the same element type 10027 // of PartVT. 10028 if (ValueEltVT != PartEltVT) { 10029 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 10030 assert(Count != 0 && "The number of element should not be zero."); 10031 SameEltTypeVT = 10032 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 10033 } 10034 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val, 10035 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 10036 if (ValueEltVT != PartEltVT) 10037 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 10038 return Val; 10039 } 10040 } 10041 return SDValue(); 10042 } 10043 10044 #define GET_REGISTER_MATCHER 10045 #include "RISCVGenAsmMatcher.inc" 10046 10047 Register 10048 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 10049 const MachineFunction &MF) const { 10050 Register Reg = MatchRegisterAltName(RegName); 10051 if (Reg == RISCV::NoRegister) 10052 Reg = MatchRegisterName(RegName); 10053 if (Reg == RISCV::NoRegister) 10054 report_fatal_error( 10055 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 10056 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 10057 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 10058 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 10059 StringRef(RegName) + "\".")); 10060 return Reg; 10061 } 10062 10063 namespace llvm { 10064 namespace RISCVVIntrinsicsTable { 10065 10066 #define GET_RISCVVIntrinsicsTable_IMPL 10067 #include "RISCVGenSearchableTables.inc" 10068 10069 } // namespace RISCVVIntrinsicsTable 10070 10071 } // namespace llvm 10072