1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineRegisterInfo.h" 28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 29 #include "llvm/CodeGen/ValueTypes.h" 30 #include "llvm/IR/DiagnosticInfo.h" 31 #include "llvm/IR/DiagnosticPrinter.h" 32 #include "llvm/IR/IRBuilder.h" 33 #include "llvm/IR/IntrinsicsRISCV.h" 34 #include "llvm/IR/PatternMatch.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/KnownBits.h" 38 #include "llvm/Support/MathExtras.h" 39 #include "llvm/Support/raw_ostream.h" 40 41 using namespace llvm; 42 43 #define DEBUG_TYPE "riscv-lower" 44 45 STATISTIC(NumTailCalls, "Number of tail calls"); 46 47 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 48 const RISCVSubtarget &STI) 49 : TargetLowering(TM), Subtarget(STI) { 50 51 if (Subtarget.isRV32E()) 52 report_fatal_error("Codegen not yet implemented for RV32E"); 53 54 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 55 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 56 57 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 58 !Subtarget.hasStdExtF()) { 59 errs() << "Hard-float 'f' ABI can't be used for a target that " 60 "doesn't support the F instruction set extension (ignoring " 61 "target-abi)\n"; 62 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 63 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 64 !Subtarget.hasStdExtD()) { 65 errs() << "Hard-float 'd' ABI can't be used for a target that " 66 "doesn't support the D instruction set extension (ignoring " 67 "target-abi)\n"; 68 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 69 } 70 71 switch (ABI) { 72 default: 73 report_fatal_error("Don't know how to lower this ABI"); 74 case RISCVABI::ABI_ILP32: 75 case RISCVABI::ABI_ILP32F: 76 case RISCVABI::ABI_ILP32D: 77 case RISCVABI::ABI_LP64: 78 case RISCVABI::ABI_LP64F: 79 case RISCVABI::ABI_LP64D: 80 break; 81 } 82 83 MVT XLenVT = Subtarget.getXLenVT(); 84 85 // Set up the register classes. 86 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 87 88 if (Subtarget.hasStdExtZfh()) 89 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 90 if (Subtarget.hasStdExtF()) 91 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 92 if (Subtarget.hasStdExtD()) 93 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 94 95 static const MVT::SimpleValueType BoolVecVTs[] = { 96 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 97 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 98 static const MVT::SimpleValueType IntVecVTs[] = { 99 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 100 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 101 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 102 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 103 MVT::nxv4i64, MVT::nxv8i64}; 104 static const MVT::SimpleValueType F16VecVTs[] = { 105 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 106 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 107 static const MVT::SimpleValueType F32VecVTs[] = { 108 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 109 static const MVT::SimpleValueType F64VecVTs[] = { 110 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 111 112 if (Subtarget.hasVInstructions()) { 113 auto addRegClassForRVV = [this](MVT VT) { 114 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 115 assert(Size <= 512 && isPowerOf2_32(Size)); 116 const TargetRegisterClass *RC; 117 if (Size <= 64) 118 RC = &RISCV::VRRegClass; 119 else if (Size == 128) 120 RC = &RISCV::VRM2RegClass; 121 else if (Size == 256) 122 RC = &RISCV::VRM4RegClass; 123 else 124 RC = &RISCV::VRM8RegClass; 125 126 addRegisterClass(VT, RC); 127 }; 128 129 for (MVT VT : BoolVecVTs) 130 addRegClassForRVV(VT); 131 for (MVT VT : IntVecVTs) { 132 if (VT.getVectorElementType() == MVT::i64 && 133 !Subtarget.hasVInstructionsI64()) 134 continue; 135 addRegClassForRVV(VT); 136 } 137 138 if (Subtarget.hasVInstructionsF16()) 139 for (MVT VT : F16VecVTs) 140 addRegClassForRVV(VT); 141 142 if (Subtarget.hasVInstructionsF32()) 143 for (MVT VT : F32VecVTs) 144 addRegClassForRVV(VT); 145 146 if (Subtarget.hasVInstructionsF64()) 147 for (MVT VT : F64VecVTs) 148 addRegClassForRVV(VT); 149 150 if (Subtarget.useRVVForFixedLengthVectors()) { 151 auto addRegClassForFixedVectors = [this](MVT VT) { 152 MVT ContainerVT = getContainerForFixedLengthVector(VT); 153 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 154 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 155 addRegisterClass(VT, TRI.getRegClass(RCID)); 156 }; 157 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 158 if (useRVVForFixedLengthVectorVT(VT)) 159 addRegClassForFixedVectors(VT); 160 161 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 162 if (useRVVForFixedLengthVectorVT(VT)) 163 addRegClassForFixedVectors(VT); 164 } 165 } 166 167 // Compute derived properties from the register classes. 168 computeRegisterProperties(STI.getRegisterInfo()); 169 170 setStackPointerRegisterToSaveRestore(RISCV::X2); 171 172 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 173 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 174 175 // TODO: add all necessary setOperationAction calls. 176 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 177 178 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 179 setOperationAction(ISD::BR_CC, XLenVT, Expand); 180 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 181 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 182 183 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 184 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 185 186 setOperationAction(ISD::VASTART, MVT::Other, Custom); 187 setOperationAction(ISD::VAARG, MVT::Other, Expand); 188 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 189 setOperationAction(ISD::VAEND, MVT::Other, Expand); 190 191 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 192 if (!Subtarget.hasStdExtZbb()) { 193 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 195 } 196 197 if (Subtarget.is64Bit()) { 198 setOperationAction(ISD::ADD, MVT::i32, Custom); 199 setOperationAction(ISD::SUB, MVT::i32, Custom); 200 setOperationAction(ISD::SHL, MVT::i32, Custom); 201 setOperationAction(ISD::SRA, MVT::i32, Custom); 202 setOperationAction(ISD::SRL, MVT::i32, Custom); 203 204 setOperationAction(ISD::UADDO, MVT::i32, Custom); 205 setOperationAction(ISD::USUBO, MVT::i32, Custom); 206 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 207 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 208 } else { 209 setLibcallName(RTLIB::SHL_I128, nullptr); 210 setLibcallName(RTLIB::SRL_I128, nullptr); 211 setLibcallName(RTLIB::SRA_I128, nullptr); 212 setLibcallName(RTLIB::MUL_I128, nullptr); 213 setLibcallName(RTLIB::MULO_I64, nullptr); 214 } 215 216 if (!Subtarget.hasStdExtM()) { 217 setOperationAction(ISD::MUL, XLenVT, Expand); 218 setOperationAction(ISD::MULHS, XLenVT, Expand); 219 setOperationAction(ISD::MULHU, XLenVT, Expand); 220 setOperationAction(ISD::SDIV, XLenVT, Expand); 221 setOperationAction(ISD::UDIV, XLenVT, Expand); 222 setOperationAction(ISD::SREM, XLenVT, Expand); 223 setOperationAction(ISD::UREM, XLenVT, Expand); 224 } else { 225 if (Subtarget.is64Bit()) { 226 setOperationAction(ISD::MUL, MVT::i32, Custom); 227 setOperationAction(ISD::MUL, MVT::i128, Custom); 228 229 setOperationAction(ISD::SDIV, MVT::i8, Custom); 230 setOperationAction(ISD::UDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UREM, MVT::i8, Custom); 232 setOperationAction(ISD::SDIV, MVT::i16, Custom); 233 setOperationAction(ISD::UDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UREM, MVT::i16, Custom); 235 setOperationAction(ISD::SDIV, MVT::i32, Custom); 236 setOperationAction(ISD::UDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UREM, MVT::i32, Custom); 238 } else { 239 setOperationAction(ISD::MUL, MVT::i64, Custom); 240 } 241 } 242 243 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 244 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 246 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 247 248 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 249 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 251 252 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 253 if (Subtarget.is64Bit()) { 254 setOperationAction(ISD::ROTL, MVT::i32, Custom); 255 setOperationAction(ISD::ROTR, MVT::i32, Custom); 256 } 257 } else { 258 setOperationAction(ISD::ROTL, XLenVT, Expand); 259 setOperationAction(ISD::ROTR, XLenVT, Expand); 260 } 261 262 if (Subtarget.hasStdExtZbp()) { 263 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 264 // more combining. 265 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 266 setOperationAction(ISD::BSWAP, XLenVT, Custom); 267 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 268 // BSWAP i8 doesn't exist. 269 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 270 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 271 272 if (Subtarget.is64Bit()) { 273 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 274 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 275 } 276 } else { 277 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 278 // pattern match it directly in isel. 279 setOperationAction(ISD::BSWAP, XLenVT, 280 Subtarget.hasStdExtZbb() ? Legal : Expand); 281 } 282 283 if (Subtarget.hasStdExtZbb()) { 284 setOperationAction(ISD::SMIN, XLenVT, Legal); 285 setOperationAction(ISD::SMAX, XLenVT, Legal); 286 setOperationAction(ISD::UMIN, XLenVT, Legal); 287 setOperationAction(ISD::UMAX, XLenVT, Legal); 288 289 if (Subtarget.is64Bit()) { 290 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 291 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 292 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 293 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 294 } 295 } else { 296 setOperationAction(ISD::CTTZ, XLenVT, Expand); 297 setOperationAction(ISD::CTLZ, XLenVT, Expand); 298 setOperationAction(ISD::CTPOP, XLenVT, Expand); 299 } 300 301 if (Subtarget.hasStdExtZbt()) { 302 setOperationAction(ISD::FSHL, XLenVT, Custom); 303 setOperationAction(ISD::FSHR, XLenVT, Custom); 304 setOperationAction(ISD::SELECT, XLenVT, Legal); 305 306 if (Subtarget.is64Bit()) { 307 setOperationAction(ISD::FSHL, MVT::i32, Custom); 308 setOperationAction(ISD::FSHR, MVT::i32, Custom); 309 } 310 } else { 311 setOperationAction(ISD::SELECT, XLenVT, Custom); 312 } 313 314 static const ISD::CondCode FPCCToExpand[] = { 315 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 316 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 317 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 318 319 static const ISD::NodeType FPOpToExpand[] = { 320 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 321 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 322 323 if (Subtarget.hasStdExtZfh()) 324 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 325 326 if (Subtarget.hasStdExtZfh()) { 327 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 328 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 329 setOperationAction(ISD::LRINT, MVT::f16, Legal); 330 setOperationAction(ISD::LLRINT, MVT::f16, Legal); 331 setOperationAction(ISD::LROUND, MVT::f16, Legal); 332 setOperationAction(ISD::LLROUND, MVT::f16, Legal); 333 for (auto CC : FPCCToExpand) 334 setCondCodeAction(CC, MVT::f16, Expand); 335 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 336 setOperationAction(ISD::SELECT, MVT::f16, Custom); 337 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 338 for (auto Op : FPOpToExpand) 339 setOperationAction(Op, MVT::f16, Expand); 340 341 setOperationAction(ISD::FREM, MVT::f16, Promote); 342 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 343 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 344 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 345 setOperationAction(ISD::FRINT, MVT::f16, Promote); 346 setOperationAction(ISD::FROUND, MVT::f16, Promote); 347 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 348 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 349 } 350 351 if (Subtarget.hasStdExtF()) { 352 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 353 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 354 setOperationAction(ISD::LRINT, MVT::f32, Legal); 355 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 356 setOperationAction(ISD::LROUND, MVT::f32, Legal); 357 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 358 for (auto CC : FPCCToExpand) 359 setCondCodeAction(CC, MVT::f32, Expand); 360 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 361 setOperationAction(ISD::SELECT, MVT::f32, Custom); 362 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 363 for (auto Op : FPOpToExpand) 364 setOperationAction(Op, MVT::f32, Expand); 365 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 366 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 367 } 368 369 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 370 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 371 372 if (Subtarget.hasStdExtD()) { 373 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 374 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 375 setOperationAction(ISD::LRINT, MVT::f64, Legal); 376 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 377 setOperationAction(ISD::LROUND, MVT::f64, Legal); 378 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 379 for (auto CC : FPCCToExpand) 380 setCondCodeAction(CC, MVT::f64, Expand); 381 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 382 setOperationAction(ISD::SELECT, MVT::f64, Custom); 383 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 384 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 385 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 386 for (auto Op : FPOpToExpand) 387 setOperationAction(Op, MVT::f64, Expand); 388 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 389 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 390 } 391 392 if (Subtarget.is64Bit()) { 393 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 394 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 395 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 396 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 397 } 398 399 if (Subtarget.hasStdExtF()) { 400 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 401 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 402 403 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 404 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 405 } 406 407 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 408 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 409 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 410 setOperationAction(ISD::JumpTable, XLenVT, Custom); 411 412 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 413 414 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 415 // Unfortunately this can't be determined just from the ISA naming string. 416 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 417 Subtarget.is64Bit() ? Legal : Custom); 418 419 setOperationAction(ISD::TRAP, MVT::Other, Legal); 420 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 421 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 422 if (Subtarget.is64Bit()) 423 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 424 425 if (Subtarget.hasStdExtA()) { 426 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 427 setMinCmpXchgSizeInBits(32); 428 } else { 429 setMaxAtomicSizeInBitsSupported(0); 430 } 431 432 setBooleanContents(ZeroOrOneBooleanContent); 433 434 if (Subtarget.hasVInstructions()) { 435 setBooleanVectorContents(ZeroOrOneBooleanContent); 436 437 setOperationAction(ISD::VSCALE, XLenVT, Custom); 438 439 // RVV intrinsics may have illegal operands. 440 // We also need to custom legalize vmv.x.s. 441 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 442 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 443 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 444 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 445 if (Subtarget.is64Bit()) { 446 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 447 } else { 448 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 449 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 450 } 451 452 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 453 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 454 455 static const unsigned IntegerVPOps[] = { 456 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 457 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 458 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 459 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 460 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 461 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 462 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}; 463 464 static const unsigned FloatingPointVPOps[] = { 465 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 466 ISD::VP_FDIV, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 467 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX}; 468 469 if (!Subtarget.is64Bit()) { 470 // We must custom-lower certain vXi64 operations on RV32 due to the vector 471 // element type being illegal. 472 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 473 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 474 475 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 476 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 477 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 478 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 479 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 480 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 481 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 482 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 483 484 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 485 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 486 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 487 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 488 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 489 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 490 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 491 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 492 } 493 494 for (MVT VT : BoolVecVTs) { 495 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 496 497 // Mask VTs are custom-expanded into a series of standard nodes 498 setOperationAction(ISD::TRUNCATE, VT, Custom); 499 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 500 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 501 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 502 503 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 504 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 505 506 setOperationAction(ISD::SELECT, VT, Custom); 507 setOperationAction(ISD::SELECT_CC, VT, Expand); 508 setOperationAction(ISD::VSELECT, VT, Expand); 509 510 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 511 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 512 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 513 514 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 515 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 516 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 517 518 // RVV has native int->float & float->int conversions where the 519 // element type sizes are within one power-of-two of each other. Any 520 // wider distances between type sizes have to be lowered as sequences 521 // which progressively narrow the gap in stages. 522 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 523 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 524 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 525 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 526 527 // Expand all extending loads to types larger than this, and truncating 528 // stores from types larger than this. 529 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 530 setTruncStoreAction(OtherVT, VT, Expand); 531 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 532 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 533 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 534 } 535 } 536 537 for (MVT VT : IntVecVTs) { 538 if (VT.getVectorElementType() == MVT::i64 && 539 !Subtarget.hasVInstructionsI64()) 540 continue; 541 542 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 543 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 544 545 // Vectors implement MULHS/MULHU. 546 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 547 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 548 549 setOperationAction(ISD::SMIN, VT, Legal); 550 setOperationAction(ISD::SMAX, VT, Legal); 551 setOperationAction(ISD::UMIN, VT, Legal); 552 setOperationAction(ISD::UMAX, VT, Legal); 553 554 setOperationAction(ISD::ROTL, VT, Expand); 555 setOperationAction(ISD::ROTR, VT, Expand); 556 557 setOperationAction(ISD::CTTZ, VT, Expand); 558 setOperationAction(ISD::CTLZ, VT, Expand); 559 setOperationAction(ISD::CTPOP, VT, Expand); 560 561 setOperationAction(ISD::BSWAP, VT, Expand); 562 563 // Custom-lower extensions and truncations from/to mask types. 564 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 565 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 566 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 567 568 // RVV has native int->float & float->int conversions where the 569 // element type sizes are within one power-of-two of each other. Any 570 // wider distances between type sizes have to be lowered as sequences 571 // which progressively narrow the gap in stages. 572 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 573 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 574 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 575 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 576 577 setOperationAction(ISD::SADDSAT, VT, Legal); 578 setOperationAction(ISD::UADDSAT, VT, Legal); 579 setOperationAction(ISD::SSUBSAT, VT, Legal); 580 setOperationAction(ISD::USUBSAT, VT, Legal); 581 582 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 583 // nodes which truncate by one power of two at a time. 584 setOperationAction(ISD::TRUNCATE, VT, Custom); 585 586 // Custom-lower insert/extract operations to simplify patterns. 587 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 588 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 589 590 // Custom-lower reduction operations to set up the corresponding custom 591 // nodes' operands. 592 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 593 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 594 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 595 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 596 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 597 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 598 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 599 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 600 601 for (unsigned VPOpc : IntegerVPOps) 602 setOperationAction(VPOpc, VT, Custom); 603 604 setOperationAction(ISD::LOAD, VT, Custom); 605 setOperationAction(ISD::STORE, VT, Custom); 606 607 setOperationAction(ISD::MLOAD, VT, Custom); 608 setOperationAction(ISD::MSTORE, VT, Custom); 609 setOperationAction(ISD::MGATHER, VT, Custom); 610 setOperationAction(ISD::MSCATTER, VT, Custom); 611 612 setOperationAction(ISD::VP_LOAD, VT, Custom); 613 setOperationAction(ISD::VP_STORE, VT, Custom); 614 setOperationAction(ISD::VP_GATHER, VT, Custom); 615 setOperationAction(ISD::VP_SCATTER, VT, Custom); 616 617 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 618 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 619 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 620 621 setOperationAction(ISD::SELECT, VT, Custom); 622 setOperationAction(ISD::SELECT_CC, VT, Expand); 623 624 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 625 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 626 627 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 628 setTruncStoreAction(VT, OtherVT, Expand); 629 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 630 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 631 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 632 } 633 } 634 635 // Expand various CCs to best match the RVV ISA, which natively supports UNE 636 // but no other unordered comparisons, and supports all ordered comparisons 637 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 638 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 639 // and we pattern-match those back to the "original", swapping operands once 640 // more. This way we catch both operations and both "vf" and "fv" forms with 641 // fewer patterns. 642 static const ISD::CondCode VFPCCToExpand[] = { 643 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 644 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 645 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 646 }; 647 648 // Sets common operation actions on RVV floating-point vector types. 649 const auto SetCommonVFPActions = [&](MVT VT) { 650 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 651 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 652 // sizes are within one power-of-two of each other. Therefore conversions 653 // between vXf16 and vXf64 must be lowered as sequences which convert via 654 // vXf32. 655 setOperationAction(ISD::FP_ROUND, VT, Custom); 656 setOperationAction(ISD::FP_EXTEND, VT, Custom); 657 // Custom-lower insert/extract operations to simplify patterns. 658 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 659 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 660 // Expand various condition codes (explained above). 661 for (auto CC : VFPCCToExpand) 662 setCondCodeAction(CC, VT, Expand); 663 664 setOperationAction(ISD::FMINNUM, VT, Legal); 665 setOperationAction(ISD::FMAXNUM, VT, Legal); 666 667 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 668 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 669 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 670 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 671 672 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 673 674 setOperationAction(ISD::LOAD, VT, Custom); 675 setOperationAction(ISD::STORE, VT, Custom); 676 677 setOperationAction(ISD::MLOAD, VT, Custom); 678 setOperationAction(ISD::MSTORE, VT, Custom); 679 setOperationAction(ISD::MGATHER, VT, Custom); 680 setOperationAction(ISD::MSCATTER, VT, Custom); 681 682 setOperationAction(ISD::VP_LOAD, VT, Custom); 683 setOperationAction(ISD::VP_STORE, VT, Custom); 684 setOperationAction(ISD::VP_GATHER, VT, Custom); 685 setOperationAction(ISD::VP_SCATTER, VT, Custom); 686 687 setOperationAction(ISD::SELECT, VT, Custom); 688 setOperationAction(ISD::SELECT_CC, VT, Expand); 689 690 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 691 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 692 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 693 694 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 695 696 for (unsigned VPOpc : FloatingPointVPOps) 697 setOperationAction(VPOpc, VT, Custom); 698 }; 699 700 // Sets common extload/truncstore actions on RVV floating-point vector 701 // types. 702 const auto SetCommonVFPExtLoadTruncStoreActions = 703 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 704 for (auto SmallVT : SmallerVTs) { 705 setTruncStoreAction(VT, SmallVT, Expand); 706 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 707 } 708 }; 709 710 if (Subtarget.hasVInstructionsF16()) 711 for (MVT VT : F16VecVTs) 712 SetCommonVFPActions(VT); 713 714 for (MVT VT : F32VecVTs) { 715 if (Subtarget.hasVInstructionsF32()) 716 SetCommonVFPActions(VT); 717 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 718 } 719 720 for (MVT VT : F64VecVTs) { 721 if (Subtarget.hasVInstructionsF64()) 722 SetCommonVFPActions(VT); 723 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 724 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 725 } 726 727 if (Subtarget.useRVVForFixedLengthVectors()) { 728 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 729 if (!useRVVForFixedLengthVectorVT(VT)) 730 continue; 731 732 // By default everything must be expanded. 733 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 734 setOperationAction(Op, VT, Expand); 735 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 736 setTruncStoreAction(VT, OtherVT, Expand); 737 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 738 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 739 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 740 } 741 742 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 743 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 744 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 745 746 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 747 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 748 749 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 750 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 751 752 setOperationAction(ISD::LOAD, VT, Custom); 753 setOperationAction(ISD::STORE, VT, Custom); 754 755 setOperationAction(ISD::SETCC, VT, Custom); 756 757 setOperationAction(ISD::SELECT, VT, Custom); 758 759 setOperationAction(ISD::TRUNCATE, VT, Custom); 760 761 setOperationAction(ISD::BITCAST, VT, Custom); 762 763 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 764 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 765 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 766 767 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 768 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 769 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 770 771 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 772 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 773 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 774 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 775 776 // Operations below are different for between masks and other vectors. 777 if (VT.getVectorElementType() == MVT::i1) { 778 setOperationAction(ISD::AND, VT, Custom); 779 setOperationAction(ISD::OR, VT, Custom); 780 setOperationAction(ISD::XOR, VT, Custom); 781 continue; 782 } 783 784 // Use SPLAT_VECTOR to prevent type legalization from destroying the 785 // splats when type legalizing i64 scalar on RV32. 786 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 787 // improvements first. 788 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 789 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 790 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 791 } 792 793 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 794 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 795 796 setOperationAction(ISD::MLOAD, VT, Custom); 797 setOperationAction(ISD::MSTORE, VT, Custom); 798 setOperationAction(ISD::MGATHER, VT, Custom); 799 setOperationAction(ISD::MSCATTER, VT, Custom); 800 801 setOperationAction(ISD::VP_LOAD, VT, Custom); 802 setOperationAction(ISD::VP_STORE, VT, Custom); 803 setOperationAction(ISD::VP_GATHER, VT, Custom); 804 setOperationAction(ISD::VP_SCATTER, VT, Custom); 805 806 setOperationAction(ISD::ADD, VT, Custom); 807 setOperationAction(ISD::MUL, VT, Custom); 808 setOperationAction(ISD::SUB, VT, Custom); 809 setOperationAction(ISD::AND, VT, Custom); 810 setOperationAction(ISD::OR, VT, Custom); 811 setOperationAction(ISD::XOR, VT, Custom); 812 setOperationAction(ISD::SDIV, VT, Custom); 813 setOperationAction(ISD::SREM, VT, Custom); 814 setOperationAction(ISD::UDIV, VT, Custom); 815 setOperationAction(ISD::UREM, VT, Custom); 816 setOperationAction(ISD::SHL, VT, Custom); 817 setOperationAction(ISD::SRA, VT, Custom); 818 setOperationAction(ISD::SRL, VT, Custom); 819 820 setOperationAction(ISD::SMIN, VT, Custom); 821 setOperationAction(ISD::SMAX, VT, Custom); 822 setOperationAction(ISD::UMIN, VT, Custom); 823 setOperationAction(ISD::UMAX, VT, Custom); 824 setOperationAction(ISD::ABS, VT, Custom); 825 826 setOperationAction(ISD::MULHS, VT, Custom); 827 setOperationAction(ISD::MULHU, VT, Custom); 828 829 setOperationAction(ISD::SADDSAT, VT, Custom); 830 setOperationAction(ISD::UADDSAT, VT, Custom); 831 setOperationAction(ISD::SSUBSAT, VT, Custom); 832 setOperationAction(ISD::USUBSAT, VT, Custom); 833 834 setOperationAction(ISD::VSELECT, VT, Custom); 835 setOperationAction(ISD::SELECT_CC, VT, Expand); 836 837 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 838 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 839 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 840 841 // Custom-lower reduction operations to set up the corresponding custom 842 // nodes' operands. 843 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 844 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 845 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 846 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 847 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 848 849 for (unsigned VPOpc : IntegerVPOps) 850 setOperationAction(VPOpc, VT, Custom); 851 } 852 853 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 854 if (!useRVVForFixedLengthVectorVT(VT)) 855 continue; 856 857 // By default everything must be expanded. 858 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 859 setOperationAction(Op, VT, Expand); 860 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 861 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 862 setTruncStoreAction(VT, OtherVT, Expand); 863 } 864 865 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 866 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 867 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 868 869 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 870 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 871 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 872 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 873 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 874 875 setOperationAction(ISD::LOAD, VT, Custom); 876 setOperationAction(ISD::STORE, VT, Custom); 877 setOperationAction(ISD::MLOAD, VT, Custom); 878 setOperationAction(ISD::MSTORE, VT, Custom); 879 setOperationAction(ISD::MGATHER, VT, Custom); 880 setOperationAction(ISD::MSCATTER, VT, Custom); 881 882 setOperationAction(ISD::VP_LOAD, VT, Custom); 883 setOperationAction(ISD::VP_STORE, VT, Custom); 884 setOperationAction(ISD::VP_GATHER, VT, Custom); 885 setOperationAction(ISD::VP_SCATTER, VT, Custom); 886 887 setOperationAction(ISD::FADD, VT, Custom); 888 setOperationAction(ISD::FSUB, VT, Custom); 889 setOperationAction(ISD::FMUL, VT, Custom); 890 setOperationAction(ISD::FDIV, VT, Custom); 891 setOperationAction(ISD::FNEG, VT, Custom); 892 setOperationAction(ISD::FABS, VT, Custom); 893 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 894 setOperationAction(ISD::FSQRT, VT, Custom); 895 setOperationAction(ISD::FMA, VT, Custom); 896 setOperationAction(ISD::FMINNUM, VT, Custom); 897 setOperationAction(ISD::FMAXNUM, VT, Custom); 898 899 setOperationAction(ISD::FP_ROUND, VT, Custom); 900 setOperationAction(ISD::FP_EXTEND, VT, Custom); 901 902 for (auto CC : VFPCCToExpand) 903 setCondCodeAction(CC, VT, Expand); 904 905 setOperationAction(ISD::VSELECT, VT, Custom); 906 setOperationAction(ISD::SELECT, VT, Custom); 907 setOperationAction(ISD::SELECT_CC, VT, Expand); 908 909 setOperationAction(ISD::BITCAST, VT, Custom); 910 911 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 912 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 913 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 914 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 915 916 for (unsigned VPOpc : FloatingPointVPOps) 917 setOperationAction(VPOpc, VT, Custom); 918 } 919 920 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 921 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 922 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 923 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 924 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 925 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 926 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 927 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 928 } 929 } 930 931 // Function alignments. 932 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 933 setMinFunctionAlignment(FunctionAlignment); 934 setPrefFunctionAlignment(FunctionAlignment); 935 936 setMinimumJumpTableEntries(5); 937 938 // Jumps are expensive, compared to logic 939 setJumpIsExpensive(); 940 941 // We can use any register for comparisons 942 setHasMultipleConditionRegisters(); 943 944 setTargetDAGCombine(ISD::ADD); 945 setTargetDAGCombine(ISD::SUB); 946 setTargetDAGCombine(ISD::AND); 947 setTargetDAGCombine(ISD::OR); 948 setTargetDAGCombine(ISD::XOR); 949 setTargetDAGCombine(ISD::ANY_EXTEND); 950 setTargetDAGCombine(ISD::ZERO_EXTEND); 951 if (Subtarget.hasVInstructions()) { 952 setTargetDAGCombine(ISD::FCOPYSIGN); 953 setTargetDAGCombine(ISD::MGATHER); 954 setTargetDAGCombine(ISD::MSCATTER); 955 setTargetDAGCombine(ISD::VP_GATHER); 956 setTargetDAGCombine(ISD::VP_SCATTER); 957 setTargetDAGCombine(ISD::SRA); 958 setTargetDAGCombine(ISD::SRL); 959 setTargetDAGCombine(ISD::SHL); 960 setTargetDAGCombine(ISD::STORE); 961 } 962 } 963 964 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 965 LLVMContext &Context, 966 EVT VT) const { 967 if (!VT.isVector()) 968 return getPointerTy(DL); 969 if (Subtarget.hasVInstructions() && 970 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 971 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 972 return VT.changeVectorElementTypeToInteger(); 973 } 974 975 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 976 return Subtarget.getXLenVT(); 977 } 978 979 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 980 const CallInst &I, 981 MachineFunction &MF, 982 unsigned Intrinsic) const { 983 auto &DL = I.getModule()->getDataLayout(); 984 switch (Intrinsic) { 985 default: 986 return false; 987 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 988 case Intrinsic::riscv_masked_atomicrmw_add_i32: 989 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 990 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 991 case Intrinsic::riscv_masked_atomicrmw_max_i32: 992 case Intrinsic::riscv_masked_atomicrmw_min_i32: 993 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 994 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 995 case Intrinsic::riscv_masked_cmpxchg_i32: { 996 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 997 Info.opc = ISD::INTRINSIC_W_CHAIN; 998 Info.memVT = MVT::getVT(PtrTy->getElementType()); 999 Info.ptrVal = I.getArgOperand(0); 1000 Info.offset = 0; 1001 Info.align = Align(4); 1002 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1003 MachineMemOperand::MOVolatile; 1004 return true; 1005 } 1006 case Intrinsic::riscv_masked_strided_load: 1007 Info.opc = ISD::INTRINSIC_W_CHAIN; 1008 Info.ptrVal = I.getArgOperand(1); 1009 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1010 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1011 Info.size = MemoryLocation::UnknownSize; 1012 Info.flags |= MachineMemOperand::MOLoad; 1013 return true; 1014 case Intrinsic::riscv_masked_strided_store: 1015 Info.opc = ISD::INTRINSIC_VOID; 1016 Info.ptrVal = I.getArgOperand(1); 1017 Info.memVT = 1018 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1019 Info.align = Align( 1020 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1021 8); 1022 Info.size = MemoryLocation::UnknownSize; 1023 Info.flags |= MachineMemOperand::MOStore; 1024 return true; 1025 } 1026 } 1027 1028 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1029 const AddrMode &AM, Type *Ty, 1030 unsigned AS, 1031 Instruction *I) const { 1032 // No global is ever allowed as a base. 1033 if (AM.BaseGV) 1034 return false; 1035 1036 // Require a 12-bit signed offset. 1037 if (!isInt<12>(AM.BaseOffs)) 1038 return false; 1039 1040 switch (AM.Scale) { 1041 case 0: // "r+i" or just "i", depending on HasBaseReg. 1042 break; 1043 case 1: 1044 if (!AM.HasBaseReg) // allow "r+i". 1045 break; 1046 return false; // disallow "r+r" or "r+r+i". 1047 default: 1048 return false; 1049 } 1050 1051 return true; 1052 } 1053 1054 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1055 return isInt<12>(Imm); 1056 } 1057 1058 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1059 return isInt<12>(Imm); 1060 } 1061 1062 // On RV32, 64-bit integers are split into their high and low parts and held 1063 // in two different registers, so the trunc is free since the low register can 1064 // just be used. 1065 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1066 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1067 return false; 1068 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1069 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1070 return (SrcBits == 64 && DestBits == 32); 1071 } 1072 1073 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1074 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1075 !SrcVT.isInteger() || !DstVT.isInteger()) 1076 return false; 1077 unsigned SrcBits = SrcVT.getSizeInBits(); 1078 unsigned DestBits = DstVT.getSizeInBits(); 1079 return (SrcBits == 64 && DestBits == 32); 1080 } 1081 1082 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1083 // Zexts are free if they can be combined with a load. 1084 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1085 EVT MemVT = LD->getMemoryVT(); 1086 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 1087 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 1088 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1089 LD->getExtensionType() == ISD::ZEXTLOAD)) 1090 return true; 1091 } 1092 1093 return TargetLowering::isZExtFree(Val, VT2); 1094 } 1095 1096 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1097 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1098 } 1099 1100 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1101 return Subtarget.hasStdExtZbb(); 1102 } 1103 1104 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1105 return Subtarget.hasStdExtZbb(); 1106 } 1107 1108 /// Check if sinking \p I's operands to I's basic block is profitable, because 1109 /// the operands can be folded into a target instruction, e.g. 1110 /// splats of scalars can fold into vector instructions. 1111 bool RISCVTargetLowering::shouldSinkOperands( 1112 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1113 using namespace llvm::PatternMatch; 1114 1115 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1116 return false; 1117 1118 auto IsSinker = [&](Instruction *I, int Operand) { 1119 switch (I->getOpcode()) { 1120 case Instruction::Add: 1121 case Instruction::Sub: 1122 case Instruction::Mul: 1123 case Instruction::And: 1124 case Instruction::Or: 1125 case Instruction::Xor: 1126 case Instruction::FAdd: 1127 case Instruction::FSub: 1128 case Instruction::FMul: 1129 case Instruction::FDiv: 1130 case Instruction::ICmp: 1131 case Instruction::FCmp: 1132 return true; 1133 case Instruction::Shl: 1134 case Instruction::LShr: 1135 case Instruction::AShr: 1136 return Operand == 1; 1137 case Instruction::Call: 1138 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1139 switch (II->getIntrinsicID()) { 1140 case Intrinsic::fma: 1141 return Operand == 0 || Operand == 1; 1142 default: 1143 return false; 1144 } 1145 } 1146 return false; 1147 default: 1148 return false; 1149 } 1150 }; 1151 1152 for (auto OpIdx : enumerate(I->operands())) { 1153 if (!IsSinker(I, OpIdx.index())) 1154 continue; 1155 1156 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1157 // Make sure we are not already sinking this operand 1158 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1159 continue; 1160 1161 // We are looking for a splat that can be sunk. 1162 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1163 m_Undef(), m_ZeroMask()))) 1164 continue; 1165 1166 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1167 // and vector registers 1168 for (Use &U : Op->uses()) { 1169 Instruction *Insn = cast<Instruction>(U.getUser()); 1170 if (!IsSinker(Insn, U.getOperandNo())) 1171 return false; 1172 } 1173 1174 Ops.push_back(&Op->getOperandUse(0)); 1175 Ops.push_back(&OpIdx.value()); 1176 } 1177 return true; 1178 } 1179 1180 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1181 bool ForCodeSize) const { 1182 if (VT == MVT::f16 && !Subtarget.hasStdExtZfhmin()) 1183 return false; 1184 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1185 return false; 1186 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1187 return false; 1188 if (Imm.isNegZero()) 1189 return false; 1190 return Imm.isZero(); 1191 } 1192 1193 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1194 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1195 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1196 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1197 } 1198 1199 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1200 CallingConv::ID CC, 1201 EVT VT) const { 1202 // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled. 1203 // We might still end up using a GPR but that will be decided based on ABI. 1204 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin()) 1205 return MVT::f32; 1206 1207 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1208 } 1209 1210 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1211 CallingConv::ID CC, 1212 EVT VT) const { 1213 // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled. 1214 // We might still end up using a GPR but that will be decided based on ABI. 1215 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin()) 1216 return 1; 1217 1218 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1219 } 1220 1221 // Changes the condition code and swaps operands if necessary, so the SetCC 1222 // operation matches one of the comparisons supported directly by branches 1223 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1224 // with 1/-1. 1225 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1226 ISD::CondCode &CC, SelectionDAG &DAG) { 1227 // Convert X > -1 to X >= 0. 1228 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1229 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1230 CC = ISD::SETGE; 1231 return; 1232 } 1233 // Convert X < 1 to 0 >= X. 1234 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1235 RHS = LHS; 1236 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1237 CC = ISD::SETGE; 1238 return; 1239 } 1240 1241 switch (CC) { 1242 default: 1243 break; 1244 case ISD::SETGT: 1245 case ISD::SETLE: 1246 case ISD::SETUGT: 1247 case ISD::SETULE: 1248 CC = ISD::getSetCCSwappedOperands(CC); 1249 std::swap(LHS, RHS); 1250 break; 1251 } 1252 } 1253 1254 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1255 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1256 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1257 if (VT.getVectorElementType() == MVT::i1) 1258 KnownSize *= 8; 1259 1260 switch (KnownSize) { 1261 default: 1262 llvm_unreachable("Invalid LMUL."); 1263 case 8: 1264 return RISCVII::VLMUL::LMUL_F8; 1265 case 16: 1266 return RISCVII::VLMUL::LMUL_F4; 1267 case 32: 1268 return RISCVII::VLMUL::LMUL_F2; 1269 case 64: 1270 return RISCVII::VLMUL::LMUL_1; 1271 case 128: 1272 return RISCVII::VLMUL::LMUL_2; 1273 case 256: 1274 return RISCVII::VLMUL::LMUL_4; 1275 case 512: 1276 return RISCVII::VLMUL::LMUL_8; 1277 } 1278 } 1279 1280 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1281 switch (LMul) { 1282 default: 1283 llvm_unreachable("Invalid LMUL."); 1284 case RISCVII::VLMUL::LMUL_F8: 1285 case RISCVII::VLMUL::LMUL_F4: 1286 case RISCVII::VLMUL::LMUL_F2: 1287 case RISCVII::VLMUL::LMUL_1: 1288 return RISCV::VRRegClassID; 1289 case RISCVII::VLMUL::LMUL_2: 1290 return RISCV::VRM2RegClassID; 1291 case RISCVII::VLMUL::LMUL_4: 1292 return RISCV::VRM4RegClassID; 1293 case RISCVII::VLMUL::LMUL_8: 1294 return RISCV::VRM8RegClassID; 1295 } 1296 } 1297 1298 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1299 RISCVII::VLMUL LMUL = getLMUL(VT); 1300 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1301 LMUL == RISCVII::VLMUL::LMUL_F4 || 1302 LMUL == RISCVII::VLMUL::LMUL_F2 || 1303 LMUL == RISCVII::VLMUL::LMUL_1) { 1304 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1305 "Unexpected subreg numbering"); 1306 return RISCV::sub_vrm1_0 + Index; 1307 } 1308 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1309 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1310 "Unexpected subreg numbering"); 1311 return RISCV::sub_vrm2_0 + Index; 1312 } 1313 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1314 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1315 "Unexpected subreg numbering"); 1316 return RISCV::sub_vrm4_0 + Index; 1317 } 1318 llvm_unreachable("Invalid vector type."); 1319 } 1320 1321 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1322 if (VT.getVectorElementType() == MVT::i1) 1323 return RISCV::VRRegClassID; 1324 return getRegClassIDForLMUL(getLMUL(VT)); 1325 } 1326 1327 // Attempt to decompose a subvector insert/extract between VecVT and 1328 // SubVecVT via subregister indices. Returns the subregister index that 1329 // can perform the subvector insert/extract with the given element index, as 1330 // well as the index corresponding to any leftover subvectors that must be 1331 // further inserted/extracted within the register class for SubVecVT. 1332 std::pair<unsigned, unsigned> 1333 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1334 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1335 const RISCVRegisterInfo *TRI) { 1336 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1337 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1338 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1339 "Register classes not ordered"); 1340 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1341 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1342 // Try to compose a subregister index that takes us from the incoming 1343 // LMUL>1 register class down to the outgoing one. At each step we half 1344 // the LMUL: 1345 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1346 // Note that this is not guaranteed to find a subregister index, such as 1347 // when we are extracting from one VR type to another. 1348 unsigned SubRegIdx = RISCV::NoSubRegister; 1349 for (const unsigned RCID : 1350 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1351 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1352 VecVT = VecVT.getHalfNumVectorElementsVT(); 1353 bool IsHi = 1354 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1355 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1356 getSubregIndexByMVT(VecVT, IsHi)); 1357 if (IsHi) 1358 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1359 } 1360 return {SubRegIdx, InsertExtractIdx}; 1361 } 1362 1363 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1364 // stores for those types. 1365 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1366 return !Subtarget.useRVVForFixedLengthVectors() || 1367 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1368 } 1369 1370 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1371 if (ScalarTy->isPointerTy()) 1372 return true; 1373 1374 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1375 ScalarTy->isIntegerTy(32)) 1376 return true; 1377 1378 if (ScalarTy->isIntegerTy(64)) 1379 return Subtarget.hasVInstructionsI64(); 1380 1381 if (ScalarTy->isHalfTy()) 1382 return Subtarget.hasVInstructionsF16(); 1383 if (ScalarTy->isFloatTy()) 1384 return Subtarget.hasVInstructionsF32(); 1385 if (ScalarTy->isDoubleTy()) 1386 return Subtarget.hasVInstructionsF64(); 1387 1388 return false; 1389 } 1390 1391 static bool useRVVForFixedLengthVectorVT(MVT VT, 1392 const RISCVSubtarget &Subtarget) { 1393 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1394 if (!Subtarget.useRVVForFixedLengthVectors()) 1395 return false; 1396 1397 // We only support a set of vector types with a consistent maximum fixed size 1398 // across all supported vector element types to avoid legalization issues. 1399 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1400 // fixed-length vector type we support is 1024 bytes. 1401 if (VT.getFixedSizeInBits() > 1024 * 8) 1402 return false; 1403 1404 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1405 1406 MVT EltVT = VT.getVectorElementType(); 1407 1408 // Don't use RVV for vectors we cannot scalarize if required. 1409 switch (EltVT.SimpleTy) { 1410 // i1 is supported but has different rules. 1411 default: 1412 return false; 1413 case MVT::i1: 1414 // Masks can only use a single register. 1415 if (VT.getVectorNumElements() > MinVLen) 1416 return false; 1417 MinVLen /= 8; 1418 break; 1419 case MVT::i8: 1420 case MVT::i16: 1421 case MVT::i32: 1422 break; 1423 case MVT::i64: 1424 if (!Subtarget.hasVInstructionsI64()) 1425 return false; 1426 break; 1427 case MVT::f16: 1428 if (!Subtarget.hasVInstructionsF16()) 1429 return false; 1430 break; 1431 case MVT::f32: 1432 if (!Subtarget.hasVInstructionsF32()) 1433 return false; 1434 break; 1435 case MVT::f64: 1436 if (!Subtarget.hasVInstructionsF64()) 1437 return false; 1438 break; 1439 } 1440 1441 // Reject elements larger than ELEN. 1442 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1443 return false; 1444 1445 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1446 // Don't use RVV for types that don't fit. 1447 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1448 return false; 1449 1450 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1451 // the base fixed length RVV support in place. 1452 if (!VT.isPow2VectorType()) 1453 return false; 1454 1455 return true; 1456 } 1457 1458 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1459 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1460 } 1461 1462 // Return the largest legal scalable vector type that matches VT's element type. 1463 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1464 const RISCVSubtarget &Subtarget) { 1465 // This may be called before legal types are setup. 1466 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1467 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1468 "Expected legal fixed length vector!"); 1469 1470 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1471 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1472 1473 MVT EltVT = VT.getVectorElementType(); 1474 switch (EltVT.SimpleTy) { 1475 default: 1476 llvm_unreachable("unexpected element type for RVV container"); 1477 case MVT::i1: 1478 case MVT::i8: 1479 case MVT::i16: 1480 case MVT::i32: 1481 case MVT::i64: 1482 case MVT::f16: 1483 case MVT::f32: 1484 case MVT::f64: { 1485 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1486 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1487 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1488 unsigned NumElts = 1489 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1490 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1491 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1492 return MVT::getScalableVectorVT(EltVT, NumElts); 1493 } 1494 } 1495 } 1496 1497 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1498 const RISCVSubtarget &Subtarget) { 1499 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1500 Subtarget); 1501 } 1502 1503 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1504 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1505 } 1506 1507 // Grow V to consume an entire RVV register. 1508 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1509 const RISCVSubtarget &Subtarget) { 1510 assert(VT.isScalableVector() && 1511 "Expected to convert into a scalable vector!"); 1512 assert(V.getValueType().isFixedLengthVector() && 1513 "Expected a fixed length vector operand!"); 1514 SDLoc DL(V); 1515 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1516 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1517 } 1518 1519 // Shrink V so it's just big enough to maintain a VT's worth of data. 1520 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1521 const RISCVSubtarget &Subtarget) { 1522 assert(VT.isFixedLengthVector() && 1523 "Expected to convert into a fixed length vector!"); 1524 assert(V.getValueType().isScalableVector() && 1525 "Expected a scalable vector operand!"); 1526 SDLoc DL(V); 1527 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1528 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1529 } 1530 1531 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1532 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1533 // the vector type that it is contained in. 1534 static std::pair<SDValue, SDValue> 1535 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1536 const RISCVSubtarget &Subtarget) { 1537 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1538 MVT XLenVT = Subtarget.getXLenVT(); 1539 SDValue VL = VecVT.isFixedLengthVector() 1540 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1541 : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT); 1542 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1543 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1544 return {Mask, VL}; 1545 } 1546 1547 // As above but assuming the given type is a scalable vector type. 1548 static std::pair<SDValue, SDValue> 1549 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1550 const RISCVSubtarget &Subtarget) { 1551 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1552 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1553 } 1554 1555 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1556 // of either is (currently) supported. This can get us into an infinite loop 1557 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1558 // as a ..., etc. 1559 // Until either (or both) of these can reliably lower any node, reporting that 1560 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1561 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1562 // which is not desirable. 1563 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1564 EVT VT, unsigned DefinedValues) const { 1565 return false; 1566 } 1567 1568 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1569 // Only splats are currently supported. 1570 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1571 return true; 1572 1573 return false; 1574 } 1575 1576 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) { 1577 // RISCV FP-to-int conversions saturate to the destination register size, but 1578 // don't produce 0 for nan. We can use a conversion instruction and fix the 1579 // nan case with a compare and a select. 1580 SDValue Src = Op.getOperand(0); 1581 1582 EVT DstVT = Op.getValueType(); 1583 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1584 1585 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1586 unsigned Opc; 1587 if (SatVT == DstVT) 1588 Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ; 1589 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1590 Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 1591 else 1592 return SDValue(); 1593 // FIXME: Support other SatVTs by clamping before or after the conversion. 1594 1595 SDLoc DL(Op); 1596 SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src); 1597 1598 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1599 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1600 } 1601 1602 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1603 const RISCVSubtarget &Subtarget) { 1604 MVT VT = Op.getSimpleValueType(); 1605 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1606 1607 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1608 1609 SDLoc DL(Op); 1610 SDValue Mask, VL; 1611 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1612 1613 unsigned Opc = 1614 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1615 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1616 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1617 } 1618 1619 struct VIDSequence { 1620 int64_t StepNumerator; 1621 unsigned StepDenominator; 1622 int64_t Addend; 1623 }; 1624 1625 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1626 // to the (non-zero) step S and start value X. This can be then lowered as the 1627 // RVV sequence (VID * S) + X, for example. 1628 // The step S is represented as an integer numerator divided by a positive 1629 // denominator. Note that the implementation currently only identifies 1630 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1631 // cannot detect 2/3, for example. 1632 // Note that this method will also match potentially unappealing index 1633 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1634 // determine whether this is worth generating code for. 1635 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1636 unsigned NumElts = Op.getNumOperands(); 1637 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1638 if (!Op.getValueType().isInteger()) 1639 return None; 1640 1641 Optional<unsigned> SeqStepDenom; 1642 Optional<int64_t> SeqStepNum, SeqAddend; 1643 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1644 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1645 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1646 // Assume undef elements match the sequence; we just have to be careful 1647 // when interpolating across them. 1648 if (Op.getOperand(Idx).isUndef()) 1649 continue; 1650 // The BUILD_VECTOR must be all constants. 1651 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1652 return None; 1653 1654 uint64_t Val = Op.getConstantOperandVal(Idx) & 1655 maskTrailingOnes<uint64_t>(EltSizeInBits); 1656 1657 if (PrevElt) { 1658 // Calculate the step since the last non-undef element, and ensure 1659 // it's consistent across the entire sequence. 1660 unsigned IdxDiff = Idx - PrevElt->second; 1661 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1662 1663 // A zero-value value difference means that we're somewhere in the middle 1664 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1665 // step change before evaluating the sequence. 1666 if (ValDiff != 0) { 1667 int64_t Remainder = ValDiff % IdxDiff; 1668 // Normalize the step if it's greater than 1. 1669 if (Remainder != ValDiff) { 1670 // The difference must cleanly divide the element span. 1671 if (Remainder != 0) 1672 return None; 1673 ValDiff /= IdxDiff; 1674 IdxDiff = 1; 1675 } 1676 1677 if (!SeqStepNum) 1678 SeqStepNum = ValDiff; 1679 else if (ValDiff != SeqStepNum) 1680 return None; 1681 1682 if (!SeqStepDenom) 1683 SeqStepDenom = IdxDiff; 1684 else if (IdxDiff != *SeqStepDenom) 1685 return None; 1686 } 1687 } 1688 1689 // Record and/or check any addend. 1690 if (SeqStepNum && SeqStepDenom) { 1691 uint64_t ExpectedVal = 1692 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1693 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1694 if (!SeqAddend) 1695 SeqAddend = Addend; 1696 else if (SeqAddend != Addend) 1697 return None; 1698 } 1699 1700 // Record this non-undef element for later. 1701 if (!PrevElt || PrevElt->first != Val) 1702 PrevElt = std::make_pair(Val, Idx); 1703 } 1704 // We need to have logged both a step and an addend for this to count as 1705 // a legal index sequence. 1706 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1707 return None; 1708 1709 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1710 } 1711 1712 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1713 const RISCVSubtarget &Subtarget) { 1714 MVT VT = Op.getSimpleValueType(); 1715 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1716 1717 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1718 1719 SDLoc DL(Op); 1720 SDValue Mask, VL; 1721 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1722 1723 MVT XLenVT = Subtarget.getXLenVT(); 1724 unsigned NumElts = Op.getNumOperands(); 1725 1726 if (VT.getVectorElementType() == MVT::i1) { 1727 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1728 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1729 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1730 } 1731 1732 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1733 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1734 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1735 } 1736 1737 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1738 // scalar integer chunks whose bit-width depends on the number of mask 1739 // bits and XLEN. 1740 // First, determine the most appropriate scalar integer type to use. This 1741 // is at most XLenVT, but may be shrunk to a smaller vector element type 1742 // according to the size of the final vector - use i8 chunks rather than 1743 // XLenVT if we're producing a v8i1. This results in more consistent 1744 // codegen across RV32 and RV64. 1745 unsigned NumViaIntegerBits = 1746 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1747 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1748 // If we have to use more than one INSERT_VECTOR_ELT then this 1749 // optimization is likely to increase code size; avoid peforming it in 1750 // such a case. We can use a load from a constant pool in this case. 1751 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1752 return SDValue(); 1753 // Now we can create our integer vector type. Note that it may be larger 1754 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1755 MVT IntegerViaVecVT = 1756 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1757 divideCeil(NumElts, NumViaIntegerBits)); 1758 1759 uint64_t Bits = 0; 1760 unsigned BitPos = 0, IntegerEltIdx = 0; 1761 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1762 1763 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1764 // Once we accumulate enough bits to fill our scalar type, insert into 1765 // our vector and clear our accumulated data. 1766 if (I != 0 && I % NumViaIntegerBits == 0) { 1767 if (NumViaIntegerBits <= 32) 1768 Bits = SignExtend64(Bits, 32); 1769 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1770 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1771 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1772 Bits = 0; 1773 BitPos = 0; 1774 IntegerEltIdx++; 1775 } 1776 SDValue V = Op.getOperand(I); 1777 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1778 Bits |= ((uint64_t)BitValue << BitPos); 1779 } 1780 1781 // Insert the (remaining) scalar value into position in our integer 1782 // vector type. 1783 if (NumViaIntegerBits <= 32) 1784 Bits = SignExtend64(Bits, 32); 1785 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1786 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1787 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1788 1789 if (NumElts < NumViaIntegerBits) { 1790 // If we're producing a smaller vector than our minimum legal integer 1791 // type, bitcast to the equivalent (known-legal) mask type, and extract 1792 // our final mask. 1793 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1794 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1795 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1796 DAG.getConstant(0, DL, XLenVT)); 1797 } else { 1798 // Else we must have produced an integer type with the same size as the 1799 // mask type; bitcast for the final result. 1800 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1801 Vec = DAG.getBitcast(VT, Vec); 1802 } 1803 1804 return Vec; 1805 } 1806 1807 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 1808 // vector type, we have a legal equivalently-sized i8 type, so we can use 1809 // that. 1810 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 1811 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 1812 1813 SDValue WideVec; 1814 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1815 // For a splat, perform a scalar truncate before creating the wider 1816 // vector. 1817 assert(Splat.getValueType() == XLenVT && 1818 "Unexpected type for i1 splat value"); 1819 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 1820 DAG.getConstant(1, DL, XLenVT)); 1821 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 1822 } else { 1823 SmallVector<SDValue, 8> Ops(Op->op_values()); 1824 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 1825 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 1826 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 1827 } 1828 1829 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 1830 } 1831 1832 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1833 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 1834 : RISCVISD::VMV_V_X_VL; 1835 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 1836 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1837 } 1838 1839 // Try and match index sequences, which we can lower to the vid instruction 1840 // with optional modifications. An all-undef vector is matched by 1841 // getSplatValue, above. 1842 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 1843 int64_t StepNumerator = SimpleVID->StepNumerator; 1844 unsigned StepDenominator = SimpleVID->StepDenominator; 1845 int64_t Addend = SimpleVID->Addend; 1846 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 1847 // threshold since it's the immediate value many RVV instructions accept. 1848 if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) && 1849 isInt<5>(Addend)) { 1850 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 1851 // Convert right out of the scalable type so we can use standard ISD 1852 // nodes for the rest of the computation. If we used scalable types with 1853 // these, we'd lose the fixed-length vector info and generate worse 1854 // vsetvli code. 1855 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 1856 assert(StepNumerator != 0 && "Invalid step"); 1857 bool Negate = false; 1858 if (StepNumerator != 1) { 1859 int64_t SplatStepVal = StepNumerator; 1860 unsigned Opcode = ISD::MUL; 1861 if (isPowerOf2_64(std::abs(StepNumerator))) { 1862 Negate = StepNumerator < 0; 1863 Opcode = ISD::SHL; 1864 SplatStepVal = Log2_64(std::abs(StepNumerator)); 1865 } 1866 SDValue SplatStep = DAG.getSplatVector( 1867 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 1868 VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep); 1869 } 1870 if (StepDenominator != 1) { 1871 SDValue SplatStep = DAG.getSplatVector( 1872 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 1873 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 1874 } 1875 if (Addend != 0 || Negate) { 1876 SDValue SplatAddend = 1877 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 1878 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 1879 } 1880 return VID; 1881 } 1882 } 1883 1884 // Attempt to detect "hidden" splats, which only reveal themselves as splats 1885 // when re-interpreted as a vector with a larger element type. For example, 1886 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 1887 // could be instead splat as 1888 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 1889 // TODO: This optimization could also work on non-constant splats, but it 1890 // would require bit-manipulation instructions to construct the splat value. 1891 SmallVector<SDValue> Sequence; 1892 unsigned EltBitSize = VT.getScalarSizeInBits(); 1893 const auto *BV = cast<BuildVectorSDNode>(Op); 1894 if (VT.isInteger() && EltBitSize < 64 && 1895 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 1896 BV->getRepeatedSequence(Sequence) && 1897 (Sequence.size() * EltBitSize) <= 64) { 1898 unsigned SeqLen = Sequence.size(); 1899 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 1900 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 1901 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 1902 ViaIntVT == MVT::i64) && 1903 "Unexpected sequence type"); 1904 1905 unsigned EltIdx = 0; 1906 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 1907 uint64_t SplatValue = 0; 1908 // Construct the amalgamated value which can be splatted as this larger 1909 // vector type. 1910 for (const auto &SeqV : Sequence) { 1911 if (!SeqV.isUndef()) 1912 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 1913 << (EltIdx * EltBitSize)); 1914 EltIdx++; 1915 } 1916 1917 // On RV64, sign-extend from 32 to 64 bits where possible in order to 1918 // achieve better constant materializion. 1919 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 1920 SplatValue = SignExtend64(SplatValue, 32); 1921 1922 // Since we can't introduce illegal i64 types at this stage, we can only 1923 // perform an i64 splat on RV32 if it is its own sign-extended value. That 1924 // way we can use RVV instructions to splat. 1925 assert((ViaIntVT.bitsLE(XLenVT) || 1926 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 1927 "Unexpected bitcast sequence"); 1928 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 1929 SDValue ViaVL = 1930 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 1931 MVT ViaContainerVT = 1932 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 1933 SDValue Splat = 1934 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 1935 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 1936 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 1937 return DAG.getBitcast(VT, Splat); 1938 } 1939 } 1940 1941 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 1942 // which constitute a large proportion of the elements. In such cases we can 1943 // splat a vector with the dominant element and make up the shortfall with 1944 // INSERT_VECTOR_ELTs. 1945 // Note that this includes vectors of 2 elements by association. The 1946 // upper-most element is the "dominant" one, allowing us to use a splat to 1947 // "insert" the upper element, and an insert of the lower element at position 1948 // 0, which improves codegen. 1949 SDValue DominantValue; 1950 unsigned MostCommonCount = 0; 1951 DenseMap<SDValue, unsigned> ValueCounts; 1952 unsigned NumUndefElts = 1953 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 1954 1955 // Track the number of scalar loads we know we'd be inserting, estimated as 1956 // any non-zero floating-point constant. Other kinds of element are either 1957 // already in registers or are materialized on demand. The threshold at which 1958 // a vector load is more desirable than several scalar materializion and 1959 // vector-insertion instructions is not known. 1960 unsigned NumScalarLoads = 0; 1961 1962 for (SDValue V : Op->op_values()) { 1963 if (V.isUndef()) 1964 continue; 1965 1966 ValueCounts.insert(std::make_pair(V, 0)); 1967 unsigned &Count = ValueCounts[V]; 1968 1969 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 1970 NumScalarLoads += !CFP->isExactlyValue(+0.0); 1971 1972 // Is this value dominant? In case of a tie, prefer the highest element as 1973 // it's cheaper to insert near the beginning of a vector than it is at the 1974 // end. 1975 if (++Count >= MostCommonCount) { 1976 DominantValue = V; 1977 MostCommonCount = Count; 1978 } 1979 } 1980 1981 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 1982 unsigned NumDefElts = NumElts - NumUndefElts; 1983 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 1984 1985 // Don't perform this optimization when optimizing for size, since 1986 // materializing elements and inserting them tends to cause code bloat. 1987 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 1988 ((MostCommonCount > DominantValueCountThreshold) || 1989 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 1990 // Start by splatting the most common element. 1991 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 1992 1993 DenseSet<SDValue> Processed{DominantValue}; 1994 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 1995 for (const auto &OpIdx : enumerate(Op->ops())) { 1996 const SDValue &V = OpIdx.value(); 1997 if (V.isUndef() || !Processed.insert(V).second) 1998 continue; 1999 if (ValueCounts[V] == 1) { 2000 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2001 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2002 } else { 2003 // Blend in all instances of this value using a VSELECT, using a 2004 // mask where each bit signals whether that element is the one 2005 // we're after. 2006 SmallVector<SDValue> Ops; 2007 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2008 return DAG.getConstant(V == V1, DL, XLenVT); 2009 }); 2010 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2011 DAG.getBuildVector(SelMaskTy, DL, Ops), 2012 DAG.getSplatBuildVector(VT, DL, V), Vec); 2013 } 2014 } 2015 2016 return Vec; 2017 } 2018 2019 return SDValue(); 2020 } 2021 2022 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 2023 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 2024 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2025 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2026 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2027 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2028 // node in order to try and match RVV vector/scalar instructions. 2029 if ((LoC >> 31) == HiC) 2030 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2031 } 2032 2033 // Fall back to a stack store and stride x0 vector load. 2034 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2035 } 2036 2037 // Called by type legalization to handle splat of i64 on RV32. 2038 // FIXME: We can optimize this when the type has sign or zero bits in one 2039 // of the halves. 2040 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2041 SDValue VL, SelectionDAG &DAG) { 2042 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2043 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2044 DAG.getConstant(0, DL, MVT::i32)); 2045 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2046 DAG.getConstant(1, DL, MVT::i32)); 2047 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2048 } 2049 2050 // This function lowers a splat of a scalar operand Splat with the vector 2051 // length VL. It ensures the final sequence is type legal, which is useful when 2052 // lowering a splat after type legalization. 2053 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2054 SelectionDAG &DAG, 2055 const RISCVSubtarget &Subtarget) { 2056 if (VT.isFloatingPoint()) 2057 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2058 2059 MVT XLenVT = Subtarget.getXLenVT(); 2060 2061 // Simplest case is that the operand needs to be promoted to XLenVT. 2062 if (Scalar.getValueType().bitsLE(XLenVT)) { 2063 // If the operand is a constant, sign extend to increase our chances 2064 // of being able to use a .vi instruction. ANY_EXTEND would become a 2065 // a zero extend and the simm5 check in isel would fail. 2066 // FIXME: Should we ignore the upper bits in isel instead? 2067 unsigned ExtOpc = 2068 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2069 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2070 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2071 } 2072 2073 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2074 "Unexpected scalar for splat lowering!"); 2075 2076 // Otherwise use the more complicated splatting algorithm. 2077 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2078 } 2079 2080 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2081 const RISCVSubtarget &Subtarget) { 2082 SDValue V1 = Op.getOperand(0); 2083 SDValue V2 = Op.getOperand(1); 2084 SDLoc DL(Op); 2085 MVT XLenVT = Subtarget.getXLenVT(); 2086 MVT VT = Op.getSimpleValueType(); 2087 unsigned NumElts = VT.getVectorNumElements(); 2088 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2089 2090 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2091 2092 SDValue TrueMask, VL; 2093 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2094 2095 if (SVN->isSplat()) { 2096 const int Lane = SVN->getSplatIndex(); 2097 if (Lane >= 0) { 2098 MVT SVT = VT.getVectorElementType(); 2099 2100 // Turn splatted vector load into a strided load with an X0 stride. 2101 SDValue V = V1; 2102 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2103 // with undef. 2104 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2105 int Offset = Lane; 2106 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2107 int OpElements = 2108 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2109 V = V.getOperand(Offset / OpElements); 2110 Offset %= OpElements; 2111 } 2112 2113 // We need to ensure the load isn't atomic or volatile. 2114 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2115 auto *Ld = cast<LoadSDNode>(V); 2116 Offset *= SVT.getStoreSize(); 2117 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2118 TypeSize::Fixed(Offset), DL); 2119 2120 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2121 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2122 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2123 SDValue IntID = 2124 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2125 SDValue Ops[] = {Ld->getChain(), IntID, NewAddr, 2126 DAG.getRegister(RISCV::X0, XLenVT), VL}; 2127 SDValue NewLoad = DAG.getMemIntrinsicNode( 2128 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2129 DAG.getMachineFunction().getMachineMemOperand( 2130 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2131 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2132 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2133 } 2134 2135 // Otherwise use a scalar load and splat. This will give the best 2136 // opportunity to fold a splat into the operation. ISel can turn it into 2137 // the x0 strided load if we aren't able to fold away the select. 2138 if (SVT.isFloatingPoint()) 2139 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2140 Ld->getPointerInfo().getWithOffset(Offset), 2141 Ld->getOriginalAlign(), 2142 Ld->getMemOperand()->getFlags()); 2143 else 2144 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2145 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2146 Ld->getOriginalAlign(), 2147 Ld->getMemOperand()->getFlags()); 2148 DAG.makeEquivalentMemoryOrdering(Ld, V); 2149 2150 unsigned Opc = 2151 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2152 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2153 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2154 } 2155 2156 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2157 assert(Lane < (int)NumElts && "Unexpected lane!"); 2158 SDValue Gather = 2159 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2160 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2161 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2162 } 2163 } 2164 2165 // Detect shuffles which can be re-expressed as vector selects; these are 2166 // shuffles in which each element in the destination is taken from an element 2167 // at the corresponding index in either source vectors. 2168 bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) { 2169 int MaskIndex = MaskIdx.value(); 2170 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2171 }); 2172 2173 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2174 2175 SmallVector<SDValue> MaskVals; 2176 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2177 // merged with a second vrgather. 2178 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2179 2180 // By default we preserve the original operand order, and use a mask to 2181 // select LHS as true and RHS as false. However, since RVV vector selects may 2182 // feature splats but only on the LHS, we may choose to invert our mask and 2183 // instead select between RHS and LHS. 2184 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2185 bool InvertMask = IsSelect == SwapOps; 2186 2187 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2188 // half. 2189 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2190 2191 // Now construct the mask that will be used by the vselect or blended 2192 // vrgather operation. For vrgathers, construct the appropriate indices into 2193 // each vector. 2194 for (int MaskIndex : SVN->getMask()) { 2195 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2196 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2197 if (!IsSelect) { 2198 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2199 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2200 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2201 : DAG.getUNDEF(XLenVT)); 2202 GatherIndicesRHS.push_back( 2203 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2204 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2205 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2206 ++LHSIndexCounts[MaskIndex]; 2207 if (!IsLHSOrUndefIndex) 2208 ++RHSIndexCounts[MaskIndex - NumElts]; 2209 } 2210 } 2211 2212 if (SwapOps) { 2213 std::swap(V1, V2); 2214 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2215 } 2216 2217 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2218 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2219 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2220 2221 if (IsSelect) 2222 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2223 2224 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2225 // On such a large vector we're unable to use i8 as the index type. 2226 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2227 // may involve vector splitting if we're already at LMUL=8, or our 2228 // user-supplied maximum fixed-length LMUL. 2229 return SDValue(); 2230 } 2231 2232 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2233 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2234 MVT IndexVT = VT.changeTypeToInteger(); 2235 // Since we can't introduce illegal index types at this stage, use i16 and 2236 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2237 // than XLenVT. 2238 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2239 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2240 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2241 } 2242 2243 MVT IndexContainerVT = 2244 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2245 2246 SDValue Gather; 2247 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2248 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2249 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2250 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2251 } else { 2252 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2253 // If only one index is used, we can use a "splat" vrgather. 2254 // TODO: We can splat the most-common index and fix-up any stragglers, if 2255 // that's beneficial. 2256 if (LHSIndexCounts.size() == 1) { 2257 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2258 Gather = 2259 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2260 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2261 } else { 2262 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2263 LHSIndices = 2264 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2265 2266 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2267 TrueMask, VL); 2268 } 2269 } 2270 2271 // If a second vector operand is used by this shuffle, blend it in with an 2272 // additional vrgather. 2273 if (!V2.isUndef()) { 2274 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2275 // If only one index is used, we can use a "splat" vrgather. 2276 // TODO: We can splat the most-common index and fix-up any stragglers, if 2277 // that's beneficial. 2278 if (RHSIndexCounts.size() == 1) { 2279 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2280 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2281 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2282 } else { 2283 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2284 RHSIndices = 2285 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2286 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2287 VL); 2288 } 2289 2290 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2291 SelectMask = 2292 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2293 2294 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2295 Gather, VL); 2296 } 2297 2298 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2299 } 2300 2301 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2302 SDLoc DL, SelectionDAG &DAG, 2303 const RISCVSubtarget &Subtarget) { 2304 if (VT.isScalableVector()) 2305 return DAG.getFPExtendOrRound(Op, DL, VT); 2306 assert(VT.isFixedLengthVector() && 2307 "Unexpected value type for RVV FP extend/round lowering"); 2308 SDValue Mask, VL; 2309 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2310 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2311 ? RISCVISD::FP_EXTEND_VL 2312 : RISCVISD::FP_ROUND_VL; 2313 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2314 } 2315 2316 // While RVV has alignment restrictions, we should always be able to load as a 2317 // legal equivalently-sized byte-typed vector instead. This method is 2318 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2319 // the load is already correctly-aligned, it returns SDValue(). 2320 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2321 SelectionDAG &DAG) const { 2322 auto *Load = cast<LoadSDNode>(Op); 2323 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2324 2325 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2326 Load->getMemoryVT(), 2327 *Load->getMemOperand())) 2328 return SDValue(); 2329 2330 SDLoc DL(Op); 2331 MVT VT = Op.getSimpleValueType(); 2332 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2333 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2334 "Unexpected unaligned RVV load type"); 2335 MVT NewVT = 2336 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2337 assert(NewVT.isValid() && 2338 "Expecting equally-sized RVV vector types to be legal"); 2339 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2340 Load->getPointerInfo(), Load->getOriginalAlign(), 2341 Load->getMemOperand()->getFlags()); 2342 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2343 } 2344 2345 // While RVV has alignment restrictions, we should always be able to store as a 2346 // legal equivalently-sized byte-typed vector instead. This method is 2347 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2348 // returns SDValue() if the store is already correctly aligned. 2349 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2350 SelectionDAG &DAG) const { 2351 auto *Store = cast<StoreSDNode>(Op); 2352 assert(Store && Store->getValue().getValueType().isVector() && 2353 "Expected vector store"); 2354 2355 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2356 Store->getMemoryVT(), 2357 *Store->getMemOperand())) 2358 return SDValue(); 2359 2360 SDLoc DL(Op); 2361 SDValue StoredVal = Store->getValue(); 2362 MVT VT = StoredVal.getSimpleValueType(); 2363 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2364 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2365 "Unexpected unaligned RVV store type"); 2366 MVT NewVT = 2367 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2368 assert(NewVT.isValid() && 2369 "Expecting equally-sized RVV vector types to be legal"); 2370 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2371 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2372 Store->getPointerInfo(), Store->getOriginalAlign(), 2373 Store->getMemOperand()->getFlags()); 2374 } 2375 2376 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2377 SelectionDAG &DAG) const { 2378 switch (Op.getOpcode()) { 2379 default: 2380 report_fatal_error("unimplemented operand"); 2381 case ISD::GlobalAddress: 2382 return lowerGlobalAddress(Op, DAG); 2383 case ISD::BlockAddress: 2384 return lowerBlockAddress(Op, DAG); 2385 case ISD::ConstantPool: 2386 return lowerConstantPool(Op, DAG); 2387 case ISD::JumpTable: 2388 return lowerJumpTable(Op, DAG); 2389 case ISD::GlobalTLSAddress: 2390 return lowerGlobalTLSAddress(Op, DAG); 2391 case ISD::SELECT: 2392 return lowerSELECT(Op, DAG); 2393 case ISD::BRCOND: 2394 return lowerBRCOND(Op, DAG); 2395 case ISD::VASTART: 2396 return lowerVASTART(Op, DAG); 2397 case ISD::FRAMEADDR: 2398 return lowerFRAMEADDR(Op, DAG); 2399 case ISD::RETURNADDR: 2400 return lowerRETURNADDR(Op, DAG); 2401 case ISD::SHL_PARTS: 2402 return lowerShiftLeftParts(Op, DAG); 2403 case ISD::SRA_PARTS: 2404 return lowerShiftRightParts(Op, DAG, true); 2405 case ISD::SRL_PARTS: 2406 return lowerShiftRightParts(Op, DAG, false); 2407 case ISD::BITCAST: { 2408 SDLoc DL(Op); 2409 EVT VT = Op.getValueType(); 2410 SDValue Op0 = Op.getOperand(0); 2411 EVT Op0VT = Op0.getValueType(); 2412 MVT XLenVT = Subtarget.getXLenVT(); 2413 if (VT.isFixedLengthVector()) { 2414 // We can handle fixed length vector bitcasts with a simple replacement 2415 // in isel. 2416 if (Op0VT.isFixedLengthVector()) 2417 return Op; 2418 // When bitcasting from scalar to fixed-length vector, insert the scalar 2419 // into a one-element vector of the result type, and perform a vector 2420 // bitcast. 2421 if (!Op0VT.isVector()) { 2422 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2423 if (!isTypeLegal(BVT)) 2424 return SDValue(); 2425 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2426 DAG.getUNDEF(BVT), Op0, 2427 DAG.getConstant(0, DL, XLenVT))); 2428 } 2429 return SDValue(); 2430 } 2431 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2432 // thus: bitcast the vector to a one-element vector type whose element type 2433 // is the same as the result type, and extract the first element. 2434 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2435 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2436 if (!isTypeLegal(BVT)) 2437 return SDValue(); 2438 SDValue BVec = DAG.getBitcast(BVT, Op0); 2439 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2440 DAG.getConstant(0, DL, XLenVT)); 2441 } 2442 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2443 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2444 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2445 return FPConv; 2446 } 2447 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2448 Subtarget.hasStdExtF()) { 2449 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2450 SDValue FPConv = 2451 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2452 return FPConv; 2453 } 2454 return SDValue(); 2455 } 2456 case ISD::INTRINSIC_WO_CHAIN: 2457 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2458 case ISD::INTRINSIC_W_CHAIN: 2459 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2460 case ISD::INTRINSIC_VOID: 2461 return LowerINTRINSIC_VOID(Op, DAG); 2462 case ISD::BSWAP: 2463 case ISD::BITREVERSE: { 2464 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2465 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 2466 MVT VT = Op.getSimpleValueType(); 2467 SDLoc DL(Op); 2468 // Start with the maximum immediate value which is the bitwidth - 1. 2469 unsigned Imm = VT.getSizeInBits() - 1; 2470 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2471 if (Op.getOpcode() == ISD::BSWAP) 2472 Imm &= ~0x7U; 2473 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2474 DAG.getConstant(Imm, DL, VT)); 2475 } 2476 case ISD::FSHL: 2477 case ISD::FSHR: { 2478 MVT VT = Op.getSimpleValueType(); 2479 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2480 SDLoc DL(Op); 2481 if (Op.getOperand(2).getOpcode() == ISD::Constant) 2482 return Op; 2483 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2484 // use log(XLen) bits. Mask the shift amount accordingly. 2485 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2486 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2487 DAG.getConstant(ShAmtWidth, DL, VT)); 2488 unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR; 2489 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt); 2490 } 2491 case ISD::TRUNCATE: { 2492 SDLoc DL(Op); 2493 MVT VT = Op.getSimpleValueType(); 2494 // Only custom-lower vector truncates 2495 if (!VT.isVector()) 2496 return Op; 2497 2498 // Truncates to mask types are handled differently 2499 if (VT.getVectorElementType() == MVT::i1) 2500 return lowerVectorMaskTrunc(Op, DAG); 2501 2502 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 2503 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 2504 // truncate by one power of two at a time. 2505 MVT DstEltVT = VT.getVectorElementType(); 2506 2507 SDValue Src = Op.getOperand(0); 2508 MVT SrcVT = Src.getSimpleValueType(); 2509 MVT SrcEltVT = SrcVT.getVectorElementType(); 2510 2511 assert(DstEltVT.bitsLT(SrcEltVT) && 2512 isPowerOf2_64(DstEltVT.getSizeInBits()) && 2513 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 2514 "Unexpected vector truncate lowering"); 2515 2516 MVT ContainerVT = SrcVT; 2517 if (SrcVT.isFixedLengthVector()) { 2518 ContainerVT = getContainerForFixedLengthVector(SrcVT); 2519 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 2520 } 2521 2522 SDValue Result = Src; 2523 SDValue Mask, VL; 2524 std::tie(Mask, VL) = 2525 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 2526 LLVMContext &Context = *DAG.getContext(); 2527 const ElementCount Count = ContainerVT.getVectorElementCount(); 2528 do { 2529 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 2530 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 2531 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 2532 Mask, VL); 2533 } while (SrcEltVT != DstEltVT); 2534 2535 if (SrcVT.isFixedLengthVector()) 2536 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 2537 2538 return Result; 2539 } 2540 case ISD::ANY_EXTEND: 2541 case ISD::ZERO_EXTEND: 2542 if (Op.getOperand(0).getValueType().isVector() && 2543 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2544 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 2545 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 2546 case ISD::SIGN_EXTEND: 2547 if (Op.getOperand(0).getValueType().isVector() && 2548 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2549 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 2550 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 2551 case ISD::SPLAT_VECTOR_PARTS: 2552 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 2553 case ISD::INSERT_VECTOR_ELT: 2554 return lowerINSERT_VECTOR_ELT(Op, DAG); 2555 case ISD::EXTRACT_VECTOR_ELT: 2556 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 2557 case ISD::VSCALE: { 2558 MVT VT = Op.getSimpleValueType(); 2559 SDLoc DL(Op); 2560 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 2561 // We define our scalable vector types for lmul=1 to use a 64 bit known 2562 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 2563 // vscale as VLENB / 8. 2564 assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!"); 2565 if (isa<ConstantSDNode>(Op.getOperand(0))) { 2566 // We assume VLENB is a multiple of 8. We manually choose the best shift 2567 // here because SimplifyDemandedBits isn't always able to simplify it. 2568 uint64_t Val = Op.getConstantOperandVal(0); 2569 if (isPowerOf2_64(Val)) { 2570 uint64_t Log2 = Log2_64(Val); 2571 if (Log2 < 3) 2572 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 2573 DAG.getConstant(3 - Log2, DL, VT)); 2574 if (Log2 > 3) 2575 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 2576 DAG.getConstant(Log2 - 3, DL, VT)); 2577 return VLENB; 2578 } 2579 // If the multiplier is a multiple of 8, scale it down to avoid needing 2580 // to shift the VLENB value. 2581 if ((Val % 8) == 0) 2582 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 2583 DAG.getConstant(Val / 8, DL, VT)); 2584 } 2585 2586 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 2587 DAG.getConstant(3, DL, VT)); 2588 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 2589 } 2590 case ISD::FP_EXTEND: { 2591 // RVV can only do fp_extend to types double the size as the source. We 2592 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 2593 // via f32. 2594 SDLoc DL(Op); 2595 MVT VT = Op.getSimpleValueType(); 2596 SDValue Src = Op.getOperand(0); 2597 MVT SrcVT = Src.getSimpleValueType(); 2598 2599 // Prepare any fixed-length vector operands. 2600 MVT ContainerVT = VT; 2601 if (SrcVT.isFixedLengthVector()) { 2602 ContainerVT = getContainerForFixedLengthVector(VT); 2603 MVT SrcContainerVT = 2604 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 2605 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2606 } 2607 2608 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 2609 SrcVT.getVectorElementType() != MVT::f16) { 2610 // For scalable vectors, we only need to close the gap between 2611 // vXf16->vXf64. 2612 if (!VT.isFixedLengthVector()) 2613 return Op; 2614 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 2615 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2616 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2617 } 2618 2619 MVT InterVT = VT.changeVectorElementType(MVT::f32); 2620 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 2621 SDValue IntermediateExtend = getRVVFPExtendOrRound( 2622 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 2623 2624 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 2625 DL, DAG, Subtarget); 2626 if (VT.isFixedLengthVector()) 2627 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 2628 return Extend; 2629 } 2630 case ISD::FP_ROUND: { 2631 // RVV can only do fp_round to types half the size as the source. We 2632 // custom-lower f64->f16 rounds via RVV's round-to-odd float 2633 // conversion instruction. 2634 SDLoc DL(Op); 2635 MVT VT = Op.getSimpleValueType(); 2636 SDValue Src = Op.getOperand(0); 2637 MVT SrcVT = Src.getSimpleValueType(); 2638 2639 // Prepare any fixed-length vector operands. 2640 MVT ContainerVT = VT; 2641 if (VT.isFixedLengthVector()) { 2642 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2643 ContainerVT = 2644 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2645 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2646 } 2647 2648 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 2649 SrcVT.getVectorElementType() != MVT::f64) { 2650 // For scalable vectors, we only need to close the gap between 2651 // vXf64<->vXf16. 2652 if (!VT.isFixedLengthVector()) 2653 return Op; 2654 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 2655 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2656 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2657 } 2658 2659 SDValue Mask, VL; 2660 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2661 2662 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 2663 SDValue IntermediateRound = 2664 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 2665 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 2666 DL, DAG, Subtarget); 2667 2668 if (VT.isFixedLengthVector()) 2669 return convertFromScalableVector(VT, Round, DAG, Subtarget); 2670 return Round; 2671 } 2672 case ISD::FP_TO_SINT: 2673 case ISD::FP_TO_UINT: 2674 case ISD::SINT_TO_FP: 2675 case ISD::UINT_TO_FP: { 2676 // RVV can only do fp<->int conversions to types half/double the size as 2677 // the source. We custom-lower any conversions that do two hops into 2678 // sequences. 2679 MVT VT = Op.getSimpleValueType(); 2680 if (!VT.isVector()) 2681 return Op; 2682 SDLoc DL(Op); 2683 SDValue Src = Op.getOperand(0); 2684 MVT EltVT = VT.getVectorElementType(); 2685 MVT SrcVT = Src.getSimpleValueType(); 2686 MVT SrcEltVT = SrcVT.getVectorElementType(); 2687 unsigned EltSize = EltVT.getSizeInBits(); 2688 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 2689 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 2690 "Unexpected vector element types"); 2691 2692 bool IsInt2FP = SrcEltVT.isInteger(); 2693 // Widening conversions 2694 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 2695 if (IsInt2FP) { 2696 // Do a regular integer sign/zero extension then convert to float. 2697 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 2698 VT.getVectorElementCount()); 2699 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 2700 ? ISD::ZERO_EXTEND 2701 : ISD::SIGN_EXTEND; 2702 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 2703 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 2704 } 2705 // FP2Int 2706 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 2707 // Do one doubling fp_extend then complete the operation by converting 2708 // to int. 2709 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2710 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 2711 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 2712 } 2713 2714 // Narrowing conversions 2715 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 2716 if (IsInt2FP) { 2717 // One narrowing int_to_fp, then an fp_round. 2718 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 2719 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2720 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 2721 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 2722 } 2723 // FP2Int 2724 // One narrowing fp_to_int, then truncate the integer. If the float isn't 2725 // representable by the integer, the result is poison. 2726 MVT IVecVT = 2727 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 2728 VT.getVectorElementCount()); 2729 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 2730 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 2731 } 2732 2733 // Scalable vectors can exit here. Patterns will handle equally-sized 2734 // conversions halving/doubling ones. 2735 if (!VT.isFixedLengthVector()) 2736 return Op; 2737 2738 // For fixed-length vectors we lower to a custom "VL" node. 2739 unsigned RVVOpc = 0; 2740 switch (Op.getOpcode()) { 2741 default: 2742 llvm_unreachable("Impossible opcode"); 2743 case ISD::FP_TO_SINT: 2744 RVVOpc = RISCVISD::FP_TO_SINT_VL; 2745 break; 2746 case ISD::FP_TO_UINT: 2747 RVVOpc = RISCVISD::FP_TO_UINT_VL; 2748 break; 2749 case ISD::SINT_TO_FP: 2750 RVVOpc = RISCVISD::SINT_TO_FP_VL; 2751 break; 2752 case ISD::UINT_TO_FP: 2753 RVVOpc = RISCVISD::UINT_TO_FP_VL; 2754 break; 2755 } 2756 2757 MVT ContainerVT, SrcContainerVT; 2758 // Derive the reference container type from the larger vector type. 2759 if (SrcEltSize > EltSize) { 2760 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2761 ContainerVT = 2762 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2763 } else { 2764 ContainerVT = getContainerForFixedLengthVector(VT); 2765 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 2766 } 2767 2768 SDValue Mask, VL; 2769 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2770 2771 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2772 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 2773 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2774 } 2775 case ISD::FP_TO_SINT_SAT: 2776 case ISD::FP_TO_UINT_SAT: 2777 return lowerFP_TO_INT_SAT(Op, DAG); 2778 case ISD::VECREDUCE_ADD: 2779 case ISD::VECREDUCE_UMAX: 2780 case ISD::VECREDUCE_SMAX: 2781 case ISD::VECREDUCE_UMIN: 2782 case ISD::VECREDUCE_SMIN: 2783 return lowerVECREDUCE(Op, DAG); 2784 case ISD::VECREDUCE_AND: 2785 case ISD::VECREDUCE_OR: 2786 case ISD::VECREDUCE_XOR: 2787 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2788 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 2789 return lowerVECREDUCE(Op, DAG); 2790 case ISD::VECREDUCE_FADD: 2791 case ISD::VECREDUCE_SEQ_FADD: 2792 case ISD::VECREDUCE_FMIN: 2793 case ISD::VECREDUCE_FMAX: 2794 return lowerFPVECREDUCE(Op, DAG); 2795 case ISD::VP_REDUCE_ADD: 2796 case ISD::VP_REDUCE_UMAX: 2797 case ISD::VP_REDUCE_SMAX: 2798 case ISD::VP_REDUCE_UMIN: 2799 case ISD::VP_REDUCE_SMIN: 2800 case ISD::VP_REDUCE_FADD: 2801 case ISD::VP_REDUCE_SEQ_FADD: 2802 case ISD::VP_REDUCE_FMIN: 2803 case ISD::VP_REDUCE_FMAX: 2804 return lowerVPREDUCE(Op, DAG); 2805 case ISD::VP_REDUCE_AND: 2806 case ISD::VP_REDUCE_OR: 2807 case ISD::VP_REDUCE_XOR: 2808 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 2809 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 2810 return lowerVPREDUCE(Op, DAG); 2811 case ISD::INSERT_SUBVECTOR: 2812 return lowerINSERT_SUBVECTOR(Op, DAG); 2813 case ISD::EXTRACT_SUBVECTOR: 2814 return lowerEXTRACT_SUBVECTOR(Op, DAG); 2815 case ISD::STEP_VECTOR: 2816 return lowerSTEP_VECTOR(Op, DAG); 2817 case ISD::VECTOR_REVERSE: 2818 return lowerVECTOR_REVERSE(Op, DAG); 2819 case ISD::BUILD_VECTOR: 2820 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 2821 case ISD::SPLAT_VECTOR: 2822 if (Op.getValueType().getVectorElementType() == MVT::i1) 2823 return lowerVectorMaskSplat(Op, DAG); 2824 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 2825 case ISD::VECTOR_SHUFFLE: 2826 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 2827 case ISD::CONCAT_VECTORS: { 2828 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 2829 // better than going through the stack, as the default expansion does. 2830 SDLoc DL(Op); 2831 MVT VT = Op.getSimpleValueType(); 2832 unsigned NumOpElts = 2833 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 2834 SDValue Vec = DAG.getUNDEF(VT); 2835 for (const auto &OpIdx : enumerate(Op->ops())) 2836 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(), 2837 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 2838 return Vec; 2839 } 2840 case ISD::LOAD: 2841 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 2842 return V; 2843 if (Op.getValueType().isFixedLengthVector()) 2844 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 2845 return Op; 2846 case ISD::STORE: 2847 if (auto V = expandUnalignedRVVStore(Op, DAG)) 2848 return V; 2849 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 2850 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 2851 return Op; 2852 case ISD::MLOAD: 2853 case ISD::VP_LOAD: 2854 return lowerMaskedLoad(Op, DAG); 2855 case ISD::MSTORE: 2856 case ISD::VP_STORE: 2857 return lowerMaskedStore(Op, DAG); 2858 case ISD::SETCC: 2859 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 2860 case ISD::ADD: 2861 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 2862 case ISD::SUB: 2863 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 2864 case ISD::MUL: 2865 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 2866 case ISD::MULHS: 2867 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 2868 case ISD::MULHU: 2869 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 2870 case ISD::AND: 2871 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 2872 RISCVISD::AND_VL); 2873 case ISD::OR: 2874 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 2875 RISCVISD::OR_VL); 2876 case ISD::XOR: 2877 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 2878 RISCVISD::XOR_VL); 2879 case ISD::SDIV: 2880 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 2881 case ISD::SREM: 2882 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 2883 case ISD::UDIV: 2884 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 2885 case ISD::UREM: 2886 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 2887 case ISD::SHL: 2888 case ISD::SRA: 2889 case ISD::SRL: 2890 if (Op.getSimpleValueType().isFixedLengthVector()) 2891 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 2892 // This can be called for an i32 shift amount that needs to be promoted. 2893 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 2894 "Unexpected custom legalisation"); 2895 return SDValue(); 2896 case ISD::SADDSAT: 2897 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 2898 case ISD::UADDSAT: 2899 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 2900 case ISD::SSUBSAT: 2901 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 2902 case ISD::USUBSAT: 2903 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 2904 case ISD::FADD: 2905 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 2906 case ISD::FSUB: 2907 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 2908 case ISD::FMUL: 2909 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 2910 case ISD::FDIV: 2911 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 2912 case ISD::FNEG: 2913 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 2914 case ISD::FABS: 2915 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 2916 case ISD::FSQRT: 2917 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 2918 case ISD::FMA: 2919 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 2920 case ISD::SMIN: 2921 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 2922 case ISD::SMAX: 2923 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 2924 case ISD::UMIN: 2925 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 2926 case ISD::UMAX: 2927 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 2928 case ISD::FMINNUM: 2929 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 2930 case ISD::FMAXNUM: 2931 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 2932 case ISD::ABS: 2933 return lowerABS(Op, DAG); 2934 case ISD::VSELECT: 2935 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 2936 case ISD::FCOPYSIGN: 2937 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 2938 case ISD::MGATHER: 2939 case ISD::VP_GATHER: 2940 return lowerMaskedGather(Op, DAG); 2941 case ISD::MSCATTER: 2942 case ISD::VP_SCATTER: 2943 return lowerMaskedScatter(Op, DAG); 2944 case ISD::FLT_ROUNDS_: 2945 return lowerGET_ROUNDING(Op, DAG); 2946 case ISD::SET_ROUNDING: 2947 return lowerSET_ROUNDING(Op, DAG); 2948 case ISD::VP_ADD: 2949 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 2950 case ISD::VP_SUB: 2951 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 2952 case ISD::VP_MUL: 2953 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 2954 case ISD::VP_SDIV: 2955 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 2956 case ISD::VP_UDIV: 2957 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 2958 case ISD::VP_SREM: 2959 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 2960 case ISD::VP_UREM: 2961 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 2962 case ISD::VP_AND: 2963 return lowerVPOp(Op, DAG, RISCVISD::AND_VL); 2964 case ISD::VP_OR: 2965 return lowerVPOp(Op, DAG, RISCVISD::OR_VL); 2966 case ISD::VP_XOR: 2967 return lowerVPOp(Op, DAG, RISCVISD::XOR_VL); 2968 case ISD::VP_ASHR: 2969 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 2970 case ISD::VP_LSHR: 2971 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 2972 case ISD::VP_SHL: 2973 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 2974 case ISD::VP_FADD: 2975 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 2976 case ISD::VP_FSUB: 2977 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 2978 case ISD::VP_FMUL: 2979 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 2980 case ISD::VP_FDIV: 2981 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 2982 } 2983 } 2984 2985 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 2986 SelectionDAG &DAG, unsigned Flags) { 2987 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 2988 } 2989 2990 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 2991 SelectionDAG &DAG, unsigned Flags) { 2992 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 2993 Flags); 2994 } 2995 2996 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 2997 SelectionDAG &DAG, unsigned Flags) { 2998 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 2999 N->getOffset(), Flags); 3000 } 3001 3002 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3003 SelectionDAG &DAG, unsigned Flags) { 3004 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3005 } 3006 3007 template <class NodeTy> 3008 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3009 bool IsLocal) const { 3010 SDLoc DL(N); 3011 EVT Ty = getPointerTy(DAG.getDataLayout()); 3012 3013 if (isPositionIndependent()) { 3014 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3015 if (IsLocal) 3016 // Use PC-relative addressing to access the symbol. This generates the 3017 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3018 // %pcrel_lo(auipc)). 3019 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3020 3021 // Use PC-relative addressing to access the GOT for this symbol, then load 3022 // the address from the GOT. This generates the pattern (PseudoLA sym), 3023 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3024 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3025 } 3026 3027 switch (getTargetMachine().getCodeModel()) { 3028 default: 3029 report_fatal_error("Unsupported code model for lowering"); 3030 case CodeModel::Small: { 3031 // Generate a sequence for accessing addresses within the first 2 GiB of 3032 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3033 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3034 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3035 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3036 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3037 } 3038 case CodeModel::Medium: { 3039 // Generate a sequence for accessing addresses within any 2GiB range within 3040 // the address space. This generates the pattern (PseudoLLA sym), which 3041 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3042 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3043 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3044 } 3045 } 3046 } 3047 3048 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3049 SelectionDAG &DAG) const { 3050 SDLoc DL(Op); 3051 EVT Ty = Op.getValueType(); 3052 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3053 int64_t Offset = N->getOffset(); 3054 MVT XLenVT = Subtarget.getXLenVT(); 3055 3056 const GlobalValue *GV = N->getGlobal(); 3057 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3058 SDValue Addr = getAddr(N, DAG, IsLocal); 3059 3060 // In order to maximise the opportunity for common subexpression elimination, 3061 // emit a separate ADD node for the global address offset instead of folding 3062 // it in the global address node. Later peephole optimisations may choose to 3063 // fold it back in when profitable. 3064 if (Offset != 0) 3065 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3066 DAG.getConstant(Offset, DL, XLenVT)); 3067 return Addr; 3068 } 3069 3070 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3071 SelectionDAG &DAG) const { 3072 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3073 3074 return getAddr(N, DAG); 3075 } 3076 3077 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3078 SelectionDAG &DAG) const { 3079 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3080 3081 return getAddr(N, DAG); 3082 } 3083 3084 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3085 SelectionDAG &DAG) const { 3086 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3087 3088 return getAddr(N, DAG); 3089 } 3090 3091 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3092 SelectionDAG &DAG, 3093 bool UseGOT) const { 3094 SDLoc DL(N); 3095 EVT Ty = getPointerTy(DAG.getDataLayout()); 3096 const GlobalValue *GV = N->getGlobal(); 3097 MVT XLenVT = Subtarget.getXLenVT(); 3098 3099 if (UseGOT) { 3100 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3101 // load the address from the GOT and add the thread pointer. This generates 3102 // the pattern (PseudoLA_TLS_IE sym), which expands to 3103 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3104 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3105 SDValue Load = 3106 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3107 3108 // Add the thread pointer. 3109 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3110 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3111 } 3112 3113 // Generate a sequence for accessing the address relative to the thread 3114 // pointer, with the appropriate adjustment for the thread pointer offset. 3115 // This generates the pattern 3116 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3117 SDValue AddrHi = 3118 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3119 SDValue AddrAdd = 3120 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3121 SDValue AddrLo = 3122 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3123 3124 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3125 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3126 SDValue MNAdd = SDValue( 3127 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3128 0); 3129 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3130 } 3131 3132 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3133 SelectionDAG &DAG) const { 3134 SDLoc DL(N); 3135 EVT Ty = getPointerTy(DAG.getDataLayout()); 3136 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3137 const GlobalValue *GV = N->getGlobal(); 3138 3139 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3140 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3141 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3142 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3143 SDValue Load = 3144 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3145 3146 // Prepare argument list to generate call. 3147 ArgListTy Args; 3148 ArgListEntry Entry; 3149 Entry.Node = Load; 3150 Entry.Ty = CallTy; 3151 Args.push_back(Entry); 3152 3153 // Setup call to __tls_get_addr. 3154 TargetLowering::CallLoweringInfo CLI(DAG); 3155 CLI.setDebugLoc(DL) 3156 .setChain(DAG.getEntryNode()) 3157 .setLibCallee(CallingConv::C, CallTy, 3158 DAG.getExternalSymbol("__tls_get_addr", Ty), 3159 std::move(Args)); 3160 3161 return LowerCallTo(CLI).first; 3162 } 3163 3164 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3165 SelectionDAG &DAG) const { 3166 SDLoc DL(Op); 3167 EVT Ty = Op.getValueType(); 3168 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3169 int64_t Offset = N->getOffset(); 3170 MVT XLenVT = Subtarget.getXLenVT(); 3171 3172 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3173 3174 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3175 CallingConv::GHC) 3176 report_fatal_error("In GHC calling convention TLS is not supported"); 3177 3178 SDValue Addr; 3179 switch (Model) { 3180 case TLSModel::LocalExec: 3181 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3182 break; 3183 case TLSModel::InitialExec: 3184 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3185 break; 3186 case TLSModel::LocalDynamic: 3187 case TLSModel::GeneralDynamic: 3188 Addr = getDynamicTLSAddr(N, DAG); 3189 break; 3190 } 3191 3192 // In order to maximise the opportunity for common subexpression elimination, 3193 // emit a separate ADD node for the global address offset instead of folding 3194 // it in the global address node. Later peephole optimisations may choose to 3195 // fold it back in when profitable. 3196 if (Offset != 0) 3197 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3198 DAG.getConstant(Offset, DL, XLenVT)); 3199 return Addr; 3200 } 3201 3202 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3203 SDValue CondV = Op.getOperand(0); 3204 SDValue TrueV = Op.getOperand(1); 3205 SDValue FalseV = Op.getOperand(2); 3206 SDLoc DL(Op); 3207 MVT VT = Op.getSimpleValueType(); 3208 MVT XLenVT = Subtarget.getXLenVT(); 3209 3210 // Lower vector SELECTs to VSELECTs by splatting the condition. 3211 if (VT.isVector()) { 3212 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3213 SDValue CondSplat = VT.isScalableVector() 3214 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3215 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3216 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3217 } 3218 3219 // If the result type is XLenVT and CondV is the output of a SETCC node 3220 // which also operated on XLenVT inputs, then merge the SETCC node into the 3221 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3222 // compare+branch instructions. i.e.: 3223 // (select (setcc lhs, rhs, cc), truev, falsev) 3224 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3225 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3226 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3227 SDValue LHS = CondV.getOperand(0); 3228 SDValue RHS = CondV.getOperand(1); 3229 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3230 ISD::CondCode CCVal = CC->get(); 3231 3232 // Special case for a select of 2 constants that have a diffence of 1. 3233 // Normally this is done by DAGCombine, but if the select is introduced by 3234 // type legalization or op legalization, we miss it. Restricting to SETLT 3235 // case for now because that is what signed saturating add/sub need. 3236 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3237 // but we would probably want to swap the true/false values if the condition 3238 // is SETGE/SETLE to avoid an XORI. 3239 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3240 CCVal == ISD::SETLT) { 3241 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3242 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3243 if (TrueVal - 1 == FalseVal) 3244 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3245 if (TrueVal + 1 == FalseVal) 3246 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3247 } 3248 3249 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3250 3251 SDValue TargetCC = DAG.getCondCode(CCVal); 3252 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3253 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3254 } 3255 3256 // Otherwise: 3257 // (select condv, truev, falsev) 3258 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3259 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3260 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3261 3262 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3263 3264 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3265 } 3266 3267 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3268 SDValue CondV = Op.getOperand(1); 3269 SDLoc DL(Op); 3270 MVT XLenVT = Subtarget.getXLenVT(); 3271 3272 if (CondV.getOpcode() == ISD::SETCC && 3273 CondV.getOperand(0).getValueType() == XLenVT) { 3274 SDValue LHS = CondV.getOperand(0); 3275 SDValue RHS = CondV.getOperand(1); 3276 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3277 3278 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3279 3280 SDValue TargetCC = DAG.getCondCode(CCVal); 3281 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3282 LHS, RHS, TargetCC, Op.getOperand(2)); 3283 } 3284 3285 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3286 CondV, DAG.getConstant(0, DL, XLenVT), 3287 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3288 } 3289 3290 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3291 MachineFunction &MF = DAG.getMachineFunction(); 3292 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3293 3294 SDLoc DL(Op); 3295 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3296 getPointerTy(MF.getDataLayout())); 3297 3298 // vastart just stores the address of the VarArgsFrameIndex slot into the 3299 // memory location argument. 3300 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3301 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3302 MachinePointerInfo(SV)); 3303 } 3304 3305 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3306 SelectionDAG &DAG) const { 3307 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3308 MachineFunction &MF = DAG.getMachineFunction(); 3309 MachineFrameInfo &MFI = MF.getFrameInfo(); 3310 MFI.setFrameAddressIsTaken(true); 3311 Register FrameReg = RI.getFrameRegister(MF); 3312 int XLenInBytes = Subtarget.getXLen() / 8; 3313 3314 EVT VT = Op.getValueType(); 3315 SDLoc DL(Op); 3316 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3317 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3318 while (Depth--) { 3319 int Offset = -(XLenInBytes * 2); 3320 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3321 DAG.getIntPtrConstant(Offset, DL)); 3322 FrameAddr = 3323 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3324 } 3325 return FrameAddr; 3326 } 3327 3328 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3329 SelectionDAG &DAG) const { 3330 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3331 MachineFunction &MF = DAG.getMachineFunction(); 3332 MachineFrameInfo &MFI = MF.getFrameInfo(); 3333 MFI.setReturnAddressIsTaken(true); 3334 MVT XLenVT = Subtarget.getXLenVT(); 3335 int XLenInBytes = Subtarget.getXLen() / 8; 3336 3337 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3338 return SDValue(); 3339 3340 EVT VT = Op.getValueType(); 3341 SDLoc DL(Op); 3342 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3343 if (Depth) { 3344 int Off = -XLenInBytes; 3345 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3346 SDValue Offset = DAG.getConstant(Off, DL, VT); 3347 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3348 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3349 MachinePointerInfo()); 3350 } 3351 3352 // Return the value of the return address register, marking it an implicit 3353 // live-in. 3354 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3355 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3356 } 3357 3358 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3359 SelectionDAG &DAG) const { 3360 SDLoc DL(Op); 3361 SDValue Lo = Op.getOperand(0); 3362 SDValue Hi = Op.getOperand(1); 3363 SDValue Shamt = Op.getOperand(2); 3364 EVT VT = Lo.getValueType(); 3365 3366 // if Shamt-XLEN < 0: // Shamt < XLEN 3367 // Lo = Lo << Shamt 3368 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3369 // else: 3370 // Lo = 0 3371 // Hi = Lo << (Shamt-XLEN) 3372 3373 SDValue Zero = DAG.getConstant(0, DL, VT); 3374 SDValue One = DAG.getConstant(1, DL, VT); 3375 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3376 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3377 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3378 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3379 3380 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3381 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3382 SDValue ShiftRightLo = 3383 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3384 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3385 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3386 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3387 3388 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3389 3390 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3391 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3392 3393 SDValue Parts[2] = {Lo, Hi}; 3394 return DAG.getMergeValues(Parts, DL); 3395 } 3396 3397 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3398 bool IsSRA) const { 3399 SDLoc DL(Op); 3400 SDValue Lo = Op.getOperand(0); 3401 SDValue Hi = Op.getOperand(1); 3402 SDValue Shamt = Op.getOperand(2); 3403 EVT VT = Lo.getValueType(); 3404 3405 // SRA expansion: 3406 // if Shamt-XLEN < 0: // Shamt < XLEN 3407 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3408 // Hi = Hi >>s Shamt 3409 // else: 3410 // Lo = Hi >>s (Shamt-XLEN); 3411 // Hi = Hi >>s (XLEN-1) 3412 // 3413 // SRL expansion: 3414 // if Shamt-XLEN < 0: // Shamt < XLEN 3415 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3416 // Hi = Hi >>u Shamt 3417 // else: 3418 // Lo = Hi >>u (Shamt-XLEN); 3419 // Hi = 0; 3420 3421 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3422 3423 SDValue Zero = DAG.getConstant(0, DL, VT); 3424 SDValue One = DAG.getConstant(1, DL, VT); 3425 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3426 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3427 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3428 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3429 3430 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3431 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3432 SDValue ShiftLeftHi = 3433 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3434 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3435 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3436 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3437 SDValue HiFalse = 3438 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3439 3440 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3441 3442 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3443 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3444 3445 SDValue Parts[2] = {Lo, Hi}; 3446 return DAG.getMergeValues(Parts, DL); 3447 } 3448 3449 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3450 // legal equivalently-sized i8 type, so we can use that as a go-between. 3451 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3452 SelectionDAG &DAG) const { 3453 SDLoc DL(Op); 3454 MVT VT = Op.getSimpleValueType(); 3455 SDValue SplatVal = Op.getOperand(0); 3456 // All-zeros or all-ones splats are handled specially. 3457 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3458 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3459 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3460 } 3461 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3462 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3463 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3464 } 3465 MVT XLenVT = Subtarget.getXLenVT(); 3466 assert(SplatVal.getValueType() == XLenVT && 3467 "Unexpected type for i1 splat value"); 3468 MVT InterVT = VT.changeVectorElementType(MVT::i8); 3469 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 3470 DAG.getConstant(1, DL, XLenVT)); 3471 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 3472 SDValue Zero = DAG.getConstant(0, DL, InterVT); 3473 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 3474 } 3475 3476 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 3477 // illegal (currently only vXi64 RV32). 3478 // FIXME: We could also catch non-constant sign-extended i32 values and lower 3479 // them to SPLAT_VECTOR_I64 3480 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 3481 SelectionDAG &DAG) const { 3482 SDLoc DL(Op); 3483 MVT VecVT = Op.getSimpleValueType(); 3484 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 3485 "Unexpected SPLAT_VECTOR_PARTS lowering"); 3486 3487 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 3488 SDValue Lo = Op.getOperand(0); 3489 SDValue Hi = Op.getOperand(1); 3490 3491 if (VecVT.isFixedLengthVector()) { 3492 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3493 SDLoc DL(Op); 3494 SDValue Mask, VL; 3495 std::tie(Mask, VL) = 3496 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3497 3498 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 3499 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 3500 } 3501 3502 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 3503 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 3504 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 3505 // If Hi constant is all the same sign bit as Lo, lower this as a custom 3506 // node in order to try and match RVV vector/scalar instructions. 3507 if ((LoC >> 31) == HiC) 3508 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3509 } 3510 3511 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 3512 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 3513 isa<ConstantSDNode>(Hi.getOperand(1)) && 3514 Hi.getConstantOperandVal(1) == 31) 3515 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3516 3517 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 3518 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 3519 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64)); 3520 } 3521 3522 // Custom-lower extensions from mask vectors by using a vselect either with 1 3523 // for zero/any-extension or -1 for sign-extension: 3524 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 3525 // Note that any-extension is lowered identically to zero-extension. 3526 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 3527 int64_t ExtTrueVal) const { 3528 SDLoc DL(Op); 3529 MVT VecVT = Op.getSimpleValueType(); 3530 SDValue Src = Op.getOperand(0); 3531 // Only custom-lower extensions from mask types 3532 assert(Src.getValueType().isVector() && 3533 Src.getValueType().getVectorElementType() == MVT::i1); 3534 3535 MVT XLenVT = Subtarget.getXLenVT(); 3536 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 3537 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 3538 3539 if (VecVT.isScalableVector()) { 3540 // Be careful not to introduce illegal scalar types at this stage, and be 3541 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 3542 // illegal and must be expanded. Since we know that the constants are 3543 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 3544 bool IsRV32E64 = 3545 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 3546 3547 if (!IsRV32E64) { 3548 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 3549 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 3550 } else { 3551 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 3552 SplatTrueVal = 3553 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 3554 } 3555 3556 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 3557 } 3558 3559 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3560 MVT I1ContainerVT = 3561 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3562 3563 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 3564 3565 SDValue Mask, VL; 3566 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3567 3568 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 3569 SplatTrueVal = 3570 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 3571 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 3572 SplatTrueVal, SplatZero, VL); 3573 3574 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 3575 } 3576 3577 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 3578 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 3579 MVT ExtVT = Op.getSimpleValueType(); 3580 // Only custom-lower extensions from fixed-length vector types. 3581 if (!ExtVT.isFixedLengthVector()) 3582 return Op; 3583 MVT VT = Op.getOperand(0).getSimpleValueType(); 3584 // Grab the canonical container type for the extended type. Infer the smaller 3585 // type from that to ensure the same number of vector elements, as we know 3586 // the LMUL will be sufficient to hold the smaller type. 3587 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 3588 // Get the extended container type manually to ensure the same number of 3589 // vector elements between source and dest. 3590 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 3591 ContainerExtVT.getVectorElementCount()); 3592 3593 SDValue Op1 = 3594 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 3595 3596 SDLoc DL(Op); 3597 SDValue Mask, VL; 3598 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3599 3600 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 3601 3602 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 3603 } 3604 3605 // Custom-lower truncations from vectors to mask vectors by using a mask and a 3606 // setcc operation: 3607 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 3608 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 3609 SelectionDAG &DAG) const { 3610 SDLoc DL(Op); 3611 EVT MaskVT = Op.getValueType(); 3612 // Only expect to custom-lower truncations to mask types 3613 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 3614 "Unexpected type for vector mask lowering"); 3615 SDValue Src = Op.getOperand(0); 3616 MVT VecVT = Src.getSimpleValueType(); 3617 3618 // If this is a fixed vector, we need to convert it to a scalable vector. 3619 MVT ContainerVT = VecVT; 3620 if (VecVT.isFixedLengthVector()) { 3621 ContainerVT = getContainerForFixedLengthVector(VecVT); 3622 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3623 } 3624 3625 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 3626 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 3627 3628 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 3629 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 3630 3631 if (VecVT.isScalableVector()) { 3632 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 3633 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 3634 } 3635 3636 SDValue Mask, VL; 3637 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3638 3639 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 3640 SDValue Trunc = 3641 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 3642 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 3643 DAG.getCondCode(ISD::SETNE), Mask, VL); 3644 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 3645 } 3646 3647 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 3648 // first position of a vector, and that vector is slid up to the insert index. 3649 // By limiting the active vector length to index+1 and merging with the 3650 // original vector (with an undisturbed tail policy for elements >= VL), we 3651 // achieve the desired result of leaving all elements untouched except the one 3652 // at VL-1, which is replaced with the desired value. 3653 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3654 SelectionDAG &DAG) const { 3655 SDLoc DL(Op); 3656 MVT VecVT = Op.getSimpleValueType(); 3657 SDValue Vec = Op.getOperand(0); 3658 SDValue Val = Op.getOperand(1); 3659 SDValue Idx = Op.getOperand(2); 3660 3661 if (VecVT.getVectorElementType() == MVT::i1) { 3662 // FIXME: For now we just promote to an i8 vector and insert into that, 3663 // but this is probably not optimal. 3664 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3665 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3666 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 3667 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 3668 } 3669 3670 MVT ContainerVT = VecVT; 3671 // If the operand is a fixed-length vector, convert to a scalable one. 3672 if (VecVT.isFixedLengthVector()) { 3673 ContainerVT = getContainerForFixedLengthVector(VecVT); 3674 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3675 } 3676 3677 MVT XLenVT = Subtarget.getXLenVT(); 3678 3679 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3680 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 3681 // Even i64-element vectors on RV32 can be lowered without scalar 3682 // legalization if the most-significant 32 bits of the value are not affected 3683 // by the sign-extension of the lower 32 bits. 3684 // TODO: We could also catch sign extensions of a 32-bit value. 3685 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 3686 const auto *CVal = cast<ConstantSDNode>(Val); 3687 if (isInt<32>(CVal->getSExtValue())) { 3688 IsLegalInsert = true; 3689 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3690 } 3691 } 3692 3693 SDValue Mask, VL; 3694 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3695 3696 SDValue ValInVec; 3697 3698 if (IsLegalInsert) { 3699 unsigned Opc = 3700 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 3701 if (isNullConstant(Idx)) { 3702 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 3703 if (!VecVT.isFixedLengthVector()) 3704 return Vec; 3705 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 3706 } 3707 ValInVec = 3708 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 3709 } else { 3710 // On RV32, i64-element vectors must be specially handled to place the 3711 // value at element 0, by using two vslide1up instructions in sequence on 3712 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 3713 // this. 3714 SDValue One = DAG.getConstant(1, DL, XLenVT); 3715 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 3716 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 3717 MVT I32ContainerVT = 3718 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 3719 SDValue I32Mask = 3720 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 3721 // Limit the active VL to two. 3722 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 3723 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 3724 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 3725 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 3726 InsertI64VL); 3727 // First slide in the hi value, then the lo in underneath it. 3728 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3729 ValHi, I32Mask, InsertI64VL); 3730 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3731 ValLo, I32Mask, InsertI64VL); 3732 // Bitcast back to the right container type. 3733 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 3734 } 3735 3736 // Now that the value is in a vector, slide it into position. 3737 SDValue InsertVL = 3738 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 3739 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 3740 ValInVec, Idx, Mask, InsertVL); 3741 if (!VecVT.isFixedLengthVector()) 3742 return Slideup; 3743 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 3744 } 3745 3746 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 3747 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 3748 // types this is done using VMV_X_S to allow us to glean information about the 3749 // sign bits of the result. 3750 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 3751 SelectionDAG &DAG) const { 3752 SDLoc DL(Op); 3753 SDValue Idx = Op.getOperand(1); 3754 SDValue Vec = Op.getOperand(0); 3755 EVT EltVT = Op.getValueType(); 3756 MVT VecVT = Vec.getSimpleValueType(); 3757 MVT XLenVT = Subtarget.getXLenVT(); 3758 3759 if (VecVT.getVectorElementType() == MVT::i1) { 3760 // FIXME: For now we just promote to an i8 vector and extract from that, 3761 // but this is probably not optimal. 3762 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3763 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3764 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 3765 } 3766 3767 // If this is a fixed vector, we need to convert it to a scalable vector. 3768 MVT ContainerVT = VecVT; 3769 if (VecVT.isFixedLengthVector()) { 3770 ContainerVT = getContainerForFixedLengthVector(VecVT); 3771 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3772 } 3773 3774 // If the index is 0, the vector is already in the right position. 3775 if (!isNullConstant(Idx)) { 3776 // Use a VL of 1 to avoid processing more elements than we need. 3777 SDValue VL = DAG.getConstant(1, DL, XLenVT); 3778 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3779 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 3780 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 3781 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 3782 } 3783 3784 if (!EltVT.isInteger()) { 3785 // Floating-point extracts are handled in TableGen. 3786 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 3787 DAG.getConstant(0, DL, XLenVT)); 3788 } 3789 3790 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 3791 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 3792 } 3793 3794 // Some RVV intrinsics may claim that they want an integer operand to be 3795 // promoted or expanded. 3796 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 3797 const RISCVSubtarget &Subtarget) { 3798 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3799 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 3800 "Unexpected opcode"); 3801 3802 if (!Subtarget.hasVInstructions()) 3803 return SDValue(); 3804 3805 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 3806 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 3807 SDLoc DL(Op); 3808 3809 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 3810 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 3811 if (!II || !II->SplatOperand) 3812 return SDValue(); 3813 3814 unsigned SplatOp = II->SplatOperand + HasChain; 3815 assert(SplatOp < Op.getNumOperands()); 3816 3817 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 3818 SDValue &ScalarOp = Operands[SplatOp]; 3819 MVT OpVT = ScalarOp.getSimpleValueType(); 3820 MVT XLenVT = Subtarget.getXLenVT(); 3821 3822 // If this isn't a scalar, or its type is XLenVT we're done. 3823 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 3824 return SDValue(); 3825 3826 // Simplest case is that the operand needs to be promoted to XLenVT. 3827 if (OpVT.bitsLT(XLenVT)) { 3828 // If the operand is a constant, sign extend to increase our chances 3829 // of being able to use a .vi instruction. ANY_EXTEND would become a 3830 // a zero extend and the simm5 check in isel would fail. 3831 // FIXME: Should we ignore the upper bits in isel instead? 3832 unsigned ExtOpc = 3833 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 3834 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 3835 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3836 } 3837 3838 // Use the previous operand to get the vXi64 VT. The result might be a mask 3839 // VT for compares. Using the previous operand assumes that the previous 3840 // operand will never have a smaller element size than a scalar operand and 3841 // that a widening operation never uses SEW=64. 3842 // NOTE: If this fails the below assert, we can probably just find the 3843 // element count from any operand or result and use it to construct the VT. 3844 assert(II->SplatOperand > 1 && "Unexpected splat operand!"); 3845 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 3846 3847 // The more complex case is when the scalar is larger than XLenVT. 3848 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 3849 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 3850 3851 // If this is a sign-extended 32-bit constant, we can truncate it and rely 3852 // on the instruction to sign-extend since SEW>XLEN. 3853 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 3854 if (isInt<32>(CVal->getSExtValue())) { 3855 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3856 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3857 } 3858 } 3859 3860 // We need to convert the scalar to a splat vector. 3861 // FIXME: Can we implicitly truncate the scalar if it is known to 3862 // be sign extended? 3863 // VL should be the last operand. 3864 SDValue VL = Op.getOperand(Op.getNumOperands() - 1); 3865 assert(VL.getValueType() == XLenVT); 3866 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 3867 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3868 } 3869 3870 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3871 SelectionDAG &DAG) const { 3872 unsigned IntNo = Op.getConstantOperandVal(0); 3873 SDLoc DL(Op); 3874 MVT XLenVT = Subtarget.getXLenVT(); 3875 3876 switch (IntNo) { 3877 default: 3878 break; // Don't custom lower most intrinsics. 3879 case Intrinsic::thread_pointer: { 3880 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3881 return DAG.getRegister(RISCV::X4, PtrVT); 3882 } 3883 case Intrinsic::riscv_orc_b: 3884 // Lower to the GORCI encoding for orc.b. 3885 return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1), 3886 DAG.getConstant(7, DL, XLenVT)); 3887 case Intrinsic::riscv_grev: 3888 case Intrinsic::riscv_gorc: { 3889 unsigned Opc = 3890 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 3891 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3892 } 3893 case Intrinsic::riscv_shfl: 3894 case Intrinsic::riscv_unshfl: { 3895 unsigned Opc = 3896 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 3897 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3898 } 3899 case Intrinsic::riscv_bcompress: 3900 case Intrinsic::riscv_bdecompress: { 3901 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 3902 : RISCVISD::BDECOMPRESS; 3903 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3904 } 3905 case Intrinsic::riscv_vmv_x_s: 3906 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 3907 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 3908 Op.getOperand(1)); 3909 case Intrinsic::riscv_vmv_v_x: 3910 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 3911 Op.getSimpleValueType(), DL, DAG, Subtarget); 3912 case Intrinsic::riscv_vfmv_v_f: 3913 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 3914 Op.getOperand(1), Op.getOperand(2)); 3915 case Intrinsic::riscv_vmv_s_x: { 3916 SDValue Scalar = Op.getOperand(2); 3917 3918 if (Scalar.getValueType().bitsLE(XLenVT)) { 3919 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 3920 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 3921 Op.getOperand(1), Scalar, Op.getOperand(3)); 3922 } 3923 3924 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 3925 3926 // This is an i64 value that lives in two scalar registers. We have to 3927 // insert this in a convoluted way. First we build vXi64 splat containing 3928 // the/ two values that we assemble using some bit math. Next we'll use 3929 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 3930 // to merge element 0 from our splat into the source vector. 3931 // FIXME: This is probably not the best way to do this, but it is 3932 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 3933 // point. 3934 // sw lo, (a0) 3935 // sw hi, 4(a0) 3936 // vlse vX, (a0) 3937 // 3938 // vid.v vVid 3939 // vmseq.vx mMask, vVid, 0 3940 // vmerge.vvm vDest, vSrc, vVal, mMask 3941 MVT VT = Op.getSimpleValueType(); 3942 SDValue Vec = Op.getOperand(1); 3943 SDValue VL = Op.getOperand(3); 3944 3945 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 3946 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 3947 DAG.getConstant(0, DL, MVT::i32), VL); 3948 3949 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 3950 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 3951 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 3952 SDValue SelectCond = 3953 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 3954 DAG.getCondCode(ISD::SETEQ), Mask, VL); 3955 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 3956 Vec, VL); 3957 } 3958 case Intrinsic::riscv_vslide1up: 3959 case Intrinsic::riscv_vslide1down: 3960 case Intrinsic::riscv_vslide1up_mask: 3961 case Intrinsic::riscv_vslide1down_mask: { 3962 // We need to special case these when the scalar is larger than XLen. 3963 unsigned NumOps = Op.getNumOperands(); 3964 bool IsMasked = NumOps == 7; 3965 unsigned OpOffset = IsMasked ? 1 : 0; 3966 SDValue Scalar = Op.getOperand(2 + OpOffset); 3967 if (Scalar.getValueType().bitsLE(XLenVT)) 3968 break; 3969 3970 // Splatting a sign extended constant is fine. 3971 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 3972 if (isInt<32>(CVal->getSExtValue())) 3973 break; 3974 3975 MVT VT = Op.getSimpleValueType(); 3976 assert(VT.getVectorElementType() == MVT::i64 && 3977 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 3978 3979 // Convert the vector source to the equivalent nxvXi32 vector. 3980 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 3981 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 3982 3983 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 3984 DAG.getConstant(0, DL, XLenVT)); 3985 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 3986 DAG.getConstant(1, DL, XLenVT)); 3987 3988 // Double the VL since we halved SEW. 3989 SDValue VL = Op.getOperand(NumOps - (1 + OpOffset)); 3990 SDValue I32VL = 3991 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 3992 3993 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 3994 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 3995 3996 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 3997 // instructions. 3998 if (IntNo == Intrinsic::riscv_vslide1up || 3999 IntNo == Intrinsic::riscv_vslide1up_mask) { 4000 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 4001 I32Mask, I32VL); 4002 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 4003 I32Mask, I32VL); 4004 } else { 4005 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 4006 I32Mask, I32VL); 4007 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 4008 I32Mask, I32VL); 4009 } 4010 4011 // Convert back to nxvXi64. 4012 Vec = DAG.getBitcast(VT, Vec); 4013 4014 if (!IsMasked) 4015 return Vec; 4016 4017 // Apply mask after the operation. 4018 SDValue Mask = Op.getOperand(NumOps - 3); 4019 SDValue MaskedOff = Op.getOperand(1); 4020 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4021 } 4022 } 4023 4024 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4025 } 4026 4027 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4028 SelectionDAG &DAG) const { 4029 unsigned IntNo = Op.getConstantOperandVal(1); 4030 switch (IntNo) { 4031 default: 4032 break; 4033 case Intrinsic::riscv_masked_strided_load: { 4034 SDLoc DL(Op); 4035 MVT XLenVT = Subtarget.getXLenVT(); 4036 4037 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4038 // the selection of the masked intrinsics doesn't do this for us. 4039 SDValue Mask = Op.getOperand(5); 4040 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4041 4042 MVT VT = Op->getSimpleValueType(0); 4043 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4044 4045 SDValue PassThru = Op.getOperand(2); 4046 if (!IsUnmasked) { 4047 MVT MaskVT = 4048 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4049 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4050 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4051 } 4052 4053 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4054 4055 SDValue IntID = DAG.getTargetConstant( 4056 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4057 XLenVT); 4058 4059 auto *Load = cast<MemIntrinsicSDNode>(Op); 4060 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4061 if (!IsUnmasked) 4062 Ops.push_back(PassThru); 4063 Ops.push_back(Op.getOperand(3)); // Ptr 4064 Ops.push_back(Op.getOperand(4)); // Stride 4065 if (!IsUnmasked) 4066 Ops.push_back(Mask); 4067 Ops.push_back(VL); 4068 if (!IsUnmasked) { 4069 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4070 Ops.push_back(Policy); 4071 } 4072 4073 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4074 SDValue Result = 4075 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4076 Load->getMemoryVT(), Load->getMemOperand()); 4077 SDValue Chain = Result.getValue(1); 4078 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4079 return DAG.getMergeValues({Result, Chain}, DL); 4080 } 4081 } 4082 4083 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4084 } 4085 4086 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4087 SelectionDAG &DAG) const { 4088 unsigned IntNo = Op.getConstantOperandVal(1); 4089 switch (IntNo) { 4090 default: 4091 break; 4092 case Intrinsic::riscv_masked_strided_store: { 4093 SDLoc DL(Op); 4094 MVT XLenVT = Subtarget.getXLenVT(); 4095 4096 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4097 // the selection of the masked intrinsics doesn't do this for us. 4098 SDValue Mask = Op.getOperand(5); 4099 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4100 4101 SDValue Val = Op.getOperand(2); 4102 MVT VT = Val.getSimpleValueType(); 4103 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4104 4105 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4106 if (!IsUnmasked) { 4107 MVT MaskVT = 4108 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4109 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4110 } 4111 4112 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4113 4114 SDValue IntID = DAG.getTargetConstant( 4115 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4116 XLenVT); 4117 4118 auto *Store = cast<MemIntrinsicSDNode>(Op); 4119 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4120 Ops.push_back(Val); 4121 Ops.push_back(Op.getOperand(3)); // Ptr 4122 Ops.push_back(Op.getOperand(4)); // Stride 4123 if (!IsUnmasked) 4124 Ops.push_back(Mask); 4125 Ops.push_back(VL); 4126 4127 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4128 Ops, Store->getMemoryVT(), 4129 Store->getMemOperand()); 4130 } 4131 } 4132 4133 return SDValue(); 4134 } 4135 4136 static MVT getLMUL1VT(MVT VT) { 4137 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4138 "Unexpected vector MVT"); 4139 return MVT::getScalableVectorVT( 4140 VT.getVectorElementType(), 4141 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4142 } 4143 4144 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4145 switch (ISDOpcode) { 4146 default: 4147 llvm_unreachable("Unhandled reduction"); 4148 case ISD::VECREDUCE_ADD: 4149 return RISCVISD::VECREDUCE_ADD_VL; 4150 case ISD::VECREDUCE_UMAX: 4151 return RISCVISD::VECREDUCE_UMAX_VL; 4152 case ISD::VECREDUCE_SMAX: 4153 return RISCVISD::VECREDUCE_SMAX_VL; 4154 case ISD::VECREDUCE_UMIN: 4155 return RISCVISD::VECREDUCE_UMIN_VL; 4156 case ISD::VECREDUCE_SMIN: 4157 return RISCVISD::VECREDUCE_SMIN_VL; 4158 case ISD::VECREDUCE_AND: 4159 return RISCVISD::VECREDUCE_AND_VL; 4160 case ISD::VECREDUCE_OR: 4161 return RISCVISD::VECREDUCE_OR_VL; 4162 case ISD::VECREDUCE_XOR: 4163 return RISCVISD::VECREDUCE_XOR_VL; 4164 } 4165 } 4166 4167 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4168 SelectionDAG &DAG, 4169 bool IsVP) const { 4170 SDLoc DL(Op); 4171 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4172 MVT VecVT = Vec.getSimpleValueType(); 4173 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4174 Op.getOpcode() == ISD::VECREDUCE_OR || 4175 Op.getOpcode() == ISD::VECREDUCE_XOR || 4176 Op.getOpcode() == ISD::VP_REDUCE_AND || 4177 Op.getOpcode() == ISD::VP_REDUCE_OR || 4178 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4179 "Unexpected reduction lowering"); 4180 4181 MVT XLenVT = Subtarget.getXLenVT(); 4182 assert(Op.getValueType() == XLenVT && 4183 "Expected reduction output to be legalized to XLenVT"); 4184 4185 MVT ContainerVT = VecVT; 4186 if (VecVT.isFixedLengthVector()) { 4187 ContainerVT = getContainerForFixedLengthVector(VecVT); 4188 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4189 } 4190 4191 SDValue Mask, VL; 4192 if (IsVP) { 4193 Mask = Op.getOperand(2); 4194 VL = Op.getOperand(3); 4195 } else { 4196 std::tie(Mask, VL) = 4197 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4198 } 4199 4200 unsigned BaseOpc; 4201 ISD::CondCode CC; 4202 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4203 4204 switch (Op.getOpcode()) { 4205 default: 4206 llvm_unreachable("Unhandled reduction"); 4207 case ISD::VECREDUCE_AND: 4208 case ISD::VP_REDUCE_AND: { 4209 // vcpop ~x == 0 4210 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4211 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4212 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4213 CC = ISD::SETEQ; 4214 BaseOpc = ISD::AND; 4215 break; 4216 } 4217 case ISD::VECREDUCE_OR: 4218 case ISD::VP_REDUCE_OR: 4219 // vcpop x != 0 4220 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4221 CC = ISD::SETNE; 4222 BaseOpc = ISD::OR; 4223 break; 4224 case ISD::VECREDUCE_XOR: 4225 case ISD::VP_REDUCE_XOR: { 4226 // ((vcpop x) & 1) != 0 4227 SDValue One = DAG.getConstant(1, DL, XLenVT); 4228 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4229 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4230 CC = ISD::SETNE; 4231 BaseOpc = ISD::XOR; 4232 break; 4233 } 4234 } 4235 4236 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4237 4238 if (!IsVP) 4239 return SetCC; 4240 4241 // Now include the start value in the operation. 4242 // Note that we must return the start value when no elements are operated 4243 // upon. The vcpop instructions we've emitted in each case above will return 4244 // 0 for an inactive vector, and so we've already received the neutral value: 4245 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4246 // can simply include the start value. 4247 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4248 } 4249 4250 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4251 SelectionDAG &DAG) const { 4252 SDLoc DL(Op); 4253 SDValue Vec = Op.getOperand(0); 4254 EVT VecEVT = Vec.getValueType(); 4255 4256 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4257 4258 // Due to ordering in legalize types we may have a vector type that needs to 4259 // be split. Do that manually so we can get down to a legal type. 4260 while (getTypeAction(*DAG.getContext(), VecEVT) == 4261 TargetLowering::TypeSplitVector) { 4262 SDValue Lo, Hi; 4263 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4264 VecEVT = Lo.getValueType(); 4265 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4266 } 4267 4268 // TODO: The type may need to be widened rather than split. Or widened before 4269 // it can be split. 4270 if (!isTypeLegal(VecEVT)) 4271 return SDValue(); 4272 4273 MVT VecVT = VecEVT.getSimpleVT(); 4274 MVT VecEltVT = VecVT.getVectorElementType(); 4275 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4276 4277 MVT ContainerVT = VecVT; 4278 if (VecVT.isFixedLengthVector()) { 4279 ContainerVT = getContainerForFixedLengthVector(VecVT); 4280 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4281 } 4282 4283 MVT M1VT = getLMUL1VT(ContainerVT); 4284 4285 SDValue Mask, VL; 4286 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4287 4288 // FIXME: This is a VLMAX splat which might be too large and can prevent 4289 // vsetvli removal. 4290 SDValue NeutralElem = 4291 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4292 SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem); 4293 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4294 IdentitySplat, Mask, VL); 4295 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4296 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4297 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4298 } 4299 4300 // Given a reduction op, this function returns the matching reduction opcode, 4301 // the vector SDValue and the scalar SDValue required to lower this to a 4302 // RISCVISD node. 4303 static std::tuple<unsigned, SDValue, SDValue> 4304 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4305 SDLoc DL(Op); 4306 auto Flags = Op->getFlags(); 4307 unsigned Opcode = Op.getOpcode(); 4308 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4309 switch (Opcode) { 4310 default: 4311 llvm_unreachable("Unhandled reduction"); 4312 case ISD::VECREDUCE_FADD: 4313 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), 4314 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4315 case ISD::VECREDUCE_SEQ_FADD: 4316 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4317 Op.getOperand(0)); 4318 case ISD::VECREDUCE_FMIN: 4319 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4320 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4321 case ISD::VECREDUCE_FMAX: 4322 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4323 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4324 } 4325 } 4326 4327 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4328 SelectionDAG &DAG) const { 4329 SDLoc DL(Op); 4330 MVT VecEltVT = Op.getSimpleValueType(); 4331 4332 unsigned RVVOpcode; 4333 SDValue VectorVal, ScalarVal; 4334 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4335 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4336 MVT VecVT = VectorVal.getSimpleValueType(); 4337 4338 MVT ContainerVT = VecVT; 4339 if (VecVT.isFixedLengthVector()) { 4340 ContainerVT = getContainerForFixedLengthVector(VecVT); 4341 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4342 } 4343 4344 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4345 4346 SDValue Mask, VL; 4347 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4348 4349 // FIXME: This is a VLMAX splat which might be too large and can prevent 4350 // vsetvli removal. 4351 SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal); 4352 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4353 VectorVal, ScalarSplat, Mask, VL); 4354 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4355 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4356 } 4357 4358 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4359 switch (ISDOpcode) { 4360 default: 4361 llvm_unreachable("Unhandled reduction"); 4362 case ISD::VP_REDUCE_ADD: 4363 return RISCVISD::VECREDUCE_ADD_VL; 4364 case ISD::VP_REDUCE_UMAX: 4365 return RISCVISD::VECREDUCE_UMAX_VL; 4366 case ISD::VP_REDUCE_SMAX: 4367 return RISCVISD::VECREDUCE_SMAX_VL; 4368 case ISD::VP_REDUCE_UMIN: 4369 return RISCVISD::VECREDUCE_UMIN_VL; 4370 case ISD::VP_REDUCE_SMIN: 4371 return RISCVISD::VECREDUCE_SMIN_VL; 4372 case ISD::VP_REDUCE_AND: 4373 return RISCVISD::VECREDUCE_AND_VL; 4374 case ISD::VP_REDUCE_OR: 4375 return RISCVISD::VECREDUCE_OR_VL; 4376 case ISD::VP_REDUCE_XOR: 4377 return RISCVISD::VECREDUCE_XOR_VL; 4378 case ISD::VP_REDUCE_FADD: 4379 return RISCVISD::VECREDUCE_FADD_VL; 4380 case ISD::VP_REDUCE_SEQ_FADD: 4381 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 4382 case ISD::VP_REDUCE_FMAX: 4383 return RISCVISD::VECREDUCE_FMAX_VL; 4384 case ISD::VP_REDUCE_FMIN: 4385 return RISCVISD::VECREDUCE_FMIN_VL; 4386 } 4387 } 4388 4389 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 4390 SelectionDAG &DAG) const { 4391 SDLoc DL(Op); 4392 SDValue Vec = Op.getOperand(1); 4393 EVT VecEVT = Vec.getValueType(); 4394 4395 // TODO: The type may need to be widened rather than split. Or widened before 4396 // it can be split. 4397 if (!isTypeLegal(VecEVT)) 4398 return SDValue(); 4399 4400 MVT VecVT = VecEVT.getSimpleVT(); 4401 MVT VecEltVT = VecVT.getVectorElementType(); 4402 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 4403 4404 MVT ContainerVT = VecVT; 4405 if (VecVT.isFixedLengthVector()) { 4406 ContainerVT = getContainerForFixedLengthVector(VecVT); 4407 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4408 } 4409 4410 SDValue VL = Op.getOperand(3); 4411 SDValue Mask = Op.getOperand(2); 4412 4413 MVT M1VT = getLMUL1VT(ContainerVT); 4414 MVT XLenVT = Subtarget.getXLenVT(); 4415 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 4416 4417 // FIXME: This is a VLMAX splat which might be too large and can prevent 4418 // vsetvli removal. 4419 SDValue StartSplat = DAG.getSplatVector(M1VT, DL, Op.getOperand(0)); 4420 SDValue Reduction = 4421 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 4422 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 4423 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4424 if (!VecVT.isInteger()) 4425 return Elt0; 4426 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4427 } 4428 4429 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4430 SelectionDAG &DAG) const { 4431 SDValue Vec = Op.getOperand(0); 4432 SDValue SubVec = Op.getOperand(1); 4433 MVT VecVT = Vec.getSimpleValueType(); 4434 MVT SubVecVT = SubVec.getSimpleValueType(); 4435 4436 SDLoc DL(Op); 4437 MVT XLenVT = Subtarget.getXLenVT(); 4438 unsigned OrigIdx = Op.getConstantOperandVal(2); 4439 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4440 4441 // We don't have the ability to slide mask vectors up indexed by their i1 4442 // elements; the smallest we can do is i8. Often we are able to bitcast to 4443 // equivalent i8 vectors. Note that when inserting a fixed-length vector 4444 // into a scalable one, we might not necessarily have enough scalable 4445 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 4446 if (SubVecVT.getVectorElementType() == MVT::i1 && 4447 (OrigIdx != 0 || !Vec.isUndef())) { 4448 if (VecVT.getVectorMinNumElements() >= 8 && 4449 SubVecVT.getVectorMinNumElements() >= 8) { 4450 assert(OrigIdx % 8 == 0 && "Invalid index"); 4451 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4452 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4453 "Unexpected mask vector lowering"); 4454 OrigIdx /= 8; 4455 SubVecVT = 4456 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4457 SubVecVT.isScalableVector()); 4458 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4459 VecVT.isScalableVector()); 4460 Vec = DAG.getBitcast(VecVT, Vec); 4461 SubVec = DAG.getBitcast(SubVecVT, SubVec); 4462 } else { 4463 // We can't slide this mask vector up indexed by its i1 elements. 4464 // This poses a problem when we wish to insert a scalable vector which 4465 // can't be re-expressed as a larger type. Just choose the slow path and 4466 // extend to a larger type, then truncate back down. 4467 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4468 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4469 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4470 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 4471 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 4472 Op.getOperand(2)); 4473 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 4474 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 4475 } 4476 } 4477 4478 // If the subvector vector is a fixed-length type, we cannot use subregister 4479 // manipulation to simplify the codegen; we don't know which register of a 4480 // LMUL group contains the specific subvector as we only know the minimum 4481 // register size. Therefore we must slide the vector group up the full 4482 // amount. 4483 if (SubVecVT.isFixedLengthVector()) { 4484 if (OrigIdx == 0 && Vec.isUndef()) 4485 return Op; 4486 MVT ContainerVT = VecVT; 4487 if (VecVT.isFixedLengthVector()) { 4488 ContainerVT = getContainerForFixedLengthVector(VecVT); 4489 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4490 } 4491 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 4492 DAG.getUNDEF(ContainerVT), SubVec, 4493 DAG.getConstant(0, DL, XLenVT)); 4494 SDValue Mask = 4495 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4496 // Set the vector length to only the number of elements we care about. Note 4497 // that for slideup this includes the offset. 4498 SDValue VL = 4499 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 4500 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4501 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4502 SubVec, SlideupAmt, Mask, VL); 4503 if (VecVT.isFixedLengthVector()) 4504 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4505 return DAG.getBitcast(Op.getValueType(), Slideup); 4506 } 4507 4508 unsigned SubRegIdx, RemIdx; 4509 std::tie(SubRegIdx, RemIdx) = 4510 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4511 VecVT, SubVecVT, OrigIdx, TRI); 4512 4513 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 4514 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 4515 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 4516 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 4517 4518 // 1. If the Idx has been completely eliminated and this subvector's size is 4519 // a vector register or a multiple thereof, or the surrounding elements are 4520 // undef, then this is a subvector insert which naturally aligns to a vector 4521 // register. These can easily be handled using subregister manipulation. 4522 // 2. If the subvector is smaller than a vector register, then the insertion 4523 // must preserve the undisturbed elements of the register. We do this by 4524 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 4525 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 4526 // subvector within the vector register, and an INSERT_SUBVECTOR of that 4527 // LMUL=1 type back into the larger vector (resolving to another subregister 4528 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 4529 // to avoid allocating a large register group to hold our subvector. 4530 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 4531 return Op; 4532 4533 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 4534 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 4535 // (in our case undisturbed). This means we can set up a subvector insertion 4536 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 4537 // size of the subvector. 4538 MVT InterSubVT = VecVT; 4539 SDValue AlignedExtract = Vec; 4540 unsigned AlignedIdx = OrigIdx - RemIdx; 4541 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4542 InterSubVT = getLMUL1VT(VecVT); 4543 // Extract a subvector equal to the nearest full vector register type. This 4544 // should resolve to a EXTRACT_SUBREG instruction. 4545 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4546 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4547 } 4548 4549 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4550 // For scalable vectors this must be further multiplied by vscale. 4551 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 4552 4553 SDValue Mask, VL; 4554 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4555 4556 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 4557 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 4558 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 4559 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 4560 4561 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 4562 DAG.getUNDEF(InterSubVT), SubVec, 4563 DAG.getConstant(0, DL, XLenVT)); 4564 4565 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 4566 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 4567 4568 // If required, insert this subvector back into the correct vector register. 4569 // This should resolve to an INSERT_SUBREG instruction. 4570 if (VecVT.bitsGT(InterSubVT)) 4571 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 4572 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4573 4574 // We might have bitcast from a mask type: cast back to the original type if 4575 // required. 4576 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 4577 } 4578 4579 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 4580 SelectionDAG &DAG) const { 4581 SDValue Vec = Op.getOperand(0); 4582 MVT SubVecVT = Op.getSimpleValueType(); 4583 MVT VecVT = Vec.getSimpleValueType(); 4584 4585 SDLoc DL(Op); 4586 MVT XLenVT = Subtarget.getXLenVT(); 4587 unsigned OrigIdx = Op.getConstantOperandVal(1); 4588 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4589 4590 // We don't have the ability to slide mask vectors down indexed by their i1 4591 // elements; the smallest we can do is i8. Often we are able to bitcast to 4592 // equivalent i8 vectors. Note that when extracting a fixed-length vector 4593 // from a scalable one, we might not necessarily have enough scalable 4594 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 4595 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 4596 if (VecVT.getVectorMinNumElements() >= 8 && 4597 SubVecVT.getVectorMinNumElements() >= 8) { 4598 assert(OrigIdx % 8 == 0 && "Invalid index"); 4599 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4600 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4601 "Unexpected mask vector lowering"); 4602 OrigIdx /= 8; 4603 SubVecVT = 4604 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4605 SubVecVT.isScalableVector()); 4606 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4607 VecVT.isScalableVector()); 4608 Vec = DAG.getBitcast(VecVT, Vec); 4609 } else { 4610 // We can't slide this mask vector down, indexed by its i1 elements. 4611 // This poses a problem when we wish to extract a scalable vector which 4612 // can't be re-expressed as a larger type. Just choose the slow path and 4613 // extend to a larger type, then truncate back down. 4614 // TODO: We could probably improve this when extracting certain fixed 4615 // from fixed, where we can extract as i8 and shift the correct element 4616 // right to reach the desired subvector? 4617 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4618 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4619 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4620 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 4621 Op.getOperand(1)); 4622 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 4623 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 4624 } 4625 } 4626 4627 // If the subvector vector is a fixed-length type, we cannot use subregister 4628 // manipulation to simplify the codegen; we don't know which register of a 4629 // LMUL group contains the specific subvector as we only know the minimum 4630 // register size. Therefore we must slide the vector group down the full 4631 // amount. 4632 if (SubVecVT.isFixedLengthVector()) { 4633 // With an index of 0 this is a cast-like subvector, which can be performed 4634 // with subregister operations. 4635 if (OrigIdx == 0) 4636 return Op; 4637 MVT ContainerVT = VecVT; 4638 if (VecVT.isFixedLengthVector()) { 4639 ContainerVT = getContainerForFixedLengthVector(VecVT); 4640 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4641 } 4642 SDValue Mask = 4643 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4644 // Set the vector length to only the number of elements we care about. This 4645 // avoids sliding down elements we're going to discard straight away. 4646 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 4647 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4648 SDValue Slidedown = 4649 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4650 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 4651 // Now we can use a cast-like subvector extract to get the result. 4652 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4653 DAG.getConstant(0, DL, XLenVT)); 4654 return DAG.getBitcast(Op.getValueType(), Slidedown); 4655 } 4656 4657 unsigned SubRegIdx, RemIdx; 4658 std::tie(SubRegIdx, RemIdx) = 4659 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4660 VecVT, SubVecVT, OrigIdx, TRI); 4661 4662 // If the Idx has been completely eliminated then this is a subvector extract 4663 // which naturally aligns to a vector register. These can easily be handled 4664 // using subregister manipulation. 4665 if (RemIdx == 0) 4666 return Op; 4667 4668 // Else we must shift our vector register directly to extract the subvector. 4669 // Do this using VSLIDEDOWN. 4670 4671 // If the vector type is an LMUL-group type, extract a subvector equal to the 4672 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 4673 // instruction. 4674 MVT InterSubVT = VecVT; 4675 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4676 InterSubVT = getLMUL1VT(VecVT); 4677 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4678 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 4679 } 4680 4681 // Slide this vector register down by the desired number of elements in order 4682 // to place the desired subvector starting at element 0. 4683 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4684 // For scalable vectors this must be further multiplied by vscale. 4685 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 4686 4687 SDValue Mask, VL; 4688 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 4689 SDValue Slidedown = 4690 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 4691 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 4692 4693 // Now the vector is in the right position, extract our final subvector. This 4694 // should resolve to a COPY. 4695 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4696 DAG.getConstant(0, DL, XLenVT)); 4697 4698 // We might have bitcast from a mask type: cast back to the original type if 4699 // required. 4700 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 4701 } 4702 4703 // Lower step_vector to the vid instruction. Any non-identity step value must 4704 // be accounted for my manual expansion. 4705 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 4706 SelectionDAG &DAG) const { 4707 SDLoc DL(Op); 4708 MVT VT = Op.getSimpleValueType(); 4709 MVT XLenVT = Subtarget.getXLenVT(); 4710 SDValue Mask, VL; 4711 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 4712 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4713 uint64_t StepValImm = Op.getConstantOperandVal(0); 4714 if (StepValImm != 1) { 4715 if (isPowerOf2_64(StepValImm)) { 4716 SDValue StepVal = 4717 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4718 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 4719 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 4720 } else { 4721 SDValue StepVal = lowerScalarSplat( 4722 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 4723 DL, DAG, Subtarget); 4724 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 4725 } 4726 } 4727 return StepVec; 4728 } 4729 4730 // Implement vector_reverse using vrgather.vv with indices determined by 4731 // subtracting the id of each element from (VLMAX-1). This will convert 4732 // the indices like so: 4733 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 4734 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 4735 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 4736 SelectionDAG &DAG) const { 4737 SDLoc DL(Op); 4738 MVT VecVT = Op.getSimpleValueType(); 4739 unsigned EltSize = VecVT.getScalarSizeInBits(); 4740 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 4741 4742 unsigned MaxVLMAX = 0; 4743 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 4744 if (VectorBitsMax != 0) 4745 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 4746 4747 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 4748 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 4749 4750 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 4751 // to use vrgatherei16.vv. 4752 // TODO: It's also possible to use vrgatherei16.vv for other types to 4753 // decrease register width for the index calculation. 4754 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 4755 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 4756 // Reverse each half, then reassemble them in reverse order. 4757 // NOTE: It's also possible that after splitting that VLMAX no longer 4758 // requires vrgatherei16.vv. 4759 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 4760 SDValue Lo, Hi; 4761 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4762 EVT LoVT, HiVT; 4763 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 4764 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 4765 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 4766 // Reassemble the low and high pieces reversed. 4767 // FIXME: This is a CONCAT_VECTORS. 4768 SDValue Res = 4769 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 4770 DAG.getIntPtrConstant(0, DL)); 4771 return DAG.getNode( 4772 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 4773 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 4774 } 4775 4776 // Just promote the int type to i16 which will double the LMUL. 4777 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 4778 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 4779 } 4780 4781 MVT XLenVT = Subtarget.getXLenVT(); 4782 SDValue Mask, VL; 4783 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4784 4785 // Calculate VLMAX-1 for the desired SEW. 4786 unsigned MinElts = VecVT.getVectorMinNumElements(); 4787 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 4788 DAG.getConstant(MinElts, DL, XLenVT)); 4789 SDValue VLMinus1 = 4790 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 4791 4792 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 4793 bool IsRV32E64 = 4794 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 4795 SDValue SplatVL; 4796 if (!IsRV32E64) 4797 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 4798 else 4799 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 4800 4801 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 4802 SDValue Indices = 4803 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 4804 4805 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 4806 } 4807 4808 SDValue 4809 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 4810 SelectionDAG &DAG) const { 4811 SDLoc DL(Op); 4812 auto *Load = cast<LoadSDNode>(Op); 4813 4814 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 4815 Load->getMemoryVT(), 4816 *Load->getMemOperand()) && 4817 "Expecting a correctly-aligned load"); 4818 4819 MVT VT = Op.getSimpleValueType(); 4820 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4821 4822 SDValue VL = 4823 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4824 4825 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4826 SDValue NewLoad = DAG.getMemIntrinsicNode( 4827 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 4828 Load->getMemoryVT(), Load->getMemOperand()); 4829 4830 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 4831 return DAG.getMergeValues({Result, Load->getChain()}, DL); 4832 } 4833 4834 SDValue 4835 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 4836 SelectionDAG &DAG) const { 4837 SDLoc DL(Op); 4838 auto *Store = cast<StoreSDNode>(Op); 4839 4840 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 4841 Store->getMemoryVT(), 4842 *Store->getMemOperand()) && 4843 "Expecting a correctly-aligned store"); 4844 4845 SDValue StoreVal = Store->getValue(); 4846 MVT VT = StoreVal.getSimpleValueType(); 4847 4848 // If the size less than a byte, we need to pad with zeros to make a byte. 4849 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 4850 VT = MVT::v8i1; 4851 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 4852 DAG.getConstant(0, DL, VT), StoreVal, 4853 DAG.getIntPtrConstant(0, DL)); 4854 } 4855 4856 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4857 4858 SDValue VL = 4859 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4860 4861 SDValue NewValue = 4862 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 4863 return DAG.getMemIntrinsicNode( 4864 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 4865 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 4866 Store->getMemoryVT(), Store->getMemOperand()); 4867 } 4868 4869 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 4870 SelectionDAG &DAG) const { 4871 SDLoc DL(Op); 4872 MVT VT = Op.getSimpleValueType(); 4873 4874 const auto *MemSD = cast<MemSDNode>(Op); 4875 EVT MemVT = MemSD->getMemoryVT(); 4876 MachineMemOperand *MMO = MemSD->getMemOperand(); 4877 SDValue Chain = MemSD->getChain(); 4878 SDValue BasePtr = MemSD->getBasePtr(); 4879 4880 SDValue Mask, PassThru, VL; 4881 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 4882 Mask = VPLoad->getMask(); 4883 PassThru = DAG.getUNDEF(VT); 4884 VL = VPLoad->getVectorLength(); 4885 } else { 4886 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 4887 Mask = MLoad->getMask(); 4888 PassThru = MLoad->getPassThru(); 4889 } 4890 4891 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4892 4893 MVT XLenVT = Subtarget.getXLenVT(); 4894 4895 MVT ContainerVT = VT; 4896 if (VT.isFixedLengthVector()) { 4897 ContainerVT = getContainerForFixedLengthVector(VT); 4898 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4899 if (!IsUnmasked) { 4900 MVT MaskVT = 4901 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4902 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4903 } 4904 } 4905 4906 if (!VL) 4907 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 4908 4909 unsigned IntID = 4910 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 4911 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 4912 if (!IsUnmasked) 4913 Ops.push_back(PassThru); 4914 Ops.push_back(BasePtr); 4915 if (!IsUnmasked) 4916 Ops.push_back(Mask); 4917 Ops.push_back(VL); 4918 if (!IsUnmasked) 4919 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 4920 4921 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4922 4923 SDValue Result = 4924 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 4925 Chain = Result.getValue(1); 4926 4927 if (VT.isFixedLengthVector()) 4928 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4929 4930 return DAG.getMergeValues({Result, Chain}, DL); 4931 } 4932 4933 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 4934 SelectionDAG &DAG) const { 4935 SDLoc DL(Op); 4936 4937 const auto *MemSD = cast<MemSDNode>(Op); 4938 EVT MemVT = MemSD->getMemoryVT(); 4939 MachineMemOperand *MMO = MemSD->getMemOperand(); 4940 SDValue Chain = MemSD->getChain(); 4941 SDValue BasePtr = MemSD->getBasePtr(); 4942 SDValue Val, Mask, VL; 4943 4944 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 4945 Val = VPStore->getValue(); 4946 Mask = VPStore->getMask(); 4947 VL = VPStore->getVectorLength(); 4948 } else { 4949 const auto *MStore = cast<MaskedStoreSDNode>(Op); 4950 Val = MStore->getValue(); 4951 Mask = MStore->getMask(); 4952 } 4953 4954 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4955 4956 MVT VT = Val.getSimpleValueType(); 4957 MVT XLenVT = Subtarget.getXLenVT(); 4958 4959 MVT ContainerVT = VT; 4960 if (VT.isFixedLengthVector()) { 4961 ContainerVT = getContainerForFixedLengthVector(VT); 4962 4963 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4964 if (!IsUnmasked) { 4965 MVT MaskVT = 4966 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4967 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4968 } 4969 } 4970 4971 if (!VL) 4972 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 4973 4974 unsigned IntID = 4975 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 4976 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 4977 Ops.push_back(Val); 4978 Ops.push_back(BasePtr); 4979 if (!IsUnmasked) 4980 Ops.push_back(Mask); 4981 Ops.push_back(VL); 4982 4983 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 4984 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 4985 } 4986 4987 SDValue 4988 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 4989 SelectionDAG &DAG) const { 4990 MVT InVT = Op.getOperand(0).getSimpleValueType(); 4991 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 4992 4993 MVT VT = Op.getSimpleValueType(); 4994 4995 SDValue Op1 = 4996 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4997 SDValue Op2 = 4998 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 4999 5000 SDLoc DL(Op); 5001 SDValue VL = 5002 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5003 5004 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5005 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5006 5007 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5008 Op.getOperand(2), Mask, VL); 5009 5010 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5011 } 5012 5013 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5014 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5015 MVT VT = Op.getSimpleValueType(); 5016 5017 if (VT.getVectorElementType() == MVT::i1) 5018 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5019 5020 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5021 } 5022 5023 SDValue 5024 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5025 SelectionDAG &DAG) const { 5026 unsigned Opc; 5027 switch (Op.getOpcode()) { 5028 default: llvm_unreachable("Unexpected opcode!"); 5029 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5030 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5031 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5032 } 5033 5034 return lowerToScalableOp(Op, DAG, Opc); 5035 } 5036 5037 // Lower vector ABS to smax(X, sub(0, X)). 5038 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5039 SDLoc DL(Op); 5040 MVT VT = Op.getSimpleValueType(); 5041 SDValue X = Op.getOperand(0); 5042 5043 assert(VT.isFixedLengthVector() && "Unexpected type"); 5044 5045 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5046 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5047 5048 SDValue Mask, VL; 5049 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5050 5051 SDValue SplatZero = 5052 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5053 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5054 SDValue NegX = 5055 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5056 SDValue Max = 5057 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5058 5059 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5060 } 5061 5062 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5063 SDValue Op, SelectionDAG &DAG) const { 5064 SDLoc DL(Op); 5065 MVT VT = Op.getSimpleValueType(); 5066 SDValue Mag = Op.getOperand(0); 5067 SDValue Sign = Op.getOperand(1); 5068 assert(Mag.getValueType() == Sign.getValueType() && 5069 "Can only handle COPYSIGN with matching types."); 5070 5071 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5072 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5073 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5074 5075 SDValue Mask, VL; 5076 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5077 5078 SDValue CopySign = 5079 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5080 5081 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5082 } 5083 5084 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5085 SDValue Op, SelectionDAG &DAG) const { 5086 MVT VT = Op.getSimpleValueType(); 5087 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5088 5089 MVT I1ContainerVT = 5090 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5091 5092 SDValue CC = 5093 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5094 SDValue Op1 = 5095 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5096 SDValue Op2 = 5097 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5098 5099 SDLoc DL(Op); 5100 SDValue Mask, VL; 5101 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5102 5103 SDValue Select = 5104 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5105 5106 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5107 } 5108 5109 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5110 unsigned NewOpc, 5111 bool HasMask) const { 5112 MVT VT = Op.getSimpleValueType(); 5113 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5114 5115 // Create list of operands by converting existing ones to scalable types. 5116 SmallVector<SDValue, 6> Ops; 5117 for (const SDValue &V : Op->op_values()) { 5118 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5119 5120 // Pass through non-vector operands. 5121 if (!V.getValueType().isVector()) { 5122 Ops.push_back(V); 5123 continue; 5124 } 5125 5126 // "cast" fixed length vector to a scalable vector. 5127 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5128 "Only fixed length vectors are supported!"); 5129 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5130 } 5131 5132 SDLoc DL(Op); 5133 SDValue Mask, VL; 5134 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5135 if (HasMask) 5136 Ops.push_back(Mask); 5137 Ops.push_back(VL); 5138 5139 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5140 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5141 } 5142 5143 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5144 // * Operands of each node are assumed to be in the same order. 5145 // * The EVL operand is promoted from i32 to i64 on RV64. 5146 // * Fixed-length vectors are converted to their scalable-vector container 5147 // types. 5148 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5149 unsigned RISCVISDOpc) const { 5150 SDLoc DL(Op); 5151 MVT VT = Op.getSimpleValueType(); 5152 SmallVector<SDValue, 4> Ops; 5153 5154 for (const auto &OpIdx : enumerate(Op->ops())) { 5155 SDValue V = OpIdx.value(); 5156 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5157 // Pass through operands which aren't fixed-length vectors. 5158 if (!V.getValueType().isFixedLengthVector()) { 5159 Ops.push_back(V); 5160 continue; 5161 } 5162 // "cast" fixed length vector to a scalable vector. 5163 MVT OpVT = V.getSimpleValueType(); 5164 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5165 assert(useRVVForFixedLengthVectorVT(OpVT) && 5166 "Only fixed length vectors are supported!"); 5167 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5168 } 5169 5170 if (!VT.isFixedLengthVector()) 5171 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5172 5173 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5174 5175 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5176 5177 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5178 } 5179 5180 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5181 // matched to a RVV indexed load. The RVV indexed load instructions only 5182 // support the "unsigned unscaled" addressing mode; indices are implicitly 5183 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5184 // signed or scaled indexing is extended to the XLEN value type and scaled 5185 // accordingly. 5186 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5187 SelectionDAG &DAG) const { 5188 SDLoc DL(Op); 5189 MVT VT = Op.getSimpleValueType(); 5190 5191 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5192 EVT MemVT = MemSD->getMemoryVT(); 5193 MachineMemOperand *MMO = MemSD->getMemOperand(); 5194 SDValue Chain = MemSD->getChain(); 5195 SDValue BasePtr = MemSD->getBasePtr(); 5196 5197 ISD::LoadExtType LoadExtType; 5198 SDValue Index, Mask, PassThru, VL; 5199 5200 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5201 Index = VPGN->getIndex(); 5202 Mask = VPGN->getMask(); 5203 PassThru = DAG.getUNDEF(VT); 5204 VL = VPGN->getVectorLength(); 5205 // VP doesn't support extending loads. 5206 LoadExtType = ISD::NON_EXTLOAD; 5207 } else { 5208 // Else it must be a MGATHER. 5209 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5210 Index = MGN->getIndex(); 5211 Mask = MGN->getMask(); 5212 PassThru = MGN->getPassThru(); 5213 LoadExtType = MGN->getExtensionType(); 5214 } 5215 5216 MVT IndexVT = Index.getSimpleValueType(); 5217 MVT XLenVT = Subtarget.getXLenVT(); 5218 5219 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5220 "Unexpected VTs!"); 5221 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5222 // Targets have to explicitly opt-in for extending vector loads. 5223 assert(LoadExtType == ISD::NON_EXTLOAD && 5224 "Unexpected extending MGATHER/VP_GATHER"); 5225 (void)LoadExtType; 5226 5227 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5228 // the selection of the masked intrinsics doesn't do this for us. 5229 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5230 5231 MVT ContainerVT = VT; 5232 if (VT.isFixedLengthVector()) { 5233 // We need to use the larger of the result and index type to determine the 5234 // scalable type to use so we don't increase LMUL for any operand/result. 5235 if (VT.bitsGE(IndexVT)) { 5236 ContainerVT = getContainerForFixedLengthVector(VT); 5237 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5238 ContainerVT.getVectorElementCount()); 5239 } else { 5240 IndexVT = getContainerForFixedLengthVector(IndexVT); 5241 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5242 IndexVT.getVectorElementCount()); 5243 } 5244 5245 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5246 5247 if (!IsUnmasked) { 5248 MVT MaskVT = 5249 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5250 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5251 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5252 } 5253 } 5254 5255 if (!VL) 5256 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5257 5258 unsigned IntID = 5259 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5260 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5261 if (!IsUnmasked) 5262 Ops.push_back(PassThru); 5263 Ops.push_back(BasePtr); 5264 Ops.push_back(Index); 5265 if (!IsUnmasked) 5266 Ops.push_back(Mask); 5267 Ops.push_back(VL); 5268 if (!IsUnmasked) 5269 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5270 5271 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5272 SDValue Result = 5273 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5274 Chain = Result.getValue(1); 5275 5276 if (VT.isFixedLengthVector()) 5277 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5278 5279 return DAG.getMergeValues({Result, Chain}, DL); 5280 } 5281 5282 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5283 // matched to a RVV indexed store. The RVV indexed store instructions only 5284 // support the "unsigned unscaled" addressing mode; indices are implicitly 5285 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5286 // signed or scaled indexing is extended to the XLEN value type and scaled 5287 // accordingly. 5288 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5289 SelectionDAG &DAG) const { 5290 SDLoc DL(Op); 5291 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5292 EVT MemVT = MemSD->getMemoryVT(); 5293 MachineMemOperand *MMO = MemSD->getMemOperand(); 5294 SDValue Chain = MemSD->getChain(); 5295 SDValue BasePtr = MemSD->getBasePtr(); 5296 5297 bool IsTruncatingStore = false; 5298 SDValue Index, Mask, Val, VL; 5299 5300 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5301 Index = VPSN->getIndex(); 5302 Mask = VPSN->getMask(); 5303 Val = VPSN->getValue(); 5304 VL = VPSN->getVectorLength(); 5305 // VP doesn't support truncating stores. 5306 IsTruncatingStore = false; 5307 } else { 5308 // Else it must be a MSCATTER. 5309 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5310 Index = MSN->getIndex(); 5311 Mask = MSN->getMask(); 5312 Val = MSN->getValue(); 5313 IsTruncatingStore = MSN->isTruncatingStore(); 5314 } 5315 5316 MVT VT = Val.getSimpleValueType(); 5317 MVT IndexVT = Index.getSimpleValueType(); 5318 MVT XLenVT = Subtarget.getXLenVT(); 5319 5320 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5321 "Unexpected VTs!"); 5322 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5323 // Targets have to explicitly opt-in for extending vector loads and 5324 // truncating vector stores. 5325 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5326 (void)IsTruncatingStore; 5327 5328 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5329 // the selection of the masked intrinsics doesn't do this for us. 5330 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5331 5332 MVT ContainerVT = VT; 5333 if (VT.isFixedLengthVector()) { 5334 // We need to use the larger of the value and index type to determine the 5335 // scalable type to use so we don't increase LMUL for any operand/result. 5336 if (VT.bitsGE(IndexVT)) { 5337 ContainerVT = getContainerForFixedLengthVector(VT); 5338 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5339 ContainerVT.getVectorElementCount()); 5340 } else { 5341 IndexVT = getContainerForFixedLengthVector(IndexVT); 5342 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 5343 IndexVT.getVectorElementCount()); 5344 } 5345 5346 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5347 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5348 5349 if (!IsUnmasked) { 5350 MVT MaskVT = 5351 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5352 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5353 } 5354 } 5355 5356 if (!VL) 5357 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5358 5359 unsigned IntID = 5360 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 5361 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5362 Ops.push_back(Val); 5363 Ops.push_back(BasePtr); 5364 Ops.push_back(Index); 5365 if (!IsUnmasked) 5366 Ops.push_back(Mask); 5367 Ops.push_back(VL); 5368 5369 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5370 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5371 } 5372 5373 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 5374 SelectionDAG &DAG) const { 5375 const MVT XLenVT = Subtarget.getXLenVT(); 5376 SDLoc DL(Op); 5377 SDValue Chain = Op->getOperand(0); 5378 SDValue SysRegNo = DAG.getTargetConstant( 5379 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5380 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 5381 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 5382 5383 // Encoding used for rounding mode in RISCV differs from that used in 5384 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 5385 // table, which consists of a sequence of 4-bit fields, each representing 5386 // corresponding FLT_ROUNDS mode. 5387 static const int Table = 5388 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 5389 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 5390 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 5391 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 5392 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 5393 5394 SDValue Shift = 5395 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 5396 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5397 DAG.getConstant(Table, DL, XLenVT), Shift); 5398 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5399 DAG.getConstant(7, DL, XLenVT)); 5400 5401 return DAG.getMergeValues({Masked, Chain}, DL); 5402 } 5403 5404 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 5405 SelectionDAG &DAG) const { 5406 const MVT XLenVT = Subtarget.getXLenVT(); 5407 SDLoc DL(Op); 5408 SDValue Chain = Op->getOperand(0); 5409 SDValue RMValue = Op->getOperand(1); 5410 SDValue SysRegNo = DAG.getTargetConstant( 5411 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5412 5413 // Encoding used for rounding mode in RISCV differs from that used in 5414 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 5415 // a table, which consists of a sequence of 4-bit fields, each representing 5416 // corresponding RISCV mode. 5417 static const unsigned Table = 5418 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 5419 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 5420 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 5421 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 5422 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 5423 5424 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 5425 DAG.getConstant(2, DL, XLenVT)); 5426 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5427 DAG.getConstant(Table, DL, XLenVT), Shift); 5428 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5429 DAG.getConstant(0x7, DL, XLenVT)); 5430 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 5431 RMValue); 5432 } 5433 5434 // Returns the opcode of the target-specific SDNode that implements the 32-bit 5435 // form of the given Opcode. 5436 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 5437 switch (Opcode) { 5438 default: 5439 llvm_unreachable("Unexpected opcode"); 5440 case ISD::SHL: 5441 return RISCVISD::SLLW; 5442 case ISD::SRA: 5443 return RISCVISD::SRAW; 5444 case ISD::SRL: 5445 return RISCVISD::SRLW; 5446 case ISD::SDIV: 5447 return RISCVISD::DIVW; 5448 case ISD::UDIV: 5449 return RISCVISD::DIVUW; 5450 case ISD::UREM: 5451 return RISCVISD::REMUW; 5452 case ISD::ROTL: 5453 return RISCVISD::ROLW; 5454 case ISD::ROTR: 5455 return RISCVISD::RORW; 5456 case RISCVISD::GREV: 5457 return RISCVISD::GREVW; 5458 case RISCVISD::GORC: 5459 return RISCVISD::GORCW; 5460 } 5461 } 5462 5463 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 5464 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 5465 // otherwise be promoted to i64, making it difficult to select the 5466 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 5467 // type i8/i16/i32 is lost. 5468 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 5469 unsigned ExtOpc = ISD::ANY_EXTEND) { 5470 SDLoc DL(N); 5471 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5472 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 5473 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 5474 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5475 // ReplaceNodeResults requires we maintain the same type for the return value. 5476 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 5477 } 5478 5479 // Converts the given 32-bit operation to a i64 operation with signed extension 5480 // semantic to reduce the signed extension instructions. 5481 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 5482 SDLoc DL(N); 5483 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5484 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5485 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 5486 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5487 DAG.getValueType(MVT::i32)); 5488 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 5489 } 5490 5491 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 5492 SmallVectorImpl<SDValue> &Results, 5493 SelectionDAG &DAG) const { 5494 SDLoc DL(N); 5495 switch (N->getOpcode()) { 5496 default: 5497 llvm_unreachable("Don't know how to custom type legalize this operation!"); 5498 case ISD::STRICT_FP_TO_SINT: 5499 case ISD::STRICT_FP_TO_UINT: 5500 case ISD::FP_TO_SINT: 5501 case ISD::FP_TO_UINT: { 5502 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5503 "Unexpected custom legalisation"); 5504 bool IsStrict = N->isStrictFPOpcode(); 5505 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 5506 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 5507 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 5508 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 5509 TargetLowering::TypeSoftenFloat) { 5510 // FIXME: Support strict FP. 5511 if (IsStrict) 5512 return; 5513 if (!isTypeLegal(Op0.getValueType())) 5514 return; 5515 unsigned Opc = 5516 IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 5517 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0); 5518 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5519 return; 5520 } 5521 // If the FP type needs to be softened, emit a library call using the 'si' 5522 // version. If we left it to default legalization we'd end up with 'di'. If 5523 // the FP type doesn't need to be softened just let generic type 5524 // legalization promote the result type. 5525 RTLIB::Libcall LC; 5526 if (IsSigned) 5527 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 5528 else 5529 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 5530 MakeLibCallOptions CallOptions; 5531 EVT OpVT = Op0.getValueType(); 5532 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 5533 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 5534 SDValue Result; 5535 std::tie(Result, Chain) = 5536 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 5537 Results.push_back(Result); 5538 if (IsStrict) 5539 Results.push_back(Chain); 5540 break; 5541 } 5542 case ISD::READCYCLECOUNTER: { 5543 assert(!Subtarget.is64Bit() && 5544 "READCYCLECOUNTER only has custom type legalization on riscv32"); 5545 5546 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 5547 SDValue RCW = 5548 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 5549 5550 Results.push_back( 5551 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 5552 Results.push_back(RCW.getValue(2)); 5553 break; 5554 } 5555 case ISD::MUL: { 5556 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 5557 unsigned XLen = Subtarget.getXLen(); 5558 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 5559 if (Size > XLen) { 5560 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 5561 SDValue LHS = N->getOperand(0); 5562 SDValue RHS = N->getOperand(1); 5563 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 5564 5565 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 5566 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 5567 // We need exactly one side to be unsigned. 5568 if (LHSIsU == RHSIsU) 5569 return; 5570 5571 auto MakeMULPair = [&](SDValue S, SDValue U) { 5572 MVT XLenVT = Subtarget.getXLenVT(); 5573 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 5574 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 5575 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 5576 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 5577 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 5578 }; 5579 5580 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 5581 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 5582 5583 // The other operand should be signed, but still prefer MULH when 5584 // possible. 5585 if (RHSIsU && LHSIsS && !RHSIsS) 5586 Results.push_back(MakeMULPair(LHS, RHS)); 5587 else if (LHSIsU && RHSIsS && !LHSIsS) 5588 Results.push_back(MakeMULPair(RHS, LHS)); 5589 5590 return; 5591 } 5592 LLVM_FALLTHROUGH; 5593 } 5594 case ISD::ADD: 5595 case ISD::SUB: 5596 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5597 "Unexpected custom legalisation"); 5598 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 5599 break; 5600 case ISD::SHL: 5601 case ISD::SRA: 5602 case ISD::SRL: 5603 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5604 "Unexpected custom legalisation"); 5605 if (N->getOperand(1).getOpcode() != ISD::Constant) { 5606 Results.push_back(customLegalizeToWOp(N, DAG)); 5607 break; 5608 } 5609 5610 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 5611 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 5612 // shift amount. 5613 if (N->getOpcode() == ISD::SHL) { 5614 SDLoc DL(N); 5615 SDValue NewOp0 = 5616 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5617 SDValue NewOp1 = 5618 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 5619 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 5620 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5621 DAG.getValueType(MVT::i32)); 5622 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5623 } 5624 5625 break; 5626 case ISD::ROTL: 5627 case ISD::ROTR: 5628 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5629 "Unexpected custom legalisation"); 5630 Results.push_back(customLegalizeToWOp(N, DAG)); 5631 break; 5632 case ISD::CTTZ: 5633 case ISD::CTTZ_ZERO_UNDEF: 5634 case ISD::CTLZ: 5635 case ISD::CTLZ_ZERO_UNDEF: { 5636 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5637 "Unexpected custom legalisation"); 5638 5639 SDValue NewOp0 = 5640 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5641 bool IsCTZ = 5642 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 5643 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 5644 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 5645 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5646 return; 5647 } 5648 case ISD::SDIV: 5649 case ISD::UDIV: 5650 case ISD::UREM: { 5651 MVT VT = N->getSimpleValueType(0); 5652 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 5653 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 5654 "Unexpected custom legalisation"); 5655 // Don't promote division/remainder by constant since we should expand those 5656 // to multiply by magic constant. 5657 // FIXME: What if the expansion is disabled for minsize. 5658 if (N->getOperand(1).getOpcode() == ISD::Constant) 5659 return; 5660 5661 // If the input is i32, use ANY_EXTEND since the W instructions don't read 5662 // the upper 32 bits. For other types we need to sign or zero extend 5663 // based on the opcode. 5664 unsigned ExtOpc = ISD::ANY_EXTEND; 5665 if (VT != MVT::i32) 5666 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 5667 : ISD::ZERO_EXTEND; 5668 5669 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 5670 break; 5671 } 5672 case ISD::UADDO: 5673 case ISD::USUBO: { 5674 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5675 "Unexpected custom legalisation"); 5676 bool IsAdd = N->getOpcode() == ISD::UADDO; 5677 // Create an ADDW or SUBW. 5678 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5679 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5680 SDValue Res = 5681 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 5682 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 5683 DAG.getValueType(MVT::i32)); 5684 5685 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 5686 // Since the inputs are sign extended from i32, this is equivalent to 5687 // comparing the lower 32 bits. 5688 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5689 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 5690 IsAdd ? ISD::SETULT : ISD::SETUGT); 5691 5692 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5693 Results.push_back(Overflow); 5694 return; 5695 } 5696 case ISD::UADDSAT: 5697 case ISD::USUBSAT: { 5698 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5699 "Unexpected custom legalisation"); 5700 if (Subtarget.hasStdExtZbb()) { 5701 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 5702 // sign extend allows overflow of the lower 32 bits to be detected on 5703 // the promoted size. 5704 SDValue LHS = 5705 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5706 SDValue RHS = 5707 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 5708 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 5709 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5710 return; 5711 } 5712 5713 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 5714 // promotion for UADDO/USUBO. 5715 Results.push_back(expandAddSubSat(N, DAG)); 5716 return; 5717 } 5718 case ISD::BITCAST: { 5719 EVT VT = N->getValueType(0); 5720 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 5721 SDValue Op0 = N->getOperand(0); 5722 EVT Op0VT = Op0.getValueType(); 5723 MVT XLenVT = Subtarget.getXLenVT(); 5724 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 5725 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 5726 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 5727 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 5728 Subtarget.hasStdExtF()) { 5729 SDValue FPConv = 5730 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 5731 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 5732 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 5733 isTypeLegal(Op0VT)) { 5734 // Custom-legalize bitcasts from fixed-length vector types to illegal 5735 // scalar types in order to improve codegen. Bitcast the vector to a 5736 // one-element vector type whose element type is the same as the result 5737 // type, and extract the first element. 5738 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 5739 if (isTypeLegal(BVT)) { 5740 SDValue BVec = DAG.getBitcast(BVT, Op0); 5741 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 5742 DAG.getConstant(0, DL, XLenVT))); 5743 } 5744 } 5745 break; 5746 } 5747 case RISCVISD::GREV: 5748 case RISCVISD::GORC: { 5749 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5750 "Unexpected custom legalisation"); 5751 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 5752 // This is similar to customLegalizeToWOp, except that we pass the second 5753 // operand (a TargetConstant) straight through: it is already of type 5754 // XLenVT. 5755 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5756 SDValue NewOp0 = 5757 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5758 SDValue NewOp1 = 5759 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5760 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5761 // ReplaceNodeResults requires we maintain the same type for the return 5762 // value. 5763 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5764 break; 5765 } 5766 case RISCVISD::SHFL: { 5767 // There is no SHFLIW instruction, but we can just promote the operation. 5768 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5769 "Unexpected custom legalisation"); 5770 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 5771 SDValue NewOp0 = 5772 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5773 SDValue NewOp1 = 5774 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5775 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 5776 // ReplaceNodeResults requires we maintain the same type for the return 5777 // value. 5778 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5779 break; 5780 } 5781 case ISD::BSWAP: 5782 case ISD::BITREVERSE: { 5783 MVT VT = N->getSimpleValueType(0); 5784 MVT XLenVT = Subtarget.getXLenVT(); 5785 assert((VT == MVT::i8 || VT == MVT::i16 || 5786 (VT == MVT::i32 && Subtarget.is64Bit())) && 5787 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 5788 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 5789 unsigned Imm = VT.getSizeInBits() - 1; 5790 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 5791 if (N->getOpcode() == ISD::BSWAP) 5792 Imm &= ~0x7U; 5793 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 5794 SDValue GREVI = 5795 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 5796 // ReplaceNodeResults requires we maintain the same type for the return 5797 // value. 5798 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 5799 break; 5800 } 5801 case ISD::FSHL: 5802 case ISD::FSHR: { 5803 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5804 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 5805 SDValue NewOp0 = 5806 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5807 SDValue NewOp1 = 5808 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5809 SDValue NewOp2 = 5810 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5811 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 5812 // Mask the shift amount to 5 bits. 5813 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 5814 DAG.getConstant(0x1f, DL, MVT::i64)); 5815 unsigned Opc = 5816 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 5817 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 5818 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 5819 break; 5820 } 5821 case ISD::EXTRACT_VECTOR_ELT: { 5822 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 5823 // type is illegal (currently only vXi64 RV32). 5824 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 5825 // transferred to the destination register. We issue two of these from the 5826 // upper- and lower- halves of the SEW-bit vector element, slid down to the 5827 // first element. 5828 SDValue Vec = N->getOperand(0); 5829 SDValue Idx = N->getOperand(1); 5830 5831 // The vector type hasn't been legalized yet so we can't issue target 5832 // specific nodes if it needs legalization. 5833 // FIXME: We would manually legalize if it's important. 5834 if (!isTypeLegal(Vec.getValueType())) 5835 return; 5836 5837 MVT VecVT = Vec.getSimpleValueType(); 5838 5839 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 5840 VecVT.getVectorElementType() == MVT::i64 && 5841 "Unexpected EXTRACT_VECTOR_ELT legalization"); 5842 5843 // If this is a fixed vector, we need to convert it to a scalable vector. 5844 MVT ContainerVT = VecVT; 5845 if (VecVT.isFixedLengthVector()) { 5846 ContainerVT = getContainerForFixedLengthVector(VecVT); 5847 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5848 } 5849 5850 MVT XLenVT = Subtarget.getXLenVT(); 5851 5852 // Use a VL of 1 to avoid processing more elements than we need. 5853 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5854 SDValue VL = DAG.getConstant(1, DL, XLenVT); 5855 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5856 5857 // Unless the index is known to be 0, we must slide the vector down to get 5858 // the desired element into index 0. 5859 if (!isNullConstant(Idx)) { 5860 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5861 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 5862 } 5863 5864 // Extract the lower XLEN bits of the correct vector element. 5865 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 5866 5867 // To extract the upper XLEN bits of the vector element, shift the first 5868 // element right by 32 bits and re-extract the lower XLEN bits. 5869 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5870 DAG.getConstant(32, DL, XLenVT), VL); 5871 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 5872 ThirtyTwoV, Mask, VL); 5873 5874 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 5875 5876 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 5877 break; 5878 } 5879 case ISD::INTRINSIC_WO_CHAIN: { 5880 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5881 switch (IntNo) { 5882 default: 5883 llvm_unreachable( 5884 "Don't know how to custom type legalize this intrinsic!"); 5885 case Intrinsic::riscv_orc_b: { 5886 // Lower to the GORCI encoding for orc.b with the operand extended. 5887 SDValue NewOp = 5888 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5889 // If Zbp is enabled, use GORCIW which will sign extend the result. 5890 unsigned Opc = 5891 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 5892 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 5893 DAG.getConstant(7, DL, MVT::i64)); 5894 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5895 return; 5896 } 5897 case Intrinsic::riscv_grev: 5898 case Intrinsic::riscv_gorc: { 5899 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5900 "Unexpected custom legalisation"); 5901 SDValue NewOp1 = 5902 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5903 SDValue NewOp2 = 5904 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5905 unsigned Opc = 5906 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 5907 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5908 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5909 break; 5910 } 5911 case Intrinsic::riscv_shfl: 5912 case Intrinsic::riscv_unshfl: { 5913 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5914 "Unexpected custom legalisation"); 5915 SDValue NewOp1 = 5916 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5917 SDValue NewOp2 = 5918 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5919 unsigned Opc = 5920 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 5921 if (isa<ConstantSDNode>(N->getOperand(2))) { 5922 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 5923 DAG.getConstant(0xf, DL, MVT::i64)); 5924 Opc = 5925 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 5926 } 5927 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5928 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5929 break; 5930 } 5931 case Intrinsic::riscv_bcompress: 5932 case Intrinsic::riscv_bdecompress: { 5933 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5934 "Unexpected custom legalisation"); 5935 SDValue NewOp1 = 5936 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5937 SDValue NewOp2 = 5938 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5939 unsigned Opc = IntNo == Intrinsic::riscv_bcompress 5940 ? RISCVISD::BCOMPRESSW 5941 : RISCVISD::BDECOMPRESSW; 5942 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5943 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5944 break; 5945 } 5946 case Intrinsic::riscv_vmv_x_s: { 5947 EVT VT = N->getValueType(0); 5948 MVT XLenVT = Subtarget.getXLenVT(); 5949 if (VT.bitsLT(XLenVT)) { 5950 // Simple case just extract using vmv.x.s and truncate. 5951 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 5952 Subtarget.getXLenVT(), N->getOperand(1)); 5953 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 5954 return; 5955 } 5956 5957 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 5958 "Unexpected custom legalization"); 5959 5960 // We need to do the move in two steps. 5961 SDValue Vec = N->getOperand(1); 5962 MVT VecVT = Vec.getSimpleValueType(); 5963 5964 // First extract the lower XLEN bits of the element. 5965 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 5966 5967 // To extract the upper XLEN bits of the vector element, shift the first 5968 // element right by 32 bits and re-extract the lower XLEN bits. 5969 SDValue VL = DAG.getConstant(1, DL, XLenVT); 5970 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5971 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5972 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 5973 DAG.getConstant(32, DL, XLenVT), VL); 5974 SDValue LShr32 = 5975 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 5976 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 5977 5978 Results.push_back( 5979 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 5980 break; 5981 } 5982 } 5983 break; 5984 } 5985 case ISD::VECREDUCE_ADD: 5986 case ISD::VECREDUCE_AND: 5987 case ISD::VECREDUCE_OR: 5988 case ISD::VECREDUCE_XOR: 5989 case ISD::VECREDUCE_SMAX: 5990 case ISD::VECREDUCE_UMAX: 5991 case ISD::VECREDUCE_SMIN: 5992 case ISD::VECREDUCE_UMIN: 5993 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 5994 Results.push_back(V); 5995 break; 5996 case ISD::VP_REDUCE_ADD: 5997 case ISD::VP_REDUCE_AND: 5998 case ISD::VP_REDUCE_OR: 5999 case ISD::VP_REDUCE_XOR: 6000 case ISD::VP_REDUCE_SMAX: 6001 case ISD::VP_REDUCE_UMAX: 6002 case ISD::VP_REDUCE_SMIN: 6003 case ISD::VP_REDUCE_UMIN: 6004 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6005 Results.push_back(V); 6006 break; 6007 case ISD::FLT_ROUNDS_: { 6008 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6009 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6010 Results.push_back(Res.getValue(0)); 6011 Results.push_back(Res.getValue(1)); 6012 break; 6013 } 6014 } 6015 } 6016 6017 // A structure to hold one of the bit-manipulation patterns below. Together, a 6018 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6019 // (or (and (shl x, 1), 0xAAAAAAAA), 6020 // (and (srl x, 1), 0x55555555)) 6021 struct RISCVBitmanipPat { 6022 SDValue Op; 6023 unsigned ShAmt; 6024 bool IsSHL; 6025 6026 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6027 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6028 } 6029 }; 6030 6031 // Matches patterns of the form 6032 // (and (shl x, C2), (C1 << C2)) 6033 // (and (srl x, C2), C1) 6034 // (shl (and x, C1), C2) 6035 // (srl (and x, (C1 << C2)), C2) 6036 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6037 // The expected masks for each shift amount are specified in BitmanipMasks where 6038 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6039 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6040 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6041 // XLen is 64. 6042 static Optional<RISCVBitmanipPat> 6043 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6044 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6045 "Unexpected number of masks"); 6046 Optional<uint64_t> Mask; 6047 // Optionally consume a mask around the shift operation. 6048 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6049 Mask = Op.getConstantOperandVal(1); 6050 Op = Op.getOperand(0); 6051 } 6052 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6053 return None; 6054 bool IsSHL = Op.getOpcode() == ISD::SHL; 6055 6056 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6057 return None; 6058 uint64_t ShAmt = Op.getConstantOperandVal(1); 6059 6060 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6061 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6062 return None; 6063 // If we don't have enough masks for 64 bit, then we must be trying to 6064 // match SHFL so we're only allowed to shift 1/4 of the width. 6065 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6066 return None; 6067 6068 SDValue Src = Op.getOperand(0); 6069 6070 // The expected mask is shifted left when the AND is found around SHL 6071 // patterns. 6072 // ((x >> 1) & 0x55555555) 6073 // ((x << 1) & 0xAAAAAAAA) 6074 bool SHLExpMask = IsSHL; 6075 6076 if (!Mask) { 6077 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6078 // the mask is all ones: consume that now. 6079 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6080 Mask = Src.getConstantOperandVal(1); 6081 Src = Src.getOperand(0); 6082 // The expected mask is now in fact shifted left for SRL, so reverse the 6083 // decision. 6084 // ((x & 0xAAAAAAAA) >> 1) 6085 // ((x & 0x55555555) << 1) 6086 SHLExpMask = !SHLExpMask; 6087 } else { 6088 // Use a default shifted mask of all-ones if there's no AND, truncated 6089 // down to the expected width. This simplifies the logic later on. 6090 Mask = maskTrailingOnes<uint64_t>(Width); 6091 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6092 } 6093 } 6094 6095 unsigned MaskIdx = Log2_32(ShAmt); 6096 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6097 6098 if (SHLExpMask) 6099 ExpMask <<= ShAmt; 6100 6101 if (Mask != ExpMask) 6102 return None; 6103 6104 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6105 } 6106 6107 // Matches any of the following bit-manipulation patterns: 6108 // (and (shl x, 1), (0x55555555 << 1)) 6109 // (and (srl x, 1), 0x55555555) 6110 // (shl (and x, 0x55555555), 1) 6111 // (srl (and x, (0x55555555 << 1)), 1) 6112 // where the shift amount and mask may vary thus: 6113 // [1] = 0x55555555 / 0xAAAAAAAA 6114 // [2] = 0x33333333 / 0xCCCCCCCC 6115 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6116 // [8] = 0x00FF00FF / 0xFF00FF00 6117 // [16] = 0x0000FFFF / 0xFFFFFFFF 6118 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6119 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6120 // These are the unshifted masks which we use to match bit-manipulation 6121 // patterns. They may be shifted left in certain circumstances. 6122 static const uint64_t BitmanipMasks[] = { 6123 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6124 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6125 6126 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6127 } 6128 6129 // Match the following pattern as a GREVI(W) operation 6130 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6131 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6132 const RISCVSubtarget &Subtarget) { 6133 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6134 EVT VT = Op.getValueType(); 6135 6136 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6137 auto LHS = matchGREVIPat(Op.getOperand(0)); 6138 auto RHS = matchGREVIPat(Op.getOperand(1)); 6139 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6140 SDLoc DL(Op); 6141 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6142 DAG.getConstant(LHS->ShAmt, DL, VT)); 6143 } 6144 } 6145 return SDValue(); 6146 } 6147 6148 // Matches any the following pattern as a GORCI(W) operation 6149 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6150 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6151 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6152 // Note that with the variant of 3., 6153 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6154 // the inner pattern will first be matched as GREVI and then the outer 6155 // pattern will be matched to GORC via the first rule above. 6156 // 4. (or (rotl/rotr x, bitwidth/2), x) 6157 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6158 const RISCVSubtarget &Subtarget) { 6159 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6160 EVT VT = Op.getValueType(); 6161 6162 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6163 SDLoc DL(Op); 6164 SDValue Op0 = Op.getOperand(0); 6165 SDValue Op1 = Op.getOperand(1); 6166 6167 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6168 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6169 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6170 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6171 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6172 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6173 if ((Reverse.getOpcode() == ISD::ROTL || 6174 Reverse.getOpcode() == ISD::ROTR) && 6175 Reverse.getOperand(0) == X && 6176 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6177 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6178 if (RotAmt == (VT.getSizeInBits() / 2)) 6179 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6180 DAG.getConstant(RotAmt, DL, VT)); 6181 } 6182 return SDValue(); 6183 }; 6184 6185 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6186 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6187 return V; 6188 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6189 return V; 6190 6191 // OR is commutable so canonicalize its OR operand to the left 6192 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6193 std::swap(Op0, Op1); 6194 if (Op0.getOpcode() != ISD::OR) 6195 return SDValue(); 6196 SDValue OrOp0 = Op0.getOperand(0); 6197 SDValue OrOp1 = Op0.getOperand(1); 6198 auto LHS = matchGREVIPat(OrOp0); 6199 // OR is commutable so swap the operands and try again: x might have been 6200 // on the left 6201 if (!LHS) { 6202 std::swap(OrOp0, OrOp1); 6203 LHS = matchGREVIPat(OrOp0); 6204 } 6205 auto RHS = matchGREVIPat(Op1); 6206 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6207 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6208 DAG.getConstant(LHS->ShAmt, DL, VT)); 6209 } 6210 } 6211 return SDValue(); 6212 } 6213 6214 // Matches any of the following bit-manipulation patterns: 6215 // (and (shl x, 1), (0x22222222 << 1)) 6216 // (and (srl x, 1), 0x22222222) 6217 // (shl (and x, 0x22222222), 1) 6218 // (srl (and x, (0x22222222 << 1)), 1) 6219 // where the shift amount and mask may vary thus: 6220 // [1] = 0x22222222 / 0x44444444 6221 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6222 // [4] = 0x00F000F0 / 0x0F000F00 6223 // [8] = 0x0000FF00 / 0x00FF0000 6224 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6225 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6226 // These are the unshifted masks which we use to match bit-manipulation 6227 // patterns. They may be shifted left in certain circumstances. 6228 static const uint64_t BitmanipMasks[] = { 6229 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6230 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6231 6232 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6233 } 6234 6235 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6236 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6237 const RISCVSubtarget &Subtarget) { 6238 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6239 EVT VT = Op.getValueType(); 6240 6241 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6242 return SDValue(); 6243 6244 SDValue Op0 = Op.getOperand(0); 6245 SDValue Op1 = Op.getOperand(1); 6246 6247 // Or is commutable so canonicalize the second OR to the LHS. 6248 if (Op0.getOpcode() != ISD::OR) 6249 std::swap(Op0, Op1); 6250 if (Op0.getOpcode() != ISD::OR) 6251 return SDValue(); 6252 6253 // We found an inner OR, so our operands are the operands of the inner OR 6254 // and the other operand of the outer OR. 6255 SDValue A = Op0.getOperand(0); 6256 SDValue B = Op0.getOperand(1); 6257 SDValue C = Op1; 6258 6259 auto Match1 = matchSHFLPat(A); 6260 auto Match2 = matchSHFLPat(B); 6261 6262 // If neither matched, we failed. 6263 if (!Match1 && !Match2) 6264 return SDValue(); 6265 6266 // We had at least one match. if one failed, try the remaining C operand. 6267 if (!Match1) { 6268 std::swap(A, C); 6269 Match1 = matchSHFLPat(A); 6270 if (!Match1) 6271 return SDValue(); 6272 } else if (!Match2) { 6273 std::swap(B, C); 6274 Match2 = matchSHFLPat(B); 6275 if (!Match2) 6276 return SDValue(); 6277 } 6278 assert(Match1 && Match2); 6279 6280 // Make sure our matches pair up. 6281 if (!Match1->formsPairWith(*Match2)) 6282 return SDValue(); 6283 6284 // All the remains is to make sure C is an AND with the same input, that masks 6285 // out the bits that are being shuffled. 6286 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 6287 C.getOperand(0) != Match1->Op) 6288 return SDValue(); 6289 6290 uint64_t Mask = C.getConstantOperandVal(1); 6291 6292 static const uint64_t BitmanipMasks[] = { 6293 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 6294 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 6295 }; 6296 6297 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6298 unsigned MaskIdx = Log2_32(Match1->ShAmt); 6299 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6300 6301 if (Mask != ExpMask) 6302 return SDValue(); 6303 6304 SDLoc DL(Op); 6305 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 6306 DAG.getConstant(Match1->ShAmt, DL, VT)); 6307 } 6308 6309 // Optimize (add (shl x, c0), (shl y, c1)) -> 6310 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 6311 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 6312 const RISCVSubtarget &Subtarget) { 6313 // Perform this optimization only in the zba extension. 6314 if (!Subtarget.hasStdExtZba()) 6315 return SDValue(); 6316 6317 // Skip for vector types and larger types. 6318 EVT VT = N->getValueType(0); 6319 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6320 return SDValue(); 6321 6322 // The two operand nodes must be SHL and have no other use. 6323 SDValue N0 = N->getOperand(0); 6324 SDValue N1 = N->getOperand(1); 6325 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 6326 !N0->hasOneUse() || !N1->hasOneUse()) 6327 return SDValue(); 6328 6329 // Check c0 and c1. 6330 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6331 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 6332 if (!N0C || !N1C) 6333 return SDValue(); 6334 int64_t C0 = N0C->getSExtValue(); 6335 int64_t C1 = N1C->getSExtValue(); 6336 if (C0 <= 0 || C1 <= 0) 6337 return SDValue(); 6338 6339 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 6340 int64_t Bits = std::min(C0, C1); 6341 int64_t Diff = std::abs(C0 - C1); 6342 if (Diff != 1 && Diff != 2 && Diff != 3) 6343 return SDValue(); 6344 6345 // Build nodes. 6346 SDLoc DL(N); 6347 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 6348 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 6349 SDValue NA0 = 6350 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 6351 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 6352 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 6353 } 6354 6355 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 6356 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 6357 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 6358 // not undo itself, but they are redundant. 6359 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 6360 SDValue Src = N->getOperand(0); 6361 6362 if (Src.getOpcode() != N->getOpcode()) 6363 return SDValue(); 6364 6365 if (!isa<ConstantSDNode>(N->getOperand(1)) || 6366 !isa<ConstantSDNode>(Src.getOperand(1))) 6367 return SDValue(); 6368 6369 unsigned ShAmt1 = N->getConstantOperandVal(1); 6370 unsigned ShAmt2 = Src.getConstantOperandVal(1); 6371 Src = Src.getOperand(0); 6372 6373 unsigned CombinedShAmt; 6374 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 6375 CombinedShAmt = ShAmt1 | ShAmt2; 6376 else 6377 CombinedShAmt = ShAmt1 ^ ShAmt2; 6378 6379 if (CombinedShAmt == 0) 6380 return Src; 6381 6382 SDLoc DL(N); 6383 return DAG.getNode( 6384 N->getOpcode(), DL, N->getValueType(0), Src, 6385 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 6386 } 6387 6388 // Combine a constant select operand into its use: 6389 // 6390 // (and (select cond, -1, c), x) 6391 // -> (select cond, x, (and x, c)) [AllOnes=1] 6392 // (or (select cond, 0, c), x) 6393 // -> (select cond, x, (or x, c)) [AllOnes=0] 6394 // (xor (select cond, 0, c), x) 6395 // -> (select cond, x, (xor x, c)) [AllOnes=0] 6396 // (add (select cond, 0, c), x) 6397 // -> (select cond, x, (add x, c)) [AllOnes=0] 6398 // (sub x, (select cond, 0, c)) 6399 // -> (select cond, x, (sub x, c)) [AllOnes=0] 6400 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 6401 SelectionDAG &DAG, bool AllOnes) { 6402 EVT VT = N->getValueType(0); 6403 6404 // Skip vectors. 6405 if (VT.isVector()) 6406 return SDValue(); 6407 6408 if ((Slct.getOpcode() != ISD::SELECT && 6409 Slct.getOpcode() != RISCVISD::SELECT_CC) || 6410 !Slct.hasOneUse()) 6411 return SDValue(); 6412 6413 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 6414 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 6415 }; 6416 6417 bool SwapSelectOps; 6418 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 6419 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 6420 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 6421 SDValue NonConstantVal; 6422 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 6423 SwapSelectOps = false; 6424 NonConstantVal = FalseVal; 6425 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 6426 SwapSelectOps = true; 6427 NonConstantVal = TrueVal; 6428 } else 6429 return SDValue(); 6430 6431 // Slct is now know to be the desired identity constant when CC is true. 6432 TrueVal = OtherOp; 6433 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 6434 // Unless SwapSelectOps says the condition should be false. 6435 if (SwapSelectOps) 6436 std::swap(TrueVal, FalseVal); 6437 6438 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 6439 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 6440 {Slct.getOperand(0), Slct.getOperand(1), 6441 Slct.getOperand(2), TrueVal, FalseVal}); 6442 6443 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 6444 {Slct.getOperand(0), TrueVal, FalseVal}); 6445 } 6446 6447 // Attempt combineSelectAndUse on each operand of a commutative operator N. 6448 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 6449 bool AllOnes) { 6450 SDValue N0 = N->getOperand(0); 6451 SDValue N1 = N->getOperand(1); 6452 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 6453 return Result; 6454 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 6455 return Result; 6456 return SDValue(); 6457 } 6458 6459 // Transform (add (mul x, c0), c1) -> 6460 // (add (mul (add x, c1/c0), c0), c1%c0). 6461 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 6462 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 6463 // to an infinite loop in DAGCombine if transformed. 6464 // Or transform (add (mul x, c0), c1) -> 6465 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 6466 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 6467 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 6468 // lead to an infinite loop in DAGCombine if transformed. 6469 // Or transform (add (mul x, c0), c1) -> 6470 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 6471 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 6472 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 6473 // lead to an infinite loop in DAGCombine if transformed. 6474 // Or transform (add (mul x, c0), c1) -> 6475 // (mul (add x, c1/c0), c0). 6476 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 6477 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 6478 const RISCVSubtarget &Subtarget) { 6479 // Skip for vector types and larger types. 6480 EVT VT = N->getValueType(0); 6481 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6482 return SDValue(); 6483 // The first operand node must be a MUL and has no other use. 6484 SDValue N0 = N->getOperand(0); 6485 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 6486 return SDValue(); 6487 // Check if c0 and c1 match above conditions. 6488 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6489 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6490 if (!N0C || !N1C) 6491 return SDValue(); 6492 int64_t C0 = N0C->getSExtValue(); 6493 int64_t C1 = N1C->getSExtValue(); 6494 int64_t CA, CB; 6495 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 6496 return SDValue(); 6497 // Search for proper CA (non-zero) and CB that both are simm12. 6498 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 6499 !isInt<12>(C0 * (C1 / C0))) { 6500 CA = C1 / C0; 6501 CB = C1 % C0; 6502 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 6503 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 6504 CA = C1 / C0 + 1; 6505 CB = C1 % C0 - C0; 6506 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 6507 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 6508 CA = C1 / C0 - 1; 6509 CB = C1 % C0 + C0; 6510 } else 6511 return SDValue(); 6512 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 6513 SDLoc DL(N); 6514 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 6515 DAG.getConstant(CA, DL, VT)); 6516 SDValue New1 = 6517 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 6518 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 6519 } 6520 6521 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 6522 const RISCVSubtarget &Subtarget) { 6523 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 6524 return V; 6525 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 6526 return V; 6527 // fold (add (select lhs, rhs, cc, 0, y), x) -> 6528 // (select lhs, rhs, cc, x, (add x, y)) 6529 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6530 } 6531 6532 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 6533 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 6534 // (select lhs, rhs, cc, x, (sub x, y)) 6535 SDValue N0 = N->getOperand(0); 6536 SDValue N1 = N->getOperand(1); 6537 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 6538 } 6539 6540 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 6541 // fold (and (select lhs, rhs, cc, -1, y), x) -> 6542 // (select lhs, rhs, cc, x, (and x, y)) 6543 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 6544 } 6545 6546 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 6547 const RISCVSubtarget &Subtarget) { 6548 if (Subtarget.hasStdExtZbp()) { 6549 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 6550 return GREV; 6551 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 6552 return GORC; 6553 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 6554 return SHFL; 6555 } 6556 6557 // fold (or (select cond, 0, y), x) -> 6558 // (select cond, x, (or x, y)) 6559 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6560 } 6561 6562 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 6563 // fold (xor (select cond, 0, y), x) -> 6564 // (select cond, x, (xor x, y)) 6565 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6566 } 6567 6568 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 6569 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 6570 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 6571 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 6572 // ADDW/SUBW/MULW. 6573 static SDValue performANY_EXTENDCombine(SDNode *N, 6574 TargetLowering::DAGCombinerInfo &DCI, 6575 const RISCVSubtarget &Subtarget) { 6576 if (!Subtarget.is64Bit()) 6577 return SDValue(); 6578 6579 SelectionDAG &DAG = DCI.DAG; 6580 6581 SDValue Src = N->getOperand(0); 6582 EVT VT = N->getValueType(0); 6583 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 6584 return SDValue(); 6585 6586 // The opcode must be one that can implicitly sign_extend. 6587 // FIXME: Additional opcodes. 6588 switch (Src.getOpcode()) { 6589 default: 6590 return SDValue(); 6591 case ISD::MUL: 6592 if (!Subtarget.hasStdExtM()) 6593 return SDValue(); 6594 LLVM_FALLTHROUGH; 6595 case ISD::ADD: 6596 case ISD::SUB: 6597 break; 6598 } 6599 6600 // Only handle cases where the result is used by a CopyToReg. That likely 6601 // means the value is a liveout of the basic block. This helps prevent 6602 // infinite combine loops like PR51206. 6603 if (none_of(N->uses(), 6604 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 6605 return SDValue(); 6606 6607 SmallVector<SDNode *, 4> SetCCs; 6608 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 6609 UE = Src.getNode()->use_end(); 6610 UI != UE; ++UI) { 6611 SDNode *User = *UI; 6612 if (User == N) 6613 continue; 6614 if (UI.getUse().getResNo() != Src.getResNo()) 6615 continue; 6616 // All i32 setccs are legalized by sign extending operands. 6617 if (User->getOpcode() == ISD::SETCC) { 6618 SetCCs.push_back(User); 6619 continue; 6620 } 6621 // We don't know if we can extend this user. 6622 break; 6623 } 6624 6625 // If we don't have any SetCCs, this isn't worthwhile. 6626 if (SetCCs.empty()) 6627 return SDValue(); 6628 6629 SDLoc DL(N); 6630 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 6631 DCI.CombineTo(N, SExt); 6632 6633 // Promote all the setccs. 6634 for (SDNode *SetCC : SetCCs) { 6635 SmallVector<SDValue, 4> Ops; 6636 6637 for (unsigned j = 0; j != 2; ++j) { 6638 SDValue SOp = SetCC->getOperand(j); 6639 if (SOp == Src) 6640 Ops.push_back(SExt); 6641 else 6642 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 6643 } 6644 6645 Ops.push_back(SetCC->getOperand(2)); 6646 DCI.CombineTo(SetCC, 6647 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6648 } 6649 return SDValue(N, 0); 6650 } 6651 6652 // Try to form VWMUL or VWMULU. 6653 // FIXME: Support VWMULSU. 6654 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1, 6655 SelectionDAG &DAG) { 6656 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 6657 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 6658 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 6659 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 6660 return SDValue(); 6661 6662 SDValue Mask = N->getOperand(2); 6663 SDValue VL = N->getOperand(3); 6664 6665 // Make sure the mask and VL match. 6666 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 6667 return SDValue(); 6668 6669 MVT VT = N->getSimpleValueType(0); 6670 6671 // Determine the narrow size for a widening multiply. 6672 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 6673 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 6674 VT.getVectorElementCount()); 6675 6676 SDLoc DL(N); 6677 6678 // See if the other operand is the same opcode. 6679 if (Op0.getOpcode() == Op1.getOpcode()) { 6680 if (!Op1.hasOneUse()) 6681 return SDValue(); 6682 6683 // Make sure the mask and VL match. 6684 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 6685 return SDValue(); 6686 6687 Op1 = Op1.getOperand(0); 6688 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 6689 // The operand is a splat of a scalar. 6690 6691 // The VL must be the same. 6692 if (Op1.getOperand(1) != VL) 6693 return SDValue(); 6694 6695 // Get the scalar value. 6696 Op1 = Op1.getOperand(0); 6697 6698 // See if have enough sign bits or zero bits in the scalar to use a 6699 // widening multiply by splatting to smaller element size. 6700 unsigned EltBits = VT.getScalarSizeInBits(); 6701 unsigned ScalarBits = Op1.getValueSizeInBits(); 6702 // Make sure we're getting all element bits from the scalar register. 6703 // FIXME: Support implicit sign extension of vmv.v.x? 6704 if (ScalarBits < EltBits) 6705 return SDValue(); 6706 6707 if (IsSignExt) { 6708 if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize)) 6709 return SDValue(); 6710 } else { 6711 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 6712 if (!DAG.MaskedValueIsZero(Op1, Mask)) 6713 return SDValue(); 6714 } 6715 6716 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 6717 } else 6718 return SDValue(); 6719 6720 Op0 = Op0.getOperand(0); 6721 6722 // Re-introduce narrower extends if needed. 6723 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 6724 if (Op0.getValueType() != NarrowVT) 6725 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 6726 if (Op1.getValueType() != NarrowVT) 6727 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 6728 6729 unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 6730 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 6731 } 6732 6733 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 6734 DAGCombinerInfo &DCI) const { 6735 SelectionDAG &DAG = DCI.DAG; 6736 6737 // Helper to call SimplifyDemandedBits on an operand of N where only some low 6738 // bits are demanded. N will be added to the Worklist if it was not deleted. 6739 // Caller should return SDValue(N, 0) if this returns true. 6740 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 6741 SDValue Op = N->getOperand(OpNo); 6742 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 6743 if (!SimplifyDemandedBits(Op, Mask, DCI)) 6744 return false; 6745 6746 if (N->getOpcode() != ISD::DELETED_NODE) 6747 DCI.AddToWorklist(N); 6748 return true; 6749 }; 6750 6751 switch (N->getOpcode()) { 6752 default: 6753 break; 6754 case RISCVISD::SplitF64: { 6755 SDValue Op0 = N->getOperand(0); 6756 // If the input to SplitF64 is just BuildPairF64 then the operation is 6757 // redundant. Instead, use BuildPairF64's operands directly. 6758 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 6759 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 6760 6761 SDLoc DL(N); 6762 6763 // It's cheaper to materialise two 32-bit integers than to load a double 6764 // from the constant pool and transfer it to integer registers through the 6765 // stack. 6766 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 6767 APInt V = C->getValueAPF().bitcastToAPInt(); 6768 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 6769 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 6770 return DCI.CombineTo(N, Lo, Hi); 6771 } 6772 6773 // This is a target-specific version of a DAGCombine performed in 6774 // DAGCombiner::visitBITCAST. It performs the equivalent of: 6775 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6776 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6777 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 6778 !Op0.getNode()->hasOneUse()) 6779 break; 6780 SDValue NewSplitF64 = 6781 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 6782 Op0.getOperand(0)); 6783 SDValue Lo = NewSplitF64.getValue(0); 6784 SDValue Hi = NewSplitF64.getValue(1); 6785 APInt SignBit = APInt::getSignMask(32); 6786 if (Op0.getOpcode() == ISD::FNEG) { 6787 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 6788 DAG.getConstant(SignBit, DL, MVT::i32)); 6789 return DCI.CombineTo(N, Lo, NewHi); 6790 } 6791 assert(Op0.getOpcode() == ISD::FABS); 6792 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 6793 DAG.getConstant(~SignBit, DL, MVT::i32)); 6794 return DCI.CombineTo(N, Lo, NewHi); 6795 } 6796 case RISCVISD::SLLW: 6797 case RISCVISD::SRAW: 6798 case RISCVISD::SRLW: 6799 case RISCVISD::ROLW: 6800 case RISCVISD::RORW: { 6801 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 6802 if (SimplifyDemandedLowBitsHelper(0, 32) || 6803 SimplifyDemandedLowBitsHelper(1, 5)) 6804 return SDValue(N, 0); 6805 break; 6806 } 6807 case RISCVISD::CLZW: 6808 case RISCVISD::CTZW: { 6809 // Only the lower 32 bits of the first operand are read 6810 if (SimplifyDemandedLowBitsHelper(0, 32)) 6811 return SDValue(N, 0); 6812 break; 6813 } 6814 case RISCVISD::FSL: 6815 case RISCVISD::FSR: { 6816 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 6817 unsigned BitWidth = N->getOperand(2).getValueSizeInBits(); 6818 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6819 if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1)) 6820 return SDValue(N, 0); 6821 break; 6822 } 6823 case RISCVISD::FSLW: 6824 case RISCVISD::FSRW: { 6825 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 6826 // read. 6827 if (SimplifyDemandedLowBitsHelper(0, 32) || 6828 SimplifyDemandedLowBitsHelper(1, 32) || 6829 SimplifyDemandedLowBitsHelper(2, 6)) 6830 return SDValue(N, 0); 6831 break; 6832 } 6833 case RISCVISD::GREV: 6834 case RISCVISD::GORC: { 6835 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 6836 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 6837 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6838 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 6839 return SDValue(N, 0); 6840 6841 return combineGREVI_GORCI(N, DCI.DAG); 6842 } 6843 case RISCVISD::GREVW: 6844 case RISCVISD::GORCW: { 6845 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 6846 if (SimplifyDemandedLowBitsHelper(0, 32) || 6847 SimplifyDemandedLowBitsHelper(1, 5)) 6848 return SDValue(N, 0); 6849 6850 return combineGREVI_GORCI(N, DCI.DAG); 6851 } 6852 case RISCVISD::SHFL: 6853 case RISCVISD::UNSHFL: { 6854 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 6855 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 6856 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6857 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 6858 return SDValue(N, 0); 6859 6860 break; 6861 } 6862 case RISCVISD::SHFLW: 6863 case RISCVISD::UNSHFLW: { 6864 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 6865 SDValue LHS = N->getOperand(0); 6866 SDValue RHS = N->getOperand(1); 6867 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 6868 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4); 6869 if (SimplifyDemandedLowBitsHelper(0, 32) || 6870 SimplifyDemandedLowBitsHelper(1, 4)) 6871 return SDValue(N, 0); 6872 6873 break; 6874 } 6875 case RISCVISD::BCOMPRESSW: 6876 case RISCVISD::BDECOMPRESSW: { 6877 // Only the lower 32 bits of LHS and RHS are read. 6878 if (SimplifyDemandedLowBitsHelper(0, 32) || 6879 SimplifyDemandedLowBitsHelper(1, 32)) 6880 return SDValue(N, 0); 6881 6882 break; 6883 } 6884 case RISCVISD::FMV_X_ANYEXTH: 6885 case RISCVISD::FMV_X_ANYEXTW_RV64: { 6886 SDLoc DL(N); 6887 SDValue Op0 = N->getOperand(0); 6888 MVT VT = N->getSimpleValueType(0); 6889 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 6890 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 6891 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 6892 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 6893 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 6894 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 6895 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 6896 assert(Op0.getOperand(0).getValueType() == VT && 6897 "Unexpected value type!"); 6898 return Op0.getOperand(0); 6899 } 6900 6901 // This is a target-specific version of a DAGCombine performed in 6902 // DAGCombiner::visitBITCAST. It performs the equivalent of: 6903 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6904 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6905 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 6906 !Op0.getNode()->hasOneUse()) 6907 break; 6908 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 6909 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 6910 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 6911 if (Op0.getOpcode() == ISD::FNEG) 6912 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 6913 DAG.getConstant(SignBit, DL, VT)); 6914 6915 assert(Op0.getOpcode() == ISD::FABS); 6916 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 6917 DAG.getConstant(~SignBit, DL, VT)); 6918 } 6919 case ISD::ADD: 6920 return performADDCombine(N, DAG, Subtarget); 6921 case ISD::SUB: 6922 return performSUBCombine(N, DAG); 6923 case ISD::AND: 6924 return performANDCombine(N, DAG); 6925 case ISD::OR: 6926 return performORCombine(N, DAG, Subtarget); 6927 case ISD::XOR: 6928 return performXORCombine(N, DAG); 6929 case ISD::ANY_EXTEND: 6930 return performANY_EXTENDCombine(N, DCI, Subtarget); 6931 case ISD::ZERO_EXTEND: 6932 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 6933 // type legalization. This is safe because fp_to_uint produces poison if 6934 // it overflows. 6935 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() && 6936 N->getOperand(0).getOpcode() == ISD::FP_TO_UINT && 6937 isTypeLegal(N->getOperand(0).getOperand(0).getValueType())) 6938 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 6939 N->getOperand(0).getOperand(0)); 6940 return SDValue(); 6941 case RISCVISD::SELECT_CC: { 6942 // Transform 6943 SDValue LHS = N->getOperand(0); 6944 SDValue RHS = N->getOperand(1); 6945 SDValue TrueV = N->getOperand(3); 6946 SDValue FalseV = N->getOperand(4); 6947 6948 // If the True and False values are the same, we don't need a select_cc. 6949 if (TrueV == FalseV) 6950 return TrueV; 6951 6952 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 6953 if (!ISD::isIntEqualitySetCC(CCVal)) 6954 break; 6955 6956 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 6957 // (select_cc X, Y, lt, trueV, falseV) 6958 // Sometimes the setcc is introduced after select_cc has been formed. 6959 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 6960 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 6961 // If we're looking for eq 0 instead of ne 0, we need to invert the 6962 // condition. 6963 bool Invert = CCVal == ISD::SETEQ; 6964 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 6965 if (Invert) 6966 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6967 6968 SDLoc DL(N); 6969 RHS = LHS.getOperand(1); 6970 LHS = LHS.getOperand(0); 6971 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 6972 6973 SDValue TargetCC = DAG.getCondCode(CCVal); 6974 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 6975 {LHS, RHS, TargetCC, TrueV, FalseV}); 6976 } 6977 6978 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 6979 // (select_cc X, Y, eq/ne, trueV, falseV) 6980 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 6981 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 6982 {LHS.getOperand(0), LHS.getOperand(1), 6983 N->getOperand(2), TrueV, FalseV}); 6984 // (select_cc X, 1, setne, trueV, falseV) -> 6985 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 6986 // This can occur when legalizing some floating point comparisons. 6987 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 6988 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 6989 SDLoc DL(N); 6990 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6991 SDValue TargetCC = DAG.getCondCode(CCVal); 6992 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 6993 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 6994 {LHS, RHS, TargetCC, TrueV, FalseV}); 6995 } 6996 6997 break; 6998 } 6999 case RISCVISD::BR_CC: { 7000 SDValue LHS = N->getOperand(1); 7001 SDValue RHS = N->getOperand(2); 7002 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 7003 if (!ISD::isIntEqualitySetCC(CCVal)) 7004 break; 7005 7006 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 7007 // (br_cc X, Y, lt, dest) 7008 // Sometimes the setcc is introduced after br_cc has been formed. 7009 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7010 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7011 // If we're looking for eq 0 instead of ne 0, we need to invert the 7012 // condition. 7013 bool Invert = CCVal == ISD::SETEQ; 7014 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7015 if (Invert) 7016 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7017 7018 SDLoc DL(N); 7019 RHS = LHS.getOperand(1); 7020 LHS = LHS.getOperand(0); 7021 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7022 7023 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7024 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 7025 N->getOperand(4)); 7026 } 7027 7028 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 7029 // (br_cc X, Y, eq/ne, trueV, falseV) 7030 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7031 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 7032 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 7033 N->getOperand(3), N->getOperand(4)); 7034 7035 // (br_cc X, 1, setne, br_cc) -> 7036 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 7037 // This can occur when legalizing some floating point comparisons. 7038 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7039 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7040 SDLoc DL(N); 7041 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7042 SDValue TargetCC = DAG.getCondCode(CCVal); 7043 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7044 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7045 N->getOperand(0), LHS, RHS, TargetCC, 7046 N->getOperand(4)); 7047 } 7048 break; 7049 } 7050 case ISD::FCOPYSIGN: { 7051 EVT VT = N->getValueType(0); 7052 if (!VT.isVector()) 7053 break; 7054 // There is a form of VFSGNJ which injects the negated sign of its second 7055 // operand. Try and bubble any FNEG up after the extend/round to produce 7056 // this optimized pattern. Avoid modifying cases where FP_ROUND and 7057 // TRUNC=1. 7058 SDValue In2 = N->getOperand(1); 7059 // Avoid cases where the extend/round has multiple uses, as duplicating 7060 // those is typically more expensive than removing a fneg. 7061 if (!In2.hasOneUse()) 7062 break; 7063 if (In2.getOpcode() != ISD::FP_EXTEND && 7064 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 7065 break; 7066 In2 = In2.getOperand(0); 7067 if (In2.getOpcode() != ISD::FNEG) 7068 break; 7069 SDLoc DL(N); 7070 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 7071 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 7072 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 7073 } 7074 case ISD::MGATHER: 7075 case ISD::MSCATTER: 7076 case ISD::VP_GATHER: 7077 case ISD::VP_SCATTER: { 7078 if (!DCI.isBeforeLegalize()) 7079 break; 7080 SDValue Index, ScaleOp; 7081 bool IsIndexScaled = false; 7082 bool IsIndexSigned = false; 7083 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 7084 Index = VPGSN->getIndex(); 7085 ScaleOp = VPGSN->getScale(); 7086 IsIndexScaled = VPGSN->isIndexScaled(); 7087 IsIndexSigned = VPGSN->isIndexSigned(); 7088 } else { 7089 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 7090 Index = MGSN->getIndex(); 7091 ScaleOp = MGSN->getScale(); 7092 IsIndexScaled = MGSN->isIndexScaled(); 7093 IsIndexSigned = MGSN->isIndexSigned(); 7094 } 7095 EVT IndexVT = Index.getValueType(); 7096 MVT XLenVT = Subtarget.getXLenVT(); 7097 // RISCV indexed loads only support the "unsigned unscaled" addressing 7098 // mode, so anything else must be manually legalized. 7099 bool NeedsIdxLegalization = 7100 IsIndexScaled || 7101 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 7102 if (!NeedsIdxLegalization) 7103 break; 7104 7105 SDLoc DL(N); 7106 7107 // Any index legalization should first promote to XLenVT, so we don't lose 7108 // bits when scaling. This may create an illegal index type so we let 7109 // LLVM's legalization take care of the splitting. 7110 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 7111 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 7112 IndexVT = IndexVT.changeVectorElementType(XLenVT); 7113 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 7114 DL, IndexVT, Index); 7115 } 7116 7117 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 7118 if (IsIndexScaled && Scale != 1) { 7119 // Manually scale the indices by the element size. 7120 // TODO: Sanitize the scale operand here? 7121 // TODO: For VP nodes, should we use VP_SHL here? 7122 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 7123 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 7124 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 7125 } 7126 7127 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 7128 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 7129 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 7130 {VPGN->getChain(), VPGN->getBasePtr(), Index, 7131 VPGN->getScale(), VPGN->getMask(), 7132 VPGN->getVectorLength()}, 7133 VPGN->getMemOperand(), NewIndexTy); 7134 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 7135 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 7136 {VPSN->getChain(), VPSN->getValue(), 7137 VPSN->getBasePtr(), Index, VPSN->getScale(), 7138 VPSN->getMask(), VPSN->getVectorLength()}, 7139 VPSN->getMemOperand(), NewIndexTy); 7140 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 7141 return DAG.getMaskedGather( 7142 N->getVTList(), MGN->getMemoryVT(), DL, 7143 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 7144 MGN->getBasePtr(), Index, MGN->getScale()}, 7145 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 7146 const auto *MSN = cast<MaskedScatterSDNode>(N); 7147 return DAG.getMaskedScatter( 7148 N->getVTList(), MSN->getMemoryVT(), DL, 7149 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 7150 Index, MSN->getScale()}, 7151 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 7152 } 7153 case RISCVISD::SRA_VL: 7154 case RISCVISD::SRL_VL: 7155 case RISCVISD::SHL_VL: { 7156 SDValue ShAmt = N->getOperand(1); 7157 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7158 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7159 SDLoc DL(N); 7160 SDValue VL = N->getOperand(3); 7161 EVT VT = N->getValueType(0); 7162 ShAmt = 7163 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 7164 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 7165 N->getOperand(2), N->getOperand(3)); 7166 } 7167 break; 7168 } 7169 case ISD::SRA: 7170 case ISD::SRL: 7171 case ISD::SHL: { 7172 SDValue ShAmt = N->getOperand(1); 7173 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7174 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7175 SDLoc DL(N); 7176 EVT VT = N->getValueType(0); 7177 ShAmt = 7178 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 7179 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 7180 } 7181 break; 7182 } 7183 case RISCVISD::MUL_VL: { 7184 SDValue Op0 = N->getOperand(0); 7185 SDValue Op1 = N->getOperand(1); 7186 if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG)) 7187 return V; 7188 if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG)) 7189 return V; 7190 return SDValue(); 7191 } 7192 case ISD::STORE: { 7193 auto *Store = cast<StoreSDNode>(N); 7194 SDValue Val = Store->getValue(); 7195 // Combine store of vmv.x.s to vse with VL of 1. 7196 // FIXME: Support FP. 7197 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 7198 SDValue Src = Val.getOperand(0); 7199 EVT VecVT = Src.getValueType(); 7200 EVT MemVT = Store->getMemoryVT(); 7201 // The memory VT and the element type must match. 7202 if (VecVT.getVectorElementType() == MemVT) { 7203 SDLoc DL(N); 7204 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7205 return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(), 7206 DAG.getConstant(1, DL, MaskVT), 7207 DAG.getConstant(1, DL, Subtarget.getXLenVT()), 7208 Store->getPointerInfo(), 7209 Store->getOriginalAlign(), 7210 Store->getMemOperand()->getFlags()); 7211 } 7212 } 7213 7214 break; 7215 } 7216 } 7217 7218 return SDValue(); 7219 } 7220 7221 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 7222 const SDNode *N, CombineLevel Level) const { 7223 // The following folds are only desirable if `(OP _, c1 << c2)` can be 7224 // materialised in fewer instructions than `(OP _, c1)`: 7225 // 7226 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 7227 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 7228 SDValue N0 = N->getOperand(0); 7229 EVT Ty = N0.getValueType(); 7230 if (Ty.isScalarInteger() && 7231 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 7232 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7233 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7234 if (C1 && C2) { 7235 const APInt &C1Int = C1->getAPIntValue(); 7236 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 7237 7238 // We can materialise `c1 << c2` into an add immediate, so it's "free", 7239 // and the combine should happen, to potentially allow further combines 7240 // later. 7241 if (ShiftedC1Int.getMinSignedBits() <= 64 && 7242 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 7243 return true; 7244 7245 // We can materialise `c1` in an add immediate, so it's "free", and the 7246 // combine should be prevented. 7247 if (C1Int.getMinSignedBits() <= 64 && 7248 isLegalAddImmediate(C1Int.getSExtValue())) 7249 return false; 7250 7251 // Neither constant will fit into an immediate, so find materialisation 7252 // costs. 7253 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 7254 Subtarget.getFeatureBits(), 7255 /*CompressionCost*/true); 7256 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 7257 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 7258 /*CompressionCost*/true); 7259 7260 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 7261 // combine should be prevented. 7262 if (C1Cost < ShiftedC1Cost) 7263 return false; 7264 } 7265 } 7266 return true; 7267 } 7268 7269 bool RISCVTargetLowering::targetShrinkDemandedConstant( 7270 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 7271 TargetLoweringOpt &TLO) const { 7272 // Delay this optimization as late as possible. 7273 if (!TLO.LegalOps) 7274 return false; 7275 7276 EVT VT = Op.getValueType(); 7277 if (VT.isVector()) 7278 return false; 7279 7280 // Only handle AND for now. 7281 if (Op.getOpcode() != ISD::AND) 7282 return false; 7283 7284 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7285 if (!C) 7286 return false; 7287 7288 const APInt &Mask = C->getAPIntValue(); 7289 7290 // Clear all non-demanded bits initially. 7291 APInt ShrunkMask = Mask & DemandedBits; 7292 7293 // Try to make a smaller immediate by setting undemanded bits. 7294 7295 APInt ExpandedMask = Mask | ~DemandedBits; 7296 7297 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 7298 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 7299 }; 7300 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 7301 if (NewMask == Mask) 7302 return true; 7303 SDLoc DL(Op); 7304 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 7305 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 7306 return TLO.CombineTo(Op, NewOp); 7307 }; 7308 7309 // If the shrunk mask fits in sign extended 12 bits, let the target 7310 // independent code apply it. 7311 if (ShrunkMask.isSignedIntN(12)) 7312 return false; 7313 7314 // Preserve (and X, 0xffff) when zext.h is supported. 7315 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 7316 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 7317 if (IsLegalMask(NewMask)) 7318 return UseMask(NewMask); 7319 } 7320 7321 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 7322 if (VT == MVT::i64) { 7323 APInt NewMask = APInt(64, 0xffffffff); 7324 if (IsLegalMask(NewMask)) 7325 return UseMask(NewMask); 7326 } 7327 7328 // For the remaining optimizations, we need to be able to make a negative 7329 // number through a combination of mask and undemanded bits. 7330 if (!ExpandedMask.isNegative()) 7331 return false; 7332 7333 // What is the fewest number of bits we need to represent the negative number. 7334 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 7335 7336 // Try to make a 12 bit negative immediate. If that fails try to make a 32 7337 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 7338 APInt NewMask = ShrunkMask; 7339 if (MinSignedBits <= 12) 7340 NewMask.setBitsFrom(11); 7341 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 7342 NewMask.setBitsFrom(31); 7343 else 7344 return false; 7345 7346 // Sanity check that our new mask is a subset of the demanded mask. 7347 assert(IsLegalMask(NewMask)); 7348 return UseMask(NewMask); 7349 } 7350 7351 static void computeGREV(APInt &Src, unsigned ShAmt) { 7352 ShAmt &= Src.getBitWidth() - 1; 7353 uint64_t x = Src.getZExtValue(); 7354 if (ShAmt & 1) 7355 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 7356 if (ShAmt & 2) 7357 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 7358 if (ShAmt & 4) 7359 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 7360 if (ShAmt & 8) 7361 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 7362 if (ShAmt & 16) 7363 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 7364 if (ShAmt & 32) 7365 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 7366 Src = x; 7367 } 7368 7369 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 7370 KnownBits &Known, 7371 const APInt &DemandedElts, 7372 const SelectionDAG &DAG, 7373 unsigned Depth) const { 7374 unsigned BitWidth = Known.getBitWidth(); 7375 unsigned Opc = Op.getOpcode(); 7376 assert((Opc >= ISD::BUILTIN_OP_END || 7377 Opc == ISD::INTRINSIC_WO_CHAIN || 7378 Opc == ISD::INTRINSIC_W_CHAIN || 7379 Opc == ISD::INTRINSIC_VOID) && 7380 "Should use MaskedValueIsZero if you don't know whether Op" 7381 " is a target node!"); 7382 7383 Known.resetAll(); 7384 switch (Opc) { 7385 default: break; 7386 case RISCVISD::SELECT_CC: { 7387 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 7388 // If we don't know any bits, early out. 7389 if (Known.isUnknown()) 7390 break; 7391 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 7392 7393 // Only known if known in both the LHS and RHS. 7394 Known = KnownBits::commonBits(Known, Known2); 7395 break; 7396 } 7397 case RISCVISD::REMUW: { 7398 KnownBits Known2; 7399 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7400 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7401 // We only care about the lower 32 bits. 7402 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 7403 // Restore the original width by sign extending. 7404 Known = Known.sext(BitWidth); 7405 break; 7406 } 7407 case RISCVISD::DIVUW: { 7408 KnownBits Known2; 7409 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7410 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7411 // We only care about the lower 32 bits. 7412 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 7413 // Restore the original width by sign extending. 7414 Known = Known.sext(BitWidth); 7415 break; 7416 } 7417 case RISCVISD::CTZW: { 7418 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7419 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 7420 unsigned LowBits = Log2_32(PossibleTZ) + 1; 7421 Known.Zero.setBitsFrom(LowBits); 7422 break; 7423 } 7424 case RISCVISD::CLZW: { 7425 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7426 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 7427 unsigned LowBits = Log2_32(PossibleLZ) + 1; 7428 Known.Zero.setBitsFrom(LowBits); 7429 break; 7430 } 7431 case RISCVISD::GREV: 7432 case RISCVISD::GREVW: { 7433 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7434 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7435 if (Opc == RISCVISD::GREVW) 7436 Known = Known.trunc(32); 7437 unsigned ShAmt = C->getZExtValue(); 7438 computeGREV(Known.Zero, ShAmt); 7439 computeGREV(Known.One, ShAmt); 7440 if (Opc == RISCVISD::GREVW) 7441 Known = Known.sext(BitWidth); 7442 } 7443 break; 7444 } 7445 case RISCVISD::READ_VLENB: 7446 // We assume VLENB is at least 16 bytes. 7447 Known.Zero.setLowBits(4); 7448 // We assume VLENB is no more than 65536 / 8 bytes. 7449 Known.Zero.setBitsFrom(14); 7450 break; 7451 case ISD::INTRINSIC_W_CHAIN: { 7452 unsigned IntNo = Op.getConstantOperandVal(1); 7453 switch (IntNo) { 7454 default: 7455 // We can't do anything for most intrinsics. 7456 break; 7457 case Intrinsic::riscv_vsetvli: 7458 case Intrinsic::riscv_vsetvlimax: 7459 // Assume that VL output is positive and would fit in an int32_t. 7460 // TODO: VLEN might be capped at 16 bits in a future V spec update. 7461 if (BitWidth >= 32) 7462 Known.Zero.setBitsFrom(31); 7463 break; 7464 } 7465 break; 7466 } 7467 } 7468 } 7469 7470 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 7471 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 7472 unsigned Depth) const { 7473 switch (Op.getOpcode()) { 7474 default: 7475 break; 7476 case RISCVISD::SELECT_CC: { 7477 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 7478 if (Tmp == 1) return 1; // Early out. 7479 unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 7480 return std::min(Tmp, Tmp2); 7481 } 7482 case RISCVISD::SLLW: 7483 case RISCVISD::SRAW: 7484 case RISCVISD::SRLW: 7485 case RISCVISD::DIVW: 7486 case RISCVISD::DIVUW: 7487 case RISCVISD::REMUW: 7488 case RISCVISD::ROLW: 7489 case RISCVISD::RORW: 7490 case RISCVISD::GREVW: 7491 case RISCVISD::GORCW: 7492 case RISCVISD::FSLW: 7493 case RISCVISD::FSRW: 7494 case RISCVISD::SHFLW: 7495 case RISCVISD::UNSHFLW: 7496 case RISCVISD::BCOMPRESSW: 7497 case RISCVISD::BDECOMPRESSW: 7498 case RISCVISD::FCVT_W_RTZ_RV64: 7499 case RISCVISD::FCVT_WU_RTZ_RV64: 7500 // TODO: As the result is sign-extended, this is conservatively correct. A 7501 // more precise answer could be calculated for SRAW depending on known 7502 // bits in the shift amount. 7503 return 33; 7504 case RISCVISD::SHFL: 7505 case RISCVISD::UNSHFL: { 7506 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 7507 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 7508 // will stay within the upper 32 bits. If there were more than 32 sign bits 7509 // before there will be at least 33 sign bits after. 7510 if (Op.getValueType() == MVT::i64 && 7511 isa<ConstantSDNode>(Op.getOperand(1)) && 7512 (Op.getConstantOperandVal(1) & 0x10) == 0) { 7513 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 7514 if (Tmp > 32) 7515 return 33; 7516 } 7517 break; 7518 } 7519 case RISCVISD::VMV_X_S: 7520 // The number of sign bits of the scalar result is computed by obtaining the 7521 // element type of the input vector operand, subtracting its width from the 7522 // XLEN, and then adding one (sign bit within the element type). If the 7523 // element type is wider than XLen, the least-significant XLEN bits are 7524 // taken. 7525 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 7526 return 1; 7527 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 7528 } 7529 7530 return 1; 7531 } 7532 7533 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 7534 MachineBasicBlock *BB) { 7535 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 7536 7537 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 7538 // Should the count have wrapped while it was being read, we need to try 7539 // again. 7540 // ... 7541 // read: 7542 // rdcycleh x3 # load high word of cycle 7543 // rdcycle x2 # load low word of cycle 7544 // rdcycleh x4 # load high word of cycle 7545 // bne x3, x4, read # check if high word reads match, otherwise try again 7546 // ... 7547 7548 MachineFunction &MF = *BB->getParent(); 7549 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7550 MachineFunction::iterator It = ++BB->getIterator(); 7551 7552 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7553 MF.insert(It, LoopMBB); 7554 7555 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7556 MF.insert(It, DoneMBB); 7557 7558 // Transfer the remainder of BB and its successor edges to DoneMBB. 7559 DoneMBB->splice(DoneMBB->begin(), BB, 7560 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7561 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 7562 7563 BB->addSuccessor(LoopMBB); 7564 7565 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7566 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 7567 Register LoReg = MI.getOperand(0).getReg(); 7568 Register HiReg = MI.getOperand(1).getReg(); 7569 DebugLoc DL = MI.getDebugLoc(); 7570 7571 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 7572 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 7573 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7574 .addReg(RISCV::X0); 7575 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 7576 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 7577 .addReg(RISCV::X0); 7578 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 7579 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7580 .addReg(RISCV::X0); 7581 7582 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 7583 .addReg(HiReg) 7584 .addReg(ReadAgainReg) 7585 .addMBB(LoopMBB); 7586 7587 LoopMBB->addSuccessor(LoopMBB); 7588 LoopMBB->addSuccessor(DoneMBB); 7589 7590 MI.eraseFromParent(); 7591 7592 return DoneMBB; 7593 } 7594 7595 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 7596 MachineBasicBlock *BB) { 7597 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 7598 7599 MachineFunction &MF = *BB->getParent(); 7600 DebugLoc DL = MI.getDebugLoc(); 7601 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7602 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7603 Register LoReg = MI.getOperand(0).getReg(); 7604 Register HiReg = MI.getOperand(1).getReg(); 7605 Register SrcReg = MI.getOperand(2).getReg(); 7606 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 7607 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7608 7609 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 7610 RI); 7611 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7612 MachineMemOperand *MMOLo = 7613 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 7614 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7615 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 7616 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 7617 .addFrameIndex(FI) 7618 .addImm(0) 7619 .addMemOperand(MMOLo); 7620 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 7621 .addFrameIndex(FI) 7622 .addImm(4) 7623 .addMemOperand(MMOHi); 7624 MI.eraseFromParent(); // The pseudo instruction is gone now. 7625 return BB; 7626 } 7627 7628 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 7629 MachineBasicBlock *BB) { 7630 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 7631 "Unexpected instruction"); 7632 7633 MachineFunction &MF = *BB->getParent(); 7634 DebugLoc DL = MI.getDebugLoc(); 7635 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7636 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7637 Register DstReg = MI.getOperand(0).getReg(); 7638 Register LoReg = MI.getOperand(1).getReg(); 7639 Register HiReg = MI.getOperand(2).getReg(); 7640 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 7641 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7642 7643 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7644 MachineMemOperand *MMOLo = 7645 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 7646 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7647 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 7648 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7649 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 7650 .addFrameIndex(FI) 7651 .addImm(0) 7652 .addMemOperand(MMOLo); 7653 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7654 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 7655 .addFrameIndex(FI) 7656 .addImm(4) 7657 .addMemOperand(MMOHi); 7658 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 7659 MI.eraseFromParent(); // The pseudo instruction is gone now. 7660 return BB; 7661 } 7662 7663 static bool isSelectPseudo(MachineInstr &MI) { 7664 switch (MI.getOpcode()) { 7665 default: 7666 return false; 7667 case RISCV::Select_GPR_Using_CC_GPR: 7668 case RISCV::Select_FPR16_Using_CC_GPR: 7669 case RISCV::Select_FPR32_Using_CC_GPR: 7670 case RISCV::Select_FPR64_Using_CC_GPR: 7671 return true; 7672 } 7673 } 7674 7675 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 7676 MachineBasicBlock *BB, 7677 const RISCVSubtarget &Subtarget) { 7678 // To "insert" Select_* instructions, we actually have to insert the triangle 7679 // control-flow pattern. The incoming instructions know the destination vreg 7680 // to set, the condition code register to branch on, the true/false values to 7681 // select between, and the condcode to use to select the appropriate branch. 7682 // 7683 // We produce the following control flow: 7684 // HeadMBB 7685 // | \ 7686 // | IfFalseMBB 7687 // | / 7688 // TailMBB 7689 // 7690 // When we find a sequence of selects we attempt to optimize their emission 7691 // by sharing the control flow. Currently we only handle cases where we have 7692 // multiple selects with the exact same condition (same LHS, RHS and CC). 7693 // The selects may be interleaved with other instructions if the other 7694 // instructions meet some requirements we deem safe: 7695 // - They are debug instructions. Otherwise, 7696 // - They do not have side-effects, do not access memory and their inputs do 7697 // not depend on the results of the select pseudo-instructions. 7698 // The TrueV/FalseV operands of the selects cannot depend on the result of 7699 // previous selects in the sequence. 7700 // These conditions could be further relaxed. See the X86 target for a 7701 // related approach and more information. 7702 Register LHS = MI.getOperand(1).getReg(); 7703 Register RHS = MI.getOperand(2).getReg(); 7704 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 7705 7706 SmallVector<MachineInstr *, 4> SelectDebugValues; 7707 SmallSet<Register, 4> SelectDests; 7708 SelectDests.insert(MI.getOperand(0).getReg()); 7709 7710 MachineInstr *LastSelectPseudo = &MI; 7711 7712 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 7713 SequenceMBBI != E; ++SequenceMBBI) { 7714 if (SequenceMBBI->isDebugInstr()) 7715 continue; 7716 else if (isSelectPseudo(*SequenceMBBI)) { 7717 if (SequenceMBBI->getOperand(1).getReg() != LHS || 7718 SequenceMBBI->getOperand(2).getReg() != RHS || 7719 SequenceMBBI->getOperand(3).getImm() != CC || 7720 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 7721 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 7722 break; 7723 LastSelectPseudo = &*SequenceMBBI; 7724 SequenceMBBI->collectDebugValues(SelectDebugValues); 7725 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 7726 } else { 7727 if (SequenceMBBI->hasUnmodeledSideEffects() || 7728 SequenceMBBI->mayLoadOrStore()) 7729 break; 7730 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 7731 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 7732 })) 7733 break; 7734 } 7735 } 7736 7737 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 7738 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7739 DebugLoc DL = MI.getDebugLoc(); 7740 MachineFunction::iterator I = ++BB->getIterator(); 7741 7742 MachineBasicBlock *HeadMBB = BB; 7743 MachineFunction *F = BB->getParent(); 7744 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 7745 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 7746 7747 F->insert(I, IfFalseMBB); 7748 F->insert(I, TailMBB); 7749 7750 // Transfer debug instructions associated with the selects to TailMBB. 7751 for (MachineInstr *DebugInstr : SelectDebugValues) { 7752 TailMBB->push_back(DebugInstr->removeFromParent()); 7753 } 7754 7755 // Move all instructions after the sequence to TailMBB. 7756 TailMBB->splice(TailMBB->end(), HeadMBB, 7757 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 7758 // Update machine-CFG edges by transferring all successors of the current 7759 // block to the new block which will contain the Phi nodes for the selects. 7760 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 7761 // Set the successors for HeadMBB. 7762 HeadMBB->addSuccessor(IfFalseMBB); 7763 HeadMBB->addSuccessor(TailMBB); 7764 7765 // Insert appropriate branch. 7766 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 7767 .addReg(LHS) 7768 .addReg(RHS) 7769 .addMBB(TailMBB); 7770 7771 // IfFalseMBB just falls through to TailMBB. 7772 IfFalseMBB->addSuccessor(TailMBB); 7773 7774 // Create PHIs for all of the select pseudo-instructions. 7775 auto SelectMBBI = MI.getIterator(); 7776 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 7777 auto InsertionPoint = TailMBB->begin(); 7778 while (SelectMBBI != SelectEnd) { 7779 auto Next = std::next(SelectMBBI); 7780 if (isSelectPseudo(*SelectMBBI)) { 7781 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 7782 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 7783 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 7784 .addReg(SelectMBBI->getOperand(4).getReg()) 7785 .addMBB(HeadMBB) 7786 .addReg(SelectMBBI->getOperand(5).getReg()) 7787 .addMBB(IfFalseMBB); 7788 SelectMBBI->eraseFromParent(); 7789 } 7790 SelectMBBI = Next; 7791 } 7792 7793 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 7794 return TailMBB; 7795 } 7796 7797 MachineBasicBlock * 7798 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 7799 MachineBasicBlock *BB) const { 7800 switch (MI.getOpcode()) { 7801 default: 7802 llvm_unreachable("Unexpected instr type to insert"); 7803 case RISCV::ReadCycleWide: 7804 assert(!Subtarget.is64Bit() && 7805 "ReadCycleWrite is only to be used on riscv32"); 7806 return emitReadCycleWidePseudo(MI, BB); 7807 case RISCV::Select_GPR_Using_CC_GPR: 7808 case RISCV::Select_FPR16_Using_CC_GPR: 7809 case RISCV::Select_FPR32_Using_CC_GPR: 7810 case RISCV::Select_FPR64_Using_CC_GPR: 7811 return emitSelectPseudo(MI, BB, Subtarget); 7812 case RISCV::BuildPairF64Pseudo: 7813 return emitBuildPairF64Pseudo(MI, BB); 7814 case RISCV::SplitF64Pseudo: 7815 return emitSplitF64Pseudo(MI, BB); 7816 } 7817 } 7818 7819 // Calling Convention Implementation. 7820 // The expectations for frontend ABI lowering vary from target to target. 7821 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 7822 // details, but this is a longer term goal. For now, we simply try to keep the 7823 // role of the frontend as simple and well-defined as possible. The rules can 7824 // be summarised as: 7825 // * Never split up large scalar arguments. We handle them here. 7826 // * If a hardfloat calling convention is being used, and the struct may be 7827 // passed in a pair of registers (fp+fp, int+fp), and both registers are 7828 // available, then pass as two separate arguments. If either the GPRs or FPRs 7829 // are exhausted, then pass according to the rule below. 7830 // * If a struct could never be passed in registers or directly in a stack 7831 // slot (as it is larger than 2*XLEN and the floating point rules don't 7832 // apply), then pass it using a pointer with the byval attribute. 7833 // * If a struct is less than 2*XLEN, then coerce to either a two-element 7834 // word-sized array or a 2*XLEN scalar (depending on alignment). 7835 // * The frontend can determine whether a struct is returned by reference or 7836 // not based on its size and fields. If it will be returned by reference, the 7837 // frontend must modify the prototype so a pointer with the sret annotation is 7838 // passed as the first argument. This is not necessary for large scalar 7839 // returns. 7840 // * Struct return values and varargs should be coerced to structs containing 7841 // register-size fields in the same situations they would be for fixed 7842 // arguments. 7843 7844 static const MCPhysReg ArgGPRs[] = { 7845 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 7846 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 7847 }; 7848 static const MCPhysReg ArgFPR16s[] = { 7849 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 7850 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 7851 }; 7852 static const MCPhysReg ArgFPR32s[] = { 7853 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 7854 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 7855 }; 7856 static const MCPhysReg ArgFPR64s[] = { 7857 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 7858 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 7859 }; 7860 // This is an interim calling convention and it may be changed in the future. 7861 static const MCPhysReg ArgVRs[] = { 7862 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 7863 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 7864 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 7865 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 7866 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 7867 RISCV::V20M2, RISCV::V22M2}; 7868 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 7869 RISCV::V20M4}; 7870 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 7871 7872 // Pass a 2*XLEN argument that has been split into two XLEN values through 7873 // registers or the stack as necessary. 7874 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 7875 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 7876 MVT ValVT2, MVT LocVT2, 7877 ISD::ArgFlagsTy ArgFlags2) { 7878 unsigned XLenInBytes = XLen / 8; 7879 if (Register Reg = State.AllocateReg(ArgGPRs)) { 7880 // At least one half can be passed via register. 7881 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 7882 VA1.getLocVT(), CCValAssign::Full)); 7883 } else { 7884 // Both halves must be passed on the stack, with proper alignment. 7885 Align StackAlign = 7886 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 7887 State.addLoc( 7888 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 7889 State.AllocateStack(XLenInBytes, StackAlign), 7890 VA1.getLocVT(), CCValAssign::Full)); 7891 State.addLoc(CCValAssign::getMem( 7892 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 7893 LocVT2, CCValAssign::Full)); 7894 return false; 7895 } 7896 7897 if (Register Reg = State.AllocateReg(ArgGPRs)) { 7898 // The second half can also be passed via register. 7899 State.addLoc( 7900 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 7901 } else { 7902 // The second half is passed via the stack, without additional alignment. 7903 State.addLoc(CCValAssign::getMem( 7904 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 7905 LocVT2, CCValAssign::Full)); 7906 } 7907 7908 return false; 7909 } 7910 7911 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 7912 Optional<unsigned> FirstMaskArgument, 7913 CCState &State, const RISCVTargetLowering &TLI) { 7914 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 7915 if (RC == &RISCV::VRRegClass) { 7916 // Assign the first mask argument to V0. 7917 // This is an interim calling convention and it may be changed in the 7918 // future. 7919 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 7920 return State.AllocateReg(RISCV::V0); 7921 return State.AllocateReg(ArgVRs); 7922 } 7923 if (RC == &RISCV::VRM2RegClass) 7924 return State.AllocateReg(ArgVRM2s); 7925 if (RC == &RISCV::VRM4RegClass) 7926 return State.AllocateReg(ArgVRM4s); 7927 if (RC == &RISCV::VRM8RegClass) 7928 return State.AllocateReg(ArgVRM8s); 7929 llvm_unreachable("Unhandled register class for ValueType"); 7930 } 7931 7932 // Implements the RISC-V calling convention. Returns true upon failure. 7933 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 7934 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 7935 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 7936 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 7937 Optional<unsigned> FirstMaskArgument) { 7938 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 7939 assert(XLen == 32 || XLen == 64); 7940 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 7941 7942 // Any return value split in to more than two values can't be returned 7943 // directly. Vectors are returned via the available vector registers. 7944 if (!LocVT.isVector() && IsRet && ValNo > 1) 7945 return true; 7946 7947 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 7948 // variadic argument, or if no F16/F32 argument registers are available. 7949 bool UseGPRForF16_F32 = true; 7950 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 7951 // variadic argument, or if no F64 argument registers are available. 7952 bool UseGPRForF64 = true; 7953 7954 switch (ABI) { 7955 default: 7956 llvm_unreachable("Unexpected ABI"); 7957 case RISCVABI::ABI_ILP32: 7958 case RISCVABI::ABI_LP64: 7959 break; 7960 case RISCVABI::ABI_ILP32F: 7961 case RISCVABI::ABI_LP64F: 7962 UseGPRForF16_F32 = !IsFixed; 7963 break; 7964 case RISCVABI::ABI_ILP32D: 7965 case RISCVABI::ABI_LP64D: 7966 UseGPRForF16_F32 = !IsFixed; 7967 UseGPRForF64 = !IsFixed; 7968 break; 7969 } 7970 7971 // FPR16, FPR32, and FPR64 alias each other. 7972 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 7973 UseGPRForF16_F32 = true; 7974 UseGPRForF64 = true; 7975 } 7976 7977 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 7978 // similar local variables rather than directly checking against the target 7979 // ABI. 7980 7981 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 7982 LocVT = XLenVT; 7983 LocInfo = CCValAssign::BCvt; 7984 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 7985 LocVT = MVT::i64; 7986 LocInfo = CCValAssign::BCvt; 7987 } 7988 7989 // If this is a variadic argument, the RISC-V calling convention requires 7990 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 7991 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 7992 // be used regardless of whether the original argument was split during 7993 // legalisation or not. The argument will not be passed by registers if the 7994 // original type is larger than 2*XLEN, so the register alignment rule does 7995 // not apply. 7996 unsigned TwoXLenInBytes = (2 * XLen) / 8; 7997 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 7998 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 7999 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 8000 // Skip 'odd' register if necessary. 8001 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 8002 State.AllocateReg(ArgGPRs); 8003 } 8004 8005 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 8006 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 8007 State.getPendingArgFlags(); 8008 8009 assert(PendingLocs.size() == PendingArgFlags.size() && 8010 "PendingLocs and PendingArgFlags out of sync"); 8011 8012 // Handle passing f64 on RV32D with a soft float ABI or when floating point 8013 // registers are exhausted. 8014 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 8015 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 8016 "Can't lower f64 if it is split"); 8017 // Depending on available argument GPRS, f64 may be passed in a pair of 8018 // GPRs, split between a GPR and the stack, or passed completely on the 8019 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 8020 // cases. 8021 Register Reg = State.AllocateReg(ArgGPRs); 8022 LocVT = MVT::i32; 8023 if (!Reg) { 8024 unsigned StackOffset = State.AllocateStack(8, Align(8)); 8025 State.addLoc( 8026 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8027 return false; 8028 } 8029 if (!State.AllocateReg(ArgGPRs)) 8030 State.AllocateStack(4, Align(4)); 8031 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8032 return false; 8033 } 8034 8035 // Fixed-length vectors are located in the corresponding scalable-vector 8036 // container types. 8037 if (ValVT.isFixedLengthVector()) 8038 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8039 8040 // Split arguments might be passed indirectly, so keep track of the pending 8041 // values. Split vectors are passed via a mix of registers and indirectly, so 8042 // treat them as we would any other argument. 8043 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 8044 LocVT = XLenVT; 8045 LocInfo = CCValAssign::Indirect; 8046 PendingLocs.push_back( 8047 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 8048 PendingArgFlags.push_back(ArgFlags); 8049 if (!ArgFlags.isSplitEnd()) { 8050 return false; 8051 } 8052 } 8053 8054 // If the split argument only had two elements, it should be passed directly 8055 // in registers or on the stack. 8056 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 8057 PendingLocs.size() <= 2) { 8058 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 8059 // Apply the normal calling convention rules to the first half of the 8060 // split argument. 8061 CCValAssign VA = PendingLocs[0]; 8062 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 8063 PendingLocs.clear(); 8064 PendingArgFlags.clear(); 8065 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 8066 ArgFlags); 8067 } 8068 8069 // Allocate to a register if possible, or else a stack slot. 8070 Register Reg; 8071 unsigned StoreSizeBytes = XLen / 8; 8072 Align StackAlign = Align(XLen / 8); 8073 8074 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 8075 Reg = State.AllocateReg(ArgFPR16s); 8076 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 8077 Reg = State.AllocateReg(ArgFPR32s); 8078 else if (ValVT == MVT::f64 && !UseGPRForF64) 8079 Reg = State.AllocateReg(ArgFPR64s); 8080 else if (ValVT.isVector()) { 8081 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 8082 if (!Reg) { 8083 // For return values, the vector must be passed fully via registers or 8084 // via the stack. 8085 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 8086 // but we're using all of them. 8087 if (IsRet) 8088 return true; 8089 // Try using a GPR to pass the address 8090 if ((Reg = State.AllocateReg(ArgGPRs))) { 8091 LocVT = XLenVT; 8092 LocInfo = CCValAssign::Indirect; 8093 } else if (ValVT.isScalableVector()) { 8094 report_fatal_error("Unable to pass scalable vector types on the stack"); 8095 } else { 8096 // Pass fixed-length vectors on the stack. 8097 LocVT = ValVT; 8098 StoreSizeBytes = ValVT.getStoreSize(); 8099 // Align vectors to their element sizes, being careful for vXi1 8100 // vectors. 8101 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8102 } 8103 } 8104 } else { 8105 Reg = State.AllocateReg(ArgGPRs); 8106 } 8107 8108 unsigned StackOffset = 8109 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 8110 8111 // If we reach this point and PendingLocs is non-empty, we must be at the 8112 // end of a split argument that must be passed indirectly. 8113 if (!PendingLocs.empty()) { 8114 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 8115 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 8116 8117 for (auto &It : PendingLocs) { 8118 if (Reg) 8119 It.convertToReg(Reg); 8120 else 8121 It.convertToMem(StackOffset); 8122 State.addLoc(It); 8123 } 8124 PendingLocs.clear(); 8125 PendingArgFlags.clear(); 8126 return false; 8127 } 8128 8129 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 8130 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 8131 "Expected an XLenVT or vector types at this stage"); 8132 8133 if (Reg) { 8134 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8135 return false; 8136 } 8137 8138 // When a floating-point value is passed on the stack, no bit-conversion is 8139 // needed. 8140 if (ValVT.isFloatingPoint()) { 8141 LocVT = ValVT; 8142 LocInfo = CCValAssign::Full; 8143 } 8144 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8145 return false; 8146 } 8147 8148 template <typename ArgTy> 8149 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 8150 for (const auto &ArgIdx : enumerate(Args)) { 8151 MVT ArgVT = ArgIdx.value().VT; 8152 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 8153 return ArgIdx.index(); 8154 } 8155 return None; 8156 } 8157 8158 void RISCVTargetLowering::analyzeInputArgs( 8159 MachineFunction &MF, CCState &CCInfo, 8160 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 8161 RISCVCCAssignFn Fn) const { 8162 unsigned NumArgs = Ins.size(); 8163 FunctionType *FType = MF.getFunction().getFunctionType(); 8164 8165 Optional<unsigned> FirstMaskArgument; 8166 if (Subtarget.hasVInstructions()) 8167 FirstMaskArgument = preAssignMask(Ins); 8168 8169 for (unsigned i = 0; i != NumArgs; ++i) { 8170 MVT ArgVT = Ins[i].VT; 8171 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 8172 8173 Type *ArgTy = nullptr; 8174 if (IsRet) 8175 ArgTy = FType->getReturnType(); 8176 else if (Ins[i].isOrigArg()) 8177 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 8178 8179 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8180 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8181 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 8182 FirstMaskArgument)) { 8183 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 8184 << EVT(ArgVT).getEVTString() << '\n'); 8185 llvm_unreachable(nullptr); 8186 } 8187 } 8188 } 8189 8190 void RISCVTargetLowering::analyzeOutputArgs( 8191 MachineFunction &MF, CCState &CCInfo, 8192 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 8193 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 8194 unsigned NumArgs = Outs.size(); 8195 8196 Optional<unsigned> FirstMaskArgument; 8197 if (Subtarget.hasVInstructions()) 8198 FirstMaskArgument = preAssignMask(Outs); 8199 8200 for (unsigned i = 0; i != NumArgs; i++) { 8201 MVT ArgVT = Outs[i].VT; 8202 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 8203 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 8204 8205 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8206 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8207 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 8208 FirstMaskArgument)) { 8209 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 8210 << EVT(ArgVT).getEVTString() << "\n"); 8211 llvm_unreachable(nullptr); 8212 } 8213 } 8214 } 8215 8216 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 8217 // values. 8218 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 8219 const CCValAssign &VA, const SDLoc &DL, 8220 const RISCVSubtarget &Subtarget) { 8221 switch (VA.getLocInfo()) { 8222 default: 8223 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8224 case CCValAssign::Full: 8225 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 8226 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 8227 break; 8228 case CCValAssign::BCvt: 8229 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8230 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 8231 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8232 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 8233 else 8234 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 8235 break; 8236 } 8237 return Val; 8238 } 8239 8240 // The caller is responsible for loading the full value if the argument is 8241 // passed with CCValAssign::Indirect. 8242 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 8243 const CCValAssign &VA, const SDLoc &DL, 8244 const RISCVTargetLowering &TLI) { 8245 MachineFunction &MF = DAG.getMachineFunction(); 8246 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8247 EVT LocVT = VA.getLocVT(); 8248 SDValue Val; 8249 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 8250 Register VReg = RegInfo.createVirtualRegister(RC); 8251 RegInfo.addLiveIn(VA.getLocReg(), VReg); 8252 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 8253 8254 if (VA.getLocInfo() == CCValAssign::Indirect) 8255 return Val; 8256 8257 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 8258 } 8259 8260 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 8261 const CCValAssign &VA, const SDLoc &DL, 8262 const RISCVSubtarget &Subtarget) { 8263 EVT LocVT = VA.getLocVT(); 8264 8265 switch (VA.getLocInfo()) { 8266 default: 8267 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8268 case CCValAssign::Full: 8269 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 8270 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 8271 break; 8272 case CCValAssign::BCvt: 8273 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8274 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 8275 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8276 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 8277 else 8278 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 8279 break; 8280 } 8281 return Val; 8282 } 8283 8284 // The caller is responsible for loading the full value if the argument is 8285 // passed with CCValAssign::Indirect. 8286 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 8287 const CCValAssign &VA, const SDLoc &DL) { 8288 MachineFunction &MF = DAG.getMachineFunction(); 8289 MachineFrameInfo &MFI = MF.getFrameInfo(); 8290 EVT LocVT = VA.getLocVT(); 8291 EVT ValVT = VA.getValVT(); 8292 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 8293 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 8294 /*Immutable=*/true); 8295 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 8296 SDValue Val; 8297 8298 ISD::LoadExtType ExtType; 8299 switch (VA.getLocInfo()) { 8300 default: 8301 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8302 case CCValAssign::Full: 8303 case CCValAssign::Indirect: 8304 case CCValAssign::BCvt: 8305 ExtType = ISD::NON_EXTLOAD; 8306 break; 8307 } 8308 Val = DAG.getExtLoad( 8309 ExtType, DL, LocVT, Chain, FIN, 8310 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 8311 return Val; 8312 } 8313 8314 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 8315 const CCValAssign &VA, const SDLoc &DL) { 8316 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 8317 "Unexpected VA"); 8318 MachineFunction &MF = DAG.getMachineFunction(); 8319 MachineFrameInfo &MFI = MF.getFrameInfo(); 8320 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8321 8322 if (VA.isMemLoc()) { 8323 // f64 is passed on the stack. 8324 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 8325 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8326 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 8327 MachinePointerInfo::getFixedStack(MF, FI)); 8328 } 8329 8330 assert(VA.isRegLoc() && "Expected register VA assignment"); 8331 8332 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8333 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 8334 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 8335 SDValue Hi; 8336 if (VA.getLocReg() == RISCV::X17) { 8337 // Second half of f64 is passed on the stack. 8338 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 8339 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8340 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 8341 MachinePointerInfo::getFixedStack(MF, FI)); 8342 } else { 8343 // Second half of f64 is passed in another GPR. 8344 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8345 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 8346 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 8347 } 8348 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 8349 } 8350 8351 // FastCC has less than 1% performance improvement for some particular 8352 // benchmark. But theoretically, it may has benenfit for some cases. 8353 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 8354 unsigned ValNo, MVT ValVT, MVT LocVT, 8355 CCValAssign::LocInfo LocInfo, 8356 ISD::ArgFlagsTy ArgFlags, CCState &State, 8357 bool IsFixed, bool IsRet, Type *OrigTy, 8358 const RISCVTargetLowering &TLI, 8359 Optional<unsigned> FirstMaskArgument) { 8360 8361 // X5 and X6 might be used for save-restore libcall. 8362 static const MCPhysReg GPRList[] = { 8363 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 8364 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 8365 RISCV::X29, RISCV::X30, RISCV::X31}; 8366 8367 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8368 if (unsigned Reg = State.AllocateReg(GPRList)) { 8369 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8370 return false; 8371 } 8372 } 8373 8374 if (LocVT == MVT::f16) { 8375 static const MCPhysReg FPR16List[] = { 8376 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 8377 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 8378 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 8379 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 8380 if (unsigned Reg = State.AllocateReg(FPR16List)) { 8381 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8382 return false; 8383 } 8384 } 8385 8386 if (LocVT == MVT::f32) { 8387 static const MCPhysReg FPR32List[] = { 8388 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 8389 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 8390 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 8391 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 8392 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8393 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8394 return false; 8395 } 8396 } 8397 8398 if (LocVT == MVT::f64) { 8399 static const MCPhysReg FPR64List[] = { 8400 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 8401 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 8402 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 8403 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 8404 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8405 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8406 return false; 8407 } 8408 } 8409 8410 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 8411 unsigned Offset4 = State.AllocateStack(4, Align(4)); 8412 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 8413 return false; 8414 } 8415 8416 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 8417 unsigned Offset5 = State.AllocateStack(8, Align(8)); 8418 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 8419 return false; 8420 } 8421 8422 if (LocVT.isVector()) { 8423 if (unsigned Reg = 8424 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 8425 // Fixed-length vectors are located in the corresponding scalable-vector 8426 // container types. 8427 if (ValVT.isFixedLengthVector()) 8428 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8429 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8430 } else { 8431 // Try and pass the address via a "fast" GPR. 8432 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 8433 LocInfo = CCValAssign::Indirect; 8434 LocVT = TLI.getSubtarget().getXLenVT(); 8435 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 8436 } else if (ValVT.isFixedLengthVector()) { 8437 auto StackAlign = 8438 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8439 unsigned StackOffset = 8440 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 8441 State.addLoc( 8442 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8443 } else { 8444 // Can't pass scalable vectors on the stack. 8445 return true; 8446 } 8447 } 8448 8449 return false; 8450 } 8451 8452 return true; // CC didn't match. 8453 } 8454 8455 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 8456 CCValAssign::LocInfo LocInfo, 8457 ISD::ArgFlagsTy ArgFlags, CCState &State) { 8458 8459 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8460 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 8461 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 8462 static const MCPhysReg GPRList[] = { 8463 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 8464 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 8465 if (unsigned Reg = State.AllocateReg(GPRList)) { 8466 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8467 return false; 8468 } 8469 } 8470 8471 if (LocVT == MVT::f32) { 8472 // Pass in STG registers: F1, ..., F6 8473 // fs0 ... fs5 8474 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 8475 RISCV::F18_F, RISCV::F19_F, 8476 RISCV::F20_F, RISCV::F21_F}; 8477 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8478 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8479 return false; 8480 } 8481 } 8482 8483 if (LocVT == MVT::f64) { 8484 // Pass in STG registers: D1, ..., D6 8485 // fs6 ... fs11 8486 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 8487 RISCV::F24_D, RISCV::F25_D, 8488 RISCV::F26_D, RISCV::F27_D}; 8489 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8490 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8491 return false; 8492 } 8493 } 8494 8495 report_fatal_error("No registers left in GHC calling convention"); 8496 return true; 8497 } 8498 8499 // Transform physical registers into virtual registers. 8500 SDValue RISCVTargetLowering::LowerFormalArguments( 8501 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 8502 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 8503 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 8504 8505 MachineFunction &MF = DAG.getMachineFunction(); 8506 8507 switch (CallConv) { 8508 default: 8509 report_fatal_error("Unsupported calling convention"); 8510 case CallingConv::C: 8511 case CallingConv::Fast: 8512 break; 8513 case CallingConv::GHC: 8514 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 8515 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 8516 report_fatal_error( 8517 "GHC calling convention requires the F and D instruction set extensions"); 8518 } 8519 8520 const Function &Func = MF.getFunction(); 8521 if (Func.hasFnAttribute("interrupt")) { 8522 if (!Func.arg_empty()) 8523 report_fatal_error( 8524 "Functions with the interrupt attribute cannot have arguments!"); 8525 8526 StringRef Kind = 8527 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 8528 8529 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 8530 report_fatal_error( 8531 "Function interrupt attribute argument not supported!"); 8532 } 8533 8534 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8535 MVT XLenVT = Subtarget.getXLenVT(); 8536 unsigned XLenInBytes = Subtarget.getXLen() / 8; 8537 // Used with vargs to acumulate store chains. 8538 std::vector<SDValue> OutChains; 8539 8540 // Assign locations to all of the incoming arguments. 8541 SmallVector<CCValAssign, 16> ArgLocs; 8542 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 8543 8544 if (CallConv == CallingConv::GHC) 8545 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 8546 else 8547 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 8548 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 8549 : CC_RISCV); 8550 8551 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 8552 CCValAssign &VA = ArgLocs[i]; 8553 SDValue ArgValue; 8554 // Passing f64 on RV32D with a soft float ABI must be handled as a special 8555 // case. 8556 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 8557 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 8558 else if (VA.isRegLoc()) 8559 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 8560 else 8561 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 8562 8563 if (VA.getLocInfo() == CCValAssign::Indirect) { 8564 // If the original argument was split and passed by reference (e.g. i128 8565 // on RV32), we need to load all parts of it here (using the same 8566 // address). Vectors may be partly split to registers and partly to the 8567 // stack, in which case the base address is partly offset and subsequent 8568 // stores are relative to that. 8569 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 8570 MachinePointerInfo())); 8571 unsigned ArgIndex = Ins[i].OrigArgIndex; 8572 unsigned ArgPartOffset = Ins[i].PartOffset; 8573 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8574 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 8575 CCValAssign &PartVA = ArgLocs[i + 1]; 8576 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 8577 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8578 if (PartVA.getValVT().isScalableVector()) 8579 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8580 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 8581 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 8582 MachinePointerInfo())); 8583 ++i; 8584 } 8585 continue; 8586 } 8587 InVals.push_back(ArgValue); 8588 } 8589 8590 if (IsVarArg) { 8591 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 8592 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 8593 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 8594 MachineFrameInfo &MFI = MF.getFrameInfo(); 8595 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8596 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 8597 8598 // Offset of the first variable argument from stack pointer, and size of 8599 // the vararg save area. For now, the varargs save area is either zero or 8600 // large enough to hold a0-a7. 8601 int VaArgOffset, VarArgsSaveSize; 8602 8603 // If all registers are allocated, then all varargs must be passed on the 8604 // stack and we don't need to save any argregs. 8605 if (ArgRegs.size() == Idx) { 8606 VaArgOffset = CCInfo.getNextStackOffset(); 8607 VarArgsSaveSize = 0; 8608 } else { 8609 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 8610 VaArgOffset = -VarArgsSaveSize; 8611 } 8612 8613 // Record the frame index of the first variable argument 8614 // which is a value necessary to VASTART. 8615 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8616 RVFI->setVarArgsFrameIndex(FI); 8617 8618 // If saving an odd number of registers then create an extra stack slot to 8619 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 8620 // offsets to even-numbered registered remain 2*XLEN-aligned. 8621 if (Idx % 2) { 8622 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 8623 VarArgsSaveSize += XLenInBytes; 8624 } 8625 8626 // Copy the integer registers that may have been used for passing varargs 8627 // to the vararg save area. 8628 for (unsigned I = Idx; I < ArgRegs.size(); 8629 ++I, VaArgOffset += XLenInBytes) { 8630 const Register Reg = RegInfo.createVirtualRegister(RC); 8631 RegInfo.addLiveIn(ArgRegs[I], Reg); 8632 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 8633 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8634 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8635 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 8636 MachinePointerInfo::getFixedStack(MF, FI)); 8637 cast<StoreSDNode>(Store.getNode()) 8638 ->getMemOperand() 8639 ->setValue((Value *)nullptr); 8640 OutChains.push_back(Store); 8641 } 8642 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 8643 } 8644 8645 // All stores are grouped in one node to allow the matching between 8646 // the size of Ins and InVals. This only happens for vararg functions. 8647 if (!OutChains.empty()) { 8648 OutChains.push_back(Chain); 8649 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 8650 } 8651 8652 return Chain; 8653 } 8654 8655 /// isEligibleForTailCallOptimization - Check whether the call is eligible 8656 /// for tail call optimization. 8657 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 8658 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 8659 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 8660 const SmallVector<CCValAssign, 16> &ArgLocs) const { 8661 8662 auto &Callee = CLI.Callee; 8663 auto CalleeCC = CLI.CallConv; 8664 auto &Outs = CLI.Outs; 8665 auto &Caller = MF.getFunction(); 8666 auto CallerCC = Caller.getCallingConv(); 8667 8668 // Exception-handling functions need a special set of instructions to 8669 // indicate a return to the hardware. Tail-calling another function would 8670 // probably break this. 8671 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 8672 // should be expanded as new function attributes are introduced. 8673 if (Caller.hasFnAttribute("interrupt")) 8674 return false; 8675 8676 // Do not tail call opt if the stack is used to pass parameters. 8677 if (CCInfo.getNextStackOffset() != 0) 8678 return false; 8679 8680 // Do not tail call opt if any parameters need to be passed indirectly. 8681 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 8682 // passed indirectly. So the address of the value will be passed in a 8683 // register, or if not available, then the address is put on the stack. In 8684 // order to pass indirectly, space on the stack often needs to be allocated 8685 // in order to store the value. In this case the CCInfo.getNextStackOffset() 8686 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 8687 // are passed CCValAssign::Indirect. 8688 for (auto &VA : ArgLocs) 8689 if (VA.getLocInfo() == CCValAssign::Indirect) 8690 return false; 8691 8692 // Do not tail call opt if either caller or callee uses struct return 8693 // semantics. 8694 auto IsCallerStructRet = Caller.hasStructRetAttr(); 8695 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 8696 if (IsCallerStructRet || IsCalleeStructRet) 8697 return false; 8698 8699 // Externally-defined functions with weak linkage should not be 8700 // tail-called. The behaviour of branch instructions in this situation (as 8701 // used for tail calls) is implementation-defined, so we cannot rely on the 8702 // linker replacing the tail call with a return. 8703 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 8704 const GlobalValue *GV = G->getGlobal(); 8705 if (GV->hasExternalWeakLinkage()) 8706 return false; 8707 } 8708 8709 // The callee has to preserve all registers the caller needs to preserve. 8710 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 8711 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 8712 if (CalleeCC != CallerCC) { 8713 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 8714 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 8715 return false; 8716 } 8717 8718 // Byval parameters hand the function a pointer directly into the stack area 8719 // we want to reuse during a tail call. Working around this *is* possible 8720 // but less efficient and uglier in LowerCall. 8721 for (auto &Arg : Outs) 8722 if (Arg.Flags.isByVal()) 8723 return false; 8724 8725 return true; 8726 } 8727 8728 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 8729 return DAG.getDataLayout().getPrefTypeAlign( 8730 VT.getTypeForEVT(*DAG.getContext())); 8731 } 8732 8733 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 8734 // and output parameter nodes. 8735 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 8736 SmallVectorImpl<SDValue> &InVals) const { 8737 SelectionDAG &DAG = CLI.DAG; 8738 SDLoc &DL = CLI.DL; 8739 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 8740 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 8741 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 8742 SDValue Chain = CLI.Chain; 8743 SDValue Callee = CLI.Callee; 8744 bool &IsTailCall = CLI.IsTailCall; 8745 CallingConv::ID CallConv = CLI.CallConv; 8746 bool IsVarArg = CLI.IsVarArg; 8747 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8748 MVT XLenVT = Subtarget.getXLenVT(); 8749 8750 MachineFunction &MF = DAG.getMachineFunction(); 8751 8752 // Analyze the operands of the call, assigning locations to each operand. 8753 SmallVector<CCValAssign, 16> ArgLocs; 8754 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 8755 8756 if (CallConv == CallingConv::GHC) 8757 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 8758 else 8759 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 8760 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 8761 : CC_RISCV); 8762 8763 // Check if it's really possible to do a tail call. 8764 if (IsTailCall) 8765 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 8766 8767 if (IsTailCall) 8768 ++NumTailCalls; 8769 else if (CLI.CB && CLI.CB->isMustTailCall()) 8770 report_fatal_error("failed to perform tail call elimination on a call " 8771 "site marked musttail"); 8772 8773 // Get a count of how many bytes are to be pushed on the stack. 8774 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 8775 8776 // Create local copies for byval args 8777 SmallVector<SDValue, 8> ByValArgs; 8778 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 8779 ISD::ArgFlagsTy Flags = Outs[i].Flags; 8780 if (!Flags.isByVal()) 8781 continue; 8782 8783 SDValue Arg = OutVals[i]; 8784 unsigned Size = Flags.getByValSize(); 8785 Align Alignment = Flags.getNonZeroByValAlign(); 8786 8787 int FI = 8788 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 8789 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8790 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 8791 8792 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 8793 /*IsVolatile=*/false, 8794 /*AlwaysInline=*/false, IsTailCall, 8795 MachinePointerInfo(), MachinePointerInfo()); 8796 ByValArgs.push_back(FIPtr); 8797 } 8798 8799 if (!IsTailCall) 8800 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 8801 8802 // Copy argument values to their designated locations. 8803 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 8804 SmallVector<SDValue, 8> MemOpChains; 8805 SDValue StackPtr; 8806 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 8807 CCValAssign &VA = ArgLocs[i]; 8808 SDValue ArgValue = OutVals[i]; 8809 ISD::ArgFlagsTy Flags = Outs[i].Flags; 8810 8811 // Handle passing f64 on RV32D with a soft float ABI as a special case. 8812 bool IsF64OnRV32DSoftABI = 8813 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 8814 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 8815 SDValue SplitF64 = DAG.getNode( 8816 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 8817 SDValue Lo = SplitF64.getValue(0); 8818 SDValue Hi = SplitF64.getValue(1); 8819 8820 Register RegLo = VA.getLocReg(); 8821 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 8822 8823 if (RegLo == RISCV::X17) { 8824 // Second half of f64 is passed on the stack. 8825 // Work out the address of the stack slot. 8826 if (!StackPtr.getNode()) 8827 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 8828 // Emit the store. 8829 MemOpChains.push_back( 8830 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 8831 } else { 8832 // Second half of f64 is passed in another GPR. 8833 assert(RegLo < RISCV::X31 && "Invalid register pair"); 8834 Register RegHigh = RegLo + 1; 8835 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 8836 } 8837 continue; 8838 } 8839 8840 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 8841 // as any other MemLoc. 8842 8843 // Promote the value if needed. 8844 // For now, only handle fully promoted and indirect arguments. 8845 if (VA.getLocInfo() == CCValAssign::Indirect) { 8846 // Store the argument in a stack slot and pass its address. 8847 Align StackAlign = 8848 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 8849 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 8850 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 8851 // If the original argument was split (e.g. i128), we need 8852 // to store the required parts of it here (and pass just one address). 8853 // Vectors may be partly split to registers and partly to the stack, in 8854 // which case the base address is partly offset and subsequent stores are 8855 // relative to that. 8856 unsigned ArgIndex = Outs[i].OrigArgIndex; 8857 unsigned ArgPartOffset = Outs[i].PartOffset; 8858 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8859 // Calculate the total size to store. We don't have access to what we're 8860 // actually storing other than performing the loop and collecting the 8861 // info. 8862 SmallVector<std::pair<SDValue, SDValue>> Parts; 8863 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 8864 SDValue PartValue = OutVals[i + 1]; 8865 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 8866 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8867 EVT PartVT = PartValue.getValueType(); 8868 if (PartVT.isScalableVector()) 8869 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8870 StoredSize += PartVT.getStoreSize(); 8871 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 8872 Parts.push_back(std::make_pair(PartValue, Offset)); 8873 ++i; 8874 } 8875 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 8876 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 8877 MemOpChains.push_back( 8878 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 8879 MachinePointerInfo::getFixedStack(MF, FI))); 8880 for (const auto &Part : Parts) { 8881 SDValue PartValue = Part.first; 8882 SDValue PartOffset = Part.second; 8883 SDValue Address = 8884 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 8885 MemOpChains.push_back( 8886 DAG.getStore(Chain, DL, PartValue, Address, 8887 MachinePointerInfo::getFixedStack(MF, FI))); 8888 } 8889 ArgValue = SpillSlot; 8890 } else { 8891 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 8892 } 8893 8894 // Use local copy if it is a byval arg. 8895 if (Flags.isByVal()) 8896 ArgValue = ByValArgs[j++]; 8897 8898 if (VA.isRegLoc()) { 8899 // Queue up the argument copies and emit them at the end. 8900 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 8901 } else { 8902 assert(VA.isMemLoc() && "Argument not register or memory"); 8903 assert(!IsTailCall && "Tail call not allowed if stack is used " 8904 "for passing parameters"); 8905 8906 // Work out the address of the stack slot. 8907 if (!StackPtr.getNode()) 8908 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 8909 SDValue Address = 8910 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 8911 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 8912 8913 // Emit the store. 8914 MemOpChains.push_back( 8915 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 8916 } 8917 } 8918 8919 // Join the stores, which are independent of one another. 8920 if (!MemOpChains.empty()) 8921 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 8922 8923 SDValue Glue; 8924 8925 // Build a sequence of copy-to-reg nodes, chained and glued together. 8926 for (auto &Reg : RegsToPass) { 8927 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 8928 Glue = Chain.getValue(1); 8929 } 8930 8931 // Validate that none of the argument registers have been marked as 8932 // reserved, if so report an error. Do the same for the return address if this 8933 // is not a tailcall. 8934 validateCCReservedRegs(RegsToPass, MF); 8935 if (!IsTailCall && 8936 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 8937 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 8938 MF.getFunction(), 8939 "Return address register required, but has been reserved."}); 8940 8941 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 8942 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 8943 // split it and then direct call can be matched by PseudoCALL. 8944 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 8945 const GlobalValue *GV = S->getGlobal(); 8946 8947 unsigned OpFlags = RISCVII::MO_CALL; 8948 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 8949 OpFlags = RISCVII::MO_PLT; 8950 8951 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 8952 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 8953 unsigned OpFlags = RISCVII::MO_CALL; 8954 8955 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 8956 nullptr)) 8957 OpFlags = RISCVII::MO_PLT; 8958 8959 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 8960 } 8961 8962 // The first call operand is the chain and the second is the target address. 8963 SmallVector<SDValue, 8> Ops; 8964 Ops.push_back(Chain); 8965 Ops.push_back(Callee); 8966 8967 // Add argument registers to the end of the list so that they are 8968 // known live into the call. 8969 for (auto &Reg : RegsToPass) 8970 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 8971 8972 if (!IsTailCall) { 8973 // Add a register mask operand representing the call-preserved registers. 8974 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 8975 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 8976 assert(Mask && "Missing call preserved mask for calling convention"); 8977 Ops.push_back(DAG.getRegisterMask(Mask)); 8978 } 8979 8980 // Glue the call to the argument copies, if any. 8981 if (Glue.getNode()) 8982 Ops.push_back(Glue); 8983 8984 // Emit the call. 8985 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8986 8987 if (IsTailCall) { 8988 MF.getFrameInfo().setHasTailCall(); 8989 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 8990 } 8991 8992 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 8993 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 8994 Glue = Chain.getValue(1); 8995 8996 // Mark the end of the call, which is glued to the call itself. 8997 Chain = DAG.getCALLSEQ_END(Chain, 8998 DAG.getConstant(NumBytes, DL, PtrVT, true), 8999 DAG.getConstant(0, DL, PtrVT, true), 9000 Glue, DL); 9001 Glue = Chain.getValue(1); 9002 9003 // Assign locations to each value returned by this call. 9004 SmallVector<CCValAssign, 16> RVLocs; 9005 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 9006 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 9007 9008 // Copy all of the result registers out of their specified physreg. 9009 for (auto &VA : RVLocs) { 9010 // Copy the value out 9011 SDValue RetValue = 9012 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 9013 // Glue the RetValue to the end of the call sequence 9014 Chain = RetValue.getValue(1); 9015 Glue = RetValue.getValue(2); 9016 9017 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9018 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 9019 SDValue RetValue2 = 9020 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 9021 Chain = RetValue2.getValue(1); 9022 Glue = RetValue2.getValue(2); 9023 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 9024 RetValue2); 9025 } 9026 9027 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 9028 9029 InVals.push_back(RetValue); 9030 } 9031 9032 return Chain; 9033 } 9034 9035 bool RISCVTargetLowering::CanLowerReturn( 9036 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 9037 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 9038 SmallVector<CCValAssign, 16> RVLocs; 9039 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 9040 9041 Optional<unsigned> FirstMaskArgument; 9042 if (Subtarget.hasVInstructions()) 9043 FirstMaskArgument = preAssignMask(Outs); 9044 9045 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9046 MVT VT = Outs[i].VT; 9047 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9048 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9049 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 9050 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 9051 *this, FirstMaskArgument)) 9052 return false; 9053 } 9054 return true; 9055 } 9056 9057 SDValue 9058 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 9059 bool IsVarArg, 9060 const SmallVectorImpl<ISD::OutputArg> &Outs, 9061 const SmallVectorImpl<SDValue> &OutVals, 9062 const SDLoc &DL, SelectionDAG &DAG) const { 9063 const MachineFunction &MF = DAG.getMachineFunction(); 9064 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9065 9066 // Stores the assignment of the return value to a location. 9067 SmallVector<CCValAssign, 16> RVLocs; 9068 9069 // Info about the registers and stack slot. 9070 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 9071 *DAG.getContext()); 9072 9073 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 9074 nullptr, CC_RISCV); 9075 9076 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 9077 report_fatal_error("GHC functions return void only"); 9078 9079 SDValue Glue; 9080 SmallVector<SDValue, 4> RetOps(1, Chain); 9081 9082 // Copy the result values into the output registers. 9083 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 9084 SDValue Val = OutVals[i]; 9085 CCValAssign &VA = RVLocs[i]; 9086 assert(VA.isRegLoc() && "Can only return in registers!"); 9087 9088 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9089 // Handle returning f64 on RV32D with a soft float ABI. 9090 assert(VA.isRegLoc() && "Expected return via registers"); 9091 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 9092 DAG.getVTList(MVT::i32, MVT::i32), Val); 9093 SDValue Lo = SplitF64.getValue(0); 9094 SDValue Hi = SplitF64.getValue(1); 9095 Register RegLo = VA.getLocReg(); 9096 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9097 Register RegHi = RegLo + 1; 9098 9099 if (STI.isRegisterReservedByUser(RegLo) || 9100 STI.isRegisterReservedByUser(RegHi)) 9101 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9102 MF.getFunction(), 9103 "Return value register required, but has been reserved."}); 9104 9105 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 9106 Glue = Chain.getValue(1); 9107 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 9108 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 9109 Glue = Chain.getValue(1); 9110 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 9111 } else { 9112 // Handle a 'normal' return. 9113 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 9114 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 9115 9116 if (STI.isRegisterReservedByUser(VA.getLocReg())) 9117 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9118 MF.getFunction(), 9119 "Return value register required, but has been reserved."}); 9120 9121 // Guarantee that all emitted copies are stuck together. 9122 Glue = Chain.getValue(1); 9123 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 9124 } 9125 } 9126 9127 RetOps[0] = Chain; // Update chain. 9128 9129 // Add the glue node if we have it. 9130 if (Glue.getNode()) { 9131 RetOps.push_back(Glue); 9132 } 9133 9134 unsigned RetOpc = RISCVISD::RET_FLAG; 9135 // Interrupt service routines use different return instructions. 9136 const Function &Func = DAG.getMachineFunction().getFunction(); 9137 if (Func.hasFnAttribute("interrupt")) { 9138 if (!Func.getReturnType()->isVoidTy()) 9139 report_fatal_error( 9140 "Functions with the interrupt attribute must have void return type!"); 9141 9142 MachineFunction &MF = DAG.getMachineFunction(); 9143 StringRef Kind = 9144 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9145 9146 if (Kind == "user") 9147 RetOpc = RISCVISD::URET_FLAG; 9148 else if (Kind == "supervisor") 9149 RetOpc = RISCVISD::SRET_FLAG; 9150 else 9151 RetOpc = RISCVISD::MRET_FLAG; 9152 } 9153 9154 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 9155 } 9156 9157 void RISCVTargetLowering::validateCCReservedRegs( 9158 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 9159 MachineFunction &MF) const { 9160 const Function &F = MF.getFunction(); 9161 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9162 9163 if (llvm::any_of(Regs, [&STI](auto Reg) { 9164 return STI.isRegisterReservedByUser(Reg.first); 9165 })) 9166 F.getContext().diagnose(DiagnosticInfoUnsupported{ 9167 F, "Argument register required, but has been reserved."}); 9168 } 9169 9170 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 9171 return CI->isTailCall(); 9172 } 9173 9174 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 9175 #define NODE_NAME_CASE(NODE) \ 9176 case RISCVISD::NODE: \ 9177 return "RISCVISD::" #NODE; 9178 // clang-format off 9179 switch ((RISCVISD::NodeType)Opcode) { 9180 case RISCVISD::FIRST_NUMBER: 9181 break; 9182 NODE_NAME_CASE(RET_FLAG) 9183 NODE_NAME_CASE(URET_FLAG) 9184 NODE_NAME_CASE(SRET_FLAG) 9185 NODE_NAME_CASE(MRET_FLAG) 9186 NODE_NAME_CASE(CALL) 9187 NODE_NAME_CASE(SELECT_CC) 9188 NODE_NAME_CASE(BR_CC) 9189 NODE_NAME_CASE(BuildPairF64) 9190 NODE_NAME_CASE(SplitF64) 9191 NODE_NAME_CASE(TAIL) 9192 NODE_NAME_CASE(MULHSU) 9193 NODE_NAME_CASE(SLLW) 9194 NODE_NAME_CASE(SRAW) 9195 NODE_NAME_CASE(SRLW) 9196 NODE_NAME_CASE(DIVW) 9197 NODE_NAME_CASE(DIVUW) 9198 NODE_NAME_CASE(REMUW) 9199 NODE_NAME_CASE(ROLW) 9200 NODE_NAME_CASE(RORW) 9201 NODE_NAME_CASE(CLZW) 9202 NODE_NAME_CASE(CTZW) 9203 NODE_NAME_CASE(FSLW) 9204 NODE_NAME_CASE(FSRW) 9205 NODE_NAME_CASE(FSL) 9206 NODE_NAME_CASE(FSR) 9207 NODE_NAME_CASE(FMV_H_X) 9208 NODE_NAME_CASE(FMV_X_ANYEXTH) 9209 NODE_NAME_CASE(FMV_W_X_RV64) 9210 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 9211 NODE_NAME_CASE(FCVT_X_RTZ) 9212 NODE_NAME_CASE(FCVT_XU_RTZ) 9213 NODE_NAME_CASE(FCVT_W_RTZ_RV64) 9214 NODE_NAME_CASE(FCVT_WU_RTZ_RV64) 9215 NODE_NAME_CASE(READ_CYCLE_WIDE) 9216 NODE_NAME_CASE(GREV) 9217 NODE_NAME_CASE(GREVW) 9218 NODE_NAME_CASE(GORC) 9219 NODE_NAME_CASE(GORCW) 9220 NODE_NAME_CASE(SHFL) 9221 NODE_NAME_CASE(SHFLW) 9222 NODE_NAME_CASE(UNSHFL) 9223 NODE_NAME_CASE(UNSHFLW) 9224 NODE_NAME_CASE(BCOMPRESS) 9225 NODE_NAME_CASE(BCOMPRESSW) 9226 NODE_NAME_CASE(BDECOMPRESS) 9227 NODE_NAME_CASE(BDECOMPRESSW) 9228 NODE_NAME_CASE(VMV_V_X_VL) 9229 NODE_NAME_CASE(VFMV_V_F_VL) 9230 NODE_NAME_CASE(VMV_X_S) 9231 NODE_NAME_CASE(VMV_S_X_VL) 9232 NODE_NAME_CASE(VFMV_S_F_VL) 9233 NODE_NAME_CASE(SPLAT_VECTOR_I64) 9234 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 9235 NODE_NAME_CASE(READ_VLENB) 9236 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 9237 NODE_NAME_CASE(VSLIDEUP_VL) 9238 NODE_NAME_CASE(VSLIDE1UP_VL) 9239 NODE_NAME_CASE(VSLIDEDOWN_VL) 9240 NODE_NAME_CASE(VSLIDE1DOWN_VL) 9241 NODE_NAME_CASE(VID_VL) 9242 NODE_NAME_CASE(VFNCVT_ROD_VL) 9243 NODE_NAME_CASE(VECREDUCE_ADD_VL) 9244 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 9245 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 9246 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 9247 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 9248 NODE_NAME_CASE(VECREDUCE_AND_VL) 9249 NODE_NAME_CASE(VECREDUCE_OR_VL) 9250 NODE_NAME_CASE(VECREDUCE_XOR_VL) 9251 NODE_NAME_CASE(VECREDUCE_FADD_VL) 9252 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 9253 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 9254 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 9255 NODE_NAME_CASE(ADD_VL) 9256 NODE_NAME_CASE(AND_VL) 9257 NODE_NAME_CASE(MUL_VL) 9258 NODE_NAME_CASE(OR_VL) 9259 NODE_NAME_CASE(SDIV_VL) 9260 NODE_NAME_CASE(SHL_VL) 9261 NODE_NAME_CASE(SREM_VL) 9262 NODE_NAME_CASE(SRA_VL) 9263 NODE_NAME_CASE(SRL_VL) 9264 NODE_NAME_CASE(SUB_VL) 9265 NODE_NAME_CASE(UDIV_VL) 9266 NODE_NAME_CASE(UREM_VL) 9267 NODE_NAME_CASE(XOR_VL) 9268 NODE_NAME_CASE(SADDSAT_VL) 9269 NODE_NAME_CASE(UADDSAT_VL) 9270 NODE_NAME_CASE(SSUBSAT_VL) 9271 NODE_NAME_CASE(USUBSAT_VL) 9272 NODE_NAME_CASE(FADD_VL) 9273 NODE_NAME_CASE(FSUB_VL) 9274 NODE_NAME_CASE(FMUL_VL) 9275 NODE_NAME_CASE(FDIV_VL) 9276 NODE_NAME_CASE(FNEG_VL) 9277 NODE_NAME_CASE(FABS_VL) 9278 NODE_NAME_CASE(FSQRT_VL) 9279 NODE_NAME_CASE(FMA_VL) 9280 NODE_NAME_CASE(FCOPYSIGN_VL) 9281 NODE_NAME_CASE(SMIN_VL) 9282 NODE_NAME_CASE(SMAX_VL) 9283 NODE_NAME_CASE(UMIN_VL) 9284 NODE_NAME_CASE(UMAX_VL) 9285 NODE_NAME_CASE(FMINNUM_VL) 9286 NODE_NAME_CASE(FMAXNUM_VL) 9287 NODE_NAME_CASE(MULHS_VL) 9288 NODE_NAME_CASE(MULHU_VL) 9289 NODE_NAME_CASE(FP_TO_SINT_VL) 9290 NODE_NAME_CASE(FP_TO_UINT_VL) 9291 NODE_NAME_CASE(SINT_TO_FP_VL) 9292 NODE_NAME_CASE(UINT_TO_FP_VL) 9293 NODE_NAME_CASE(FP_EXTEND_VL) 9294 NODE_NAME_CASE(FP_ROUND_VL) 9295 NODE_NAME_CASE(VWMUL_VL) 9296 NODE_NAME_CASE(VWMULU_VL) 9297 NODE_NAME_CASE(SETCC_VL) 9298 NODE_NAME_CASE(VSELECT_VL) 9299 NODE_NAME_CASE(VMAND_VL) 9300 NODE_NAME_CASE(VMOR_VL) 9301 NODE_NAME_CASE(VMXOR_VL) 9302 NODE_NAME_CASE(VMCLR_VL) 9303 NODE_NAME_CASE(VMSET_VL) 9304 NODE_NAME_CASE(VRGATHER_VX_VL) 9305 NODE_NAME_CASE(VRGATHER_VV_VL) 9306 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 9307 NODE_NAME_CASE(VSEXT_VL) 9308 NODE_NAME_CASE(VZEXT_VL) 9309 NODE_NAME_CASE(VCPOP_VL) 9310 NODE_NAME_CASE(VLE_VL) 9311 NODE_NAME_CASE(VSE_VL) 9312 NODE_NAME_CASE(READ_CSR) 9313 NODE_NAME_CASE(WRITE_CSR) 9314 NODE_NAME_CASE(SWAP_CSR) 9315 } 9316 // clang-format on 9317 return nullptr; 9318 #undef NODE_NAME_CASE 9319 } 9320 9321 /// getConstraintType - Given a constraint letter, return the type of 9322 /// constraint it is for this target. 9323 RISCVTargetLowering::ConstraintType 9324 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 9325 if (Constraint.size() == 1) { 9326 switch (Constraint[0]) { 9327 default: 9328 break; 9329 case 'f': 9330 return C_RegisterClass; 9331 case 'I': 9332 case 'J': 9333 case 'K': 9334 return C_Immediate; 9335 case 'A': 9336 return C_Memory; 9337 case 'S': // A symbolic address 9338 return C_Other; 9339 } 9340 } else { 9341 if (Constraint == "vr" || Constraint == "vm") 9342 return C_RegisterClass; 9343 } 9344 return TargetLowering::getConstraintType(Constraint); 9345 } 9346 9347 std::pair<unsigned, const TargetRegisterClass *> 9348 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 9349 StringRef Constraint, 9350 MVT VT) const { 9351 // First, see if this is a constraint that directly corresponds to a 9352 // RISCV register class. 9353 if (Constraint.size() == 1) { 9354 switch (Constraint[0]) { 9355 case 'r': 9356 return std::make_pair(0U, &RISCV::GPRRegClass); 9357 case 'f': 9358 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 9359 return std::make_pair(0U, &RISCV::FPR16RegClass); 9360 if (Subtarget.hasStdExtF() && VT == MVT::f32) 9361 return std::make_pair(0U, &RISCV::FPR32RegClass); 9362 if (Subtarget.hasStdExtD() && VT == MVT::f64) 9363 return std::make_pair(0U, &RISCV::FPR64RegClass); 9364 break; 9365 default: 9366 break; 9367 } 9368 } else { 9369 if (Constraint == "vr") { 9370 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 9371 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9372 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 9373 return std::make_pair(0U, RC); 9374 } 9375 } else if (Constraint == "vm") { 9376 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9377 return std::make_pair(0U, &RISCV::VMRegClass); 9378 } 9379 } 9380 9381 // Clang will correctly decode the usage of register name aliases into their 9382 // official names. However, other frontends like `rustc` do not. This allows 9383 // users of these frontends to use the ABI names for registers in LLVM-style 9384 // register constraints. 9385 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 9386 .Case("{zero}", RISCV::X0) 9387 .Case("{ra}", RISCV::X1) 9388 .Case("{sp}", RISCV::X2) 9389 .Case("{gp}", RISCV::X3) 9390 .Case("{tp}", RISCV::X4) 9391 .Case("{t0}", RISCV::X5) 9392 .Case("{t1}", RISCV::X6) 9393 .Case("{t2}", RISCV::X7) 9394 .Cases("{s0}", "{fp}", RISCV::X8) 9395 .Case("{s1}", RISCV::X9) 9396 .Case("{a0}", RISCV::X10) 9397 .Case("{a1}", RISCV::X11) 9398 .Case("{a2}", RISCV::X12) 9399 .Case("{a3}", RISCV::X13) 9400 .Case("{a4}", RISCV::X14) 9401 .Case("{a5}", RISCV::X15) 9402 .Case("{a6}", RISCV::X16) 9403 .Case("{a7}", RISCV::X17) 9404 .Case("{s2}", RISCV::X18) 9405 .Case("{s3}", RISCV::X19) 9406 .Case("{s4}", RISCV::X20) 9407 .Case("{s5}", RISCV::X21) 9408 .Case("{s6}", RISCV::X22) 9409 .Case("{s7}", RISCV::X23) 9410 .Case("{s8}", RISCV::X24) 9411 .Case("{s9}", RISCV::X25) 9412 .Case("{s10}", RISCV::X26) 9413 .Case("{s11}", RISCV::X27) 9414 .Case("{t3}", RISCV::X28) 9415 .Case("{t4}", RISCV::X29) 9416 .Case("{t5}", RISCV::X30) 9417 .Case("{t6}", RISCV::X31) 9418 .Default(RISCV::NoRegister); 9419 if (XRegFromAlias != RISCV::NoRegister) 9420 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 9421 9422 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 9423 // TableGen record rather than the AsmName to choose registers for InlineAsm 9424 // constraints, plus we want to match those names to the widest floating point 9425 // register type available, manually select floating point registers here. 9426 // 9427 // The second case is the ABI name of the register, so that frontends can also 9428 // use the ABI names in register constraint lists. 9429 if (Subtarget.hasStdExtF()) { 9430 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 9431 .Cases("{f0}", "{ft0}", RISCV::F0_F) 9432 .Cases("{f1}", "{ft1}", RISCV::F1_F) 9433 .Cases("{f2}", "{ft2}", RISCV::F2_F) 9434 .Cases("{f3}", "{ft3}", RISCV::F3_F) 9435 .Cases("{f4}", "{ft4}", RISCV::F4_F) 9436 .Cases("{f5}", "{ft5}", RISCV::F5_F) 9437 .Cases("{f6}", "{ft6}", RISCV::F6_F) 9438 .Cases("{f7}", "{ft7}", RISCV::F7_F) 9439 .Cases("{f8}", "{fs0}", RISCV::F8_F) 9440 .Cases("{f9}", "{fs1}", RISCV::F9_F) 9441 .Cases("{f10}", "{fa0}", RISCV::F10_F) 9442 .Cases("{f11}", "{fa1}", RISCV::F11_F) 9443 .Cases("{f12}", "{fa2}", RISCV::F12_F) 9444 .Cases("{f13}", "{fa3}", RISCV::F13_F) 9445 .Cases("{f14}", "{fa4}", RISCV::F14_F) 9446 .Cases("{f15}", "{fa5}", RISCV::F15_F) 9447 .Cases("{f16}", "{fa6}", RISCV::F16_F) 9448 .Cases("{f17}", "{fa7}", RISCV::F17_F) 9449 .Cases("{f18}", "{fs2}", RISCV::F18_F) 9450 .Cases("{f19}", "{fs3}", RISCV::F19_F) 9451 .Cases("{f20}", "{fs4}", RISCV::F20_F) 9452 .Cases("{f21}", "{fs5}", RISCV::F21_F) 9453 .Cases("{f22}", "{fs6}", RISCV::F22_F) 9454 .Cases("{f23}", "{fs7}", RISCV::F23_F) 9455 .Cases("{f24}", "{fs8}", RISCV::F24_F) 9456 .Cases("{f25}", "{fs9}", RISCV::F25_F) 9457 .Cases("{f26}", "{fs10}", RISCV::F26_F) 9458 .Cases("{f27}", "{fs11}", RISCV::F27_F) 9459 .Cases("{f28}", "{ft8}", RISCV::F28_F) 9460 .Cases("{f29}", "{ft9}", RISCV::F29_F) 9461 .Cases("{f30}", "{ft10}", RISCV::F30_F) 9462 .Cases("{f31}", "{ft11}", RISCV::F31_F) 9463 .Default(RISCV::NoRegister); 9464 if (FReg != RISCV::NoRegister) { 9465 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 9466 if (Subtarget.hasStdExtD()) { 9467 unsigned RegNo = FReg - RISCV::F0_F; 9468 unsigned DReg = RISCV::F0_D + RegNo; 9469 return std::make_pair(DReg, &RISCV::FPR64RegClass); 9470 } 9471 return std::make_pair(FReg, &RISCV::FPR32RegClass); 9472 } 9473 } 9474 9475 if (Subtarget.hasVInstructions()) { 9476 Register VReg = StringSwitch<Register>(Constraint.lower()) 9477 .Case("{v0}", RISCV::V0) 9478 .Case("{v1}", RISCV::V1) 9479 .Case("{v2}", RISCV::V2) 9480 .Case("{v3}", RISCV::V3) 9481 .Case("{v4}", RISCV::V4) 9482 .Case("{v5}", RISCV::V5) 9483 .Case("{v6}", RISCV::V6) 9484 .Case("{v7}", RISCV::V7) 9485 .Case("{v8}", RISCV::V8) 9486 .Case("{v9}", RISCV::V9) 9487 .Case("{v10}", RISCV::V10) 9488 .Case("{v11}", RISCV::V11) 9489 .Case("{v12}", RISCV::V12) 9490 .Case("{v13}", RISCV::V13) 9491 .Case("{v14}", RISCV::V14) 9492 .Case("{v15}", RISCV::V15) 9493 .Case("{v16}", RISCV::V16) 9494 .Case("{v17}", RISCV::V17) 9495 .Case("{v18}", RISCV::V18) 9496 .Case("{v19}", RISCV::V19) 9497 .Case("{v20}", RISCV::V20) 9498 .Case("{v21}", RISCV::V21) 9499 .Case("{v22}", RISCV::V22) 9500 .Case("{v23}", RISCV::V23) 9501 .Case("{v24}", RISCV::V24) 9502 .Case("{v25}", RISCV::V25) 9503 .Case("{v26}", RISCV::V26) 9504 .Case("{v27}", RISCV::V27) 9505 .Case("{v28}", RISCV::V28) 9506 .Case("{v29}", RISCV::V29) 9507 .Case("{v30}", RISCV::V30) 9508 .Case("{v31}", RISCV::V31) 9509 .Default(RISCV::NoRegister); 9510 if (VReg != RISCV::NoRegister) { 9511 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9512 return std::make_pair(VReg, &RISCV::VMRegClass); 9513 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 9514 return std::make_pair(VReg, &RISCV::VRRegClass); 9515 for (const auto *RC : 9516 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9517 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 9518 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 9519 return std::make_pair(VReg, RC); 9520 } 9521 } 9522 } 9523 } 9524 9525 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 9526 } 9527 9528 unsigned 9529 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 9530 // Currently only support length 1 constraints. 9531 if (ConstraintCode.size() == 1) { 9532 switch (ConstraintCode[0]) { 9533 case 'A': 9534 return InlineAsm::Constraint_A; 9535 default: 9536 break; 9537 } 9538 } 9539 9540 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 9541 } 9542 9543 void RISCVTargetLowering::LowerAsmOperandForConstraint( 9544 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 9545 SelectionDAG &DAG) const { 9546 // Currently only support length 1 constraints. 9547 if (Constraint.length() == 1) { 9548 switch (Constraint[0]) { 9549 case 'I': 9550 // Validate & create a 12-bit signed immediate operand. 9551 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9552 uint64_t CVal = C->getSExtValue(); 9553 if (isInt<12>(CVal)) 9554 Ops.push_back( 9555 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9556 } 9557 return; 9558 case 'J': 9559 // Validate & create an integer zero operand. 9560 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 9561 if (C->getZExtValue() == 0) 9562 Ops.push_back( 9563 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 9564 return; 9565 case 'K': 9566 // Validate & create a 5-bit unsigned immediate operand. 9567 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9568 uint64_t CVal = C->getZExtValue(); 9569 if (isUInt<5>(CVal)) 9570 Ops.push_back( 9571 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9572 } 9573 return; 9574 case 'S': 9575 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9576 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 9577 GA->getValueType(0))); 9578 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 9579 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 9580 BA->getValueType(0))); 9581 } 9582 return; 9583 default: 9584 break; 9585 } 9586 } 9587 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 9588 } 9589 9590 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 9591 Instruction *Inst, 9592 AtomicOrdering Ord) const { 9593 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 9594 return Builder.CreateFence(Ord); 9595 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 9596 return Builder.CreateFence(AtomicOrdering::Release); 9597 return nullptr; 9598 } 9599 9600 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 9601 Instruction *Inst, 9602 AtomicOrdering Ord) const { 9603 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 9604 return Builder.CreateFence(AtomicOrdering::Acquire); 9605 return nullptr; 9606 } 9607 9608 TargetLowering::AtomicExpansionKind 9609 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 9610 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 9611 // point operations can't be used in an lr/sc sequence without breaking the 9612 // forward-progress guarantee. 9613 if (AI->isFloatingPointOperation()) 9614 return AtomicExpansionKind::CmpXChg; 9615 9616 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 9617 if (Size == 8 || Size == 16) 9618 return AtomicExpansionKind::MaskedIntrinsic; 9619 return AtomicExpansionKind::None; 9620 } 9621 9622 static Intrinsic::ID 9623 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 9624 if (XLen == 32) { 9625 switch (BinOp) { 9626 default: 9627 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9628 case AtomicRMWInst::Xchg: 9629 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 9630 case AtomicRMWInst::Add: 9631 return Intrinsic::riscv_masked_atomicrmw_add_i32; 9632 case AtomicRMWInst::Sub: 9633 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 9634 case AtomicRMWInst::Nand: 9635 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 9636 case AtomicRMWInst::Max: 9637 return Intrinsic::riscv_masked_atomicrmw_max_i32; 9638 case AtomicRMWInst::Min: 9639 return Intrinsic::riscv_masked_atomicrmw_min_i32; 9640 case AtomicRMWInst::UMax: 9641 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 9642 case AtomicRMWInst::UMin: 9643 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 9644 } 9645 } 9646 9647 if (XLen == 64) { 9648 switch (BinOp) { 9649 default: 9650 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9651 case AtomicRMWInst::Xchg: 9652 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 9653 case AtomicRMWInst::Add: 9654 return Intrinsic::riscv_masked_atomicrmw_add_i64; 9655 case AtomicRMWInst::Sub: 9656 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 9657 case AtomicRMWInst::Nand: 9658 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 9659 case AtomicRMWInst::Max: 9660 return Intrinsic::riscv_masked_atomicrmw_max_i64; 9661 case AtomicRMWInst::Min: 9662 return Intrinsic::riscv_masked_atomicrmw_min_i64; 9663 case AtomicRMWInst::UMax: 9664 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 9665 case AtomicRMWInst::UMin: 9666 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 9667 } 9668 } 9669 9670 llvm_unreachable("Unexpected XLen\n"); 9671 } 9672 9673 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 9674 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 9675 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 9676 unsigned XLen = Subtarget.getXLen(); 9677 Value *Ordering = 9678 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 9679 Type *Tys[] = {AlignedAddr->getType()}; 9680 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 9681 AI->getModule(), 9682 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 9683 9684 if (XLen == 64) { 9685 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 9686 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 9687 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 9688 } 9689 9690 Value *Result; 9691 9692 // Must pass the shift amount needed to sign extend the loaded value prior 9693 // to performing a signed comparison for min/max. ShiftAmt is the number of 9694 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 9695 // is the number of bits to left+right shift the value in order to 9696 // sign-extend. 9697 if (AI->getOperation() == AtomicRMWInst::Min || 9698 AI->getOperation() == AtomicRMWInst::Max) { 9699 const DataLayout &DL = AI->getModule()->getDataLayout(); 9700 unsigned ValWidth = 9701 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 9702 Value *SextShamt = 9703 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 9704 Result = Builder.CreateCall(LrwOpScwLoop, 9705 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 9706 } else { 9707 Result = 9708 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 9709 } 9710 9711 if (XLen == 64) 9712 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 9713 return Result; 9714 } 9715 9716 TargetLowering::AtomicExpansionKind 9717 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 9718 AtomicCmpXchgInst *CI) const { 9719 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 9720 if (Size == 8 || Size == 16) 9721 return AtomicExpansionKind::MaskedIntrinsic; 9722 return AtomicExpansionKind::None; 9723 } 9724 9725 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 9726 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 9727 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 9728 unsigned XLen = Subtarget.getXLen(); 9729 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 9730 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 9731 if (XLen == 64) { 9732 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 9733 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 9734 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 9735 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 9736 } 9737 Type *Tys[] = {AlignedAddr->getType()}; 9738 Function *MaskedCmpXchg = 9739 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 9740 Value *Result = Builder.CreateCall( 9741 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 9742 if (XLen == 64) 9743 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 9744 return Result; 9745 } 9746 9747 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 9748 return false; 9749 } 9750 9751 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 9752 EVT VT) const { 9753 VT = VT.getScalarType(); 9754 9755 if (!VT.isSimple()) 9756 return false; 9757 9758 switch (VT.getSimpleVT().SimpleTy) { 9759 case MVT::f16: 9760 return Subtarget.hasStdExtZfh(); 9761 case MVT::f32: 9762 return Subtarget.hasStdExtF(); 9763 case MVT::f64: 9764 return Subtarget.hasStdExtD(); 9765 default: 9766 break; 9767 } 9768 9769 return false; 9770 } 9771 9772 Register RISCVTargetLowering::getExceptionPointerRegister( 9773 const Constant *PersonalityFn) const { 9774 return RISCV::X10; 9775 } 9776 9777 Register RISCVTargetLowering::getExceptionSelectorRegister( 9778 const Constant *PersonalityFn) const { 9779 return RISCV::X11; 9780 } 9781 9782 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 9783 // Return false to suppress the unnecessary extensions if the LibCall 9784 // arguments or return value is f32 type for LP64 ABI. 9785 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 9786 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 9787 return false; 9788 9789 return true; 9790 } 9791 9792 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 9793 if (Subtarget.is64Bit() && Type == MVT::i32) 9794 return true; 9795 9796 return IsSigned; 9797 } 9798 9799 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 9800 SDValue C) const { 9801 // Check integral scalar types. 9802 if (VT.isScalarInteger()) { 9803 // Omit the optimization if the sub target has the M extension and the data 9804 // size exceeds XLen. 9805 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 9806 return false; 9807 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 9808 // Break the MUL to a SLLI and an ADD/SUB. 9809 const APInt &Imm = ConstNode->getAPIntValue(); 9810 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 9811 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 9812 return true; 9813 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 9814 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 9815 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 9816 (Imm - 8).isPowerOf2())) 9817 return true; 9818 // Omit the following optimization if the sub target has the M extension 9819 // and the data size >= XLen. 9820 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 9821 return false; 9822 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 9823 // a pair of LUI/ADDI. 9824 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 9825 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 9826 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 9827 (1 - ImmS).isPowerOf2()) 9828 return true; 9829 } 9830 } 9831 } 9832 9833 return false; 9834 } 9835 9836 bool RISCVTargetLowering::isMulAddWithConstProfitable( 9837 const SDValue &AddNode, const SDValue &ConstNode) const { 9838 // Let the DAGCombiner decide for vectors. 9839 EVT VT = AddNode.getValueType(); 9840 if (VT.isVector()) 9841 return true; 9842 9843 // Let the DAGCombiner decide for larger types. 9844 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 9845 return true; 9846 9847 // It is worse if c1 is simm12 while c1*c2 is not. 9848 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 9849 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 9850 const APInt &C1 = C1Node->getAPIntValue(); 9851 const APInt &C2 = C2Node->getAPIntValue(); 9852 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 9853 return false; 9854 9855 // Default to true and let the DAGCombiner decide. 9856 return true; 9857 } 9858 9859 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 9860 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 9861 bool *Fast) const { 9862 if (!VT.isVector()) 9863 return false; 9864 9865 EVT ElemVT = VT.getVectorElementType(); 9866 if (Alignment >= ElemVT.getStoreSize()) { 9867 if (Fast) 9868 *Fast = true; 9869 return true; 9870 } 9871 9872 return false; 9873 } 9874 9875 bool RISCVTargetLowering::splitValueIntoRegisterParts( 9876 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 9877 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 9878 bool IsABIRegCopy = CC.hasValue(); 9879 EVT ValueVT = Val.getValueType(); 9880 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 9881 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 9882 // and cast to f32. 9883 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 9884 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 9885 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 9886 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 9887 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 9888 Parts[0] = Val; 9889 return true; 9890 } 9891 9892 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 9893 LLVMContext &Context = *DAG.getContext(); 9894 EVT ValueEltVT = ValueVT.getVectorElementType(); 9895 EVT PartEltVT = PartVT.getVectorElementType(); 9896 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 9897 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 9898 if (PartVTBitSize % ValueVTBitSize == 0) { 9899 // If the element types are different, bitcast to the same element type of 9900 // PartVT first. 9901 if (ValueEltVT != PartEltVT) { 9902 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 9903 assert(Count != 0 && "The number of element should not be zero."); 9904 EVT SameEltTypeVT = 9905 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 9906 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 9907 } 9908 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 9909 Val, DAG.getConstant(0, DL, Subtarget.getXLenVT())); 9910 Parts[0] = Val; 9911 return true; 9912 } 9913 } 9914 return false; 9915 } 9916 9917 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 9918 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 9919 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 9920 bool IsABIRegCopy = CC.hasValue(); 9921 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 9922 SDValue Val = Parts[0]; 9923 9924 // Cast the f32 to i32, truncate to i16, and cast back to f16. 9925 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 9926 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 9927 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 9928 return Val; 9929 } 9930 9931 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 9932 LLVMContext &Context = *DAG.getContext(); 9933 SDValue Val = Parts[0]; 9934 EVT ValueEltVT = ValueVT.getVectorElementType(); 9935 EVT PartEltVT = PartVT.getVectorElementType(); 9936 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 9937 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 9938 if (PartVTBitSize % ValueVTBitSize == 0) { 9939 EVT SameEltTypeVT = ValueVT; 9940 // If the element types are different, convert it to the same element type 9941 // of PartVT. 9942 if (ValueEltVT != PartEltVT) { 9943 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 9944 assert(Count != 0 && "The number of element should not be zero."); 9945 SameEltTypeVT = 9946 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 9947 } 9948 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val, 9949 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 9950 if (ValueEltVT != PartEltVT) 9951 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 9952 return Val; 9953 } 9954 } 9955 return SDValue(); 9956 } 9957 9958 #define GET_REGISTER_MATCHER 9959 #include "RISCVGenAsmMatcher.inc" 9960 9961 Register 9962 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 9963 const MachineFunction &MF) const { 9964 Register Reg = MatchRegisterAltName(RegName); 9965 if (Reg == RISCV::NoRegister) 9966 Reg = MatchRegisterName(RegName); 9967 if (Reg == RISCV::NoRegister) 9968 report_fatal_error( 9969 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 9970 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 9971 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 9972 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 9973 StringRef(RegName) + "\".")); 9974 return Reg; 9975 } 9976 9977 namespace llvm { 9978 namespace RISCVVIntrinsicsTable { 9979 9980 #define GET_RISCVVIntrinsicsTable_IMPL 9981 #include "RISCVGenSearchableTables.inc" 9982 9983 } // namespace RISCVVIntrinsicsTable 9984 9985 } // namespace llvm 9986