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.hasStdExtV()) { 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 addRegClassForRVV(VT); 133 134 if (Subtarget.hasStdExtZfh()) 135 for (MVT VT : F16VecVTs) 136 addRegClassForRVV(VT); 137 138 if (Subtarget.hasStdExtF()) 139 for (MVT VT : F32VecVTs) 140 addRegClassForRVV(VT); 141 142 if (Subtarget.hasStdExtD()) 143 for (MVT VT : F64VecVTs) 144 addRegClassForRVV(VT); 145 146 if (Subtarget.useRVVForFixedLengthVectors()) { 147 auto addRegClassForFixedVectors = [this](MVT VT) { 148 MVT ContainerVT = getContainerForFixedLengthVector(VT); 149 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 150 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 151 addRegisterClass(VT, TRI.getRegClass(RCID)); 152 }; 153 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 154 if (useRVVForFixedLengthVectorVT(VT)) 155 addRegClassForFixedVectors(VT); 156 157 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 158 if (useRVVForFixedLengthVectorVT(VT)) 159 addRegClassForFixedVectors(VT); 160 } 161 } 162 163 // Compute derived properties from the register classes. 164 computeRegisterProperties(STI.getRegisterInfo()); 165 166 setStackPointerRegisterToSaveRestore(RISCV::X2); 167 168 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 169 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 170 171 // TODO: add all necessary setOperationAction calls. 172 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 173 174 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 175 setOperationAction(ISD::BR_CC, XLenVT, Expand); 176 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 177 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 178 179 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 180 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 181 182 setOperationAction(ISD::VASTART, MVT::Other, Custom); 183 setOperationAction(ISD::VAARG, MVT::Other, Expand); 184 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 185 setOperationAction(ISD::VAEND, MVT::Other, Expand); 186 187 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 188 if (!Subtarget.hasStdExtZbb()) { 189 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 190 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 191 } 192 193 if (Subtarget.is64Bit()) { 194 setOperationAction(ISD::ADD, MVT::i32, Custom); 195 setOperationAction(ISD::SUB, MVT::i32, Custom); 196 setOperationAction(ISD::SHL, MVT::i32, Custom); 197 setOperationAction(ISD::SRA, MVT::i32, Custom); 198 setOperationAction(ISD::SRL, MVT::i32, Custom); 199 200 setOperationAction(ISD::UADDO, MVT::i32, Custom); 201 setOperationAction(ISD::USUBO, MVT::i32, Custom); 202 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 203 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 204 } else { 205 setLibcallName(RTLIB::SHL_I128, nullptr); 206 setLibcallName(RTLIB::SRL_I128, nullptr); 207 setLibcallName(RTLIB::SRA_I128, nullptr); 208 setLibcallName(RTLIB::MUL_I128, nullptr); 209 setLibcallName(RTLIB::MULO_I64, nullptr); 210 } 211 212 if (!Subtarget.hasStdExtM()) { 213 setOperationAction(ISD::MUL, XLenVT, Expand); 214 setOperationAction(ISD::MULHS, XLenVT, Expand); 215 setOperationAction(ISD::MULHU, XLenVT, Expand); 216 setOperationAction(ISD::SDIV, XLenVT, Expand); 217 setOperationAction(ISD::UDIV, XLenVT, Expand); 218 setOperationAction(ISD::SREM, XLenVT, Expand); 219 setOperationAction(ISD::UREM, XLenVT, Expand); 220 } else { 221 if (Subtarget.is64Bit()) { 222 setOperationAction(ISD::MUL, MVT::i32, Custom); 223 setOperationAction(ISD::MUL, MVT::i128, Custom); 224 225 setOperationAction(ISD::SDIV, MVT::i8, Custom); 226 setOperationAction(ISD::UDIV, MVT::i8, Custom); 227 setOperationAction(ISD::UREM, MVT::i8, Custom); 228 setOperationAction(ISD::SDIV, MVT::i16, Custom); 229 setOperationAction(ISD::UDIV, MVT::i16, Custom); 230 setOperationAction(ISD::UREM, MVT::i16, Custom); 231 setOperationAction(ISD::SDIV, MVT::i32, Custom); 232 setOperationAction(ISD::UDIV, MVT::i32, Custom); 233 setOperationAction(ISD::UREM, MVT::i32, Custom); 234 } else { 235 setOperationAction(ISD::MUL, MVT::i64, Custom); 236 } 237 } 238 239 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 240 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 241 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 242 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 243 244 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 245 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 246 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 247 248 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 249 if (Subtarget.is64Bit()) { 250 setOperationAction(ISD::ROTL, MVT::i32, Custom); 251 setOperationAction(ISD::ROTR, MVT::i32, Custom); 252 } 253 } else { 254 setOperationAction(ISD::ROTL, XLenVT, Expand); 255 setOperationAction(ISD::ROTR, XLenVT, Expand); 256 } 257 258 if (Subtarget.hasStdExtZbp()) { 259 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 260 // more combining. 261 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 262 setOperationAction(ISD::BSWAP, XLenVT, Custom); 263 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 264 // BSWAP i8 doesn't exist. 265 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 266 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 267 268 if (Subtarget.is64Bit()) { 269 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 270 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 271 } 272 } else { 273 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 274 // pattern match it directly in isel. 275 setOperationAction(ISD::BSWAP, XLenVT, 276 Subtarget.hasStdExtZbb() ? Legal : Expand); 277 } 278 279 if (Subtarget.hasStdExtZbb()) { 280 setOperationAction(ISD::SMIN, XLenVT, Legal); 281 setOperationAction(ISD::SMAX, XLenVT, Legal); 282 setOperationAction(ISD::UMIN, XLenVT, Legal); 283 setOperationAction(ISD::UMAX, XLenVT, Legal); 284 285 if (Subtarget.is64Bit()) { 286 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 287 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 288 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 289 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 290 } 291 } else { 292 setOperationAction(ISD::CTTZ, XLenVT, Expand); 293 setOperationAction(ISD::CTLZ, XLenVT, Expand); 294 setOperationAction(ISD::CTPOP, XLenVT, Expand); 295 } 296 297 if (Subtarget.hasStdExtZbt()) { 298 setOperationAction(ISD::FSHL, XLenVT, Custom); 299 setOperationAction(ISD::FSHR, XLenVT, Custom); 300 setOperationAction(ISD::SELECT, XLenVT, Legal); 301 302 if (Subtarget.is64Bit()) { 303 setOperationAction(ISD::FSHL, MVT::i32, Custom); 304 setOperationAction(ISD::FSHR, MVT::i32, Custom); 305 } 306 } else { 307 setOperationAction(ISD::SELECT, XLenVT, Custom); 308 } 309 310 static const ISD::CondCode FPCCToExpand[] = { 311 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 312 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 313 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 314 315 static const ISD::NodeType FPOpToExpand[] = { 316 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 317 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 318 319 if (Subtarget.hasStdExtZfh()) 320 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 321 322 if (Subtarget.hasStdExtZfh()) { 323 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 324 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 325 setOperationAction(ISD::LRINT, MVT::f16, Legal); 326 setOperationAction(ISD::LLRINT, MVT::f16, Legal); 327 setOperationAction(ISD::LROUND, MVT::f16, Legal); 328 setOperationAction(ISD::LLROUND, MVT::f16, Legal); 329 for (auto CC : FPCCToExpand) 330 setCondCodeAction(CC, MVT::f16, Expand); 331 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 332 setOperationAction(ISD::SELECT, MVT::f16, Custom); 333 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 334 for (auto Op : FPOpToExpand) 335 setOperationAction(Op, MVT::f16, Expand); 336 } 337 338 if (Subtarget.hasStdExtF()) { 339 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 340 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 341 setOperationAction(ISD::LRINT, MVT::f32, Legal); 342 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 343 setOperationAction(ISD::LROUND, MVT::f32, Legal); 344 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 345 for (auto CC : FPCCToExpand) 346 setCondCodeAction(CC, MVT::f32, Expand); 347 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 348 setOperationAction(ISD::SELECT, MVT::f32, Custom); 349 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 350 for (auto Op : FPOpToExpand) 351 setOperationAction(Op, MVT::f32, Expand); 352 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 353 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 354 } 355 356 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 357 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 358 359 if (Subtarget.hasStdExtD()) { 360 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 361 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 362 setOperationAction(ISD::LRINT, MVT::f64, Legal); 363 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 364 setOperationAction(ISD::LROUND, MVT::f64, Legal); 365 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 366 for (auto CC : FPCCToExpand) 367 setCondCodeAction(CC, MVT::f64, Expand); 368 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 369 setOperationAction(ISD::SELECT, MVT::f64, Custom); 370 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 371 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 372 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 373 for (auto Op : FPOpToExpand) 374 setOperationAction(Op, MVT::f64, Expand); 375 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 376 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 377 } 378 379 if (Subtarget.is64Bit()) { 380 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 381 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 382 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 383 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 384 } 385 386 if (Subtarget.hasStdExtF()) { 387 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 388 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 389 390 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 391 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 392 } 393 394 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 395 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 396 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 397 setOperationAction(ISD::JumpTable, XLenVT, Custom); 398 399 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 400 401 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 402 // Unfortunately this can't be determined just from the ISA naming string. 403 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 404 Subtarget.is64Bit() ? Legal : Custom); 405 406 setOperationAction(ISD::TRAP, MVT::Other, Legal); 407 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 408 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 409 if (Subtarget.is64Bit()) 410 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 411 412 if (Subtarget.hasStdExtA()) { 413 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 414 setMinCmpXchgSizeInBits(32); 415 } else { 416 setMaxAtomicSizeInBitsSupported(0); 417 } 418 419 setBooleanContents(ZeroOrOneBooleanContent); 420 421 if (Subtarget.hasStdExtV()) { 422 setBooleanVectorContents(ZeroOrOneBooleanContent); 423 424 setOperationAction(ISD::VSCALE, XLenVT, Custom); 425 426 // RVV intrinsics may have illegal operands. 427 // We also need to custom legalize vmv.x.s. 428 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 429 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 430 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 431 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 432 if (Subtarget.is64Bit()) { 433 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 434 } else { 435 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 436 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 437 } 438 439 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 440 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 441 442 static const unsigned IntegerVPOps[] = { 443 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 444 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 445 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 446 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 447 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 448 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 449 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}; 450 451 static const unsigned FloatingPointVPOps[] = { 452 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 453 ISD::VP_FDIV, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 454 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX}; 455 456 if (!Subtarget.is64Bit()) { 457 // We must custom-lower certain vXi64 operations on RV32 due to the vector 458 // element type being illegal. 459 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 460 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 461 462 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 463 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 464 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 465 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 466 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 467 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 468 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 469 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 470 471 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 472 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 473 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 474 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 475 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 476 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 477 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 478 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 479 } 480 481 for (MVT VT : BoolVecVTs) { 482 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 483 484 // Mask VTs are custom-expanded into a series of standard nodes 485 setOperationAction(ISD::TRUNCATE, VT, Custom); 486 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 487 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 488 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 489 490 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 491 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 492 493 setOperationAction(ISD::SELECT, VT, Custom); 494 setOperationAction(ISD::SELECT_CC, VT, Expand); 495 setOperationAction(ISD::VSELECT, VT, Expand); 496 497 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 498 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 499 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 500 501 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 502 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 503 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 504 505 // RVV has native int->float & float->int conversions where the 506 // element type sizes are within one power-of-two of each other. Any 507 // wider distances between type sizes have to be lowered as sequences 508 // which progressively narrow the gap in stages. 509 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 510 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 511 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 512 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 513 514 // Expand all extending loads to types larger than this, and truncating 515 // stores from types larger than this. 516 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 517 setTruncStoreAction(OtherVT, VT, Expand); 518 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 519 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 520 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 521 } 522 } 523 524 for (MVT VT : IntVecVTs) { 525 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 526 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 527 528 setOperationAction(ISD::SMIN, VT, Legal); 529 setOperationAction(ISD::SMAX, VT, Legal); 530 setOperationAction(ISD::UMIN, VT, Legal); 531 setOperationAction(ISD::UMAX, VT, Legal); 532 533 setOperationAction(ISD::ROTL, VT, Expand); 534 setOperationAction(ISD::ROTR, VT, Expand); 535 536 // Custom-lower extensions and truncations from/to mask types. 537 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 538 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 539 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 540 541 // RVV has native int->float & float->int conversions where the 542 // element type sizes are within one power-of-two of each other. Any 543 // wider distances between type sizes have to be lowered as sequences 544 // which progressively narrow the gap in stages. 545 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 546 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 547 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 548 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 549 550 setOperationAction(ISD::SADDSAT, VT, Legal); 551 setOperationAction(ISD::UADDSAT, VT, Legal); 552 setOperationAction(ISD::SSUBSAT, VT, Legal); 553 setOperationAction(ISD::USUBSAT, VT, Legal); 554 555 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 556 // nodes which truncate by one power of two at a time. 557 setOperationAction(ISD::TRUNCATE, VT, Custom); 558 559 // Custom-lower insert/extract operations to simplify patterns. 560 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 561 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 562 563 // Custom-lower reduction operations to set up the corresponding custom 564 // nodes' operands. 565 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 566 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 567 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 568 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 569 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 570 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 571 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 572 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 573 574 for (unsigned VPOpc : IntegerVPOps) 575 setOperationAction(VPOpc, VT, Custom); 576 577 setOperationAction(ISD::LOAD, VT, Custom); 578 setOperationAction(ISD::STORE, VT, Custom); 579 580 setOperationAction(ISD::MLOAD, VT, Custom); 581 setOperationAction(ISD::MSTORE, VT, Custom); 582 setOperationAction(ISD::MGATHER, VT, Custom); 583 setOperationAction(ISD::MSCATTER, VT, Custom); 584 585 setOperationAction(ISD::VP_LOAD, VT, Custom); 586 setOperationAction(ISD::VP_STORE, VT, Custom); 587 setOperationAction(ISD::VP_GATHER, VT, Custom); 588 setOperationAction(ISD::VP_SCATTER, VT, Custom); 589 590 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 591 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 592 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 593 594 setOperationAction(ISD::SELECT, VT, Custom); 595 setOperationAction(ISD::SELECT_CC, VT, Expand); 596 597 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 598 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 599 600 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 601 setTruncStoreAction(VT, OtherVT, Expand); 602 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 603 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 604 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 605 } 606 } 607 608 // Expand various CCs to best match the RVV ISA, which natively supports UNE 609 // but no other unordered comparisons, and supports all ordered comparisons 610 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 611 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 612 // and we pattern-match those back to the "original", swapping operands once 613 // more. This way we catch both operations and both "vf" and "fv" forms with 614 // fewer patterns. 615 static const ISD::CondCode VFPCCToExpand[] = { 616 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 617 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 618 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 619 }; 620 621 // Sets common operation actions on RVV floating-point vector types. 622 const auto SetCommonVFPActions = [&](MVT VT) { 623 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 624 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 625 // sizes are within one power-of-two of each other. Therefore conversions 626 // between vXf16 and vXf64 must be lowered as sequences which convert via 627 // vXf32. 628 setOperationAction(ISD::FP_ROUND, VT, Custom); 629 setOperationAction(ISD::FP_EXTEND, VT, Custom); 630 // Custom-lower insert/extract operations to simplify patterns. 631 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 632 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 633 // Expand various condition codes (explained above). 634 for (auto CC : VFPCCToExpand) 635 setCondCodeAction(CC, VT, Expand); 636 637 setOperationAction(ISD::FMINNUM, VT, Legal); 638 setOperationAction(ISD::FMAXNUM, VT, Legal); 639 640 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 641 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 642 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 643 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 644 645 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 646 647 setOperationAction(ISD::LOAD, VT, Custom); 648 setOperationAction(ISD::STORE, VT, Custom); 649 650 setOperationAction(ISD::MLOAD, VT, Custom); 651 setOperationAction(ISD::MSTORE, VT, Custom); 652 setOperationAction(ISD::MGATHER, VT, Custom); 653 setOperationAction(ISD::MSCATTER, VT, Custom); 654 655 setOperationAction(ISD::VP_LOAD, VT, Custom); 656 setOperationAction(ISD::VP_STORE, VT, Custom); 657 setOperationAction(ISD::VP_GATHER, VT, Custom); 658 setOperationAction(ISD::VP_SCATTER, VT, Custom); 659 660 setOperationAction(ISD::SELECT, VT, Custom); 661 setOperationAction(ISD::SELECT_CC, VT, Expand); 662 663 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 664 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 665 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 666 667 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 668 669 for (unsigned VPOpc : FloatingPointVPOps) 670 setOperationAction(VPOpc, VT, Custom); 671 }; 672 673 // Sets common extload/truncstore actions on RVV floating-point vector 674 // types. 675 const auto SetCommonVFPExtLoadTruncStoreActions = 676 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 677 for (auto SmallVT : SmallerVTs) { 678 setTruncStoreAction(VT, SmallVT, Expand); 679 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 680 } 681 }; 682 683 if (Subtarget.hasStdExtZfh()) 684 for (MVT VT : F16VecVTs) 685 SetCommonVFPActions(VT); 686 687 for (MVT VT : F32VecVTs) { 688 if (Subtarget.hasStdExtF()) 689 SetCommonVFPActions(VT); 690 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 691 } 692 693 for (MVT VT : F64VecVTs) { 694 if (Subtarget.hasStdExtD()) 695 SetCommonVFPActions(VT); 696 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 697 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 698 } 699 700 if (Subtarget.useRVVForFixedLengthVectors()) { 701 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 702 if (!useRVVForFixedLengthVectorVT(VT)) 703 continue; 704 705 // By default everything must be expanded. 706 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 707 setOperationAction(Op, VT, Expand); 708 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 709 setTruncStoreAction(VT, OtherVT, Expand); 710 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 711 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 712 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 713 } 714 715 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 716 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 717 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 718 719 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 720 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 721 722 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 723 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 724 725 setOperationAction(ISD::LOAD, VT, Custom); 726 setOperationAction(ISD::STORE, VT, Custom); 727 728 setOperationAction(ISD::SETCC, VT, Custom); 729 730 setOperationAction(ISD::SELECT, VT, Custom); 731 732 setOperationAction(ISD::TRUNCATE, VT, Custom); 733 734 setOperationAction(ISD::BITCAST, VT, Custom); 735 736 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 737 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 738 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 739 740 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 741 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 742 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 743 744 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 745 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 746 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 747 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 748 749 // Operations below are different for between masks and other vectors. 750 if (VT.getVectorElementType() == MVT::i1) { 751 setOperationAction(ISD::AND, VT, Custom); 752 setOperationAction(ISD::OR, VT, Custom); 753 setOperationAction(ISD::XOR, VT, Custom); 754 continue; 755 } 756 757 // Use SPLAT_VECTOR to prevent type legalization from destroying the 758 // splats when type legalizing i64 scalar on RV32. 759 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 760 // improvements first. 761 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 762 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 763 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 764 } 765 766 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 767 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 768 769 setOperationAction(ISD::MLOAD, VT, Custom); 770 setOperationAction(ISD::MSTORE, VT, Custom); 771 setOperationAction(ISD::MGATHER, VT, Custom); 772 setOperationAction(ISD::MSCATTER, VT, Custom); 773 774 setOperationAction(ISD::VP_LOAD, VT, Custom); 775 setOperationAction(ISD::VP_STORE, VT, Custom); 776 setOperationAction(ISD::VP_GATHER, VT, Custom); 777 setOperationAction(ISD::VP_SCATTER, VT, Custom); 778 779 setOperationAction(ISD::ADD, VT, Custom); 780 setOperationAction(ISD::MUL, VT, Custom); 781 setOperationAction(ISD::SUB, VT, Custom); 782 setOperationAction(ISD::AND, VT, Custom); 783 setOperationAction(ISD::OR, VT, Custom); 784 setOperationAction(ISD::XOR, VT, Custom); 785 setOperationAction(ISD::SDIV, VT, Custom); 786 setOperationAction(ISD::SREM, VT, Custom); 787 setOperationAction(ISD::UDIV, VT, Custom); 788 setOperationAction(ISD::UREM, VT, Custom); 789 setOperationAction(ISD::SHL, VT, Custom); 790 setOperationAction(ISD::SRA, VT, Custom); 791 setOperationAction(ISD::SRL, VT, Custom); 792 793 setOperationAction(ISD::SMIN, VT, Custom); 794 setOperationAction(ISD::SMAX, VT, Custom); 795 setOperationAction(ISD::UMIN, VT, Custom); 796 setOperationAction(ISD::UMAX, VT, Custom); 797 setOperationAction(ISD::ABS, VT, Custom); 798 799 setOperationAction(ISD::MULHS, VT, Custom); 800 setOperationAction(ISD::MULHU, VT, Custom); 801 802 setOperationAction(ISD::SADDSAT, VT, Custom); 803 setOperationAction(ISD::UADDSAT, VT, Custom); 804 setOperationAction(ISD::SSUBSAT, VT, Custom); 805 setOperationAction(ISD::USUBSAT, VT, Custom); 806 807 setOperationAction(ISD::VSELECT, VT, Custom); 808 setOperationAction(ISD::SELECT_CC, VT, Expand); 809 810 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 811 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 812 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 813 814 // Custom-lower reduction operations to set up the corresponding custom 815 // nodes' operands. 816 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 817 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 818 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 819 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 820 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 821 822 for (unsigned VPOpc : IntegerVPOps) 823 setOperationAction(VPOpc, VT, Custom); 824 } 825 826 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 827 if (!useRVVForFixedLengthVectorVT(VT)) 828 continue; 829 830 // By default everything must be expanded. 831 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 832 setOperationAction(Op, VT, Expand); 833 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 834 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 835 setTruncStoreAction(VT, OtherVT, Expand); 836 } 837 838 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 839 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 840 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 841 842 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 843 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 844 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 845 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 846 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 847 848 setOperationAction(ISD::LOAD, VT, Custom); 849 setOperationAction(ISD::STORE, VT, Custom); 850 setOperationAction(ISD::MLOAD, VT, Custom); 851 setOperationAction(ISD::MSTORE, VT, Custom); 852 setOperationAction(ISD::MGATHER, VT, Custom); 853 setOperationAction(ISD::MSCATTER, VT, Custom); 854 855 setOperationAction(ISD::VP_LOAD, VT, Custom); 856 setOperationAction(ISD::VP_STORE, VT, Custom); 857 setOperationAction(ISD::VP_GATHER, VT, Custom); 858 setOperationAction(ISD::VP_SCATTER, VT, Custom); 859 860 setOperationAction(ISD::FADD, VT, Custom); 861 setOperationAction(ISD::FSUB, VT, Custom); 862 setOperationAction(ISD::FMUL, VT, Custom); 863 setOperationAction(ISD::FDIV, VT, Custom); 864 setOperationAction(ISD::FNEG, VT, Custom); 865 setOperationAction(ISD::FABS, VT, Custom); 866 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 867 setOperationAction(ISD::FSQRT, VT, Custom); 868 setOperationAction(ISD::FMA, VT, Custom); 869 setOperationAction(ISD::FMINNUM, VT, Custom); 870 setOperationAction(ISD::FMAXNUM, VT, Custom); 871 872 setOperationAction(ISD::FP_ROUND, VT, Custom); 873 setOperationAction(ISD::FP_EXTEND, VT, Custom); 874 875 for (auto CC : VFPCCToExpand) 876 setCondCodeAction(CC, VT, Expand); 877 878 setOperationAction(ISD::VSELECT, VT, Custom); 879 setOperationAction(ISD::SELECT, VT, Custom); 880 setOperationAction(ISD::SELECT_CC, VT, Expand); 881 882 setOperationAction(ISD::BITCAST, VT, Custom); 883 884 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 885 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 886 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 887 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 888 889 for (unsigned VPOpc : FloatingPointVPOps) 890 setOperationAction(VPOpc, VT, Custom); 891 } 892 893 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 894 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 895 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 896 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 897 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 898 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 899 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 900 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 901 } 902 } 903 904 // Function alignments. 905 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 906 setMinFunctionAlignment(FunctionAlignment); 907 setPrefFunctionAlignment(FunctionAlignment); 908 909 setMinimumJumpTableEntries(5); 910 911 // Jumps are expensive, compared to logic 912 setJumpIsExpensive(); 913 914 // We can use any register for comparisons 915 setHasMultipleConditionRegisters(); 916 917 setTargetDAGCombine(ISD::ADD); 918 setTargetDAGCombine(ISD::SUB); 919 setTargetDAGCombine(ISD::AND); 920 setTargetDAGCombine(ISD::OR); 921 setTargetDAGCombine(ISD::XOR); 922 setTargetDAGCombine(ISD::ANY_EXTEND); 923 setTargetDAGCombine(ISD::ZERO_EXTEND); 924 if (Subtarget.hasStdExtV()) { 925 setTargetDAGCombine(ISD::FCOPYSIGN); 926 setTargetDAGCombine(ISD::MGATHER); 927 setTargetDAGCombine(ISD::MSCATTER); 928 setTargetDAGCombine(ISD::VP_GATHER); 929 setTargetDAGCombine(ISD::VP_SCATTER); 930 setTargetDAGCombine(ISD::SRA); 931 setTargetDAGCombine(ISD::SRL); 932 setTargetDAGCombine(ISD::SHL); 933 } 934 } 935 936 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 937 LLVMContext &Context, 938 EVT VT) const { 939 if (!VT.isVector()) 940 return getPointerTy(DL); 941 if (Subtarget.hasStdExtV() && 942 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 943 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 944 return VT.changeVectorElementTypeToInteger(); 945 } 946 947 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 948 return Subtarget.getXLenVT(); 949 } 950 951 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 952 const CallInst &I, 953 MachineFunction &MF, 954 unsigned Intrinsic) const { 955 switch (Intrinsic) { 956 default: 957 return false; 958 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 959 case Intrinsic::riscv_masked_atomicrmw_add_i32: 960 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 961 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 962 case Intrinsic::riscv_masked_atomicrmw_max_i32: 963 case Intrinsic::riscv_masked_atomicrmw_min_i32: 964 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 965 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 966 case Intrinsic::riscv_masked_cmpxchg_i32: { 967 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 968 Info.opc = ISD::INTRINSIC_W_CHAIN; 969 Info.memVT = MVT::getVT(PtrTy->getElementType()); 970 Info.ptrVal = I.getArgOperand(0); 971 Info.offset = 0; 972 Info.align = Align(4); 973 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 974 MachineMemOperand::MOVolatile; 975 return true; 976 } 977 case Intrinsic::riscv_masked_strided_load: 978 Info.opc = ISD::INTRINSIC_W_CHAIN; 979 Info.ptrVal = I.getArgOperand(1); 980 Info.memVT = MVT::getVT(I.getType()->getScalarType()); 981 Info.align = Align(I.getType()->getScalarSizeInBits() / 8); 982 Info.size = MemoryLocation::UnknownSize; 983 Info.flags |= MachineMemOperand::MOLoad; 984 return true; 985 case Intrinsic::riscv_masked_strided_store: 986 Info.opc = ISD::INTRINSIC_VOID; 987 Info.ptrVal = I.getArgOperand(1); 988 Info.memVT = MVT::getVT(I.getArgOperand(0)->getType()->getScalarType()); 989 Info.align = 990 Align(I.getArgOperand(0)->getType()->getScalarSizeInBits() / 8); 991 Info.size = MemoryLocation::UnknownSize; 992 Info.flags |= MachineMemOperand::MOStore; 993 return true; 994 } 995 } 996 997 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 998 const AddrMode &AM, Type *Ty, 999 unsigned AS, 1000 Instruction *I) const { 1001 // No global is ever allowed as a base. 1002 if (AM.BaseGV) 1003 return false; 1004 1005 // Require a 12-bit signed offset. 1006 if (!isInt<12>(AM.BaseOffs)) 1007 return false; 1008 1009 switch (AM.Scale) { 1010 case 0: // "r+i" or just "i", depending on HasBaseReg. 1011 break; 1012 case 1: 1013 if (!AM.HasBaseReg) // allow "r+i". 1014 break; 1015 return false; // disallow "r+r" or "r+r+i". 1016 default: 1017 return false; 1018 } 1019 1020 return true; 1021 } 1022 1023 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1024 return isInt<12>(Imm); 1025 } 1026 1027 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1028 return isInt<12>(Imm); 1029 } 1030 1031 // On RV32, 64-bit integers are split into their high and low parts and held 1032 // in two different registers, so the trunc is free since the low register can 1033 // just be used. 1034 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1035 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1036 return false; 1037 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1038 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1039 return (SrcBits == 64 && DestBits == 32); 1040 } 1041 1042 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1043 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1044 !SrcVT.isInteger() || !DstVT.isInteger()) 1045 return false; 1046 unsigned SrcBits = SrcVT.getSizeInBits(); 1047 unsigned DestBits = DstVT.getSizeInBits(); 1048 return (SrcBits == 64 && DestBits == 32); 1049 } 1050 1051 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1052 // Zexts are free if they can be combined with a load. 1053 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1054 EVT MemVT = LD->getMemoryVT(); 1055 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 1056 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 1057 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1058 LD->getExtensionType() == ISD::ZEXTLOAD)) 1059 return true; 1060 } 1061 1062 return TargetLowering::isZExtFree(Val, VT2); 1063 } 1064 1065 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1066 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1067 } 1068 1069 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1070 return Subtarget.hasStdExtZbb(); 1071 } 1072 1073 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1074 return Subtarget.hasStdExtZbb(); 1075 } 1076 1077 /// Check if sinking \p I's operands to I's basic block is profitable, because 1078 /// the operands can be folded into a target instruction, e.g. 1079 /// splats of scalars can fold into vector instructions. 1080 bool RISCVTargetLowering::shouldSinkOperands( 1081 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1082 using namespace llvm::PatternMatch; 1083 1084 if (!I->getType()->isVectorTy() || !Subtarget.hasStdExtV()) 1085 return false; 1086 1087 auto IsSinker = [&](Instruction *I, int Operand) { 1088 switch (I->getOpcode()) { 1089 case Instruction::Add: 1090 case Instruction::Sub: 1091 case Instruction::Mul: 1092 case Instruction::And: 1093 case Instruction::Or: 1094 case Instruction::Xor: 1095 case Instruction::FAdd: 1096 case Instruction::FSub: 1097 case Instruction::FMul: 1098 case Instruction::FDiv: 1099 return true; 1100 case Instruction::Shl: 1101 case Instruction::LShr: 1102 case Instruction::AShr: 1103 return Operand == 1; 1104 case Instruction::Call: 1105 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1106 switch (II->getIntrinsicID()) { 1107 case Intrinsic::fma: 1108 return Operand == 0 || Operand == 1; 1109 default: 1110 return false; 1111 } 1112 } 1113 return false; 1114 default: 1115 return false; 1116 } 1117 }; 1118 1119 for (auto OpIdx : enumerate(I->operands())) { 1120 if (!IsSinker(I, OpIdx.index())) 1121 continue; 1122 1123 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1124 // Make sure we are not already sinking this operand 1125 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1126 continue; 1127 1128 // We are looking for a splat that can be sunk. 1129 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1130 m_Undef(), m_ZeroMask()))) 1131 continue; 1132 1133 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1134 // and vector registers 1135 for (Use &U : Op->uses()) { 1136 Instruction *Insn = cast<Instruction>(U.getUser()); 1137 if (!IsSinker(Insn, U.getOperandNo())) 1138 return false; 1139 } 1140 1141 Ops.push_back(&Op->getOperandUse(0)); 1142 Ops.push_back(&OpIdx.value()); 1143 } 1144 return true; 1145 } 1146 1147 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1148 bool ForCodeSize) const { 1149 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1150 return false; 1151 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1152 return false; 1153 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1154 return false; 1155 if (Imm.isNegZero()) 1156 return false; 1157 return Imm.isZero(); 1158 } 1159 1160 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1161 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1162 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1163 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1164 } 1165 1166 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1167 CallingConv::ID CC, 1168 EVT VT) const { 1169 // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still 1170 // end up using a GPR but that will be decided based on ABI. 1171 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1172 return MVT::f32; 1173 1174 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1175 } 1176 1177 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1178 CallingConv::ID CC, 1179 EVT VT) const { 1180 // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still 1181 // end up using a GPR but that will be decided based on ABI. 1182 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1183 return 1; 1184 1185 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1186 } 1187 1188 // Changes the condition code and swaps operands if necessary, so the SetCC 1189 // operation matches one of the comparisons supported directly by branches 1190 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1191 // with 1/-1. 1192 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1193 ISD::CondCode &CC, SelectionDAG &DAG) { 1194 // Convert X > -1 to X >= 0. 1195 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1196 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1197 CC = ISD::SETGE; 1198 return; 1199 } 1200 // Convert X < 1 to 0 >= X. 1201 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1202 RHS = LHS; 1203 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1204 CC = ISD::SETGE; 1205 return; 1206 } 1207 1208 switch (CC) { 1209 default: 1210 break; 1211 case ISD::SETGT: 1212 case ISD::SETLE: 1213 case ISD::SETUGT: 1214 case ISD::SETULE: 1215 CC = ISD::getSetCCSwappedOperands(CC); 1216 std::swap(LHS, RHS); 1217 break; 1218 } 1219 } 1220 1221 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1222 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1223 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1224 if (VT.getVectorElementType() == MVT::i1) 1225 KnownSize *= 8; 1226 1227 switch (KnownSize) { 1228 default: 1229 llvm_unreachable("Invalid LMUL."); 1230 case 8: 1231 return RISCVII::VLMUL::LMUL_F8; 1232 case 16: 1233 return RISCVII::VLMUL::LMUL_F4; 1234 case 32: 1235 return RISCVII::VLMUL::LMUL_F2; 1236 case 64: 1237 return RISCVII::VLMUL::LMUL_1; 1238 case 128: 1239 return RISCVII::VLMUL::LMUL_2; 1240 case 256: 1241 return RISCVII::VLMUL::LMUL_4; 1242 case 512: 1243 return RISCVII::VLMUL::LMUL_8; 1244 } 1245 } 1246 1247 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1248 switch (LMul) { 1249 default: 1250 llvm_unreachable("Invalid LMUL."); 1251 case RISCVII::VLMUL::LMUL_F8: 1252 case RISCVII::VLMUL::LMUL_F4: 1253 case RISCVII::VLMUL::LMUL_F2: 1254 case RISCVII::VLMUL::LMUL_1: 1255 return RISCV::VRRegClassID; 1256 case RISCVII::VLMUL::LMUL_2: 1257 return RISCV::VRM2RegClassID; 1258 case RISCVII::VLMUL::LMUL_4: 1259 return RISCV::VRM4RegClassID; 1260 case RISCVII::VLMUL::LMUL_8: 1261 return RISCV::VRM8RegClassID; 1262 } 1263 } 1264 1265 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1266 RISCVII::VLMUL LMUL = getLMUL(VT); 1267 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1268 LMUL == RISCVII::VLMUL::LMUL_F4 || 1269 LMUL == RISCVII::VLMUL::LMUL_F2 || 1270 LMUL == RISCVII::VLMUL::LMUL_1) { 1271 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1272 "Unexpected subreg numbering"); 1273 return RISCV::sub_vrm1_0 + Index; 1274 } 1275 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1276 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1277 "Unexpected subreg numbering"); 1278 return RISCV::sub_vrm2_0 + Index; 1279 } 1280 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1281 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1282 "Unexpected subreg numbering"); 1283 return RISCV::sub_vrm4_0 + Index; 1284 } 1285 llvm_unreachable("Invalid vector type."); 1286 } 1287 1288 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1289 if (VT.getVectorElementType() == MVT::i1) 1290 return RISCV::VRRegClassID; 1291 return getRegClassIDForLMUL(getLMUL(VT)); 1292 } 1293 1294 // Attempt to decompose a subvector insert/extract between VecVT and 1295 // SubVecVT via subregister indices. Returns the subregister index that 1296 // can perform the subvector insert/extract with the given element index, as 1297 // well as the index corresponding to any leftover subvectors that must be 1298 // further inserted/extracted within the register class for SubVecVT. 1299 std::pair<unsigned, unsigned> 1300 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1301 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1302 const RISCVRegisterInfo *TRI) { 1303 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1304 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1305 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1306 "Register classes not ordered"); 1307 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1308 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1309 // Try to compose a subregister index that takes us from the incoming 1310 // LMUL>1 register class down to the outgoing one. At each step we half 1311 // the LMUL: 1312 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1313 // Note that this is not guaranteed to find a subregister index, such as 1314 // when we are extracting from one VR type to another. 1315 unsigned SubRegIdx = RISCV::NoSubRegister; 1316 for (const unsigned RCID : 1317 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1318 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1319 VecVT = VecVT.getHalfNumVectorElementsVT(); 1320 bool IsHi = 1321 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1322 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1323 getSubregIndexByMVT(VecVT, IsHi)); 1324 if (IsHi) 1325 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1326 } 1327 return {SubRegIdx, InsertExtractIdx}; 1328 } 1329 1330 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1331 // stores for those types. 1332 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1333 return !Subtarget.useRVVForFixedLengthVectors() || 1334 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1335 } 1336 1337 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1338 if (ScalarTy->isPointerTy()) 1339 return true; 1340 1341 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1342 ScalarTy->isIntegerTy(32) || ScalarTy->isIntegerTy(64)) 1343 return true; 1344 1345 if (ScalarTy->isHalfTy()) 1346 return Subtarget.hasStdExtZfh(); 1347 if (ScalarTy->isFloatTy()) 1348 return Subtarget.hasStdExtF(); 1349 if (ScalarTy->isDoubleTy()) 1350 return Subtarget.hasStdExtD(); 1351 1352 return false; 1353 } 1354 1355 static bool useRVVForFixedLengthVectorVT(MVT VT, 1356 const RISCVSubtarget &Subtarget) { 1357 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1358 if (!Subtarget.useRVVForFixedLengthVectors()) 1359 return false; 1360 1361 // We only support a set of vector types with a consistent maximum fixed size 1362 // across all supported vector element types to avoid legalization issues. 1363 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1364 // fixed-length vector type we support is 1024 bytes. 1365 if (VT.getFixedSizeInBits() > 1024 * 8) 1366 return false; 1367 1368 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1369 1370 MVT EltVT = VT.getVectorElementType(); 1371 1372 // Don't use RVV for vectors we cannot scalarize if required. 1373 switch (EltVT.SimpleTy) { 1374 // i1 is supported but has different rules. 1375 default: 1376 return false; 1377 case MVT::i1: 1378 // Masks can only use a single register. 1379 if (VT.getVectorNumElements() > MinVLen) 1380 return false; 1381 MinVLen /= 8; 1382 break; 1383 case MVT::i8: 1384 case MVT::i16: 1385 case MVT::i32: 1386 case MVT::i64: 1387 break; 1388 case MVT::f16: 1389 if (!Subtarget.hasStdExtZfh()) 1390 return false; 1391 break; 1392 case MVT::f32: 1393 if (!Subtarget.hasStdExtF()) 1394 return false; 1395 break; 1396 case MVT::f64: 1397 if (!Subtarget.hasStdExtD()) 1398 return false; 1399 break; 1400 } 1401 1402 // Reject elements larger than ELEN. 1403 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1404 return false; 1405 1406 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1407 // Don't use RVV for types that don't fit. 1408 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1409 return false; 1410 1411 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1412 // the base fixed length RVV support in place. 1413 if (!VT.isPow2VectorType()) 1414 return false; 1415 1416 return true; 1417 } 1418 1419 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1420 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1421 } 1422 1423 // Return the largest legal scalable vector type that matches VT's element type. 1424 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1425 const RISCVSubtarget &Subtarget) { 1426 // This may be called before legal types are setup. 1427 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1428 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1429 "Expected legal fixed length vector!"); 1430 1431 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1432 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1433 1434 MVT EltVT = VT.getVectorElementType(); 1435 switch (EltVT.SimpleTy) { 1436 default: 1437 llvm_unreachable("unexpected element type for RVV container"); 1438 case MVT::i1: 1439 case MVT::i8: 1440 case MVT::i16: 1441 case MVT::i32: 1442 case MVT::i64: 1443 case MVT::f16: 1444 case MVT::f32: 1445 case MVT::f64: { 1446 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1447 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1448 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1449 unsigned NumElts = 1450 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1451 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1452 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1453 return MVT::getScalableVectorVT(EltVT, NumElts); 1454 } 1455 } 1456 } 1457 1458 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1459 const RISCVSubtarget &Subtarget) { 1460 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1461 Subtarget); 1462 } 1463 1464 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1465 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1466 } 1467 1468 // Grow V to consume an entire RVV register. 1469 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1470 const RISCVSubtarget &Subtarget) { 1471 assert(VT.isScalableVector() && 1472 "Expected to convert into a scalable vector!"); 1473 assert(V.getValueType().isFixedLengthVector() && 1474 "Expected a fixed length vector operand!"); 1475 SDLoc DL(V); 1476 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1477 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1478 } 1479 1480 // Shrink V so it's just big enough to maintain a VT's worth of data. 1481 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1482 const RISCVSubtarget &Subtarget) { 1483 assert(VT.isFixedLengthVector() && 1484 "Expected to convert into a fixed length vector!"); 1485 assert(V.getValueType().isScalableVector() && 1486 "Expected a scalable vector operand!"); 1487 SDLoc DL(V); 1488 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1489 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1490 } 1491 1492 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1493 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1494 // the vector type that it is contained in. 1495 static std::pair<SDValue, SDValue> 1496 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1497 const RISCVSubtarget &Subtarget) { 1498 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1499 MVT XLenVT = Subtarget.getXLenVT(); 1500 SDValue VL = VecVT.isFixedLengthVector() 1501 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1502 : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT); 1503 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1504 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1505 return {Mask, VL}; 1506 } 1507 1508 // As above but assuming the given type is a scalable vector type. 1509 static std::pair<SDValue, SDValue> 1510 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1511 const RISCVSubtarget &Subtarget) { 1512 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1513 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1514 } 1515 1516 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1517 // of either is (currently) supported. This can get us into an infinite loop 1518 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1519 // as a ..., etc. 1520 // Until either (or both) of these can reliably lower any node, reporting that 1521 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1522 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1523 // which is not desirable. 1524 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1525 EVT VT, unsigned DefinedValues) const { 1526 return false; 1527 } 1528 1529 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1530 // Only splats are currently supported. 1531 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1532 return true; 1533 1534 return false; 1535 } 1536 1537 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) { 1538 // RISCV FP-to-int conversions saturate to the destination register size, but 1539 // don't produce 0 for nan. We can use a conversion instruction and fix the 1540 // nan case with a compare and a select. 1541 SDValue Src = Op.getOperand(0); 1542 1543 EVT DstVT = Op.getValueType(); 1544 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1545 1546 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1547 unsigned Opc; 1548 if (SatVT == DstVT) 1549 Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ; 1550 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1551 Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 1552 else 1553 return SDValue(); 1554 // FIXME: Support other SatVTs by clamping before or after the conversion. 1555 1556 SDLoc DL(Op); 1557 SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src); 1558 1559 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1560 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1561 } 1562 1563 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1564 const RISCVSubtarget &Subtarget) { 1565 MVT VT = Op.getSimpleValueType(); 1566 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1567 1568 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1569 1570 SDLoc DL(Op); 1571 SDValue Mask, VL; 1572 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1573 1574 unsigned Opc = 1575 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1576 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1577 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1578 } 1579 1580 struct VIDSequence { 1581 int64_t StepNumerator; 1582 unsigned StepDenominator; 1583 int64_t Addend; 1584 }; 1585 1586 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1587 // to the (non-zero) step S and start value X. This can be then lowered as the 1588 // RVV sequence (VID * S) + X, for example. 1589 // The step S is represented as an integer numerator divided by a positive 1590 // denominator. Note that the implementation currently only identifies 1591 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1592 // cannot detect 2/3, for example. 1593 // Note that this method will also match potentially unappealing index 1594 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1595 // determine whether this is worth generating code for. 1596 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1597 unsigned NumElts = Op.getNumOperands(); 1598 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1599 if (!Op.getValueType().isInteger()) 1600 return None; 1601 1602 Optional<unsigned> SeqStepDenom; 1603 Optional<int64_t> SeqStepNum, SeqAddend; 1604 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1605 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1606 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1607 // Assume undef elements match the sequence; we just have to be careful 1608 // when interpolating across them. 1609 if (Op.getOperand(Idx).isUndef()) 1610 continue; 1611 // The BUILD_VECTOR must be all constants. 1612 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1613 return None; 1614 1615 uint64_t Val = Op.getConstantOperandVal(Idx) & 1616 maskTrailingOnes<uint64_t>(EltSizeInBits); 1617 1618 if (PrevElt) { 1619 // Calculate the step since the last non-undef element, and ensure 1620 // it's consistent across the entire sequence. 1621 unsigned IdxDiff = Idx - PrevElt->second; 1622 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1623 1624 // A zero-value value difference means that we're somewhere in the middle 1625 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1626 // step change before evaluating the sequence. 1627 if (ValDiff != 0) { 1628 int64_t Remainder = ValDiff % IdxDiff; 1629 // Normalize the step if it's greater than 1. 1630 if (Remainder != ValDiff) { 1631 // The difference must cleanly divide the element span. 1632 if (Remainder != 0) 1633 return None; 1634 ValDiff /= IdxDiff; 1635 IdxDiff = 1; 1636 } 1637 1638 if (!SeqStepNum) 1639 SeqStepNum = ValDiff; 1640 else if (ValDiff != SeqStepNum) 1641 return None; 1642 1643 if (!SeqStepDenom) 1644 SeqStepDenom = IdxDiff; 1645 else if (IdxDiff != *SeqStepDenom) 1646 return None; 1647 } 1648 } 1649 1650 // Record and/or check any addend. 1651 if (SeqStepNum && SeqStepDenom) { 1652 uint64_t ExpectedVal = 1653 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1654 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1655 if (!SeqAddend) 1656 SeqAddend = Addend; 1657 else if (SeqAddend != Addend) 1658 return None; 1659 } 1660 1661 // Record this non-undef element for later. 1662 if (!PrevElt || PrevElt->first != Val) 1663 PrevElt = std::make_pair(Val, Idx); 1664 } 1665 // We need to have logged both a step and an addend for this to count as 1666 // a legal index sequence. 1667 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1668 return None; 1669 1670 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1671 } 1672 1673 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1674 const RISCVSubtarget &Subtarget) { 1675 MVT VT = Op.getSimpleValueType(); 1676 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1677 1678 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1679 1680 SDLoc DL(Op); 1681 SDValue Mask, VL; 1682 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1683 1684 MVT XLenVT = Subtarget.getXLenVT(); 1685 unsigned NumElts = Op.getNumOperands(); 1686 1687 if (VT.getVectorElementType() == MVT::i1) { 1688 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1689 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1690 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1691 } 1692 1693 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1694 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1695 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1696 } 1697 1698 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1699 // scalar integer chunks whose bit-width depends on the number of mask 1700 // bits and XLEN. 1701 // First, determine the most appropriate scalar integer type to use. This 1702 // is at most XLenVT, but may be shrunk to a smaller vector element type 1703 // according to the size of the final vector - use i8 chunks rather than 1704 // XLenVT if we're producing a v8i1. This results in more consistent 1705 // codegen across RV32 and RV64. 1706 unsigned NumViaIntegerBits = 1707 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1708 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1709 // If we have to use more than one INSERT_VECTOR_ELT then this 1710 // optimization is likely to increase code size; avoid peforming it in 1711 // such a case. We can use a load from a constant pool in this case. 1712 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1713 return SDValue(); 1714 // Now we can create our integer vector type. Note that it may be larger 1715 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1716 MVT IntegerViaVecVT = 1717 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1718 divideCeil(NumElts, NumViaIntegerBits)); 1719 1720 uint64_t Bits = 0; 1721 unsigned BitPos = 0, IntegerEltIdx = 0; 1722 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1723 1724 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1725 // Once we accumulate enough bits to fill our scalar type, insert into 1726 // our vector and clear our accumulated data. 1727 if (I != 0 && I % NumViaIntegerBits == 0) { 1728 if (NumViaIntegerBits <= 32) 1729 Bits = SignExtend64(Bits, 32); 1730 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1731 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1732 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1733 Bits = 0; 1734 BitPos = 0; 1735 IntegerEltIdx++; 1736 } 1737 SDValue V = Op.getOperand(I); 1738 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1739 Bits |= ((uint64_t)BitValue << BitPos); 1740 } 1741 1742 // Insert the (remaining) scalar value into position in our integer 1743 // vector type. 1744 if (NumViaIntegerBits <= 32) 1745 Bits = SignExtend64(Bits, 32); 1746 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1747 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1748 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1749 1750 if (NumElts < NumViaIntegerBits) { 1751 // If we're producing a smaller vector than our minimum legal integer 1752 // type, bitcast to the equivalent (known-legal) mask type, and extract 1753 // our final mask. 1754 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1755 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1756 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1757 DAG.getConstant(0, DL, XLenVT)); 1758 } else { 1759 // Else we must have produced an integer type with the same size as the 1760 // mask type; bitcast for the final result. 1761 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1762 Vec = DAG.getBitcast(VT, Vec); 1763 } 1764 1765 return Vec; 1766 } 1767 1768 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 1769 // vector type, we have a legal equivalently-sized i8 type, so we can use 1770 // that. 1771 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 1772 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 1773 1774 SDValue WideVec; 1775 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1776 // For a splat, perform a scalar truncate before creating the wider 1777 // vector. 1778 assert(Splat.getValueType() == XLenVT && 1779 "Unexpected type for i1 splat value"); 1780 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 1781 DAG.getConstant(1, DL, XLenVT)); 1782 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 1783 } else { 1784 SmallVector<SDValue, 8> Ops(Op->op_values()); 1785 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 1786 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 1787 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 1788 } 1789 1790 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 1791 } 1792 1793 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1794 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 1795 : RISCVISD::VMV_V_X_VL; 1796 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 1797 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1798 } 1799 1800 // Try and match index sequences, which we can lower to the vid instruction 1801 // with optional modifications. An all-undef vector is matched by 1802 // getSplatValue, above. 1803 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 1804 int64_t StepNumerator = SimpleVID->StepNumerator; 1805 unsigned StepDenominator = SimpleVID->StepDenominator; 1806 int64_t Addend = SimpleVID->Addend; 1807 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 1808 // threshold since it's the immediate value many RVV instructions accept. 1809 if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) && 1810 isInt<5>(Addend)) { 1811 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 1812 // Convert right out of the scalable type so we can use standard ISD 1813 // nodes for the rest of the computation. If we used scalable types with 1814 // these, we'd lose the fixed-length vector info and generate worse 1815 // vsetvli code. 1816 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 1817 assert(StepNumerator != 0 && "Invalid step"); 1818 bool Negate = false; 1819 if (StepNumerator != 1) { 1820 int64_t SplatStepVal = StepNumerator; 1821 unsigned Opcode = ISD::MUL; 1822 if (isPowerOf2_64(std::abs(StepNumerator))) { 1823 Negate = StepNumerator < 0; 1824 Opcode = ISD::SHL; 1825 SplatStepVal = Log2_64(std::abs(StepNumerator)); 1826 } 1827 SDValue SplatStep = DAG.getSplatVector( 1828 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 1829 VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep); 1830 } 1831 if (StepDenominator != 1) { 1832 SDValue SplatStep = DAG.getSplatVector( 1833 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 1834 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 1835 } 1836 if (Addend != 0 || Negate) { 1837 SDValue SplatAddend = 1838 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 1839 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 1840 } 1841 return VID; 1842 } 1843 } 1844 1845 // Attempt to detect "hidden" splats, which only reveal themselves as splats 1846 // when re-interpreted as a vector with a larger element type. For example, 1847 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 1848 // could be instead splat as 1849 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 1850 // TODO: This optimization could also work on non-constant splats, but it 1851 // would require bit-manipulation instructions to construct the splat value. 1852 SmallVector<SDValue> Sequence; 1853 unsigned EltBitSize = VT.getScalarSizeInBits(); 1854 const auto *BV = cast<BuildVectorSDNode>(Op); 1855 if (VT.isInteger() && EltBitSize < 64 && 1856 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 1857 BV->getRepeatedSequence(Sequence) && 1858 (Sequence.size() * EltBitSize) <= 64) { 1859 unsigned SeqLen = Sequence.size(); 1860 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 1861 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 1862 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 1863 ViaIntVT == MVT::i64) && 1864 "Unexpected sequence type"); 1865 1866 unsigned EltIdx = 0; 1867 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 1868 uint64_t SplatValue = 0; 1869 // Construct the amalgamated value which can be splatted as this larger 1870 // vector type. 1871 for (const auto &SeqV : Sequence) { 1872 if (!SeqV.isUndef()) 1873 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 1874 << (EltIdx * EltBitSize)); 1875 EltIdx++; 1876 } 1877 1878 // On RV64, sign-extend from 32 to 64 bits where possible in order to 1879 // achieve better constant materializion. 1880 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 1881 SplatValue = SignExtend64(SplatValue, 32); 1882 1883 // Since we can't introduce illegal i64 types at this stage, we can only 1884 // perform an i64 splat on RV32 if it is its own sign-extended value. That 1885 // way we can use RVV instructions to splat. 1886 assert((ViaIntVT.bitsLE(XLenVT) || 1887 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 1888 "Unexpected bitcast sequence"); 1889 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 1890 SDValue ViaVL = 1891 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 1892 MVT ViaContainerVT = 1893 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 1894 SDValue Splat = 1895 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 1896 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 1897 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 1898 return DAG.getBitcast(VT, Splat); 1899 } 1900 } 1901 1902 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 1903 // which constitute a large proportion of the elements. In such cases we can 1904 // splat a vector with the dominant element and make up the shortfall with 1905 // INSERT_VECTOR_ELTs. 1906 // Note that this includes vectors of 2 elements by association. The 1907 // upper-most element is the "dominant" one, allowing us to use a splat to 1908 // "insert" the upper element, and an insert of the lower element at position 1909 // 0, which improves codegen. 1910 SDValue DominantValue; 1911 unsigned MostCommonCount = 0; 1912 DenseMap<SDValue, unsigned> ValueCounts; 1913 unsigned NumUndefElts = 1914 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 1915 1916 // Track the number of scalar loads we know we'd be inserting, estimated as 1917 // any non-zero floating-point constant. Other kinds of element are either 1918 // already in registers or are materialized on demand. The threshold at which 1919 // a vector load is more desirable than several scalar materializion and 1920 // vector-insertion instructions is not known. 1921 unsigned NumScalarLoads = 0; 1922 1923 for (SDValue V : Op->op_values()) { 1924 if (V.isUndef()) 1925 continue; 1926 1927 ValueCounts.insert(std::make_pair(V, 0)); 1928 unsigned &Count = ValueCounts[V]; 1929 1930 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 1931 NumScalarLoads += !CFP->isExactlyValue(+0.0); 1932 1933 // Is this value dominant? In case of a tie, prefer the highest element as 1934 // it's cheaper to insert near the beginning of a vector than it is at the 1935 // end. 1936 if (++Count >= MostCommonCount) { 1937 DominantValue = V; 1938 MostCommonCount = Count; 1939 } 1940 } 1941 1942 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 1943 unsigned NumDefElts = NumElts - NumUndefElts; 1944 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 1945 1946 // Don't perform this optimization when optimizing for size, since 1947 // materializing elements and inserting them tends to cause code bloat. 1948 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 1949 ((MostCommonCount > DominantValueCountThreshold) || 1950 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 1951 // Start by splatting the most common element. 1952 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 1953 1954 DenseSet<SDValue> Processed{DominantValue}; 1955 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 1956 for (const auto &OpIdx : enumerate(Op->ops())) { 1957 const SDValue &V = OpIdx.value(); 1958 if (V.isUndef() || !Processed.insert(V).second) 1959 continue; 1960 if (ValueCounts[V] == 1) { 1961 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 1962 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 1963 } else { 1964 // Blend in all instances of this value using a VSELECT, using a 1965 // mask where each bit signals whether that element is the one 1966 // we're after. 1967 SmallVector<SDValue> Ops; 1968 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 1969 return DAG.getConstant(V == V1, DL, XLenVT); 1970 }); 1971 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 1972 DAG.getBuildVector(SelMaskTy, DL, Ops), 1973 DAG.getSplatBuildVector(VT, DL, V), Vec); 1974 } 1975 } 1976 1977 return Vec; 1978 } 1979 1980 return SDValue(); 1981 } 1982 1983 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 1984 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 1985 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 1986 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 1987 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 1988 // If Hi constant is all the same sign bit as Lo, lower this as a custom 1989 // node in order to try and match RVV vector/scalar instructions. 1990 if ((LoC >> 31) == HiC) 1991 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 1992 } 1993 1994 // Fall back to a stack store and stride x0 vector load. 1995 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 1996 } 1997 1998 // Called by type legalization to handle splat of i64 on RV32. 1999 // FIXME: We can optimize this when the type has sign or zero bits in one 2000 // of the halves. 2001 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2002 SDValue VL, SelectionDAG &DAG) { 2003 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2004 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2005 DAG.getConstant(0, DL, MVT::i32)); 2006 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2007 DAG.getConstant(1, DL, MVT::i32)); 2008 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2009 } 2010 2011 // This function lowers a splat of a scalar operand Splat with the vector 2012 // length VL. It ensures the final sequence is type legal, which is useful when 2013 // lowering a splat after type legalization. 2014 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2015 SelectionDAG &DAG, 2016 const RISCVSubtarget &Subtarget) { 2017 if (VT.isFloatingPoint()) 2018 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2019 2020 MVT XLenVT = Subtarget.getXLenVT(); 2021 2022 // Simplest case is that the operand needs to be promoted to XLenVT. 2023 if (Scalar.getValueType().bitsLE(XLenVT)) { 2024 // If the operand is a constant, sign extend to increase our chances 2025 // of being able to use a .vi instruction. ANY_EXTEND would become a 2026 // a zero extend and the simm5 check in isel would fail. 2027 // FIXME: Should we ignore the upper bits in isel instead? 2028 unsigned ExtOpc = 2029 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2030 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2031 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2032 } 2033 2034 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2035 "Unexpected scalar for splat lowering!"); 2036 2037 // Otherwise use the more complicated splatting algorithm. 2038 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2039 } 2040 2041 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2042 const RISCVSubtarget &Subtarget) { 2043 SDValue V1 = Op.getOperand(0); 2044 SDValue V2 = Op.getOperand(1); 2045 SDLoc DL(Op); 2046 MVT XLenVT = Subtarget.getXLenVT(); 2047 MVT VT = Op.getSimpleValueType(); 2048 unsigned NumElts = VT.getVectorNumElements(); 2049 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2050 2051 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2052 2053 SDValue TrueMask, VL; 2054 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2055 2056 if (SVN->isSplat()) { 2057 const int Lane = SVN->getSplatIndex(); 2058 if (Lane >= 0) { 2059 MVT SVT = VT.getVectorElementType(); 2060 2061 // Turn splatted vector load into a strided load with an X0 stride. 2062 SDValue V = V1; 2063 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2064 // with undef. 2065 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2066 int Offset = Lane; 2067 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2068 int OpElements = 2069 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2070 V = V.getOperand(Offset / OpElements); 2071 Offset %= OpElements; 2072 } 2073 2074 // We need to ensure the load isn't atomic or volatile. 2075 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2076 auto *Ld = cast<LoadSDNode>(V); 2077 Offset *= SVT.getStoreSize(); 2078 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2079 TypeSize::Fixed(Offset), DL); 2080 2081 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2082 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2083 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2084 SDValue IntID = 2085 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2086 SDValue Ops[] = {Ld->getChain(), IntID, NewAddr, 2087 DAG.getRegister(RISCV::X0, XLenVT), VL}; 2088 SDValue NewLoad = DAG.getMemIntrinsicNode( 2089 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2090 DAG.getMachineFunction().getMachineMemOperand( 2091 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2092 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2093 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2094 } 2095 2096 // Otherwise use a scalar load and splat. This will give the best 2097 // opportunity to fold a splat into the operation. ISel can turn it into 2098 // the x0 strided load if we aren't able to fold away the select. 2099 if (SVT.isFloatingPoint()) 2100 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2101 Ld->getPointerInfo().getWithOffset(Offset), 2102 Ld->getOriginalAlign(), 2103 Ld->getMemOperand()->getFlags()); 2104 else 2105 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2106 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2107 Ld->getOriginalAlign(), 2108 Ld->getMemOperand()->getFlags()); 2109 DAG.makeEquivalentMemoryOrdering(Ld, V); 2110 2111 unsigned Opc = 2112 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2113 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2114 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2115 } 2116 2117 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2118 assert(Lane < (int)NumElts && "Unexpected lane!"); 2119 SDValue Gather = 2120 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2121 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2122 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2123 } 2124 } 2125 2126 // Detect shuffles which can be re-expressed as vector selects; these are 2127 // shuffles in which each element in the destination is taken from an element 2128 // at the corresponding index in either source vectors. 2129 bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) { 2130 int MaskIndex = MaskIdx.value(); 2131 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2132 }); 2133 2134 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2135 2136 SmallVector<SDValue> MaskVals; 2137 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2138 // merged with a second vrgather. 2139 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2140 2141 // By default we preserve the original operand order, and use a mask to 2142 // select LHS as true and RHS as false. However, since RVV vector selects may 2143 // feature splats but only on the LHS, we may choose to invert our mask and 2144 // instead select between RHS and LHS. 2145 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2146 bool InvertMask = IsSelect == SwapOps; 2147 2148 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2149 // half. 2150 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2151 2152 // Now construct the mask that will be used by the vselect or blended 2153 // vrgather operation. For vrgathers, construct the appropriate indices into 2154 // each vector. 2155 for (int MaskIndex : SVN->getMask()) { 2156 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2157 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2158 if (!IsSelect) { 2159 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2160 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2161 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2162 : DAG.getUNDEF(XLenVT)); 2163 GatherIndicesRHS.push_back( 2164 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2165 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2166 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2167 ++LHSIndexCounts[MaskIndex]; 2168 if (!IsLHSOrUndefIndex) 2169 ++RHSIndexCounts[MaskIndex - NumElts]; 2170 } 2171 } 2172 2173 if (SwapOps) { 2174 std::swap(V1, V2); 2175 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2176 } 2177 2178 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2179 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2180 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2181 2182 if (IsSelect) 2183 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2184 2185 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2186 // On such a large vector we're unable to use i8 as the index type. 2187 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2188 // may involve vector splitting if we're already at LMUL=8, or our 2189 // user-supplied maximum fixed-length LMUL. 2190 return SDValue(); 2191 } 2192 2193 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2194 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2195 MVT IndexVT = VT.changeTypeToInteger(); 2196 // Since we can't introduce illegal index types at this stage, use i16 and 2197 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2198 // than XLenVT. 2199 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2200 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2201 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2202 } 2203 2204 MVT IndexContainerVT = 2205 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2206 2207 SDValue Gather; 2208 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2209 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2210 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2211 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2212 } else { 2213 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2214 // If only one index is used, we can use a "splat" vrgather. 2215 // TODO: We can splat the most-common index and fix-up any stragglers, if 2216 // that's beneficial. 2217 if (LHSIndexCounts.size() == 1) { 2218 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2219 Gather = 2220 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2221 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2222 } else { 2223 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2224 LHSIndices = 2225 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2226 2227 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2228 TrueMask, VL); 2229 } 2230 } 2231 2232 // If a second vector operand is used by this shuffle, blend it in with an 2233 // additional vrgather. 2234 if (!V2.isUndef()) { 2235 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2236 // If only one index is used, we can use a "splat" vrgather. 2237 // TODO: We can splat the most-common index and fix-up any stragglers, if 2238 // that's beneficial. 2239 if (RHSIndexCounts.size() == 1) { 2240 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2241 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2242 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2243 } else { 2244 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2245 RHSIndices = 2246 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2247 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2248 VL); 2249 } 2250 2251 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2252 SelectMask = 2253 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2254 2255 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2256 Gather, VL); 2257 } 2258 2259 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2260 } 2261 2262 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2263 SDLoc DL, SelectionDAG &DAG, 2264 const RISCVSubtarget &Subtarget) { 2265 if (VT.isScalableVector()) 2266 return DAG.getFPExtendOrRound(Op, DL, VT); 2267 assert(VT.isFixedLengthVector() && 2268 "Unexpected value type for RVV FP extend/round lowering"); 2269 SDValue Mask, VL; 2270 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2271 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2272 ? RISCVISD::FP_EXTEND_VL 2273 : RISCVISD::FP_ROUND_VL; 2274 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2275 } 2276 2277 // While RVV has alignment restrictions, we should always be able to load as a 2278 // legal equivalently-sized byte-typed vector instead. This method is 2279 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2280 // the load is already correctly-aligned, it returns SDValue(). 2281 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2282 SelectionDAG &DAG) const { 2283 auto *Load = cast<LoadSDNode>(Op); 2284 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2285 2286 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2287 Load->getMemoryVT(), 2288 *Load->getMemOperand())) 2289 return SDValue(); 2290 2291 SDLoc DL(Op); 2292 MVT VT = Op.getSimpleValueType(); 2293 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2294 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2295 "Unexpected unaligned RVV load type"); 2296 MVT NewVT = 2297 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2298 assert(NewVT.isValid() && 2299 "Expecting equally-sized RVV vector types to be legal"); 2300 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2301 Load->getPointerInfo(), Load->getOriginalAlign(), 2302 Load->getMemOperand()->getFlags()); 2303 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2304 } 2305 2306 // While RVV has alignment restrictions, we should always be able to store as a 2307 // legal equivalently-sized byte-typed vector instead. This method is 2308 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2309 // returns SDValue() if the store is already correctly aligned. 2310 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2311 SelectionDAG &DAG) const { 2312 auto *Store = cast<StoreSDNode>(Op); 2313 assert(Store && Store->getValue().getValueType().isVector() && 2314 "Expected vector store"); 2315 2316 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2317 Store->getMemoryVT(), 2318 *Store->getMemOperand())) 2319 return SDValue(); 2320 2321 SDLoc DL(Op); 2322 SDValue StoredVal = Store->getValue(); 2323 MVT VT = StoredVal.getSimpleValueType(); 2324 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2325 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2326 "Unexpected unaligned RVV store type"); 2327 MVT NewVT = 2328 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2329 assert(NewVT.isValid() && 2330 "Expecting equally-sized RVV vector types to be legal"); 2331 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2332 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2333 Store->getPointerInfo(), Store->getOriginalAlign(), 2334 Store->getMemOperand()->getFlags()); 2335 } 2336 2337 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2338 SelectionDAG &DAG) const { 2339 switch (Op.getOpcode()) { 2340 default: 2341 report_fatal_error("unimplemented operand"); 2342 case ISD::GlobalAddress: 2343 return lowerGlobalAddress(Op, DAG); 2344 case ISD::BlockAddress: 2345 return lowerBlockAddress(Op, DAG); 2346 case ISD::ConstantPool: 2347 return lowerConstantPool(Op, DAG); 2348 case ISD::JumpTable: 2349 return lowerJumpTable(Op, DAG); 2350 case ISD::GlobalTLSAddress: 2351 return lowerGlobalTLSAddress(Op, DAG); 2352 case ISD::SELECT: 2353 return lowerSELECT(Op, DAG); 2354 case ISD::BRCOND: 2355 return lowerBRCOND(Op, DAG); 2356 case ISD::VASTART: 2357 return lowerVASTART(Op, DAG); 2358 case ISD::FRAMEADDR: 2359 return lowerFRAMEADDR(Op, DAG); 2360 case ISD::RETURNADDR: 2361 return lowerRETURNADDR(Op, DAG); 2362 case ISD::SHL_PARTS: 2363 return lowerShiftLeftParts(Op, DAG); 2364 case ISD::SRA_PARTS: 2365 return lowerShiftRightParts(Op, DAG, true); 2366 case ISD::SRL_PARTS: 2367 return lowerShiftRightParts(Op, DAG, false); 2368 case ISD::BITCAST: { 2369 SDLoc DL(Op); 2370 EVT VT = Op.getValueType(); 2371 SDValue Op0 = Op.getOperand(0); 2372 EVT Op0VT = Op0.getValueType(); 2373 MVT XLenVT = Subtarget.getXLenVT(); 2374 if (VT.isFixedLengthVector()) { 2375 // We can handle fixed length vector bitcasts with a simple replacement 2376 // in isel. 2377 if (Op0VT.isFixedLengthVector()) 2378 return Op; 2379 // When bitcasting from scalar to fixed-length vector, insert the scalar 2380 // into a one-element vector of the result type, and perform a vector 2381 // bitcast. 2382 if (!Op0VT.isVector()) { 2383 auto BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2384 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2385 DAG.getUNDEF(BVT), Op0, 2386 DAG.getConstant(0, DL, XLenVT))); 2387 } 2388 return SDValue(); 2389 } 2390 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2391 // thus: bitcast the vector to a one-element vector type whose element type 2392 // is the same as the result type, and extract the first element. 2393 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2394 LLVMContext &Context = *DAG.getContext(); 2395 SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0); 2396 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2397 DAG.getConstant(0, DL, XLenVT)); 2398 } 2399 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2400 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2401 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2402 return FPConv; 2403 } 2404 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2405 Subtarget.hasStdExtF()) { 2406 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2407 SDValue FPConv = 2408 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2409 return FPConv; 2410 } 2411 return SDValue(); 2412 } 2413 case ISD::INTRINSIC_WO_CHAIN: 2414 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2415 case ISD::INTRINSIC_W_CHAIN: 2416 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2417 case ISD::INTRINSIC_VOID: 2418 return LowerINTRINSIC_VOID(Op, DAG); 2419 case ISD::BSWAP: 2420 case ISD::BITREVERSE: { 2421 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2422 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 2423 MVT VT = Op.getSimpleValueType(); 2424 SDLoc DL(Op); 2425 // Start with the maximum immediate value which is the bitwidth - 1. 2426 unsigned Imm = VT.getSizeInBits() - 1; 2427 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2428 if (Op.getOpcode() == ISD::BSWAP) 2429 Imm &= ~0x7U; 2430 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2431 DAG.getConstant(Imm, DL, VT)); 2432 } 2433 case ISD::FSHL: 2434 case ISD::FSHR: { 2435 MVT VT = Op.getSimpleValueType(); 2436 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2437 SDLoc DL(Op); 2438 if (Op.getOperand(2).getOpcode() == ISD::Constant) 2439 return Op; 2440 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2441 // use log(XLen) bits. Mask the shift amount accordingly. 2442 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2443 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2444 DAG.getConstant(ShAmtWidth, DL, VT)); 2445 unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR; 2446 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt); 2447 } 2448 case ISD::TRUNCATE: { 2449 SDLoc DL(Op); 2450 MVT VT = Op.getSimpleValueType(); 2451 // Only custom-lower vector truncates 2452 if (!VT.isVector()) 2453 return Op; 2454 2455 // Truncates to mask types are handled differently 2456 if (VT.getVectorElementType() == MVT::i1) 2457 return lowerVectorMaskTrunc(Op, DAG); 2458 2459 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 2460 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 2461 // truncate by one power of two at a time. 2462 MVT DstEltVT = VT.getVectorElementType(); 2463 2464 SDValue Src = Op.getOperand(0); 2465 MVT SrcVT = Src.getSimpleValueType(); 2466 MVT SrcEltVT = SrcVT.getVectorElementType(); 2467 2468 assert(DstEltVT.bitsLT(SrcEltVT) && 2469 isPowerOf2_64(DstEltVT.getSizeInBits()) && 2470 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 2471 "Unexpected vector truncate lowering"); 2472 2473 MVT ContainerVT = SrcVT; 2474 if (SrcVT.isFixedLengthVector()) { 2475 ContainerVT = getContainerForFixedLengthVector(SrcVT); 2476 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 2477 } 2478 2479 SDValue Result = Src; 2480 SDValue Mask, VL; 2481 std::tie(Mask, VL) = 2482 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 2483 LLVMContext &Context = *DAG.getContext(); 2484 const ElementCount Count = ContainerVT.getVectorElementCount(); 2485 do { 2486 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 2487 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 2488 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 2489 Mask, VL); 2490 } while (SrcEltVT != DstEltVT); 2491 2492 if (SrcVT.isFixedLengthVector()) 2493 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 2494 2495 return Result; 2496 } 2497 case ISD::ANY_EXTEND: 2498 case ISD::ZERO_EXTEND: 2499 if (Op.getOperand(0).getValueType().isVector() && 2500 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2501 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 2502 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 2503 case ISD::SIGN_EXTEND: 2504 if (Op.getOperand(0).getValueType().isVector() && 2505 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2506 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 2507 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 2508 case ISD::SPLAT_VECTOR_PARTS: 2509 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 2510 case ISD::INSERT_VECTOR_ELT: 2511 return lowerINSERT_VECTOR_ELT(Op, DAG); 2512 case ISD::EXTRACT_VECTOR_ELT: 2513 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 2514 case ISD::VSCALE: { 2515 MVT VT = Op.getSimpleValueType(); 2516 SDLoc DL(Op); 2517 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 2518 // We define our scalable vector types for lmul=1 to use a 64 bit known 2519 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 2520 // vscale as VLENB / 8. 2521 assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!"); 2522 if (isa<ConstantSDNode>(Op.getOperand(0))) { 2523 // We assume VLENB is a multiple of 8. We manually choose the best shift 2524 // here because SimplifyDemandedBits isn't always able to simplify it. 2525 uint64_t Val = Op.getConstantOperandVal(0); 2526 if (isPowerOf2_64(Val)) { 2527 uint64_t Log2 = Log2_64(Val); 2528 if (Log2 < 3) 2529 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 2530 DAG.getConstant(3 - Log2, DL, VT)); 2531 if (Log2 > 3) 2532 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 2533 DAG.getConstant(Log2 - 3, DL, VT)); 2534 return VLENB; 2535 } 2536 // If the multiplier is a multiple of 8, scale it down to avoid needing 2537 // to shift the VLENB value. 2538 if ((Val % 8) == 0) 2539 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 2540 DAG.getConstant(Val / 8, DL, VT)); 2541 } 2542 2543 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 2544 DAG.getConstant(3, DL, VT)); 2545 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 2546 } 2547 case ISD::FP_EXTEND: { 2548 // RVV can only do fp_extend to types double the size as the source. We 2549 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 2550 // via f32. 2551 SDLoc DL(Op); 2552 MVT VT = Op.getSimpleValueType(); 2553 SDValue Src = Op.getOperand(0); 2554 MVT SrcVT = Src.getSimpleValueType(); 2555 2556 // Prepare any fixed-length vector operands. 2557 MVT ContainerVT = VT; 2558 if (SrcVT.isFixedLengthVector()) { 2559 ContainerVT = getContainerForFixedLengthVector(VT); 2560 MVT SrcContainerVT = 2561 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 2562 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2563 } 2564 2565 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 2566 SrcVT.getVectorElementType() != MVT::f16) { 2567 // For scalable vectors, we only need to close the gap between 2568 // vXf16->vXf64. 2569 if (!VT.isFixedLengthVector()) 2570 return Op; 2571 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 2572 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2573 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2574 } 2575 2576 MVT InterVT = VT.changeVectorElementType(MVT::f32); 2577 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 2578 SDValue IntermediateExtend = getRVVFPExtendOrRound( 2579 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 2580 2581 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 2582 DL, DAG, Subtarget); 2583 if (VT.isFixedLengthVector()) 2584 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 2585 return Extend; 2586 } 2587 case ISD::FP_ROUND: { 2588 // RVV can only do fp_round to types half the size as the source. We 2589 // custom-lower f64->f16 rounds via RVV's round-to-odd float 2590 // conversion instruction. 2591 SDLoc DL(Op); 2592 MVT VT = Op.getSimpleValueType(); 2593 SDValue Src = Op.getOperand(0); 2594 MVT SrcVT = Src.getSimpleValueType(); 2595 2596 // Prepare any fixed-length vector operands. 2597 MVT ContainerVT = VT; 2598 if (VT.isFixedLengthVector()) { 2599 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2600 ContainerVT = 2601 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2602 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2603 } 2604 2605 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 2606 SrcVT.getVectorElementType() != MVT::f64) { 2607 // For scalable vectors, we only need to close the gap between 2608 // vXf64<->vXf16. 2609 if (!VT.isFixedLengthVector()) 2610 return Op; 2611 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 2612 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2613 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2614 } 2615 2616 SDValue Mask, VL; 2617 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2618 2619 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 2620 SDValue IntermediateRound = 2621 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 2622 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 2623 DL, DAG, Subtarget); 2624 2625 if (VT.isFixedLengthVector()) 2626 return convertFromScalableVector(VT, Round, DAG, Subtarget); 2627 return Round; 2628 } 2629 case ISD::FP_TO_SINT: 2630 case ISD::FP_TO_UINT: 2631 case ISD::SINT_TO_FP: 2632 case ISD::UINT_TO_FP: { 2633 // RVV can only do fp<->int conversions to types half/double the size as 2634 // the source. We custom-lower any conversions that do two hops into 2635 // sequences. 2636 MVT VT = Op.getSimpleValueType(); 2637 if (!VT.isVector()) 2638 return Op; 2639 SDLoc DL(Op); 2640 SDValue Src = Op.getOperand(0); 2641 MVT EltVT = VT.getVectorElementType(); 2642 MVT SrcVT = Src.getSimpleValueType(); 2643 MVT SrcEltVT = SrcVT.getVectorElementType(); 2644 unsigned EltSize = EltVT.getSizeInBits(); 2645 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 2646 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 2647 "Unexpected vector element types"); 2648 2649 bool IsInt2FP = SrcEltVT.isInteger(); 2650 // Widening conversions 2651 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 2652 if (IsInt2FP) { 2653 // Do a regular integer sign/zero extension then convert to float. 2654 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 2655 VT.getVectorElementCount()); 2656 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 2657 ? ISD::ZERO_EXTEND 2658 : ISD::SIGN_EXTEND; 2659 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 2660 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 2661 } 2662 // FP2Int 2663 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 2664 // Do one doubling fp_extend then complete the operation by converting 2665 // to int. 2666 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2667 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 2668 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 2669 } 2670 2671 // Narrowing conversions 2672 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 2673 if (IsInt2FP) { 2674 // One narrowing int_to_fp, then an fp_round. 2675 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 2676 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2677 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 2678 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 2679 } 2680 // FP2Int 2681 // One narrowing fp_to_int, then truncate the integer. If the float isn't 2682 // representable by the integer, the result is poison. 2683 MVT IVecVT = 2684 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 2685 VT.getVectorElementCount()); 2686 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 2687 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 2688 } 2689 2690 // Scalable vectors can exit here. Patterns will handle equally-sized 2691 // conversions halving/doubling ones. 2692 if (!VT.isFixedLengthVector()) 2693 return Op; 2694 2695 // For fixed-length vectors we lower to a custom "VL" node. 2696 unsigned RVVOpc = 0; 2697 switch (Op.getOpcode()) { 2698 default: 2699 llvm_unreachable("Impossible opcode"); 2700 case ISD::FP_TO_SINT: 2701 RVVOpc = RISCVISD::FP_TO_SINT_VL; 2702 break; 2703 case ISD::FP_TO_UINT: 2704 RVVOpc = RISCVISD::FP_TO_UINT_VL; 2705 break; 2706 case ISD::SINT_TO_FP: 2707 RVVOpc = RISCVISD::SINT_TO_FP_VL; 2708 break; 2709 case ISD::UINT_TO_FP: 2710 RVVOpc = RISCVISD::UINT_TO_FP_VL; 2711 break; 2712 } 2713 2714 MVT ContainerVT, SrcContainerVT; 2715 // Derive the reference container type from the larger vector type. 2716 if (SrcEltSize > EltSize) { 2717 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2718 ContainerVT = 2719 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2720 } else { 2721 ContainerVT = getContainerForFixedLengthVector(VT); 2722 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 2723 } 2724 2725 SDValue Mask, VL; 2726 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2727 2728 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2729 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 2730 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2731 } 2732 case ISD::FP_TO_SINT_SAT: 2733 case ISD::FP_TO_UINT_SAT: 2734 return lowerFP_TO_INT_SAT(Op, DAG); 2735 case ISD::VECREDUCE_ADD: 2736 case ISD::VECREDUCE_UMAX: 2737 case ISD::VECREDUCE_SMAX: 2738 case ISD::VECREDUCE_UMIN: 2739 case ISD::VECREDUCE_SMIN: 2740 return lowerVECREDUCE(Op, DAG); 2741 case ISD::VECREDUCE_AND: 2742 case ISD::VECREDUCE_OR: 2743 case ISD::VECREDUCE_XOR: 2744 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2745 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 2746 return lowerVECREDUCE(Op, DAG); 2747 case ISD::VECREDUCE_FADD: 2748 case ISD::VECREDUCE_SEQ_FADD: 2749 case ISD::VECREDUCE_FMIN: 2750 case ISD::VECREDUCE_FMAX: 2751 return lowerFPVECREDUCE(Op, DAG); 2752 case ISD::VP_REDUCE_ADD: 2753 case ISD::VP_REDUCE_UMAX: 2754 case ISD::VP_REDUCE_SMAX: 2755 case ISD::VP_REDUCE_UMIN: 2756 case ISD::VP_REDUCE_SMIN: 2757 case ISD::VP_REDUCE_FADD: 2758 case ISD::VP_REDUCE_SEQ_FADD: 2759 case ISD::VP_REDUCE_FMIN: 2760 case ISD::VP_REDUCE_FMAX: 2761 return lowerVPREDUCE(Op, DAG); 2762 case ISD::VP_REDUCE_AND: 2763 case ISD::VP_REDUCE_OR: 2764 case ISD::VP_REDUCE_XOR: 2765 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 2766 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 2767 return lowerVPREDUCE(Op, DAG); 2768 case ISD::INSERT_SUBVECTOR: 2769 return lowerINSERT_SUBVECTOR(Op, DAG); 2770 case ISD::EXTRACT_SUBVECTOR: 2771 return lowerEXTRACT_SUBVECTOR(Op, DAG); 2772 case ISD::STEP_VECTOR: 2773 return lowerSTEP_VECTOR(Op, DAG); 2774 case ISD::VECTOR_REVERSE: 2775 return lowerVECTOR_REVERSE(Op, DAG); 2776 case ISD::BUILD_VECTOR: 2777 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 2778 case ISD::SPLAT_VECTOR: 2779 if (Op.getValueType().getVectorElementType() == MVT::i1) 2780 return lowerVectorMaskSplat(Op, DAG); 2781 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 2782 case ISD::VECTOR_SHUFFLE: 2783 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 2784 case ISD::CONCAT_VECTORS: { 2785 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 2786 // better than going through the stack, as the default expansion does. 2787 SDLoc DL(Op); 2788 MVT VT = Op.getSimpleValueType(); 2789 unsigned NumOpElts = 2790 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 2791 SDValue Vec = DAG.getUNDEF(VT); 2792 for (const auto &OpIdx : enumerate(Op->ops())) 2793 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(), 2794 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 2795 return Vec; 2796 } 2797 case ISD::LOAD: 2798 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 2799 return V; 2800 if (Op.getValueType().isFixedLengthVector()) 2801 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 2802 return Op; 2803 case ISD::STORE: 2804 if (auto V = expandUnalignedRVVStore(Op, DAG)) 2805 return V; 2806 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 2807 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 2808 return Op; 2809 case ISD::MLOAD: 2810 case ISD::VP_LOAD: 2811 return lowerMaskedLoad(Op, DAG); 2812 case ISD::MSTORE: 2813 case ISD::VP_STORE: 2814 return lowerMaskedStore(Op, DAG); 2815 case ISD::SETCC: 2816 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 2817 case ISD::ADD: 2818 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 2819 case ISD::SUB: 2820 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 2821 case ISD::MUL: 2822 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 2823 case ISD::MULHS: 2824 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 2825 case ISD::MULHU: 2826 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 2827 case ISD::AND: 2828 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 2829 RISCVISD::AND_VL); 2830 case ISD::OR: 2831 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 2832 RISCVISD::OR_VL); 2833 case ISD::XOR: 2834 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 2835 RISCVISD::XOR_VL); 2836 case ISD::SDIV: 2837 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 2838 case ISD::SREM: 2839 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 2840 case ISD::UDIV: 2841 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 2842 case ISD::UREM: 2843 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 2844 case ISD::SHL: 2845 case ISD::SRA: 2846 case ISD::SRL: 2847 if (Op.getSimpleValueType().isFixedLengthVector()) 2848 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 2849 // This can be called for an i32 shift amount that needs to be promoted. 2850 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 2851 "Unexpected custom legalisation"); 2852 return SDValue(); 2853 case ISD::SADDSAT: 2854 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 2855 case ISD::UADDSAT: 2856 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 2857 case ISD::SSUBSAT: 2858 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 2859 case ISD::USUBSAT: 2860 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 2861 case ISD::FADD: 2862 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 2863 case ISD::FSUB: 2864 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 2865 case ISD::FMUL: 2866 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 2867 case ISD::FDIV: 2868 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 2869 case ISD::FNEG: 2870 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 2871 case ISD::FABS: 2872 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 2873 case ISD::FSQRT: 2874 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 2875 case ISD::FMA: 2876 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 2877 case ISD::SMIN: 2878 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 2879 case ISD::SMAX: 2880 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 2881 case ISD::UMIN: 2882 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 2883 case ISD::UMAX: 2884 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 2885 case ISD::FMINNUM: 2886 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 2887 case ISD::FMAXNUM: 2888 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 2889 case ISD::ABS: 2890 return lowerABS(Op, DAG); 2891 case ISD::VSELECT: 2892 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 2893 case ISD::FCOPYSIGN: 2894 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 2895 case ISD::MGATHER: 2896 case ISD::VP_GATHER: 2897 return lowerMaskedGather(Op, DAG); 2898 case ISD::MSCATTER: 2899 case ISD::VP_SCATTER: 2900 return lowerMaskedScatter(Op, DAG); 2901 case ISD::FLT_ROUNDS_: 2902 return lowerGET_ROUNDING(Op, DAG); 2903 case ISD::SET_ROUNDING: 2904 return lowerSET_ROUNDING(Op, DAG); 2905 case ISD::VP_ADD: 2906 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 2907 case ISD::VP_SUB: 2908 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 2909 case ISD::VP_MUL: 2910 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 2911 case ISD::VP_SDIV: 2912 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 2913 case ISD::VP_UDIV: 2914 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 2915 case ISD::VP_SREM: 2916 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 2917 case ISD::VP_UREM: 2918 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 2919 case ISD::VP_AND: 2920 return lowerVPOp(Op, DAG, RISCVISD::AND_VL); 2921 case ISD::VP_OR: 2922 return lowerVPOp(Op, DAG, RISCVISD::OR_VL); 2923 case ISD::VP_XOR: 2924 return lowerVPOp(Op, DAG, RISCVISD::XOR_VL); 2925 case ISD::VP_ASHR: 2926 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 2927 case ISD::VP_LSHR: 2928 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 2929 case ISD::VP_SHL: 2930 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 2931 case ISD::VP_FADD: 2932 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 2933 case ISD::VP_FSUB: 2934 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 2935 case ISD::VP_FMUL: 2936 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 2937 case ISD::VP_FDIV: 2938 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 2939 } 2940 } 2941 2942 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 2943 SelectionDAG &DAG, unsigned Flags) { 2944 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 2945 } 2946 2947 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 2948 SelectionDAG &DAG, unsigned Flags) { 2949 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 2950 Flags); 2951 } 2952 2953 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 2954 SelectionDAG &DAG, unsigned Flags) { 2955 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 2956 N->getOffset(), Flags); 2957 } 2958 2959 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 2960 SelectionDAG &DAG, unsigned Flags) { 2961 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 2962 } 2963 2964 template <class NodeTy> 2965 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 2966 bool IsLocal) const { 2967 SDLoc DL(N); 2968 EVT Ty = getPointerTy(DAG.getDataLayout()); 2969 2970 if (isPositionIndependent()) { 2971 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 2972 if (IsLocal) 2973 // Use PC-relative addressing to access the symbol. This generates the 2974 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 2975 // %pcrel_lo(auipc)). 2976 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 2977 2978 // Use PC-relative addressing to access the GOT for this symbol, then load 2979 // the address from the GOT. This generates the pattern (PseudoLA sym), 2980 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 2981 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 2982 } 2983 2984 switch (getTargetMachine().getCodeModel()) { 2985 default: 2986 report_fatal_error("Unsupported code model for lowering"); 2987 case CodeModel::Small: { 2988 // Generate a sequence for accessing addresses within the first 2 GiB of 2989 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 2990 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 2991 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 2992 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 2993 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 2994 } 2995 case CodeModel::Medium: { 2996 // Generate a sequence for accessing addresses within any 2GiB range within 2997 // the address space. This generates the pattern (PseudoLLA sym), which 2998 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 2999 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3000 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3001 } 3002 } 3003 } 3004 3005 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3006 SelectionDAG &DAG) const { 3007 SDLoc DL(Op); 3008 EVT Ty = Op.getValueType(); 3009 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3010 int64_t Offset = N->getOffset(); 3011 MVT XLenVT = Subtarget.getXLenVT(); 3012 3013 const GlobalValue *GV = N->getGlobal(); 3014 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3015 SDValue Addr = getAddr(N, DAG, IsLocal); 3016 3017 // In order to maximise the opportunity for common subexpression elimination, 3018 // emit a separate ADD node for the global address offset instead of folding 3019 // it in the global address node. Later peephole optimisations may choose to 3020 // fold it back in when profitable. 3021 if (Offset != 0) 3022 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3023 DAG.getConstant(Offset, DL, XLenVT)); 3024 return Addr; 3025 } 3026 3027 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3028 SelectionDAG &DAG) const { 3029 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3030 3031 return getAddr(N, DAG); 3032 } 3033 3034 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3035 SelectionDAG &DAG) const { 3036 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3037 3038 return getAddr(N, DAG); 3039 } 3040 3041 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3042 SelectionDAG &DAG) const { 3043 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3044 3045 return getAddr(N, DAG); 3046 } 3047 3048 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3049 SelectionDAG &DAG, 3050 bool UseGOT) const { 3051 SDLoc DL(N); 3052 EVT Ty = getPointerTy(DAG.getDataLayout()); 3053 const GlobalValue *GV = N->getGlobal(); 3054 MVT XLenVT = Subtarget.getXLenVT(); 3055 3056 if (UseGOT) { 3057 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3058 // load the address from the GOT and add the thread pointer. This generates 3059 // the pattern (PseudoLA_TLS_IE sym), which expands to 3060 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3061 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3062 SDValue Load = 3063 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3064 3065 // Add the thread pointer. 3066 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3067 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3068 } 3069 3070 // Generate a sequence for accessing the address relative to the thread 3071 // pointer, with the appropriate adjustment for the thread pointer offset. 3072 // This generates the pattern 3073 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3074 SDValue AddrHi = 3075 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3076 SDValue AddrAdd = 3077 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3078 SDValue AddrLo = 3079 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3080 3081 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3082 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3083 SDValue MNAdd = SDValue( 3084 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3085 0); 3086 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3087 } 3088 3089 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3090 SelectionDAG &DAG) const { 3091 SDLoc DL(N); 3092 EVT Ty = getPointerTy(DAG.getDataLayout()); 3093 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3094 const GlobalValue *GV = N->getGlobal(); 3095 3096 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3097 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3098 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3099 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3100 SDValue Load = 3101 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3102 3103 // Prepare argument list to generate call. 3104 ArgListTy Args; 3105 ArgListEntry Entry; 3106 Entry.Node = Load; 3107 Entry.Ty = CallTy; 3108 Args.push_back(Entry); 3109 3110 // Setup call to __tls_get_addr. 3111 TargetLowering::CallLoweringInfo CLI(DAG); 3112 CLI.setDebugLoc(DL) 3113 .setChain(DAG.getEntryNode()) 3114 .setLibCallee(CallingConv::C, CallTy, 3115 DAG.getExternalSymbol("__tls_get_addr", Ty), 3116 std::move(Args)); 3117 3118 return LowerCallTo(CLI).first; 3119 } 3120 3121 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3122 SelectionDAG &DAG) const { 3123 SDLoc DL(Op); 3124 EVT Ty = Op.getValueType(); 3125 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3126 int64_t Offset = N->getOffset(); 3127 MVT XLenVT = Subtarget.getXLenVT(); 3128 3129 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3130 3131 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3132 CallingConv::GHC) 3133 report_fatal_error("In GHC calling convention TLS is not supported"); 3134 3135 SDValue Addr; 3136 switch (Model) { 3137 case TLSModel::LocalExec: 3138 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3139 break; 3140 case TLSModel::InitialExec: 3141 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3142 break; 3143 case TLSModel::LocalDynamic: 3144 case TLSModel::GeneralDynamic: 3145 Addr = getDynamicTLSAddr(N, DAG); 3146 break; 3147 } 3148 3149 // In order to maximise the opportunity for common subexpression elimination, 3150 // emit a separate ADD node for the global address offset instead of folding 3151 // it in the global address node. Later peephole optimisations may choose to 3152 // fold it back in when profitable. 3153 if (Offset != 0) 3154 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3155 DAG.getConstant(Offset, DL, XLenVT)); 3156 return Addr; 3157 } 3158 3159 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3160 SDValue CondV = Op.getOperand(0); 3161 SDValue TrueV = Op.getOperand(1); 3162 SDValue FalseV = Op.getOperand(2); 3163 SDLoc DL(Op); 3164 MVT VT = Op.getSimpleValueType(); 3165 MVT XLenVT = Subtarget.getXLenVT(); 3166 3167 // Lower vector SELECTs to VSELECTs by splatting the condition. 3168 if (VT.isVector()) { 3169 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3170 SDValue CondSplat = VT.isScalableVector() 3171 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3172 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3173 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3174 } 3175 3176 // If the result type is XLenVT and CondV is the output of a SETCC node 3177 // which also operated on XLenVT inputs, then merge the SETCC node into the 3178 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3179 // compare+branch instructions. i.e.: 3180 // (select (setcc lhs, rhs, cc), truev, falsev) 3181 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3182 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3183 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3184 SDValue LHS = CondV.getOperand(0); 3185 SDValue RHS = CondV.getOperand(1); 3186 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3187 ISD::CondCode CCVal = CC->get(); 3188 3189 // Special case for a select of 2 constants that have a diffence of 1. 3190 // Normally this is done by DAGCombine, but if the select is introduced by 3191 // type legalization or op legalization, we miss it. Restricting to SETLT 3192 // case for now because that is what signed saturating add/sub need. 3193 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3194 // but we would probably want to swap the true/false values if the condition 3195 // is SETGE/SETLE to avoid an XORI. 3196 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3197 CCVal == ISD::SETLT) { 3198 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3199 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3200 if (TrueVal - 1 == FalseVal) 3201 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3202 if (TrueVal + 1 == FalseVal) 3203 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3204 } 3205 3206 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3207 3208 SDValue TargetCC = DAG.getCondCode(CCVal); 3209 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3210 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3211 } 3212 3213 // Otherwise: 3214 // (select condv, truev, falsev) 3215 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3216 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3217 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3218 3219 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3220 3221 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3222 } 3223 3224 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3225 SDValue CondV = Op.getOperand(1); 3226 SDLoc DL(Op); 3227 MVT XLenVT = Subtarget.getXLenVT(); 3228 3229 if (CondV.getOpcode() == ISD::SETCC && 3230 CondV.getOperand(0).getValueType() == XLenVT) { 3231 SDValue LHS = CondV.getOperand(0); 3232 SDValue RHS = CondV.getOperand(1); 3233 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3234 3235 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3236 3237 SDValue TargetCC = DAG.getCondCode(CCVal); 3238 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3239 LHS, RHS, TargetCC, Op.getOperand(2)); 3240 } 3241 3242 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3243 CondV, DAG.getConstant(0, DL, XLenVT), 3244 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3245 } 3246 3247 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3248 MachineFunction &MF = DAG.getMachineFunction(); 3249 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3250 3251 SDLoc DL(Op); 3252 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3253 getPointerTy(MF.getDataLayout())); 3254 3255 // vastart just stores the address of the VarArgsFrameIndex slot into the 3256 // memory location argument. 3257 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3258 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3259 MachinePointerInfo(SV)); 3260 } 3261 3262 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3263 SelectionDAG &DAG) const { 3264 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3265 MachineFunction &MF = DAG.getMachineFunction(); 3266 MachineFrameInfo &MFI = MF.getFrameInfo(); 3267 MFI.setFrameAddressIsTaken(true); 3268 Register FrameReg = RI.getFrameRegister(MF); 3269 int XLenInBytes = Subtarget.getXLen() / 8; 3270 3271 EVT VT = Op.getValueType(); 3272 SDLoc DL(Op); 3273 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3274 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3275 while (Depth--) { 3276 int Offset = -(XLenInBytes * 2); 3277 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3278 DAG.getIntPtrConstant(Offset, DL)); 3279 FrameAddr = 3280 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3281 } 3282 return FrameAddr; 3283 } 3284 3285 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3286 SelectionDAG &DAG) const { 3287 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3288 MachineFunction &MF = DAG.getMachineFunction(); 3289 MachineFrameInfo &MFI = MF.getFrameInfo(); 3290 MFI.setReturnAddressIsTaken(true); 3291 MVT XLenVT = Subtarget.getXLenVT(); 3292 int XLenInBytes = Subtarget.getXLen() / 8; 3293 3294 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3295 return SDValue(); 3296 3297 EVT VT = Op.getValueType(); 3298 SDLoc DL(Op); 3299 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3300 if (Depth) { 3301 int Off = -XLenInBytes; 3302 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3303 SDValue Offset = DAG.getConstant(Off, DL, VT); 3304 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3305 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3306 MachinePointerInfo()); 3307 } 3308 3309 // Return the value of the return address register, marking it an implicit 3310 // live-in. 3311 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3312 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3313 } 3314 3315 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3316 SelectionDAG &DAG) const { 3317 SDLoc DL(Op); 3318 SDValue Lo = Op.getOperand(0); 3319 SDValue Hi = Op.getOperand(1); 3320 SDValue Shamt = Op.getOperand(2); 3321 EVT VT = Lo.getValueType(); 3322 3323 // if Shamt-XLEN < 0: // Shamt < XLEN 3324 // Lo = Lo << Shamt 3325 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3326 // else: 3327 // Lo = 0 3328 // Hi = Lo << (Shamt-XLEN) 3329 3330 SDValue Zero = DAG.getConstant(0, DL, VT); 3331 SDValue One = DAG.getConstant(1, DL, VT); 3332 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3333 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3334 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3335 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3336 3337 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3338 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3339 SDValue ShiftRightLo = 3340 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3341 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3342 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3343 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3344 3345 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3346 3347 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3348 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3349 3350 SDValue Parts[2] = {Lo, Hi}; 3351 return DAG.getMergeValues(Parts, DL); 3352 } 3353 3354 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3355 bool IsSRA) const { 3356 SDLoc DL(Op); 3357 SDValue Lo = Op.getOperand(0); 3358 SDValue Hi = Op.getOperand(1); 3359 SDValue Shamt = Op.getOperand(2); 3360 EVT VT = Lo.getValueType(); 3361 3362 // SRA expansion: 3363 // if Shamt-XLEN < 0: // Shamt < XLEN 3364 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3365 // Hi = Hi >>s Shamt 3366 // else: 3367 // Lo = Hi >>s (Shamt-XLEN); 3368 // Hi = Hi >>s (XLEN-1) 3369 // 3370 // SRL expansion: 3371 // if Shamt-XLEN < 0: // Shamt < XLEN 3372 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3373 // Hi = Hi >>u Shamt 3374 // else: 3375 // Lo = Hi >>u (Shamt-XLEN); 3376 // Hi = 0; 3377 3378 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3379 3380 SDValue Zero = DAG.getConstant(0, DL, VT); 3381 SDValue One = DAG.getConstant(1, DL, VT); 3382 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3383 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3384 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3385 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3386 3387 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3388 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3389 SDValue ShiftLeftHi = 3390 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3391 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3392 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3393 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3394 SDValue HiFalse = 3395 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3396 3397 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3398 3399 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3400 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3401 3402 SDValue Parts[2] = {Lo, Hi}; 3403 return DAG.getMergeValues(Parts, DL); 3404 } 3405 3406 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3407 // legal equivalently-sized i8 type, so we can use that as a go-between. 3408 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3409 SelectionDAG &DAG) const { 3410 SDLoc DL(Op); 3411 MVT VT = Op.getSimpleValueType(); 3412 SDValue SplatVal = Op.getOperand(0); 3413 // All-zeros or all-ones splats are handled specially. 3414 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3415 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3416 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3417 } 3418 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3419 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3420 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3421 } 3422 MVT XLenVT = Subtarget.getXLenVT(); 3423 assert(SplatVal.getValueType() == XLenVT && 3424 "Unexpected type for i1 splat value"); 3425 MVT InterVT = VT.changeVectorElementType(MVT::i8); 3426 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 3427 DAG.getConstant(1, DL, XLenVT)); 3428 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 3429 SDValue Zero = DAG.getConstant(0, DL, InterVT); 3430 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 3431 } 3432 3433 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 3434 // illegal (currently only vXi64 RV32). 3435 // FIXME: We could also catch non-constant sign-extended i32 values and lower 3436 // them to SPLAT_VECTOR_I64 3437 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 3438 SelectionDAG &DAG) const { 3439 SDLoc DL(Op); 3440 MVT VecVT = Op.getSimpleValueType(); 3441 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 3442 "Unexpected SPLAT_VECTOR_PARTS lowering"); 3443 3444 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 3445 SDValue Lo = Op.getOperand(0); 3446 SDValue Hi = Op.getOperand(1); 3447 3448 if (VecVT.isFixedLengthVector()) { 3449 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3450 SDLoc DL(Op); 3451 SDValue Mask, VL; 3452 std::tie(Mask, VL) = 3453 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3454 3455 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 3456 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 3457 } 3458 3459 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 3460 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 3461 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 3462 // If Hi constant is all the same sign bit as Lo, lower this as a custom 3463 // node in order to try and match RVV vector/scalar instructions. 3464 if ((LoC >> 31) == HiC) 3465 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3466 } 3467 3468 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 3469 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 3470 isa<ConstantSDNode>(Hi.getOperand(1)) && 3471 Hi.getConstantOperandVal(1) == 31) 3472 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3473 3474 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 3475 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 3476 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64)); 3477 } 3478 3479 // Custom-lower extensions from mask vectors by using a vselect either with 1 3480 // for zero/any-extension or -1 for sign-extension: 3481 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 3482 // Note that any-extension is lowered identically to zero-extension. 3483 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 3484 int64_t ExtTrueVal) const { 3485 SDLoc DL(Op); 3486 MVT VecVT = Op.getSimpleValueType(); 3487 SDValue Src = Op.getOperand(0); 3488 // Only custom-lower extensions from mask types 3489 assert(Src.getValueType().isVector() && 3490 Src.getValueType().getVectorElementType() == MVT::i1); 3491 3492 MVT XLenVT = Subtarget.getXLenVT(); 3493 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 3494 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 3495 3496 if (VecVT.isScalableVector()) { 3497 // Be careful not to introduce illegal scalar types at this stage, and be 3498 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 3499 // illegal and must be expanded. Since we know that the constants are 3500 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 3501 bool IsRV32E64 = 3502 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 3503 3504 if (!IsRV32E64) { 3505 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 3506 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 3507 } else { 3508 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 3509 SplatTrueVal = 3510 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 3511 } 3512 3513 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 3514 } 3515 3516 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3517 MVT I1ContainerVT = 3518 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3519 3520 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 3521 3522 SDValue Mask, VL; 3523 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3524 3525 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 3526 SplatTrueVal = 3527 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 3528 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 3529 SplatTrueVal, SplatZero, VL); 3530 3531 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 3532 } 3533 3534 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 3535 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 3536 MVT ExtVT = Op.getSimpleValueType(); 3537 // Only custom-lower extensions from fixed-length vector types. 3538 if (!ExtVT.isFixedLengthVector()) 3539 return Op; 3540 MVT VT = Op.getOperand(0).getSimpleValueType(); 3541 // Grab the canonical container type for the extended type. Infer the smaller 3542 // type from that to ensure the same number of vector elements, as we know 3543 // the LMUL will be sufficient to hold the smaller type. 3544 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 3545 // Get the extended container type manually to ensure the same number of 3546 // vector elements between source and dest. 3547 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 3548 ContainerExtVT.getVectorElementCount()); 3549 3550 SDValue Op1 = 3551 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 3552 3553 SDLoc DL(Op); 3554 SDValue Mask, VL; 3555 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3556 3557 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 3558 3559 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 3560 } 3561 3562 // Custom-lower truncations from vectors to mask vectors by using a mask and a 3563 // setcc operation: 3564 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 3565 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 3566 SelectionDAG &DAG) const { 3567 SDLoc DL(Op); 3568 EVT MaskVT = Op.getValueType(); 3569 // Only expect to custom-lower truncations to mask types 3570 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 3571 "Unexpected type for vector mask lowering"); 3572 SDValue Src = Op.getOperand(0); 3573 MVT VecVT = Src.getSimpleValueType(); 3574 3575 // If this is a fixed vector, we need to convert it to a scalable vector. 3576 MVT ContainerVT = VecVT; 3577 if (VecVT.isFixedLengthVector()) { 3578 ContainerVT = getContainerForFixedLengthVector(VecVT); 3579 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3580 } 3581 3582 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 3583 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 3584 3585 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 3586 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 3587 3588 if (VecVT.isScalableVector()) { 3589 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 3590 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 3591 } 3592 3593 SDValue Mask, VL; 3594 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3595 3596 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 3597 SDValue Trunc = 3598 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 3599 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 3600 DAG.getCondCode(ISD::SETNE), Mask, VL); 3601 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 3602 } 3603 3604 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 3605 // first position of a vector, and that vector is slid up to the insert index. 3606 // By limiting the active vector length to index+1 and merging with the 3607 // original vector (with an undisturbed tail policy for elements >= VL), we 3608 // achieve the desired result of leaving all elements untouched except the one 3609 // at VL-1, which is replaced with the desired value. 3610 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3611 SelectionDAG &DAG) const { 3612 SDLoc DL(Op); 3613 MVT VecVT = Op.getSimpleValueType(); 3614 SDValue Vec = Op.getOperand(0); 3615 SDValue Val = Op.getOperand(1); 3616 SDValue Idx = Op.getOperand(2); 3617 3618 if (VecVT.getVectorElementType() == MVT::i1) { 3619 // FIXME: For now we just promote to an i8 vector and insert into that, 3620 // but this is probably not optimal. 3621 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3622 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3623 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 3624 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 3625 } 3626 3627 MVT ContainerVT = VecVT; 3628 // If the operand is a fixed-length vector, convert to a scalable one. 3629 if (VecVT.isFixedLengthVector()) { 3630 ContainerVT = getContainerForFixedLengthVector(VecVT); 3631 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3632 } 3633 3634 MVT XLenVT = Subtarget.getXLenVT(); 3635 3636 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3637 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 3638 // Even i64-element vectors on RV32 can be lowered without scalar 3639 // legalization if the most-significant 32 bits of the value are not affected 3640 // by the sign-extension of the lower 32 bits. 3641 // TODO: We could also catch sign extensions of a 32-bit value. 3642 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 3643 const auto *CVal = cast<ConstantSDNode>(Val); 3644 if (isInt<32>(CVal->getSExtValue())) { 3645 IsLegalInsert = true; 3646 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3647 } 3648 } 3649 3650 SDValue Mask, VL; 3651 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3652 3653 SDValue ValInVec; 3654 3655 if (IsLegalInsert) { 3656 unsigned Opc = 3657 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 3658 if (isNullConstant(Idx)) { 3659 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 3660 if (!VecVT.isFixedLengthVector()) 3661 return Vec; 3662 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 3663 } 3664 ValInVec = 3665 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 3666 } else { 3667 // On RV32, i64-element vectors must be specially handled to place the 3668 // value at element 0, by using two vslide1up instructions in sequence on 3669 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 3670 // this. 3671 SDValue One = DAG.getConstant(1, DL, XLenVT); 3672 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 3673 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 3674 MVT I32ContainerVT = 3675 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 3676 SDValue I32Mask = 3677 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 3678 // Limit the active VL to two. 3679 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 3680 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 3681 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 3682 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 3683 InsertI64VL); 3684 // First slide in the hi value, then the lo in underneath it. 3685 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3686 ValHi, I32Mask, InsertI64VL); 3687 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3688 ValLo, I32Mask, InsertI64VL); 3689 // Bitcast back to the right container type. 3690 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 3691 } 3692 3693 // Now that the value is in a vector, slide it into position. 3694 SDValue InsertVL = 3695 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 3696 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 3697 ValInVec, Idx, Mask, InsertVL); 3698 if (!VecVT.isFixedLengthVector()) 3699 return Slideup; 3700 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 3701 } 3702 3703 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 3704 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 3705 // types this is done using VMV_X_S to allow us to glean information about the 3706 // sign bits of the result. 3707 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 3708 SelectionDAG &DAG) const { 3709 SDLoc DL(Op); 3710 SDValue Idx = Op.getOperand(1); 3711 SDValue Vec = Op.getOperand(0); 3712 EVT EltVT = Op.getValueType(); 3713 MVT VecVT = Vec.getSimpleValueType(); 3714 MVT XLenVT = Subtarget.getXLenVT(); 3715 3716 if (VecVT.getVectorElementType() == MVT::i1) { 3717 // FIXME: For now we just promote to an i8 vector and extract from that, 3718 // but this is probably not optimal. 3719 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3720 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3721 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 3722 } 3723 3724 // If this is a fixed vector, we need to convert it to a scalable vector. 3725 MVT ContainerVT = VecVT; 3726 if (VecVT.isFixedLengthVector()) { 3727 ContainerVT = getContainerForFixedLengthVector(VecVT); 3728 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3729 } 3730 3731 // If the index is 0, the vector is already in the right position. 3732 if (!isNullConstant(Idx)) { 3733 // Use a VL of 1 to avoid processing more elements than we need. 3734 SDValue VL = DAG.getConstant(1, DL, XLenVT); 3735 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3736 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 3737 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 3738 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 3739 } 3740 3741 if (!EltVT.isInteger()) { 3742 // Floating-point extracts are handled in TableGen. 3743 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 3744 DAG.getConstant(0, DL, XLenVT)); 3745 } 3746 3747 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 3748 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 3749 } 3750 3751 // Some RVV intrinsics may claim that they want an integer operand to be 3752 // promoted or expanded. 3753 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 3754 const RISCVSubtarget &Subtarget) { 3755 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3756 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 3757 "Unexpected opcode"); 3758 3759 if (!Subtarget.hasStdExtV()) 3760 return SDValue(); 3761 3762 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 3763 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 3764 SDLoc DL(Op); 3765 3766 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 3767 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 3768 if (!II || !II->SplatOperand) 3769 return SDValue(); 3770 3771 unsigned SplatOp = II->SplatOperand + HasChain; 3772 assert(SplatOp < Op.getNumOperands()); 3773 3774 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 3775 SDValue &ScalarOp = Operands[SplatOp]; 3776 MVT OpVT = ScalarOp.getSimpleValueType(); 3777 MVT XLenVT = Subtarget.getXLenVT(); 3778 3779 // If this isn't a scalar, or its type is XLenVT we're done. 3780 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 3781 return SDValue(); 3782 3783 // Simplest case is that the operand needs to be promoted to XLenVT. 3784 if (OpVT.bitsLT(XLenVT)) { 3785 // If the operand is a constant, sign extend to increase our chances 3786 // of being able to use a .vi instruction. ANY_EXTEND would become a 3787 // a zero extend and the simm5 check in isel would fail. 3788 // FIXME: Should we ignore the upper bits in isel instead? 3789 unsigned ExtOpc = 3790 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 3791 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 3792 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3793 } 3794 3795 // Use the previous operand to get the vXi64 VT. The result might be a mask 3796 // VT for compares. Using the previous operand assumes that the previous 3797 // operand will never have a smaller element size than a scalar operand and 3798 // that a widening operation never uses SEW=64. 3799 // NOTE: If this fails the below assert, we can probably just find the 3800 // element count from any operand or result and use it to construct the VT. 3801 assert(II->SplatOperand > 1 && "Unexpected splat operand!"); 3802 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 3803 3804 // The more complex case is when the scalar is larger than XLenVT. 3805 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 3806 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 3807 3808 // If this is a sign-extended 32-bit constant, we can truncate it and rely 3809 // on the instruction to sign-extend since SEW>XLEN. 3810 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 3811 if (isInt<32>(CVal->getSExtValue())) { 3812 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3813 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3814 } 3815 } 3816 3817 // We need to convert the scalar to a splat vector. 3818 // FIXME: Can we implicitly truncate the scalar if it is known to 3819 // be sign extended? 3820 // VL should be the last operand. 3821 SDValue VL = Op.getOperand(Op.getNumOperands() - 1); 3822 assert(VL.getValueType() == XLenVT); 3823 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 3824 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3825 } 3826 3827 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3828 SelectionDAG &DAG) const { 3829 unsigned IntNo = Op.getConstantOperandVal(0); 3830 SDLoc DL(Op); 3831 MVT XLenVT = Subtarget.getXLenVT(); 3832 3833 switch (IntNo) { 3834 default: 3835 break; // Don't custom lower most intrinsics. 3836 case Intrinsic::thread_pointer: { 3837 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3838 return DAG.getRegister(RISCV::X4, PtrVT); 3839 } 3840 case Intrinsic::riscv_orc_b: 3841 // Lower to the GORCI encoding for orc.b. 3842 return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1), 3843 DAG.getConstant(7, DL, XLenVT)); 3844 case Intrinsic::riscv_grev: 3845 case Intrinsic::riscv_gorc: { 3846 unsigned Opc = 3847 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 3848 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3849 } 3850 case Intrinsic::riscv_shfl: 3851 case Intrinsic::riscv_unshfl: { 3852 unsigned Opc = 3853 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 3854 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3855 } 3856 case Intrinsic::riscv_bcompress: 3857 case Intrinsic::riscv_bdecompress: { 3858 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 3859 : RISCVISD::BDECOMPRESS; 3860 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3861 } 3862 case Intrinsic::riscv_vmv_x_s: 3863 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 3864 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 3865 Op.getOperand(1)); 3866 case Intrinsic::riscv_vmv_v_x: 3867 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 3868 Op.getSimpleValueType(), DL, DAG, Subtarget); 3869 case Intrinsic::riscv_vfmv_v_f: 3870 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 3871 Op.getOperand(1), Op.getOperand(2)); 3872 case Intrinsic::riscv_vmv_s_x: { 3873 SDValue Scalar = Op.getOperand(2); 3874 3875 if (Scalar.getValueType().bitsLE(XLenVT)) { 3876 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 3877 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 3878 Op.getOperand(1), Scalar, Op.getOperand(3)); 3879 } 3880 3881 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 3882 3883 // This is an i64 value that lives in two scalar registers. We have to 3884 // insert this in a convoluted way. First we build vXi64 splat containing 3885 // the/ two values that we assemble using some bit math. Next we'll use 3886 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 3887 // to merge element 0 from our splat into the source vector. 3888 // FIXME: This is probably not the best way to do this, but it is 3889 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 3890 // point. 3891 // sw lo, (a0) 3892 // sw hi, 4(a0) 3893 // vlse vX, (a0) 3894 // 3895 // vid.v vVid 3896 // vmseq.vx mMask, vVid, 0 3897 // vmerge.vvm vDest, vSrc, vVal, mMask 3898 MVT VT = Op.getSimpleValueType(); 3899 SDValue Vec = Op.getOperand(1); 3900 SDValue VL = Op.getOperand(3); 3901 3902 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 3903 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 3904 DAG.getConstant(0, DL, MVT::i32), VL); 3905 3906 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 3907 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 3908 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 3909 SDValue SelectCond = 3910 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 3911 DAG.getCondCode(ISD::SETEQ), Mask, VL); 3912 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 3913 Vec, VL); 3914 } 3915 case Intrinsic::riscv_vslide1up: 3916 case Intrinsic::riscv_vslide1down: 3917 case Intrinsic::riscv_vslide1up_mask: 3918 case Intrinsic::riscv_vslide1down_mask: { 3919 // We need to special case these when the scalar is larger than XLen. 3920 unsigned NumOps = Op.getNumOperands(); 3921 bool IsMasked = NumOps == 6; 3922 unsigned OpOffset = IsMasked ? 1 : 0; 3923 SDValue Scalar = Op.getOperand(2 + OpOffset); 3924 if (Scalar.getValueType().bitsLE(XLenVT)) 3925 break; 3926 3927 // Splatting a sign extended constant is fine. 3928 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 3929 if (isInt<32>(CVal->getSExtValue())) 3930 break; 3931 3932 MVT VT = Op.getSimpleValueType(); 3933 assert(VT.getVectorElementType() == MVT::i64 && 3934 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 3935 3936 // Convert the vector source to the equivalent nxvXi32 vector. 3937 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 3938 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 3939 3940 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 3941 DAG.getConstant(0, DL, XLenVT)); 3942 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 3943 DAG.getConstant(1, DL, XLenVT)); 3944 3945 // Double the VL since we halved SEW. 3946 SDValue VL = Op.getOperand(NumOps - 1); 3947 SDValue I32VL = 3948 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 3949 3950 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 3951 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 3952 3953 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 3954 // instructions. 3955 if (IntNo == Intrinsic::riscv_vslide1up || 3956 IntNo == Intrinsic::riscv_vslide1up_mask) { 3957 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 3958 I32Mask, I32VL); 3959 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 3960 I32Mask, I32VL); 3961 } else { 3962 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 3963 I32Mask, I32VL); 3964 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 3965 I32Mask, I32VL); 3966 } 3967 3968 // Convert back to nxvXi64. 3969 Vec = DAG.getBitcast(VT, Vec); 3970 3971 if (!IsMasked) 3972 return Vec; 3973 3974 // Apply mask after the operation. 3975 SDValue Mask = Op.getOperand(NumOps - 2); 3976 SDValue MaskedOff = Op.getOperand(1); 3977 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 3978 } 3979 } 3980 3981 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 3982 } 3983 3984 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 3985 SelectionDAG &DAG) const { 3986 unsigned IntNo = Op.getConstantOperandVal(1); 3987 switch (IntNo) { 3988 default: 3989 break; 3990 case Intrinsic::riscv_masked_strided_load: { 3991 SDLoc DL(Op); 3992 MVT XLenVT = Subtarget.getXLenVT(); 3993 3994 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 3995 // the selection of the masked intrinsics doesn't do this for us. 3996 SDValue Mask = Op.getOperand(5); 3997 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 3998 3999 MVT VT = Op->getSimpleValueType(0); 4000 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4001 4002 SDValue PassThru = Op.getOperand(2); 4003 if (!IsUnmasked) { 4004 MVT MaskVT = 4005 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4006 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4007 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4008 } 4009 4010 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4011 4012 SDValue IntID = DAG.getTargetConstant( 4013 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4014 XLenVT); 4015 4016 auto *Load = cast<MemIntrinsicSDNode>(Op); 4017 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4018 if (!IsUnmasked) 4019 Ops.push_back(PassThru); 4020 Ops.push_back(Op.getOperand(3)); // Ptr 4021 Ops.push_back(Op.getOperand(4)); // Stride 4022 if (!IsUnmasked) 4023 Ops.push_back(Mask); 4024 Ops.push_back(VL); 4025 4026 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4027 SDValue Result = 4028 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4029 Load->getMemoryVT(), Load->getMemOperand()); 4030 SDValue Chain = Result.getValue(1); 4031 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4032 return DAG.getMergeValues({Result, Chain}, DL); 4033 } 4034 } 4035 4036 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4037 } 4038 4039 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4040 SelectionDAG &DAG) const { 4041 unsigned IntNo = Op.getConstantOperandVal(1); 4042 switch (IntNo) { 4043 default: 4044 break; 4045 case Intrinsic::riscv_masked_strided_store: { 4046 SDLoc DL(Op); 4047 MVT XLenVT = Subtarget.getXLenVT(); 4048 4049 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4050 // the selection of the masked intrinsics doesn't do this for us. 4051 SDValue Mask = Op.getOperand(5); 4052 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4053 4054 SDValue Val = Op.getOperand(2); 4055 MVT VT = Val.getSimpleValueType(); 4056 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4057 4058 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4059 if (!IsUnmasked) { 4060 MVT MaskVT = 4061 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4062 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4063 } 4064 4065 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4066 4067 SDValue IntID = DAG.getTargetConstant( 4068 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4069 XLenVT); 4070 4071 auto *Store = cast<MemIntrinsicSDNode>(Op); 4072 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4073 Ops.push_back(Val); 4074 Ops.push_back(Op.getOperand(3)); // Ptr 4075 Ops.push_back(Op.getOperand(4)); // Stride 4076 if (!IsUnmasked) 4077 Ops.push_back(Mask); 4078 Ops.push_back(VL); 4079 4080 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4081 Ops, Store->getMemoryVT(), 4082 Store->getMemOperand()); 4083 } 4084 } 4085 4086 return SDValue(); 4087 } 4088 4089 static MVT getLMUL1VT(MVT VT) { 4090 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4091 "Unexpected vector MVT"); 4092 return MVT::getScalableVectorVT( 4093 VT.getVectorElementType(), 4094 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4095 } 4096 4097 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4098 switch (ISDOpcode) { 4099 default: 4100 llvm_unreachable("Unhandled reduction"); 4101 case ISD::VECREDUCE_ADD: 4102 return RISCVISD::VECREDUCE_ADD_VL; 4103 case ISD::VECREDUCE_UMAX: 4104 return RISCVISD::VECREDUCE_UMAX_VL; 4105 case ISD::VECREDUCE_SMAX: 4106 return RISCVISD::VECREDUCE_SMAX_VL; 4107 case ISD::VECREDUCE_UMIN: 4108 return RISCVISD::VECREDUCE_UMIN_VL; 4109 case ISD::VECREDUCE_SMIN: 4110 return RISCVISD::VECREDUCE_SMIN_VL; 4111 case ISD::VECREDUCE_AND: 4112 return RISCVISD::VECREDUCE_AND_VL; 4113 case ISD::VECREDUCE_OR: 4114 return RISCVISD::VECREDUCE_OR_VL; 4115 case ISD::VECREDUCE_XOR: 4116 return RISCVISD::VECREDUCE_XOR_VL; 4117 } 4118 } 4119 4120 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4121 SelectionDAG &DAG, 4122 bool IsVP) const { 4123 SDLoc DL(Op); 4124 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4125 MVT VecVT = Vec.getSimpleValueType(); 4126 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4127 Op.getOpcode() == ISD::VECREDUCE_OR || 4128 Op.getOpcode() == ISD::VECREDUCE_XOR || 4129 Op.getOpcode() == ISD::VP_REDUCE_AND || 4130 Op.getOpcode() == ISD::VP_REDUCE_OR || 4131 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4132 "Unexpected reduction lowering"); 4133 4134 MVT XLenVT = Subtarget.getXLenVT(); 4135 assert(Op.getValueType() == XLenVT && 4136 "Expected reduction output to be legalized to XLenVT"); 4137 4138 MVT ContainerVT = VecVT; 4139 if (VecVT.isFixedLengthVector()) { 4140 ContainerVT = getContainerForFixedLengthVector(VecVT); 4141 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4142 } 4143 4144 SDValue Mask, VL; 4145 if (IsVP) { 4146 Mask = Op.getOperand(2); 4147 VL = Op.getOperand(3); 4148 } else { 4149 std::tie(Mask, VL) = 4150 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4151 } 4152 4153 unsigned BaseOpc; 4154 ISD::CondCode CC; 4155 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4156 4157 switch (Op.getOpcode()) { 4158 default: 4159 llvm_unreachable("Unhandled reduction"); 4160 case ISD::VECREDUCE_AND: 4161 case ISD::VP_REDUCE_AND: { 4162 // vpopc ~x == 0 4163 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4164 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4165 Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL); 4166 CC = ISD::SETEQ; 4167 BaseOpc = ISD::AND; 4168 break; 4169 } 4170 case ISD::VECREDUCE_OR: 4171 case ISD::VP_REDUCE_OR: 4172 // vpopc x != 0 4173 Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL); 4174 CC = ISD::SETNE; 4175 BaseOpc = ISD::OR; 4176 break; 4177 case ISD::VECREDUCE_XOR: 4178 case ISD::VP_REDUCE_XOR: { 4179 // ((vpopc x) & 1) != 0 4180 SDValue One = DAG.getConstant(1, DL, XLenVT); 4181 Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL); 4182 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4183 CC = ISD::SETNE; 4184 BaseOpc = ISD::XOR; 4185 break; 4186 } 4187 } 4188 4189 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4190 4191 if (!IsVP) 4192 return SetCC; 4193 4194 // Now include the start value in the operation. 4195 // Note that we must return the start value when no elements are operated 4196 // upon. The vpopc instructions we've emitted in each case above will return 4197 // 0 for an inactive vector, and so we've already received the neutral value: 4198 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4199 // can simply include the start value. 4200 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4201 } 4202 4203 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4204 SelectionDAG &DAG) const { 4205 SDLoc DL(Op); 4206 SDValue Vec = Op.getOperand(0); 4207 EVT VecEVT = Vec.getValueType(); 4208 4209 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4210 4211 // Due to ordering in legalize types we may have a vector type that needs to 4212 // be split. Do that manually so we can get down to a legal type. 4213 while (getTypeAction(*DAG.getContext(), VecEVT) == 4214 TargetLowering::TypeSplitVector) { 4215 SDValue Lo, Hi; 4216 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4217 VecEVT = Lo.getValueType(); 4218 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4219 } 4220 4221 // TODO: The type may need to be widened rather than split. Or widened before 4222 // it can be split. 4223 if (!isTypeLegal(VecEVT)) 4224 return SDValue(); 4225 4226 MVT VecVT = VecEVT.getSimpleVT(); 4227 MVT VecEltVT = VecVT.getVectorElementType(); 4228 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4229 4230 MVT ContainerVT = VecVT; 4231 if (VecVT.isFixedLengthVector()) { 4232 ContainerVT = getContainerForFixedLengthVector(VecVT); 4233 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4234 } 4235 4236 MVT M1VT = getLMUL1VT(ContainerVT); 4237 4238 SDValue Mask, VL; 4239 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4240 4241 // FIXME: This is a VLMAX splat which might be too large and can prevent 4242 // vsetvli removal. 4243 SDValue NeutralElem = 4244 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4245 SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem); 4246 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4247 IdentitySplat, Mask, VL); 4248 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4249 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4250 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4251 } 4252 4253 // Given a reduction op, this function returns the matching reduction opcode, 4254 // the vector SDValue and the scalar SDValue required to lower this to a 4255 // RISCVISD node. 4256 static std::tuple<unsigned, SDValue, SDValue> 4257 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4258 SDLoc DL(Op); 4259 auto Flags = Op->getFlags(); 4260 unsigned Opcode = Op.getOpcode(); 4261 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4262 switch (Opcode) { 4263 default: 4264 llvm_unreachable("Unhandled reduction"); 4265 case ISD::VECREDUCE_FADD: 4266 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), 4267 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4268 case ISD::VECREDUCE_SEQ_FADD: 4269 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4270 Op.getOperand(0)); 4271 case ISD::VECREDUCE_FMIN: 4272 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4273 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4274 case ISD::VECREDUCE_FMAX: 4275 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4276 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4277 } 4278 } 4279 4280 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4281 SelectionDAG &DAG) const { 4282 SDLoc DL(Op); 4283 MVT VecEltVT = Op.getSimpleValueType(); 4284 4285 unsigned RVVOpcode; 4286 SDValue VectorVal, ScalarVal; 4287 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4288 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4289 MVT VecVT = VectorVal.getSimpleValueType(); 4290 4291 MVT ContainerVT = VecVT; 4292 if (VecVT.isFixedLengthVector()) { 4293 ContainerVT = getContainerForFixedLengthVector(VecVT); 4294 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4295 } 4296 4297 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4298 4299 SDValue Mask, VL; 4300 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4301 4302 // FIXME: This is a VLMAX splat which might be too large and can prevent 4303 // vsetvli removal. 4304 SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal); 4305 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4306 VectorVal, ScalarSplat, Mask, VL); 4307 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4308 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4309 } 4310 4311 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4312 switch (ISDOpcode) { 4313 default: 4314 llvm_unreachable("Unhandled reduction"); 4315 case ISD::VP_REDUCE_ADD: 4316 return RISCVISD::VECREDUCE_ADD_VL; 4317 case ISD::VP_REDUCE_UMAX: 4318 return RISCVISD::VECREDUCE_UMAX_VL; 4319 case ISD::VP_REDUCE_SMAX: 4320 return RISCVISD::VECREDUCE_SMAX_VL; 4321 case ISD::VP_REDUCE_UMIN: 4322 return RISCVISD::VECREDUCE_UMIN_VL; 4323 case ISD::VP_REDUCE_SMIN: 4324 return RISCVISD::VECREDUCE_SMIN_VL; 4325 case ISD::VP_REDUCE_AND: 4326 return RISCVISD::VECREDUCE_AND_VL; 4327 case ISD::VP_REDUCE_OR: 4328 return RISCVISD::VECREDUCE_OR_VL; 4329 case ISD::VP_REDUCE_XOR: 4330 return RISCVISD::VECREDUCE_XOR_VL; 4331 case ISD::VP_REDUCE_FADD: 4332 return RISCVISD::VECREDUCE_FADD_VL; 4333 case ISD::VP_REDUCE_SEQ_FADD: 4334 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 4335 case ISD::VP_REDUCE_FMAX: 4336 return RISCVISD::VECREDUCE_FMAX_VL; 4337 case ISD::VP_REDUCE_FMIN: 4338 return RISCVISD::VECREDUCE_FMIN_VL; 4339 } 4340 } 4341 4342 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 4343 SelectionDAG &DAG) const { 4344 SDLoc DL(Op); 4345 SDValue Vec = Op.getOperand(1); 4346 EVT VecEVT = Vec.getValueType(); 4347 4348 // TODO: The type may need to be widened rather than split. Or widened before 4349 // it can be split. 4350 if (!isTypeLegal(VecEVT)) 4351 return SDValue(); 4352 4353 MVT VecVT = VecEVT.getSimpleVT(); 4354 MVT VecEltVT = VecVT.getVectorElementType(); 4355 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 4356 4357 MVT ContainerVT = VecVT; 4358 if (VecVT.isFixedLengthVector()) { 4359 ContainerVT = getContainerForFixedLengthVector(VecVT); 4360 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4361 } 4362 4363 SDValue VL = Op.getOperand(3); 4364 SDValue Mask = Op.getOperand(2); 4365 4366 MVT M1VT = getLMUL1VT(ContainerVT); 4367 MVT XLenVT = Subtarget.getXLenVT(); 4368 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 4369 4370 // FIXME: This is a VLMAX splat which might be too large and can prevent 4371 // vsetvli removal. 4372 SDValue StartSplat = DAG.getSplatVector(M1VT, DL, Op.getOperand(0)); 4373 SDValue Reduction = 4374 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 4375 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 4376 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4377 if (!VecVT.isInteger()) 4378 return Elt0; 4379 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4380 } 4381 4382 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4383 SelectionDAG &DAG) const { 4384 SDValue Vec = Op.getOperand(0); 4385 SDValue SubVec = Op.getOperand(1); 4386 MVT VecVT = Vec.getSimpleValueType(); 4387 MVT SubVecVT = SubVec.getSimpleValueType(); 4388 4389 SDLoc DL(Op); 4390 MVT XLenVT = Subtarget.getXLenVT(); 4391 unsigned OrigIdx = Op.getConstantOperandVal(2); 4392 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4393 4394 // We don't have the ability to slide mask vectors up indexed by their i1 4395 // elements; the smallest we can do is i8. Often we are able to bitcast to 4396 // equivalent i8 vectors. Note that when inserting a fixed-length vector 4397 // into a scalable one, we might not necessarily have enough scalable 4398 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 4399 if (SubVecVT.getVectorElementType() == MVT::i1 && 4400 (OrigIdx != 0 || !Vec.isUndef())) { 4401 if (VecVT.getVectorMinNumElements() >= 8 && 4402 SubVecVT.getVectorMinNumElements() >= 8) { 4403 assert(OrigIdx % 8 == 0 && "Invalid index"); 4404 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4405 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4406 "Unexpected mask vector lowering"); 4407 OrigIdx /= 8; 4408 SubVecVT = 4409 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4410 SubVecVT.isScalableVector()); 4411 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4412 VecVT.isScalableVector()); 4413 Vec = DAG.getBitcast(VecVT, Vec); 4414 SubVec = DAG.getBitcast(SubVecVT, SubVec); 4415 } else { 4416 // We can't slide this mask vector up indexed by its i1 elements. 4417 // This poses a problem when we wish to insert a scalable vector which 4418 // can't be re-expressed as a larger type. Just choose the slow path and 4419 // extend to a larger type, then truncate back down. 4420 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4421 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4422 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4423 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 4424 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 4425 Op.getOperand(2)); 4426 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 4427 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 4428 } 4429 } 4430 4431 // If the subvector vector is a fixed-length type, we cannot use subregister 4432 // manipulation to simplify the codegen; we don't know which register of a 4433 // LMUL group contains the specific subvector as we only know the minimum 4434 // register size. Therefore we must slide the vector group up the full 4435 // amount. 4436 if (SubVecVT.isFixedLengthVector()) { 4437 if (OrigIdx == 0 && Vec.isUndef()) 4438 return Op; 4439 MVT ContainerVT = VecVT; 4440 if (VecVT.isFixedLengthVector()) { 4441 ContainerVT = getContainerForFixedLengthVector(VecVT); 4442 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4443 } 4444 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 4445 DAG.getUNDEF(ContainerVT), SubVec, 4446 DAG.getConstant(0, DL, XLenVT)); 4447 SDValue Mask = 4448 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4449 // Set the vector length to only the number of elements we care about. Note 4450 // that for slideup this includes the offset. 4451 SDValue VL = 4452 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 4453 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4454 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4455 SubVec, SlideupAmt, Mask, VL); 4456 if (VecVT.isFixedLengthVector()) 4457 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4458 return DAG.getBitcast(Op.getValueType(), Slideup); 4459 } 4460 4461 unsigned SubRegIdx, RemIdx; 4462 std::tie(SubRegIdx, RemIdx) = 4463 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4464 VecVT, SubVecVT, OrigIdx, TRI); 4465 4466 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 4467 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 4468 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 4469 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 4470 4471 // 1. If the Idx has been completely eliminated and this subvector's size is 4472 // a vector register or a multiple thereof, or the surrounding elements are 4473 // undef, then this is a subvector insert which naturally aligns to a vector 4474 // register. These can easily be handled using subregister manipulation. 4475 // 2. If the subvector is smaller than a vector register, then the insertion 4476 // must preserve the undisturbed elements of the register. We do this by 4477 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 4478 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 4479 // subvector within the vector register, and an INSERT_SUBVECTOR of that 4480 // LMUL=1 type back into the larger vector (resolving to another subregister 4481 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 4482 // to avoid allocating a large register group to hold our subvector. 4483 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 4484 return Op; 4485 4486 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 4487 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 4488 // (in our case undisturbed). This means we can set up a subvector insertion 4489 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 4490 // size of the subvector. 4491 MVT InterSubVT = VecVT; 4492 SDValue AlignedExtract = Vec; 4493 unsigned AlignedIdx = OrigIdx - RemIdx; 4494 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4495 InterSubVT = getLMUL1VT(VecVT); 4496 // Extract a subvector equal to the nearest full vector register type. This 4497 // should resolve to a EXTRACT_SUBREG instruction. 4498 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4499 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4500 } 4501 4502 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4503 // For scalable vectors this must be further multiplied by vscale. 4504 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 4505 4506 SDValue Mask, VL; 4507 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4508 4509 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 4510 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 4511 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 4512 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 4513 4514 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 4515 DAG.getUNDEF(InterSubVT), SubVec, 4516 DAG.getConstant(0, DL, XLenVT)); 4517 4518 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 4519 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 4520 4521 // If required, insert this subvector back into the correct vector register. 4522 // This should resolve to an INSERT_SUBREG instruction. 4523 if (VecVT.bitsGT(InterSubVT)) 4524 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 4525 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4526 4527 // We might have bitcast from a mask type: cast back to the original type if 4528 // required. 4529 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 4530 } 4531 4532 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 4533 SelectionDAG &DAG) const { 4534 SDValue Vec = Op.getOperand(0); 4535 MVT SubVecVT = Op.getSimpleValueType(); 4536 MVT VecVT = Vec.getSimpleValueType(); 4537 4538 SDLoc DL(Op); 4539 MVT XLenVT = Subtarget.getXLenVT(); 4540 unsigned OrigIdx = Op.getConstantOperandVal(1); 4541 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4542 4543 // We don't have the ability to slide mask vectors down indexed by their i1 4544 // elements; the smallest we can do is i8. Often we are able to bitcast to 4545 // equivalent i8 vectors. Note that when extracting a fixed-length vector 4546 // from a scalable one, we might not necessarily have enough scalable 4547 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 4548 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 4549 if (VecVT.getVectorMinNumElements() >= 8 && 4550 SubVecVT.getVectorMinNumElements() >= 8) { 4551 assert(OrigIdx % 8 == 0 && "Invalid index"); 4552 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4553 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4554 "Unexpected mask vector lowering"); 4555 OrigIdx /= 8; 4556 SubVecVT = 4557 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4558 SubVecVT.isScalableVector()); 4559 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4560 VecVT.isScalableVector()); 4561 Vec = DAG.getBitcast(VecVT, Vec); 4562 } else { 4563 // We can't slide this mask vector down, indexed by its i1 elements. 4564 // This poses a problem when we wish to extract a scalable vector which 4565 // can't be re-expressed as a larger type. Just choose the slow path and 4566 // extend to a larger type, then truncate back down. 4567 // TODO: We could probably improve this when extracting certain fixed 4568 // from fixed, where we can extract as i8 and shift the correct element 4569 // right to reach the desired subvector? 4570 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4571 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4572 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4573 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 4574 Op.getOperand(1)); 4575 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 4576 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 4577 } 4578 } 4579 4580 // If the subvector vector is a fixed-length type, we cannot use subregister 4581 // manipulation to simplify the codegen; we don't know which register of a 4582 // LMUL group contains the specific subvector as we only know the minimum 4583 // register size. Therefore we must slide the vector group down the full 4584 // amount. 4585 if (SubVecVT.isFixedLengthVector()) { 4586 // With an index of 0 this is a cast-like subvector, which can be performed 4587 // with subregister operations. 4588 if (OrigIdx == 0) 4589 return Op; 4590 MVT ContainerVT = VecVT; 4591 if (VecVT.isFixedLengthVector()) { 4592 ContainerVT = getContainerForFixedLengthVector(VecVT); 4593 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4594 } 4595 SDValue Mask = 4596 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4597 // Set the vector length to only the number of elements we care about. This 4598 // avoids sliding down elements we're going to discard straight away. 4599 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 4600 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4601 SDValue Slidedown = 4602 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4603 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 4604 // Now we can use a cast-like subvector extract to get the result. 4605 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4606 DAG.getConstant(0, DL, XLenVT)); 4607 return DAG.getBitcast(Op.getValueType(), Slidedown); 4608 } 4609 4610 unsigned SubRegIdx, RemIdx; 4611 std::tie(SubRegIdx, RemIdx) = 4612 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4613 VecVT, SubVecVT, OrigIdx, TRI); 4614 4615 // If the Idx has been completely eliminated then this is a subvector extract 4616 // which naturally aligns to a vector register. These can easily be handled 4617 // using subregister manipulation. 4618 if (RemIdx == 0) 4619 return Op; 4620 4621 // Else we must shift our vector register directly to extract the subvector. 4622 // Do this using VSLIDEDOWN. 4623 4624 // If the vector type is an LMUL-group type, extract a subvector equal to the 4625 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 4626 // instruction. 4627 MVT InterSubVT = VecVT; 4628 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4629 InterSubVT = getLMUL1VT(VecVT); 4630 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4631 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 4632 } 4633 4634 // Slide this vector register down by the desired number of elements in order 4635 // to place the desired subvector starting at element 0. 4636 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4637 // For scalable vectors this must be further multiplied by vscale. 4638 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 4639 4640 SDValue Mask, VL; 4641 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 4642 SDValue Slidedown = 4643 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 4644 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 4645 4646 // Now the vector is in the right position, extract our final subvector. This 4647 // should resolve to a COPY. 4648 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4649 DAG.getConstant(0, DL, XLenVT)); 4650 4651 // We might have bitcast from a mask type: cast back to the original type if 4652 // required. 4653 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 4654 } 4655 4656 // Lower step_vector to the vid instruction. Any non-identity step value must 4657 // be accounted for my manual expansion. 4658 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 4659 SelectionDAG &DAG) const { 4660 SDLoc DL(Op); 4661 MVT VT = Op.getSimpleValueType(); 4662 MVT XLenVT = Subtarget.getXLenVT(); 4663 SDValue Mask, VL; 4664 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 4665 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4666 uint64_t StepValImm = Op.getConstantOperandVal(0); 4667 if (StepValImm != 1) { 4668 if (isPowerOf2_64(StepValImm)) { 4669 SDValue StepVal = 4670 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4671 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 4672 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 4673 } else { 4674 SDValue StepVal = lowerScalarSplat( 4675 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 4676 DL, DAG, Subtarget); 4677 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 4678 } 4679 } 4680 return StepVec; 4681 } 4682 4683 // Implement vector_reverse using vrgather.vv with indices determined by 4684 // subtracting the id of each element from (VLMAX-1). This will convert 4685 // the indices like so: 4686 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 4687 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 4688 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 4689 SelectionDAG &DAG) const { 4690 SDLoc DL(Op); 4691 MVT VecVT = Op.getSimpleValueType(); 4692 unsigned EltSize = VecVT.getScalarSizeInBits(); 4693 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 4694 4695 unsigned MaxVLMAX = 0; 4696 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 4697 if (VectorBitsMax != 0) 4698 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 4699 4700 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 4701 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 4702 4703 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 4704 // to use vrgatherei16.vv. 4705 // TODO: It's also possible to use vrgatherei16.vv for other types to 4706 // decrease register width for the index calculation. 4707 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 4708 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 4709 // Reverse each half, then reassemble them in reverse order. 4710 // NOTE: It's also possible that after splitting that VLMAX no longer 4711 // requires vrgatherei16.vv. 4712 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 4713 SDValue Lo, Hi; 4714 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4715 EVT LoVT, HiVT; 4716 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 4717 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 4718 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 4719 // Reassemble the low and high pieces reversed. 4720 // FIXME: This is a CONCAT_VECTORS. 4721 SDValue Res = 4722 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 4723 DAG.getIntPtrConstant(0, DL)); 4724 return DAG.getNode( 4725 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 4726 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 4727 } 4728 4729 // Just promote the int type to i16 which will double the LMUL. 4730 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 4731 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 4732 } 4733 4734 MVT XLenVT = Subtarget.getXLenVT(); 4735 SDValue Mask, VL; 4736 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4737 4738 // Calculate VLMAX-1 for the desired SEW. 4739 unsigned MinElts = VecVT.getVectorMinNumElements(); 4740 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 4741 DAG.getConstant(MinElts, DL, XLenVT)); 4742 SDValue VLMinus1 = 4743 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 4744 4745 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 4746 bool IsRV32E64 = 4747 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 4748 SDValue SplatVL; 4749 if (!IsRV32E64) 4750 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 4751 else 4752 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 4753 4754 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 4755 SDValue Indices = 4756 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 4757 4758 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 4759 } 4760 4761 SDValue 4762 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 4763 SelectionDAG &DAG) const { 4764 SDLoc DL(Op); 4765 auto *Load = cast<LoadSDNode>(Op); 4766 4767 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 4768 Load->getMemoryVT(), 4769 *Load->getMemOperand()) && 4770 "Expecting a correctly-aligned load"); 4771 4772 MVT VT = Op.getSimpleValueType(); 4773 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4774 4775 SDValue VL = 4776 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4777 4778 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4779 SDValue NewLoad = DAG.getMemIntrinsicNode( 4780 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 4781 Load->getMemoryVT(), Load->getMemOperand()); 4782 4783 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 4784 return DAG.getMergeValues({Result, Load->getChain()}, DL); 4785 } 4786 4787 SDValue 4788 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 4789 SelectionDAG &DAG) const { 4790 SDLoc DL(Op); 4791 auto *Store = cast<StoreSDNode>(Op); 4792 4793 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 4794 Store->getMemoryVT(), 4795 *Store->getMemOperand()) && 4796 "Expecting a correctly-aligned store"); 4797 4798 SDValue StoreVal = Store->getValue(); 4799 MVT VT = StoreVal.getSimpleValueType(); 4800 4801 // If the size less than a byte, we need to pad with zeros to make a byte. 4802 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 4803 VT = MVT::v8i1; 4804 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 4805 DAG.getConstant(0, DL, VT), StoreVal, 4806 DAG.getIntPtrConstant(0, DL)); 4807 } 4808 4809 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4810 4811 SDValue VL = 4812 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4813 4814 SDValue NewValue = 4815 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 4816 return DAG.getMemIntrinsicNode( 4817 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 4818 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 4819 Store->getMemoryVT(), Store->getMemOperand()); 4820 } 4821 4822 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 4823 SelectionDAG &DAG) const { 4824 SDLoc DL(Op); 4825 MVT VT = Op.getSimpleValueType(); 4826 4827 const auto *MemSD = cast<MemSDNode>(Op); 4828 EVT MemVT = MemSD->getMemoryVT(); 4829 MachineMemOperand *MMO = MemSD->getMemOperand(); 4830 SDValue Chain = MemSD->getChain(); 4831 SDValue BasePtr = MemSD->getBasePtr(); 4832 4833 SDValue Mask, PassThru, VL; 4834 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 4835 Mask = VPLoad->getMask(); 4836 PassThru = DAG.getUNDEF(VT); 4837 VL = VPLoad->getVectorLength(); 4838 } else { 4839 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 4840 Mask = MLoad->getMask(); 4841 PassThru = MLoad->getPassThru(); 4842 } 4843 4844 MVT XLenVT = Subtarget.getXLenVT(); 4845 4846 MVT ContainerVT = VT; 4847 if (VT.isFixedLengthVector()) { 4848 ContainerVT = getContainerForFixedLengthVector(VT); 4849 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4850 4851 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4852 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4853 } 4854 4855 if (!VL) 4856 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 4857 4858 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4859 SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vle_mask, DL, XLenVT); 4860 SDValue Ops[] = {Chain, IntID, PassThru, BasePtr, Mask, VL}; 4861 SDValue Result = 4862 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 4863 Chain = Result.getValue(1); 4864 4865 if (VT.isFixedLengthVector()) 4866 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4867 4868 return DAG.getMergeValues({Result, Chain}, DL); 4869 } 4870 4871 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 4872 SelectionDAG &DAG) const { 4873 SDLoc DL(Op); 4874 4875 const auto *MemSD = cast<MemSDNode>(Op); 4876 EVT MemVT = MemSD->getMemoryVT(); 4877 MachineMemOperand *MMO = MemSD->getMemOperand(); 4878 SDValue Chain = MemSD->getChain(); 4879 SDValue BasePtr = MemSD->getBasePtr(); 4880 SDValue Val, Mask, VL; 4881 4882 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 4883 Val = VPStore->getValue(); 4884 Mask = VPStore->getMask(); 4885 VL = VPStore->getVectorLength(); 4886 } else { 4887 const auto *MStore = cast<MaskedStoreSDNode>(Op); 4888 Val = MStore->getValue(); 4889 Mask = MStore->getMask(); 4890 } 4891 4892 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4893 4894 MVT VT = Val.getSimpleValueType(); 4895 MVT XLenVT = Subtarget.getXLenVT(); 4896 4897 MVT ContainerVT = VT; 4898 if (VT.isFixedLengthVector()) { 4899 ContainerVT = getContainerForFixedLengthVector(VT); 4900 4901 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4902 if (!IsUnmasked) { 4903 MVT MaskVT = 4904 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4905 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4906 } 4907 } 4908 4909 if (!VL) 4910 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 4911 4912 unsigned IntID = 4913 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 4914 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 4915 Ops.push_back(Val); 4916 Ops.push_back(BasePtr); 4917 if (!IsUnmasked) 4918 Ops.push_back(Mask); 4919 Ops.push_back(VL); 4920 4921 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 4922 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 4923 } 4924 4925 SDValue 4926 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 4927 SelectionDAG &DAG) const { 4928 MVT InVT = Op.getOperand(0).getSimpleValueType(); 4929 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 4930 4931 MVT VT = Op.getSimpleValueType(); 4932 4933 SDValue Op1 = 4934 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4935 SDValue Op2 = 4936 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 4937 4938 SDLoc DL(Op); 4939 SDValue VL = 4940 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4941 4942 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4943 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4944 4945 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 4946 Op.getOperand(2), Mask, VL); 4947 4948 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 4949 } 4950 4951 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 4952 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 4953 MVT VT = Op.getSimpleValueType(); 4954 4955 if (VT.getVectorElementType() == MVT::i1) 4956 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 4957 4958 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 4959 } 4960 4961 SDValue 4962 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 4963 SelectionDAG &DAG) const { 4964 unsigned Opc; 4965 switch (Op.getOpcode()) { 4966 default: llvm_unreachable("Unexpected opcode!"); 4967 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 4968 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 4969 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 4970 } 4971 4972 return lowerToScalableOp(Op, DAG, Opc); 4973 } 4974 4975 // Lower vector ABS to smax(X, sub(0, X)). 4976 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 4977 SDLoc DL(Op); 4978 MVT VT = Op.getSimpleValueType(); 4979 SDValue X = Op.getOperand(0); 4980 4981 assert(VT.isFixedLengthVector() && "Unexpected type"); 4982 4983 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4984 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 4985 4986 SDValue Mask, VL; 4987 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4988 4989 SDValue SplatZero = 4990 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4991 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4992 SDValue NegX = 4993 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 4994 SDValue Max = 4995 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 4996 4997 return convertFromScalableVector(VT, Max, DAG, Subtarget); 4998 } 4999 5000 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5001 SDValue Op, SelectionDAG &DAG) const { 5002 SDLoc DL(Op); 5003 MVT VT = Op.getSimpleValueType(); 5004 SDValue Mag = Op.getOperand(0); 5005 SDValue Sign = Op.getOperand(1); 5006 assert(Mag.getValueType() == Sign.getValueType() && 5007 "Can only handle COPYSIGN with matching types."); 5008 5009 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5010 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5011 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5012 5013 SDValue Mask, VL; 5014 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5015 5016 SDValue CopySign = 5017 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5018 5019 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5020 } 5021 5022 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5023 SDValue Op, SelectionDAG &DAG) const { 5024 MVT VT = Op.getSimpleValueType(); 5025 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5026 5027 MVT I1ContainerVT = 5028 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5029 5030 SDValue CC = 5031 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5032 SDValue Op1 = 5033 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5034 SDValue Op2 = 5035 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5036 5037 SDLoc DL(Op); 5038 SDValue Mask, VL; 5039 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5040 5041 SDValue Select = 5042 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5043 5044 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5045 } 5046 5047 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5048 unsigned NewOpc, 5049 bool HasMask) const { 5050 MVT VT = Op.getSimpleValueType(); 5051 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5052 5053 // Create list of operands by converting existing ones to scalable types. 5054 SmallVector<SDValue, 6> Ops; 5055 for (const SDValue &V : Op->op_values()) { 5056 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5057 5058 // Pass through non-vector operands. 5059 if (!V.getValueType().isVector()) { 5060 Ops.push_back(V); 5061 continue; 5062 } 5063 5064 // "cast" fixed length vector to a scalable vector. 5065 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5066 "Only fixed length vectors are supported!"); 5067 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5068 } 5069 5070 SDLoc DL(Op); 5071 SDValue Mask, VL; 5072 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5073 if (HasMask) 5074 Ops.push_back(Mask); 5075 Ops.push_back(VL); 5076 5077 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5078 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5079 } 5080 5081 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5082 // * Operands of each node are assumed to be in the same order. 5083 // * The EVL operand is promoted from i32 to i64 on RV64. 5084 // * Fixed-length vectors are converted to their scalable-vector container 5085 // types. 5086 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5087 unsigned RISCVISDOpc) const { 5088 SDLoc DL(Op); 5089 MVT VT = Op.getSimpleValueType(); 5090 SmallVector<SDValue, 4> Ops; 5091 5092 for (const auto &OpIdx : enumerate(Op->ops())) { 5093 SDValue V = OpIdx.value(); 5094 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5095 // Pass through operands which aren't fixed-length vectors. 5096 if (!V.getValueType().isFixedLengthVector()) { 5097 Ops.push_back(V); 5098 continue; 5099 } 5100 // "cast" fixed length vector to a scalable vector. 5101 MVT OpVT = V.getSimpleValueType(); 5102 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5103 assert(useRVVForFixedLengthVectorVT(OpVT) && 5104 "Only fixed length vectors are supported!"); 5105 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5106 } 5107 5108 if (!VT.isFixedLengthVector()) 5109 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5110 5111 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5112 5113 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5114 5115 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5116 } 5117 5118 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5119 // matched to a RVV indexed load. The RVV indexed load instructions only 5120 // support the "unsigned unscaled" addressing mode; indices are implicitly 5121 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5122 // signed or scaled indexing is extended to the XLEN value type and scaled 5123 // accordingly. 5124 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5125 SelectionDAG &DAG) const { 5126 SDLoc DL(Op); 5127 MVT VT = Op.getSimpleValueType(); 5128 5129 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5130 EVT MemVT = MemSD->getMemoryVT(); 5131 MachineMemOperand *MMO = MemSD->getMemOperand(); 5132 SDValue Chain = MemSD->getChain(); 5133 SDValue BasePtr = MemSD->getBasePtr(); 5134 5135 ISD::LoadExtType LoadExtType; 5136 SDValue Index, Mask, PassThru, VL; 5137 5138 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5139 Index = VPGN->getIndex(); 5140 Mask = VPGN->getMask(); 5141 PassThru = DAG.getUNDEF(VT); 5142 VL = VPGN->getVectorLength(); 5143 // VP doesn't support extending loads. 5144 LoadExtType = ISD::NON_EXTLOAD; 5145 } else { 5146 // Else it must be a MGATHER. 5147 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5148 Index = MGN->getIndex(); 5149 Mask = MGN->getMask(); 5150 PassThru = MGN->getPassThru(); 5151 LoadExtType = MGN->getExtensionType(); 5152 } 5153 5154 MVT IndexVT = Index.getSimpleValueType(); 5155 MVT XLenVT = Subtarget.getXLenVT(); 5156 5157 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5158 "Unexpected VTs!"); 5159 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5160 // Targets have to explicitly opt-in for extending vector loads. 5161 assert(LoadExtType == ISD::NON_EXTLOAD && 5162 "Unexpected extending MGATHER/VP_GATHER"); 5163 (void)LoadExtType; 5164 5165 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5166 // the selection of the masked intrinsics doesn't do this for us. 5167 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5168 5169 MVT ContainerVT = VT; 5170 if (VT.isFixedLengthVector()) { 5171 // We need to use the larger of the result and index type to determine the 5172 // scalable type to use so we don't increase LMUL for any operand/result. 5173 if (VT.bitsGE(IndexVT)) { 5174 ContainerVT = getContainerForFixedLengthVector(VT); 5175 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5176 ContainerVT.getVectorElementCount()); 5177 } else { 5178 IndexVT = getContainerForFixedLengthVector(IndexVT); 5179 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5180 IndexVT.getVectorElementCount()); 5181 } 5182 5183 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5184 5185 if (!IsUnmasked) { 5186 MVT MaskVT = 5187 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5188 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5189 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5190 } 5191 } 5192 5193 if (!VL) 5194 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5195 5196 unsigned IntID = 5197 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5198 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5199 if (!IsUnmasked) 5200 Ops.push_back(PassThru); 5201 Ops.push_back(BasePtr); 5202 Ops.push_back(Index); 5203 if (!IsUnmasked) 5204 Ops.push_back(Mask); 5205 Ops.push_back(VL); 5206 5207 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5208 SDValue Result = 5209 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5210 Chain = Result.getValue(1); 5211 5212 if (VT.isFixedLengthVector()) 5213 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5214 5215 return DAG.getMergeValues({Result, Chain}, DL); 5216 } 5217 5218 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5219 // matched to a RVV indexed store. The RVV indexed store instructions only 5220 // support the "unsigned unscaled" addressing mode; indices are implicitly 5221 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5222 // signed or scaled indexing is extended to the XLEN value type and scaled 5223 // accordingly. 5224 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5225 SelectionDAG &DAG) const { 5226 SDLoc DL(Op); 5227 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5228 EVT MemVT = MemSD->getMemoryVT(); 5229 MachineMemOperand *MMO = MemSD->getMemOperand(); 5230 SDValue Chain = MemSD->getChain(); 5231 SDValue BasePtr = MemSD->getBasePtr(); 5232 5233 bool IsTruncatingStore = false; 5234 SDValue Index, Mask, Val, VL; 5235 5236 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5237 Index = VPSN->getIndex(); 5238 Mask = VPSN->getMask(); 5239 Val = VPSN->getValue(); 5240 VL = VPSN->getVectorLength(); 5241 // VP doesn't support truncating stores. 5242 IsTruncatingStore = false; 5243 } else { 5244 // Else it must be a MSCATTER. 5245 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5246 Index = MSN->getIndex(); 5247 Mask = MSN->getMask(); 5248 Val = MSN->getValue(); 5249 IsTruncatingStore = MSN->isTruncatingStore(); 5250 } 5251 5252 MVT VT = Val.getSimpleValueType(); 5253 MVT IndexVT = Index.getSimpleValueType(); 5254 MVT XLenVT = Subtarget.getXLenVT(); 5255 5256 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5257 "Unexpected VTs!"); 5258 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5259 // Targets have to explicitly opt-in for extending vector loads and 5260 // truncating vector stores. 5261 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5262 (void)IsTruncatingStore; 5263 5264 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5265 // the selection of the masked intrinsics doesn't do this for us. 5266 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5267 5268 MVT ContainerVT = VT; 5269 if (VT.isFixedLengthVector()) { 5270 // We need to use the larger of the value and index type to determine the 5271 // scalable type to use so we don't increase LMUL for any operand/result. 5272 if (VT.bitsGE(IndexVT)) { 5273 ContainerVT = getContainerForFixedLengthVector(VT); 5274 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5275 ContainerVT.getVectorElementCount()); 5276 } else { 5277 IndexVT = getContainerForFixedLengthVector(IndexVT); 5278 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 5279 IndexVT.getVectorElementCount()); 5280 } 5281 5282 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5283 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5284 5285 if (!IsUnmasked) { 5286 MVT MaskVT = 5287 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5288 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5289 } 5290 } 5291 5292 if (!VL) 5293 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5294 5295 unsigned IntID = 5296 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 5297 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5298 Ops.push_back(Val); 5299 Ops.push_back(BasePtr); 5300 Ops.push_back(Index); 5301 if (!IsUnmasked) 5302 Ops.push_back(Mask); 5303 Ops.push_back(VL); 5304 5305 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5306 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5307 } 5308 5309 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 5310 SelectionDAG &DAG) const { 5311 const MVT XLenVT = Subtarget.getXLenVT(); 5312 SDLoc DL(Op); 5313 SDValue Chain = Op->getOperand(0); 5314 SDValue SysRegNo = DAG.getConstant( 5315 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5316 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 5317 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 5318 5319 // Encoding used for rounding mode in RISCV differs from that used in 5320 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 5321 // table, which consists of a sequence of 4-bit fields, each representing 5322 // corresponding FLT_ROUNDS mode. 5323 static const int Table = 5324 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 5325 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 5326 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 5327 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 5328 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 5329 5330 SDValue Shift = 5331 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 5332 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5333 DAG.getConstant(Table, DL, XLenVT), Shift); 5334 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5335 DAG.getConstant(7, DL, XLenVT)); 5336 5337 return DAG.getMergeValues({Masked, Chain}, DL); 5338 } 5339 5340 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 5341 SelectionDAG &DAG) const { 5342 const MVT XLenVT = Subtarget.getXLenVT(); 5343 SDLoc DL(Op); 5344 SDValue Chain = Op->getOperand(0); 5345 SDValue RMValue = Op->getOperand(1); 5346 SDValue SysRegNo = DAG.getConstant( 5347 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5348 5349 // Encoding used for rounding mode in RISCV differs from that used in 5350 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 5351 // a table, which consists of a sequence of 4-bit fields, each representing 5352 // corresponding RISCV mode. 5353 static const unsigned Table = 5354 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 5355 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 5356 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 5357 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 5358 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 5359 5360 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 5361 DAG.getConstant(2, DL, XLenVT)); 5362 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5363 DAG.getConstant(Table, DL, XLenVT), Shift); 5364 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5365 DAG.getConstant(0x7, DL, XLenVT)); 5366 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 5367 RMValue); 5368 } 5369 5370 // Returns the opcode of the target-specific SDNode that implements the 32-bit 5371 // form of the given Opcode. 5372 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 5373 switch (Opcode) { 5374 default: 5375 llvm_unreachable("Unexpected opcode"); 5376 case ISD::SHL: 5377 return RISCVISD::SLLW; 5378 case ISD::SRA: 5379 return RISCVISD::SRAW; 5380 case ISD::SRL: 5381 return RISCVISD::SRLW; 5382 case ISD::SDIV: 5383 return RISCVISD::DIVW; 5384 case ISD::UDIV: 5385 return RISCVISD::DIVUW; 5386 case ISD::UREM: 5387 return RISCVISD::REMUW; 5388 case ISD::ROTL: 5389 return RISCVISD::ROLW; 5390 case ISD::ROTR: 5391 return RISCVISD::RORW; 5392 case RISCVISD::GREV: 5393 return RISCVISD::GREVW; 5394 case RISCVISD::GORC: 5395 return RISCVISD::GORCW; 5396 } 5397 } 5398 5399 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 5400 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 5401 // otherwise be promoted to i64, making it difficult to select the 5402 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 5403 // type i8/i16/i32 is lost. 5404 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 5405 unsigned ExtOpc = ISD::ANY_EXTEND) { 5406 SDLoc DL(N); 5407 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5408 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 5409 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 5410 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5411 // ReplaceNodeResults requires we maintain the same type for the return value. 5412 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 5413 } 5414 5415 // Converts the given 32-bit operation to a i64 operation with signed extension 5416 // semantic to reduce the signed extension instructions. 5417 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 5418 SDLoc DL(N); 5419 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5420 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5421 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 5422 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5423 DAG.getValueType(MVT::i32)); 5424 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 5425 } 5426 5427 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 5428 SmallVectorImpl<SDValue> &Results, 5429 SelectionDAG &DAG) const { 5430 SDLoc DL(N); 5431 switch (N->getOpcode()) { 5432 default: 5433 llvm_unreachable("Don't know how to custom type legalize this operation!"); 5434 case ISD::STRICT_FP_TO_SINT: 5435 case ISD::STRICT_FP_TO_UINT: 5436 case ISD::FP_TO_SINT: 5437 case ISD::FP_TO_UINT: { 5438 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5439 "Unexpected custom legalisation"); 5440 bool IsStrict = N->isStrictFPOpcode(); 5441 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 5442 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 5443 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 5444 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 5445 TargetLowering::TypeSoftenFloat) { 5446 // FIXME: Support strict FP. 5447 if (IsStrict) 5448 return; 5449 if (!isTypeLegal(Op0.getValueType())) 5450 return; 5451 unsigned Opc = 5452 IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 5453 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0); 5454 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5455 return; 5456 } 5457 // If the FP type needs to be softened, emit a library call using the 'si' 5458 // version. If we left it to default legalization we'd end up with 'di'. If 5459 // the FP type doesn't need to be softened just let generic type 5460 // legalization promote the result type. 5461 RTLIB::Libcall LC; 5462 if (IsSigned) 5463 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 5464 else 5465 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 5466 MakeLibCallOptions CallOptions; 5467 EVT OpVT = Op0.getValueType(); 5468 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 5469 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 5470 SDValue Result; 5471 std::tie(Result, Chain) = 5472 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 5473 Results.push_back(Result); 5474 if (IsStrict) 5475 Results.push_back(Chain); 5476 break; 5477 } 5478 case ISD::READCYCLECOUNTER: { 5479 assert(!Subtarget.is64Bit() && 5480 "READCYCLECOUNTER only has custom type legalization on riscv32"); 5481 5482 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 5483 SDValue RCW = 5484 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 5485 5486 Results.push_back( 5487 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 5488 Results.push_back(RCW.getValue(2)); 5489 break; 5490 } 5491 case ISD::MUL: { 5492 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 5493 unsigned XLen = Subtarget.getXLen(); 5494 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 5495 if (Size > XLen) { 5496 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 5497 SDValue LHS = N->getOperand(0); 5498 SDValue RHS = N->getOperand(1); 5499 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 5500 5501 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 5502 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 5503 // We need exactly one side to be unsigned. 5504 if (LHSIsU == RHSIsU) 5505 return; 5506 5507 auto MakeMULPair = [&](SDValue S, SDValue U) { 5508 MVT XLenVT = Subtarget.getXLenVT(); 5509 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 5510 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 5511 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 5512 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 5513 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 5514 }; 5515 5516 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 5517 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 5518 5519 // The other operand should be signed, but still prefer MULH when 5520 // possible. 5521 if (RHSIsU && LHSIsS && !RHSIsS) 5522 Results.push_back(MakeMULPair(LHS, RHS)); 5523 else if (LHSIsU && RHSIsS && !LHSIsS) 5524 Results.push_back(MakeMULPair(RHS, LHS)); 5525 5526 return; 5527 } 5528 LLVM_FALLTHROUGH; 5529 } 5530 case ISD::ADD: 5531 case ISD::SUB: 5532 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5533 "Unexpected custom legalisation"); 5534 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 5535 break; 5536 case ISD::SHL: 5537 case ISD::SRA: 5538 case ISD::SRL: 5539 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5540 "Unexpected custom legalisation"); 5541 if (N->getOperand(1).getOpcode() != ISD::Constant) { 5542 Results.push_back(customLegalizeToWOp(N, DAG)); 5543 break; 5544 } 5545 5546 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 5547 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 5548 // shift amount. 5549 if (N->getOpcode() == ISD::SHL) { 5550 SDLoc DL(N); 5551 SDValue NewOp0 = 5552 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5553 SDValue NewOp1 = 5554 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 5555 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 5556 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5557 DAG.getValueType(MVT::i32)); 5558 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5559 } 5560 5561 break; 5562 case ISD::ROTL: 5563 case ISD::ROTR: 5564 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5565 "Unexpected custom legalisation"); 5566 Results.push_back(customLegalizeToWOp(N, DAG)); 5567 break; 5568 case ISD::CTTZ: 5569 case ISD::CTTZ_ZERO_UNDEF: 5570 case ISD::CTLZ: 5571 case ISD::CTLZ_ZERO_UNDEF: { 5572 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5573 "Unexpected custom legalisation"); 5574 5575 SDValue NewOp0 = 5576 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5577 bool IsCTZ = 5578 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 5579 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 5580 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 5581 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5582 return; 5583 } 5584 case ISD::SDIV: 5585 case ISD::UDIV: 5586 case ISD::UREM: { 5587 MVT VT = N->getSimpleValueType(0); 5588 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 5589 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 5590 "Unexpected custom legalisation"); 5591 // Don't promote division/remainder by constant since we should expand those 5592 // to multiply by magic constant. 5593 // FIXME: What if the expansion is disabled for minsize. 5594 if (N->getOperand(1).getOpcode() == ISD::Constant) 5595 return; 5596 5597 // If the input is i32, use ANY_EXTEND since the W instructions don't read 5598 // the upper 32 bits. For other types we need to sign or zero extend 5599 // based on the opcode. 5600 unsigned ExtOpc = ISD::ANY_EXTEND; 5601 if (VT != MVT::i32) 5602 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 5603 : ISD::ZERO_EXTEND; 5604 5605 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 5606 break; 5607 } 5608 case ISD::UADDO: 5609 case ISD::USUBO: { 5610 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5611 "Unexpected custom legalisation"); 5612 bool IsAdd = N->getOpcode() == ISD::UADDO; 5613 // Create an ADDW or SUBW. 5614 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5615 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5616 SDValue Res = 5617 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 5618 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 5619 DAG.getValueType(MVT::i32)); 5620 5621 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 5622 // Since the inputs are sign extended from i32, this is equivalent to 5623 // comparing the lower 32 bits. 5624 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5625 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 5626 IsAdd ? ISD::SETULT : ISD::SETUGT); 5627 5628 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5629 Results.push_back(Overflow); 5630 return; 5631 } 5632 case ISD::UADDSAT: 5633 case ISD::USUBSAT: { 5634 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5635 "Unexpected custom legalisation"); 5636 if (Subtarget.hasStdExtZbb()) { 5637 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 5638 // sign extend allows overflow of the lower 32 bits to be detected on 5639 // the promoted size. 5640 SDValue LHS = 5641 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5642 SDValue RHS = 5643 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 5644 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 5645 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5646 return; 5647 } 5648 5649 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 5650 // promotion for UADDO/USUBO. 5651 Results.push_back(expandAddSubSat(N, DAG)); 5652 return; 5653 } 5654 case ISD::BITCAST: { 5655 EVT VT = N->getValueType(0); 5656 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 5657 SDValue Op0 = N->getOperand(0); 5658 EVT Op0VT = Op0.getValueType(); 5659 MVT XLenVT = Subtarget.getXLenVT(); 5660 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 5661 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 5662 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 5663 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 5664 Subtarget.hasStdExtF()) { 5665 SDValue FPConv = 5666 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 5667 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 5668 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 5669 isTypeLegal(Op0VT)) { 5670 // Custom-legalize bitcasts from fixed-length vector types to illegal 5671 // scalar types in order to improve codegen. Bitcast the vector to a 5672 // one-element vector type whose element type is the same as the result 5673 // type, and extract the first element. 5674 LLVMContext &Context = *DAG.getContext(); 5675 SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0); 5676 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 5677 DAG.getConstant(0, DL, XLenVT))); 5678 } 5679 break; 5680 } 5681 case RISCVISD::GREV: 5682 case RISCVISD::GORC: { 5683 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5684 "Unexpected custom legalisation"); 5685 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 5686 // This is similar to customLegalizeToWOp, except that we pass the second 5687 // operand (a TargetConstant) straight through: it is already of type 5688 // XLenVT. 5689 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5690 SDValue NewOp0 = 5691 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5692 SDValue NewOp1 = 5693 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5694 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5695 // ReplaceNodeResults requires we maintain the same type for the return 5696 // value. 5697 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5698 break; 5699 } 5700 case RISCVISD::SHFL: { 5701 // There is no SHFLIW instruction, but we can just promote the operation. 5702 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5703 "Unexpected custom legalisation"); 5704 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 5705 SDValue NewOp0 = 5706 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5707 SDValue NewOp1 = 5708 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5709 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 5710 // ReplaceNodeResults requires we maintain the same type for the return 5711 // value. 5712 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5713 break; 5714 } 5715 case ISD::BSWAP: 5716 case ISD::BITREVERSE: { 5717 MVT VT = N->getSimpleValueType(0); 5718 MVT XLenVT = Subtarget.getXLenVT(); 5719 assert((VT == MVT::i8 || VT == MVT::i16 || 5720 (VT == MVT::i32 && Subtarget.is64Bit())) && 5721 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 5722 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 5723 unsigned Imm = VT.getSizeInBits() - 1; 5724 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 5725 if (N->getOpcode() == ISD::BSWAP) 5726 Imm &= ~0x7U; 5727 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 5728 SDValue GREVI = 5729 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 5730 // ReplaceNodeResults requires we maintain the same type for the return 5731 // value. 5732 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 5733 break; 5734 } 5735 case ISD::FSHL: 5736 case ISD::FSHR: { 5737 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5738 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 5739 SDValue NewOp0 = 5740 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5741 SDValue NewOp1 = 5742 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5743 SDValue NewOp2 = 5744 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5745 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 5746 // Mask the shift amount to 5 bits. 5747 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 5748 DAG.getConstant(0x1f, DL, MVT::i64)); 5749 unsigned Opc = 5750 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 5751 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 5752 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 5753 break; 5754 } 5755 case ISD::EXTRACT_VECTOR_ELT: { 5756 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 5757 // type is illegal (currently only vXi64 RV32). 5758 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 5759 // transferred to the destination register. We issue two of these from the 5760 // upper- and lower- halves of the SEW-bit vector element, slid down to the 5761 // first element. 5762 SDValue Vec = N->getOperand(0); 5763 SDValue Idx = N->getOperand(1); 5764 5765 // The vector type hasn't been legalized yet so we can't issue target 5766 // specific nodes if it needs legalization. 5767 // FIXME: We would manually legalize if it's important. 5768 if (!isTypeLegal(Vec.getValueType())) 5769 return; 5770 5771 MVT VecVT = Vec.getSimpleValueType(); 5772 5773 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 5774 VecVT.getVectorElementType() == MVT::i64 && 5775 "Unexpected EXTRACT_VECTOR_ELT legalization"); 5776 5777 // If this is a fixed vector, we need to convert it to a scalable vector. 5778 MVT ContainerVT = VecVT; 5779 if (VecVT.isFixedLengthVector()) { 5780 ContainerVT = getContainerForFixedLengthVector(VecVT); 5781 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5782 } 5783 5784 MVT XLenVT = Subtarget.getXLenVT(); 5785 5786 // Use a VL of 1 to avoid processing more elements than we need. 5787 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5788 SDValue VL = DAG.getConstant(1, DL, XLenVT); 5789 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5790 5791 // Unless the index is known to be 0, we must slide the vector down to get 5792 // the desired element into index 0. 5793 if (!isNullConstant(Idx)) { 5794 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5795 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 5796 } 5797 5798 // Extract the lower XLEN bits of the correct vector element. 5799 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 5800 5801 // To extract the upper XLEN bits of the vector element, shift the first 5802 // element right by 32 bits and re-extract the lower XLEN bits. 5803 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5804 DAG.getConstant(32, DL, XLenVT), VL); 5805 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 5806 ThirtyTwoV, Mask, VL); 5807 5808 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 5809 5810 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 5811 break; 5812 } 5813 case ISD::INTRINSIC_WO_CHAIN: { 5814 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5815 switch (IntNo) { 5816 default: 5817 llvm_unreachable( 5818 "Don't know how to custom type legalize this intrinsic!"); 5819 case Intrinsic::riscv_orc_b: { 5820 // Lower to the GORCI encoding for orc.b with the operand extended. 5821 SDValue NewOp = 5822 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5823 // If Zbp is enabled, use GORCIW which will sign extend the result. 5824 unsigned Opc = 5825 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 5826 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 5827 DAG.getConstant(7, DL, MVT::i64)); 5828 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5829 return; 5830 } 5831 case Intrinsic::riscv_grev: 5832 case Intrinsic::riscv_gorc: { 5833 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5834 "Unexpected custom legalisation"); 5835 SDValue NewOp1 = 5836 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5837 SDValue NewOp2 = 5838 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5839 unsigned Opc = 5840 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 5841 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5842 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5843 break; 5844 } 5845 case Intrinsic::riscv_shfl: 5846 case Intrinsic::riscv_unshfl: { 5847 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5848 "Unexpected custom legalisation"); 5849 SDValue NewOp1 = 5850 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5851 SDValue NewOp2 = 5852 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5853 unsigned Opc = 5854 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 5855 if (isa<ConstantSDNode>(N->getOperand(2))) { 5856 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 5857 DAG.getConstant(0xf, DL, MVT::i64)); 5858 Opc = 5859 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 5860 } 5861 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5862 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5863 break; 5864 } 5865 case Intrinsic::riscv_bcompress: 5866 case Intrinsic::riscv_bdecompress: { 5867 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5868 "Unexpected custom legalisation"); 5869 SDValue NewOp1 = 5870 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5871 SDValue NewOp2 = 5872 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5873 unsigned Opc = IntNo == Intrinsic::riscv_bcompress 5874 ? RISCVISD::BCOMPRESSW 5875 : RISCVISD::BDECOMPRESSW; 5876 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5877 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5878 break; 5879 } 5880 case Intrinsic::riscv_vmv_x_s: { 5881 EVT VT = N->getValueType(0); 5882 MVT XLenVT = Subtarget.getXLenVT(); 5883 if (VT.bitsLT(XLenVT)) { 5884 // Simple case just extract using vmv.x.s and truncate. 5885 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 5886 Subtarget.getXLenVT(), N->getOperand(1)); 5887 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 5888 return; 5889 } 5890 5891 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 5892 "Unexpected custom legalization"); 5893 5894 // We need to do the move in two steps. 5895 SDValue Vec = N->getOperand(1); 5896 MVT VecVT = Vec.getSimpleValueType(); 5897 5898 // First extract the lower XLEN bits of the element. 5899 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 5900 5901 // To extract the upper XLEN bits of the vector element, shift the first 5902 // element right by 32 bits and re-extract the lower XLEN bits. 5903 SDValue VL = DAG.getConstant(1, DL, XLenVT); 5904 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5905 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5906 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 5907 DAG.getConstant(32, DL, XLenVT), VL); 5908 SDValue LShr32 = 5909 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 5910 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 5911 5912 Results.push_back( 5913 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 5914 break; 5915 } 5916 } 5917 break; 5918 } 5919 case ISD::VECREDUCE_ADD: 5920 case ISD::VECREDUCE_AND: 5921 case ISD::VECREDUCE_OR: 5922 case ISD::VECREDUCE_XOR: 5923 case ISD::VECREDUCE_SMAX: 5924 case ISD::VECREDUCE_UMAX: 5925 case ISD::VECREDUCE_SMIN: 5926 case ISD::VECREDUCE_UMIN: 5927 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 5928 Results.push_back(V); 5929 break; 5930 case ISD::VP_REDUCE_ADD: 5931 case ISD::VP_REDUCE_AND: 5932 case ISD::VP_REDUCE_OR: 5933 case ISD::VP_REDUCE_XOR: 5934 case ISD::VP_REDUCE_SMAX: 5935 case ISD::VP_REDUCE_UMAX: 5936 case ISD::VP_REDUCE_SMIN: 5937 case ISD::VP_REDUCE_UMIN: 5938 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 5939 Results.push_back(V); 5940 break; 5941 case ISD::FLT_ROUNDS_: { 5942 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 5943 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 5944 Results.push_back(Res.getValue(0)); 5945 Results.push_back(Res.getValue(1)); 5946 break; 5947 } 5948 } 5949 } 5950 5951 // A structure to hold one of the bit-manipulation patterns below. Together, a 5952 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 5953 // (or (and (shl x, 1), 0xAAAAAAAA), 5954 // (and (srl x, 1), 0x55555555)) 5955 struct RISCVBitmanipPat { 5956 SDValue Op; 5957 unsigned ShAmt; 5958 bool IsSHL; 5959 5960 bool formsPairWith(const RISCVBitmanipPat &Other) const { 5961 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 5962 } 5963 }; 5964 5965 // Matches patterns of the form 5966 // (and (shl x, C2), (C1 << C2)) 5967 // (and (srl x, C2), C1) 5968 // (shl (and x, C1), C2) 5969 // (srl (and x, (C1 << C2)), C2) 5970 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 5971 // The expected masks for each shift amount are specified in BitmanipMasks where 5972 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 5973 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 5974 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 5975 // XLen is 64. 5976 static Optional<RISCVBitmanipPat> 5977 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 5978 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 5979 "Unexpected number of masks"); 5980 Optional<uint64_t> Mask; 5981 // Optionally consume a mask around the shift operation. 5982 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 5983 Mask = Op.getConstantOperandVal(1); 5984 Op = Op.getOperand(0); 5985 } 5986 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 5987 return None; 5988 bool IsSHL = Op.getOpcode() == ISD::SHL; 5989 5990 if (!isa<ConstantSDNode>(Op.getOperand(1))) 5991 return None; 5992 uint64_t ShAmt = Op.getConstantOperandVal(1); 5993 5994 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 5995 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 5996 return None; 5997 // If we don't have enough masks for 64 bit, then we must be trying to 5998 // match SHFL so we're only allowed to shift 1/4 of the width. 5999 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6000 return None; 6001 6002 SDValue Src = Op.getOperand(0); 6003 6004 // The expected mask is shifted left when the AND is found around SHL 6005 // patterns. 6006 // ((x >> 1) & 0x55555555) 6007 // ((x << 1) & 0xAAAAAAAA) 6008 bool SHLExpMask = IsSHL; 6009 6010 if (!Mask) { 6011 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6012 // the mask is all ones: consume that now. 6013 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6014 Mask = Src.getConstantOperandVal(1); 6015 Src = Src.getOperand(0); 6016 // The expected mask is now in fact shifted left for SRL, so reverse the 6017 // decision. 6018 // ((x & 0xAAAAAAAA) >> 1) 6019 // ((x & 0x55555555) << 1) 6020 SHLExpMask = !SHLExpMask; 6021 } else { 6022 // Use a default shifted mask of all-ones if there's no AND, truncated 6023 // down to the expected width. This simplifies the logic later on. 6024 Mask = maskTrailingOnes<uint64_t>(Width); 6025 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6026 } 6027 } 6028 6029 unsigned MaskIdx = Log2_32(ShAmt); 6030 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6031 6032 if (SHLExpMask) 6033 ExpMask <<= ShAmt; 6034 6035 if (Mask != ExpMask) 6036 return None; 6037 6038 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6039 } 6040 6041 // Matches any of the following bit-manipulation patterns: 6042 // (and (shl x, 1), (0x55555555 << 1)) 6043 // (and (srl x, 1), 0x55555555) 6044 // (shl (and x, 0x55555555), 1) 6045 // (srl (and x, (0x55555555 << 1)), 1) 6046 // where the shift amount and mask may vary thus: 6047 // [1] = 0x55555555 / 0xAAAAAAAA 6048 // [2] = 0x33333333 / 0xCCCCCCCC 6049 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6050 // [8] = 0x00FF00FF / 0xFF00FF00 6051 // [16] = 0x0000FFFF / 0xFFFFFFFF 6052 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6053 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6054 // These are the unshifted masks which we use to match bit-manipulation 6055 // patterns. They may be shifted left in certain circumstances. 6056 static const uint64_t BitmanipMasks[] = { 6057 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6058 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6059 6060 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6061 } 6062 6063 // Match the following pattern as a GREVI(W) operation 6064 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6065 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6066 const RISCVSubtarget &Subtarget) { 6067 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6068 EVT VT = Op.getValueType(); 6069 6070 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6071 auto LHS = matchGREVIPat(Op.getOperand(0)); 6072 auto RHS = matchGREVIPat(Op.getOperand(1)); 6073 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6074 SDLoc DL(Op); 6075 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6076 DAG.getConstant(LHS->ShAmt, DL, VT)); 6077 } 6078 } 6079 return SDValue(); 6080 } 6081 6082 // Matches any the following pattern as a GORCI(W) operation 6083 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6084 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6085 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6086 // Note that with the variant of 3., 6087 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6088 // the inner pattern will first be matched as GREVI and then the outer 6089 // pattern will be matched to GORC via the first rule above. 6090 // 4. (or (rotl/rotr x, bitwidth/2), x) 6091 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6092 const RISCVSubtarget &Subtarget) { 6093 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6094 EVT VT = Op.getValueType(); 6095 6096 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6097 SDLoc DL(Op); 6098 SDValue Op0 = Op.getOperand(0); 6099 SDValue Op1 = Op.getOperand(1); 6100 6101 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6102 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6103 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6104 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6105 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6106 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6107 if ((Reverse.getOpcode() == ISD::ROTL || 6108 Reverse.getOpcode() == ISD::ROTR) && 6109 Reverse.getOperand(0) == X && 6110 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6111 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6112 if (RotAmt == (VT.getSizeInBits() / 2)) 6113 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6114 DAG.getConstant(RotAmt, DL, VT)); 6115 } 6116 return SDValue(); 6117 }; 6118 6119 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6120 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6121 return V; 6122 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6123 return V; 6124 6125 // OR is commutable so canonicalize its OR operand to the left 6126 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6127 std::swap(Op0, Op1); 6128 if (Op0.getOpcode() != ISD::OR) 6129 return SDValue(); 6130 SDValue OrOp0 = Op0.getOperand(0); 6131 SDValue OrOp1 = Op0.getOperand(1); 6132 auto LHS = matchGREVIPat(OrOp0); 6133 // OR is commutable so swap the operands and try again: x might have been 6134 // on the left 6135 if (!LHS) { 6136 std::swap(OrOp0, OrOp1); 6137 LHS = matchGREVIPat(OrOp0); 6138 } 6139 auto RHS = matchGREVIPat(Op1); 6140 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6141 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6142 DAG.getConstant(LHS->ShAmt, DL, VT)); 6143 } 6144 } 6145 return SDValue(); 6146 } 6147 6148 // Matches any of the following bit-manipulation patterns: 6149 // (and (shl x, 1), (0x22222222 << 1)) 6150 // (and (srl x, 1), 0x22222222) 6151 // (shl (and x, 0x22222222), 1) 6152 // (srl (and x, (0x22222222 << 1)), 1) 6153 // where the shift amount and mask may vary thus: 6154 // [1] = 0x22222222 / 0x44444444 6155 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6156 // [4] = 0x00F000F0 / 0x0F000F00 6157 // [8] = 0x0000FF00 / 0x00FF0000 6158 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6159 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6160 // These are the unshifted masks which we use to match bit-manipulation 6161 // patterns. They may be shifted left in certain circumstances. 6162 static const uint64_t BitmanipMasks[] = { 6163 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6164 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6165 6166 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6167 } 6168 6169 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6170 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6171 const RISCVSubtarget &Subtarget) { 6172 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6173 EVT VT = Op.getValueType(); 6174 6175 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6176 return SDValue(); 6177 6178 SDValue Op0 = Op.getOperand(0); 6179 SDValue Op1 = Op.getOperand(1); 6180 6181 // Or is commutable so canonicalize the second OR to the LHS. 6182 if (Op0.getOpcode() != ISD::OR) 6183 std::swap(Op0, Op1); 6184 if (Op0.getOpcode() != ISD::OR) 6185 return SDValue(); 6186 6187 // We found an inner OR, so our operands are the operands of the inner OR 6188 // and the other operand of the outer OR. 6189 SDValue A = Op0.getOperand(0); 6190 SDValue B = Op0.getOperand(1); 6191 SDValue C = Op1; 6192 6193 auto Match1 = matchSHFLPat(A); 6194 auto Match2 = matchSHFLPat(B); 6195 6196 // If neither matched, we failed. 6197 if (!Match1 && !Match2) 6198 return SDValue(); 6199 6200 // We had at least one match. if one failed, try the remaining C operand. 6201 if (!Match1) { 6202 std::swap(A, C); 6203 Match1 = matchSHFLPat(A); 6204 if (!Match1) 6205 return SDValue(); 6206 } else if (!Match2) { 6207 std::swap(B, C); 6208 Match2 = matchSHFLPat(B); 6209 if (!Match2) 6210 return SDValue(); 6211 } 6212 assert(Match1 && Match2); 6213 6214 // Make sure our matches pair up. 6215 if (!Match1->formsPairWith(*Match2)) 6216 return SDValue(); 6217 6218 // All the remains is to make sure C is an AND with the same input, that masks 6219 // out the bits that are being shuffled. 6220 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 6221 C.getOperand(0) != Match1->Op) 6222 return SDValue(); 6223 6224 uint64_t Mask = C.getConstantOperandVal(1); 6225 6226 static const uint64_t BitmanipMasks[] = { 6227 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 6228 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 6229 }; 6230 6231 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6232 unsigned MaskIdx = Log2_32(Match1->ShAmt); 6233 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6234 6235 if (Mask != ExpMask) 6236 return SDValue(); 6237 6238 SDLoc DL(Op); 6239 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 6240 DAG.getConstant(Match1->ShAmt, DL, VT)); 6241 } 6242 6243 // Optimize (add (shl x, c0), (shl y, c1)) -> 6244 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 6245 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 6246 const RISCVSubtarget &Subtarget) { 6247 // Perform this optimization only in the zba extension. 6248 if (!Subtarget.hasStdExtZba()) 6249 return SDValue(); 6250 6251 // Skip for vector types and larger types. 6252 EVT VT = N->getValueType(0); 6253 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6254 return SDValue(); 6255 6256 // The two operand nodes must be SHL and have no other use. 6257 SDValue N0 = N->getOperand(0); 6258 SDValue N1 = N->getOperand(1); 6259 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 6260 !N0->hasOneUse() || !N1->hasOneUse()) 6261 return SDValue(); 6262 6263 // Check c0 and c1. 6264 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6265 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 6266 if (!N0C || !N1C) 6267 return SDValue(); 6268 int64_t C0 = N0C->getSExtValue(); 6269 int64_t C1 = N1C->getSExtValue(); 6270 if (C0 <= 0 || C1 <= 0) 6271 return SDValue(); 6272 6273 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 6274 int64_t Bits = std::min(C0, C1); 6275 int64_t Diff = std::abs(C0 - C1); 6276 if (Diff != 1 && Diff != 2 && Diff != 3) 6277 return SDValue(); 6278 6279 // Build nodes. 6280 SDLoc DL(N); 6281 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 6282 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 6283 SDValue NA0 = 6284 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 6285 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 6286 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 6287 } 6288 6289 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 6290 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 6291 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 6292 // not undo itself, but they are redundant. 6293 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 6294 SDValue Src = N->getOperand(0); 6295 6296 if (Src.getOpcode() != N->getOpcode()) 6297 return SDValue(); 6298 6299 if (!isa<ConstantSDNode>(N->getOperand(1)) || 6300 !isa<ConstantSDNode>(Src.getOperand(1))) 6301 return SDValue(); 6302 6303 unsigned ShAmt1 = N->getConstantOperandVal(1); 6304 unsigned ShAmt2 = Src.getConstantOperandVal(1); 6305 Src = Src.getOperand(0); 6306 6307 unsigned CombinedShAmt; 6308 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 6309 CombinedShAmt = ShAmt1 | ShAmt2; 6310 else 6311 CombinedShAmt = ShAmt1 ^ ShAmt2; 6312 6313 if (CombinedShAmt == 0) 6314 return Src; 6315 6316 SDLoc DL(N); 6317 return DAG.getNode( 6318 N->getOpcode(), DL, N->getValueType(0), Src, 6319 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 6320 } 6321 6322 // Combine a constant select operand into its use: 6323 // 6324 // (and (select cond, -1, c), x) 6325 // -> (select cond, x, (and x, c)) [AllOnes=1] 6326 // (or (select cond, 0, c), x) 6327 // -> (select cond, x, (or x, c)) [AllOnes=0] 6328 // (xor (select cond, 0, c), x) 6329 // -> (select cond, x, (xor x, c)) [AllOnes=0] 6330 // (add (select cond, 0, c), x) 6331 // -> (select cond, x, (add x, c)) [AllOnes=0] 6332 // (sub x, (select cond, 0, c)) 6333 // -> (select cond, x, (sub x, c)) [AllOnes=0] 6334 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 6335 SelectionDAG &DAG, bool AllOnes) { 6336 EVT VT = N->getValueType(0); 6337 6338 // Skip vectors. 6339 if (VT.isVector()) 6340 return SDValue(); 6341 6342 if ((Slct.getOpcode() != ISD::SELECT && 6343 Slct.getOpcode() != RISCVISD::SELECT_CC) || 6344 !Slct.hasOneUse()) 6345 return SDValue(); 6346 6347 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 6348 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 6349 }; 6350 6351 bool SwapSelectOps; 6352 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 6353 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 6354 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 6355 SDValue NonConstantVal; 6356 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 6357 SwapSelectOps = false; 6358 NonConstantVal = FalseVal; 6359 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 6360 SwapSelectOps = true; 6361 NonConstantVal = TrueVal; 6362 } else 6363 return SDValue(); 6364 6365 // Slct is now know to be the desired identity constant when CC is true. 6366 TrueVal = OtherOp; 6367 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 6368 // Unless SwapSelectOps says the condition should be false. 6369 if (SwapSelectOps) 6370 std::swap(TrueVal, FalseVal); 6371 6372 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 6373 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 6374 {Slct.getOperand(0), Slct.getOperand(1), 6375 Slct.getOperand(2), TrueVal, FalseVal}); 6376 6377 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 6378 {Slct.getOperand(0), TrueVal, FalseVal}); 6379 } 6380 6381 // Attempt combineSelectAndUse on each operand of a commutative operator N. 6382 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 6383 bool AllOnes) { 6384 SDValue N0 = N->getOperand(0); 6385 SDValue N1 = N->getOperand(1); 6386 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 6387 return Result; 6388 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 6389 return Result; 6390 return SDValue(); 6391 } 6392 6393 // Transform (add (mul x, c0), c1) -> 6394 // (add (mul (add x, c1/c0), c0), c1%c0). 6395 // if c1/c0 and c1%c0 are simm12, while c1 is not. 6396 // Or transform (add (mul x, c0), c1) -> 6397 // (mul (add x, c1/c0), c0). 6398 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 6399 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 6400 const RISCVSubtarget &Subtarget) { 6401 // Skip for vector types and larger types. 6402 EVT VT = N->getValueType(0); 6403 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6404 return SDValue(); 6405 // The first operand node must be a MUL and has no other use. 6406 SDValue N0 = N->getOperand(0); 6407 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 6408 return SDValue(); 6409 // Check if c0 and c1 match above conditions. 6410 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6411 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6412 if (!N0C || !N1C) 6413 return SDValue(); 6414 int64_t C0 = N0C->getSExtValue(); 6415 int64_t C1 = N1C->getSExtValue(); 6416 if (C0 == -1 || C0 == 0 || C0 == 1 || (C1 / C0) == 0 || isInt<12>(C1) || 6417 !isInt<12>(C1 % C0) || !isInt<12>(C1 / C0)) 6418 return SDValue(); 6419 // If C0 * (C1 / C0) is a 12-bit integer, this transform will be reversed. 6420 if (isInt<12>(C0 * (C1 / C0))) 6421 return SDValue(); 6422 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 6423 SDLoc DL(N); 6424 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 6425 DAG.getConstant(C1 / C0, DL, VT)); 6426 SDValue New1 = 6427 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 6428 if ((C1 % C0) == 0) 6429 return New1; 6430 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(C1 % C0, DL, VT)); 6431 } 6432 6433 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 6434 const RISCVSubtarget &Subtarget) { 6435 // Transform (add (mul x, c0), c1) -> 6436 // (add (mul (add x, c1/c0), c0), c1%c0). 6437 // if c1/c0 and c1%c0 are simm12, while c1 is not. 6438 // Or transform (add (mul x, c0), c1) -> 6439 // (mul (add x, c1/c0), c0). 6440 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 6441 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 6442 return V; 6443 // Fold (add (shl x, c0), (shl y, c1)) -> 6444 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 6445 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 6446 return V; 6447 // fold (add (select lhs, rhs, cc, 0, y), x) -> 6448 // (select lhs, rhs, cc, x, (add x, y)) 6449 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6450 } 6451 6452 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 6453 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 6454 // (select lhs, rhs, cc, x, (sub x, y)) 6455 SDValue N0 = N->getOperand(0); 6456 SDValue N1 = N->getOperand(1); 6457 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 6458 } 6459 6460 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 6461 // fold (and (select lhs, rhs, cc, -1, y), x) -> 6462 // (select lhs, rhs, cc, x, (and x, y)) 6463 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 6464 } 6465 6466 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 6467 const RISCVSubtarget &Subtarget) { 6468 if (Subtarget.hasStdExtZbp()) { 6469 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 6470 return GREV; 6471 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 6472 return GORC; 6473 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 6474 return SHFL; 6475 } 6476 6477 // fold (or (select cond, 0, y), x) -> 6478 // (select cond, x, (or x, y)) 6479 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6480 } 6481 6482 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 6483 // fold (xor (select cond, 0, y), x) -> 6484 // (select cond, x, (xor x, y)) 6485 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6486 } 6487 6488 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 6489 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 6490 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 6491 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 6492 // ADDW/SUBW/MULW. 6493 static SDValue performANY_EXTENDCombine(SDNode *N, 6494 TargetLowering::DAGCombinerInfo &DCI, 6495 const RISCVSubtarget &Subtarget) { 6496 if (!Subtarget.is64Bit()) 6497 return SDValue(); 6498 6499 SelectionDAG &DAG = DCI.DAG; 6500 6501 SDValue Src = N->getOperand(0); 6502 EVT VT = N->getValueType(0); 6503 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 6504 return SDValue(); 6505 6506 // The opcode must be one that can implicitly sign_extend. 6507 // FIXME: Additional opcodes. 6508 switch (Src.getOpcode()) { 6509 default: 6510 return SDValue(); 6511 case ISD::MUL: 6512 if (!Subtarget.hasStdExtM()) 6513 return SDValue(); 6514 LLVM_FALLTHROUGH; 6515 case ISD::ADD: 6516 case ISD::SUB: 6517 break; 6518 } 6519 6520 // Only handle cases where the result is used by a CopyToReg. That likely 6521 // means the value is a liveout of the basic block. This helps prevent 6522 // infinite combine loops like PR51206. 6523 if (none_of(N->uses(), 6524 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 6525 return SDValue(); 6526 6527 SmallVector<SDNode *, 4> SetCCs; 6528 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 6529 UE = Src.getNode()->use_end(); 6530 UI != UE; ++UI) { 6531 SDNode *User = *UI; 6532 if (User == N) 6533 continue; 6534 if (UI.getUse().getResNo() != Src.getResNo()) 6535 continue; 6536 // All i32 setccs are legalized by sign extending operands. 6537 if (User->getOpcode() == ISD::SETCC) { 6538 SetCCs.push_back(User); 6539 continue; 6540 } 6541 // We don't know if we can extend this user. 6542 break; 6543 } 6544 6545 // If we don't have any SetCCs, this isn't worthwhile. 6546 if (SetCCs.empty()) 6547 return SDValue(); 6548 6549 SDLoc DL(N); 6550 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 6551 DCI.CombineTo(N, SExt); 6552 6553 // Promote all the setccs. 6554 for (SDNode *SetCC : SetCCs) { 6555 SmallVector<SDValue, 4> Ops; 6556 6557 for (unsigned j = 0; j != 2; ++j) { 6558 SDValue SOp = SetCC->getOperand(j); 6559 if (SOp == Src) 6560 Ops.push_back(SExt); 6561 else 6562 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 6563 } 6564 6565 Ops.push_back(SetCC->getOperand(2)); 6566 DCI.CombineTo(SetCC, 6567 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6568 } 6569 return SDValue(N, 0); 6570 } 6571 6572 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 6573 DAGCombinerInfo &DCI) const { 6574 SelectionDAG &DAG = DCI.DAG; 6575 6576 // Helper to call SimplifyDemandedBits on an operand of N where only some low 6577 // bits are demanded. N will be added to the Worklist if it was not deleted. 6578 // Caller should return SDValue(N, 0) if this returns true. 6579 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 6580 SDValue Op = N->getOperand(OpNo); 6581 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 6582 if (!SimplifyDemandedBits(Op, Mask, DCI)) 6583 return false; 6584 6585 if (N->getOpcode() != ISD::DELETED_NODE) 6586 DCI.AddToWorklist(N); 6587 return true; 6588 }; 6589 6590 switch (N->getOpcode()) { 6591 default: 6592 break; 6593 case RISCVISD::SplitF64: { 6594 SDValue Op0 = N->getOperand(0); 6595 // If the input to SplitF64 is just BuildPairF64 then the operation is 6596 // redundant. Instead, use BuildPairF64's operands directly. 6597 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 6598 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 6599 6600 SDLoc DL(N); 6601 6602 // It's cheaper to materialise two 32-bit integers than to load a double 6603 // from the constant pool and transfer it to integer registers through the 6604 // stack. 6605 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 6606 APInt V = C->getValueAPF().bitcastToAPInt(); 6607 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 6608 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 6609 return DCI.CombineTo(N, Lo, Hi); 6610 } 6611 6612 // This is a target-specific version of a DAGCombine performed in 6613 // DAGCombiner::visitBITCAST. It performs the equivalent of: 6614 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6615 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6616 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 6617 !Op0.getNode()->hasOneUse()) 6618 break; 6619 SDValue NewSplitF64 = 6620 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 6621 Op0.getOperand(0)); 6622 SDValue Lo = NewSplitF64.getValue(0); 6623 SDValue Hi = NewSplitF64.getValue(1); 6624 APInt SignBit = APInt::getSignMask(32); 6625 if (Op0.getOpcode() == ISD::FNEG) { 6626 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 6627 DAG.getConstant(SignBit, DL, MVT::i32)); 6628 return DCI.CombineTo(N, Lo, NewHi); 6629 } 6630 assert(Op0.getOpcode() == ISD::FABS); 6631 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 6632 DAG.getConstant(~SignBit, DL, MVT::i32)); 6633 return DCI.CombineTo(N, Lo, NewHi); 6634 } 6635 case RISCVISD::SLLW: 6636 case RISCVISD::SRAW: 6637 case RISCVISD::SRLW: 6638 case RISCVISD::ROLW: 6639 case RISCVISD::RORW: { 6640 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 6641 if (SimplifyDemandedLowBitsHelper(0, 32) || 6642 SimplifyDemandedLowBitsHelper(1, 5)) 6643 return SDValue(N, 0); 6644 break; 6645 } 6646 case RISCVISD::CLZW: 6647 case RISCVISD::CTZW: { 6648 // Only the lower 32 bits of the first operand are read 6649 if (SimplifyDemandedLowBitsHelper(0, 32)) 6650 return SDValue(N, 0); 6651 break; 6652 } 6653 case RISCVISD::FSL: 6654 case RISCVISD::FSR: { 6655 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 6656 unsigned BitWidth = N->getOperand(2).getValueSizeInBits(); 6657 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6658 if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1)) 6659 return SDValue(N, 0); 6660 break; 6661 } 6662 case RISCVISD::FSLW: 6663 case RISCVISD::FSRW: { 6664 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 6665 // read. 6666 if (SimplifyDemandedLowBitsHelper(0, 32) || 6667 SimplifyDemandedLowBitsHelper(1, 32) || 6668 SimplifyDemandedLowBitsHelper(2, 6)) 6669 return SDValue(N, 0); 6670 break; 6671 } 6672 case RISCVISD::GREV: 6673 case RISCVISD::GORC: { 6674 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 6675 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 6676 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6677 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 6678 return SDValue(N, 0); 6679 6680 return combineGREVI_GORCI(N, DCI.DAG); 6681 } 6682 case RISCVISD::GREVW: 6683 case RISCVISD::GORCW: { 6684 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 6685 if (SimplifyDemandedLowBitsHelper(0, 32) || 6686 SimplifyDemandedLowBitsHelper(1, 5)) 6687 return SDValue(N, 0); 6688 6689 return combineGREVI_GORCI(N, DCI.DAG); 6690 } 6691 case RISCVISD::SHFL: 6692 case RISCVISD::UNSHFL: { 6693 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 6694 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 6695 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6696 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 6697 return SDValue(N, 0); 6698 6699 break; 6700 } 6701 case RISCVISD::SHFLW: 6702 case RISCVISD::UNSHFLW: { 6703 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 6704 SDValue LHS = N->getOperand(0); 6705 SDValue RHS = N->getOperand(1); 6706 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 6707 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4); 6708 if (SimplifyDemandedLowBitsHelper(0, 32) || 6709 SimplifyDemandedLowBitsHelper(1, 4)) 6710 return SDValue(N, 0); 6711 6712 break; 6713 } 6714 case RISCVISD::BCOMPRESSW: 6715 case RISCVISD::BDECOMPRESSW: { 6716 // Only the lower 32 bits of LHS and RHS are read. 6717 if (SimplifyDemandedLowBitsHelper(0, 32) || 6718 SimplifyDemandedLowBitsHelper(1, 32)) 6719 return SDValue(N, 0); 6720 6721 break; 6722 } 6723 case RISCVISD::FMV_X_ANYEXTH: 6724 case RISCVISD::FMV_X_ANYEXTW_RV64: { 6725 SDLoc DL(N); 6726 SDValue Op0 = N->getOperand(0); 6727 MVT VT = N->getSimpleValueType(0); 6728 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 6729 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 6730 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 6731 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 6732 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 6733 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 6734 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 6735 assert(Op0.getOperand(0).getValueType() == VT && 6736 "Unexpected value type!"); 6737 return Op0.getOperand(0); 6738 } 6739 6740 // This is a target-specific version of a DAGCombine performed in 6741 // DAGCombiner::visitBITCAST. It performs the equivalent of: 6742 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6743 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6744 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 6745 !Op0.getNode()->hasOneUse()) 6746 break; 6747 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 6748 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 6749 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 6750 if (Op0.getOpcode() == ISD::FNEG) 6751 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 6752 DAG.getConstant(SignBit, DL, VT)); 6753 6754 assert(Op0.getOpcode() == ISD::FABS); 6755 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 6756 DAG.getConstant(~SignBit, DL, VT)); 6757 } 6758 case ISD::ADD: 6759 return performADDCombine(N, DAG, Subtarget); 6760 case ISD::SUB: 6761 return performSUBCombine(N, DAG); 6762 case ISD::AND: 6763 return performANDCombine(N, DAG); 6764 case ISD::OR: 6765 return performORCombine(N, DAG, Subtarget); 6766 case ISD::XOR: 6767 return performXORCombine(N, DAG); 6768 case ISD::ANY_EXTEND: 6769 return performANY_EXTENDCombine(N, DCI, Subtarget); 6770 case ISD::ZERO_EXTEND: 6771 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 6772 // type legalization. This is safe because fp_to_uint produces poison if 6773 // it overflows. 6774 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() && 6775 N->getOperand(0).getOpcode() == ISD::FP_TO_UINT && 6776 isTypeLegal(N->getOperand(0).getOperand(0).getValueType())) 6777 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 6778 N->getOperand(0).getOperand(0)); 6779 return SDValue(); 6780 case RISCVISD::SELECT_CC: { 6781 // Transform 6782 SDValue LHS = N->getOperand(0); 6783 SDValue RHS = N->getOperand(1); 6784 SDValue TrueV = N->getOperand(3); 6785 SDValue FalseV = N->getOperand(4); 6786 6787 // If the True and False values are the same, we don't need a select_cc. 6788 if (TrueV == FalseV) 6789 return TrueV; 6790 6791 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 6792 if (!ISD::isIntEqualitySetCC(CCVal)) 6793 break; 6794 6795 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 6796 // (select_cc X, Y, lt, trueV, falseV) 6797 // Sometimes the setcc is introduced after select_cc has been formed. 6798 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 6799 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 6800 // If we're looking for eq 0 instead of ne 0, we need to invert the 6801 // condition. 6802 bool Invert = CCVal == ISD::SETEQ; 6803 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 6804 if (Invert) 6805 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6806 6807 SDLoc DL(N); 6808 RHS = LHS.getOperand(1); 6809 LHS = LHS.getOperand(0); 6810 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 6811 6812 SDValue TargetCC = DAG.getCondCode(CCVal); 6813 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 6814 {LHS, RHS, TargetCC, TrueV, FalseV}); 6815 } 6816 6817 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 6818 // (select_cc X, Y, eq/ne, trueV, falseV) 6819 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 6820 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 6821 {LHS.getOperand(0), LHS.getOperand(1), 6822 N->getOperand(2), TrueV, FalseV}); 6823 // (select_cc X, 1, setne, trueV, falseV) -> 6824 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 6825 // This can occur when legalizing some floating point comparisons. 6826 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 6827 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 6828 SDLoc DL(N); 6829 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6830 SDValue TargetCC = DAG.getCondCode(CCVal); 6831 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 6832 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 6833 {LHS, RHS, TargetCC, TrueV, FalseV}); 6834 } 6835 6836 break; 6837 } 6838 case RISCVISD::BR_CC: { 6839 SDValue LHS = N->getOperand(1); 6840 SDValue RHS = N->getOperand(2); 6841 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 6842 if (!ISD::isIntEqualitySetCC(CCVal)) 6843 break; 6844 6845 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 6846 // (br_cc X, Y, lt, dest) 6847 // Sometimes the setcc is introduced after br_cc has been formed. 6848 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 6849 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 6850 // If we're looking for eq 0 instead of ne 0, we need to invert the 6851 // condition. 6852 bool Invert = CCVal == ISD::SETEQ; 6853 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 6854 if (Invert) 6855 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6856 6857 SDLoc DL(N); 6858 RHS = LHS.getOperand(1); 6859 LHS = LHS.getOperand(0); 6860 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 6861 6862 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 6863 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 6864 N->getOperand(4)); 6865 } 6866 6867 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 6868 // (br_cc X, Y, eq/ne, trueV, falseV) 6869 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 6870 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 6871 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 6872 N->getOperand(3), N->getOperand(4)); 6873 6874 // (br_cc X, 1, setne, br_cc) -> 6875 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 6876 // This can occur when legalizing some floating point comparisons. 6877 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 6878 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 6879 SDLoc DL(N); 6880 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6881 SDValue TargetCC = DAG.getCondCode(CCVal); 6882 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 6883 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 6884 N->getOperand(0), LHS, RHS, TargetCC, 6885 N->getOperand(4)); 6886 } 6887 break; 6888 } 6889 case ISD::FCOPYSIGN: { 6890 EVT VT = N->getValueType(0); 6891 if (!VT.isVector()) 6892 break; 6893 // There is a form of VFSGNJ which injects the negated sign of its second 6894 // operand. Try and bubble any FNEG up after the extend/round to produce 6895 // this optimized pattern. Avoid modifying cases where FP_ROUND and 6896 // TRUNC=1. 6897 SDValue In2 = N->getOperand(1); 6898 // Avoid cases where the extend/round has multiple uses, as duplicating 6899 // those is typically more expensive than removing a fneg. 6900 if (!In2.hasOneUse()) 6901 break; 6902 if (In2.getOpcode() != ISD::FP_EXTEND && 6903 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 6904 break; 6905 In2 = In2.getOperand(0); 6906 if (In2.getOpcode() != ISD::FNEG) 6907 break; 6908 SDLoc DL(N); 6909 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 6910 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 6911 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 6912 } 6913 case ISD::MGATHER: 6914 case ISD::MSCATTER: 6915 case ISD::VP_GATHER: 6916 case ISD::VP_SCATTER: { 6917 if (!DCI.isBeforeLegalize()) 6918 break; 6919 SDValue Index, ScaleOp; 6920 bool IsIndexScaled = false; 6921 bool IsIndexSigned = false; 6922 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 6923 Index = VPGSN->getIndex(); 6924 ScaleOp = VPGSN->getScale(); 6925 IsIndexScaled = VPGSN->isIndexScaled(); 6926 IsIndexSigned = VPGSN->isIndexSigned(); 6927 } else { 6928 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 6929 Index = MGSN->getIndex(); 6930 ScaleOp = MGSN->getScale(); 6931 IsIndexScaled = MGSN->isIndexScaled(); 6932 IsIndexSigned = MGSN->isIndexSigned(); 6933 } 6934 EVT IndexVT = Index.getValueType(); 6935 MVT XLenVT = Subtarget.getXLenVT(); 6936 // RISCV indexed loads only support the "unsigned unscaled" addressing 6937 // mode, so anything else must be manually legalized. 6938 bool NeedsIdxLegalization = 6939 IsIndexScaled || 6940 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 6941 if (!NeedsIdxLegalization) 6942 break; 6943 6944 SDLoc DL(N); 6945 6946 // Any index legalization should first promote to XLenVT, so we don't lose 6947 // bits when scaling. This may create an illegal index type so we let 6948 // LLVM's legalization take care of the splitting. 6949 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 6950 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 6951 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6952 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 6953 DL, IndexVT, Index); 6954 } 6955 6956 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 6957 if (IsIndexScaled && Scale != 1) { 6958 // Manually scale the indices by the element size. 6959 // TODO: Sanitize the scale operand here? 6960 // TODO: For VP nodes, should we use VP_SHL here? 6961 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 6962 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 6963 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 6964 } 6965 6966 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 6967 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 6968 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 6969 {VPGN->getChain(), VPGN->getBasePtr(), Index, 6970 VPGN->getScale(), VPGN->getMask(), 6971 VPGN->getVectorLength()}, 6972 VPGN->getMemOperand(), NewIndexTy); 6973 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 6974 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 6975 {VPSN->getChain(), VPSN->getValue(), 6976 VPSN->getBasePtr(), Index, VPSN->getScale(), 6977 VPSN->getMask(), VPSN->getVectorLength()}, 6978 VPSN->getMemOperand(), NewIndexTy); 6979 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 6980 return DAG.getMaskedGather( 6981 N->getVTList(), MGN->getMemoryVT(), DL, 6982 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 6983 MGN->getBasePtr(), Index, MGN->getScale()}, 6984 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 6985 const auto *MSN = cast<MaskedScatterSDNode>(N); 6986 return DAG.getMaskedScatter( 6987 N->getVTList(), MSN->getMemoryVT(), DL, 6988 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 6989 Index, MSN->getScale()}, 6990 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 6991 } 6992 case RISCVISD::SRA_VL: 6993 case RISCVISD::SRL_VL: 6994 case RISCVISD::SHL_VL: { 6995 SDValue ShAmt = N->getOperand(1); 6996 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 6997 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 6998 SDLoc DL(N); 6999 SDValue VL = N->getOperand(3); 7000 EVT VT = N->getValueType(0); 7001 ShAmt = 7002 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 7003 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 7004 N->getOperand(2), N->getOperand(3)); 7005 } 7006 break; 7007 } 7008 case ISD::SRA: 7009 case ISD::SRL: 7010 case ISD::SHL: { 7011 SDValue ShAmt = N->getOperand(1); 7012 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7013 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7014 SDLoc DL(N); 7015 EVT VT = N->getValueType(0); 7016 ShAmt = 7017 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 7018 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 7019 } 7020 break; 7021 } 7022 case RISCVISD::MUL_VL: { 7023 // Try to form VWMUL or VWMULU. 7024 // FIXME: Look for splat of extended scalar as well. 7025 // FIXME: Support VWMULSU. 7026 SDValue Op0 = N->getOperand(0); 7027 SDValue Op1 = N->getOperand(1); 7028 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7029 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7030 if ((!IsSignExt && !IsZeroExt) || Op0.getOpcode() != Op1.getOpcode()) 7031 return SDValue(); 7032 7033 // Make sure the extends have a single use. 7034 if (!Op0.hasOneUse() || !Op1.hasOneUse()) 7035 return SDValue(); 7036 7037 SDValue Mask = N->getOperand(2); 7038 SDValue VL = N->getOperand(3); 7039 if (Op0.getOperand(1) != Mask || Op1.getOperand(1) != Mask || 7040 Op0.getOperand(2) != VL || Op1.getOperand(2) != VL) 7041 return SDValue(); 7042 7043 Op0 = Op0.getOperand(0); 7044 Op1 = Op1.getOperand(0); 7045 7046 MVT VT = N->getSimpleValueType(0); 7047 MVT NarrowVT = 7048 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() / 2), 7049 VT.getVectorElementCount()); 7050 7051 SDLoc DL(N); 7052 7053 // Re-introduce narrower extends if needed. 7054 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7055 if (Op0.getValueType() != NarrowVT) 7056 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7057 if (Op1.getValueType() != NarrowVT) 7058 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7059 7060 unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7061 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7062 } 7063 } 7064 7065 return SDValue(); 7066 } 7067 7068 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 7069 const SDNode *N, CombineLevel Level) const { 7070 // The following folds are only desirable if `(OP _, c1 << c2)` can be 7071 // materialised in fewer instructions than `(OP _, c1)`: 7072 // 7073 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 7074 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 7075 SDValue N0 = N->getOperand(0); 7076 EVT Ty = N0.getValueType(); 7077 if (Ty.isScalarInteger() && 7078 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 7079 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7080 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7081 if (C1 && C2) { 7082 const APInt &C1Int = C1->getAPIntValue(); 7083 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 7084 7085 // We can materialise `c1 << c2` into an add immediate, so it's "free", 7086 // and the combine should happen, to potentially allow further combines 7087 // later. 7088 if (ShiftedC1Int.getMinSignedBits() <= 64 && 7089 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 7090 return true; 7091 7092 // We can materialise `c1` in an add immediate, so it's "free", and the 7093 // combine should be prevented. 7094 if (C1Int.getMinSignedBits() <= 64 && 7095 isLegalAddImmediate(C1Int.getSExtValue())) 7096 return false; 7097 7098 // Neither constant will fit into an immediate, so find materialisation 7099 // costs. 7100 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 7101 Subtarget.getFeatureBits(), 7102 /*CompressionCost*/true); 7103 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 7104 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 7105 /*CompressionCost*/true); 7106 7107 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 7108 // combine should be prevented. 7109 if (C1Cost < ShiftedC1Cost) 7110 return false; 7111 } 7112 } 7113 return true; 7114 } 7115 7116 bool RISCVTargetLowering::targetShrinkDemandedConstant( 7117 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 7118 TargetLoweringOpt &TLO) const { 7119 // Delay this optimization as late as possible. 7120 if (!TLO.LegalOps) 7121 return false; 7122 7123 EVT VT = Op.getValueType(); 7124 if (VT.isVector()) 7125 return false; 7126 7127 // Only handle AND for now. 7128 if (Op.getOpcode() != ISD::AND) 7129 return false; 7130 7131 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7132 if (!C) 7133 return false; 7134 7135 const APInt &Mask = C->getAPIntValue(); 7136 7137 // Clear all non-demanded bits initially. 7138 APInt ShrunkMask = Mask & DemandedBits; 7139 7140 // Try to make a smaller immediate by setting undemanded bits. 7141 7142 APInt ExpandedMask = Mask | ~DemandedBits; 7143 7144 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 7145 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 7146 }; 7147 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 7148 if (NewMask == Mask) 7149 return true; 7150 SDLoc DL(Op); 7151 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 7152 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 7153 return TLO.CombineTo(Op, NewOp); 7154 }; 7155 7156 // If the shrunk mask fits in sign extended 12 bits, let the target 7157 // independent code apply it. 7158 if (ShrunkMask.isSignedIntN(12)) 7159 return false; 7160 7161 // Preserve (and X, 0xffff) when zext.h is supported. 7162 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 7163 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 7164 if (IsLegalMask(NewMask)) 7165 return UseMask(NewMask); 7166 } 7167 7168 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 7169 if (VT == MVT::i64) { 7170 APInt NewMask = APInt(64, 0xffffffff); 7171 if (IsLegalMask(NewMask)) 7172 return UseMask(NewMask); 7173 } 7174 7175 // For the remaining optimizations, we need to be able to make a negative 7176 // number through a combination of mask and undemanded bits. 7177 if (!ExpandedMask.isNegative()) 7178 return false; 7179 7180 // What is the fewest number of bits we need to represent the negative number. 7181 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 7182 7183 // Try to make a 12 bit negative immediate. If that fails try to make a 32 7184 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 7185 APInt NewMask = ShrunkMask; 7186 if (MinSignedBits <= 12) 7187 NewMask.setBitsFrom(11); 7188 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 7189 NewMask.setBitsFrom(31); 7190 else 7191 return false; 7192 7193 // Sanity check that our new mask is a subset of the demanded mask. 7194 assert(IsLegalMask(NewMask)); 7195 return UseMask(NewMask); 7196 } 7197 7198 static void computeGREV(APInt &Src, unsigned ShAmt) { 7199 ShAmt &= Src.getBitWidth() - 1; 7200 uint64_t x = Src.getZExtValue(); 7201 if (ShAmt & 1) 7202 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 7203 if (ShAmt & 2) 7204 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 7205 if (ShAmt & 4) 7206 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 7207 if (ShAmt & 8) 7208 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 7209 if (ShAmt & 16) 7210 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 7211 if (ShAmt & 32) 7212 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 7213 Src = x; 7214 } 7215 7216 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 7217 KnownBits &Known, 7218 const APInt &DemandedElts, 7219 const SelectionDAG &DAG, 7220 unsigned Depth) const { 7221 unsigned BitWidth = Known.getBitWidth(); 7222 unsigned Opc = Op.getOpcode(); 7223 assert((Opc >= ISD::BUILTIN_OP_END || 7224 Opc == ISD::INTRINSIC_WO_CHAIN || 7225 Opc == ISD::INTRINSIC_W_CHAIN || 7226 Opc == ISD::INTRINSIC_VOID) && 7227 "Should use MaskedValueIsZero if you don't know whether Op" 7228 " is a target node!"); 7229 7230 Known.resetAll(); 7231 switch (Opc) { 7232 default: break; 7233 case RISCVISD::SELECT_CC: { 7234 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 7235 // If we don't know any bits, early out. 7236 if (Known.isUnknown()) 7237 break; 7238 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 7239 7240 // Only known if known in both the LHS and RHS. 7241 Known = KnownBits::commonBits(Known, Known2); 7242 break; 7243 } 7244 case RISCVISD::REMUW: { 7245 KnownBits Known2; 7246 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7247 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7248 // We only care about the lower 32 bits. 7249 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 7250 // Restore the original width by sign extending. 7251 Known = Known.sext(BitWidth); 7252 break; 7253 } 7254 case RISCVISD::DIVUW: { 7255 KnownBits Known2; 7256 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7257 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7258 // We only care about the lower 32 bits. 7259 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 7260 // Restore the original width by sign extending. 7261 Known = Known.sext(BitWidth); 7262 break; 7263 } 7264 case RISCVISD::CTZW: { 7265 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7266 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 7267 unsigned LowBits = Log2_32(PossibleTZ) + 1; 7268 Known.Zero.setBitsFrom(LowBits); 7269 break; 7270 } 7271 case RISCVISD::CLZW: { 7272 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7273 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 7274 unsigned LowBits = Log2_32(PossibleLZ) + 1; 7275 Known.Zero.setBitsFrom(LowBits); 7276 break; 7277 } 7278 case RISCVISD::GREV: 7279 case RISCVISD::GREVW: { 7280 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7281 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7282 if (Opc == RISCVISD::GREVW) 7283 Known = Known.trunc(32); 7284 unsigned ShAmt = C->getZExtValue(); 7285 computeGREV(Known.Zero, ShAmt); 7286 computeGREV(Known.One, ShAmt); 7287 if (Opc == RISCVISD::GREVW) 7288 Known = Known.sext(BitWidth); 7289 } 7290 break; 7291 } 7292 case RISCVISD::READ_VLENB: 7293 // We assume VLENB is at least 16 bytes. 7294 Known.Zero.setLowBits(4); 7295 // We assume VLENB is no more than 65536 / 8 bytes. 7296 Known.Zero.setBitsFrom(14); 7297 break; 7298 case ISD::INTRINSIC_W_CHAIN: { 7299 unsigned IntNo = Op.getConstantOperandVal(1); 7300 switch (IntNo) { 7301 default: 7302 // We can't do anything for most intrinsics. 7303 break; 7304 case Intrinsic::riscv_vsetvli: 7305 case Intrinsic::riscv_vsetvlimax: 7306 // Assume that VL output is positive and would fit in an int32_t. 7307 // TODO: VLEN might be capped at 16 bits in a future V spec update. 7308 if (BitWidth >= 32) 7309 Known.Zero.setBitsFrom(31); 7310 break; 7311 } 7312 break; 7313 } 7314 } 7315 } 7316 7317 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 7318 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 7319 unsigned Depth) const { 7320 switch (Op.getOpcode()) { 7321 default: 7322 break; 7323 case RISCVISD::SELECT_CC: { 7324 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 7325 if (Tmp == 1) return 1; // Early out. 7326 unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 7327 return std::min(Tmp, Tmp2); 7328 } 7329 case RISCVISD::SLLW: 7330 case RISCVISD::SRAW: 7331 case RISCVISD::SRLW: 7332 case RISCVISD::DIVW: 7333 case RISCVISD::DIVUW: 7334 case RISCVISD::REMUW: 7335 case RISCVISD::ROLW: 7336 case RISCVISD::RORW: 7337 case RISCVISD::GREVW: 7338 case RISCVISD::GORCW: 7339 case RISCVISD::FSLW: 7340 case RISCVISD::FSRW: 7341 case RISCVISD::SHFLW: 7342 case RISCVISD::UNSHFLW: 7343 case RISCVISD::BCOMPRESSW: 7344 case RISCVISD::BDECOMPRESSW: 7345 case RISCVISD::FCVT_W_RTZ_RV64: 7346 case RISCVISD::FCVT_WU_RTZ_RV64: 7347 // TODO: As the result is sign-extended, this is conservatively correct. A 7348 // more precise answer could be calculated for SRAW depending on known 7349 // bits in the shift amount. 7350 return 33; 7351 case RISCVISD::SHFL: 7352 case RISCVISD::UNSHFL: { 7353 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 7354 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 7355 // will stay within the upper 32 bits. If there were more than 32 sign bits 7356 // before there will be at least 33 sign bits after. 7357 if (Op.getValueType() == MVT::i64 && 7358 isa<ConstantSDNode>(Op.getOperand(1)) && 7359 (Op.getConstantOperandVal(1) & 0x10) == 0) { 7360 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 7361 if (Tmp > 32) 7362 return 33; 7363 } 7364 break; 7365 } 7366 case RISCVISD::VMV_X_S: 7367 // The number of sign bits of the scalar result is computed by obtaining the 7368 // element type of the input vector operand, subtracting its width from the 7369 // XLEN, and then adding one (sign bit within the element type). If the 7370 // element type is wider than XLen, the least-significant XLEN bits are 7371 // taken. 7372 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 7373 return 1; 7374 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 7375 } 7376 7377 return 1; 7378 } 7379 7380 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 7381 MachineBasicBlock *BB) { 7382 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 7383 7384 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 7385 // Should the count have wrapped while it was being read, we need to try 7386 // again. 7387 // ... 7388 // read: 7389 // rdcycleh x3 # load high word of cycle 7390 // rdcycle x2 # load low word of cycle 7391 // rdcycleh x4 # load high word of cycle 7392 // bne x3, x4, read # check if high word reads match, otherwise try again 7393 // ... 7394 7395 MachineFunction &MF = *BB->getParent(); 7396 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7397 MachineFunction::iterator It = ++BB->getIterator(); 7398 7399 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7400 MF.insert(It, LoopMBB); 7401 7402 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7403 MF.insert(It, DoneMBB); 7404 7405 // Transfer the remainder of BB and its successor edges to DoneMBB. 7406 DoneMBB->splice(DoneMBB->begin(), BB, 7407 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7408 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 7409 7410 BB->addSuccessor(LoopMBB); 7411 7412 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7413 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 7414 Register LoReg = MI.getOperand(0).getReg(); 7415 Register HiReg = MI.getOperand(1).getReg(); 7416 DebugLoc DL = MI.getDebugLoc(); 7417 7418 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 7419 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 7420 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7421 .addReg(RISCV::X0); 7422 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 7423 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 7424 .addReg(RISCV::X0); 7425 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 7426 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7427 .addReg(RISCV::X0); 7428 7429 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 7430 .addReg(HiReg) 7431 .addReg(ReadAgainReg) 7432 .addMBB(LoopMBB); 7433 7434 LoopMBB->addSuccessor(LoopMBB); 7435 LoopMBB->addSuccessor(DoneMBB); 7436 7437 MI.eraseFromParent(); 7438 7439 return DoneMBB; 7440 } 7441 7442 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 7443 MachineBasicBlock *BB) { 7444 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 7445 7446 MachineFunction &MF = *BB->getParent(); 7447 DebugLoc DL = MI.getDebugLoc(); 7448 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7449 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7450 Register LoReg = MI.getOperand(0).getReg(); 7451 Register HiReg = MI.getOperand(1).getReg(); 7452 Register SrcReg = MI.getOperand(2).getReg(); 7453 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 7454 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7455 7456 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 7457 RI); 7458 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7459 MachineMemOperand *MMOLo = 7460 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 7461 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7462 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 7463 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 7464 .addFrameIndex(FI) 7465 .addImm(0) 7466 .addMemOperand(MMOLo); 7467 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 7468 .addFrameIndex(FI) 7469 .addImm(4) 7470 .addMemOperand(MMOHi); 7471 MI.eraseFromParent(); // The pseudo instruction is gone now. 7472 return BB; 7473 } 7474 7475 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 7476 MachineBasicBlock *BB) { 7477 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 7478 "Unexpected instruction"); 7479 7480 MachineFunction &MF = *BB->getParent(); 7481 DebugLoc DL = MI.getDebugLoc(); 7482 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7483 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7484 Register DstReg = MI.getOperand(0).getReg(); 7485 Register LoReg = MI.getOperand(1).getReg(); 7486 Register HiReg = MI.getOperand(2).getReg(); 7487 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 7488 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7489 7490 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7491 MachineMemOperand *MMOLo = 7492 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 7493 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7494 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 7495 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7496 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 7497 .addFrameIndex(FI) 7498 .addImm(0) 7499 .addMemOperand(MMOLo); 7500 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7501 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 7502 .addFrameIndex(FI) 7503 .addImm(4) 7504 .addMemOperand(MMOHi); 7505 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 7506 MI.eraseFromParent(); // The pseudo instruction is gone now. 7507 return BB; 7508 } 7509 7510 static bool isSelectPseudo(MachineInstr &MI) { 7511 switch (MI.getOpcode()) { 7512 default: 7513 return false; 7514 case RISCV::Select_GPR_Using_CC_GPR: 7515 case RISCV::Select_FPR16_Using_CC_GPR: 7516 case RISCV::Select_FPR32_Using_CC_GPR: 7517 case RISCV::Select_FPR64_Using_CC_GPR: 7518 return true; 7519 } 7520 } 7521 7522 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 7523 MachineBasicBlock *BB, 7524 const RISCVSubtarget &Subtarget) { 7525 // To "insert" Select_* instructions, we actually have to insert the triangle 7526 // control-flow pattern. The incoming instructions know the destination vreg 7527 // to set, the condition code register to branch on, the true/false values to 7528 // select between, and the condcode to use to select the appropriate branch. 7529 // 7530 // We produce the following control flow: 7531 // HeadMBB 7532 // | \ 7533 // | IfFalseMBB 7534 // | / 7535 // TailMBB 7536 // 7537 // When we find a sequence of selects we attempt to optimize their emission 7538 // by sharing the control flow. Currently we only handle cases where we have 7539 // multiple selects with the exact same condition (same LHS, RHS and CC). 7540 // The selects may be interleaved with other instructions if the other 7541 // instructions meet some requirements we deem safe: 7542 // - They are debug instructions. Otherwise, 7543 // - They do not have side-effects, do not access memory and their inputs do 7544 // not depend on the results of the select pseudo-instructions. 7545 // The TrueV/FalseV operands of the selects cannot depend on the result of 7546 // previous selects in the sequence. 7547 // These conditions could be further relaxed. See the X86 target for a 7548 // related approach and more information. 7549 Register LHS = MI.getOperand(1).getReg(); 7550 Register RHS = MI.getOperand(2).getReg(); 7551 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 7552 7553 SmallVector<MachineInstr *, 4> SelectDebugValues; 7554 SmallSet<Register, 4> SelectDests; 7555 SelectDests.insert(MI.getOperand(0).getReg()); 7556 7557 MachineInstr *LastSelectPseudo = &MI; 7558 7559 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 7560 SequenceMBBI != E; ++SequenceMBBI) { 7561 if (SequenceMBBI->isDebugInstr()) 7562 continue; 7563 else if (isSelectPseudo(*SequenceMBBI)) { 7564 if (SequenceMBBI->getOperand(1).getReg() != LHS || 7565 SequenceMBBI->getOperand(2).getReg() != RHS || 7566 SequenceMBBI->getOperand(3).getImm() != CC || 7567 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 7568 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 7569 break; 7570 LastSelectPseudo = &*SequenceMBBI; 7571 SequenceMBBI->collectDebugValues(SelectDebugValues); 7572 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 7573 } else { 7574 if (SequenceMBBI->hasUnmodeledSideEffects() || 7575 SequenceMBBI->mayLoadOrStore()) 7576 break; 7577 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 7578 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 7579 })) 7580 break; 7581 } 7582 } 7583 7584 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 7585 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7586 DebugLoc DL = MI.getDebugLoc(); 7587 MachineFunction::iterator I = ++BB->getIterator(); 7588 7589 MachineBasicBlock *HeadMBB = BB; 7590 MachineFunction *F = BB->getParent(); 7591 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 7592 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 7593 7594 F->insert(I, IfFalseMBB); 7595 F->insert(I, TailMBB); 7596 7597 // Transfer debug instructions associated with the selects to TailMBB. 7598 for (MachineInstr *DebugInstr : SelectDebugValues) { 7599 TailMBB->push_back(DebugInstr->removeFromParent()); 7600 } 7601 7602 // Move all instructions after the sequence to TailMBB. 7603 TailMBB->splice(TailMBB->end(), HeadMBB, 7604 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 7605 // Update machine-CFG edges by transferring all successors of the current 7606 // block to the new block which will contain the Phi nodes for the selects. 7607 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 7608 // Set the successors for HeadMBB. 7609 HeadMBB->addSuccessor(IfFalseMBB); 7610 HeadMBB->addSuccessor(TailMBB); 7611 7612 // Insert appropriate branch. 7613 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 7614 .addReg(LHS) 7615 .addReg(RHS) 7616 .addMBB(TailMBB); 7617 7618 // IfFalseMBB just falls through to TailMBB. 7619 IfFalseMBB->addSuccessor(TailMBB); 7620 7621 // Create PHIs for all of the select pseudo-instructions. 7622 auto SelectMBBI = MI.getIterator(); 7623 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 7624 auto InsertionPoint = TailMBB->begin(); 7625 while (SelectMBBI != SelectEnd) { 7626 auto Next = std::next(SelectMBBI); 7627 if (isSelectPseudo(*SelectMBBI)) { 7628 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 7629 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 7630 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 7631 .addReg(SelectMBBI->getOperand(4).getReg()) 7632 .addMBB(HeadMBB) 7633 .addReg(SelectMBBI->getOperand(5).getReg()) 7634 .addMBB(IfFalseMBB); 7635 SelectMBBI->eraseFromParent(); 7636 } 7637 SelectMBBI = Next; 7638 } 7639 7640 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 7641 return TailMBB; 7642 } 7643 7644 MachineBasicBlock * 7645 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 7646 MachineBasicBlock *BB) const { 7647 switch (MI.getOpcode()) { 7648 default: 7649 llvm_unreachable("Unexpected instr type to insert"); 7650 case RISCV::ReadCycleWide: 7651 assert(!Subtarget.is64Bit() && 7652 "ReadCycleWrite is only to be used on riscv32"); 7653 return emitReadCycleWidePseudo(MI, BB); 7654 case RISCV::Select_GPR_Using_CC_GPR: 7655 case RISCV::Select_FPR16_Using_CC_GPR: 7656 case RISCV::Select_FPR32_Using_CC_GPR: 7657 case RISCV::Select_FPR64_Using_CC_GPR: 7658 return emitSelectPseudo(MI, BB, Subtarget); 7659 case RISCV::BuildPairF64Pseudo: 7660 return emitBuildPairF64Pseudo(MI, BB); 7661 case RISCV::SplitF64Pseudo: 7662 return emitSplitF64Pseudo(MI, BB); 7663 } 7664 } 7665 7666 // Calling Convention Implementation. 7667 // The expectations for frontend ABI lowering vary from target to target. 7668 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 7669 // details, but this is a longer term goal. For now, we simply try to keep the 7670 // role of the frontend as simple and well-defined as possible. The rules can 7671 // be summarised as: 7672 // * Never split up large scalar arguments. We handle them here. 7673 // * If a hardfloat calling convention is being used, and the struct may be 7674 // passed in a pair of registers (fp+fp, int+fp), and both registers are 7675 // available, then pass as two separate arguments. If either the GPRs or FPRs 7676 // are exhausted, then pass according to the rule below. 7677 // * If a struct could never be passed in registers or directly in a stack 7678 // slot (as it is larger than 2*XLEN and the floating point rules don't 7679 // apply), then pass it using a pointer with the byval attribute. 7680 // * If a struct is less than 2*XLEN, then coerce to either a two-element 7681 // word-sized array or a 2*XLEN scalar (depending on alignment). 7682 // * The frontend can determine whether a struct is returned by reference or 7683 // not based on its size and fields. If it will be returned by reference, the 7684 // frontend must modify the prototype so a pointer with the sret annotation is 7685 // passed as the first argument. This is not necessary for large scalar 7686 // returns. 7687 // * Struct return values and varargs should be coerced to structs containing 7688 // register-size fields in the same situations they would be for fixed 7689 // arguments. 7690 7691 static const MCPhysReg ArgGPRs[] = { 7692 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 7693 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 7694 }; 7695 static const MCPhysReg ArgFPR16s[] = { 7696 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 7697 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 7698 }; 7699 static const MCPhysReg ArgFPR32s[] = { 7700 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 7701 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 7702 }; 7703 static const MCPhysReg ArgFPR64s[] = { 7704 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 7705 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 7706 }; 7707 // This is an interim calling convention and it may be changed in the future. 7708 static const MCPhysReg ArgVRs[] = { 7709 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 7710 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 7711 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 7712 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 7713 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 7714 RISCV::V20M2, RISCV::V22M2}; 7715 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 7716 RISCV::V20M4}; 7717 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 7718 7719 // Pass a 2*XLEN argument that has been split into two XLEN values through 7720 // registers or the stack as necessary. 7721 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 7722 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 7723 MVT ValVT2, MVT LocVT2, 7724 ISD::ArgFlagsTy ArgFlags2) { 7725 unsigned XLenInBytes = XLen / 8; 7726 if (Register Reg = State.AllocateReg(ArgGPRs)) { 7727 // At least one half can be passed via register. 7728 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 7729 VA1.getLocVT(), CCValAssign::Full)); 7730 } else { 7731 // Both halves must be passed on the stack, with proper alignment. 7732 Align StackAlign = 7733 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 7734 State.addLoc( 7735 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 7736 State.AllocateStack(XLenInBytes, StackAlign), 7737 VA1.getLocVT(), CCValAssign::Full)); 7738 State.addLoc(CCValAssign::getMem( 7739 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 7740 LocVT2, CCValAssign::Full)); 7741 return false; 7742 } 7743 7744 if (Register Reg = State.AllocateReg(ArgGPRs)) { 7745 // The second half can also be passed via register. 7746 State.addLoc( 7747 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 7748 } else { 7749 // The second half is passed via the stack, without additional alignment. 7750 State.addLoc(CCValAssign::getMem( 7751 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 7752 LocVT2, CCValAssign::Full)); 7753 } 7754 7755 return false; 7756 } 7757 7758 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 7759 Optional<unsigned> FirstMaskArgument, 7760 CCState &State, const RISCVTargetLowering &TLI) { 7761 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 7762 if (RC == &RISCV::VRRegClass) { 7763 // Assign the first mask argument to V0. 7764 // This is an interim calling convention and it may be changed in the 7765 // future. 7766 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 7767 return State.AllocateReg(RISCV::V0); 7768 return State.AllocateReg(ArgVRs); 7769 } 7770 if (RC == &RISCV::VRM2RegClass) 7771 return State.AllocateReg(ArgVRM2s); 7772 if (RC == &RISCV::VRM4RegClass) 7773 return State.AllocateReg(ArgVRM4s); 7774 if (RC == &RISCV::VRM8RegClass) 7775 return State.AllocateReg(ArgVRM8s); 7776 llvm_unreachable("Unhandled register class for ValueType"); 7777 } 7778 7779 // Implements the RISC-V calling convention. Returns true upon failure. 7780 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 7781 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 7782 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 7783 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 7784 Optional<unsigned> FirstMaskArgument) { 7785 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 7786 assert(XLen == 32 || XLen == 64); 7787 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 7788 7789 // Any return value split in to more than two values can't be returned 7790 // directly. Vectors are returned via the available vector registers. 7791 if (!LocVT.isVector() && IsRet && ValNo > 1) 7792 return true; 7793 7794 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 7795 // variadic argument, or if no F16/F32 argument registers are available. 7796 bool UseGPRForF16_F32 = true; 7797 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 7798 // variadic argument, or if no F64 argument registers are available. 7799 bool UseGPRForF64 = true; 7800 7801 switch (ABI) { 7802 default: 7803 llvm_unreachable("Unexpected ABI"); 7804 case RISCVABI::ABI_ILP32: 7805 case RISCVABI::ABI_LP64: 7806 break; 7807 case RISCVABI::ABI_ILP32F: 7808 case RISCVABI::ABI_LP64F: 7809 UseGPRForF16_F32 = !IsFixed; 7810 break; 7811 case RISCVABI::ABI_ILP32D: 7812 case RISCVABI::ABI_LP64D: 7813 UseGPRForF16_F32 = !IsFixed; 7814 UseGPRForF64 = !IsFixed; 7815 break; 7816 } 7817 7818 // FPR16, FPR32, and FPR64 alias each other. 7819 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 7820 UseGPRForF16_F32 = true; 7821 UseGPRForF64 = true; 7822 } 7823 7824 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 7825 // similar local variables rather than directly checking against the target 7826 // ABI. 7827 7828 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 7829 LocVT = XLenVT; 7830 LocInfo = CCValAssign::BCvt; 7831 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 7832 LocVT = MVT::i64; 7833 LocInfo = CCValAssign::BCvt; 7834 } 7835 7836 // If this is a variadic argument, the RISC-V calling convention requires 7837 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 7838 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 7839 // be used regardless of whether the original argument was split during 7840 // legalisation or not. The argument will not be passed by registers if the 7841 // original type is larger than 2*XLEN, so the register alignment rule does 7842 // not apply. 7843 unsigned TwoXLenInBytes = (2 * XLen) / 8; 7844 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 7845 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 7846 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 7847 // Skip 'odd' register if necessary. 7848 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 7849 State.AllocateReg(ArgGPRs); 7850 } 7851 7852 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 7853 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 7854 State.getPendingArgFlags(); 7855 7856 assert(PendingLocs.size() == PendingArgFlags.size() && 7857 "PendingLocs and PendingArgFlags out of sync"); 7858 7859 // Handle passing f64 on RV32D with a soft float ABI or when floating point 7860 // registers are exhausted. 7861 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 7862 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 7863 "Can't lower f64 if it is split"); 7864 // Depending on available argument GPRS, f64 may be passed in a pair of 7865 // GPRs, split between a GPR and the stack, or passed completely on the 7866 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 7867 // cases. 7868 Register Reg = State.AllocateReg(ArgGPRs); 7869 LocVT = MVT::i32; 7870 if (!Reg) { 7871 unsigned StackOffset = State.AllocateStack(8, Align(8)); 7872 State.addLoc( 7873 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 7874 return false; 7875 } 7876 if (!State.AllocateReg(ArgGPRs)) 7877 State.AllocateStack(4, Align(4)); 7878 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 7879 return false; 7880 } 7881 7882 // Fixed-length vectors are located in the corresponding scalable-vector 7883 // container types. 7884 if (ValVT.isFixedLengthVector()) 7885 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 7886 7887 // Split arguments might be passed indirectly, so keep track of the pending 7888 // values. Split vectors are passed via a mix of registers and indirectly, so 7889 // treat them as we would any other argument. 7890 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 7891 LocVT = XLenVT; 7892 LocInfo = CCValAssign::Indirect; 7893 PendingLocs.push_back( 7894 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 7895 PendingArgFlags.push_back(ArgFlags); 7896 if (!ArgFlags.isSplitEnd()) { 7897 return false; 7898 } 7899 } 7900 7901 // If the split argument only had two elements, it should be passed directly 7902 // in registers or on the stack. 7903 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 7904 PendingLocs.size() <= 2) { 7905 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 7906 // Apply the normal calling convention rules to the first half of the 7907 // split argument. 7908 CCValAssign VA = PendingLocs[0]; 7909 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 7910 PendingLocs.clear(); 7911 PendingArgFlags.clear(); 7912 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 7913 ArgFlags); 7914 } 7915 7916 // Allocate to a register if possible, or else a stack slot. 7917 Register Reg; 7918 unsigned StoreSizeBytes = XLen / 8; 7919 Align StackAlign = Align(XLen / 8); 7920 7921 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 7922 Reg = State.AllocateReg(ArgFPR16s); 7923 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 7924 Reg = State.AllocateReg(ArgFPR32s); 7925 else if (ValVT == MVT::f64 && !UseGPRForF64) 7926 Reg = State.AllocateReg(ArgFPR64s); 7927 else if (ValVT.isVector()) { 7928 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 7929 if (!Reg) { 7930 // For return values, the vector must be passed fully via registers or 7931 // via the stack. 7932 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 7933 // but we're using all of them. 7934 if (IsRet) 7935 return true; 7936 // Try using a GPR to pass the address 7937 if ((Reg = State.AllocateReg(ArgGPRs))) { 7938 LocVT = XLenVT; 7939 LocInfo = CCValAssign::Indirect; 7940 } else if (ValVT.isScalableVector()) { 7941 report_fatal_error("Unable to pass scalable vector types on the stack"); 7942 } else { 7943 // Pass fixed-length vectors on the stack. 7944 LocVT = ValVT; 7945 StoreSizeBytes = ValVT.getStoreSize(); 7946 // Align vectors to their element sizes, being careful for vXi1 7947 // vectors. 7948 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 7949 } 7950 } 7951 } else { 7952 Reg = State.AllocateReg(ArgGPRs); 7953 } 7954 7955 unsigned StackOffset = 7956 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 7957 7958 // If we reach this point and PendingLocs is non-empty, we must be at the 7959 // end of a split argument that must be passed indirectly. 7960 if (!PendingLocs.empty()) { 7961 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 7962 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 7963 7964 for (auto &It : PendingLocs) { 7965 if (Reg) 7966 It.convertToReg(Reg); 7967 else 7968 It.convertToMem(StackOffset); 7969 State.addLoc(It); 7970 } 7971 PendingLocs.clear(); 7972 PendingArgFlags.clear(); 7973 return false; 7974 } 7975 7976 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 7977 (TLI.getSubtarget().hasStdExtV() && ValVT.isVector())) && 7978 "Expected an XLenVT or vector types at this stage"); 7979 7980 if (Reg) { 7981 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 7982 return false; 7983 } 7984 7985 // When a floating-point value is passed on the stack, no bit-conversion is 7986 // needed. 7987 if (ValVT.isFloatingPoint()) { 7988 LocVT = ValVT; 7989 LocInfo = CCValAssign::Full; 7990 } 7991 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 7992 return false; 7993 } 7994 7995 template <typename ArgTy> 7996 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 7997 for (const auto &ArgIdx : enumerate(Args)) { 7998 MVT ArgVT = ArgIdx.value().VT; 7999 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 8000 return ArgIdx.index(); 8001 } 8002 return None; 8003 } 8004 8005 void RISCVTargetLowering::analyzeInputArgs( 8006 MachineFunction &MF, CCState &CCInfo, 8007 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 8008 RISCVCCAssignFn Fn) const { 8009 unsigned NumArgs = Ins.size(); 8010 FunctionType *FType = MF.getFunction().getFunctionType(); 8011 8012 Optional<unsigned> FirstMaskArgument; 8013 if (Subtarget.hasStdExtV()) 8014 FirstMaskArgument = preAssignMask(Ins); 8015 8016 for (unsigned i = 0; i != NumArgs; ++i) { 8017 MVT ArgVT = Ins[i].VT; 8018 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 8019 8020 Type *ArgTy = nullptr; 8021 if (IsRet) 8022 ArgTy = FType->getReturnType(); 8023 else if (Ins[i].isOrigArg()) 8024 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 8025 8026 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8027 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8028 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 8029 FirstMaskArgument)) { 8030 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 8031 << EVT(ArgVT).getEVTString() << '\n'); 8032 llvm_unreachable(nullptr); 8033 } 8034 } 8035 } 8036 8037 void RISCVTargetLowering::analyzeOutputArgs( 8038 MachineFunction &MF, CCState &CCInfo, 8039 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 8040 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 8041 unsigned NumArgs = Outs.size(); 8042 8043 Optional<unsigned> FirstMaskArgument; 8044 if (Subtarget.hasStdExtV()) 8045 FirstMaskArgument = preAssignMask(Outs); 8046 8047 for (unsigned i = 0; i != NumArgs; i++) { 8048 MVT ArgVT = Outs[i].VT; 8049 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 8050 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 8051 8052 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8053 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8054 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 8055 FirstMaskArgument)) { 8056 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 8057 << EVT(ArgVT).getEVTString() << "\n"); 8058 llvm_unreachable(nullptr); 8059 } 8060 } 8061 } 8062 8063 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 8064 // values. 8065 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 8066 const CCValAssign &VA, const SDLoc &DL, 8067 const RISCVSubtarget &Subtarget) { 8068 switch (VA.getLocInfo()) { 8069 default: 8070 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8071 case CCValAssign::Full: 8072 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 8073 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 8074 break; 8075 case CCValAssign::BCvt: 8076 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8077 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 8078 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8079 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 8080 else 8081 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 8082 break; 8083 } 8084 return Val; 8085 } 8086 8087 // The caller is responsible for loading the full value if the argument is 8088 // passed with CCValAssign::Indirect. 8089 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 8090 const CCValAssign &VA, const SDLoc &DL, 8091 const RISCVTargetLowering &TLI) { 8092 MachineFunction &MF = DAG.getMachineFunction(); 8093 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8094 EVT LocVT = VA.getLocVT(); 8095 SDValue Val; 8096 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 8097 Register VReg = RegInfo.createVirtualRegister(RC); 8098 RegInfo.addLiveIn(VA.getLocReg(), VReg); 8099 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 8100 8101 if (VA.getLocInfo() == CCValAssign::Indirect) 8102 return Val; 8103 8104 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 8105 } 8106 8107 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 8108 const CCValAssign &VA, const SDLoc &DL, 8109 const RISCVSubtarget &Subtarget) { 8110 EVT LocVT = VA.getLocVT(); 8111 8112 switch (VA.getLocInfo()) { 8113 default: 8114 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8115 case CCValAssign::Full: 8116 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 8117 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 8118 break; 8119 case CCValAssign::BCvt: 8120 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8121 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 8122 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8123 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 8124 else 8125 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 8126 break; 8127 } 8128 return Val; 8129 } 8130 8131 // The caller is responsible for loading the full value if the argument is 8132 // passed with CCValAssign::Indirect. 8133 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 8134 const CCValAssign &VA, const SDLoc &DL) { 8135 MachineFunction &MF = DAG.getMachineFunction(); 8136 MachineFrameInfo &MFI = MF.getFrameInfo(); 8137 EVT LocVT = VA.getLocVT(); 8138 EVT ValVT = VA.getValVT(); 8139 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 8140 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 8141 /*Immutable=*/true); 8142 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 8143 SDValue Val; 8144 8145 ISD::LoadExtType ExtType; 8146 switch (VA.getLocInfo()) { 8147 default: 8148 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8149 case CCValAssign::Full: 8150 case CCValAssign::Indirect: 8151 case CCValAssign::BCvt: 8152 ExtType = ISD::NON_EXTLOAD; 8153 break; 8154 } 8155 Val = DAG.getExtLoad( 8156 ExtType, DL, LocVT, Chain, FIN, 8157 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 8158 return Val; 8159 } 8160 8161 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 8162 const CCValAssign &VA, const SDLoc &DL) { 8163 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 8164 "Unexpected VA"); 8165 MachineFunction &MF = DAG.getMachineFunction(); 8166 MachineFrameInfo &MFI = MF.getFrameInfo(); 8167 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8168 8169 if (VA.isMemLoc()) { 8170 // f64 is passed on the stack. 8171 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 8172 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8173 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 8174 MachinePointerInfo::getFixedStack(MF, FI)); 8175 } 8176 8177 assert(VA.isRegLoc() && "Expected register VA assignment"); 8178 8179 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8180 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 8181 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 8182 SDValue Hi; 8183 if (VA.getLocReg() == RISCV::X17) { 8184 // Second half of f64 is passed on the stack. 8185 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 8186 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8187 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 8188 MachinePointerInfo::getFixedStack(MF, FI)); 8189 } else { 8190 // Second half of f64 is passed in another GPR. 8191 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8192 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 8193 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 8194 } 8195 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 8196 } 8197 8198 // FastCC has less than 1% performance improvement for some particular 8199 // benchmark. But theoretically, it may has benenfit for some cases. 8200 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 8201 unsigned ValNo, MVT ValVT, MVT LocVT, 8202 CCValAssign::LocInfo LocInfo, 8203 ISD::ArgFlagsTy ArgFlags, CCState &State, 8204 bool IsFixed, bool IsRet, Type *OrigTy, 8205 const RISCVTargetLowering &TLI, 8206 Optional<unsigned> FirstMaskArgument) { 8207 8208 // X5 and X6 might be used for save-restore libcall. 8209 static const MCPhysReg GPRList[] = { 8210 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 8211 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 8212 RISCV::X29, RISCV::X30, RISCV::X31}; 8213 8214 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8215 if (unsigned Reg = State.AllocateReg(GPRList)) { 8216 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8217 return false; 8218 } 8219 } 8220 8221 if (LocVT == MVT::f16) { 8222 static const MCPhysReg FPR16List[] = { 8223 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 8224 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 8225 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 8226 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 8227 if (unsigned Reg = State.AllocateReg(FPR16List)) { 8228 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8229 return false; 8230 } 8231 } 8232 8233 if (LocVT == MVT::f32) { 8234 static const MCPhysReg FPR32List[] = { 8235 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 8236 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 8237 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 8238 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 8239 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8240 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8241 return false; 8242 } 8243 } 8244 8245 if (LocVT == MVT::f64) { 8246 static const MCPhysReg FPR64List[] = { 8247 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 8248 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 8249 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 8250 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 8251 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8252 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8253 return false; 8254 } 8255 } 8256 8257 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 8258 unsigned Offset4 = State.AllocateStack(4, Align(4)); 8259 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 8260 return false; 8261 } 8262 8263 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 8264 unsigned Offset5 = State.AllocateStack(8, Align(8)); 8265 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 8266 return false; 8267 } 8268 8269 if (LocVT.isVector()) { 8270 if (unsigned Reg = 8271 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 8272 // Fixed-length vectors are located in the corresponding scalable-vector 8273 // container types. 8274 if (ValVT.isFixedLengthVector()) 8275 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8276 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8277 } else { 8278 // Try and pass the address via a "fast" GPR. 8279 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 8280 LocInfo = CCValAssign::Indirect; 8281 LocVT = TLI.getSubtarget().getXLenVT(); 8282 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 8283 } else if (ValVT.isFixedLengthVector()) { 8284 auto StackAlign = 8285 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8286 unsigned StackOffset = 8287 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 8288 State.addLoc( 8289 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8290 } else { 8291 // Can't pass scalable vectors on the stack. 8292 return true; 8293 } 8294 } 8295 8296 return false; 8297 } 8298 8299 return true; // CC didn't match. 8300 } 8301 8302 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 8303 CCValAssign::LocInfo LocInfo, 8304 ISD::ArgFlagsTy ArgFlags, CCState &State) { 8305 8306 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8307 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 8308 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 8309 static const MCPhysReg GPRList[] = { 8310 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 8311 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 8312 if (unsigned Reg = State.AllocateReg(GPRList)) { 8313 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8314 return false; 8315 } 8316 } 8317 8318 if (LocVT == MVT::f32) { 8319 // Pass in STG registers: F1, ..., F6 8320 // fs0 ... fs5 8321 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 8322 RISCV::F18_F, RISCV::F19_F, 8323 RISCV::F20_F, RISCV::F21_F}; 8324 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8325 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8326 return false; 8327 } 8328 } 8329 8330 if (LocVT == MVT::f64) { 8331 // Pass in STG registers: D1, ..., D6 8332 // fs6 ... fs11 8333 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 8334 RISCV::F24_D, RISCV::F25_D, 8335 RISCV::F26_D, RISCV::F27_D}; 8336 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8337 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8338 return false; 8339 } 8340 } 8341 8342 report_fatal_error("No registers left in GHC calling convention"); 8343 return true; 8344 } 8345 8346 // Transform physical registers into virtual registers. 8347 SDValue RISCVTargetLowering::LowerFormalArguments( 8348 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 8349 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 8350 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 8351 8352 MachineFunction &MF = DAG.getMachineFunction(); 8353 8354 switch (CallConv) { 8355 default: 8356 report_fatal_error("Unsupported calling convention"); 8357 case CallingConv::C: 8358 case CallingConv::Fast: 8359 break; 8360 case CallingConv::GHC: 8361 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 8362 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 8363 report_fatal_error( 8364 "GHC calling convention requires the F and D instruction set extensions"); 8365 } 8366 8367 const Function &Func = MF.getFunction(); 8368 if (Func.hasFnAttribute("interrupt")) { 8369 if (!Func.arg_empty()) 8370 report_fatal_error( 8371 "Functions with the interrupt attribute cannot have arguments!"); 8372 8373 StringRef Kind = 8374 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 8375 8376 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 8377 report_fatal_error( 8378 "Function interrupt attribute argument not supported!"); 8379 } 8380 8381 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8382 MVT XLenVT = Subtarget.getXLenVT(); 8383 unsigned XLenInBytes = Subtarget.getXLen() / 8; 8384 // Used with vargs to acumulate store chains. 8385 std::vector<SDValue> OutChains; 8386 8387 // Assign locations to all of the incoming arguments. 8388 SmallVector<CCValAssign, 16> ArgLocs; 8389 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 8390 8391 if (CallConv == CallingConv::GHC) 8392 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 8393 else 8394 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 8395 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 8396 : CC_RISCV); 8397 8398 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 8399 CCValAssign &VA = ArgLocs[i]; 8400 SDValue ArgValue; 8401 // Passing f64 on RV32D with a soft float ABI must be handled as a special 8402 // case. 8403 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 8404 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 8405 else if (VA.isRegLoc()) 8406 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 8407 else 8408 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 8409 8410 if (VA.getLocInfo() == CCValAssign::Indirect) { 8411 // If the original argument was split and passed by reference (e.g. i128 8412 // on RV32), we need to load all parts of it here (using the same 8413 // address). Vectors may be partly split to registers and partly to the 8414 // stack, in which case the base address is partly offset and subsequent 8415 // stores are relative to that. 8416 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 8417 MachinePointerInfo())); 8418 unsigned ArgIndex = Ins[i].OrigArgIndex; 8419 unsigned ArgPartOffset = Ins[i].PartOffset; 8420 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8421 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 8422 CCValAssign &PartVA = ArgLocs[i + 1]; 8423 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 8424 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8425 if (PartVA.getValVT().isScalableVector()) 8426 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8427 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 8428 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 8429 MachinePointerInfo())); 8430 ++i; 8431 } 8432 continue; 8433 } 8434 InVals.push_back(ArgValue); 8435 } 8436 8437 if (IsVarArg) { 8438 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 8439 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 8440 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 8441 MachineFrameInfo &MFI = MF.getFrameInfo(); 8442 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8443 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 8444 8445 // Offset of the first variable argument from stack pointer, and size of 8446 // the vararg save area. For now, the varargs save area is either zero or 8447 // large enough to hold a0-a7. 8448 int VaArgOffset, VarArgsSaveSize; 8449 8450 // If all registers are allocated, then all varargs must be passed on the 8451 // stack and we don't need to save any argregs. 8452 if (ArgRegs.size() == Idx) { 8453 VaArgOffset = CCInfo.getNextStackOffset(); 8454 VarArgsSaveSize = 0; 8455 } else { 8456 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 8457 VaArgOffset = -VarArgsSaveSize; 8458 } 8459 8460 // Record the frame index of the first variable argument 8461 // which is a value necessary to VASTART. 8462 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8463 RVFI->setVarArgsFrameIndex(FI); 8464 8465 // If saving an odd number of registers then create an extra stack slot to 8466 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 8467 // offsets to even-numbered registered remain 2*XLEN-aligned. 8468 if (Idx % 2) { 8469 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 8470 VarArgsSaveSize += XLenInBytes; 8471 } 8472 8473 // Copy the integer registers that may have been used for passing varargs 8474 // to the vararg save area. 8475 for (unsigned I = Idx; I < ArgRegs.size(); 8476 ++I, VaArgOffset += XLenInBytes) { 8477 const Register Reg = RegInfo.createVirtualRegister(RC); 8478 RegInfo.addLiveIn(ArgRegs[I], Reg); 8479 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 8480 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8481 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8482 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 8483 MachinePointerInfo::getFixedStack(MF, FI)); 8484 cast<StoreSDNode>(Store.getNode()) 8485 ->getMemOperand() 8486 ->setValue((Value *)nullptr); 8487 OutChains.push_back(Store); 8488 } 8489 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 8490 } 8491 8492 // All stores are grouped in one node to allow the matching between 8493 // the size of Ins and InVals. This only happens for vararg functions. 8494 if (!OutChains.empty()) { 8495 OutChains.push_back(Chain); 8496 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 8497 } 8498 8499 return Chain; 8500 } 8501 8502 /// isEligibleForTailCallOptimization - Check whether the call is eligible 8503 /// for tail call optimization. 8504 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 8505 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 8506 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 8507 const SmallVector<CCValAssign, 16> &ArgLocs) const { 8508 8509 auto &Callee = CLI.Callee; 8510 auto CalleeCC = CLI.CallConv; 8511 auto &Outs = CLI.Outs; 8512 auto &Caller = MF.getFunction(); 8513 auto CallerCC = Caller.getCallingConv(); 8514 8515 // Exception-handling functions need a special set of instructions to 8516 // indicate a return to the hardware. Tail-calling another function would 8517 // probably break this. 8518 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 8519 // should be expanded as new function attributes are introduced. 8520 if (Caller.hasFnAttribute("interrupt")) 8521 return false; 8522 8523 // Do not tail call opt if the stack is used to pass parameters. 8524 if (CCInfo.getNextStackOffset() != 0) 8525 return false; 8526 8527 // Do not tail call opt if any parameters need to be passed indirectly. 8528 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 8529 // passed indirectly. So the address of the value will be passed in a 8530 // register, or if not available, then the address is put on the stack. In 8531 // order to pass indirectly, space on the stack often needs to be allocated 8532 // in order to store the value. In this case the CCInfo.getNextStackOffset() 8533 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 8534 // are passed CCValAssign::Indirect. 8535 for (auto &VA : ArgLocs) 8536 if (VA.getLocInfo() == CCValAssign::Indirect) 8537 return false; 8538 8539 // Do not tail call opt if either caller or callee uses struct return 8540 // semantics. 8541 auto IsCallerStructRet = Caller.hasStructRetAttr(); 8542 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 8543 if (IsCallerStructRet || IsCalleeStructRet) 8544 return false; 8545 8546 // Externally-defined functions with weak linkage should not be 8547 // tail-called. The behaviour of branch instructions in this situation (as 8548 // used for tail calls) is implementation-defined, so we cannot rely on the 8549 // linker replacing the tail call with a return. 8550 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 8551 const GlobalValue *GV = G->getGlobal(); 8552 if (GV->hasExternalWeakLinkage()) 8553 return false; 8554 } 8555 8556 // The callee has to preserve all registers the caller needs to preserve. 8557 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 8558 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 8559 if (CalleeCC != CallerCC) { 8560 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 8561 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 8562 return false; 8563 } 8564 8565 // Byval parameters hand the function a pointer directly into the stack area 8566 // we want to reuse during a tail call. Working around this *is* possible 8567 // but less efficient and uglier in LowerCall. 8568 for (auto &Arg : Outs) 8569 if (Arg.Flags.isByVal()) 8570 return false; 8571 8572 return true; 8573 } 8574 8575 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 8576 return DAG.getDataLayout().getPrefTypeAlign( 8577 VT.getTypeForEVT(*DAG.getContext())); 8578 } 8579 8580 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 8581 // and output parameter nodes. 8582 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 8583 SmallVectorImpl<SDValue> &InVals) const { 8584 SelectionDAG &DAG = CLI.DAG; 8585 SDLoc &DL = CLI.DL; 8586 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 8587 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 8588 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 8589 SDValue Chain = CLI.Chain; 8590 SDValue Callee = CLI.Callee; 8591 bool &IsTailCall = CLI.IsTailCall; 8592 CallingConv::ID CallConv = CLI.CallConv; 8593 bool IsVarArg = CLI.IsVarArg; 8594 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8595 MVT XLenVT = Subtarget.getXLenVT(); 8596 8597 MachineFunction &MF = DAG.getMachineFunction(); 8598 8599 // Analyze the operands of the call, assigning locations to each operand. 8600 SmallVector<CCValAssign, 16> ArgLocs; 8601 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 8602 8603 if (CallConv == CallingConv::GHC) 8604 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 8605 else 8606 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 8607 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 8608 : CC_RISCV); 8609 8610 // Check if it's really possible to do a tail call. 8611 if (IsTailCall) 8612 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 8613 8614 if (IsTailCall) 8615 ++NumTailCalls; 8616 else if (CLI.CB && CLI.CB->isMustTailCall()) 8617 report_fatal_error("failed to perform tail call elimination on a call " 8618 "site marked musttail"); 8619 8620 // Get a count of how many bytes are to be pushed on the stack. 8621 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 8622 8623 // Create local copies for byval args 8624 SmallVector<SDValue, 8> ByValArgs; 8625 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 8626 ISD::ArgFlagsTy Flags = Outs[i].Flags; 8627 if (!Flags.isByVal()) 8628 continue; 8629 8630 SDValue Arg = OutVals[i]; 8631 unsigned Size = Flags.getByValSize(); 8632 Align Alignment = Flags.getNonZeroByValAlign(); 8633 8634 int FI = 8635 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 8636 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8637 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 8638 8639 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 8640 /*IsVolatile=*/false, 8641 /*AlwaysInline=*/false, IsTailCall, 8642 MachinePointerInfo(), MachinePointerInfo()); 8643 ByValArgs.push_back(FIPtr); 8644 } 8645 8646 if (!IsTailCall) 8647 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 8648 8649 // Copy argument values to their designated locations. 8650 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 8651 SmallVector<SDValue, 8> MemOpChains; 8652 SDValue StackPtr; 8653 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 8654 CCValAssign &VA = ArgLocs[i]; 8655 SDValue ArgValue = OutVals[i]; 8656 ISD::ArgFlagsTy Flags = Outs[i].Flags; 8657 8658 // Handle passing f64 on RV32D with a soft float ABI as a special case. 8659 bool IsF64OnRV32DSoftABI = 8660 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 8661 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 8662 SDValue SplitF64 = DAG.getNode( 8663 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 8664 SDValue Lo = SplitF64.getValue(0); 8665 SDValue Hi = SplitF64.getValue(1); 8666 8667 Register RegLo = VA.getLocReg(); 8668 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 8669 8670 if (RegLo == RISCV::X17) { 8671 // Second half of f64 is passed on the stack. 8672 // Work out the address of the stack slot. 8673 if (!StackPtr.getNode()) 8674 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 8675 // Emit the store. 8676 MemOpChains.push_back( 8677 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 8678 } else { 8679 // Second half of f64 is passed in another GPR. 8680 assert(RegLo < RISCV::X31 && "Invalid register pair"); 8681 Register RegHigh = RegLo + 1; 8682 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 8683 } 8684 continue; 8685 } 8686 8687 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 8688 // as any other MemLoc. 8689 8690 // Promote the value if needed. 8691 // For now, only handle fully promoted and indirect arguments. 8692 if (VA.getLocInfo() == CCValAssign::Indirect) { 8693 // Store the argument in a stack slot and pass its address. 8694 Align StackAlign = 8695 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 8696 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 8697 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 8698 // If the original argument was split (e.g. i128), we need 8699 // to store the required parts of it here (and pass just one address). 8700 // Vectors may be partly split to registers and partly to the stack, in 8701 // which case the base address is partly offset and subsequent stores are 8702 // relative to that. 8703 unsigned ArgIndex = Outs[i].OrigArgIndex; 8704 unsigned ArgPartOffset = Outs[i].PartOffset; 8705 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8706 // Calculate the total size to store. We don't have access to what we're 8707 // actually storing other than performing the loop and collecting the 8708 // info. 8709 SmallVector<std::pair<SDValue, SDValue>> Parts; 8710 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 8711 SDValue PartValue = OutVals[i + 1]; 8712 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 8713 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8714 EVT PartVT = PartValue.getValueType(); 8715 if (PartVT.isScalableVector()) 8716 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8717 StoredSize += PartVT.getStoreSize(); 8718 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 8719 Parts.push_back(std::make_pair(PartValue, Offset)); 8720 ++i; 8721 } 8722 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 8723 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 8724 MemOpChains.push_back( 8725 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 8726 MachinePointerInfo::getFixedStack(MF, FI))); 8727 for (const auto &Part : Parts) { 8728 SDValue PartValue = Part.first; 8729 SDValue PartOffset = Part.second; 8730 SDValue Address = 8731 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 8732 MemOpChains.push_back( 8733 DAG.getStore(Chain, DL, PartValue, Address, 8734 MachinePointerInfo::getFixedStack(MF, FI))); 8735 } 8736 ArgValue = SpillSlot; 8737 } else { 8738 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 8739 } 8740 8741 // Use local copy if it is a byval arg. 8742 if (Flags.isByVal()) 8743 ArgValue = ByValArgs[j++]; 8744 8745 if (VA.isRegLoc()) { 8746 // Queue up the argument copies and emit them at the end. 8747 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 8748 } else { 8749 assert(VA.isMemLoc() && "Argument not register or memory"); 8750 assert(!IsTailCall && "Tail call not allowed if stack is used " 8751 "for passing parameters"); 8752 8753 // Work out the address of the stack slot. 8754 if (!StackPtr.getNode()) 8755 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 8756 SDValue Address = 8757 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 8758 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 8759 8760 // Emit the store. 8761 MemOpChains.push_back( 8762 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 8763 } 8764 } 8765 8766 // Join the stores, which are independent of one another. 8767 if (!MemOpChains.empty()) 8768 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 8769 8770 SDValue Glue; 8771 8772 // Build a sequence of copy-to-reg nodes, chained and glued together. 8773 for (auto &Reg : RegsToPass) { 8774 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 8775 Glue = Chain.getValue(1); 8776 } 8777 8778 // Validate that none of the argument registers have been marked as 8779 // reserved, if so report an error. Do the same for the return address if this 8780 // is not a tailcall. 8781 validateCCReservedRegs(RegsToPass, MF); 8782 if (!IsTailCall && 8783 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 8784 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 8785 MF.getFunction(), 8786 "Return address register required, but has been reserved."}); 8787 8788 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 8789 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 8790 // split it and then direct call can be matched by PseudoCALL. 8791 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 8792 const GlobalValue *GV = S->getGlobal(); 8793 8794 unsigned OpFlags = RISCVII::MO_CALL; 8795 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 8796 OpFlags = RISCVII::MO_PLT; 8797 8798 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 8799 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 8800 unsigned OpFlags = RISCVII::MO_CALL; 8801 8802 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 8803 nullptr)) 8804 OpFlags = RISCVII::MO_PLT; 8805 8806 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 8807 } 8808 8809 // The first call operand is the chain and the second is the target address. 8810 SmallVector<SDValue, 8> Ops; 8811 Ops.push_back(Chain); 8812 Ops.push_back(Callee); 8813 8814 // Add argument registers to the end of the list so that they are 8815 // known live into the call. 8816 for (auto &Reg : RegsToPass) 8817 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 8818 8819 if (!IsTailCall) { 8820 // Add a register mask operand representing the call-preserved registers. 8821 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 8822 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 8823 assert(Mask && "Missing call preserved mask for calling convention"); 8824 Ops.push_back(DAG.getRegisterMask(Mask)); 8825 } 8826 8827 // Glue the call to the argument copies, if any. 8828 if (Glue.getNode()) 8829 Ops.push_back(Glue); 8830 8831 // Emit the call. 8832 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8833 8834 if (IsTailCall) { 8835 MF.getFrameInfo().setHasTailCall(); 8836 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 8837 } 8838 8839 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 8840 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 8841 Glue = Chain.getValue(1); 8842 8843 // Mark the end of the call, which is glued to the call itself. 8844 Chain = DAG.getCALLSEQ_END(Chain, 8845 DAG.getConstant(NumBytes, DL, PtrVT, true), 8846 DAG.getConstant(0, DL, PtrVT, true), 8847 Glue, DL); 8848 Glue = Chain.getValue(1); 8849 8850 // Assign locations to each value returned by this call. 8851 SmallVector<CCValAssign, 16> RVLocs; 8852 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 8853 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 8854 8855 // Copy all of the result registers out of their specified physreg. 8856 for (auto &VA : RVLocs) { 8857 // Copy the value out 8858 SDValue RetValue = 8859 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 8860 // Glue the RetValue to the end of the call sequence 8861 Chain = RetValue.getValue(1); 8862 Glue = RetValue.getValue(2); 8863 8864 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 8865 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 8866 SDValue RetValue2 = 8867 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 8868 Chain = RetValue2.getValue(1); 8869 Glue = RetValue2.getValue(2); 8870 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 8871 RetValue2); 8872 } 8873 8874 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 8875 8876 InVals.push_back(RetValue); 8877 } 8878 8879 return Chain; 8880 } 8881 8882 bool RISCVTargetLowering::CanLowerReturn( 8883 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 8884 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 8885 SmallVector<CCValAssign, 16> RVLocs; 8886 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 8887 8888 Optional<unsigned> FirstMaskArgument; 8889 if (Subtarget.hasStdExtV()) 8890 FirstMaskArgument = preAssignMask(Outs); 8891 8892 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 8893 MVT VT = Outs[i].VT; 8894 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 8895 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8896 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 8897 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 8898 *this, FirstMaskArgument)) 8899 return false; 8900 } 8901 return true; 8902 } 8903 8904 SDValue 8905 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 8906 bool IsVarArg, 8907 const SmallVectorImpl<ISD::OutputArg> &Outs, 8908 const SmallVectorImpl<SDValue> &OutVals, 8909 const SDLoc &DL, SelectionDAG &DAG) const { 8910 const MachineFunction &MF = DAG.getMachineFunction(); 8911 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 8912 8913 // Stores the assignment of the return value to a location. 8914 SmallVector<CCValAssign, 16> RVLocs; 8915 8916 // Info about the registers and stack slot. 8917 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 8918 *DAG.getContext()); 8919 8920 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 8921 nullptr, CC_RISCV); 8922 8923 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 8924 report_fatal_error("GHC functions return void only"); 8925 8926 SDValue Glue; 8927 SmallVector<SDValue, 4> RetOps(1, Chain); 8928 8929 // Copy the result values into the output registers. 8930 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 8931 SDValue Val = OutVals[i]; 8932 CCValAssign &VA = RVLocs[i]; 8933 assert(VA.isRegLoc() && "Can only return in registers!"); 8934 8935 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 8936 // Handle returning f64 on RV32D with a soft float ABI. 8937 assert(VA.isRegLoc() && "Expected return via registers"); 8938 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 8939 DAG.getVTList(MVT::i32, MVT::i32), Val); 8940 SDValue Lo = SplitF64.getValue(0); 8941 SDValue Hi = SplitF64.getValue(1); 8942 Register RegLo = VA.getLocReg(); 8943 assert(RegLo < RISCV::X31 && "Invalid register pair"); 8944 Register RegHi = RegLo + 1; 8945 8946 if (STI.isRegisterReservedByUser(RegLo) || 8947 STI.isRegisterReservedByUser(RegHi)) 8948 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 8949 MF.getFunction(), 8950 "Return value register required, but has been reserved."}); 8951 8952 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 8953 Glue = Chain.getValue(1); 8954 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 8955 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 8956 Glue = Chain.getValue(1); 8957 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 8958 } else { 8959 // Handle a 'normal' return. 8960 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 8961 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 8962 8963 if (STI.isRegisterReservedByUser(VA.getLocReg())) 8964 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 8965 MF.getFunction(), 8966 "Return value register required, but has been reserved."}); 8967 8968 // Guarantee that all emitted copies are stuck together. 8969 Glue = Chain.getValue(1); 8970 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 8971 } 8972 } 8973 8974 RetOps[0] = Chain; // Update chain. 8975 8976 // Add the glue node if we have it. 8977 if (Glue.getNode()) { 8978 RetOps.push_back(Glue); 8979 } 8980 8981 unsigned RetOpc = RISCVISD::RET_FLAG; 8982 // Interrupt service routines use different return instructions. 8983 const Function &Func = DAG.getMachineFunction().getFunction(); 8984 if (Func.hasFnAttribute("interrupt")) { 8985 if (!Func.getReturnType()->isVoidTy()) 8986 report_fatal_error( 8987 "Functions with the interrupt attribute must have void return type!"); 8988 8989 MachineFunction &MF = DAG.getMachineFunction(); 8990 StringRef Kind = 8991 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 8992 8993 if (Kind == "user") 8994 RetOpc = RISCVISD::URET_FLAG; 8995 else if (Kind == "supervisor") 8996 RetOpc = RISCVISD::SRET_FLAG; 8997 else 8998 RetOpc = RISCVISD::MRET_FLAG; 8999 } 9000 9001 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 9002 } 9003 9004 void RISCVTargetLowering::validateCCReservedRegs( 9005 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 9006 MachineFunction &MF) const { 9007 const Function &F = MF.getFunction(); 9008 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9009 9010 if (llvm::any_of(Regs, [&STI](auto Reg) { 9011 return STI.isRegisterReservedByUser(Reg.first); 9012 })) 9013 F.getContext().diagnose(DiagnosticInfoUnsupported{ 9014 F, "Argument register required, but has been reserved."}); 9015 } 9016 9017 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 9018 return CI->isTailCall(); 9019 } 9020 9021 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 9022 #define NODE_NAME_CASE(NODE) \ 9023 case RISCVISD::NODE: \ 9024 return "RISCVISD::" #NODE; 9025 // clang-format off 9026 switch ((RISCVISD::NodeType)Opcode) { 9027 case RISCVISD::FIRST_NUMBER: 9028 break; 9029 NODE_NAME_CASE(RET_FLAG) 9030 NODE_NAME_CASE(URET_FLAG) 9031 NODE_NAME_CASE(SRET_FLAG) 9032 NODE_NAME_CASE(MRET_FLAG) 9033 NODE_NAME_CASE(CALL) 9034 NODE_NAME_CASE(SELECT_CC) 9035 NODE_NAME_CASE(BR_CC) 9036 NODE_NAME_CASE(BuildPairF64) 9037 NODE_NAME_CASE(SplitF64) 9038 NODE_NAME_CASE(TAIL) 9039 NODE_NAME_CASE(MULHSU) 9040 NODE_NAME_CASE(SLLW) 9041 NODE_NAME_CASE(SRAW) 9042 NODE_NAME_CASE(SRLW) 9043 NODE_NAME_CASE(DIVW) 9044 NODE_NAME_CASE(DIVUW) 9045 NODE_NAME_CASE(REMUW) 9046 NODE_NAME_CASE(ROLW) 9047 NODE_NAME_CASE(RORW) 9048 NODE_NAME_CASE(CLZW) 9049 NODE_NAME_CASE(CTZW) 9050 NODE_NAME_CASE(FSLW) 9051 NODE_NAME_CASE(FSRW) 9052 NODE_NAME_CASE(FSL) 9053 NODE_NAME_CASE(FSR) 9054 NODE_NAME_CASE(FMV_H_X) 9055 NODE_NAME_CASE(FMV_X_ANYEXTH) 9056 NODE_NAME_CASE(FMV_W_X_RV64) 9057 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 9058 NODE_NAME_CASE(FCVT_X_RTZ) 9059 NODE_NAME_CASE(FCVT_XU_RTZ) 9060 NODE_NAME_CASE(FCVT_W_RTZ_RV64) 9061 NODE_NAME_CASE(FCVT_WU_RTZ_RV64) 9062 NODE_NAME_CASE(READ_CYCLE_WIDE) 9063 NODE_NAME_CASE(GREV) 9064 NODE_NAME_CASE(GREVW) 9065 NODE_NAME_CASE(GORC) 9066 NODE_NAME_CASE(GORCW) 9067 NODE_NAME_CASE(SHFL) 9068 NODE_NAME_CASE(SHFLW) 9069 NODE_NAME_CASE(UNSHFL) 9070 NODE_NAME_CASE(UNSHFLW) 9071 NODE_NAME_CASE(BCOMPRESS) 9072 NODE_NAME_CASE(BCOMPRESSW) 9073 NODE_NAME_CASE(BDECOMPRESS) 9074 NODE_NAME_CASE(BDECOMPRESSW) 9075 NODE_NAME_CASE(VMV_V_X_VL) 9076 NODE_NAME_CASE(VFMV_V_F_VL) 9077 NODE_NAME_CASE(VMV_X_S) 9078 NODE_NAME_CASE(VMV_S_X_VL) 9079 NODE_NAME_CASE(VFMV_S_F_VL) 9080 NODE_NAME_CASE(SPLAT_VECTOR_I64) 9081 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 9082 NODE_NAME_CASE(READ_VLENB) 9083 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 9084 NODE_NAME_CASE(VSLIDEUP_VL) 9085 NODE_NAME_CASE(VSLIDE1UP_VL) 9086 NODE_NAME_CASE(VSLIDEDOWN_VL) 9087 NODE_NAME_CASE(VSLIDE1DOWN_VL) 9088 NODE_NAME_CASE(VID_VL) 9089 NODE_NAME_CASE(VFNCVT_ROD_VL) 9090 NODE_NAME_CASE(VECREDUCE_ADD_VL) 9091 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 9092 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 9093 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 9094 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 9095 NODE_NAME_CASE(VECREDUCE_AND_VL) 9096 NODE_NAME_CASE(VECREDUCE_OR_VL) 9097 NODE_NAME_CASE(VECREDUCE_XOR_VL) 9098 NODE_NAME_CASE(VECREDUCE_FADD_VL) 9099 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 9100 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 9101 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 9102 NODE_NAME_CASE(ADD_VL) 9103 NODE_NAME_CASE(AND_VL) 9104 NODE_NAME_CASE(MUL_VL) 9105 NODE_NAME_CASE(OR_VL) 9106 NODE_NAME_CASE(SDIV_VL) 9107 NODE_NAME_CASE(SHL_VL) 9108 NODE_NAME_CASE(SREM_VL) 9109 NODE_NAME_CASE(SRA_VL) 9110 NODE_NAME_CASE(SRL_VL) 9111 NODE_NAME_CASE(SUB_VL) 9112 NODE_NAME_CASE(UDIV_VL) 9113 NODE_NAME_CASE(UREM_VL) 9114 NODE_NAME_CASE(XOR_VL) 9115 NODE_NAME_CASE(SADDSAT_VL) 9116 NODE_NAME_CASE(UADDSAT_VL) 9117 NODE_NAME_CASE(SSUBSAT_VL) 9118 NODE_NAME_CASE(USUBSAT_VL) 9119 NODE_NAME_CASE(FADD_VL) 9120 NODE_NAME_CASE(FSUB_VL) 9121 NODE_NAME_CASE(FMUL_VL) 9122 NODE_NAME_CASE(FDIV_VL) 9123 NODE_NAME_CASE(FNEG_VL) 9124 NODE_NAME_CASE(FABS_VL) 9125 NODE_NAME_CASE(FSQRT_VL) 9126 NODE_NAME_CASE(FMA_VL) 9127 NODE_NAME_CASE(FCOPYSIGN_VL) 9128 NODE_NAME_CASE(SMIN_VL) 9129 NODE_NAME_CASE(SMAX_VL) 9130 NODE_NAME_CASE(UMIN_VL) 9131 NODE_NAME_CASE(UMAX_VL) 9132 NODE_NAME_CASE(FMINNUM_VL) 9133 NODE_NAME_CASE(FMAXNUM_VL) 9134 NODE_NAME_CASE(MULHS_VL) 9135 NODE_NAME_CASE(MULHU_VL) 9136 NODE_NAME_CASE(FP_TO_SINT_VL) 9137 NODE_NAME_CASE(FP_TO_UINT_VL) 9138 NODE_NAME_CASE(SINT_TO_FP_VL) 9139 NODE_NAME_CASE(UINT_TO_FP_VL) 9140 NODE_NAME_CASE(FP_EXTEND_VL) 9141 NODE_NAME_CASE(FP_ROUND_VL) 9142 NODE_NAME_CASE(VWMUL_VL) 9143 NODE_NAME_CASE(VWMULU_VL) 9144 NODE_NAME_CASE(SETCC_VL) 9145 NODE_NAME_CASE(VSELECT_VL) 9146 NODE_NAME_CASE(VMAND_VL) 9147 NODE_NAME_CASE(VMOR_VL) 9148 NODE_NAME_CASE(VMXOR_VL) 9149 NODE_NAME_CASE(VMCLR_VL) 9150 NODE_NAME_CASE(VMSET_VL) 9151 NODE_NAME_CASE(VRGATHER_VX_VL) 9152 NODE_NAME_CASE(VRGATHER_VV_VL) 9153 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 9154 NODE_NAME_CASE(VSEXT_VL) 9155 NODE_NAME_CASE(VZEXT_VL) 9156 NODE_NAME_CASE(VPOPC_VL) 9157 NODE_NAME_CASE(VLE_VL) 9158 NODE_NAME_CASE(VSE_VL) 9159 NODE_NAME_CASE(READ_CSR) 9160 NODE_NAME_CASE(WRITE_CSR) 9161 NODE_NAME_CASE(SWAP_CSR) 9162 } 9163 // clang-format on 9164 return nullptr; 9165 #undef NODE_NAME_CASE 9166 } 9167 9168 /// getConstraintType - Given a constraint letter, return the type of 9169 /// constraint it is for this target. 9170 RISCVTargetLowering::ConstraintType 9171 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 9172 if (Constraint.size() == 1) { 9173 switch (Constraint[0]) { 9174 default: 9175 break; 9176 case 'f': 9177 return C_RegisterClass; 9178 case 'I': 9179 case 'J': 9180 case 'K': 9181 return C_Immediate; 9182 case 'A': 9183 return C_Memory; 9184 case 'S': // A symbolic address 9185 return C_Other; 9186 } 9187 } else { 9188 if (Constraint == "vr" || Constraint == "vm") 9189 return C_RegisterClass; 9190 } 9191 return TargetLowering::getConstraintType(Constraint); 9192 } 9193 9194 std::pair<unsigned, const TargetRegisterClass *> 9195 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 9196 StringRef Constraint, 9197 MVT VT) const { 9198 // First, see if this is a constraint that directly corresponds to a 9199 // RISCV register class. 9200 if (Constraint.size() == 1) { 9201 switch (Constraint[0]) { 9202 case 'r': 9203 return std::make_pair(0U, &RISCV::GPRRegClass); 9204 case 'f': 9205 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 9206 return std::make_pair(0U, &RISCV::FPR16RegClass); 9207 if (Subtarget.hasStdExtF() && VT == MVT::f32) 9208 return std::make_pair(0U, &RISCV::FPR32RegClass); 9209 if (Subtarget.hasStdExtD() && VT == MVT::f64) 9210 return std::make_pair(0U, &RISCV::FPR64RegClass); 9211 break; 9212 default: 9213 break; 9214 } 9215 } else { 9216 if (Constraint == "vr") { 9217 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 9218 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9219 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 9220 return std::make_pair(0U, RC); 9221 } 9222 } else if (Constraint == "vm") { 9223 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9224 return std::make_pair(0U, &RISCV::VMRegClass); 9225 } 9226 } 9227 9228 // Clang will correctly decode the usage of register name aliases into their 9229 // official names. However, other frontends like `rustc` do not. This allows 9230 // users of these frontends to use the ABI names for registers in LLVM-style 9231 // register constraints. 9232 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 9233 .Case("{zero}", RISCV::X0) 9234 .Case("{ra}", RISCV::X1) 9235 .Case("{sp}", RISCV::X2) 9236 .Case("{gp}", RISCV::X3) 9237 .Case("{tp}", RISCV::X4) 9238 .Case("{t0}", RISCV::X5) 9239 .Case("{t1}", RISCV::X6) 9240 .Case("{t2}", RISCV::X7) 9241 .Cases("{s0}", "{fp}", RISCV::X8) 9242 .Case("{s1}", RISCV::X9) 9243 .Case("{a0}", RISCV::X10) 9244 .Case("{a1}", RISCV::X11) 9245 .Case("{a2}", RISCV::X12) 9246 .Case("{a3}", RISCV::X13) 9247 .Case("{a4}", RISCV::X14) 9248 .Case("{a5}", RISCV::X15) 9249 .Case("{a6}", RISCV::X16) 9250 .Case("{a7}", RISCV::X17) 9251 .Case("{s2}", RISCV::X18) 9252 .Case("{s3}", RISCV::X19) 9253 .Case("{s4}", RISCV::X20) 9254 .Case("{s5}", RISCV::X21) 9255 .Case("{s6}", RISCV::X22) 9256 .Case("{s7}", RISCV::X23) 9257 .Case("{s8}", RISCV::X24) 9258 .Case("{s9}", RISCV::X25) 9259 .Case("{s10}", RISCV::X26) 9260 .Case("{s11}", RISCV::X27) 9261 .Case("{t3}", RISCV::X28) 9262 .Case("{t4}", RISCV::X29) 9263 .Case("{t5}", RISCV::X30) 9264 .Case("{t6}", RISCV::X31) 9265 .Default(RISCV::NoRegister); 9266 if (XRegFromAlias != RISCV::NoRegister) 9267 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 9268 9269 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 9270 // TableGen record rather than the AsmName to choose registers for InlineAsm 9271 // constraints, plus we want to match those names to the widest floating point 9272 // register type available, manually select floating point registers here. 9273 // 9274 // The second case is the ABI name of the register, so that frontends can also 9275 // use the ABI names in register constraint lists. 9276 if (Subtarget.hasStdExtF()) { 9277 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 9278 .Cases("{f0}", "{ft0}", RISCV::F0_F) 9279 .Cases("{f1}", "{ft1}", RISCV::F1_F) 9280 .Cases("{f2}", "{ft2}", RISCV::F2_F) 9281 .Cases("{f3}", "{ft3}", RISCV::F3_F) 9282 .Cases("{f4}", "{ft4}", RISCV::F4_F) 9283 .Cases("{f5}", "{ft5}", RISCV::F5_F) 9284 .Cases("{f6}", "{ft6}", RISCV::F6_F) 9285 .Cases("{f7}", "{ft7}", RISCV::F7_F) 9286 .Cases("{f8}", "{fs0}", RISCV::F8_F) 9287 .Cases("{f9}", "{fs1}", RISCV::F9_F) 9288 .Cases("{f10}", "{fa0}", RISCV::F10_F) 9289 .Cases("{f11}", "{fa1}", RISCV::F11_F) 9290 .Cases("{f12}", "{fa2}", RISCV::F12_F) 9291 .Cases("{f13}", "{fa3}", RISCV::F13_F) 9292 .Cases("{f14}", "{fa4}", RISCV::F14_F) 9293 .Cases("{f15}", "{fa5}", RISCV::F15_F) 9294 .Cases("{f16}", "{fa6}", RISCV::F16_F) 9295 .Cases("{f17}", "{fa7}", RISCV::F17_F) 9296 .Cases("{f18}", "{fs2}", RISCV::F18_F) 9297 .Cases("{f19}", "{fs3}", RISCV::F19_F) 9298 .Cases("{f20}", "{fs4}", RISCV::F20_F) 9299 .Cases("{f21}", "{fs5}", RISCV::F21_F) 9300 .Cases("{f22}", "{fs6}", RISCV::F22_F) 9301 .Cases("{f23}", "{fs7}", RISCV::F23_F) 9302 .Cases("{f24}", "{fs8}", RISCV::F24_F) 9303 .Cases("{f25}", "{fs9}", RISCV::F25_F) 9304 .Cases("{f26}", "{fs10}", RISCV::F26_F) 9305 .Cases("{f27}", "{fs11}", RISCV::F27_F) 9306 .Cases("{f28}", "{ft8}", RISCV::F28_F) 9307 .Cases("{f29}", "{ft9}", RISCV::F29_F) 9308 .Cases("{f30}", "{ft10}", RISCV::F30_F) 9309 .Cases("{f31}", "{ft11}", RISCV::F31_F) 9310 .Default(RISCV::NoRegister); 9311 if (FReg != RISCV::NoRegister) { 9312 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 9313 if (Subtarget.hasStdExtD()) { 9314 unsigned RegNo = FReg - RISCV::F0_F; 9315 unsigned DReg = RISCV::F0_D + RegNo; 9316 return std::make_pair(DReg, &RISCV::FPR64RegClass); 9317 } 9318 return std::make_pair(FReg, &RISCV::FPR32RegClass); 9319 } 9320 } 9321 9322 if (Subtarget.hasStdExtV()) { 9323 Register VReg = StringSwitch<Register>(Constraint.lower()) 9324 .Case("{v0}", RISCV::V0) 9325 .Case("{v1}", RISCV::V1) 9326 .Case("{v2}", RISCV::V2) 9327 .Case("{v3}", RISCV::V3) 9328 .Case("{v4}", RISCV::V4) 9329 .Case("{v5}", RISCV::V5) 9330 .Case("{v6}", RISCV::V6) 9331 .Case("{v7}", RISCV::V7) 9332 .Case("{v8}", RISCV::V8) 9333 .Case("{v9}", RISCV::V9) 9334 .Case("{v10}", RISCV::V10) 9335 .Case("{v11}", RISCV::V11) 9336 .Case("{v12}", RISCV::V12) 9337 .Case("{v13}", RISCV::V13) 9338 .Case("{v14}", RISCV::V14) 9339 .Case("{v15}", RISCV::V15) 9340 .Case("{v16}", RISCV::V16) 9341 .Case("{v17}", RISCV::V17) 9342 .Case("{v18}", RISCV::V18) 9343 .Case("{v19}", RISCV::V19) 9344 .Case("{v20}", RISCV::V20) 9345 .Case("{v21}", RISCV::V21) 9346 .Case("{v22}", RISCV::V22) 9347 .Case("{v23}", RISCV::V23) 9348 .Case("{v24}", RISCV::V24) 9349 .Case("{v25}", RISCV::V25) 9350 .Case("{v26}", RISCV::V26) 9351 .Case("{v27}", RISCV::V27) 9352 .Case("{v28}", RISCV::V28) 9353 .Case("{v29}", RISCV::V29) 9354 .Case("{v30}", RISCV::V30) 9355 .Case("{v31}", RISCV::V31) 9356 .Default(RISCV::NoRegister); 9357 if (VReg != RISCV::NoRegister) { 9358 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9359 return std::make_pair(VReg, &RISCV::VMRegClass); 9360 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 9361 return std::make_pair(VReg, &RISCV::VRRegClass); 9362 for (const auto *RC : 9363 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9364 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 9365 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 9366 return std::make_pair(VReg, RC); 9367 } 9368 } 9369 } 9370 } 9371 9372 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 9373 } 9374 9375 unsigned 9376 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 9377 // Currently only support length 1 constraints. 9378 if (ConstraintCode.size() == 1) { 9379 switch (ConstraintCode[0]) { 9380 case 'A': 9381 return InlineAsm::Constraint_A; 9382 default: 9383 break; 9384 } 9385 } 9386 9387 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 9388 } 9389 9390 void RISCVTargetLowering::LowerAsmOperandForConstraint( 9391 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 9392 SelectionDAG &DAG) const { 9393 // Currently only support length 1 constraints. 9394 if (Constraint.length() == 1) { 9395 switch (Constraint[0]) { 9396 case 'I': 9397 // Validate & create a 12-bit signed immediate operand. 9398 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9399 uint64_t CVal = C->getSExtValue(); 9400 if (isInt<12>(CVal)) 9401 Ops.push_back( 9402 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9403 } 9404 return; 9405 case 'J': 9406 // Validate & create an integer zero operand. 9407 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 9408 if (C->getZExtValue() == 0) 9409 Ops.push_back( 9410 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 9411 return; 9412 case 'K': 9413 // Validate & create a 5-bit unsigned immediate operand. 9414 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9415 uint64_t CVal = C->getZExtValue(); 9416 if (isUInt<5>(CVal)) 9417 Ops.push_back( 9418 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9419 } 9420 return; 9421 case 'S': 9422 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9423 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 9424 GA->getValueType(0))); 9425 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 9426 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 9427 BA->getValueType(0))); 9428 } 9429 return; 9430 default: 9431 break; 9432 } 9433 } 9434 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 9435 } 9436 9437 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 9438 Instruction *Inst, 9439 AtomicOrdering Ord) const { 9440 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 9441 return Builder.CreateFence(Ord); 9442 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 9443 return Builder.CreateFence(AtomicOrdering::Release); 9444 return nullptr; 9445 } 9446 9447 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 9448 Instruction *Inst, 9449 AtomicOrdering Ord) const { 9450 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 9451 return Builder.CreateFence(AtomicOrdering::Acquire); 9452 return nullptr; 9453 } 9454 9455 TargetLowering::AtomicExpansionKind 9456 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 9457 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 9458 // point operations can't be used in an lr/sc sequence without breaking the 9459 // forward-progress guarantee. 9460 if (AI->isFloatingPointOperation()) 9461 return AtomicExpansionKind::CmpXChg; 9462 9463 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 9464 if (Size == 8 || Size == 16) 9465 return AtomicExpansionKind::MaskedIntrinsic; 9466 return AtomicExpansionKind::None; 9467 } 9468 9469 static Intrinsic::ID 9470 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 9471 if (XLen == 32) { 9472 switch (BinOp) { 9473 default: 9474 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9475 case AtomicRMWInst::Xchg: 9476 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 9477 case AtomicRMWInst::Add: 9478 return Intrinsic::riscv_masked_atomicrmw_add_i32; 9479 case AtomicRMWInst::Sub: 9480 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 9481 case AtomicRMWInst::Nand: 9482 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 9483 case AtomicRMWInst::Max: 9484 return Intrinsic::riscv_masked_atomicrmw_max_i32; 9485 case AtomicRMWInst::Min: 9486 return Intrinsic::riscv_masked_atomicrmw_min_i32; 9487 case AtomicRMWInst::UMax: 9488 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 9489 case AtomicRMWInst::UMin: 9490 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 9491 } 9492 } 9493 9494 if (XLen == 64) { 9495 switch (BinOp) { 9496 default: 9497 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9498 case AtomicRMWInst::Xchg: 9499 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 9500 case AtomicRMWInst::Add: 9501 return Intrinsic::riscv_masked_atomicrmw_add_i64; 9502 case AtomicRMWInst::Sub: 9503 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 9504 case AtomicRMWInst::Nand: 9505 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 9506 case AtomicRMWInst::Max: 9507 return Intrinsic::riscv_masked_atomicrmw_max_i64; 9508 case AtomicRMWInst::Min: 9509 return Intrinsic::riscv_masked_atomicrmw_min_i64; 9510 case AtomicRMWInst::UMax: 9511 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 9512 case AtomicRMWInst::UMin: 9513 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 9514 } 9515 } 9516 9517 llvm_unreachable("Unexpected XLen\n"); 9518 } 9519 9520 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 9521 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 9522 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 9523 unsigned XLen = Subtarget.getXLen(); 9524 Value *Ordering = 9525 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 9526 Type *Tys[] = {AlignedAddr->getType()}; 9527 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 9528 AI->getModule(), 9529 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 9530 9531 if (XLen == 64) { 9532 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 9533 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 9534 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 9535 } 9536 9537 Value *Result; 9538 9539 // Must pass the shift amount needed to sign extend the loaded value prior 9540 // to performing a signed comparison for min/max. ShiftAmt is the number of 9541 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 9542 // is the number of bits to left+right shift the value in order to 9543 // sign-extend. 9544 if (AI->getOperation() == AtomicRMWInst::Min || 9545 AI->getOperation() == AtomicRMWInst::Max) { 9546 const DataLayout &DL = AI->getModule()->getDataLayout(); 9547 unsigned ValWidth = 9548 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 9549 Value *SextShamt = 9550 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 9551 Result = Builder.CreateCall(LrwOpScwLoop, 9552 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 9553 } else { 9554 Result = 9555 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 9556 } 9557 9558 if (XLen == 64) 9559 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 9560 return Result; 9561 } 9562 9563 TargetLowering::AtomicExpansionKind 9564 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 9565 AtomicCmpXchgInst *CI) const { 9566 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 9567 if (Size == 8 || Size == 16) 9568 return AtomicExpansionKind::MaskedIntrinsic; 9569 return AtomicExpansionKind::None; 9570 } 9571 9572 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 9573 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 9574 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 9575 unsigned XLen = Subtarget.getXLen(); 9576 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 9577 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 9578 if (XLen == 64) { 9579 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 9580 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 9581 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 9582 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 9583 } 9584 Type *Tys[] = {AlignedAddr->getType()}; 9585 Function *MaskedCmpXchg = 9586 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 9587 Value *Result = Builder.CreateCall( 9588 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 9589 if (XLen == 64) 9590 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 9591 return Result; 9592 } 9593 9594 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 9595 return false; 9596 } 9597 9598 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 9599 EVT VT) const { 9600 VT = VT.getScalarType(); 9601 9602 if (!VT.isSimple()) 9603 return false; 9604 9605 switch (VT.getSimpleVT().SimpleTy) { 9606 case MVT::f16: 9607 return Subtarget.hasStdExtZfh(); 9608 case MVT::f32: 9609 return Subtarget.hasStdExtF(); 9610 case MVT::f64: 9611 return Subtarget.hasStdExtD(); 9612 default: 9613 break; 9614 } 9615 9616 return false; 9617 } 9618 9619 Register RISCVTargetLowering::getExceptionPointerRegister( 9620 const Constant *PersonalityFn) const { 9621 return RISCV::X10; 9622 } 9623 9624 Register RISCVTargetLowering::getExceptionSelectorRegister( 9625 const Constant *PersonalityFn) const { 9626 return RISCV::X11; 9627 } 9628 9629 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 9630 // Return false to suppress the unnecessary extensions if the LibCall 9631 // arguments or return value is f32 type for LP64 ABI. 9632 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 9633 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 9634 return false; 9635 9636 return true; 9637 } 9638 9639 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 9640 if (Subtarget.is64Bit() && Type == MVT::i32) 9641 return true; 9642 9643 return IsSigned; 9644 } 9645 9646 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 9647 SDValue C) const { 9648 // Check integral scalar types. 9649 if (VT.isScalarInteger()) { 9650 // Omit the optimization if the sub target has the M extension and the data 9651 // size exceeds XLen. 9652 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 9653 return false; 9654 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 9655 // Break the MUL to a SLLI and an ADD/SUB. 9656 const APInt &Imm = ConstNode->getAPIntValue(); 9657 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 9658 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 9659 return true; 9660 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 9661 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 9662 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 9663 (Imm - 8).isPowerOf2())) 9664 return true; 9665 // Omit the following optimization if the sub target has the M extension 9666 // and the data size >= XLen. 9667 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 9668 return false; 9669 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 9670 // a pair of LUI/ADDI. 9671 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 9672 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 9673 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 9674 (1 - ImmS).isPowerOf2()) 9675 return true; 9676 } 9677 } 9678 } 9679 9680 return false; 9681 } 9682 9683 bool RISCVTargetLowering::isMulAddWithConstProfitable( 9684 const SDValue &AddNode, const SDValue &ConstNode) const { 9685 // Let the DAGCombiner decide for vectors. 9686 EVT VT = AddNode.getValueType(); 9687 if (VT.isVector()) 9688 return true; 9689 9690 // Let the DAGCombiner decide for larger types. 9691 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 9692 return true; 9693 9694 // It is worse if c1 is simm12 while c1*c2 is not. 9695 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 9696 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 9697 const APInt &C1 = C1Node->getAPIntValue(); 9698 const APInt &C2 = C2Node->getAPIntValue(); 9699 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 9700 return false; 9701 9702 // Default to true and let the DAGCombiner decide. 9703 return true; 9704 } 9705 9706 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 9707 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 9708 bool *Fast) const { 9709 if (!VT.isVector()) 9710 return false; 9711 9712 EVT ElemVT = VT.getVectorElementType(); 9713 if (Alignment >= ElemVT.getStoreSize()) { 9714 if (Fast) 9715 *Fast = true; 9716 return true; 9717 } 9718 9719 return false; 9720 } 9721 9722 bool RISCVTargetLowering::splitValueIntoRegisterParts( 9723 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 9724 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 9725 bool IsABIRegCopy = CC.hasValue(); 9726 EVT ValueVT = Val.getValueType(); 9727 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 9728 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 9729 // and cast to f32. 9730 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 9731 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 9732 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 9733 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 9734 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 9735 Parts[0] = Val; 9736 return true; 9737 } 9738 9739 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 9740 LLVMContext &Context = *DAG.getContext(); 9741 EVT ValueEltVT = ValueVT.getVectorElementType(); 9742 EVT PartEltVT = PartVT.getVectorElementType(); 9743 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 9744 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 9745 if (PartVTBitSize % ValueVTBitSize == 0) { 9746 // If the element types are different, bitcast to the same element type of 9747 // PartVT first. 9748 if (ValueEltVT != PartEltVT) { 9749 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 9750 assert(Count != 0 && "The number of element should not be zero."); 9751 EVT SameEltTypeVT = 9752 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 9753 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 9754 } 9755 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 9756 Val, DAG.getConstant(0, DL, Subtarget.getXLenVT())); 9757 Parts[0] = Val; 9758 return true; 9759 } 9760 } 9761 return false; 9762 } 9763 9764 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 9765 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 9766 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 9767 bool IsABIRegCopy = CC.hasValue(); 9768 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 9769 SDValue Val = Parts[0]; 9770 9771 // Cast the f32 to i32, truncate to i16, and cast back to f16. 9772 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 9773 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 9774 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 9775 return Val; 9776 } 9777 9778 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 9779 LLVMContext &Context = *DAG.getContext(); 9780 SDValue Val = Parts[0]; 9781 EVT ValueEltVT = ValueVT.getVectorElementType(); 9782 EVT PartEltVT = PartVT.getVectorElementType(); 9783 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 9784 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 9785 if (PartVTBitSize % ValueVTBitSize == 0) { 9786 EVT SameEltTypeVT = ValueVT; 9787 // If the element types are different, convert it to the same element type 9788 // of PartVT. 9789 if (ValueEltVT != PartEltVT) { 9790 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 9791 assert(Count != 0 && "The number of element should not be zero."); 9792 SameEltTypeVT = 9793 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 9794 } 9795 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val, 9796 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 9797 if (ValueEltVT != PartEltVT) 9798 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 9799 return Val; 9800 } 9801 } 9802 return SDValue(); 9803 } 9804 9805 #define GET_REGISTER_MATCHER 9806 #include "RISCVGenAsmMatcher.inc" 9807 9808 Register 9809 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 9810 const MachineFunction &MF) const { 9811 Register Reg = MatchRegisterAltName(RegName); 9812 if (Reg == RISCV::NoRegister) 9813 Reg = MatchRegisterName(RegName); 9814 if (Reg == RISCV::NoRegister) 9815 report_fatal_error( 9816 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 9817 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 9818 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 9819 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 9820 StringRef(RegName) + "\".")); 9821 return Reg; 9822 } 9823 9824 namespace llvm { 9825 namespace RISCVVIntrinsicsTable { 9826 9827 #define GET_RISCVVIntrinsicsTable_IMPL 9828 #include "RISCVGenSearchableTables.inc" 9829 9830 } // namespace RISCVVIntrinsicsTable 9831 9832 } // namespace llvm 9833