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/CodeGen/MachineFrameInfo.h" 24 #include "llvm/CodeGen/MachineFunction.h" 25 #include "llvm/CodeGen/MachineInstrBuilder.h" 26 #include "llvm/CodeGen/MachineRegisterInfo.h" 27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 28 #include "llvm/CodeGen/ValueTypes.h" 29 #include "llvm/IR/DiagnosticInfo.h" 30 #include "llvm/IR/DiagnosticPrinter.h" 31 #include "llvm/IR/IntrinsicsRISCV.h" 32 #include "llvm/IR/IRBuilder.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/KnownBits.h" 36 #include "llvm/Support/MathExtras.h" 37 #include "llvm/Support/raw_ostream.h" 38 39 using namespace llvm; 40 41 #define DEBUG_TYPE "riscv-lower" 42 43 STATISTIC(NumTailCalls, "Number of tail calls"); 44 45 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 46 const RISCVSubtarget &STI) 47 : TargetLowering(TM), Subtarget(STI) { 48 49 if (Subtarget.isRV32E()) 50 report_fatal_error("Codegen not yet implemented for RV32E"); 51 52 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 53 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 54 55 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 56 !Subtarget.hasStdExtF()) { 57 errs() << "Hard-float 'f' ABI can't be used for a target that " 58 "doesn't support the F instruction set extension (ignoring " 59 "target-abi)\n"; 60 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 61 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 62 !Subtarget.hasStdExtD()) { 63 errs() << "Hard-float 'd' ABI can't be used for a target that " 64 "doesn't support the D instruction set extension (ignoring " 65 "target-abi)\n"; 66 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 67 } 68 69 switch (ABI) { 70 default: 71 report_fatal_error("Don't know how to lower this ABI"); 72 case RISCVABI::ABI_ILP32: 73 case RISCVABI::ABI_ILP32F: 74 case RISCVABI::ABI_ILP32D: 75 case RISCVABI::ABI_LP64: 76 case RISCVABI::ABI_LP64F: 77 case RISCVABI::ABI_LP64D: 78 break; 79 } 80 81 MVT XLenVT = Subtarget.getXLenVT(); 82 83 // Set up the register classes. 84 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 85 86 if (Subtarget.hasStdExtZfh()) 87 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 88 if (Subtarget.hasStdExtF()) 89 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 90 if (Subtarget.hasStdExtD()) 91 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 92 93 static const MVT::SimpleValueType BoolVecVTs[] = { 94 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 95 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 96 static const MVT::SimpleValueType IntVecVTs[] = { 97 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 98 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 99 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 100 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 101 MVT::nxv4i64, MVT::nxv8i64}; 102 static const MVT::SimpleValueType F16VecVTs[] = { 103 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 104 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 105 static const MVT::SimpleValueType F32VecVTs[] = { 106 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 107 static const MVT::SimpleValueType F64VecVTs[] = { 108 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 109 110 if (Subtarget.hasStdExtV()) { 111 auto addRegClassForRVV = [this](MVT VT) { 112 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 113 assert(Size <= 512 && isPowerOf2_32(Size)); 114 const TargetRegisterClass *RC; 115 if (Size <= 64) 116 RC = &RISCV::VRRegClass; 117 else if (Size == 128) 118 RC = &RISCV::VRM2RegClass; 119 else if (Size == 256) 120 RC = &RISCV::VRM4RegClass; 121 else 122 RC = &RISCV::VRM8RegClass; 123 124 addRegisterClass(VT, RC); 125 }; 126 127 for (MVT VT : BoolVecVTs) 128 addRegClassForRVV(VT); 129 for (MVT VT : IntVecVTs) 130 addRegClassForRVV(VT); 131 132 if (Subtarget.hasStdExtZfh()) 133 for (MVT VT : F16VecVTs) 134 addRegClassForRVV(VT); 135 136 if (Subtarget.hasStdExtF()) 137 for (MVT VT : F32VecVTs) 138 addRegClassForRVV(VT); 139 140 if (Subtarget.hasStdExtD()) 141 for (MVT VT : F64VecVTs) 142 addRegClassForRVV(VT); 143 144 if (Subtarget.useRVVForFixedLengthVectors()) { 145 auto addRegClassForFixedVectors = [this](MVT VT) { 146 MVT ContainerVT = getContainerForFixedLengthVector(VT); 147 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 148 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 149 addRegisterClass(VT, TRI.getRegClass(RCID)); 150 }; 151 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 152 if (useRVVForFixedLengthVectorVT(VT)) 153 addRegClassForFixedVectors(VT); 154 155 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 156 if (useRVVForFixedLengthVectorVT(VT)) 157 addRegClassForFixedVectors(VT); 158 } 159 } 160 161 // Compute derived properties from the register classes. 162 computeRegisterProperties(STI.getRegisterInfo()); 163 164 setStackPointerRegisterToSaveRestore(RISCV::X2); 165 166 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 167 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 168 169 // TODO: add all necessary setOperationAction calls. 170 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 171 172 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 173 setOperationAction(ISD::BR_CC, XLenVT, Expand); 174 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 175 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 176 177 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 178 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 179 180 setOperationAction(ISD::VASTART, MVT::Other, Custom); 181 setOperationAction(ISD::VAARG, MVT::Other, Expand); 182 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 183 setOperationAction(ISD::VAEND, MVT::Other, Expand); 184 185 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 186 if (!Subtarget.hasStdExtZbb()) { 187 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 188 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 189 } 190 191 if (Subtarget.is64Bit()) { 192 setOperationAction(ISD::ADD, MVT::i32, Custom); 193 setOperationAction(ISD::SUB, MVT::i32, Custom); 194 setOperationAction(ISD::SHL, MVT::i32, Custom); 195 setOperationAction(ISD::SRA, MVT::i32, Custom); 196 setOperationAction(ISD::SRL, MVT::i32, Custom); 197 198 setOperationAction(ISD::UADDO, MVT::i32, Custom); 199 setOperationAction(ISD::USUBO, MVT::i32, Custom); 200 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 201 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 202 } 203 204 if (!Subtarget.hasStdExtM()) { 205 setOperationAction(ISD::MUL, XLenVT, Expand); 206 setOperationAction(ISD::MULHS, XLenVT, Expand); 207 setOperationAction(ISD::MULHU, XLenVT, Expand); 208 setOperationAction(ISD::SDIV, XLenVT, Expand); 209 setOperationAction(ISD::UDIV, XLenVT, Expand); 210 setOperationAction(ISD::SREM, XLenVT, Expand); 211 setOperationAction(ISD::UREM, XLenVT, Expand); 212 } else { 213 if (Subtarget.is64Bit()) { 214 setOperationAction(ISD::MUL, MVT::i32, Custom); 215 setOperationAction(ISD::MUL, MVT::i128, Custom); 216 217 setOperationAction(ISD::SDIV, MVT::i8, Custom); 218 setOperationAction(ISD::UDIV, MVT::i8, Custom); 219 setOperationAction(ISD::UREM, MVT::i8, Custom); 220 setOperationAction(ISD::SDIV, MVT::i16, Custom); 221 setOperationAction(ISD::UDIV, MVT::i16, Custom); 222 setOperationAction(ISD::UREM, MVT::i16, Custom); 223 setOperationAction(ISD::SDIV, MVT::i32, Custom); 224 setOperationAction(ISD::UDIV, MVT::i32, Custom); 225 setOperationAction(ISD::UREM, MVT::i32, Custom); 226 } else { 227 setOperationAction(ISD::MUL, MVT::i64, Custom); 228 } 229 } 230 231 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 232 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 233 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 234 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 235 236 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 237 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 238 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 239 240 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 241 if (Subtarget.is64Bit()) { 242 setOperationAction(ISD::ROTL, MVT::i32, Custom); 243 setOperationAction(ISD::ROTR, MVT::i32, Custom); 244 } 245 } else { 246 setOperationAction(ISD::ROTL, XLenVT, Expand); 247 setOperationAction(ISD::ROTR, XLenVT, Expand); 248 } 249 250 if (Subtarget.hasStdExtZbp()) { 251 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 252 // more combining. 253 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 254 setOperationAction(ISD::BSWAP, XLenVT, Custom); 255 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 256 // BSWAP i8 doesn't exist. 257 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 258 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 259 260 if (Subtarget.is64Bit()) { 261 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 262 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 263 } 264 } else { 265 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 266 // pattern match it directly in isel. 267 setOperationAction(ISD::BSWAP, XLenVT, 268 Subtarget.hasStdExtZbb() ? Legal : Expand); 269 } 270 271 if (Subtarget.hasStdExtZbb()) { 272 setOperationAction(ISD::SMIN, XLenVT, Legal); 273 setOperationAction(ISD::SMAX, XLenVT, Legal); 274 setOperationAction(ISD::UMIN, XLenVT, Legal); 275 setOperationAction(ISD::UMAX, XLenVT, Legal); 276 277 if (Subtarget.is64Bit()) { 278 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 279 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 280 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 281 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 282 } 283 } else { 284 setOperationAction(ISD::CTTZ, XLenVT, Expand); 285 setOperationAction(ISD::CTLZ, XLenVT, Expand); 286 setOperationAction(ISD::CTPOP, XLenVT, Expand); 287 } 288 289 if (Subtarget.hasStdExtZbt()) { 290 setOperationAction(ISD::FSHL, XLenVT, Custom); 291 setOperationAction(ISD::FSHR, XLenVT, Custom); 292 setOperationAction(ISD::SELECT, XLenVT, Legal); 293 294 if (Subtarget.is64Bit()) { 295 setOperationAction(ISD::FSHL, MVT::i32, Custom); 296 setOperationAction(ISD::FSHR, MVT::i32, Custom); 297 } 298 } else { 299 setOperationAction(ISD::SELECT, XLenVT, Custom); 300 } 301 302 ISD::CondCode FPCCToExpand[] = { 303 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 304 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 305 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 306 307 ISD::NodeType FPOpToExpand[] = { 308 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP, 309 ISD::FP_TO_FP16}; 310 311 if (Subtarget.hasStdExtZfh()) 312 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 313 314 if (Subtarget.hasStdExtZfh()) { 315 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 316 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 317 setOperationAction(ISD::LRINT, MVT::f16, Legal); 318 setOperationAction(ISD::LLRINT, MVT::f16, Legal); 319 setOperationAction(ISD::LROUND, MVT::f16, Legal); 320 setOperationAction(ISD::LLROUND, MVT::f16, Legal); 321 for (auto CC : FPCCToExpand) 322 setCondCodeAction(CC, MVT::f16, Expand); 323 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 324 setOperationAction(ISD::SELECT, MVT::f16, Custom); 325 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 326 for (auto Op : FPOpToExpand) 327 setOperationAction(Op, MVT::f16, Expand); 328 } 329 330 if (Subtarget.hasStdExtF()) { 331 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 332 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 333 setOperationAction(ISD::LRINT, MVT::f32, Legal); 334 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 335 setOperationAction(ISD::LROUND, MVT::f32, Legal); 336 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 337 for (auto CC : FPCCToExpand) 338 setCondCodeAction(CC, MVT::f32, Expand); 339 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 340 setOperationAction(ISD::SELECT, MVT::f32, Custom); 341 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 342 for (auto Op : FPOpToExpand) 343 setOperationAction(Op, MVT::f32, Expand); 344 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 345 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 346 } 347 348 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 349 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 350 351 if (Subtarget.hasStdExtD()) { 352 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 353 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 354 setOperationAction(ISD::LRINT, MVT::f64, Legal); 355 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 356 setOperationAction(ISD::LROUND, MVT::f64, Legal); 357 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 358 for (auto CC : FPCCToExpand) 359 setCondCodeAction(CC, MVT::f64, Expand); 360 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 361 setOperationAction(ISD::SELECT, MVT::f64, Custom); 362 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 363 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 364 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 365 for (auto Op : FPOpToExpand) 366 setOperationAction(Op, MVT::f64, Expand); 367 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 368 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 369 } 370 371 if (Subtarget.is64Bit()) { 372 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 373 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 374 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 375 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 376 } 377 378 if (Subtarget.hasStdExtF()) { 379 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 380 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 381 382 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 383 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 384 } 385 386 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 387 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 388 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 389 setOperationAction(ISD::JumpTable, XLenVT, Custom); 390 391 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 392 393 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 394 // Unfortunately this can't be determined just from the ISA naming string. 395 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 396 Subtarget.is64Bit() ? Legal : Custom); 397 398 setOperationAction(ISD::TRAP, MVT::Other, Legal); 399 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 400 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 401 if (Subtarget.is64Bit()) 402 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 403 404 if (Subtarget.hasStdExtA()) { 405 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 406 setMinCmpXchgSizeInBits(32); 407 } else { 408 setMaxAtomicSizeInBitsSupported(0); 409 } 410 411 setBooleanContents(ZeroOrOneBooleanContent); 412 413 if (Subtarget.hasStdExtV()) { 414 setBooleanVectorContents(ZeroOrOneBooleanContent); 415 416 setOperationAction(ISD::VSCALE, XLenVT, Custom); 417 418 // RVV intrinsics may have illegal operands. 419 // We also need to custom legalize vmv.x.s. 420 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 421 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 422 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 423 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 424 if (Subtarget.is64Bit()) { 425 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 426 } else { 427 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 428 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 429 } 430 431 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 432 433 static unsigned IntegerVPOps[] = { 434 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, ISD::VP_SDIV, ISD::VP_UDIV, 435 ISD::VP_SREM, ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, 436 ISD::VP_ASHR, ISD::VP_LSHR, ISD::VP_SHL}; 437 438 static unsigned FloatingPointVPOps[] = {ISD::VP_FADD, ISD::VP_FSUB, 439 ISD::VP_FMUL, ISD::VP_FDIV}; 440 441 if (!Subtarget.is64Bit()) { 442 // We must custom-lower certain vXi64 operations on RV32 due to the vector 443 // element type being illegal. 444 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 445 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 446 447 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 448 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 449 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 450 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 451 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 452 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 453 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 454 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 455 } 456 457 for (MVT VT : BoolVecVTs) { 458 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 459 460 // Mask VTs are custom-expanded into a series of standard nodes 461 setOperationAction(ISD::TRUNCATE, VT, Custom); 462 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 463 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 464 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 465 466 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 467 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 468 469 setOperationAction(ISD::SELECT, VT, Custom); 470 setOperationAction(ISD::SELECT_CC, VT, Expand); 471 setOperationAction(ISD::VSELECT, VT, Expand); 472 473 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 474 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 475 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 476 477 // RVV has native int->float & float->int conversions where the 478 // element type sizes are within one power-of-two of each other. Any 479 // wider distances between type sizes have to be lowered as sequences 480 // which progressively narrow the gap in stages. 481 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 482 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 483 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 484 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 485 486 // Expand all extending loads to types larger than this, and truncating 487 // stores from types larger than this. 488 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 489 setTruncStoreAction(OtherVT, VT, Expand); 490 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 491 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 492 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 493 } 494 } 495 496 for (MVT VT : IntVecVTs) { 497 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 498 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 499 500 setOperationAction(ISD::SMIN, VT, Legal); 501 setOperationAction(ISD::SMAX, VT, Legal); 502 setOperationAction(ISD::UMIN, VT, Legal); 503 setOperationAction(ISD::UMAX, VT, Legal); 504 505 setOperationAction(ISD::ROTL, VT, Expand); 506 setOperationAction(ISD::ROTR, VT, Expand); 507 508 // Custom-lower extensions and truncations from/to mask types. 509 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 510 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 511 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 512 513 // RVV has native int->float & float->int conversions where the 514 // element type sizes are within one power-of-two of each other. Any 515 // wider distances between type sizes have to be lowered as sequences 516 // which progressively narrow the gap in stages. 517 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 518 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 519 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 520 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 521 522 setOperationAction(ISD::SADDSAT, VT, Legal); 523 setOperationAction(ISD::UADDSAT, VT, Legal); 524 setOperationAction(ISD::SSUBSAT, VT, Legal); 525 setOperationAction(ISD::USUBSAT, VT, Legal); 526 527 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 528 // nodes which truncate by one power of two at a time. 529 setOperationAction(ISD::TRUNCATE, VT, Custom); 530 531 // Custom-lower insert/extract operations to simplify patterns. 532 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 533 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 534 535 // Custom-lower reduction operations to set up the corresponding custom 536 // nodes' operands. 537 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 538 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 539 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 540 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 541 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 542 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 543 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 544 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 545 546 for (unsigned VPOpc : IntegerVPOps) 547 setOperationAction(VPOpc, VT, Custom); 548 549 setOperationAction(ISD::LOAD, VT, Custom); 550 setOperationAction(ISD::STORE, VT, Custom); 551 552 setOperationAction(ISD::MLOAD, VT, Custom); 553 setOperationAction(ISD::MSTORE, VT, Custom); 554 setOperationAction(ISD::MGATHER, VT, Custom); 555 setOperationAction(ISD::MSCATTER, VT, Custom); 556 557 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 558 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 559 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 560 561 setOperationAction(ISD::SELECT, VT, Custom); 562 setOperationAction(ISD::SELECT_CC, VT, Expand); 563 564 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 565 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 566 567 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 568 setTruncStoreAction(VT, OtherVT, Expand); 569 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 570 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 571 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 572 } 573 } 574 575 // Expand various CCs to best match the RVV ISA, which natively supports UNE 576 // but no other unordered comparisons, and supports all ordered comparisons 577 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 578 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 579 // and we pattern-match those back to the "original", swapping operands once 580 // more. This way we catch both operations and both "vf" and "fv" forms with 581 // fewer patterns. 582 ISD::CondCode VFPCCToExpand[] = { 583 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 584 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 585 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 586 }; 587 588 // Sets common operation actions on RVV floating-point vector types. 589 const auto SetCommonVFPActions = [&](MVT VT) { 590 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 591 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 592 // sizes are within one power-of-two of each other. Therefore conversions 593 // between vXf16 and vXf64 must be lowered as sequences which convert via 594 // vXf32. 595 setOperationAction(ISD::FP_ROUND, VT, Custom); 596 setOperationAction(ISD::FP_EXTEND, VT, Custom); 597 // Custom-lower insert/extract operations to simplify patterns. 598 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 599 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 600 // Expand various condition codes (explained above). 601 for (auto CC : VFPCCToExpand) 602 setCondCodeAction(CC, VT, Expand); 603 604 setOperationAction(ISD::FMINNUM, VT, Legal); 605 setOperationAction(ISD::FMAXNUM, VT, Legal); 606 607 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 608 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 609 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 610 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 611 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 612 613 setOperationAction(ISD::LOAD, VT, Custom); 614 setOperationAction(ISD::STORE, VT, Custom); 615 616 setOperationAction(ISD::MLOAD, VT, Custom); 617 setOperationAction(ISD::MSTORE, VT, Custom); 618 setOperationAction(ISD::MGATHER, VT, Custom); 619 setOperationAction(ISD::MSCATTER, VT, Custom); 620 621 setOperationAction(ISD::SELECT, VT, Custom); 622 setOperationAction(ISD::SELECT_CC, VT, Expand); 623 624 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 625 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 626 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 627 628 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 629 630 for (unsigned VPOpc : FloatingPointVPOps) 631 setOperationAction(VPOpc, VT, Custom); 632 }; 633 634 // Sets common extload/truncstore actions on RVV floating-point vector 635 // types. 636 const auto SetCommonVFPExtLoadTruncStoreActions = 637 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 638 for (auto SmallVT : SmallerVTs) { 639 setTruncStoreAction(VT, SmallVT, Expand); 640 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 641 } 642 }; 643 644 if (Subtarget.hasStdExtZfh()) 645 for (MVT VT : F16VecVTs) 646 SetCommonVFPActions(VT); 647 648 for (MVT VT : F32VecVTs) { 649 if (Subtarget.hasStdExtF()) 650 SetCommonVFPActions(VT); 651 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 652 } 653 654 for (MVT VT : F64VecVTs) { 655 if (Subtarget.hasStdExtD()) 656 SetCommonVFPActions(VT); 657 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 658 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 659 } 660 661 if (Subtarget.useRVVForFixedLengthVectors()) { 662 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 663 if (!useRVVForFixedLengthVectorVT(VT)) 664 continue; 665 666 // By default everything must be expanded. 667 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 668 setOperationAction(Op, VT, Expand); 669 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 670 setTruncStoreAction(VT, OtherVT, Expand); 671 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 672 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 673 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 674 } 675 676 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 677 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 678 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 679 680 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 681 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 682 683 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 684 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 685 686 setOperationAction(ISD::LOAD, VT, Custom); 687 setOperationAction(ISD::STORE, VT, Custom); 688 689 setOperationAction(ISD::SETCC, VT, Custom); 690 691 setOperationAction(ISD::SELECT, VT, Custom); 692 693 setOperationAction(ISD::TRUNCATE, VT, Custom); 694 695 setOperationAction(ISD::BITCAST, VT, Custom); 696 697 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 698 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 699 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 700 701 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 702 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 703 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 704 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 705 706 // Operations below are different for between masks and other vectors. 707 if (VT.getVectorElementType() == MVT::i1) { 708 setOperationAction(ISD::AND, VT, Custom); 709 setOperationAction(ISD::OR, VT, Custom); 710 setOperationAction(ISD::XOR, VT, Custom); 711 continue; 712 } 713 714 // Use SPLAT_VECTOR to prevent type legalization from destroying the 715 // splats when type legalizing i64 scalar on RV32. 716 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 717 // improvements first. 718 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 719 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 720 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 721 } 722 723 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 724 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 725 726 setOperationAction(ISD::MLOAD, VT, Custom); 727 setOperationAction(ISD::MSTORE, VT, Custom); 728 setOperationAction(ISD::MGATHER, VT, Custom); 729 setOperationAction(ISD::MSCATTER, VT, Custom); 730 setOperationAction(ISD::ADD, VT, Custom); 731 setOperationAction(ISD::MUL, VT, Custom); 732 setOperationAction(ISD::SUB, VT, Custom); 733 setOperationAction(ISD::AND, VT, Custom); 734 setOperationAction(ISD::OR, VT, Custom); 735 setOperationAction(ISD::XOR, VT, Custom); 736 setOperationAction(ISD::SDIV, VT, Custom); 737 setOperationAction(ISD::SREM, VT, Custom); 738 setOperationAction(ISD::UDIV, VT, Custom); 739 setOperationAction(ISD::UREM, VT, Custom); 740 setOperationAction(ISD::SHL, VT, Custom); 741 setOperationAction(ISD::SRA, VT, Custom); 742 setOperationAction(ISD::SRL, VT, Custom); 743 744 setOperationAction(ISD::SMIN, VT, Custom); 745 setOperationAction(ISD::SMAX, VT, Custom); 746 setOperationAction(ISD::UMIN, VT, Custom); 747 setOperationAction(ISD::UMAX, VT, Custom); 748 setOperationAction(ISD::ABS, VT, Custom); 749 750 setOperationAction(ISD::MULHS, VT, Custom); 751 setOperationAction(ISD::MULHU, VT, Custom); 752 753 setOperationAction(ISD::SADDSAT, VT, Custom); 754 setOperationAction(ISD::UADDSAT, VT, Custom); 755 setOperationAction(ISD::SSUBSAT, VT, Custom); 756 setOperationAction(ISD::USUBSAT, VT, Custom); 757 758 setOperationAction(ISD::VSELECT, VT, Custom); 759 setOperationAction(ISD::SELECT_CC, VT, Expand); 760 761 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 762 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 763 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 764 765 // Custom-lower reduction operations to set up the corresponding custom 766 // nodes' operands. 767 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 768 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 769 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 770 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 771 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 772 773 for (unsigned VPOpc : IntegerVPOps) 774 setOperationAction(VPOpc, VT, Custom); 775 } 776 777 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 778 if (!useRVVForFixedLengthVectorVT(VT)) 779 continue; 780 781 // By default everything must be expanded. 782 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 783 setOperationAction(Op, VT, Expand); 784 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 785 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 786 setTruncStoreAction(VT, OtherVT, Expand); 787 } 788 789 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 790 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 791 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 792 793 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 794 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 795 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 796 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 797 798 setOperationAction(ISD::LOAD, VT, Custom); 799 setOperationAction(ISD::STORE, VT, Custom); 800 setOperationAction(ISD::MLOAD, VT, Custom); 801 setOperationAction(ISD::MSTORE, VT, Custom); 802 setOperationAction(ISD::MGATHER, VT, Custom); 803 setOperationAction(ISD::MSCATTER, VT, Custom); 804 setOperationAction(ISD::FADD, VT, Custom); 805 setOperationAction(ISD::FSUB, VT, Custom); 806 setOperationAction(ISD::FMUL, VT, Custom); 807 setOperationAction(ISD::FDIV, VT, Custom); 808 setOperationAction(ISD::FNEG, VT, Custom); 809 setOperationAction(ISD::FABS, VT, Custom); 810 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 811 setOperationAction(ISD::FSQRT, VT, Custom); 812 setOperationAction(ISD::FMA, VT, Custom); 813 setOperationAction(ISD::FMINNUM, VT, Custom); 814 setOperationAction(ISD::FMAXNUM, VT, Custom); 815 816 setOperationAction(ISD::FP_ROUND, VT, Custom); 817 setOperationAction(ISD::FP_EXTEND, VT, Custom); 818 819 for (auto CC : VFPCCToExpand) 820 setCondCodeAction(CC, VT, Expand); 821 822 setOperationAction(ISD::VSELECT, VT, Custom); 823 setOperationAction(ISD::SELECT, VT, Custom); 824 setOperationAction(ISD::SELECT_CC, VT, Expand); 825 826 setOperationAction(ISD::BITCAST, VT, Custom); 827 828 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 829 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 830 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 831 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 832 833 for (unsigned VPOpc : FloatingPointVPOps) 834 setOperationAction(VPOpc, VT, Custom); 835 } 836 837 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 838 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 839 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 840 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 841 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 842 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 843 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 844 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 845 } 846 } 847 848 // Function alignments. 849 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 850 setMinFunctionAlignment(FunctionAlignment); 851 setPrefFunctionAlignment(FunctionAlignment); 852 853 setMinimumJumpTableEntries(5); 854 855 // Jumps are expensive, compared to logic 856 setJumpIsExpensive(); 857 858 // We can use any register for comparisons 859 setHasMultipleConditionRegisters(); 860 861 setTargetDAGCombine(ISD::ADD); 862 setTargetDAGCombine(ISD::SUB); 863 setTargetDAGCombine(ISD::AND); 864 setTargetDAGCombine(ISD::OR); 865 setTargetDAGCombine(ISD::XOR); 866 setTargetDAGCombine(ISD::ANY_EXTEND); 867 setTargetDAGCombine(ISD::ZERO_EXTEND); 868 if (Subtarget.hasStdExtV()) { 869 setTargetDAGCombine(ISD::FCOPYSIGN); 870 setTargetDAGCombine(ISD::MGATHER); 871 setTargetDAGCombine(ISD::MSCATTER); 872 setTargetDAGCombine(ISD::SRA); 873 setTargetDAGCombine(ISD::SRL); 874 setTargetDAGCombine(ISD::SHL); 875 } 876 } 877 878 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 879 LLVMContext &Context, 880 EVT VT) const { 881 if (!VT.isVector()) 882 return getPointerTy(DL); 883 if (Subtarget.hasStdExtV() && 884 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 885 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 886 return VT.changeVectorElementTypeToInteger(); 887 } 888 889 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 890 return Subtarget.getXLenVT(); 891 } 892 893 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 894 const CallInst &I, 895 MachineFunction &MF, 896 unsigned Intrinsic) const { 897 switch (Intrinsic) { 898 default: 899 return false; 900 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 901 case Intrinsic::riscv_masked_atomicrmw_add_i32: 902 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 903 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 904 case Intrinsic::riscv_masked_atomicrmw_max_i32: 905 case Intrinsic::riscv_masked_atomicrmw_min_i32: 906 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 907 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 908 case Intrinsic::riscv_masked_cmpxchg_i32: { 909 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 910 Info.opc = ISD::INTRINSIC_W_CHAIN; 911 Info.memVT = MVT::getVT(PtrTy->getElementType()); 912 Info.ptrVal = I.getArgOperand(0); 913 Info.offset = 0; 914 Info.align = Align(4); 915 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 916 MachineMemOperand::MOVolatile; 917 return true; 918 } 919 } 920 } 921 922 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 923 const AddrMode &AM, Type *Ty, 924 unsigned AS, 925 Instruction *I) const { 926 // No global is ever allowed as a base. 927 if (AM.BaseGV) 928 return false; 929 930 // Require a 12-bit signed offset. 931 if (!isInt<12>(AM.BaseOffs)) 932 return false; 933 934 switch (AM.Scale) { 935 case 0: // "r+i" or just "i", depending on HasBaseReg. 936 break; 937 case 1: 938 if (!AM.HasBaseReg) // allow "r+i". 939 break; 940 return false; // disallow "r+r" or "r+r+i". 941 default: 942 return false; 943 } 944 945 return true; 946 } 947 948 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 949 return isInt<12>(Imm); 950 } 951 952 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 953 return isInt<12>(Imm); 954 } 955 956 // On RV32, 64-bit integers are split into their high and low parts and held 957 // in two different registers, so the trunc is free since the low register can 958 // just be used. 959 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 960 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 961 return false; 962 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 963 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 964 return (SrcBits == 64 && DestBits == 32); 965 } 966 967 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 968 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 969 !SrcVT.isInteger() || !DstVT.isInteger()) 970 return false; 971 unsigned SrcBits = SrcVT.getSizeInBits(); 972 unsigned DestBits = DstVT.getSizeInBits(); 973 return (SrcBits == 64 && DestBits == 32); 974 } 975 976 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 977 // Zexts are free if they can be combined with a load. 978 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 979 EVT MemVT = LD->getMemoryVT(); 980 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 981 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 982 (LD->getExtensionType() == ISD::NON_EXTLOAD || 983 LD->getExtensionType() == ISD::ZEXTLOAD)) 984 return true; 985 } 986 987 return TargetLowering::isZExtFree(Val, VT2); 988 } 989 990 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 991 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 992 } 993 994 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 995 return Subtarget.hasStdExtZbb(); 996 } 997 998 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 999 return Subtarget.hasStdExtZbb(); 1000 } 1001 1002 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1003 bool ForCodeSize) const { 1004 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1005 return false; 1006 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1007 return false; 1008 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1009 return false; 1010 if (Imm.isNegZero()) 1011 return false; 1012 return Imm.isZero(); 1013 } 1014 1015 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1016 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1017 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1018 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1019 } 1020 1021 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1022 CallingConv::ID CC, 1023 EVT VT) const { 1024 // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still 1025 // end up using a GPR but that will be decided based on ABI. 1026 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1027 return MVT::f32; 1028 1029 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1030 } 1031 1032 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1033 CallingConv::ID CC, 1034 EVT VT) const { 1035 // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still 1036 // end up using a GPR but that will be decided based on ABI. 1037 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1038 return 1; 1039 1040 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1041 } 1042 1043 // Changes the condition code and swaps operands if necessary, so the SetCC 1044 // operation matches one of the comparisons supported directly by branches 1045 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1046 // with 1/-1. 1047 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1048 ISD::CondCode &CC, SelectionDAG &DAG) { 1049 // Convert X > -1 to X >= 0. 1050 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1051 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1052 CC = ISD::SETGE; 1053 return; 1054 } 1055 // Convert X < 1 to 0 >= X. 1056 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1057 RHS = LHS; 1058 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1059 CC = ISD::SETGE; 1060 return; 1061 } 1062 1063 switch (CC) { 1064 default: 1065 break; 1066 case ISD::SETGT: 1067 case ISD::SETLE: 1068 case ISD::SETUGT: 1069 case ISD::SETULE: 1070 CC = ISD::getSetCCSwappedOperands(CC); 1071 std::swap(LHS, RHS); 1072 break; 1073 } 1074 } 1075 1076 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1077 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1078 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1079 if (VT.getVectorElementType() == MVT::i1) 1080 KnownSize *= 8; 1081 1082 switch (KnownSize) { 1083 default: 1084 llvm_unreachable("Invalid LMUL."); 1085 case 8: 1086 return RISCVII::VLMUL::LMUL_F8; 1087 case 16: 1088 return RISCVII::VLMUL::LMUL_F4; 1089 case 32: 1090 return RISCVII::VLMUL::LMUL_F2; 1091 case 64: 1092 return RISCVII::VLMUL::LMUL_1; 1093 case 128: 1094 return RISCVII::VLMUL::LMUL_2; 1095 case 256: 1096 return RISCVII::VLMUL::LMUL_4; 1097 case 512: 1098 return RISCVII::VLMUL::LMUL_8; 1099 } 1100 } 1101 1102 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1103 switch (LMul) { 1104 default: 1105 llvm_unreachable("Invalid LMUL."); 1106 case RISCVII::VLMUL::LMUL_F8: 1107 case RISCVII::VLMUL::LMUL_F4: 1108 case RISCVII::VLMUL::LMUL_F2: 1109 case RISCVII::VLMUL::LMUL_1: 1110 return RISCV::VRRegClassID; 1111 case RISCVII::VLMUL::LMUL_2: 1112 return RISCV::VRM2RegClassID; 1113 case RISCVII::VLMUL::LMUL_4: 1114 return RISCV::VRM4RegClassID; 1115 case RISCVII::VLMUL::LMUL_8: 1116 return RISCV::VRM8RegClassID; 1117 } 1118 } 1119 1120 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1121 RISCVII::VLMUL LMUL = getLMUL(VT); 1122 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1123 LMUL == RISCVII::VLMUL::LMUL_F4 || 1124 LMUL == RISCVII::VLMUL::LMUL_F2 || 1125 LMUL == RISCVII::VLMUL::LMUL_1) { 1126 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1127 "Unexpected subreg numbering"); 1128 return RISCV::sub_vrm1_0 + Index; 1129 } 1130 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1131 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1132 "Unexpected subreg numbering"); 1133 return RISCV::sub_vrm2_0 + Index; 1134 } 1135 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1136 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1137 "Unexpected subreg numbering"); 1138 return RISCV::sub_vrm4_0 + Index; 1139 } 1140 llvm_unreachable("Invalid vector type."); 1141 } 1142 1143 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1144 if (VT.getVectorElementType() == MVT::i1) 1145 return RISCV::VRRegClassID; 1146 return getRegClassIDForLMUL(getLMUL(VT)); 1147 } 1148 1149 // Attempt to decompose a subvector insert/extract between VecVT and 1150 // SubVecVT via subregister indices. Returns the subregister index that 1151 // can perform the subvector insert/extract with the given element index, as 1152 // well as the index corresponding to any leftover subvectors that must be 1153 // further inserted/extracted within the register class for SubVecVT. 1154 std::pair<unsigned, unsigned> 1155 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1156 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1157 const RISCVRegisterInfo *TRI) { 1158 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1159 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1160 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1161 "Register classes not ordered"); 1162 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1163 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1164 // Try to compose a subregister index that takes us from the incoming 1165 // LMUL>1 register class down to the outgoing one. At each step we half 1166 // the LMUL: 1167 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1168 // Note that this is not guaranteed to find a subregister index, such as 1169 // when we are extracting from one VR type to another. 1170 unsigned SubRegIdx = RISCV::NoSubRegister; 1171 for (const unsigned RCID : 1172 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1173 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1174 VecVT = VecVT.getHalfNumVectorElementsVT(); 1175 bool IsHi = 1176 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1177 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1178 getSubregIndexByMVT(VecVT, IsHi)); 1179 if (IsHi) 1180 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1181 } 1182 return {SubRegIdx, InsertExtractIdx}; 1183 } 1184 1185 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1186 // stores for those types. 1187 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1188 return !Subtarget.useRVVForFixedLengthVectors() || 1189 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1190 } 1191 1192 static bool useRVVForFixedLengthVectorVT(MVT VT, 1193 const RISCVSubtarget &Subtarget) { 1194 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1195 if (!Subtarget.useRVVForFixedLengthVectors()) 1196 return false; 1197 1198 // We only support a set of vector types with a consistent maximum fixed size 1199 // across all supported vector element types to avoid legalization issues. 1200 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1201 // fixed-length vector type we support is 1024 bytes. 1202 if (VT.getFixedSizeInBits() > 1024 * 8) 1203 return false; 1204 1205 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1206 1207 MVT EltVT = VT.getVectorElementType(); 1208 1209 // Don't use RVV for vectors we cannot scalarize if required. 1210 switch (EltVT.SimpleTy) { 1211 // i1 is supported but has different rules. 1212 default: 1213 return false; 1214 case MVT::i1: 1215 // Masks can only use a single register. 1216 if (VT.getVectorNumElements() > MinVLen) 1217 return false; 1218 MinVLen /= 8; 1219 break; 1220 case MVT::i8: 1221 case MVT::i16: 1222 case MVT::i32: 1223 case MVT::i64: 1224 break; 1225 case MVT::f16: 1226 if (!Subtarget.hasStdExtZfh()) 1227 return false; 1228 break; 1229 case MVT::f32: 1230 if (!Subtarget.hasStdExtF()) 1231 return false; 1232 break; 1233 case MVT::f64: 1234 if (!Subtarget.hasStdExtD()) 1235 return false; 1236 break; 1237 } 1238 1239 // Reject elements larger than ELEN. 1240 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1241 return false; 1242 1243 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1244 // Don't use RVV for types that don't fit. 1245 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1246 return false; 1247 1248 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1249 // the base fixed length RVV support in place. 1250 if (!VT.isPow2VectorType()) 1251 return false; 1252 1253 return true; 1254 } 1255 1256 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1257 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1258 } 1259 1260 // Return the largest legal scalable vector type that matches VT's element type. 1261 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1262 const RISCVSubtarget &Subtarget) { 1263 // This may be called before legal types are setup. 1264 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1265 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1266 "Expected legal fixed length vector!"); 1267 1268 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1269 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1270 1271 MVT EltVT = VT.getVectorElementType(); 1272 switch (EltVT.SimpleTy) { 1273 default: 1274 llvm_unreachable("unexpected element type for RVV container"); 1275 case MVT::i1: 1276 case MVT::i8: 1277 case MVT::i16: 1278 case MVT::i32: 1279 case MVT::i64: 1280 case MVT::f16: 1281 case MVT::f32: 1282 case MVT::f64: { 1283 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1284 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1285 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1286 unsigned NumElts = 1287 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1288 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1289 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1290 return MVT::getScalableVectorVT(EltVT, NumElts); 1291 } 1292 } 1293 } 1294 1295 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1296 const RISCVSubtarget &Subtarget) { 1297 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1298 Subtarget); 1299 } 1300 1301 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1302 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1303 } 1304 1305 // Grow V to consume an entire RVV register. 1306 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1307 const RISCVSubtarget &Subtarget) { 1308 assert(VT.isScalableVector() && 1309 "Expected to convert into a scalable vector!"); 1310 assert(V.getValueType().isFixedLengthVector() && 1311 "Expected a fixed length vector operand!"); 1312 SDLoc DL(V); 1313 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1314 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1315 } 1316 1317 // Shrink V so it's just big enough to maintain a VT's worth of data. 1318 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1319 const RISCVSubtarget &Subtarget) { 1320 assert(VT.isFixedLengthVector() && 1321 "Expected to convert into a fixed length vector!"); 1322 assert(V.getValueType().isScalableVector() && 1323 "Expected a scalable vector operand!"); 1324 SDLoc DL(V); 1325 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1326 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1327 } 1328 1329 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1330 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1331 // the vector type that it is contained in. 1332 static std::pair<SDValue, SDValue> 1333 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1334 const RISCVSubtarget &Subtarget) { 1335 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1336 MVT XLenVT = Subtarget.getXLenVT(); 1337 SDValue VL = VecVT.isFixedLengthVector() 1338 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1339 : DAG.getRegister(RISCV::X0, XLenVT); 1340 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1341 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1342 return {Mask, VL}; 1343 } 1344 1345 // As above but assuming the given type is a scalable vector type. 1346 static std::pair<SDValue, SDValue> 1347 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1348 const RISCVSubtarget &Subtarget) { 1349 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1350 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1351 } 1352 1353 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1354 // of either is (currently) supported. This can get us into an infinite loop 1355 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1356 // as a ..., etc. 1357 // Until either (or both) of these can reliably lower any node, reporting that 1358 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1359 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1360 // which is not desirable. 1361 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1362 EVT VT, unsigned DefinedValues) const { 1363 return false; 1364 } 1365 1366 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1367 // Only splats are currently supported. 1368 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1369 return true; 1370 1371 return false; 1372 } 1373 1374 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) { 1375 // RISCV FP-to-int conversions saturate to the destination register size, but 1376 // don't produce 0 for nan. We can use a conversion instruction and fix the 1377 // nan case with a compare and a select. 1378 SDValue Src = Op.getOperand(0); 1379 1380 EVT DstVT = Op.getValueType(); 1381 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1382 1383 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1384 unsigned Opc; 1385 if (SatVT == DstVT) 1386 Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ; 1387 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1388 Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 1389 else 1390 return SDValue(); 1391 // FIXME: Support other SatVTs by clamping before or after the conversion. 1392 1393 SDLoc DL(Op); 1394 SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src); 1395 1396 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1397 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1398 } 1399 1400 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1401 const RISCVSubtarget &Subtarget) { 1402 MVT VT = Op.getSimpleValueType(); 1403 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1404 1405 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1406 1407 SDLoc DL(Op); 1408 SDValue Mask, VL; 1409 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1410 1411 unsigned Opc = 1412 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1413 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1414 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1415 } 1416 1417 struct VIDSequence { 1418 int64_t StepNumerator; 1419 unsigned StepDenominator; 1420 int64_t Addend; 1421 }; 1422 1423 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1424 // to the (non-zero) step S and start value X. This can be then lowered as the 1425 // RVV sequence (VID * S) + X, for example. 1426 // The step S is represented as an integer numerator divided by a positive 1427 // denominator. Note that the implementation currently only identifies 1428 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1429 // cannot detect 2/3, for example. 1430 // Note that this method will also match potentially unappealing index 1431 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1432 // determine whether this is worth generating code for. 1433 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1434 unsigned NumElts = Op.getNumOperands(); 1435 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1436 if (!Op.getValueType().isInteger()) 1437 return None; 1438 1439 Optional<unsigned> SeqStepDenom; 1440 Optional<int64_t> SeqStepNum, SeqAddend; 1441 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1442 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1443 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1444 // Assume undef elements match the sequence; we just have to be careful 1445 // when interpolating across them. 1446 if (Op.getOperand(Idx).isUndef()) 1447 continue; 1448 // The BUILD_VECTOR must be all constants. 1449 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1450 return None; 1451 1452 uint64_t Val = Op.getConstantOperandVal(Idx) & 1453 maskTrailingOnes<uint64_t>(EltSizeInBits); 1454 1455 if (PrevElt) { 1456 // Calculate the step since the last non-undef element, and ensure 1457 // it's consistent across the entire sequence. 1458 unsigned IdxDiff = Idx - PrevElt->second; 1459 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1460 1461 // A zero-value value difference means that we're somewhere in the middle 1462 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1463 // step change before evaluating the sequence. 1464 if (ValDiff != 0) { 1465 int64_t Remainder = ValDiff % IdxDiff; 1466 // Normalize the step if it's greater than 1. 1467 if (Remainder != ValDiff) { 1468 // The difference must cleanly divide the element span. 1469 if (Remainder != 0) 1470 return None; 1471 ValDiff /= IdxDiff; 1472 IdxDiff = 1; 1473 } 1474 1475 if (!SeqStepNum) 1476 SeqStepNum = ValDiff; 1477 else if (ValDiff != SeqStepNum) 1478 return None; 1479 1480 if (!SeqStepDenom) 1481 SeqStepDenom = IdxDiff; 1482 else if (IdxDiff != *SeqStepDenom) 1483 return None; 1484 } 1485 } 1486 1487 // Record and/or check any addend. 1488 if (SeqStepNum && SeqStepDenom) { 1489 uint64_t ExpectedVal = 1490 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1491 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1492 if (!SeqAddend) 1493 SeqAddend = Addend; 1494 else if (SeqAddend != Addend) 1495 return None; 1496 } 1497 1498 // Record this non-undef element for later. 1499 if (!PrevElt || PrevElt->first != Val) 1500 PrevElt = std::make_pair(Val, Idx); 1501 } 1502 // We need to have logged both a step and an addend for this to count as 1503 // a legal index sequence. 1504 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1505 return None; 1506 1507 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1508 } 1509 1510 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1511 const RISCVSubtarget &Subtarget) { 1512 MVT VT = Op.getSimpleValueType(); 1513 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1514 1515 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1516 1517 SDLoc DL(Op); 1518 SDValue Mask, VL; 1519 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1520 1521 MVT XLenVT = Subtarget.getXLenVT(); 1522 unsigned NumElts = Op.getNumOperands(); 1523 1524 if (VT.getVectorElementType() == MVT::i1) { 1525 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1526 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1527 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1528 } 1529 1530 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1531 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1532 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1533 } 1534 1535 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1536 // scalar integer chunks whose bit-width depends on the number of mask 1537 // bits and XLEN. 1538 // First, determine the most appropriate scalar integer type to use. This 1539 // is at most XLenVT, but may be shrunk to a smaller vector element type 1540 // according to the size of the final vector - use i8 chunks rather than 1541 // XLenVT if we're producing a v8i1. This results in more consistent 1542 // codegen across RV32 and RV64. 1543 unsigned NumViaIntegerBits = 1544 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1545 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1546 // If we have to use more than one INSERT_VECTOR_ELT then this 1547 // optimization is likely to increase code size; avoid peforming it in 1548 // such a case. We can use a load from a constant pool in this case. 1549 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1550 return SDValue(); 1551 // Now we can create our integer vector type. Note that it may be larger 1552 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1553 MVT IntegerViaVecVT = 1554 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1555 divideCeil(NumElts, NumViaIntegerBits)); 1556 1557 uint64_t Bits = 0; 1558 unsigned BitPos = 0, IntegerEltIdx = 0; 1559 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1560 1561 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1562 // Once we accumulate enough bits to fill our scalar type, insert into 1563 // our vector and clear our accumulated data. 1564 if (I != 0 && I % NumViaIntegerBits == 0) { 1565 if (NumViaIntegerBits <= 32) 1566 Bits = SignExtend64(Bits, 32); 1567 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1568 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1569 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1570 Bits = 0; 1571 BitPos = 0; 1572 IntegerEltIdx++; 1573 } 1574 SDValue V = Op.getOperand(I); 1575 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1576 Bits |= ((uint64_t)BitValue << BitPos); 1577 } 1578 1579 // Insert the (remaining) scalar value into position in our integer 1580 // vector type. 1581 if (NumViaIntegerBits <= 32) 1582 Bits = SignExtend64(Bits, 32); 1583 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1584 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1585 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1586 1587 if (NumElts < NumViaIntegerBits) { 1588 // If we're producing a smaller vector than our minimum legal integer 1589 // type, bitcast to the equivalent (known-legal) mask type, and extract 1590 // our final mask. 1591 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1592 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1593 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1594 DAG.getConstant(0, DL, XLenVT)); 1595 } else { 1596 // Else we must have produced an integer type with the same size as the 1597 // mask type; bitcast for the final result. 1598 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1599 Vec = DAG.getBitcast(VT, Vec); 1600 } 1601 1602 return Vec; 1603 } 1604 1605 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 1606 // vector type, we have a legal equivalently-sized i8 type, so we can use 1607 // that. 1608 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 1609 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 1610 1611 SDValue WideVec; 1612 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1613 // For a splat, perform a scalar truncate before creating the wider 1614 // vector. 1615 assert(Splat.getValueType() == XLenVT && 1616 "Unexpected type for i1 splat value"); 1617 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 1618 DAG.getConstant(1, DL, XLenVT)); 1619 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 1620 } else { 1621 SmallVector<SDValue, 8> Ops(Op->op_values()); 1622 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 1623 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 1624 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 1625 } 1626 1627 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 1628 } 1629 1630 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1631 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 1632 : RISCVISD::VMV_V_X_VL; 1633 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 1634 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1635 } 1636 1637 // Try and match index sequences, which we can lower to the vid instruction 1638 // with optional modifications. An all-undef vector is matched by 1639 // getSplatValue, above. 1640 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 1641 int64_t StepNumerator = SimpleVID->StepNumerator; 1642 unsigned StepDenominator = SimpleVID->StepDenominator; 1643 int64_t Addend = SimpleVID->Addend; 1644 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 1645 // threshold since it's the immediate value many RVV instructions accept. 1646 if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) && 1647 isInt<5>(Addend)) { 1648 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 1649 // Convert right out of the scalable type so we can use standard ISD 1650 // nodes for the rest of the computation. If we used scalable types with 1651 // these, we'd lose the fixed-length vector info and generate worse 1652 // vsetvli code. 1653 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 1654 assert(StepNumerator != 0 && "Invalid step"); 1655 bool Negate = false; 1656 if (StepNumerator != 1) { 1657 int64_t SplatStepVal = StepNumerator; 1658 unsigned Opcode = ISD::MUL; 1659 if (isPowerOf2_64(std::abs(StepNumerator))) { 1660 Negate = StepNumerator < 0; 1661 Opcode = ISD::SHL; 1662 SplatStepVal = Log2_64(std::abs(StepNumerator)); 1663 } 1664 SDValue SplatStep = DAG.getSplatVector( 1665 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 1666 VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep); 1667 } 1668 if (StepDenominator != 1) { 1669 SDValue SplatStep = DAG.getSplatVector( 1670 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 1671 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 1672 } 1673 if (Addend != 0 || Negate) { 1674 SDValue SplatAddend = 1675 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 1676 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 1677 } 1678 return VID; 1679 } 1680 } 1681 1682 // Attempt to detect "hidden" splats, which only reveal themselves as splats 1683 // when re-interpreted as a vector with a larger element type. For example, 1684 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 1685 // could be instead splat as 1686 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 1687 // TODO: This optimization could also work on non-constant splats, but it 1688 // would require bit-manipulation instructions to construct the splat value. 1689 SmallVector<SDValue> Sequence; 1690 unsigned EltBitSize = VT.getScalarSizeInBits(); 1691 const auto *BV = cast<BuildVectorSDNode>(Op); 1692 if (VT.isInteger() && EltBitSize < 64 && 1693 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 1694 BV->getRepeatedSequence(Sequence) && 1695 (Sequence.size() * EltBitSize) <= 64) { 1696 unsigned SeqLen = Sequence.size(); 1697 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 1698 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 1699 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 1700 ViaIntVT == MVT::i64) && 1701 "Unexpected sequence type"); 1702 1703 unsigned EltIdx = 0; 1704 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 1705 uint64_t SplatValue = 0; 1706 // Construct the amalgamated value which can be splatted as this larger 1707 // vector type. 1708 for (const auto &SeqV : Sequence) { 1709 if (!SeqV.isUndef()) 1710 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 1711 << (EltIdx * EltBitSize)); 1712 EltIdx++; 1713 } 1714 1715 // On RV64, sign-extend from 32 to 64 bits where possible in order to 1716 // achieve better constant materializion. 1717 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 1718 SplatValue = SignExtend64(SplatValue, 32); 1719 1720 // Since we can't introduce illegal i64 types at this stage, we can only 1721 // perform an i64 splat on RV32 if it is its own sign-extended value. That 1722 // way we can use RVV instructions to splat. 1723 assert((ViaIntVT.bitsLE(XLenVT) || 1724 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 1725 "Unexpected bitcast sequence"); 1726 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 1727 SDValue ViaVL = 1728 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 1729 MVT ViaContainerVT = 1730 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 1731 SDValue Splat = 1732 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 1733 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 1734 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 1735 return DAG.getBitcast(VT, Splat); 1736 } 1737 } 1738 1739 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 1740 // which constitute a large proportion of the elements. In such cases we can 1741 // splat a vector with the dominant element and make up the shortfall with 1742 // INSERT_VECTOR_ELTs. 1743 // Note that this includes vectors of 2 elements by association. The 1744 // upper-most element is the "dominant" one, allowing us to use a splat to 1745 // "insert" the upper element, and an insert of the lower element at position 1746 // 0, which improves codegen. 1747 SDValue DominantValue; 1748 unsigned MostCommonCount = 0; 1749 DenseMap<SDValue, unsigned> ValueCounts; 1750 unsigned NumUndefElts = 1751 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 1752 1753 // Track the number of scalar loads we know we'd be inserting, estimated as 1754 // any non-zero floating-point constant. Other kinds of element are either 1755 // already in registers or are materialized on demand. The threshold at which 1756 // a vector load is more desirable than several scalar materializion and 1757 // vector-insertion instructions is not known. 1758 unsigned NumScalarLoads = 0; 1759 1760 for (SDValue V : Op->op_values()) { 1761 if (V.isUndef()) 1762 continue; 1763 1764 ValueCounts.insert(std::make_pair(V, 0)); 1765 unsigned &Count = ValueCounts[V]; 1766 1767 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 1768 NumScalarLoads += !CFP->isExactlyValue(+0.0); 1769 1770 // Is this value dominant? In case of a tie, prefer the highest element as 1771 // it's cheaper to insert near the beginning of a vector than it is at the 1772 // end. 1773 if (++Count >= MostCommonCount) { 1774 DominantValue = V; 1775 MostCommonCount = Count; 1776 } 1777 } 1778 1779 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 1780 unsigned NumDefElts = NumElts - NumUndefElts; 1781 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 1782 1783 // Don't perform this optimization when optimizing for size, since 1784 // materializing elements and inserting them tends to cause code bloat. 1785 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 1786 ((MostCommonCount > DominantValueCountThreshold) || 1787 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 1788 // Start by splatting the most common element. 1789 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 1790 1791 DenseSet<SDValue> Processed{DominantValue}; 1792 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 1793 for (const auto &OpIdx : enumerate(Op->ops())) { 1794 const SDValue &V = OpIdx.value(); 1795 if (V.isUndef() || !Processed.insert(V).second) 1796 continue; 1797 if (ValueCounts[V] == 1) { 1798 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 1799 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 1800 } else { 1801 // Blend in all instances of this value using a VSELECT, using a 1802 // mask where each bit signals whether that element is the one 1803 // we're after. 1804 SmallVector<SDValue> Ops; 1805 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 1806 return DAG.getConstant(V == V1, DL, XLenVT); 1807 }); 1808 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 1809 DAG.getBuildVector(SelMaskTy, DL, Ops), 1810 DAG.getSplatBuildVector(VT, DL, V), Vec); 1811 } 1812 } 1813 1814 return Vec; 1815 } 1816 1817 return SDValue(); 1818 } 1819 1820 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 1821 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 1822 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 1823 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 1824 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 1825 // If Hi constant is all the same sign bit as Lo, lower this as a custom 1826 // node in order to try and match RVV vector/scalar instructions. 1827 if ((LoC >> 31) == HiC) 1828 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 1829 } 1830 1831 // Fall back to a stack store and stride x0 vector load. 1832 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 1833 } 1834 1835 // Called by type legalization to handle splat of i64 on RV32. 1836 // FIXME: We can optimize this when the type has sign or zero bits in one 1837 // of the halves. 1838 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 1839 SDValue VL, SelectionDAG &DAG) { 1840 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 1841 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 1842 DAG.getConstant(0, DL, MVT::i32)); 1843 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 1844 DAG.getConstant(1, DL, MVT::i32)); 1845 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 1846 } 1847 1848 // This function lowers a splat of a scalar operand Splat with the vector 1849 // length VL. It ensures the final sequence is type legal, which is useful when 1850 // lowering a splat after type legalization. 1851 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 1852 SelectionDAG &DAG, 1853 const RISCVSubtarget &Subtarget) { 1854 if (VT.isFloatingPoint()) 1855 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 1856 1857 MVT XLenVT = Subtarget.getXLenVT(); 1858 1859 // Simplest case is that the operand needs to be promoted to XLenVT. 1860 if (Scalar.getValueType().bitsLE(XLenVT)) { 1861 // If the operand is a constant, sign extend to increase our chances 1862 // of being able to use a .vi instruction. ANY_EXTEND would become a 1863 // a zero extend and the simm5 check in isel would fail. 1864 // FIXME: Should we ignore the upper bits in isel instead? 1865 unsigned ExtOpc = 1866 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 1867 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 1868 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 1869 } 1870 1871 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 1872 "Unexpected scalar for splat lowering!"); 1873 1874 // Otherwise use the more complicated splatting algorithm. 1875 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 1876 } 1877 1878 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 1879 const RISCVSubtarget &Subtarget) { 1880 SDValue V1 = Op.getOperand(0); 1881 SDValue V2 = Op.getOperand(1); 1882 SDLoc DL(Op); 1883 MVT XLenVT = Subtarget.getXLenVT(); 1884 MVT VT = Op.getSimpleValueType(); 1885 unsigned NumElts = VT.getVectorNumElements(); 1886 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 1887 1888 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1889 1890 SDValue TrueMask, VL; 1891 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1892 1893 if (SVN->isSplat()) { 1894 const int Lane = SVN->getSplatIndex(); 1895 if (Lane >= 0) { 1896 MVT SVT = VT.getVectorElementType(); 1897 1898 // Turn splatted vector load into a strided load with an X0 stride. 1899 SDValue V = V1; 1900 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 1901 // with undef. 1902 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 1903 int Offset = Lane; 1904 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 1905 int OpElements = 1906 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 1907 V = V.getOperand(Offset / OpElements); 1908 Offset %= OpElements; 1909 } 1910 1911 // We need to ensure the load isn't atomic or volatile. 1912 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 1913 auto *Ld = cast<LoadSDNode>(V); 1914 Offset *= SVT.getStoreSize(); 1915 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 1916 TypeSize::Fixed(Offset), DL); 1917 1918 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 1919 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 1920 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 1921 SDValue IntID = 1922 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 1923 SDValue Ops[] = {Ld->getChain(), IntID, NewAddr, 1924 DAG.getRegister(RISCV::X0, XLenVT), VL}; 1925 SDValue NewLoad = DAG.getMemIntrinsicNode( 1926 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 1927 DAG.getMachineFunction().getMachineMemOperand( 1928 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 1929 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 1930 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 1931 } 1932 1933 // Otherwise use a scalar load and splat. This will give the best 1934 // opportunity to fold a splat into the operation. ISel can turn it into 1935 // the x0 strided load if we aren't able to fold away the select. 1936 if (SVT.isFloatingPoint()) 1937 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 1938 Ld->getPointerInfo().getWithOffset(Offset), 1939 Ld->getOriginalAlign(), 1940 Ld->getMemOperand()->getFlags()); 1941 else 1942 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 1943 Ld->getPointerInfo().getWithOffset(Offset), SVT, 1944 Ld->getOriginalAlign(), 1945 Ld->getMemOperand()->getFlags()); 1946 DAG.makeEquivalentMemoryOrdering(Ld, V); 1947 1948 unsigned Opc = 1949 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1950 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 1951 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1952 } 1953 1954 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 1955 assert(Lane < (int)NumElts && "Unexpected lane!"); 1956 SDValue Gather = 1957 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 1958 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 1959 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 1960 } 1961 } 1962 1963 // Detect shuffles which can be re-expressed as vector selects; these are 1964 // shuffles in which each element in the destination is taken from an element 1965 // at the corresponding index in either source vectors. 1966 bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) { 1967 int MaskIndex = MaskIdx.value(); 1968 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 1969 }); 1970 1971 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 1972 1973 SmallVector<SDValue> MaskVals; 1974 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 1975 // merged with a second vrgather. 1976 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 1977 1978 // By default we preserve the original operand order, and use a mask to 1979 // select LHS as true and RHS as false. However, since RVV vector selects may 1980 // feature splats but only on the LHS, we may choose to invert our mask and 1981 // instead select between RHS and LHS. 1982 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 1983 bool InvertMask = IsSelect == SwapOps; 1984 1985 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 1986 // half. 1987 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 1988 1989 // Now construct the mask that will be used by the vselect or blended 1990 // vrgather operation. For vrgathers, construct the appropriate indices into 1991 // each vector. 1992 for (int MaskIndex : SVN->getMask()) { 1993 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 1994 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 1995 if (!IsSelect) { 1996 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 1997 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 1998 ? DAG.getConstant(MaskIndex, DL, XLenVT) 1999 : DAG.getUNDEF(XLenVT)); 2000 GatherIndicesRHS.push_back( 2001 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2002 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2003 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2004 ++LHSIndexCounts[MaskIndex]; 2005 if (!IsLHSOrUndefIndex) 2006 ++RHSIndexCounts[MaskIndex - NumElts]; 2007 } 2008 } 2009 2010 if (SwapOps) { 2011 std::swap(V1, V2); 2012 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2013 } 2014 2015 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2016 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2017 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2018 2019 if (IsSelect) 2020 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2021 2022 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2023 // On such a large vector we're unable to use i8 as the index type. 2024 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2025 // may involve vector splitting if we're already at LMUL=8, or our 2026 // user-supplied maximum fixed-length LMUL. 2027 return SDValue(); 2028 } 2029 2030 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2031 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2032 MVT IndexVT = VT.changeTypeToInteger(); 2033 // Since we can't introduce illegal index types at this stage, use i16 and 2034 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2035 // than XLenVT. 2036 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2037 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2038 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2039 } 2040 2041 MVT IndexContainerVT = 2042 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2043 2044 SDValue Gather; 2045 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2046 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2047 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2048 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2049 } else { 2050 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2051 // If only one index is used, we can use a "splat" vrgather. 2052 // TODO: We can splat the most-common index and fix-up any stragglers, if 2053 // that's beneficial. 2054 if (LHSIndexCounts.size() == 1) { 2055 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2056 Gather = 2057 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2058 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2059 } else { 2060 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2061 LHSIndices = 2062 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2063 2064 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2065 TrueMask, VL); 2066 } 2067 } 2068 2069 // If a second vector operand is used by this shuffle, blend it in with an 2070 // additional vrgather. 2071 if (!V2.isUndef()) { 2072 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2073 // If only one index is used, we can use a "splat" vrgather. 2074 // TODO: We can splat the most-common index and fix-up any stragglers, if 2075 // that's beneficial. 2076 if (RHSIndexCounts.size() == 1) { 2077 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2078 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2079 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2080 } else { 2081 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2082 RHSIndices = 2083 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2084 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2085 VL); 2086 } 2087 2088 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2089 SelectMask = 2090 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2091 2092 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2093 Gather, VL); 2094 } 2095 2096 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2097 } 2098 2099 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2100 SDLoc DL, SelectionDAG &DAG, 2101 const RISCVSubtarget &Subtarget) { 2102 if (VT.isScalableVector()) 2103 return DAG.getFPExtendOrRound(Op, DL, VT); 2104 assert(VT.isFixedLengthVector() && 2105 "Unexpected value type for RVV FP extend/round lowering"); 2106 SDValue Mask, VL; 2107 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2108 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2109 ? RISCVISD::FP_EXTEND_VL 2110 : RISCVISD::FP_ROUND_VL; 2111 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2112 } 2113 2114 // While RVV has alignment restrictions, we should always be able to load as a 2115 // legal equivalently-sized byte-typed vector instead. This method is 2116 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2117 // the load is already correctly-aligned, it returns SDValue(). 2118 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2119 SelectionDAG &DAG) const { 2120 auto *Load = cast<LoadSDNode>(Op); 2121 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2122 2123 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2124 Load->getMemoryVT(), 2125 *Load->getMemOperand())) 2126 return SDValue(); 2127 2128 SDLoc DL(Op); 2129 MVT VT = Op.getSimpleValueType(); 2130 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2131 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2132 "Unexpected unaligned RVV load type"); 2133 MVT NewVT = 2134 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2135 assert(NewVT.isValid() && 2136 "Expecting equally-sized RVV vector types to be legal"); 2137 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2138 Load->getPointerInfo(), Load->getOriginalAlign(), 2139 Load->getMemOperand()->getFlags()); 2140 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2141 } 2142 2143 // While RVV has alignment restrictions, we should always be able to store as a 2144 // legal equivalently-sized byte-typed vector instead. This method is 2145 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2146 // returns SDValue() if the store is already correctly aligned. 2147 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2148 SelectionDAG &DAG) const { 2149 auto *Store = cast<StoreSDNode>(Op); 2150 assert(Store && Store->getValue().getValueType().isVector() && 2151 "Expected vector store"); 2152 2153 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2154 Store->getMemoryVT(), 2155 *Store->getMemOperand())) 2156 return SDValue(); 2157 2158 SDLoc DL(Op); 2159 SDValue StoredVal = Store->getValue(); 2160 MVT VT = StoredVal.getSimpleValueType(); 2161 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2162 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2163 "Unexpected unaligned RVV store type"); 2164 MVT NewVT = 2165 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2166 assert(NewVT.isValid() && 2167 "Expecting equally-sized RVV vector types to be legal"); 2168 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2169 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2170 Store->getPointerInfo(), Store->getOriginalAlign(), 2171 Store->getMemOperand()->getFlags()); 2172 } 2173 2174 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2175 SelectionDAG &DAG) const { 2176 switch (Op.getOpcode()) { 2177 default: 2178 report_fatal_error("unimplemented operand"); 2179 case ISD::GlobalAddress: 2180 return lowerGlobalAddress(Op, DAG); 2181 case ISD::BlockAddress: 2182 return lowerBlockAddress(Op, DAG); 2183 case ISD::ConstantPool: 2184 return lowerConstantPool(Op, DAG); 2185 case ISD::JumpTable: 2186 return lowerJumpTable(Op, DAG); 2187 case ISD::GlobalTLSAddress: 2188 return lowerGlobalTLSAddress(Op, DAG); 2189 case ISD::SELECT: 2190 return lowerSELECT(Op, DAG); 2191 case ISD::BRCOND: 2192 return lowerBRCOND(Op, DAG); 2193 case ISD::VASTART: 2194 return lowerVASTART(Op, DAG); 2195 case ISD::FRAMEADDR: 2196 return lowerFRAMEADDR(Op, DAG); 2197 case ISD::RETURNADDR: 2198 return lowerRETURNADDR(Op, DAG); 2199 case ISD::SHL_PARTS: 2200 return lowerShiftLeftParts(Op, DAG); 2201 case ISD::SRA_PARTS: 2202 return lowerShiftRightParts(Op, DAG, true); 2203 case ISD::SRL_PARTS: 2204 return lowerShiftRightParts(Op, DAG, false); 2205 case ISD::BITCAST: { 2206 SDLoc DL(Op); 2207 EVT VT = Op.getValueType(); 2208 SDValue Op0 = Op.getOperand(0); 2209 EVT Op0VT = Op0.getValueType(); 2210 MVT XLenVT = Subtarget.getXLenVT(); 2211 if (VT.isFixedLengthVector()) { 2212 // We can handle fixed length vector bitcasts with a simple replacement 2213 // in isel. 2214 if (Op0VT.isFixedLengthVector()) 2215 return Op; 2216 // When bitcasting from scalar to fixed-length vector, insert the scalar 2217 // into a one-element vector of the result type, and perform a vector 2218 // bitcast. 2219 if (!Op0VT.isVector()) { 2220 auto BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2221 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2222 DAG.getUNDEF(BVT), Op0, 2223 DAG.getConstant(0, DL, XLenVT))); 2224 } 2225 return SDValue(); 2226 } 2227 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2228 // thus: bitcast the vector to a one-element vector type whose element type 2229 // is the same as the result type, and extract the first element. 2230 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2231 LLVMContext &Context = *DAG.getContext(); 2232 SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0); 2233 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2234 DAG.getConstant(0, DL, XLenVT)); 2235 } 2236 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2237 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2238 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2239 return FPConv; 2240 } 2241 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2242 Subtarget.hasStdExtF()) { 2243 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2244 SDValue FPConv = 2245 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2246 return FPConv; 2247 } 2248 return SDValue(); 2249 } 2250 case ISD::INTRINSIC_WO_CHAIN: 2251 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2252 case ISD::INTRINSIC_W_CHAIN: 2253 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2254 case ISD::BSWAP: 2255 case ISD::BITREVERSE: { 2256 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2257 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 2258 MVT VT = Op.getSimpleValueType(); 2259 SDLoc DL(Op); 2260 // Start with the maximum immediate value which is the bitwidth - 1. 2261 unsigned Imm = VT.getSizeInBits() - 1; 2262 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2263 if (Op.getOpcode() == ISD::BSWAP) 2264 Imm &= ~0x7U; 2265 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2266 DAG.getConstant(Imm, DL, VT)); 2267 } 2268 case ISD::FSHL: 2269 case ISD::FSHR: { 2270 MVT VT = Op.getSimpleValueType(); 2271 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2272 SDLoc DL(Op); 2273 if (Op.getOperand(2).getOpcode() == ISD::Constant) 2274 return Op; 2275 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2276 // use log(XLen) bits. Mask the shift amount accordingly. 2277 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2278 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2279 DAG.getConstant(ShAmtWidth, DL, VT)); 2280 unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR; 2281 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt); 2282 } 2283 case ISD::TRUNCATE: { 2284 SDLoc DL(Op); 2285 MVT VT = Op.getSimpleValueType(); 2286 // Only custom-lower vector truncates 2287 if (!VT.isVector()) 2288 return Op; 2289 2290 // Truncates to mask types are handled differently 2291 if (VT.getVectorElementType() == MVT::i1) 2292 return lowerVectorMaskTrunc(Op, DAG); 2293 2294 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 2295 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 2296 // truncate by one power of two at a time. 2297 MVT DstEltVT = VT.getVectorElementType(); 2298 2299 SDValue Src = Op.getOperand(0); 2300 MVT SrcVT = Src.getSimpleValueType(); 2301 MVT SrcEltVT = SrcVT.getVectorElementType(); 2302 2303 assert(DstEltVT.bitsLT(SrcEltVT) && 2304 isPowerOf2_64(DstEltVT.getSizeInBits()) && 2305 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 2306 "Unexpected vector truncate lowering"); 2307 2308 MVT ContainerVT = SrcVT; 2309 if (SrcVT.isFixedLengthVector()) { 2310 ContainerVT = getContainerForFixedLengthVector(SrcVT); 2311 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 2312 } 2313 2314 SDValue Result = Src; 2315 SDValue Mask, VL; 2316 std::tie(Mask, VL) = 2317 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 2318 LLVMContext &Context = *DAG.getContext(); 2319 const ElementCount Count = ContainerVT.getVectorElementCount(); 2320 do { 2321 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 2322 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 2323 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 2324 Mask, VL); 2325 } while (SrcEltVT != DstEltVT); 2326 2327 if (SrcVT.isFixedLengthVector()) 2328 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 2329 2330 return Result; 2331 } 2332 case ISD::ANY_EXTEND: 2333 case ISD::ZERO_EXTEND: 2334 if (Op.getOperand(0).getValueType().isVector() && 2335 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2336 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 2337 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 2338 case ISD::SIGN_EXTEND: 2339 if (Op.getOperand(0).getValueType().isVector() && 2340 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2341 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 2342 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 2343 case ISD::SPLAT_VECTOR_PARTS: 2344 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 2345 case ISD::INSERT_VECTOR_ELT: 2346 return lowerINSERT_VECTOR_ELT(Op, DAG); 2347 case ISD::EXTRACT_VECTOR_ELT: 2348 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 2349 case ISD::VSCALE: { 2350 MVT VT = Op.getSimpleValueType(); 2351 SDLoc DL(Op); 2352 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 2353 // We define our scalable vector types for lmul=1 to use a 64 bit known 2354 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 2355 // vscale as VLENB / 8. 2356 assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!"); 2357 if (isa<ConstantSDNode>(Op.getOperand(0))) { 2358 // We assume VLENB is a multiple of 8. We manually choose the best shift 2359 // here because SimplifyDemandedBits isn't always able to simplify it. 2360 uint64_t Val = Op.getConstantOperandVal(0); 2361 if (isPowerOf2_64(Val)) { 2362 uint64_t Log2 = Log2_64(Val); 2363 if (Log2 < 3) 2364 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 2365 DAG.getConstant(3 - Log2, DL, VT)); 2366 if (Log2 > 3) 2367 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 2368 DAG.getConstant(Log2 - 3, DL, VT)); 2369 return VLENB; 2370 } 2371 // If the multiplier is a multiple of 8, scale it down to avoid needing 2372 // to shift the VLENB value. 2373 if ((Val % 8) == 0) 2374 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 2375 DAG.getConstant(Val / 8, DL, VT)); 2376 } 2377 2378 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 2379 DAG.getConstant(3, DL, VT)); 2380 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 2381 } 2382 case ISD::FP_EXTEND: { 2383 // RVV can only do fp_extend to types double the size as the source. We 2384 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 2385 // via f32. 2386 SDLoc DL(Op); 2387 MVT VT = Op.getSimpleValueType(); 2388 SDValue Src = Op.getOperand(0); 2389 MVT SrcVT = Src.getSimpleValueType(); 2390 2391 // Prepare any fixed-length vector operands. 2392 MVT ContainerVT = VT; 2393 if (SrcVT.isFixedLengthVector()) { 2394 ContainerVT = getContainerForFixedLengthVector(VT); 2395 MVT SrcContainerVT = 2396 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 2397 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2398 } 2399 2400 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 2401 SrcVT.getVectorElementType() != MVT::f16) { 2402 // For scalable vectors, we only need to close the gap between 2403 // vXf16->vXf64. 2404 if (!VT.isFixedLengthVector()) 2405 return Op; 2406 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 2407 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2408 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2409 } 2410 2411 MVT InterVT = VT.changeVectorElementType(MVT::f32); 2412 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 2413 SDValue IntermediateExtend = getRVVFPExtendOrRound( 2414 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 2415 2416 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 2417 DL, DAG, Subtarget); 2418 if (VT.isFixedLengthVector()) 2419 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 2420 return Extend; 2421 } 2422 case ISD::FP_ROUND: { 2423 // RVV can only do fp_round to types half the size as the source. We 2424 // custom-lower f64->f16 rounds via RVV's round-to-odd float 2425 // conversion instruction. 2426 SDLoc DL(Op); 2427 MVT VT = Op.getSimpleValueType(); 2428 SDValue Src = Op.getOperand(0); 2429 MVT SrcVT = Src.getSimpleValueType(); 2430 2431 // Prepare any fixed-length vector operands. 2432 MVT ContainerVT = VT; 2433 if (VT.isFixedLengthVector()) { 2434 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2435 ContainerVT = 2436 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2437 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2438 } 2439 2440 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 2441 SrcVT.getVectorElementType() != MVT::f64) { 2442 // For scalable vectors, we only need to close the gap between 2443 // vXf64<->vXf16. 2444 if (!VT.isFixedLengthVector()) 2445 return Op; 2446 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 2447 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2448 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2449 } 2450 2451 SDValue Mask, VL; 2452 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2453 2454 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 2455 SDValue IntermediateRound = 2456 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 2457 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 2458 DL, DAG, Subtarget); 2459 2460 if (VT.isFixedLengthVector()) 2461 return convertFromScalableVector(VT, Round, DAG, Subtarget); 2462 return Round; 2463 } 2464 case ISD::FP_TO_SINT: 2465 case ISD::FP_TO_UINT: 2466 case ISD::SINT_TO_FP: 2467 case ISD::UINT_TO_FP: { 2468 // RVV can only do fp<->int conversions to types half/double the size as 2469 // the source. We custom-lower any conversions that do two hops into 2470 // sequences. 2471 MVT VT = Op.getSimpleValueType(); 2472 if (!VT.isVector()) 2473 return Op; 2474 SDLoc DL(Op); 2475 SDValue Src = Op.getOperand(0); 2476 MVT EltVT = VT.getVectorElementType(); 2477 MVT SrcVT = Src.getSimpleValueType(); 2478 MVT SrcEltVT = SrcVT.getVectorElementType(); 2479 unsigned EltSize = EltVT.getSizeInBits(); 2480 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 2481 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 2482 "Unexpected vector element types"); 2483 2484 bool IsInt2FP = SrcEltVT.isInteger(); 2485 // Widening conversions 2486 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 2487 if (IsInt2FP) { 2488 // Do a regular integer sign/zero extension then convert to float. 2489 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 2490 VT.getVectorElementCount()); 2491 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 2492 ? ISD::ZERO_EXTEND 2493 : ISD::SIGN_EXTEND; 2494 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 2495 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 2496 } 2497 // FP2Int 2498 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 2499 // Do one doubling fp_extend then complete the operation by converting 2500 // to int. 2501 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2502 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 2503 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 2504 } 2505 2506 // Narrowing conversions 2507 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 2508 if (IsInt2FP) { 2509 // One narrowing int_to_fp, then an fp_round. 2510 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 2511 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2512 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 2513 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 2514 } 2515 // FP2Int 2516 // One narrowing fp_to_int, then truncate the integer. If the float isn't 2517 // representable by the integer, the result is poison. 2518 MVT IVecVT = 2519 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 2520 VT.getVectorElementCount()); 2521 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 2522 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 2523 } 2524 2525 // Scalable vectors can exit here. Patterns will handle equally-sized 2526 // conversions halving/doubling ones. 2527 if (!VT.isFixedLengthVector()) 2528 return Op; 2529 2530 // For fixed-length vectors we lower to a custom "VL" node. 2531 unsigned RVVOpc = 0; 2532 switch (Op.getOpcode()) { 2533 default: 2534 llvm_unreachable("Impossible opcode"); 2535 case ISD::FP_TO_SINT: 2536 RVVOpc = RISCVISD::FP_TO_SINT_VL; 2537 break; 2538 case ISD::FP_TO_UINT: 2539 RVVOpc = RISCVISD::FP_TO_UINT_VL; 2540 break; 2541 case ISD::SINT_TO_FP: 2542 RVVOpc = RISCVISD::SINT_TO_FP_VL; 2543 break; 2544 case ISD::UINT_TO_FP: 2545 RVVOpc = RISCVISD::UINT_TO_FP_VL; 2546 break; 2547 } 2548 2549 MVT ContainerVT, SrcContainerVT; 2550 // Derive the reference container type from the larger vector type. 2551 if (SrcEltSize > EltSize) { 2552 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2553 ContainerVT = 2554 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2555 } else { 2556 ContainerVT = getContainerForFixedLengthVector(VT); 2557 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 2558 } 2559 2560 SDValue Mask, VL; 2561 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2562 2563 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2564 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 2565 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2566 } 2567 case ISD::FP_TO_SINT_SAT: 2568 case ISD::FP_TO_UINT_SAT: 2569 return lowerFP_TO_INT_SAT(Op, DAG); 2570 case ISD::VECREDUCE_ADD: 2571 case ISD::VECREDUCE_UMAX: 2572 case ISD::VECREDUCE_SMAX: 2573 case ISD::VECREDUCE_UMIN: 2574 case ISD::VECREDUCE_SMIN: 2575 return lowerVECREDUCE(Op, DAG); 2576 case ISD::VECREDUCE_AND: 2577 case ISD::VECREDUCE_OR: 2578 case ISD::VECREDUCE_XOR: 2579 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2580 return lowerVectorMaskVECREDUCE(Op, DAG); 2581 return lowerVECREDUCE(Op, DAG); 2582 case ISD::VECREDUCE_FADD: 2583 case ISD::VECREDUCE_SEQ_FADD: 2584 case ISD::VECREDUCE_FMIN: 2585 case ISD::VECREDUCE_FMAX: 2586 return lowerFPVECREDUCE(Op, DAG); 2587 case ISD::INSERT_SUBVECTOR: 2588 return lowerINSERT_SUBVECTOR(Op, DAG); 2589 case ISD::EXTRACT_SUBVECTOR: 2590 return lowerEXTRACT_SUBVECTOR(Op, DAG); 2591 case ISD::STEP_VECTOR: 2592 return lowerSTEP_VECTOR(Op, DAG); 2593 case ISD::VECTOR_REVERSE: 2594 return lowerVECTOR_REVERSE(Op, DAG); 2595 case ISD::BUILD_VECTOR: 2596 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 2597 case ISD::SPLAT_VECTOR: 2598 if (Op.getValueType().getVectorElementType() == MVT::i1) 2599 return lowerVectorMaskSplat(Op, DAG); 2600 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 2601 case ISD::VECTOR_SHUFFLE: 2602 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 2603 case ISD::CONCAT_VECTORS: { 2604 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 2605 // better than going through the stack, as the default expansion does. 2606 SDLoc DL(Op); 2607 MVT VT = Op.getSimpleValueType(); 2608 unsigned NumOpElts = 2609 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 2610 SDValue Vec = DAG.getUNDEF(VT); 2611 for (const auto &OpIdx : enumerate(Op->ops())) 2612 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(), 2613 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 2614 return Vec; 2615 } 2616 case ISD::LOAD: 2617 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 2618 return V; 2619 if (Op.getValueType().isFixedLengthVector()) 2620 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 2621 return Op; 2622 case ISD::STORE: 2623 if (auto V = expandUnalignedRVVStore(Op, DAG)) 2624 return V; 2625 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 2626 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 2627 return Op; 2628 case ISD::MLOAD: 2629 return lowerMLOAD(Op, DAG); 2630 case ISD::MSTORE: 2631 return lowerMSTORE(Op, DAG); 2632 case ISD::SETCC: 2633 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 2634 case ISD::ADD: 2635 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 2636 case ISD::SUB: 2637 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 2638 case ISD::MUL: 2639 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 2640 case ISD::MULHS: 2641 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 2642 case ISD::MULHU: 2643 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 2644 case ISD::AND: 2645 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 2646 RISCVISD::AND_VL); 2647 case ISD::OR: 2648 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 2649 RISCVISD::OR_VL); 2650 case ISD::XOR: 2651 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 2652 RISCVISD::XOR_VL); 2653 case ISD::SDIV: 2654 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 2655 case ISD::SREM: 2656 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 2657 case ISD::UDIV: 2658 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 2659 case ISD::UREM: 2660 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 2661 case ISD::SHL: 2662 case ISD::SRA: 2663 case ISD::SRL: 2664 if (Op.getSimpleValueType().isFixedLengthVector()) 2665 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 2666 // This can be called for an i32 shift amount that needs to be promoted. 2667 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 2668 "Unexpected custom legalisation"); 2669 return SDValue(); 2670 case ISD::SADDSAT: 2671 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 2672 case ISD::UADDSAT: 2673 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 2674 case ISD::SSUBSAT: 2675 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 2676 case ISD::USUBSAT: 2677 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 2678 case ISD::FADD: 2679 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 2680 case ISD::FSUB: 2681 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 2682 case ISD::FMUL: 2683 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 2684 case ISD::FDIV: 2685 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 2686 case ISD::FNEG: 2687 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 2688 case ISD::FABS: 2689 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 2690 case ISD::FSQRT: 2691 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 2692 case ISD::FMA: 2693 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 2694 case ISD::SMIN: 2695 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 2696 case ISD::SMAX: 2697 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 2698 case ISD::UMIN: 2699 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 2700 case ISD::UMAX: 2701 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 2702 case ISD::FMINNUM: 2703 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 2704 case ISD::FMAXNUM: 2705 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 2706 case ISD::ABS: 2707 return lowerABS(Op, DAG); 2708 case ISD::VSELECT: 2709 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 2710 case ISD::FCOPYSIGN: 2711 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 2712 case ISD::MGATHER: 2713 return lowerMGATHER(Op, DAG); 2714 case ISD::MSCATTER: 2715 return lowerMSCATTER(Op, DAG); 2716 case ISD::FLT_ROUNDS_: 2717 return lowerGET_ROUNDING(Op, DAG); 2718 case ISD::SET_ROUNDING: 2719 return lowerSET_ROUNDING(Op, DAG); 2720 case ISD::VP_ADD: 2721 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 2722 case ISD::VP_SUB: 2723 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 2724 case ISD::VP_MUL: 2725 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 2726 case ISD::VP_SDIV: 2727 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 2728 case ISD::VP_UDIV: 2729 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 2730 case ISD::VP_SREM: 2731 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 2732 case ISD::VP_UREM: 2733 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 2734 case ISD::VP_AND: 2735 return lowerVPOp(Op, DAG, RISCVISD::AND_VL); 2736 case ISD::VP_OR: 2737 return lowerVPOp(Op, DAG, RISCVISD::OR_VL); 2738 case ISD::VP_XOR: 2739 return lowerVPOp(Op, DAG, RISCVISD::XOR_VL); 2740 case ISD::VP_ASHR: 2741 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 2742 case ISD::VP_LSHR: 2743 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 2744 case ISD::VP_SHL: 2745 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 2746 case ISD::VP_FADD: 2747 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 2748 case ISD::VP_FSUB: 2749 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 2750 case ISD::VP_FMUL: 2751 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 2752 case ISD::VP_FDIV: 2753 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 2754 } 2755 } 2756 2757 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 2758 SelectionDAG &DAG, unsigned Flags) { 2759 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 2760 } 2761 2762 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 2763 SelectionDAG &DAG, unsigned Flags) { 2764 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 2765 Flags); 2766 } 2767 2768 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 2769 SelectionDAG &DAG, unsigned Flags) { 2770 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 2771 N->getOffset(), Flags); 2772 } 2773 2774 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 2775 SelectionDAG &DAG, unsigned Flags) { 2776 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 2777 } 2778 2779 template <class NodeTy> 2780 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 2781 bool IsLocal) const { 2782 SDLoc DL(N); 2783 EVT Ty = getPointerTy(DAG.getDataLayout()); 2784 2785 if (isPositionIndependent()) { 2786 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 2787 if (IsLocal) 2788 // Use PC-relative addressing to access the symbol. This generates the 2789 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 2790 // %pcrel_lo(auipc)). 2791 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 2792 2793 // Use PC-relative addressing to access the GOT for this symbol, then load 2794 // the address from the GOT. This generates the pattern (PseudoLA sym), 2795 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 2796 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 2797 } 2798 2799 switch (getTargetMachine().getCodeModel()) { 2800 default: 2801 report_fatal_error("Unsupported code model for lowering"); 2802 case CodeModel::Small: { 2803 // Generate a sequence for accessing addresses within the first 2 GiB of 2804 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 2805 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 2806 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 2807 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 2808 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 2809 } 2810 case CodeModel::Medium: { 2811 // Generate a sequence for accessing addresses within any 2GiB range within 2812 // the address space. This generates the pattern (PseudoLLA sym), which 2813 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 2814 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 2815 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 2816 } 2817 } 2818 } 2819 2820 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 2821 SelectionDAG &DAG) const { 2822 SDLoc DL(Op); 2823 EVT Ty = Op.getValueType(); 2824 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 2825 int64_t Offset = N->getOffset(); 2826 MVT XLenVT = Subtarget.getXLenVT(); 2827 2828 const GlobalValue *GV = N->getGlobal(); 2829 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 2830 SDValue Addr = getAddr(N, DAG, IsLocal); 2831 2832 // In order to maximise the opportunity for common subexpression elimination, 2833 // emit a separate ADD node for the global address offset instead of folding 2834 // it in the global address node. Later peephole optimisations may choose to 2835 // fold it back in when profitable. 2836 if (Offset != 0) 2837 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 2838 DAG.getConstant(Offset, DL, XLenVT)); 2839 return Addr; 2840 } 2841 2842 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 2843 SelectionDAG &DAG) const { 2844 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 2845 2846 return getAddr(N, DAG); 2847 } 2848 2849 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 2850 SelectionDAG &DAG) const { 2851 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 2852 2853 return getAddr(N, DAG); 2854 } 2855 2856 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 2857 SelectionDAG &DAG) const { 2858 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 2859 2860 return getAddr(N, DAG); 2861 } 2862 2863 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 2864 SelectionDAG &DAG, 2865 bool UseGOT) const { 2866 SDLoc DL(N); 2867 EVT Ty = getPointerTy(DAG.getDataLayout()); 2868 const GlobalValue *GV = N->getGlobal(); 2869 MVT XLenVT = Subtarget.getXLenVT(); 2870 2871 if (UseGOT) { 2872 // Use PC-relative addressing to access the GOT for this TLS symbol, then 2873 // load the address from the GOT and add the thread pointer. This generates 2874 // the pattern (PseudoLA_TLS_IE sym), which expands to 2875 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 2876 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 2877 SDValue Load = 2878 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 2879 2880 // Add the thread pointer. 2881 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 2882 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 2883 } 2884 2885 // Generate a sequence for accessing the address relative to the thread 2886 // pointer, with the appropriate adjustment for the thread pointer offset. 2887 // This generates the pattern 2888 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 2889 SDValue AddrHi = 2890 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 2891 SDValue AddrAdd = 2892 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 2893 SDValue AddrLo = 2894 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 2895 2896 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 2897 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 2898 SDValue MNAdd = SDValue( 2899 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 2900 0); 2901 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 2902 } 2903 2904 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 2905 SelectionDAG &DAG) const { 2906 SDLoc DL(N); 2907 EVT Ty = getPointerTy(DAG.getDataLayout()); 2908 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 2909 const GlobalValue *GV = N->getGlobal(); 2910 2911 // Use a PC-relative addressing mode to access the global dynamic GOT address. 2912 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 2913 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 2914 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 2915 SDValue Load = 2916 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 2917 2918 // Prepare argument list to generate call. 2919 ArgListTy Args; 2920 ArgListEntry Entry; 2921 Entry.Node = Load; 2922 Entry.Ty = CallTy; 2923 Args.push_back(Entry); 2924 2925 // Setup call to __tls_get_addr. 2926 TargetLowering::CallLoweringInfo CLI(DAG); 2927 CLI.setDebugLoc(DL) 2928 .setChain(DAG.getEntryNode()) 2929 .setLibCallee(CallingConv::C, CallTy, 2930 DAG.getExternalSymbol("__tls_get_addr", Ty), 2931 std::move(Args)); 2932 2933 return LowerCallTo(CLI).first; 2934 } 2935 2936 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 2937 SelectionDAG &DAG) const { 2938 SDLoc DL(Op); 2939 EVT Ty = Op.getValueType(); 2940 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 2941 int64_t Offset = N->getOffset(); 2942 MVT XLenVT = Subtarget.getXLenVT(); 2943 2944 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 2945 2946 if (DAG.getMachineFunction().getFunction().getCallingConv() == 2947 CallingConv::GHC) 2948 report_fatal_error("In GHC calling convention TLS is not supported"); 2949 2950 SDValue Addr; 2951 switch (Model) { 2952 case TLSModel::LocalExec: 2953 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 2954 break; 2955 case TLSModel::InitialExec: 2956 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 2957 break; 2958 case TLSModel::LocalDynamic: 2959 case TLSModel::GeneralDynamic: 2960 Addr = getDynamicTLSAddr(N, DAG); 2961 break; 2962 } 2963 2964 // In order to maximise the opportunity for common subexpression elimination, 2965 // emit a separate ADD node for the global address offset instead of folding 2966 // it in the global address node. Later peephole optimisations may choose to 2967 // fold it back in when profitable. 2968 if (Offset != 0) 2969 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 2970 DAG.getConstant(Offset, DL, XLenVT)); 2971 return Addr; 2972 } 2973 2974 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 2975 SDValue CondV = Op.getOperand(0); 2976 SDValue TrueV = Op.getOperand(1); 2977 SDValue FalseV = Op.getOperand(2); 2978 SDLoc DL(Op); 2979 MVT VT = Op.getSimpleValueType(); 2980 MVT XLenVT = Subtarget.getXLenVT(); 2981 2982 // Lower vector SELECTs to VSELECTs by splatting the condition. 2983 if (VT.isVector()) { 2984 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 2985 SDValue CondSplat = VT.isScalableVector() 2986 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 2987 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 2988 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 2989 } 2990 2991 // If the result type is XLenVT and CondV is the output of a SETCC node 2992 // which also operated on XLenVT inputs, then merge the SETCC node into the 2993 // lowered RISCVISD::SELECT_CC to take advantage of the integer 2994 // compare+branch instructions. i.e.: 2995 // (select (setcc lhs, rhs, cc), truev, falsev) 2996 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 2997 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 2998 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 2999 SDValue LHS = CondV.getOperand(0); 3000 SDValue RHS = CondV.getOperand(1); 3001 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3002 ISD::CondCode CCVal = CC->get(); 3003 3004 // Special case for a select of 2 constants that have a diffence of 1. 3005 // Normally this is done by DAGCombine, but if the select is introduced by 3006 // type legalization or op legalization, we miss it. Restricting to SETLT 3007 // case for now because that is what signed saturating add/sub need. 3008 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3009 // but we would probably want to swap the true/false values if the condition 3010 // is SETGE/SETLE to avoid an XORI. 3011 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3012 CCVal == ISD::SETLT) { 3013 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3014 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3015 if (TrueVal - 1 == FalseVal) 3016 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3017 if (TrueVal + 1 == FalseVal) 3018 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3019 } 3020 3021 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3022 3023 SDValue TargetCC = DAG.getCondCode(CCVal); 3024 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3025 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3026 } 3027 3028 // Otherwise: 3029 // (select condv, truev, falsev) 3030 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3031 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3032 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3033 3034 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3035 3036 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3037 } 3038 3039 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3040 SDValue CondV = Op.getOperand(1); 3041 SDLoc DL(Op); 3042 MVT XLenVT = Subtarget.getXLenVT(); 3043 3044 if (CondV.getOpcode() == ISD::SETCC && 3045 CondV.getOperand(0).getValueType() == XLenVT) { 3046 SDValue LHS = CondV.getOperand(0); 3047 SDValue RHS = CondV.getOperand(1); 3048 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3049 3050 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3051 3052 SDValue TargetCC = DAG.getCondCode(CCVal); 3053 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3054 LHS, RHS, TargetCC, Op.getOperand(2)); 3055 } 3056 3057 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3058 CondV, DAG.getConstant(0, DL, XLenVT), 3059 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3060 } 3061 3062 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3063 MachineFunction &MF = DAG.getMachineFunction(); 3064 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3065 3066 SDLoc DL(Op); 3067 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3068 getPointerTy(MF.getDataLayout())); 3069 3070 // vastart just stores the address of the VarArgsFrameIndex slot into the 3071 // memory location argument. 3072 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3073 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3074 MachinePointerInfo(SV)); 3075 } 3076 3077 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3078 SelectionDAG &DAG) const { 3079 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3080 MachineFunction &MF = DAG.getMachineFunction(); 3081 MachineFrameInfo &MFI = MF.getFrameInfo(); 3082 MFI.setFrameAddressIsTaken(true); 3083 Register FrameReg = RI.getFrameRegister(MF); 3084 int XLenInBytes = Subtarget.getXLen() / 8; 3085 3086 EVT VT = Op.getValueType(); 3087 SDLoc DL(Op); 3088 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3089 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3090 while (Depth--) { 3091 int Offset = -(XLenInBytes * 2); 3092 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3093 DAG.getIntPtrConstant(Offset, DL)); 3094 FrameAddr = 3095 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3096 } 3097 return FrameAddr; 3098 } 3099 3100 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3101 SelectionDAG &DAG) const { 3102 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3103 MachineFunction &MF = DAG.getMachineFunction(); 3104 MachineFrameInfo &MFI = MF.getFrameInfo(); 3105 MFI.setReturnAddressIsTaken(true); 3106 MVT XLenVT = Subtarget.getXLenVT(); 3107 int XLenInBytes = Subtarget.getXLen() / 8; 3108 3109 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3110 return SDValue(); 3111 3112 EVT VT = Op.getValueType(); 3113 SDLoc DL(Op); 3114 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3115 if (Depth) { 3116 int Off = -XLenInBytes; 3117 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3118 SDValue Offset = DAG.getConstant(Off, DL, VT); 3119 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3120 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3121 MachinePointerInfo()); 3122 } 3123 3124 // Return the value of the return address register, marking it an implicit 3125 // live-in. 3126 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3127 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3128 } 3129 3130 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3131 SelectionDAG &DAG) const { 3132 SDLoc DL(Op); 3133 SDValue Lo = Op.getOperand(0); 3134 SDValue Hi = Op.getOperand(1); 3135 SDValue Shamt = Op.getOperand(2); 3136 EVT VT = Lo.getValueType(); 3137 3138 // if Shamt-XLEN < 0: // Shamt < XLEN 3139 // Lo = Lo << Shamt 3140 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3141 // else: 3142 // Lo = 0 3143 // Hi = Lo << (Shamt-XLEN) 3144 3145 SDValue Zero = DAG.getConstant(0, DL, VT); 3146 SDValue One = DAG.getConstant(1, DL, VT); 3147 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3148 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3149 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3150 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3151 3152 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3153 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3154 SDValue ShiftRightLo = 3155 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3156 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3157 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3158 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3159 3160 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3161 3162 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3163 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3164 3165 SDValue Parts[2] = {Lo, Hi}; 3166 return DAG.getMergeValues(Parts, DL); 3167 } 3168 3169 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3170 bool IsSRA) const { 3171 SDLoc DL(Op); 3172 SDValue Lo = Op.getOperand(0); 3173 SDValue Hi = Op.getOperand(1); 3174 SDValue Shamt = Op.getOperand(2); 3175 EVT VT = Lo.getValueType(); 3176 3177 // SRA expansion: 3178 // if Shamt-XLEN < 0: // Shamt < XLEN 3179 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3180 // Hi = Hi >>s Shamt 3181 // else: 3182 // Lo = Hi >>s (Shamt-XLEN); 3183 // Hi = Hi >>s (XLEN-1) 3184 // 3185 // SRL expansion: 3186 // if Shamt-XLEN < 0: // Shamt < XLEN 3187 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3188 // Hi = Hi >>u Shamt 3189 // else: 3190 // Lo = Hi >>u (Shamt-XLEN); 3191 // Hi = 0; 3192 3193 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3194 3195 SDValue Zero = DAG.getConstant(0, DL, VT); 3196 SDValue One = DAG.getConstant(1, DL, VT); 3197 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3198 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3199 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3200 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3201 3202 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3203 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3204 SDValue ShiftLeftHi = 3205 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3206 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3207 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3208 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3209 SDValue HiFalse = 3210 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3211 3212 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3213 3214 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3215 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3216 3217 SDValue Parts[2] = {Lo, Hi}; 3218 return DAG.getMergeValues(Parts, DL); 3219 } 3220 3221 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3222 // legal equivalently-sized i8 type, so we can use that as a go-between. 3223 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3224 SelectionDAG &DAG) const { 3225 SDLoc DL(Op); 3226 MVT VT = Op.getSimpleValueType(); 3227 SDValue SplatVal = Op.getOperand(0); 3228 // All-zeros or all-ones splats are handled specially. 3229 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3230 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3231 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3232 } 3233 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3234 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3235 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3236 } 3237 MVT XLenVT = Subtarget.getXLenVT(); 3238 assert(SplatVal.getValueType() == XLenVT && 3239 "Unexpected type for i1 splat value"); 3240 MVT InterVT = VT.changeVectorElementType(MVT::i8); 3241 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 3242 DAG.getConstant(1, DL, XLenVT)); 3243 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 3244 SDValue Zero = DAG.getConstant(0, DL, InterVT); 3245 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 3246 } 3247 3248 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 3249 // illegal (currently only vXi64 RV32). 3250 // FIXME: We could also catch non-constant sign-extended i32 values and lower 3251 // them to SPLAT_VECTOR_I64 3252 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 3253 SelectionDAG &DAG) const { 3254 SDLoc DL(Op); 3255 MVT VecVT = Op.getSimpleValueType(); 3256 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 3257 "Unexpected SPLAT_VECTOR_PARTS lowering"); 3258 3259 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 3260 SDValue Lo = Op.getOperand(0); 3261 SDValue Hi = Op.getOperand(1); 3262 3263 if (VecVT.isFixedLengthVector()) { 3264 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3265 SDLoc DL(Op); 3266 SDValue Mask, VL; 3267 std::tie(Mask, VL) = 3268 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3269 3270 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 3271 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 3272 } 3273 3274 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 3275 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 3276 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 3277 // If Hi constant is all the same sign bit as Lo, lower this as a custom 3278 // node in order to try and match RVV vector/scalar instructions. 3279 if ((LoC >> 31) == HiC) 3280 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3281 } 3282 3283 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 3284 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 3285 isa<ConstantSDNode>(Hi.getOperand(1)) && 3286 Hi.getConstantOperandVal(1) == 31) 3287 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3288 3289 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 3290 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 3291 DAG.getRegister(RISCV::X0, MVT::i64)); 3292 } 3293 3294 // Custom-lower extensions from mask vectors by using a vselect either with 1 3295 // for zero/any-extension or -1 for sign-extension: 3296 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 3297 // Note that any-extension is lowered identically to zero-extension. 3298 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 3299 int64_t ExtTrueVal) const { 3300 SDLoc DL(Op); 3301 MVT VecVT = Op.getSimpleValueType(); 3302 SDValue Src = Op.getOperand(0); 3303 // Only custom-lower extensions from mask types 3304 assert(Src.getValueType().isVector() && 3305 Src.getValueType().getVectorElementType() == MVT::i1); 3306 3307 MVT XLenVT = Subtarget.getXLenVT(); 3308 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 3309 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 3310 3311 if (VecVT.isScalableVector()) { 3312 // Be careful not to introduce illegal scalar types at this stage, and be 3313 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 3314 // illegal and must be expanded. Since we know that the constants are 3315 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 3316 bool IsRV32E64 = 3317 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 3318 3319 if (!IsRV32E64) { 3320 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 3321 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 3322 } else { 3323 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 3324 SplatTrueVal = 3325 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 3326 } 3327 3328 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 3329 } 3330 3331 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3332 MVT I1ContainerVT = 3333 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3334 3335 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 3336 3337 SDValue Mask, VL; 3338 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3339 3340 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 3341 SplatTrueVal = 3342 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 3343 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 3344 SplatTrueVal, SplatZero, VL); 3345 3346 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 3347 } 3348 3349 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 3350 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 3351 MVT ExtVT = Op.getSimpleValueType(); 3352 // Only custom-lower extensions from fixed-length vector types. 3353 if (!ExtVT.isFixedLengthVector()) 3354 return Op; 3355 MVT VT = Op.getOperand(0).getSimpleValueType(); 3356 // Grab the canonical container type for the extended type. Infer the smaller 3357 // type from that to ensure the same number of vector elements, as we know 3358 // the LMUL will be sufficient to hold the smaller type. 3359 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 3360 // Get the extended container type manually to ensure the same number of 3361 // vector elements between source and dest. 3362 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 3363 ContainerExtVT.getVectorElementCount()); 3364 3365 SDValue Op1 = 3366 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 3367 3368 SDLoc DL(Op); 3369 SDValue Mask, VL; 3370 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3371 3372 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 3373 3374 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 3375 } 3376 3377 // Custom-lower truncations from vectors to mask vectors by using a mask and a 3378 // setcc operation: 3379 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 3380 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 3381 SelectionDAG &DAG) const { 3382 SDLoc DL(Op); 3383 EVT MaskVT = Op.getValueType(); 3384 // Only expect to custom-lower truncations to mask types 3385 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 3386 "Unexpected type for vector mask lowering"); 3387 SDValue Src = Op.getOperand(0); 3388 MVT VecVT = Src.getSimpleValueType(); 3389 3390 // If this is a fixed vector, we need to convert it to a scalable vector. 3391 MVT ContainerVT = VecVT; 3392 if (VecVT.isFixedLengthVector()) { 3393 ContainerVT = getContainerForFixedLengthVector(VecVT); 3394 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3395 } 3396 3397 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 3398 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 3399 3400 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 3401 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 3402 3403 if (VecVT.isScalableVector()) { 3404 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 3405 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 3406 } 3407 3408 SDValue Mask, VL; 3409 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3410 3411 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 3412 SDValue Trunc = 3413 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 3414 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 3415 DAG.getCondCode(ISD::SETNE), Mask, VL); 3416 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 3417 } 3418 3419 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 3420 // first position of a vector, and that vector is slid up to the insert index. 3421 // By limiting the active vector length to index+1 and merging with the 3422 // original vector (with an undisturbed tail policy for elements >= VL), we 3423 // achieve the desired result of leaving all elements untouched except the one 3424 // at VL-1, which is replaced with the desired value. 3425 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3426 SelectionDAG &DAG) const { 3427 SDLoc DL(Op); 3428 MVT VecVT = Op.getSimpleValueType(); 3429 SDValue Vec = Op.getOperand(0); 3430 SDValue Val = Op.getOperand(1); 3431 SDValue Idx = Op.getOperand(2); 3432 3433 if (VecVT.getVectorElementType() == MVT::i1) { 3434 // FIXME: For now we just promote to an i8 vector and insert into that, 3435 // but this is probably not optimal. 3436 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3437 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3438 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 3439 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 3440 } 3441 3442 MVT ContainerVT = VecVT; 3443 // If the operand is a fixed-length vector, convert to a scalable one. 3444 if (VecVT.isFixedLengthVector()) { 3445 ContainerVT = getContainerForFixedLengthVector(VecVT); 3446 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3447 } 3448 3449 MVT XLenVT = Subtarget.getXLenVT(); 3450 3451 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3452 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 3453 // Even i64-element vectors on RV32 can be lowered without scalar 3454 // legalization if the most-significant 32 bits of the value are not affected 3455 // by the sign-extension of the lower 32 bits. 3456 // TODO: We could also catch sign extensions of a 32-bit value. 3457 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 3458 const auto *CVal = cast<ConstantSDNode>(Val); 3459 if (isInt<32>(CVal->getSExtValue())) { 3460 IsLegalInsert = true; 3461 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3462 } 3463 } 3464 3465 SDValue Mask, VL; 3466 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3467 3468 SDValue ValInVec; 3469 3470 if (IsLegalInsert) { 3471 unsigned Opc = 3472 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 3473 if (isNullConstant(Idx)) { 3474 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 3475 if (!VecVT.isFixedLengthVector()) 3476 return Vec; 3477 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 3478 } 3479 ValInVec = 3480 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 3481 } else { 3482 // On RV32, i64-element vectors must be specially handled to place the 3483 // value at element 0, by using two vslide1up instructions in sequence on 3484 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 3485 // this. 3486 SDValue One = DAG.getConstant(1, DL, XLenVT); 3487 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 3488 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 3489 MVT I32ContainerVT = 3490 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 3491 SDValue I32Mask = 3492 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 3493 // Limit the active VL to two. 3494 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 3495 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 3496 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 3497 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 3498 InsertI64VL); 3499 // First slide in the hi value, then the lo in underneath it. 3500 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3501 ValHi, I32Mask, InsertI64VL); 3502 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3503 ValLo, I32Mask, InsertI64VL); 3504 // Bitcast back to the right container type. 3505 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 3506 } 3507 3508 // Now that the value is in a vector, slide it into position. 3509 SDValue InsertVL = 3510 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 3511 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 3512 ValInVec, Idx, Mask, InsertVL); 3513 if (!VecVT.isFixedLengthVector()) 3514 return Slideup; 3515 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 3516 } 3517 3518 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 3519 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 3520 // types this is done using VMV_X_S to allow us to glean information about the 3521 // sign bits of the result. 3522 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 3523 SelectionDAG &DAG) const { 3524 SDLoc DL(Op); 3525 SDValue Idx = Op.getOperand(1); 3526 SDValue Vec = Op.getOperand(0); 3527 EVT EltVT = Op.getValueType(); 3528 MVT VecVT = Vec.getSimpleValueType(); 3529 MVT XLenVT = Subtarget.getXLenVT(); 3530 3531 if (VecVT.getVectorElementType() == MVT::i1) { 3532 // FIXME: For now we just promote to an i8 vector and extract from that, 3533 // but this is probably not optimal. 3534 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3535 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3536 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 3537 } 3538 3539 // If this is a fixed vector, we need to convert it to a scalable vector. 3540 MVT ContainerVT = VecVT; 3541 if (VecVT.isFixedLengthVector()) { 3542 ContainerVT = getContainerForFixedLengthVector(VecVT); 3543 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3544 } 3545 3546 // If the index is 0, the vector is already in the right position. 3547 if (!isNullConstant(Idx)) { 3548 // Use a VL of 1 to avoid processing more elements than we need. 3549 SDValue VL = DAG.getConstant(1, DL, XLenVT); 3550 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3551 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 3552 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 3553 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 3554 } 3555 3556 if (!EltVT.isInteger()) { 3557 // Floating-point extracts are handled in TableGen. 3558 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 3559 DAG.getConstant(0, DL, XLenVT)); 3560 } 3561 3562 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 3563 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 3564 } 3565 3566 // Some RVV intrinsics may claim that they want an integer operand to be 3567 // promoted or expanded. 3568 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 3569 const RISCVSubtarget &Subtarget) { 3570 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3571 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 3572 "Unexpected opcode"); 3573 3574 if (!Subtarget.hasStdExtV()) 3575 return SDValue(); 3576 3577 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 3578 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 3579 SDLoc DL(Op); 3580 3581 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 3582 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 3583 if (!II || !II->SplatOperand) 3584 return SDValue(); 3585 3586 unsigned SplatOp = II->SplatOperand + HasChain; 3587 assert(SplatOp < Op.getNumOperands()); 3588 3589 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 3590 SDValue &ScalarOp = Operands[SplatOp]; 3591 MVT OpVT = ScalarOp.getSimpleValueType(); 3592 MVT XLenVT = Subtarget.getXLenVT(); 3593 3594 // If this isn't a scalar, or its type is XLenVT we're done. 3595 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 3596 return SDValue(); 3597 3598 // Simplest case is that the operand needs to be promoted to XLenVT. 3599 if (OpVT.bitsLT(XLenVT)) { 3600 // If the operand is a constant, sign extend to increase our chances 3601 // of being able to use a .vi instruction. ANY_EXTEND would become a 3602 // a zero extend and the simm5 check in isel would fail. 3603 // FIXME: Should we ignore the upper bits in isel instead? 3604 unsigned ExtOpc = 3605 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 3606 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 3607 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3608 } 3609 3610 // Use the previous operand to get the vXi64 VT. The result might be a mask 3611 // VT for compares. Using the previous operand assumes that the previous 3612 // operand will never have a smaller element size than a scalar operand and 3613 // that a widening operation never uses SEW=64. 3614 // NOTE: If this fails the below assert, we can probably just find the 3615 // element count from any operand or result and use it to construct the VT. 3616 assert(II->SplatOperand > 1 && "Unexpected splat operand!"); 3617 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 3618 3619 // The more complex case is when the scalar is larger than XLenVT. 3620 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 3621 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 3622 3623 // If this is a sign-extended 32-bit constant, we can truncate it and rely 3624 // on the instruction to sign-extend since SEW>XLEN. 3625 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 3626 if (isInt<32>(CVal->getSExtValue())) { 3627 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3628 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3629 } 3630 } 3631 3632 // We need to convert the scalar to a splat vector. 3633 // FIXME: Can we implicitly truncate the scalar if it is known to 3634 // be sign extended? 3635 // VL should be the last operand. 3636 SDValue VL = Op.getOperand(Op.getNumOperands() - 1); 3637 assert(VL.getValueType() == XLenVT); 3638 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 3639 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3640 } 3641 3642 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3643 SelectionDAG &DAG) const { 3644 unsigned IntNo = Op.getConstantOperandVal(0); 3645 SDLoc DL(Op); 3646 MVT XLenVT = Subtarget.getXLenVT(); 3647 3648 switch (IntNo) { 3649 default: 3650 break; // Don't custom lower most intrinsics. 3651 case Intrinsic::thread_pointer: { 3652 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3653 return DAG.getRegister(RISCV::X4, PtrVT); 3654 } 3655 case Intrinsic::riscv_orc_b: 3656 // Lower to the GORCI encoding for orc.b. 3657 return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1), 3658 DAG.getConstant(7, DL, XLenVT)); 3659 case Intrinsic::riscv_grev: 3660 case Intrinsic::riscv_gorc: { 3661 unsigned Opc = 3662 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 3663 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3664 } 3665 case Intrinsic::riscv_shfl: 3666 case Intrinsic::riscv_unshfl: { 3667 unsigned Opc = 3668 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 3669 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3670 } 3671 case Intrinsic::riscv_bcompress: 3672 case Intrinsic::riscv_bdecompress: { 3673 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 3674 : RISCVISD::BDECOMPRESS; 3675 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3676 } 3677 case Intrinsic::riscv_vmv_x_s: 3678 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 3679 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 3680 Op.getOperand(1)); 3681 case Intrinsic::riscv_vmv_v_x: 3682 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 3683 Op.getSimpleValueType(), DL, DAG, Subtarget); 3684 case Intrinsic::riscv_vfmv_v_f: 3685 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 3686 Op.getOperand(1), Op.getOperand(2)); 3687 case Intrinsic::riscv_vmv_s_x: { 3688 SDValue Scalar = Op.getOperand(2); 3689 3690 if (Scalar.getValueType().bitsLE(XLenVT)) { 3691 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 3692 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 3693 Op.getOperand(1), Scalar, Op.getOperand(3)); 3694 } 3695 3696 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 3697 3698 // This is an i64 value that lives in two scalar registers. We have to 3699 // insert this in a convoluted way. First we build vXi64 splat containing 3700 // the/ two values that we assemble using some bit math. Next we'll use 3701 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 3702 // to merge element 0 from our splat into the source vector. 3703 // FIXME: This is probably not the best way to do this, but it is 3704 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 3705 // point. 3706 // sw lo, (a0) 3707 // sw hi, 4(a0) 3708 // vlse vX, (a0) 3709 // 3710 // vid.v vVid 3711 // vmseq.vx mMask, vVid, 0 3712 // vmerge.vvm vDest, vSrc, vVal, mMask 3713 MVT VT = Op.getSimpleValueType(); 3714 SDValue Vec = Op.getOperand(1); 3715 SDValue VL = Op.getOperand(3); 3716 3717 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 3718 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 3719 DAG.getConstant(0, DL, MVT::i32), VL); 3720 3721 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 3722 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 3723 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 3724 SDValue SelectCond = 3725 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 3726 DAG.getCondCode(ISD::SETEQ), Mask, VL); 3727 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 3728 Vec, VL); 3729 } 3730 case Intrinsic::riscv_vslide1up: 3731 case Intrinsic::riscv_vslide1down: 3732 case Intrinsic::riscv_vslide1up_mask: 3733 case Intrinsic::riscv_vslide1down_mask: { 3734 // We need to special case these when the scalar is larger than XLen. 3735 unsigned NumOps = Op.getNumOperands(); 3736 bool IsMasked = NumOps == 6; 3737 unsigned OpOffset = IsMasked ? 1 : 0; 3738 SDValue Scalar = Op.getOperand(2 + OpOffset); 3739 if (Scalar.getValueType().bitsLE(XLenVT)) 3740 break; 3741 3742 // Splatting a sign extended constant is fine. 3743 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 3744 if (isInt<32>(CVal->getSExtValue())) 3745 break; 3746 3747 MVT VT = Op.getSimpleValueType(); 3748 assert(VT.getVectorElementType() == MVT::i64 && 3749 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 3750 3751 // Convert the vector source to the equivalent nxvXi32 vector. 3752 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 3753 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 3754 3755 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 3756 DAG.getConstant(0, DL, XLenVT)); 3757 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 3758 DAG.getConstant(1, DL, XLenVT)); 3759 3760 // Double the VL since we halved SEW. 3761 SDValue VL = Op.getOperand(NumOps - 1); 3762 SDValue I32VL = 3763 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 3764 3765 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 3766 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 3767 3768 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 3769 // instructions. 3770 if (IntNo == Intrinsic::riscv_vslide1up || 3771 IntNo == Intrinsic::riscv_vslide1up_mask) { 3772 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 3773 I32Mask, I32VL); 3774 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 3775 I32Mask, I32VL); 3776 } else { 3777 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 3778 I32Mask, I32VL); 3779 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 3780 I32Mask, I32VL); 3781 } 3782 3783 // Convert back to nxvXi64. 3784 Vec = DAG.getBitcast(VT, Vec); 3785 3786 if (!IsMasked) 3787 return Vec; 3788 3789 // Apply mask after the operation. 3790 SDValue Mask = Op.getOperand(NumOps - 2); 3791 SDValue MaskedOff = Op.getOperand(1); 3792 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 3793 } 3794 } 3795 3796 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 3797 } 3798 3799 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 3800 SelectionDAG &DAG) const { 3801 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 3802 } 3803 3804 static MVT getLMUL1VT(MVT VT) { 3805 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 3806 "Unexpected vector MVT"); 3807 return MVT::getScalableVectorVT( 3808 VT.getVectorElementType(), 3809 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 3810 } 3811 3812 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 3813 switch (ISDOpcode) { 3814 default: 3815 llvm_unreachable("Unhandled reduction"); 3816 case ISD::VECREDUCE_ADD: 3817 return RISCVISD::VECREDUCE_ADD_VL; 3818 case ISD::VECREDUCE_UMAX: 3819 return RISCVISD::VECREDUCE_UMAX_VL; 3820 case ISD::VECREDUCE_SMAX: 3821 return RISCVISD::VECREDUCE_SMAX_VL; 3822 case ISD::VECREDUCE_UMIN: 3823 return RISCVISD::VECREDUCE_UMIN_VL; 3824 case ISD::VECREDUCE_SMIN: 3825 return RISCVISD::VECREDUCE_SMIN_VL; 3826 case ISD::VECREDUCE_AND: 3827 return RISCVISD::VECREDUCE_AND_VL; 3828 case ISD::VECREDUCE_OR: 3829 return RISCVISD::VECREDUCE_OR_VL; 3830 case ISD::VECREDUCE_XOR: 3831 return RISCVISD::VECREDUCE_XOR_VL; 3832 } 3833 } 3834 3835 SDValue RISCVTargetLowering::lowerVectorMaskVECREDUCE(SDValue Op, 3836 SelectionDAG &DAG) const { 3837 SDLoc DL(Op); 3838 SDValue Vec = Op.getOperand(0); 3839 MVT VecVT = Vec.getSimpleValueType(); 3840 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 3841 Op.getOpcode() == ISD::VECREDUCE_OR || 3842 Op.getOpcode() == ISD::VECREDUCE_XOR) && 3843 "Unexpected reduction lowering"); 3844 3845 MVT XLenVT = Subtarget.getXLenVT(); 3846 assert(Op.getValueType() == XLenVT && 3847 "Expected reduction output to be legalized to XLenVT"); 3848 3849 MVT ContainerVT = VecVT; 3850 if (VecVT.isFixedLengthVector()) { 3851 ContainerVT = getContainerForFixedLengthVector(VecVT); 3852 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3853 } 3854 3855 SDValue Mask, VL; 3856 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3857 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3858 3859 switch (Op.getOpcode()) { 3860 default: 3861 llvm_unreachable("Unhandled reduction"); 3862 case ISD::VECREDUCE_AND: 3863 // vpopc ~x == 0 3864 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, Mask, VL); 3865 Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL); 3866 return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETEQ); 3867 case ISD::VECREDUCE_OR: 3868 // vpopc x != 0 3869 Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL); 3870 return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETNE); 3871 case ISD::VECREDUCE_XOR: { 3872 // ((vpopc x) & 1) != 0 3873 SDValue One = DAG.getConstant(1, DL, XLenVT); 3874 Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL); 3875 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 3876 return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETNE); 3877 } 3878 } 3879 } 3880 3881 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 3882 SelectionDAG &DAG) const { 3883 SDLoc DL(Op); 3884 SDValue Vec = Op.getOperand(0); 3885 EVT VecEVT = Vec.getValueType(); 3886 3887 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 3888 3889 // Due to ordering in legalize types we may have a vector type that needs to 3890 // be split. Do that manually so we can get down to a legal type. 3891 while (getTypeAction(*DAG.getContext(), VecEVT) == 3892 TargetLowering::TypeSplitVector) { 3893 SDValue Lo, Hi; 3894 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 3895 VecEVT = Lo.getValueType(); 3896 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 3897 } 3898 3899 // TODO: The type may need to be widened rather than split. Or widened before 3900 // it can be split. 3901 if (!isTypeLegal(VecEVT)) 3902 return SDValue(); 3903 3904 MVT VecVT = VecEVT.getSimpleVT(); 3905 MVT VecEltVT = VecVT.getVectorElementType(); 3906 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 3907 3908 MVT ContainerVT = VecVT; 3909 if (VecVT.isFixedLengthVector()) { 3910 ContainerVT = getContainerForFixedLengthVector(VecVT); 3911 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3912 } 3913 3914 MVT M1VT = getLMUL1VT(ContainerVT); 3915 3916 SDValue Mask, VL; 3917 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3918 3919 // FIXME: This is a VLMAX splat which might be too large and can prevent 3920 // vsetvli removal. 3921 SDValue NeutralElem = 3922 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 3923 SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem); 3924 SDValue Reduction = 3925 DAG.getNode(RVVOpcode, DL, M1VT, Vec, IdentitySplat, Mask, VL); 3926 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 3927 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 3928 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 3929 } 3930 3931 // Given a reduction op, this function returns the matching reduction opcode, 3932 // the vector SDValue and the scalar SDValue required to lower this to a 3933 // RISCVISD node. 3934 static std::tuple<unsigned, SDValue, SDValue> 3935 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 3936 SDLoc DL(Op); 3937 auto Flags = Op->getFlags(); 3938 unsigned Opcode = Op.getOpcode(); 3939 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 3940 switch (Opcode) { 3941 default: 3942 llvm_unreachable("Unhandled reduction"); 3943 case ISD::VECREDUCE_FADD: 3944 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), 3945 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 3946 case ISD::VECREDUCE_SEQ_FADD: 3947 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 3948 Op.getOperand(0)); 3949 case ISD::VECREDUCE_FMIN: 3950 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 3951 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 3952 case ISD::VECREDUCE_FMAX: 3953 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 3954 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 3955 } 3956 } 3957 3958 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 3959 SelectionDAG &DAG) const { 3960 SDLoc DL(Op); 3961 MVT VecEltVT = Op.getSimpleValueType(); 3962 3963 unsigned RVVOpcode; 3964 SDValue VectorVal, ScalarVal; 3965 std::tie(RVVOpcode, VectorVal, ScalarVal) = 3966 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 3967 MVT VecVT = VectorVal.getSimpleValueType(); 3968 3969 MVT ContainerVT = VecVT; 3970 if (VecVT.isFixedLengthVector()) { 3971 ContainerVT = getContainerForFixedLengthVector(VecVT); 3972 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 3973 } 3974 3975 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 3976 3977 SDValue Mask, VL; 3978 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3979 3980 // FIXME: This is a VLMAX splat which might be too large and can prevent 3981 // vsetvli removal. 3982 SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal); 3983 SDValue Reduction = 3984 DAG.getNode(RVVOpcode, DL, M1VT, VectorVal, ScalarSplat, Mask, VL); 3985 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 3986 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 3987 } 3988 3989 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 3990 SelectionDAG &DAG) const { 3991 SDValue Vec = Op.getOperand(0); 3992 SDValue SubVec = Op.getOperand(1); 3993 MVT VecVT = Vec.getSimpleValueType(); 3994 MVT SubVecVT = SubVec.getSimpleValueType(); 3995 3996 SDLoc DL(Op); 3997 MVT XLenVT = Subtarget.getXLenVT(); 3998 unsigned OrigIdx = Op.getConstantOperandVal(2); 3999 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4000 4001 // We don't have the ability to slide mask vectors up indexed by their i1 4002 // elements; the smallest we can do is i8. Often we are able to bitcast to 4003 // equivalent i8 vectors. Note that when inserting a fixed-length vector 4004 // into a scalable one, we might not necessarily have enough scalable 4005 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 4006 if (SubVecVT.getVectorElementType() == MVT::i1 && 4007 (OrigIdx != 0 || !Vec.isUndef())) { 4008 if (VecVT.getVectorMinNumElements() >= 8 && 4009 SubVecVT.getVectorMinNumElements() >= 8) { 4010 assert(OrigIdx % 8 == 0 && "Invalid index"); 4011 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4012 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4013 "Unexpected mask vector lowering"); 4014 OrigIdx /= 8; 4015 SubVecVT = 4016 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4017 SubVecVT.isScalableVector()); 4018 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4019 VecVT.isScalableVector()); 4020 Vec = DAG.getBitcast(VecVT, Vec); 4021 SubVec = DAG.getBitcast(SubVecVT, SubVec); 4022 } else { 4023 // We can't slide this mask vector up indexed by its i1 elements. 4024 // This poses a problem when we wish to insert a scalable vector which 4025 // can't be re-expressed as a larger type. Just choose the slow path and 4026 // extend to a larger type, then truncate back down. 4027 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4028 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4029 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4030 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 4031 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 4032 Op.getOperand(2)); 4033 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 4034 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 4035 } 4036 } 4037 4038 // If the subvector vector is a fixed-length type, we cannot use subregister 4039 // manipulation to simplify the codegen; we don't know which register of a 4040 // LMUL group contains the specific subvector as we only know the minimum 4041 // register size. Therefore we must slide the vector group up the full 4042 // amount. 4043 if (SubVecVT.isFixedLengthVector()) { 4044 if (OrigIdx == 0 && Vec.isUndef()) 4045 return Op; 4046 MVT ContainerVT = VecVT; 4047 if (VecVT.isFixedLengthVector()) { 4048 ContainerVT = getContainerForFixedLengthVector(VecVT); 4049 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4050 } 4051 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 4052 DAG.getUNDEF(ContainerVT), SubVec, 4053 DAG.getConstant(0, DL, XLenVT)); 4054 SDValue Mask = 4055 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4056 // Set the vector length to only the number of elements we care about. Note 4057 // that for slideup this includes the offset. 4058 SDValue VL = 4059 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 4060 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4061 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4062 SubVec, SlideupAmt, Mask, VL); 4063 if (VecVT.isFixedLengthVector()) 4064 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4065 return DAG.getBitcast(Op.getValueType(), Slideup); 4066 } 4067 4068 unsigned SubRegIdx, RemIdx; 4069 std::tie(SubRegIdx, RemIdx) = 4070 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4071 VecVT, SubVecVT, OrigIdx, TRI); 4072 4073 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 4074 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 4075 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 4076 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 4077 4078 // 1. If the Idx has been completely eliminated and this subvector's size is 4079 // a vector register or a multiple thereof, or the surrounding elements are 4080 // undef, then this is a subvector insert which naturally aligns to a vector 4081 // register. These can easily be handled using subregister manipulation. 4082 // 2. If the subvector is smaller than a vector register, then the insertion 4083 // must preserve the undisturbed elements of the register. We do this by 4084 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 4085 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 4086 // subvector within the vector register, and an INSERT_SUBVECTOR of that 4087 // LMUL=1 type back into the larger vector (resolving to another subregister 4088 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 4089 // to avoid allocating a large register group to hold our subvector. 4090 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 4091 return Op; 4092 4093 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 4094 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 4095 // (in our case undisturbed). This means we can set up a subvector insertion 4096 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 4097 // size of the subvector. 4098 MVT InterSubVT = VecVT; 4099 SDValue AlignedExtract = Vec; 4100 unsigned AlignedIdx = OrigIdx - RemIdx; 4101 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4102 InterSubVT = getLMUL1VT(VecVT); 4103 // Extract a subvector equal to the nearest full vector register type. This 4104 // should resolve to a EXTRACT_SUBREG instruction. 4105 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4106 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4107 } 4108 4109 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4110 // For scalable vectors this must be further multiplied by vscale. 4111 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 4112 4113 SDValue Mask, VL; 4114 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4115 4116 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 4117 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 4118 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 4119 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 4120 4121 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 4122 DAG.getUNDEF(InterSubVT), SubVec, 4123 DAG.getConstant(0, DL, XLenVT)); 4124 4125 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 4126 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 4127 4128 // If required, insert this subvector back into the correct vector register. 4129 // This should resolve to an INSERT_SUBREG instruction. 4130 if (VecVT.bitsGT(InterSubVT)) 4131 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 4132 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4133 4134 // We might have bitcast from a mask type: cast back to the original type if 4135 // required. 4136 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 4137 } 4138 4139 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 4140 SelectionDAG &DAG) const { 4141 SDValue Vec = Op.getOperand(0); 4142 MVT SubVecVT = Op.getSimpleValueType(); 4143 MVT VecVT = Vec.getSimpleValueType(); 4144 4145 SDLoc DL(Op); 4146 MVT XLenVT = Subtarget.getXLenVT(); 4147 unsigned OrigIdx = Op.getConstantOperandVal(1); 4148 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4149 4150 // We don't have the ability to slide mask vectors down indexed by their i1 4151 // elements; the smallest we can do is i8. Often we are able to bitcast to 4152 // equivalent i8 vectors. Note that when extracting a fixed-length vector 4153 // from a scalable one, we might not necessarily have enough scalable 4154 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 4155 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 4156 if (VecVT.getVectorMinNumElements() >= 8 && 4157 SubVecVT.getVectorMinNumElements() >= 8) { 4158 assert(OrigIdx % 8 == 0 && "Invalid index"); 4159 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4160 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4161 "Unexpected mask vector lowering"); 4162 OrigIdx /= 8; 4163 SubVecVT = 4164 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4165 SubVecVT.isScalableVector()); 4166 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4167 VecVT.isScalableVector()); 4168 Vec = DAG.getBitcast(VecVT, Vec); 4169 } else { 4170 // We can't slide this mask vector down, indexed by its i1 elements. 4171 // This poses a problem when we wish to extract a scalable vector which 4172 // can't be re-expressed as a larger type. Just choose the slow path and 4173 // extend to a larger type, then truncate back down. 4174 // TODO: We could probably improve this when extracting certain fixed 4175 // from fixed, where we can extract as i8 and shift the correct element 4176 // right to reach the desired subvector? 4177 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4178 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4179 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4180 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 4181 Op.getOperand(1)); 4182 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 4183 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 4184 } 4185 } 4186 4187 // If the subvector vector is a fixed-length type, we cannot use subregister 4188 // manipulation to simplify the codegen; we don't know which register of a 4189 // LMUL group contains the specific subvector as we only know the minimum 4190 // register size. Therefore we must slide the vector group down the full 4191 // amount. 4192 if (SubVecVT.isFixedLengthVector()) { 4193 // With an index of 0 this is a cast-like subvector, which can be performed 4194 // with subregister operations. 4195 if (OrigIdx == 0) 4196 return Op; 4197 MVT ContainerVT = VecVT; 4198 if (VecVT.isFixedLengthVector()) { 4199 ContainerVT = getContainerForFixedLengthVector(VecVT); 4200 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4201 } 4202 SDValue Mask = 4203 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4204 // Set the vector length to only the number of elements we care about. This 4205 // avoids sliding down elements we're going to discard straight away. 4206 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 4207 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4208 SDValue Slidedown = 4209 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4210 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 4211 // Now we can use a cast-like subvector extract to get the result. 4212 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4213 DAG.getConstant(0, DL, XLenVT)); 4214 return DAG.getBitcast(Op.getValueType(), Slidedown); 4215 } 4216 4217 unsigned SubRegIdx, RemIdx; 4218 std::tie(SubRegIdx, RemIdx) = 4219 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4220 VecVT, SubVecVT, OrigIdx, TRI); 4221 4222 // If the Idx has been completely eliminated then this is a subvector extract 4223 // which naturally aligns to a vector register. These can easily be handled 4224 // using subregister manipulation. 4225 if (RemIdx == 0) 4226 return Op; 4227 4228 // Else we must shift our vector register directly to extract the subvector. 4229 // Do this using VSLIDEDOWN. 4230 4231 // If the vector type is an LMUL-group type, extract a subvector equal to the 4232 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 4233 // instruction. 4234 MVT InterSubVT = VecVT; 4235 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4236 InterSubVT = getLMUL1VT(VecVT); 4237 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4238 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 4239 } 4240 4241 // Slide this vector register down by the desired number of elements in order 4242 // to place the desired subvector starting at element 0. 4243 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4244 // For scalable vectors this must be further multiplied by vscale. 4245 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 4246 4247 SDValue Mask, VL; 4248 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 4249 SDValue Slidedown = 4250 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 4251 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 4252 4253 // Now the vector is in the right position, extract our final subvector. This 4254 // should resolve to a COPY. 4255 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4256 DAG.getConstant(0, DL, XLenVT)); 4257 4258 // We might have bitcast from a mask type: cast back to the original type if 4259 // required. 4260 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 4261 } 4262 4263 // Lower step_vector to the vid instruction. Any non-identity step value must 4264 // be accounted for my manual expansion. 4265 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 4266 SelectionDAG &DAG) const { 4267 SDLoc DL(Op); 4268 MVT VT = Op.getSimpleValueType(); 4269 MVT XLenVT = Subtarget.getXLenVT(); 4270 SDValue Mask, VL; 4271 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 4272 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4273 uint64_t StepValImm = Op.getConstantOperandVal(0); 4274 if (StepValImm != 1) { 4275 if (isPowerOf2_64(StepValImm)) { 4276 SDValue StepVal = 4277 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4278 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 4279 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 4280 } else { 4281 SDValue StepVal = lowerScalarSplat( 4282 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 4283 DL, DAG, Subtarget); 4284 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 4285 } 4286 } 4287 return StepVec; 4288 } 4289 4290 // Implement vector_reverse using vrgather.vv with indices determined by 4291 // subtracting the id of each element from (VLMAX-1). This will convert 4292 // the indices like so: 4293 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 4294 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 4295 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 4296 SelectionDAG &DAG) const { 4297 SDLoc DL(Op); 4298 MVT VecVT = Op.getSimpleValueType(); 4299 unsigned EltSize = VecVT.getScalarSizeInBits(); 4300 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 4301 4302 unsigned MaxVLMAX = 0; 4303 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 4304 if (VectorBitsMax != 0) 4305 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 4306 4307 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 4308 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 4309 4310 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 4311 // to use vrgatherei16.vv. 4312 // TODO: It's also possible to use vrgatherei16.vv for other types to 4313 // decrease register width for the index calculation. 4314 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 4315 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 4316 // Reverse each half, then reassemble them in reverse order. 4317 // NOTE: It's also possible that after splitting that VLMAX no longer 4318 // requires vrgatherei16.vv. 4319 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 4320 SDValue Lo, Hi; 4321 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4322 EVT LoVT, HiVT; 4323 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 4324 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 4325 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 4326 // Reassemble the low and high pieces reversed. 4327 // FIXME: This is a CONCAT_VECTORS. 4328 SDValue Res = 4329 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 4330 DAG.getIntPtrConstant(0, DL)); 4331 return DAG.getNode( 4332 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 4333 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 4334 } 4335 4336 // Just promote the int type to i16 which will double the LMUL. 4337 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 4338 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 4339 } 4340 4341 MVT XLenVT = Subtarget.getXLenVT(); 4342 SDValue Mask, VL; 4343 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4344 4345 // Calculate VLMAX-1 for the desired SEW. 4346 unsigned MinElts = VecVT.getVectorMinNumElements(); 4347 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 4348 DAG.getConstant(MinElts, DL, XLenVT)); 4349 SDValue VLMinus1 = 4350 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 4351 4352 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 4353 bool IsRV32E64 = 4354 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 4355 SDValue SplatVL; 4356 if (!IsRV32E64) 4357 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 4358 else 4359 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 4360 4361 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 4362 SDValue Indices = 4363 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 4364 4365 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 4366 } 4367 4368 SDValue 4369 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 4370 SelectionDAG &DAG) const { 4371 SDLoc DL(Op); 4372 auto *Load = cast<LoadSDNode>(Op); 4373 4374 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 4375 Load->getMemoryVT(), 4376 *Load->getMemOperand()) && 4377 "Expecting a correctly-aligned load"); 4378 4379 MVT VT = Op.getSimpleValueType(); 4380 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4381 4382 SDValue VL = 4383 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4384 4385 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4386 SDValue NewLoad = DAG.getMemIntrinsicNode( 4387 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 4388 Load->getMemoryVT(), Load->getMemOperand()); 4389 4390 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 4391 return DAG.getMergeValues({Result, Load->getChain()}, DL); 4392 } 4393 4394 SDValue 4395 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 4396 SelectionDAG &DAG) const { 4397 SDLoc DL(Op); 4398 auto *Store = cast<StoreSDNode>(Op); 4399 4400 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 4401 Store->getMemoryVT(), 4402 *Store->getMemOperand()) && 4403 "Expecting a correctly-aligned store"); 4404 4405 SDValue StoreVal = Store->getValue(); 4406 MVT VT = StoreVal.getSimpleValueType(); 4407 4408 // If the size less than a byte, we need to pad with zeros to make a byte. 4409 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 4410 VT = MVT::v8i1; 4411 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 4412 DAG.getConstant(0, DL, VT), StoreVal, 4413 DAG.getIntPtrConstant(0, DL)); 4414 } 4415 4416 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4417 4418 SDValue VL = 4419 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4420 4421 SDValue NewValue = 4422 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 4423 return DAG.getMemIntrinsicNode( 4424 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 4425 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 4426 Store->getMemoryVT(), Store->getMemOperand()); 4427 } 4428 4429 SDValue RISCVTargetLowering::lowerMLOAD(SDValue Op, SelectionDAG &DAG) const { 4430 auto *Load = cast<MaskedLoadSDNode>(Op); 4431 4432 SDLoc DL(Op); 4433 MVT VT = Op.getSimpleValueType(); 4434 MVT XLenVT = Subtarget.getXLenVT(); 4435 4436 SDValue Mask = Load->getMask(); 4437 SDValue PassThru = Load->getPassThru(); 4438 SDValue VL; 4439 4440 MVT ContainerVT = VT; 4441 if (VT.isFixedLengthVector()) { 4442 ContainerVT = getContainerForFixedLengthVector(VT); 4443 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4444 4445 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4446 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4447 VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4448 } else 4449 VL = DAG.getRegister(RISCV::X0, XLenVT); 4450 4451 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4452 SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vle_mask, DL, XLenVT); 4453 SDValue Ops[] = {Load->getChain(), IntID, PassThru, 4454 Load->getBasePtr(), Mask, VL}; 4455 SDValue Result = 4456 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4457 Load->getMemoryVT(), Load->getMemOperand()); 4458 SDValue Chain = Result.getValue(1); 4459 4460 if (VT.isFixedLengthVector()) 4461 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4462 4463 return DAG.getMergeValues({Result, Chain}, DL); 4464 } 4465 4466 SDValue RISCVTargetLowering::lowerMSTORE(SDValue Op, SelectionDAG &DAG) const { 4467 auto *Store = cast<MaskedStoreSDNode>(Op); 4468 4469 SDLoc DL(Op); 4470 SDValue Val = Store->getValue(); 4471 SDValue Mask = Store->getMask(); 4472 MVT VT = Val.getSimpleValueType(); 4473 MVT XLenVT = Subtarget.getXLenVT(); 4474 SDValue VL; 4475 4476 MVT ContainerVT = VT; 4477 if (VT.isFixedLengthVector()) { 4478 ContainerVT = getContainerForFixedLengthVector(VT); 4479 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4480 4481 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4482 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4483 VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4484 } else 4485 VL = DAG.getRegister(RISCV::X0, XLenVT); 4486 4487 SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vse_mask, DL, XLenVT); 4488 return DAG.getMemIntrinsicNode( 4489 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 4490 {Store->getChain(), IntID, Val, Store->getBasePtr(), Mask, VL}, 4491 Store->getMemoryVT(), Store->getMemOperand()); 4492 } 4493 4494 SDValue 4495 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 4496 SelectionDAG &DAG) const { 4497 MVT InVT = Op.getOperand(0).getSimpleValueType(); 4498 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 4499 4500 MVT VT = Op.getSimpleValueType(); 4501 4502 SDValue Op1 = 4503 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4504 SDValue Op2 = 4505 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 4506 4507 SDLoc DL(Op); 4508 SDValue VL = 4509 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4510 4511 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4512 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4513 4514 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 4515 Op.getOperand(2), Mask, VL); 4516 4517 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 4518 } 4519 4520 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 4521 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 4522 MVT VT = Op.getSimpleValueType(); 4523 4524 if (VT.getVectorElementType() == MVT::i1) 4525 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 4526 4527 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 4528 } 4529 4530 SDValue 4531 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 4532 SelectionDAG &DAG) const { 4533 unsigned Opc; 4534 switch (Op.getOpcode()) { 4535 default: llvm_unreachable("Unexpected opcode!"); 4536 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 4537 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 4538 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 4539 } 4540 4541 return lowerToScalableOp(Op, DAG, Opc); 4542 } 4543 4544 // Lower vector ABS to smax(X, sub(0, X)). 4545 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 4546 SDLoc DL(Op); 4547 MVT VT = Op.getSimpleValueType(); 4548 SDValue X = Op.getOperand(0); 4549 4550 assert(VT.isFixedLengthVector() && "Unexpected type"); 4551 4552 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4553 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 4554 4555 SDValue Mask, VL; 4556 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4557 4558 SDValue SplatZero = 4559 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4560 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4561 SDValue NegX = 4562 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 4563 SDValue Max = 4564 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 4565 4566 return convertFromScalableVector(VT, Max, DAG, Subtarget); 4567 } 4568 4569 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 4570 SDValue Op, SelectionDAG &DAG) const { 4571 SDLoc DL(Op); 4572 MVT VT = Op.getSimpleValueType(); 4573 SDValue Mag = Op.getOperand(0); 4574 SDValue Sign = Op.getOperand(1); 4575 assert(Mag.getValueType() == Sign.getValueType() && 4576 "Can only handle COPYSIGN with matching types."); 4577 4578 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4579 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 4580 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 4581 4582 SDValue Mask, VL; 4583 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4584 4585 SDValue CopySign = 4586 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 4587 4588 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 4589 } 4590 4591 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 4592 SDValue Op, SelectionDAG &DAG) const { 4593 MVT VT = Op.getSimpleValueType(); 4594 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4595 4596 MVT I1ContainerVT = 4597 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4598 4599 SDValue CC = 4600 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 4601 SDValue Op1 = 4602 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 4603 SDValue Op2 = 4604 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 4605 4606 SDLoc DL(Op); 4607 SDValue Mask, VL; 4608 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4609 4610 SDValue Select = 4611 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 4612 4613 return convertFromScalableVector(VT, Select, DAG, Subtarget); 4614 } 4615 4616 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 4617 unsigned NewOpc, 4618 bool HasMask) const { 4619 MVT VT = Op.getSimpleValueType(); 4620 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4621 4622 // Create list of operands by converting existing ones to scalable types. 4623 SmallVector<SDValue, 6> Ops; 4624 for (const SDValue &V : Op->op_values()) { 4625 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 4626 4627 // Pass through non-vector operands. 4628 if (!V.getValueType().isVector()) { 4629 Ops.push_back(V); 4630 continue; 4631 } 4632 4633 // "cast" fixed length vector to a scalable vector. 4634 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 4635 "Only fixed length vectors are supported!"); 4636 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 4637 } 4638 4639 SDLoc DL(Op); 4640 SDValue Mask, VL; 4641 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4642 if (HasMask) 4643 Ops.push_back(Mask); 4644 Ops.push_back(VL); 4645 4646 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 4647 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 4648 } 4649 4650 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 4651 // * Operands of each node are assumed to be in the same order. 4652 // * The EVL operand is promoted from i32 to i64 on RV64. 4653 // * Fixed-length vectors are converted to their scalable-vector container 4654 // types. 4655 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 4656 unsigned RISCVISDOpc) const { 4657 SDLoc DL(Op); 4658 MVT VT = Op.getSimpleValueType(); 4659 SmallVector<SDValue, 4> Ops; 4660 4661 for (const auto &OpIdx : enumerate(Op->ops())) { 4662 SDValue V = OpIdx.value(); 4663 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 4664 // Pass through operands which aren't fixed-length vectors. 4665 if (!V.getValueType().isFixedLengthVector()) { 4666 Ops.push_back(V); 4667 continue; 4668 } 4669 // "cast" fixed length vector to a scalable vector. 4670 MVT OpVT = V.getSimpleValueType(); 4671 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 4672 assert(useRVVForFixedLengthVectorVT(OpVT) && 4673 "Only fixed length vectors are supported!"); 4674 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 4675 } 4676 4677 if (!VT.isFixedLengthVector()) 4678 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 4679 4680 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4681 4682 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 4683 4684 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 4685 } 4686 4687 // Custom lower MGATHER to a legalized form for RVV. It will then be matched to 4688 // a RVV indexed load. The RVV indexed load instructions only support the 4689 // "unsigned unscaled" addressing mode; indices are implicitly zero-extended or 4690 // truncated to XLEN and are treated as byte offsets. Any signed or scaled 4691 // indexing is extended to the XLEN value type and scaled accordingly. 4692 SDValue RISCVTargetLowering::lowerMGATHER(SDValue Op, SelectionDAG &DAG) const { 4693 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 4694 SDLoc DL(Op); 4695 4696 SDValue Index = MGN->getIndex(); 4697 SDValue Mask = MGN->getMask(); 4698 SDValue PassThru = MGN->getPassThru(); 4699 4700 MVT VT = Op.getSimpleValueType(); 4701 MVT IndexVT = Index.getSimpleValueType(); 4702 MVT XLenVT = Subtarget.getXLenVT(); 4703 4704 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 4705 "Unexpected VTs!"); 4706 assert(MGN->getBasePtr().getSimpleValueType() == XLenVT && 4707 "Unexpected pointer type"); 4708 // Targets have to explicitly opt-in for extending vector loads. 4709 assert(MGN->getExtensionType() == ISD::NON_EXTLOAD && 4710 "Unexpected extending MGATHER"); 4711 4712 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4713 // the selection of the masked intrinsics doesn't do this for us. 4714 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4715 4716 SDValue VL; 4717 MVT ContainerVT = VT; 4718 if (VT.isFixedLengthVector()) { 4719 // We need to use the larger of the result and index type to determine the 4720 // scalable type to use so we don't increase LMUL for any operand/result. 4721 if (VT.bitsGE(IndexVT)) { 4722 ContainerVT = getContainerForFixedLengthVector(VT); 4723 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 4724 ContainerVT.getVectorElementCount()); 4725 } else { 4726 IndexVT = getContainerForFixedLengthVector(IndexVT); 4727 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 4728 IndexVT.getVectorElementCount()); 4729 } 4730 4731 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 4732 4733 if (!IsUnmasked) { 4734 MVT MaskVT = 4735 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4736 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4737 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4738 } 4739 4740 VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4741 } else 4742 VL = DAG.getRegister(RISCV::X0, XLenVT); 4743 4744 unsigned IntID = 4745 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 4746 SmallVector<SDValue, 8> Ops{MGN->getChain(), 4747 DAG.getTargetConstant(IntID, DL, XLenVT)}; 4748 if (!IsUnmasked) 4749 Ops.push_back(PassThru); 4750 Ops.push_back(MGN->getBasePtr()); 4751 Ops.push_back(Index); 4752 if (!IsUnmasked) 4753 Ops.push_back(Mask); 4754 Ops.push_back(VL); 4755 4756 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4757 SDValue Result = 4758 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4759 MGN->getMemoryVT(), MGN->getMemOperand()); 4760 SDValue Chain = Result.getValue(1); 4761 4762 if (VT.isFixedLengthVector()) 4763 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4764 4765 return DAG.getMergeValues({Result, Chain}, DL); 4766 } 4767 4768 // Custom lower MSCATTER to a legalized form for RVV. It will then be matched to 4769 // a RVV indexed store. The RVV indexed store instructions only support the 4770 // "unsigned unscaled" addressing mode; indices are implicitly zero-extended or 4771 // truncated to XLEN and are treated as byte offsets. Any signed or scaled 4772 // indexing is extended to the XLEN value type and scaled accordingly. 4773 SDValue RISCVTargetLowering::lowerMSCATTER(SDValue Op, 4774 SelectionDAG &DAG) const { 4775 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 4776 SDLoc DL(Op); 4777 SDValue Index = MSN->getIndex(); 4778 SDValue Mask = MSN->getMask(); 4779 SDValue Val = MSN->getValue(); 4780 4781 MVT VT = Val.getSimpleValueType(); 4782 MVT IndexVT = Index.getSimpleValueType(); 4783 MVT XLenVT = Subtarget.getXLenVT(); 4784 4785 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 4786 "Unexpected VTs!"); 4787 assert(MSN->getBasePtr().getSimpleValueType() == XLenVT && 4788 "Unexpected pointer type"); 4789 // Targets have to explicitly opt-in for extending vector loads and 4790 // truncating vector stores. 4791 assert(!MSN->isTruncatingStore() && "Unexpected extending MSCATTER"); 4792 4793 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4794 // the selection of the masked intrinsics doesn't do this for us. 4795 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4796 4797 SDValue VL; 4798 if (VT.isFixedLengthVector()) { 4799 // We need to use the larger of the value and index type to determine the 4800 // scalable type to use so we don't increase LMUL for any operand/result. 4801 MVT ContainerVT; 4802 if (VT.bitsGE(IndexVT)) { 4803 ContainerVT = getContainerForFixedLengthVector(VT); 4804 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 4805 ContainerVT.getVectorElementCount()); 4806 } else { 4807 IndexVT = getContainerForFixedLengthVector(IndexVT); 4808 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4809 IndexVT.getVectorElementCount()); 4810 } 4811 4812 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 4813 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4814 4815 if (!IsUnmasked) { 4816 MVT MaskVT = 4817 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4818 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4819 } 4820 4821 VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4822 } else 4823 VL = DAG.getRegister(RISCV::X0, XLenVT); 4824 4825 unsigned IntID = 4826 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 4827 SmallVector<SDValue, 8> Ops{MSN->getChain(), 4828 DAG.getTargetConstant(IntID, DL, XLenVT)}; 4829 Ops.push_back(Val); 4830 Ops.push_back(MSN->getBasePtr()); 4831 Ops.push_back(Index); 4832 if (!IsUnmasked) 4833 Ops.push_back(Mask); 4834 Ops.push_back(VL); 4835 4836 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, MSN->getVTList(), Ops, 4837 MSN->getMemoryVT(), MSN->getMemOperand()); 4838 } 4839 4840 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 4841 SelectionDAG &DAG) const { 4842 const MVT XLenVT = Subtarget.getXLenVT(); 4843 SDLoc DL(Op); 4844 SDValue Chain = Op->getOperand(0); 4845 SDValue SysRegNo = DAG.getConstant( 4846 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 4847 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 4848 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 4849 4850 // Encoding used for rounding mode in RISCV differs from that used in 4851 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 4852 // table, which consists of a sequence of 4-bit fields, each representing 4853 // corresponding FLT_ROUNDS mode. 4854 static const int Table = 4855 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 4856 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 4857 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 4858 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 4859 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 4860 4861 SDValue Shift = 4862 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 4863 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 4864 DAG.getConstant(Table, DL, XLenVT), Shift); 4865 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 4866 DAG.getConstant(7, DL, XLenVT)); 4867 4868 return DAG.getMergeValues({Masked, Chain}, DL); 4869 } 4870 4871 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 4872 SelectionDAG &DAG) const { 4873 const MVT XLenVT = Subtarget.getXLenVT(); 4874 SDLoc DL(Op); 4875 SDValue Chain = Op->getOperand(0); 4876 SDValue RMValue = Op->getOperand(1); 4877 SDValue SysRegNo = DAG.getConstant( 4878 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 4879 4880 // Encoding used for rounding mode in RISCV differs from that used in 4881 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 4882 // a table, which consists of a sequence of 4-bit fields, each representing 4883 // corresponding RISCV mode. 4884 static const unsigned Table = 4885 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 4886 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 4887 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 4888 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 4889 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 4890 4891 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 4892 DAG.getConstant(2, DL, XLenVT)); 4893 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 4894 DAG.getConstant(Table, DL, XLenVT), Shift); 4895 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 4896 DAG.getConstant(0x7, DL, XLenVT)); 4897 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 4898 RMValue); 4899 } 4900 4901 // Returns the opcode of the target-specific SDNode that implements the 32-bit 4902 // form of the given Opcode. 4903 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 4904 switch (Opcode) { 4905 default: 4906 llvm_unreachable("Unexpected opcode"); 4907 case ISD::SHL: 4908 return RISCVISD::SLLW; 4909 case ISD::SRA: 4910 return RISCVISD::SRAW; 4911 case ISD::SRL: 4912 return RISCVISD::SRLW; 4913 case ISD::SDIV: 4914 return RISCVISD::DIVW; 4915 case ISD::UDIV: 4916 return RISCVISD::DIVUW; 4917 case ISD::UREM: 4918 return RISCVISD::REMUW; 4919 case ISD::ROTL: 4920 return RISCVISD::ROLW; 4921 case ISD::ROTR: 4922 return RISCVISD::RORW; 4923 case RISCVISD::GREV: 4924 return RISCVISD::GREVW; 4925 case RISCVISD::GORC: 4926 return RISCVISD::GORCW; 4927 } 4928 } 4929 4930 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 4931 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 4932 // otherwise be promoted to i64, making it difficult to select the 4933 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 4934 // type i8/i16/i32 is lost. 4935 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 4936 unsigned ExtOpc = ISD::ANY_EXTEND) { 4937 SDLoc DL(N); 4938 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 4939 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 4940 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 4941 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 4942 // ReplaceNodeResults requires we maintain the same type for the return value. 4943 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 4944 } 4945 4946 // Converts the given 32-bit operation to a i64 operation with signed extension 4947 // semantic to reduce the signed extension instructions. 4948 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 4949 SDLoc DL(N); 4950 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 4951 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 4952 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 4953 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 4954 DAG.getValueType(MVT::i32)); 4955 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 4956 } 4957 4958 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 4959 SmallVectorImpl<SDValue> &Results, 4960 SelectionDAG &DAG) const { 4961 SDLoc DL(N); 4962 switch (N->getOpcode()) { 4963 default: 4964 llvm_unreachable("Don't know how to custom type legalize this operation!"); 4965 case ISD::STRICT_FP_TO_SINT: 4966 case ISD::STRICT_FP_TO_UINT: 4967 case ISD::FP_TO_SINT: 4968 case ISD::FP_TO_UINT: { 4969 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 4970 "Unexpected custom legalisation"); 4971 bool IsStrict = N->isStrictFPOpcode(); 4972 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 4973 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 4974 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 4975 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 4976 TargetLowering::TypeSoftenFloat) { 4977 // FIXME: Support strict FP. 4978 if (IsStrict) 4979 return; 4980 if (!isTypeLegal(Op0.getValueType())) 4981 return; 4982 unsigned Opc = 4983 IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 4984 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0); 4985 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 4986 return; 4987 } 4988 // If the FP type needs to be softened, emit a library call using the 'si' 4989 // version. If we left it to default legalization we'd end up with 'di'. If 4990 // the FP type doesn't need to be softened just let generic type 4991 // legalization promote the result type. 4992 RTLIB::Libcall LC; 4993 if (IsSigned) 4994 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 4995 else 4996 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 4997 MakeLibCallOptions CallOptions; 4998 EVT OpVT = Op0.getValueType(); 4999 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 5000 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 5001 SDValue Result; 5002 std::tie(Result, Chain) = 5003 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 5004 Results.push_back(Result); 5005 if (IsStrict) 5006 Results.push_back(Chain); 5007 break; 5008 } 5009 case ISD::READCYCLECOUNTER: { 5010 assert(!Subtarget.is64Bit() && 5011 "READCYCLECOUNTER only has custom type legalization on riscv32"); 5012 5013 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 5014 SDValue RCW = 5015 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 5016 5017 Results.push_back( 5018 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 5019 Results.push_back(RCW.getValue(2)); 5020 break; 5021 } 5022 case ISD::MUL: { 5023 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 5024 unsigned XLen = Subtarget.getXLen(); 5025 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 5026 if (Size > XLen) { 5027 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 5028 SDValue LHS = N->getOperand(0); 5029 SDValue RHS = N->getOperand(1); 5030 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 5031 5032 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 5033 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 5034 // We need exactly one side to be unsigned. 5035 if (LHSIsU == RHSIsU) 5036 return; 5037 5038 auto MakeMULPair = [&](SDValue S, SDValue U) { 5039 MVT XLenVT = Subtarget.getXLenVT(); 5040 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 5041 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 5042 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 5043 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 5044 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 5045 }; 5046 5047 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 5048 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 5049 5050 // The other operand should be signed, but still prefer MULH when 5051 // possible. 5052 if (RHSIsU && LHSIsS && !RHSIsS) 5053 Results.push_back(MakeMULPair(LHS, RHS)); 5054 else if (LHSIsU && RHSIsS && !LHSIsS) 5055 Results.push_back(MakeMULPair(RHS, LHS)); 5056 5057 return; 5058 } 5059 LLVM_FALLTHROUGH; 5060 } 5061 case ISD::ADD: 5062 case ISD::SUB: 5063 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5064 "Unexpected custom legalisation"); 5065 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 5066 break; 5067 case ISD::SHL: 5068 case ISD::SRA: 5069 case ISD::SRL: 5070 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5071 "Unexpected custom legalisation"); 5072 if (N->getOperand(1).getOpcode() != ISD::Constant) { 5073 Results.push_back(customLegalizeToWOp(N, DAG)); 5074 break; 5075 } 5076 5077 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 5078 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 5079 // shift amount. 5080 if (N->getOpcode() == ISD::SHL) { 5081 SDLoc DL(N); 5082 SDValue NewOp0 = 5083 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5084 SDValue NewOp1 = 5085 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 5086 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 5087 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5088 DAG.getValueType(MVT::i32)); 5089 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5090 } 5091 5092 break; 5093 case ISD::ROTL: 5094 case ISD::ROTR: 5095 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5096 "Unexpected custom legalisation"); 5097 Results.push_back(customLegalizeToWOp(N, DAG)); 5098 break; 5099 case ISD::CTTZ: 5100 case ISD::CTTZ_ZERO_UNDEF: 5101 case ISD::CTLZ: 5102 case ISD::CTLZ_ZERO_UNDEF: { 5103 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5104 "Unexpected custom legalisation"); 5105 5106 SDValue NewOp0 = 5107 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5108 bool IsCTZ = 5109 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 5110 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 5111 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 5112 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5113 return; 5114 } 5115 case ISD::SDIV: 5116 case ISD::UDIV: 5117 case ISD::UREM: { 5118 MVT VT = N->getSimpleValueType(0); 5119 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 5120 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 5121 "Unexpected custom legalisation"); 5122 // Don't promote division/remainder by constant since we should expand those 5123 // to multiply by magic constant. 5124 // FIXME: What if the expansion is disabled for minsize. 5125 if (N->getOperand(1).getOpcode() == ISD::Constant) 5126 return; 5127 5128 // If the input is i32, use ANY_EXTEND since the W instructions don't read 5129 // the upper 32 bits. For other types we need to sign or zero extend 5130 // based on the opcode. 5131 unsigned ExtOpc = ISD::ANY_EXTEND; 5132 if (VT != MVT::i32) 5133 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 5134 : ISD::ZERO_EXTEND; 5135 5136 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 5137 break; 5138 } 5139 case ISD::UADDO: 5140 case ISD::USUBO: { 5141 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5142 "Unexpected custom legalisation"); 5143 bool IsAdd = N->getOpcode() == ISD::UADDO; 5144 // Create an ADDW or SUBW. 5145 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5146 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5147 SDValue Res = 5148 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 5149 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 5150 DAG.getValueType(MVT::i32)); 5151 5152 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 5153 // Since the inputs are sign extended from i32, this is equivalent to 5154 // comparing the lower 32 bits. 5155 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5156 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 5157 IsAdd ? ISD::SETULT : ISD::SETUGT); 5158 5159 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5160 Results.push_back(Overflow); 5161 return; 5162 } 5163 case ISD::UADDSAT: 5164 case ISD::USUBSAT: { 5165 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5166 "Unexpected custom legalisation"); 5167 if (Subtarget.hasStdExtZbb()) { 5168 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 5169 // sign extend allows overflow of the lower 32 bits to be detected on 5170 // the promoted size. 5171 SDValue LHS = 5172 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5173 SDValue RHS = 5174 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 5175 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 5176 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5177 return; 5178 } 5179 5180 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 5181 // promotion for UADDO/USUBO. 5182 Results.push_back(expandAddSubSat(N, DAG)); 5183 return; 5184 } 5185 case ISD::BITCAST: { 5186 EVT VT = N->getValueType(0); 5187 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 5188 SDValue Op0 = N->getOperand(0); 5189 EVT Op0VT = Op0.getValueType(); 5190 MVT XLenVT = Subtarget.getXLenVT(); 5191 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 5192 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 5193 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 5194 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 5195 Subtarget.hasStdExtF()) { 5196 SDValue FPConv = 5197 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 5198 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 5199 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 5200 isTypeLegal(Op0VT)) { 5201 // Custom-legalize bitcasts from fixed-length vector types to illegal 5202 // scalar types in order to improve codegen. Bitcast the vector to a 5203 // one-element vector type whose element type is the same as the result 5204 // type, and extract the first element. 5205 LLVMContext &Context = *DAG.getContext(); 5206 SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0); 5207 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 5208 DAG.getConstant(0, DL, XLenVT))); 5209 } 5210 break; 5211 } 5212 case RISCVISD::GREV: 5213 case RISCVISD::GORC: { 5214 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5215 "Unexpected custom legalisation"); 5216 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 5217 // This is similar to customLegalizeToWOp, except that we pass the second 5218 // operand (a TargetConstant) straight through: it is already of type 5219 // XLenVT. 5220 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5221 SDValue NewOp0 = 5222 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5223 SDValue NewOp1 = 5224 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5225 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5226 // ReplaceNodeResults requires we maintain the same type for the return 5227 // value. 5228 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5229 break; 5230 } 5231 case RISCVISD::SHFL: { 5232 // There is no SHFLIW instruction, but we can just promote the operation. 5233 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5234 "Unexpected custom legalisation"); 5235 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 5236 SDValue NewOp0 = 5237 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5238 SDValue NewOp1 = 5239 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5240 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 5241 // ReplaceNodeResults requires we maintain the same type for the return 5242 // value. 5243 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5244 break; 5245 } 5246 case ISD::BSWAP: 5247 case ISD::BITREVERSE: { 5248 MVT VT = N->getSimpleValueType(0); 5249 MVT XLenVT = Subtarget.getXLenVT(); 5250 assert((VT == MVT::i8 || VT == MVT::i16 || 5251 (VT == MVT::i32 && Subtarget.is64Bit())) && 5252 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 5253 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 5254 unsigned Imm = VT.getSizeInBits() - 1; 5255 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 5256 if (N->getOpcode() == ISD::BSWAP) 5257 Imm &= ~0x7U; 5258 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 5259 SDValue GREVI = 5260 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 5261 // ReplaceNodeResults requires we maintain the same type for the return 5262 // value. 5263 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 5264 break; 5265 } 5266 case ISD::FSHL: 5267 case ISD::FSHR: { 5268 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5269 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 5270 SDValue NewOp0 = 5271 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5272 SDValue NewOp1 = 5273 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5274 SDValue NewOp2 = 5275 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5276 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 5277 // Mask the shift amount to 5 bits. 5278 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 5279 DAG.getConstant(0x1f, DL, MVT::i64)); 5280 unsigned Opc = 5281 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 5282 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 5283 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 5284 break; 5285 } 5286 case ISD::EXTRACT_VECTOR_ELT: { 5287 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 5288 // type is illegal (currently only vXi64 RV32). 5289 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 5290 // transferred to the destination register. We issue two of these from the 5291 // upper- and lower- halves of the SEW-bit vector element, slid down to the 5292 // first element. 5293 SDValue Vec = N->getOperand(0); 5294 SDValue Idx = N->getOperand(1); 5295 5296 // The vector type hasn't been legalized yet so we can't issue target 5297 // specific nodes if it needs legalization. 5298 // FIXME: We would manually legalize if it's important. 5299 if (!isTypeLegal(Vec.getValueType())) 5300 return; 5301 5302 MVT VecVT = Vec.getSimpleValueType(); 5303 5304 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 5305 VecVT.getVectorElementType() == MVT::i64 && 5306 "Unexpected EXTRACT_VECTOR_ELT legalization"); 5307 5308 // If this is a fixed vector, we need to convert it to a scalable vector. 5309 MVT ContainerVT = VecVT; 5310 if (VecVT.isFixedLengthVector()) { 5311 ContainerVT = getContainerForFixedLengthVector(VecVT); 5312 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5313 } 5314 5315 MVT XLenVT = Subtarget.getXLenVT(); 5316 5317 // Use a VL of 1 to avoid processing more elements than we need. 5318 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5319 SDValue VL = DAG.getConstant(1, DL, XLenVT); 5320 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5321 5322 // Unless the index is known to be 0, we must slide the vector down to get 5323 // the desired element into index 0. 5324 if (!isNullConstant(Idx)) { 5325 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5326 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 5327 } 5328 5329 // Extract the lower XLEN bits of the correct vector element. 5330 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 5331 5332 // To extract the upper XLEN bits of the vector element, shift the first 5333 // element right by 32 bits and re-extract the lower XLEN bits. 5334 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5335 DAG.getConstant(32, DL, XLenVT), VL); 5336 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 5337 ThirtyTwoV, Mask, VL); 5338 5339 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 5340 5341 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 5342 break; 5343 } 5344 case ISD::INTRINSIC_WO_CHAIN: { 5345 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5346 switch (IntNo) { 5347 default: 5348 llvm_unreachable( 5349 "Don't know how to custom type legalize this intrinsic!"); 5350 case Intrinsic::riscv_orc_b: { 5351 // Lower to the GORCI encoding for orc.b with the operand extended. 5352 SDValue NewOp = 5353 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5354 // If Zbp is enabled, use GORCIW which will sign extend the result. 5355 unsigned Opc = 5356 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 5357 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 5358 DAG.getConstant(7, DL, MVT::i64)); 5359 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5360 return; 5361 } 5362 case Intrinsic::riscv_grev: 5363 case Intrinsic::riscv_gorc: { 5364 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5365 "Unexpected custom legalisation"); 5366 SDValue NewOp1 = 5367 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5368 SDValue NewOp2 = 5369 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5370 unsigned Opc = 5371 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 5372 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5373 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5374 break; 5375 } 5376 case Intrinsic::riscv_shfl: 5377 case Intrinsic::riscv_unshfl: { 5378 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5379 "Unexpected custom legalisation"); 5380 SDValue NewOp1 = 5381 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5382 SDValue NewOp2 = 5383 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5384 unsigned Opc = 5385 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 5386 if (isa<ConstantSDNode>(N->getOperand(2))) { 5387 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 5388 DAG.getConstant(0xf, DL, MVT::i64)); 5389 Opc = 5390 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 5391 } 5392 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5393 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5394 break; 5395 } 5396 case Intrinsic::riscv_bcompress: 5397 case Intrinsic::riscv_bdecompress: { 5398 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5399 "Unexpected custom legalisation"); 5400 SDValue NewOp1 = 5401 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5402 SDValue NewOp2 = 5403 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5404 unsigned Opc = IntNo == Intrinsic::riscv_bcompress 5405 ? RISCVISD::BCOMPRESSW 5406 : RISCVISD::BDECOMPRESSW; 5407 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5408 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5409 break; 5410 } 5411 case Intrinsic::riscv_vmv_x_s: { 5412 EVT VT = N->getValueType(0); 5413 MVT XLenVT = Subtarget.getXLenVT(); 5414 if (VT.bitsLT(XLenVT)) { 5415 // Simple case just extract using vmv.x.s and truncate. 5416 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 5417 Subtarget.getXLenVT(), N->getOperand(1)); 5418 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 5419 return; 5420 } 5421 5422 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 5423 "Unexpected custom legalization"); 5424 5425 // We need to do the move in two steps. 5426 SDValue Vec = N->getOperand(1); 5427 MVT VecVT = Vec.getSimpleValueType(); 5428 5429 // First extract the lower XLEN bits of the element. 5430 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 5431 5432 // To extract the upper XLEN bits of the vector element, shift the first 5433 // element right by 32 bits and re-extract the lower XLEN bits. 5434 SDValue VL = DAG.getConstant(1, DL, XLenVT); 5435 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5436 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5437 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 5438 DAG.getConstant(32, DL, XLenVT), VL); 5439 SDValue LShr32 = 5440 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 5441 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 5442 5443 Results.push_back( 5444 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 5445 break; 5446 } 5447 } 5448 break; 5449 } 5450 case ISD::VECREDUCE_ADD: 5451 case ISD::VECREDUCE_AND: 5452 case ISD::VECREDUCE_OR: 5453 case ISD::VECREDUCE_XOR: 5454 case ISD::VECREDUCE_SMAX: 5455 case ISD::VECREDUCE_UMAX: 5456 case ISD::VECREDUCE_SMIN: 5457 case ISD::VECREDUCE_UMIN: 5458 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 5459 Results.push_back(V); 5460 break; 5461 case ISD::FLT_ROUNDS_: { 5462 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 5463 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 5464 Results.push_back(Res.getValue(0)); 5465 Results.push_back(Res.getValue(1)); 5466 break; 5467 } 5468 } 5469 } 5470 5471 // A structure to hold one of the bit-manipulation patterns below. Together, a 5472 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 5473 // (or (and (shl x, 1), 0xAAAAAAAA), 5474 // (and (srl x, 1), 0x55555555)) 5475 struct RISCVBitmanipPat { 5476 SDValue Op; 5477 unsigned ShAmt; 5478 bool IsSHL; 5479 5480 bool formsPairWith(const RISCVBitmanipPat &Other) const { 5481 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 5482 } 5483 }; 5484 5485 // Matches patterns of the form 5486 // (and (shl x, C2), (C1 << C2)) 5487 // (and (srl x, C2), C1) 5488 // (shl (and x, C1), C2) 5489 // (srl (and x, (C1 << C2)), C2) 5490 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 5491 // The expected masks for each shift amount are specified in BitmanipMasks where 5492 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 5493 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 5494 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 5495 // XLen is 64. 5496 static Optional<RISCVBitmanipPat> 5497 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 5498 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 5499 "Unexpected number of masks"); 5500 Optional<uint64_t> Mask; 5501 // Optionally consume a mask around the shift operation. 5502 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 5503 Mask = Op.getConstantOperandVal(1); 5504 Op = Op.getOperand(0); 5505 } 5506 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 5507 return None; 5508 bool IsSHL = Op.getOpcode() == ISD::SHL; 5509 5510 if (!isa<ConstantSDNode>(Op.getOperand(1))) 5511 return None; 5512 uint64_t ShAmt = Op.getConstantOperandVal(1); 5513 5514 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 5515 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 5516 return None; 5517 // If we don't have enough masks for 64 bit, then we must be trying to 5518 // match SHFL so we're only allowed to shift 1/4 of the width. 5519 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 5520 return None; 5521 5522 SDValue Src = Op.getOperand(0); 5523 5524 // The expected mask is shifted left when the AND is found around SHL 5525 // patterns. 5526 // ((x >> 1) & 0x55555555) 5527 // ((x << 1) & 0xAAAAAAAA) 5528 bool SHLExpMask = IsSHL; 5529 5530 if (!Mask) { 5531 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 5532 // the mask is all ones: consume that now. 5533 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 5534 Mask = Src.getConstantOperandVal(1); 5535 Src = Src.getOperand(0); 5536 // The expected mask is now in fact shifted left for SRL, so reverse the 5537 // decision. 5538 // ((x & 0xAAAAAAAA) >> 1) 5539 // ((x & 0x55555555) << 1) 5540 SHLExpMask = !SHLExpMask; 5541 } else { 5542 // Use a default shifted mask of all-ones if there's no AND, truncated 5543 // down to the expected width. This simplifies the logic later on. 5544 Mask = maskTrailingOnes<uint64_t>(Width); 5545 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 5546 } 5547 } 5548 5549 unsigned MaskIdx = Log2_32(ShAmt); 5550 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 5551 5552 if (SHLExpMask) 5553 ExpMask <<= ShAmt; 5554 5555 if (Mask != ExpMask) 5556 return None; 5557 5558 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 5559 } 5560 5561 // Matches any of the following bit-manipulation patterns: 5562 // (and (shl x, 1), (0x55555555 << 1)) 5563 // (and (srl x, 1), 0x55555555) 5564 // (shl (and x, 0x55555555), 1) 5565 // (srl (and x, (0x55555555 << 1)), 1) 5566 // where the shift amount and mask may vary thus: 5567 // [1] = 0x55555555 / 0xAAAAAAAA 5568 // [2] = 0x33333333 / 0xCCCCCCCC 5569 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 5570 // [8] = 0x00FF00FF / 0xFF00FF00 5571 // [16] = 0x0000FFFF / 0xFFFFFFFF 5572 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 5573 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 5574 // These are the unshifted masks which we use to match bit-manipulation 5575 // patterns. They may be shifted left in certain circumstances. 5576 static const uint64_t BitmanipMasks[] = { 5577 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 5578 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 5579 5580 return matchRISCVBitmanipPat(Op, BitmanipMasks); 5581 } 5582 5583 // Match the following pattern as a GREVI(W) operation 5584 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 5585 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 5586 const RISCVSubtarget &Subtarget) { 5587 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 5588 EVT VT = Op.getValueType(); 5589 5590 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 5591 auto LHS = matchGREVIPat(Op.getOperand(0)); 5592 auto RHS = matchGREVIPat(Op.getOperand(1)); 5593 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 5594 SDLoc DL(Op); 5595 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 5596 DAG.getConstant(LHS->ShAmt, DL, VT)); 5597 } 5598 } 5599 return SDValue(); 5600 } 5601 5602 // Matches any the following pattern as a GORCI(W) operation 5603 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 5604 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 5605 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 5606 // Note that with the variant of 3., 5607 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 5608 // the inner pattern will first be matched as GREVI and then the outer 5609 // pattern will be matched to GORC via the first rule above. 5610 // 4. (or (rotl/rotr x, bitwidth/2), x) 5611 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 5612 const RISCVSubtarget &Subtarget) { 5613 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 5614 EVT VT = Op.getValueType(); 5615 5616 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 5617 SDLoc DL(Op); 5618 SDValue Op0 = Op.getOperand(0); 5619 SDValue Op1 = Op.getOperand(1); 5620 5621 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 5622 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 5623 isa<ConstantSDNode>(Reverse.getOperand(1)) && 5624 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 5625 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 5626 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 5627 if ((Reverse.getOpcode() == ISD::ROTL || 5628 Reverse.getOpcode() == ISD::ROTR) && 5629 Reverse.getOperand(0) == X && 5630 isa<ConstantSDNode>(Reverse.getOperand(1))) { 5631 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 5632 if (RotAmt == (VT.getSizeInBits() / 2)) 5633 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 5634 DAG.getConstant(RotAmt, DL, VT)); 5635 } 5636 return SDValue(); 5637 }; 5638 5639 // Check for either commutable permutation of (or (GREVI x, shamt), x) 5640 if (SDValue V = MatchOROfReverse(Op0, Op1)) 5641 return V; 5642 if (SDValue V = MatchOROfReverse(Op1, Op0)) 5643 return V; 5644 5645 // OR is commutable so canonicalize its OR operand to the left 5646 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 5647 std::swap(Op0, Op1); 5648 if (Op0.getOpcode() != ISD::OR) 5649 return SDValue(); 5650 SDValue OrOp0 = Op0.getOperand(0); 5651 SDValue OrOp1 = Op0.getOperand(1); 5652 auto LHS = matchGREVIPat(OrOp0); 5653 // OR is commutable so swap the operands and try again: x might have been 5654 // on the left 5655 if (!LHS) { 5656 std::swap(OrOp0, OrOp1); 5657 LHS = matchGREVIPat(OrOp0); 5658 } 5659 auto RHS = matchGREVIPat(Op1); 5660 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 5661 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 5662 DAG.getConstant(LHS->ShAmt, DL, VT)); 5663 } 5664 } 5665 return SDValue(); 5666 } 5667 5668 // Matches any of the following bit-manipulation patterns: 5669 // (and (shl x, 1), (0x22222222 << 1)) 5670 // (and (srl x, 1), 0x22222222) 5671 // (shl (and x, 0x22222222), 1) 5672 // (srl (and x, (0x22222222 << 1)), 1) 5673 // where the shift amount and mask may vary thus: 5674 // [1] = 0x22222222 / 0x44444444 5675 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 5676 // [4] = 0x00F000F0 / 0x0F000F00 5677 // [8] = 0x0000FF00 / 0x00FF0000 5678 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 5679 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 5680 // These are the unshifted masks which we use to match bit-manipulation 5681 // patterns. They may be shifted left in certain circumstances. 5682 static const uint64_t BitmanipMasks[] = { 5683 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 5684 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 5685 5686 return matchRISCVBitmanipPat(Op, BitmanipMasks); 5687 } 5688 5689 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 5690 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 5691 const RISCVSubtarget &Subtarget) { 5692 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 5693 EVT VT = Op.getValueType(); 5694 5695 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 5696 return SDValue(); 5697 5698 SDValue Op0 = Op.getOperand(0); 5699 SDValue Op1 = Op.getOperand(1); 5700 5701 // Or is commutable so canonicalize the second OR to the LHS. 5702 if (Op0.getOpcode() != ISD::OR) 5703 std::swap(Op0, Op1); 5704 if (Op0.getOpcode() != ISD::OR) 5705 return SDValue(); 5706 5707 // We found an inner OR, so our operands are the operands of the inner OR 5708 // and the other operand of the outer OR. 5709 SDValue A = Op0.getOperand(0); 5710 SDValue B = Op0.getOperand(1); 5711 SDValue C = Op1; 5712 5713 auto Match1 = matchSHFLPat(A); 5714 auto Match2 = matchSHFLPat(B); 5715 5716 // If neither matched, we failed. 5717 if (!Match1 && !Match2) 5718 return SDValue(); 5719 5720 // We had at least one match. if one failed, try the remaining C operand. 5721 if (!Match1) { 5722 std::swap(A, C); 5723 Match1 = matchSHFLPat(A); 5724 if (!Match1) 5725 return SDValue(); 5726 } else if (!Match2) { 5727 std::swap(B, C); 5728 Match2 = matchSHFLPat(B); 5729 if (!Match2) 5730 return SDValue(); 5731 } 5732 assert(Match1 && Match2); 5733 5734 // Make sure our matches pair up. 5735 if (!Match1->formsPairWith(*Match2)) 5736 return SDValue(); 5737 5738 // All the remains is to make sure C is an AND with the same input, that masks 5739 // out the bits that are being shuffled. 5740 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 5741 C.getOperand(0) != Match1->Op) 5742 return SDValue(); 5743 5744 uint64_t Mask = C.getConstantOperandVal(1); 5745 5746 static const uint64_t BitmanipMasks[] = { 5747 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 5748 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 5749 }; 5750 5751 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 5752 unsigned MaskIdx = Log2_32(Match1->ShAmt); 5753 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 5754 5755 if (Mask != ExpMask) 5756 return SDValue(); 5757 5758 SDLoc DL(Op); 5759 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 5760 DAG.getConstant(Match1->ShAmt, DL, VT)); 5761 } 5762 5763 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 5764 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 5765 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 5766 // not undo itself, but they are redundant. 5767 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 5768 SDValue Src = N->getOperand(0); 5769 5770 if (Src.getOpcode() != N->getOpcode()) 5771 return SDValue(); 5772 5773 if (!isa<ConstantSDNode>(N->getOperand(1)) || 5774 !isa<ConstantSDNode>(Src.getOperand(1))) 5775 return SDValue(); 5776 5777 unsigned ShAmt1 = N->getConstantOperandVal(1); 5778 unsigned ShAmt2 = Src.getConstantOperandVal(1); 5779 Src = Src.getOperand(0); 5780 5781 unsigned CombinedShAmt; 5782 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 5783 CombinedShAmt = ShAmt1 | ShAmt2; 5784 else 5785 CombinedShAmt = ShAmt1 ^ ShAmt2; 5786 5787 if (CombinedShAmt == 0) 5788 return Src; 5789 5790 SDLoc DL(N); 5791 return DAG.getNode( 5792 N->getOpcode(), DL, N->getValueType(0), Src, 5793 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 5794 } 5795 5796 // Combine a constant select operand into its use: 5797 // 5798 // (and (select cond, -1, c), x) 5799 // -> (select cond, x, (and x, c)) [AllOnes=1] 5800 // (or (select cond, 0, c), x) 5801 // -> (select cond, x, (or x, c)) [AllOnes=0] 5802 // (xor (select cond, 0, c), x) 5803 // -> (select cond, x, (xor x, c)) [AllOnes=0] 5804 // (add (select cond, 0, c), x) 5805 // -> (select cond, x, (add x, c)) [AllOnes=0] 5806 // (sub x, (select cond, 0, c)) 5807 // -> (select cond, x, (sub x, c)) [AllOnes=0] 5808 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 5809 SelectionDAG &DAG, bool AllOnes) { 5810 EVT VT = N->getValueType(0); 5811 5812 // Skip vectors. 5813 if (VT.isVector()) 5814 return SDValue(); 5815 5816 if ((Slct.getOpcode() != ISD::SELECT && 5817 Slct.getOpcode() != RISCVISD::SELECT_CC) || 5818 !Slct.hasOneUse()) 5819 return SDValue(); 5820 5821 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 5822 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 5823 }; 5824 5825 bool SwapSelectOps; 5826 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 5827 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 5828 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 5829 SDValue NonConstantVal; 5830 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 5831 SwapSelectOps = false; 5832 NonConstantVal = FalseVal; 5833 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 5834 SwapSelectOps = true; 5835 NonConstantVal = TrueVal; 5836 } else 5837 return SDValue(); 5838 5839 // Slct is now know to be the desired identity constant when CC is true. 5840 TrueVal = OtherOp; 5841 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 5842 // Unless SwapSelectOps says the condition should be false. 5843 if (SwapSelectOps) 5844 std::swap(TrueVal, FalseVal); 5845 5846 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 5847 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 5848 {Slct.getOperand(0), Slct.getOperand(1), 5849 Slct.getOperand(2), TrueVal, FalseVal}); 5850 5851 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 5852 {Slct.getOperand(0), TrueVal, FalseVal}); 5853 } 5854 5855 // Attempt combineSelectAndUse on each operand of a commutative operator N. 5856 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 5857 bool AllOnes) { 5858 SDValue N0 = N->getOperand(0); 5859 SDValue N1 = N->getOperand(1); 5860 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 5861 return Result; 5862 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 5863 return Result; 5864 return SDValue(); 5865 } 5866 5867 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG) { 5868 // fold (add (select lhs, rhs, cc, 0, y), x) -> 5869 // (select lhs, rhs, cc, x, (add x, y)) 5870 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 5871 } 5872 5873 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 5874 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 5875 // (select lhs, rhs, cc, x, (sub x, y)) 5876 SDValue N0 = N->getOperand(0); 5877 SDValue N1 = N->getOperand(1); 5878 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 5879 } 5880 5881 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 5882 // fold (and (select lhs, rhs, cc, -1, y), x) -> 5883 // (select lhs, rhs, cc, x, (and x, y)) 5884 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 5885 } 5886 5887 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 5888 const RISCVSubtarget &Subtarget) { 5889 if (Subtarget.hasStdExtZbp()) { 5890 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 5891 return GREV; 5892 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 5893 return GORC; 5894 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 5895 return SHFL; 5896 } 5897 5898 // fold (or (select cond, 0, y), x) -> 5899 // (select cond, x, (or x, y)) 5900 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 5901 } 5902 5903 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 5904 // fold (xor (select cond, 0, y), x) -> 5905 // (select cond, x, (xor x, y)) 5906 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 5907 } 5908 5909 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 5910 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 5911 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 5912 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 5913 // ADDW/SUBW/MULW. 5914 static SDValue performANY_EXTENDCombine(SDNode *N, 5915 TargetLowering::DAGCombinerInfo &DCI, 5916 const RISCVSubtarget &Subtarget) { 5917 if (!Subtarget.is64Bit()) 5918 return SDValue(); 5919 5920 SelectionDAG &DAG = DCI.DAG; 5921 5922 SDValue Src = N->getOperand(0); 5923 EVT VT = N->getValueType(0); 5924 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 5925 return SDValue(); 5926 5927 // The opcode must be one that can implicitly sign_extend. 5928 // FIXME: Additional opcodes. 5929 switch (Src.getOpcode()) { 5930 default: 5931 return SDValue(); 5932 case ISD::MUL: 5933 if (!Subtarget.hasStdExtM()) 5934 return SDValue(); 5935 LLVM_FALLTHROUGH; 5936 case ISD::ADD: 5937 case ISD::SUB: 5938 break; 5939 } 5940 5941 // Only handle cases where the result is used by a CopyToReg. That likely 5942 // means the value is a liveout of the basic block. This helps prevent 5943 // infinite combine loops like PR51206. 5944 if (none_of(N->uses(), 5945 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 5946 return SDValue(); 5947 5948 SmallVector<SDNode *, 4> SetCCs; 5949 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 5950 UE = Src.getNode()->use_end(); 5951 UI != UE; ++UI) { 5952 SDNode *User = *UI; 5953 if (User == N) 5954 continue; 5955 if (UI.getUse().getResNo() != Src.getResNo()) 5956 continue; 5957 // All i32 setccs are legalized by sign extending operands. 5958 if (User->getOpcode() == ISD::SETCC) { 5959 SetCCs.push_back(User); 5960 continue; 5961 } 5962 // We don't know if we can extend this user. 5963 break; 5964 } 5965 5966 // If we don't have any SetCCs, this isn't worthwhile. 5967 if (SetCCs.empty()) 5968 return SDValue(); 5969 5970 SDLoc DL(N); 5971 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 5972 DCI.CombineTo(N, SExt); 5973 5974 // Promote all the setccs. 5975 for (SDNode *SetCC : SetCCs) { 5976 SmallVector<SDValue, 4> Ops; 5977 5978 for (unsigned j = 0; j != 2; ++j) { 5979 SDValue SOp = SetCC->getOperand(j); 5980 if (SOp == Src) 5981 Ops.push_back(SExt); 5982 else 5983 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 5984 } 5985 5986 Ops.push_back(SetCC->getOperand(2)); 5987 DCI.CombineTo(SetCC, 5988 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5989 } 5990 return SDValue(N, 0); 5991 } 5992 5993 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 5994 DAGCombinerInfo &DCI) const { 5995 SelectionDAG &DAG = DCI.DAG; 5996 5997 // Helper to call SimplifyDemandedBits on an operand of N where only some low 5998 // bits are demanded. N will be added to the Worklist if it was not deleted. 5999 // Caller should return SDValue(N, 0) if this returns true. 6000 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 6001 SDValue Op = N->getOperand(OpNo); 6002 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 6003 if (!SimplifyDemandedBits(Op, Mask, DCI)) 6004 return false; 6005 6006 if (N->getOpcode() != ISD::DELETED_NODE) 6007 DCI.AddToWorklist(N); 6008 return true; 6009 }; 6010 6011 switch (N->getOpcode()) { 6012 default: 6013 break; 6014 case RISCVISD::SplitF64: { 6015 SDValue Op0 = N->getOperand(0); 6016 // If the input to SplitF64 is just BuildPairF64 then the operation is 6017 // redundant. Instead, use BuildPairF64's operands directly. 6018 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 6019 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 6020 6021 SDLoc DL(N); 6022 6023 // It's cheaper to materialise two 32-bit integers than to load a double 6024 // from the constant pool and transfer it to integer registers through the 6025 // stack. 6026 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 6027 APInt V = C->getValueAPF().bitcastToAPInt(); 6028 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 6029 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 6030 return DCI.CombineTo(N, Lo, Hi); 6031 } 6032 6033 // This is a target-specific version of a DAGCombine performed in 6034 // DAGCombiner::visitBITCAST. It performs the equivalent of: 6035 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6036 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6037 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 6038 !Op0.getNode()->hasOneUse()) 6039 break; 6040 SDValue NewSplitF64 = 6041 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 6042 Op0.getOperand(0)); 6043 SDValue Lo = NewSplitF64.getValue(0); 6044 SDValue Hi = NewSplitF64.getValue(1); 6045 APInt SignBit = APInt::getSignMask(32); 6046 if (Op0.getOpcode() == ISD::FNEG) { 6047 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 6048 DAG.getConstant(SignBit, DL, MVT::i32)); 6049 return DCI.CombineTo(N, Lo, NewHi); 6050 } 6051 assert(Op0.getOpcode() == ISD::FABS); 6052 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 6053 DAG.getConstant(~SignBit, DL, MVT::i32)); 6054 return DCI.CombineTo(N, Lo, NewHi); 6055 } 6056 case RISCVISD::SLLW: 6057 case RISCVISD::SRAW: 6058 case RISCVISD::SRLW: 6059 case RISCVISD::ROLW: 6060 case RISCVISD::RORW: { 6061 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 6062 if (SimplifyDemandedLowBitsHelper(0, 32) || 6063 SimplifyDemandedLowBitsHelper(1, 5)) 6064 return SDValue(N, 0); 6065 break; 6066 } 6067 case RISCVISD::CLZW: 6068 case RISCVISD::CTZW: { 6069 // Only the lower 32 bits of the first operand are read 6070 if (SimplifyDemandedLowBitsHelper(0, 32)) 6071 return SDValue(N, 0); 6072 break; 6073 } 6074 case RISCVISD::FSL: 6075 case RISCVISD::FSR: { 6076 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 6077 unsigned BitWidth = N->getOperand(2).getValueSizeInBits(); 6078 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6079 if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1)) 6080 return SDValue(N, 0); 6081 break; 6082 } 6083 case RISCVISD::FSLW: 6084 case RISCVISD::FSRW: { 6085 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 6086 // read. 6087 if (SimplifyDemandedLowBitsHelper(0, 32) || 6088 SimplifyDemandedLowBitsHelper(1, 32) || 6089 SimplifyDemandedLowBitsHelper(2, 6)) 6090 return SDValue(N, 0); 6091 break; 6092 } 6093 case RISCVISD::GREV: 6094 case RISCVISD::GORC: { 6095 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 6096 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 6097 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6098 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 6099 return SDValue(N, 0); 6100 6101 return combineGREVI_GORCI(N, DCI.DAG); 6102 } 6103 case RISCVISD::GREVW: 6104 case RISCVISD::GORCW: { 6105 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 6106 if (SimplifyDemandedLowBitsHelper(0, 32) || 6107 SimplifyDemandedLowBitsHelper(1, 5)) 6108 return SDValue(N, 0); 6109 6110 return combineGREVI_GORCI(N, DCI.DAG); 6111 } 6112 case RISCVISD::SHFL: 6113 case RISCVISD::UNSHFL: { 6114 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 6115 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 6116 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6117 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 6118 return SDValue(N, 0); 6119 6120 break; 6121 } 6122 case RISCVISD::SHFLW: 6123 case RISCVISD::UNSHFLW: { 6124 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 6125 SDValue LHS = N->getOperand(0); 6126 SDValue RHS = N->getOperand(1); 6127 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 6128 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4); 6129 if (SimplifyDemandedLowBitsHelper(0, 32) || 6130 SimplifyDemandedLowBitsHelper(1, 4)) 6131 return SDValue(N, 0); 6132 6133 break; 6134 } 6135 case RISCVISD::BCOMPRESSW: 6136 case RISCVISD::BDECOMPRESSW: { 6137 // Only the lower 32 bits of LHS and RHS are read. 6138 if (SimplifyDemandedLowBitsHelper(0, 32) || 6139 SimplifyDemandedLowBitsHelper(1, 32)) 6140 return SDValue(N, 0); 6141 6142 break; 6143 } 6144 case RISCVISD::FMV_X_ANYEXTH: 6145 case RISCVISD::FMV_X_ANYEXTW_RV64: { 6146 SDLoc DL(N); 6147 SDValue Op0 = N->getOperand(0); 6148 MVT VT = N->getSimpleValueType(0); 6149 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 6150 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 6151 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 6152 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 6153 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 6154 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 6155 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 6156 assert(Op0.getOperand(0).getValueType() == VT && 6157 "Unexpected value type!"); 6158 return Op0.getOperand(0); 6159 } 6160 6161 // This is a target-specific version of a DAGCombine performed in 6162 // DAGCombiner::visitBITCAST. It performs the equivalent of: 6163 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6164 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6165 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 6166 !Op0.getNode()->hasOneUse()) 6167 break; 6168 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 6169 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 6170 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 6171 if (Op0.getOpcode() == ISD::FNEG) 6172 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 6173 DAG.getConstant(SignBit, DL, VT)); 6174 6175 assert(Op0.getOpcode() == ISD::FABS); 6176 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 6177 DAG.getConstant(~SignBit, DL, VT)); 6178 } 6179 case ISD::ADD: 6180 return performADDCombine(N, DAG); 6181 case ISD::SUB: 6182 return performSUBCombine(N, DAG); 6183 case ISD::AND: 6184 return performANDCombine(N, DAG); 6185 case ISD::OR: 6186 return performORCombine(N, DAG, Subtarget); 6187 case ISD::XOR: 6188 return performXORCombine(N, DAG); 6189 case ISD::ANY_EXTEND: 6190 return performANY_EXTENDCombine(N, DCI, Subtarget); 6191 case ISD::ZERO_EXTEND: 6192 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 6193 // type legalization. This is safe because fp_to_uint produces poison if 6194 // it overflows. 6195 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() && 6196 N->getOperand(0).getOpcode() == ISD::FP_TO_UINT && 6197 isTypeLegal(N->getOperand(0).getOperand(0).getValueType())) 6198 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 6199 N->getOperand(0).getOperand(0)); 6200 return SDValue(); 6201 case RISCVISD::SELECT_CC: { 6202 // Transform 6203 SDValue LHS = N->getOperand(0); 6204 SDValue RHS = N->getOperand(1); 6205 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 6206 if (!ISD::isIntEqualitySetCC(CCVal)) 6207 break; 6208 6209 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 6210 // (select_cc X, Y, lt, trueV, falseV) 6211 // Sometimes the setcc is introduced after select_cc has been formed. 6212 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 6213 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 6214 // If we're looking for eq 0 instead of ne 0, we need to invert the 6215 // condition. 6216 bool Invert = CCVal == ISD::SETEQ; 6217 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 6218 if (Invert) 6219 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6220 6221 SDLoc DL(N); 6222 RHS = LHS.getOperand(1); 6223 LHS = LHS.getOperand(0); 6224 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 6225 6226 SDValue TargetCC = DAG.getCondCode(CCVal); 6227 return DAG.getNode( 6228 RISCVISD::SELECT_CC, DL, N->getValueType(0), 6229 {LHS, RHS, TargetCC, N->getOperand(3), N->getOperand(4)}); 6230 } 6231 6232 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 6233 // (select_cc X, Y, eq/ne, trueV, falseV) 6234 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 6235 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 6236 {LHS.getOperand(0), LHS.getOperand(1), 6237 N->getOperand(2), N->getOperand(3), 6238 N->getOperand(4)}); 6239 // (select_cc X, 1, setne, trueV, falseV) -> 6240 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 6241 // This can occur when legalizing some floating point comparisons. 6242 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 6243 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 6244 SDLoc DL(N); 6245 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6246 SDValue TargetCC = DAG.getCondCode(CCVal); 6247 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 6248 return DAG.getNode( 6249 RISCVISD::SELECT_CC, DL, N->getValueType(0), 6250 {LHS, RHS, TargetCC, N->getOperand(3), N->getOperand(4)}); 6251 } 6252 6253 break; 6254 } 6255 case RISCVISD::BR_CC: { 6256 SDValue LHS = N->getOperand(1); 6257 SDValue RHS = N->getOperand(2); 6258 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 6259 if (!ISD::isIntEqualitySetCC(CCVal)) 6260 break; 6261 6262 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 6263 // (br_cc X, Y, lt, dest) 6264 // Sometimes the setcc is introduced after br_cc has been formed. 6265 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 6266 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 6267 // If we're looking for eq 0 instead of ne 0, we need to invert the 6268 // condition. 6269 bool Invert = CCVal == ISD::SETEQ; 6270 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 6271 if (Invert) 6272 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6273 6274 SDLoc DL(N); 6275 RHS = LHS.getOperand(1); 6276 LHS = LHS.getOperand(0); 6277 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 6278 6279 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 6280 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 6281 N->getOperand(4)); 6282 } 6283 6284 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 6285 // (br_cc X, Y, eq/ne, trueV, falseV) 6286 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 6287 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 6288 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 6289 N->getOperand(3), N->getOperand(4)); 6290 6291 // (br_cc X, 1, setne, br_cc) -> 6292 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 6293 // This can occur when legalizing some floating point comparisons. 6294 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 6295 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 6296 SDLoc DL(N); 6297 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6298 SDValue TargetCC = DAG.getCondCode(CCVal); 6299 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 6300 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 6301 N->getOperand(0), LHS, RHS, TargetCC, 6302 N->getOperand(4)); 6303 } 6304 break; 6305 } 6306 case ISD::FCOPYSIGN: { 6307 EVT VT = N->getValueType(0); 6308 if (!VT.isVector()) 6309 break; 6310 // There is a form of VFSGNJ which injects the negated sign of its second 6311 // operand. Try and bubble any FNEG up after the extend/round to produce 6312 // this optimized pattern. Avoid modifying cases where FP_ROUND and 6313 // TRUNC=1. 6314 SDValue In2 = N->getOperand(1); 6315 // Avoid cases where the extend/round has multiple uses, as duplicating 6316 // those is typically more expensive than removing a fneg. 6317 if (!In2.hasOneUse()) 6318 break; 6319 if (In2.getOpcode() != ISD::FP_EXTEND && 6320 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 6321 break; 6322 In2 = In2.getOperand(0); 6323 if (In2.getOpcode() != ISD::FNEG) 6324 break; 6325 SDLoc DL(N); 6326 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 6327 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 6328 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 6329 } 6330 case ISD::MGATHER: 6331 case ISD::MSCATTER: { 6332 if (!DCI.isBeforeLegalize()) 6333 break; 6334 MaskedGatherScatterSDNode *MGSN = cast<MaskedGatherScatterSDNode>(N); 6335 SDValue Index = MGSN->getIndex(); 6336 EVT IndexVT = Index.getValueType(); 6337 MVT XLenVT = Subtarget.getXLenVT(); 6338 // RISCV indexed loads only support the "unsigned unscaled" addressing 6339 // mode, so anything else must be manually legalized. 6340 bool NeedsIdxLegalization = MGSN->isIndexScaled() || 6341 (MGSN->isIndexSigned() && 6342 IndexVT.getVectorElementType().bitsLT(XLenVT)); 6343 if (!NeedsIdxLegalization) 6344 break; 6345 6346 SDLoc DL(N); 6347 6348 // Any index legalization should first promote to XLenVT, so we don't lose 6349 // bits when scaling. This may create an illegal index type so we let 6350 // LLVM's legalization take care of the splitting. 6351 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 6352 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6353 Index = DAG.getNode(MGSN->isIndexSigned() ? ISD::SIGN_EXTEND 6354 : ISD::ZERO_EXTEND, 6355 DL, IndexVT, Index); 6356 } 6357 6358 unsigned Scale = N->getConstantOperandVal(5); 6359 if (MGSN->isIndexScaled() && Scale != 1) { 6360 // Manually scale the indices by the element size. 6361 // TODO: Sanitize the scale operand here? 6362 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 6363 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 6364 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 6365 } 6366 6367 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 6368 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) { 6369 return DAG.getMaskedGather( 6370 N->getVTList(), MGSN->getMemoryVT(), DL, 6371 {MGSN->getChain(), MGN->getPassThru(), MGSN->getMask(), 6372 MGSN->getBasePtr(), Index, MGN->getScale()}, 6373 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 6374 } 6375 const auto *MSN = cast<MaskedScatterSDNode>(N); 6376 return DAG.getMaskedScatter( 6377 N->getVTList(), MGSN->getMemoryVT(), DL, 6378 {MGSN->getChain(), MSN->getValue(), MGSN->getMask(), MGSN->getBasePtr(), 6379 Index, MGSN->getScale()}, 6380 MGSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 6381 } 6382 case RISCVISD::SRA_VL: 6383 case RISCVISD::SRL_VL: 6384 case RISCVISD::SHL_VL: { 6385 SDValue ShAmt = N->getOperand(1); 6386 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 6387 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 6388 SDLoc DL(N); 6389 SDValue VL = N->getOperand(3); 6390 EVT VT = N->getValueType(0); 6391 ShAmt = 6392 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 6393 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 6394 N->getOperand(2), N->getOperand(3)); 6395 } 6396 break; 6397 } 6398 case ISD::SRA: 6399 case ISD::SRL: 6400 case ISD::SHL: { 6401 SDValue ShAmt = N->getOperand(1); 6402 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 6403 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 6404 SDLoc DL(N); 6405 EVT VT = N->getValueType(0); 6406 ShAmt = 6407 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 6408 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 6409 } 6410 break; 6411 } 6412 case RISCVISD::MUL_VL: { 6413 // Try to form VWMUL or VWMULU. 6414 // FIXME: Look for splat of extended scalar as well. 6415 // FIXME: Support VWMULSU. 6416 SDValue Op0 = N->getOperand(0); 6417 SDValue Op1 = N->getOperand(1); 6418 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 6419 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 6420 if ((!IsSignExt && !IsZeroExt) || Op0.getOpcode() != Op1.getOpcode()) 6421 return SDValue(); 6422 6423 // Make sure the extends have a single use. 6424 if (!Op0.hasOneUse() || !Op1.hasOneUse()) 6425 return SDValue(); 6426 6427 SDValue Mask = N->getOperand(2); 6428 SDValue VL = N->getOperand(3); 6429 if (Op0.getOperand(1) != Mask || Op1.getOperand(1) != Mask || 6430 Op0.getOperand(2) != VL || Op1.getOperand(2) != VL) 6431 return SDValue(); 6432 6433 Op0 = Op0.getOperand(0); 6434 Op1 = Op1.getOperand(0); 6435 6436 MVT VT = N->getSimpleValueType(0); 6437 MVT NarrowVT = 6438 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() / 2), 6439 VT.getVectorElementCount()); 6440 6441 SDLoc DL(N); 6442 6443 // Re-introduce narrower extends if needed. 6444 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 6445 if (Op0.getValueType() != NarrowVT) 6446 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 6447 if (Op1.getValueType() != NarrowVT) 6448 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 6449 6450 unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 6451 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 6452 } 6453 } 6454 6455 return SDValue(); 6456 } 6457 6458 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 6459 const SDNode *N, CombineLevel Level) const { 6460 // The following folds are only desirable if `(OP _, c1 << c2)` can be 6461 // materialised in fewer instructions than `(OP _, c1)`: 6462 // 6463 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 6464 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 6465 SDValue N0 = N->getOperand(0); 6466 EVT Ty = N0.getValueType(); 6467 if (Ty.isScalarInteger() && 6468 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 6469 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6470 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6471 if (C1 && C2) { 6472 const APInt &C1Int = C1->getAPIntValue(); 6473 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 6474 6475 // We can materialise `c1 << c2` into an add immediate, so it's "free", 6476 // and the combine should happen, to potentially allow further combines 6477 // later. 6478 if (ShiftedC1Int.getMinSignedBits() <= 64 && 6479 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 6480 return true; 6481 6482 // We can materialise `c1` in an add immediate, so it's "free", and the 6483 // combine should be prevented. 6484 if (C1Int.getMinSignedBits() <= 64 && 6485 isLegalAddImmediate(C1Int.getSExtValue())) 6486 return false; 6487 6488 // Neither constant will fit into an immediate, so find materialisation 6489 // costs. 6490 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 6491 Subtarget.getFeatureBits(), 6492 /*CompressionCost*/true); 6493 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 6494 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 6495 /*CompressionCost*/true); 6496 6497 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 6498 // combine should be prevented. 6499 if (C1Cost < ShiftedC1Cost) 6500 return false; 6501 } 6502 } 6503 return true; 6504 } 6505 6506 bool RISCVTargetLowering::targetShrinkDemandedConstant( 6507 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 6508 TargetLoweringOpt &TLO) const { 6509 // Delay this optimization as late as possible. 6510 if (!TLO.LegalOps) 6511 return false; 6512 6513 EVT VT = Op.getValueType(); 6514 if (VT.isVector()) 6515 return false; 6516 6517 // Only handle AND for now. 6518 if (Op.getOpcode() != ISD::AND) 6519 return false; 6520 6521 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 6522 if (!C) 6523 return false; 6524 6525 const APInt &Mask = C->getAPIntValue(); 6526 6527 // Clear all non-demanded bits initially. 6528 APInt ShrunkMask = Mask & DemandedBits; 6529 6530 // Try to make a smaller immediate by setting undemanded bits. 6531 6532 APInt ExpandedMask = Mask | ~DemandedBits; 6533 6534 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 6535 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 6536 }; 6537 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 6538 if (NewMask == Mask) 6539 return true; 6540 SDLoc DL(Op); 6541 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 6542 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 6543 return TLO.CombineTo(Op, NewOp); 6544 }; 6545 6546 // If the shrunk mask fits in sign extended 12 bits, let the target 6547 // independent code apply it. 6548 if (ShrunkMask.isSignedIntN(12)) 6549 return false; 6550 6551 // Preserve (and X, 0xffff) when zext.h is supported. 6552 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 6553 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 6554 if (IsLegalMask(NewMask)) 6555 return UseMask(NewMask); 6556 } 6557 6558 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 6559 if (VT == MVT::i64) { 6560 APInt NewMask = APInt(64, 0xffffffff); 6561 if (IsLegalMask(NewMask)) 6562 return UseMask(NewMask); 6563 } 6564 6565 // For the remaining optimizations, we need to be able to make a negative 6566 // number through a combination of mask and undemanded bits. 6567 if (!ExpandedMask.isNegative()) 6568 return false; 6569 6570 // What is the fewest number of bits we need to represent the negative number. 6571 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 6572 6573 // Try to make a 12 bit negative immediate. If that fails try to make a 32 6574 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 6575 APInt NewMask = ShrunkMask; 6576 if (MinSignedBits <= 12) 6577 NewMask.setBitsFrom(11); 6578 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 6579 NewMask.setBitsFrom(31); 6580 else 6581 return false; 6582 6583 // Sanity check that our new mask is a subset of the demanded mask. 6584 assert(IsLegalMask(NewMask)); 6585 return UseMask(NewMask); 6586 } 6587 6588 static void computeGREV(APInt &Src, unsigned ShAmt) { 6589 ShAmt &= Src.getBitWidth() - 1; 6590 uint64_t x = Src.getZExtValue(); 6591 if (ShAmt & 1) 6592 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 6593 if (ShAmt & 2) 6594 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 6595 if (ShAmt & 4) 6596 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 6597 if (ShAmt & 8) 6598 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 6599 if (ShAmt & 16) 6600 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 6601 if (ShAmt & 32) 6602 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 6603 Src = x; 6604 } 6605 6606 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 6607 KnownBits &Known, 6608 const APInt &DemandedElts, 6609 const SelectionDAG &DAG, 6610 unsigned Depth) const { 6611 unsigned BitWidth = Known.getBitWidth(); 6612 unsigned Opc = Op.getOpcode(); 6613 assert((Opc >= ISD::BUILTIN_OP_END || 6614 Opc == ISD::INTRINSIC_WO_CHAIN || 6615 Opc == ISD::INTRINSIC_W_CHAIN || 6616 Opc == ISD::INTRINSIC_VOID) && 6617 "Should use MaskedValueIsZero if you don't know whether Op" 6618 " is a target node!"); 6619 6620 Known.resetAll(); 6621 switch (Opc) { 6622 default: break; 6623 case RISCVISD::SELECT_CC: { 6624 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 6625 // If we don't know any bits, early out. 6626 if (Known.isUnknown()) 6627 break; 6628 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 6629 6630 // Only known if known in both the LHS and RHS. 6631 Known = KnownBits::commonBits(Known, Known2); 6632 break; 6633 } 6634 case RISCVISD::REMUW: { 6635 KnownBits Known2; 6636 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 6637 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 6638 // We only care about the lower 32 bits. 6639 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 6640 // Restore the original width by sign extending. 6641 Known = Known.sext(BitWidth); 6642 break; 6643 } 6644 case RISCVISD::DIVUW: { 6645 KnownBits Known2; 6646 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 6647 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 6648 // We only care about the lower 32 bits. 6649 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 6650 // Restore the original width by sign extending. 6651 Known = Known.sext(BitWidth); 6652 break; 6653 } 6654 case RISCVISD::CTZW: { 6655 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 6656 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 6657 unsigned LowBits = Log2_32(PossibleTZ) + 1; 6658 Known.Zero.setBitsFrom(LowBits); 6659 break; 6660 } 6661 case RISCVISD::CLZW: { 6662 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 6663 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 6664 unsigned LowBits = Log2_32(PossibleLZ) + 1; 6665 Known.Zero.setBitsFrom(LowBits); 6666 break; 6667 } 6668 case RISCVISD::GREV: 6669 case RISCVISD::GREVW: { 6670 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 6671 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 6672 if (Opc == RISCVISD::GREVW) 6673 Known = Known.trunc(32); 6674 unsigned ShAmt = C->getZExtValue(); 6675 computeGREV(Known.Zero, ShAmt); 6676 computeGREV(Known.One, ShAmt); 6677 if (Opc == RISCVISD::GREVW) 6678 Known = Known.sext(BitWidth); 6679 } 6680 break; 6681 } 6682 case RISCVISD::READ_VLENB: 6683 // We assume VLENB is at least 16 bytes. 6684 Known.Zero.setLowBits(4); 6685 // We assume VLENB is no more than 65536 / 8 bytes. 6686 Known.Zero.setBitsFrom(14); 6687 break; 6688 case ISD::INTRINSIC_W_CHAIN: { 6689 unsigned IntNo = Op.getConstantOperandVal(1); 6690 switch (IntNo) { 6691 default: 6692 // We can't do anything for most intrinsics. 6693 break; 6694 case Intrinsic::riscv_vsetvli: 6695 case Intrinsic::riscv_vsetvlimax: 6696 // Assume that VL output is positive and would fit in an int32_t. 6697 // TODO: VLEN might be capped at 16 bits in a future V spec update. 6698 if (BitWidth >= 32) 6699 Known.Zero.setBitsFrom(31); 6700 break; 6701 } 6702 break; 6703 } 6704 } 6705 } 6706 6707 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 6708 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 6709 unsigned Depth) const { 6710 switch (Op.getOpcode()) { 6711 default: 6712 break; 6713 case RISCVISD::SELECT_CC: { 6714 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 6715 if (Tmp == 1) return 1; // Early out. 6716 unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 6717 return std::min(Tmp, Tmp2); 6718 } 6719 case RISCVISD::SLLW: 6720 case RISCVISD::SRAW: 6721 case RISCVISD::SRLW: 6722 case RISCVISD::DIVW: 6723 case RISCVISD::DIVUW: 6724 case RISCVISD::REMUW: 6725 case RISCVISD::ROLW: 6726 case RISCVISD::RORW: 6727 case RISCVISD::GREVW: 6728 case RISCVISD::GORCW: 6729 case RISCVISD::FSLW: 6730 case RISCVISD::FSRW: 6731 case RISCVISD::SHFLW: 6732 case RISCVISD::UNSHFLW: 6733 case RISCVISD::BCOMPRESSW: 6734 case RISCVISD::BDECOMPRESSW: 6735 case RISCVISD::FCVT_W_RTZ_RV64: 6736 case RISCVISD::FCVT_WU_RTZ_RV64: 6737 // TODO: As the result is sign-extended, this is conservatively correct. A 6738 // more precise answer could be calculated for SRAW depending on known 6739 // bits in the shift amount. 6740 return 33; 6741 case RISCVISD::SHFL: 6742 case RISCVISD::UNSHFL: { 6743 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 6744 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 6745 // will stay within the upper 32 bits. If there were more than 32 sign bits 6746 // before there will be at least 33 sign bits after. 6747 if (Op.getValueType() == MVT::i64 && 6748 isa<ConstantSDNode>(Op.getOperand(1)) && 6749 (Op.getConstantOperandVal(1) & 0x10) == 0) { 6750 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 6751 if (Tmp > 32) 6752 return 33; 6753 } 6754 break; 6755 } 6756 case RISCVISD::VMV_X_S: 6757 // The number of sign bits of the scalar result is computed by obtaining the 6758 // element type of the input vector operand, subtracting its width from the 6759 // XLEN, and then adding one (sign bit within the element type). If the 6760 // element type is wider than XLen, the least-significant XLEN bits are 6761 // taken. 6762 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 6763 return 1; 6764 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 6765 } 6766 6767 return 1; 6768 } 6769 6770 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 6771 MachineBasicBlock *BB) { 6772 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 6773 6774 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 6775 // Should the count have wrapped while it was being read, we need to try 6776 // again. 6777 // ... 6778 // read: 6779 // rdcycleh x3 # load high word of cycle 6780 // rdcycle x2 # load low word of cycle 6781 // rdcycleh x4 # load high word of cycle 6782 // bne x3, x4, read # check if high word reads match, otherwise try again 6783 // ... 6784 6785 MachineFunction &MF = *BB->getParent(); 6786 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 6787 MachineFunction::iterator It = ++BB->getIterator(); 6788 6789 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 6790 MF.insert(It, LoopMBB); 6791 6792 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 6793 MF.insert(It, DoneMBB); 6794 6795 // Transfer the remainder of BB and its successor edges to DoneMBB. 6796 DoneMBB->splice(DoneMBB->begin(), BB, 6797 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 6798 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 6799 6800 BB->addSuccessor(LoopMBB); 6801 6802 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 6803 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 6804 Register LoReg = MI.getOperand(0).getReg(); 6805 Register HiReg = MI.getOperand(1).getReg(); 6806 DebugLoc DL = MI.getDebugLoc(); 6807 6808 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 6809 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 6810 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 6811 .addReg(RISCV::X0); 6812 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 6813 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 6814 .addReg(RISCV::X0); 6815 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 6816 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 6817 .addReg(RISCV::X0); 6818 6819 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 6820 .addReg(HiReg) 6821 .addReg(ReadAgainReg) 6822 .addMBB(LoopMBB); 6823 6824 LoopMBB->addSuccessor(LoopMBB); 6825 LoopMBB->addSuccessor(DoneMBB); 6826 6827 MI.eraseFromParent(); 6828 6829 return DoneMBB; 6830 } 6831 6832 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 6833 MachineBasicBlock *BB) { 6834 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 6835 6836 MachineFunction &MF = *BB->getParent(); 6837 DebugLoc DL = MI.getDebugLoc(); 6838 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 6839 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 6840 Register LoReg = MI.getOperand(0).getReg(); 6841 Register HiReg = MI.getOperand(1).getReg(); 6842 Register SrcReg = MI.getOperand(2).getReg(); 6843 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 6844 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 6845 6846 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 6847 RI); 6848 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 6849 MachineMemOperand *MMOLo = 6850 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 6851 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 6852 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 6853 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 6854 .addFrameIndex(FI) 6855 .addImm(0) 6856 .addMemOperand(MMOLo); 6857 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 6858 .addFrameIndex(FI) 6859 .addImm(4) 6860 .addMemOperand(MMOHi); 6861 MI.eraseFromParent(); // The pseudo instruction is gone now. 6862 return BB; 6863 } 6864 6865 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 6866 MachineBasicBlock *BB) { 6867 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 6868 "Unexpected instruction"); 6869 6870 MachineFunction &MF = *BB->getParent(); 6871 DebugLoc DL = MI.getDebugLoc(); 6872 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 6873 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 6874 Register DstReg = MI.getOperand(0).getReg(); 6875 Register LoReg = MI.getOperand(1).getReg(); 6876 Register HiReg = MI.getOperand(2).getReg(); 6877 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 6878 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 6879 6880 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 6881 MachineMemOperand *MMOLo = 6882 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 6883 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 6884 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 6885 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 6886 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 6887 .addFrameIndex(FI) 6888 .addImm(0) 6889 .addMemOperand(MMOLo); 6890 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 6891 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 6892 .addFrameIndex(FI) 6893 .addImm(4) 6894 .addMemOperand(MMOHi); 6895 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 6896 MI.eraseFromParent(); // The pseudo instruction is gone now. 6897 return BB; 6898 } 6899 6900 static bool isSelectPseudo(MachineInstr &MI) { 6901 switch (MI.getOpcode()) { 6902 default: 6903 return false; 6904 case RISCV::Select_GPR_Using_CC_GPR: 6905 case RISCV::Select_FPR16_Using_CC_GPR: 6906 case RISCV::Select_FPR32_Using_CC_GPR: 6907 case RISCV::Select_FPR64_Using_CC_GPR: 6908 return true; 6909 } 6910 } 6911 6912 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 6913 MachineBasicBlock *BB, 6914 const RISCVSubtarget &Subtarget) { 6915 // To "insert" Select_* instructions, we actually have to insert the triangle 6916 // control-flow pattern. The incoming instructions know the destination vreg 6917 // to set, the condition code register to branch on, the true/false values to 6918 // select between, and the condcode to use to select the appropriate branch. 6919 // 6920 // We produce the following control flow: 6921 // HeadMBB 6922 // | \ 6923 // | IfFalseMBB 6924 // | / 6925 // TailMBB 6926 // 6927 // When we find a sequence of selects we attempt to optimize their emission 6928 // by sharing the control flow. Currently we only handle cases where we have 6929 // multiple selects with the exact same condition (same LHS, RHS and CC). 6930 // The selects may be interleaved with other instructions if the other 6931 // instructions meet some requirements we deem safe: 6932 // - They are debug instructions. Otherwise, 6933 // - They do not have side-effects, do not access memory and their inputs do 6934 // not depend on the results of the select pseudo-instructions. 6935 // The TrueV/FalseV operands of the selects cannot depend on the result of 6936 // previous selects in the sequence. 6937 // These conditions could be further relaxed. See the X86 target for a 6938 // related approach and more information. 6939 Register LHS = MI.getOperand(1).getReg(); 6940 Register RHS = MI.getOperand(2).getReg(); 6941 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 6942 6943 SmallVector<MachineInstr *, 4> SelectDebugValues; 6944 SmallSet<Register, 4> SelectDests; 6945 SelectDests.insert(MI.getOperand(0).getReg()); 6946 6947 MachineInstr *LastSelectPseudo = &MI; 6948 6949 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 6950 SequenceMBBI != E; ++SequenceMBBI) { 6951 if (SequenceMBBI->isDebugInstr()) 6952 continue; 6953 else if (isSelectPseudo(*SequenceMBBI)) { 6954 if (SequenceMBBI->getOperand(1).getReg() != LHS || 6955 SequenceMBBI->getOperand(2).getReg() != RHS || 6956 SequenceMBBI->getOperand(3).getImm() != CC || 6957 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 6958 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 6959 break; 6960 LastSelectPseudo = &*SequenceMBBI; 6961 SequenceMBBI->collectDebugValues(SelectDebugValues); 6962 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 6963 } else { 6964 if (SequenceMBBI->hasUnmodeledSideEffects() || 6965 SequenceMBBI->mayLoadOrStore()) 6966 break; 6967 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 6968 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 6969 })) 6970 break; 6971 } 6972 } 6973 6974 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 6975 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 6976 DebugLoc DL = MI.getDebugLoc(); 6977 MachineFunction::iterator I = ++BB->getIterator(); 6978 6979 MachineBasicBlock *HeadMBB = BB; 6980 MachineFunction *F = BB->getParent(); 6981 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 6982 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 6983 6984 F->insert(I, IfFalseMBB); 6985 F->insert(I, TailMBB); 6986 6987 // Transfer debug instructions associated with the selects to TailMBB. 6988 for (MachineInstr *DebugInstr : SelectDebugValues) { 6989 TailMBB->push_back(DebugInstr->removeFromParent()); 6990 } 6991 6992 // Move all instructions after the sequence to TailMBB. 6993 TailMBB->splice(TailMBB->end(), HeadMBB, 6994 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 6995 // Update machine-CFG edges by transferring all successors of the current 6996 // block to the new block which will contain the Phi nodes for the selects. 6997 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 6998 // Set the successors for HeadMBB. 6999 HeadMBB->addSuccessor(IfFalseMBB); 7000 HeadMBB->addSuccessor(TailMBB); 7001 7002 // Insert appropriate branch. 7003 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 7004 .addReg(LHS) 7005 .addReg(RHS) 7006 .addMBB(TailMBB); 7007 7008 // IfFalseMBB just falls through to TailMBB. 7009 IfFalseMBB->addSuccessor(TailMBB); 7010 7011 // Create PHIs for all of the select pseudo-instructions. 7012 auto SelectMBBI = MI.getIterator(); 7013 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 7014 auto InsertionPoint = TailMBB->begin(); 7015 while (SelectMBBI != SelectEnd) { 7016 auto Next = std::next(SelectMBBI); 7017 if (isSelectPseudo(*SelectMBBI)) { 7018 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 7019 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 7020 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 7021 .addReg(SelectMBBI->getOperand(4).getReg()) 7022 .addMBB(HeadMBB) 7023 .addReg(SelectMBBI->getOperand(5).getReg()) 7024 .addMBB(IfFalseMBB); 7025 SelectMBBI->eraseFromParent(); 7026 } 7027 SelectMBBI = Next; 7028 } 7029 7030 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 7031 return TailMBB; 7032 } 7033 7034 MachineBasicBlock * 7035 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 7036 MachineBasicBlock *BB) const { 7037 switch (MI.getOpcode()) { 7038 default: 7039 llvm_unreachable("Unexpected instr type to insert"); 7040 case RISCV::ReadCycleWide: 7041 assert(!Subtarget.is64Bit() && 7042 "ReadCycleWrite is only to be used on riscv32"); 7043 return emitReadCycleWidePseudo(MI, BB); 7044 case RISCV::Select_GPR_Using_CC_GPR: 7045 case RISCV::Select_FPR16_Using_CC_GPR: 7046 case RISCV::Select_FPR32_Using_CC_GPR: 7047 case RISCV::Select_FPR64_Using_CC_GPR: 7048 return emitSelectPseudo(MI, BB, Subtarget); 7049 case RISCV::BuildPairF64Pseudo: 7050 return emitBuildPairF64Pseudo(MI, BB); 7051 case RISCV::SplitF64Pseudo: 7052 return emitSplitF64Pseudo(MI, BB); 7053 } 7054 } 7055 7056 // Calling Convention Implementation. 7057 // The expectations for frontend ABI lowering vary from target to target. 7058 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 7059 // details, but this is a longer term goal. For now, we simply try to keep the 7060 // role of the frontend as simple and well-defined as possible. The rules can 7061 // be summarised as: 7062 // * Never split up large scalar arguments. We handle them here. 7063 // * If a hardfloat calling convention is being used, and the struct may be 7064 // passed in a pair of registers (fp+fp, int+fp), and both registers are 7065 // available, then pass as two separate arguments. If either the GPRs or FPRs 7066 // are exhausted, then pass according to the rule below. 7067 // * If a struct could never be passed in registers or directly in a stack 7068 // slot (as it is larger than 2*XLEN and the floating point rules don't 7069 // apply), then pass it using a pointer with the byval attribute. 7070 // * If a struct is less than 2*XLEN, then coerce to either a two-element 7071 // word-sized array or a 2*XLEN scalar (depending on alignment). 7072 // * The frontend can determine whether a struct is returned by reference or 7073 // not based on its size and fields. If it will be returned by reference, the 7074 // frontend must modify the prototype so a pointer with the sret annotation is 7075 // passed as the first argument. This is not necessary for large scalar 7076 // returns. 7077 // * Struct return values and varargs should be coerced to structs containing 7078 // register-size fields in the same situations they would be for fixed 7079 // arguments. 7080 7081 static const MCPhysReg ArgGPRs[] = { 7082 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 7083 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 7084 }; 7085 static const MCPhysReg ArgFPR16s[] = { 7086 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 7087 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 7088 }; 7089 static const MCPhysReg ArgFPR32s[] = { 7090 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 7091 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 7092 }; 7093 static const MCPhysReg ArgFPR64s[] = { 7094 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 7095 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 7096 }; 7097 // This is an interim calling convention and it may be changed in the future. 7098 static const MCPhysReg ArgVRs[] = { 7099 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 7100 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 7101 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 7102 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 7103 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 7104 RISCV::V20M2, RISCV::V22M2}; 7105 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 7106 RISCV::V20M4}; 7107 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 7108 7109 // Pass a 2*XLEN argument that has been split into two XLEN values through 7110 // registers or the stack as necessary. 7111 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 7112 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 7113 MVT ValVT2, MVT LocVT2, 7114 ISD::ArgFlagsTy ArgFlags2) { 7115 unsigned XLenInBytes = XLen / 8; 7116 if (Register Reg = State.AllocateReg(ArgGPRs)) { 7117 // At least one half can be passed via register. 7118 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 7119 VA1.getLocVT(), CCValAssign::Full)); 7120 } else { 7121 // Both halves must be passed on the stack, with proper alignment. 7122 Align StackAlign = 7123 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 7124 State.addLoc( 7125 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 7126 State.AllocateStack(XLenInBytes, StackAlign), 7127 VA1.getLocVT(), CCValAssign::Full)); 7128 State.addLoc(CCValAssign::getMem( 7129 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 7130 LocVT2, CCValAssign::Full)); 7131 return false; 7132 } 7133 7134 if (Register Reg = State.AllocateReg(ArgGPRs)) { 7135 // The second half can also be passed via register. 7136 State.addLoc( 7137 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 7138 } else { 7139 // The second half is passed via the stack, without additional alignment. 7140 State.addLoc(CCValAssign::getMem( 7141 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 7142 LocVT2, CCValAssign::Full)); 7143 } 7144 7145 return false; 7146 } 7147 7148 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 7149 Optional<unsigned> FirstMaskArgument, 7150 CCState &State, const RISCVTargetLowering &TLI) { 7151 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 7152 if (RC == &RISCV::VRRegClass) { 7153 // Assign the first mask argument to V0. 7154 // This is an interim calling convention and it may be changed in the 7155 // future. 7156 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 7157 return State.AllocateReg(RISCV::V0); 7158 return State.AllocateReg(ArgVRs); 7159 } 7160 if (RC == &RISCV::VRM2RegClass) 7161 return State.AllocateReg(ArgVRM2s); 7162 if (RC == &RISCV::VRM4RegClass) 7163 return State.AllocateReg(ArgVRM4s); 7164 if (RC == &RISCV::VRM8RegClass) 7165 return State.AllocateReg(ArgVRM8s); 7166 llvm_unreachable("Unhandled register class for ValueType"); 7167 } 7168 7169 // Implements the RISC-V calling convention. Returns true upon failure. 7170 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 7171 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 7172 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 7173 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 7174 Optional<unsigned> FirstMaskArgument) { 7175 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 7176 assert(XLen == 32 || XLen == 64); 7177 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 7178 7179 // Any return value split in to more than two values can't be returned 7180 // directly. Vectors are returned via the available vector registers. 7181 if (!LocVT.isVector() && IsRet && ValNo > 1) 7182 return true; 7183 7184 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 7185 // variadic argument, or if no F16/F32 argument registers are available. 7186 bool UseGPRForF16_F32 = true; 7187 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 7188 // variadic argument, or if no F64 argument registers are available. 7189 bool UseGPRForF64 = true; 7190 7191 switch (ABI) { 7192 default: 7193 llvm_unreachable("Unexpected ABI"); 7194 case RISCVABI::ABI_ILP32: 7195 case RISCVABI::ABI_LP64: 7196 break; 7197 case RISCVABI::ABI_ILP32F: 7198 case RISCVABI::ABI_LP64F: 7199 UseGPRForF16_F32 = !IsFixed; 7200 break; 7201 case RISCVABI::ABI_ILP32D: 7202 case RISCVABI::ABI_LP64D: 7203 UseGPRForF16_F32 = !IsFixed; 7204 UseGPRForF64 = !IsFixed; 7205 break; 7206 } 7207 7208 // FPR16, FPR32, and FPR64 alias each other. 7209 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 7210 UseGPRForF16_F32 = true; 7211 UseGPRForF64 = true; 7212 } 7213 7214 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 7215 // similar local variables rather than directly checking against the target 7216 // ABI. 7217 7218 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 7219 LocVT = XLenVT; 7220 LocInfo = CCValAssign::BCvt; 7221 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 7222 LocVT = MVT::i64; 7223 LocInfo = CCValAssign::BCvt; 7224 } 7225 7226 // If this is a variadic argument, the RISC-V calling convention requires 7227 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 7228 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 7229 // be used regardless of whether the original argument was split during 7230 // legalisation or not. The argument will not be passed by registers if the 7231 // original type is larger than 2*XLEN, so the register alignment rule does 7232 // not apply. 7233 unsigned TwoXLenInBytes = (2 * XLen) / 8; 7234 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 7235 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 7236 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 7237 // Skip 'odd' register if necessary. 7238 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 7239 State.AllocateReg(ArgGPRs); 7240 } 7241 7242 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 7243 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 7244 State.getPendingArgFlags(); 7245 7246 assert(PendingLocs.size() == PendingArgFlags.size() && 7247 "PendingLocs and PendingArgFlags out of sync"); 7248 7249 // Handle passing f64 on RV32D with a soft float ABI or when floating point 7250 // registers are exhausted. 7251 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 7252 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 7253 "Can't lower f64 if it is split"); 7254 // Depending on available argument GPRS, f64 may be passed in a pair of 7255 // GPRs, split between a GPR and the stack, or passed completely on the 7256 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 7257 // cases. 7258 Register Reg = State.AllocateReg(ArgGPRs); 7259 LocVT = MVT::i32; 7260 if (!Reg) { 7261 unsigned StackOffset = State.AllocateStack(8, Align(8)); 7262 State.addLoc( 7263 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 7264 return false; 7265 } 7266 if (!State.AllocateReg(ArgGPRs)) 7267 State.AllocateStack(4, Align(4)); 7268 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 7269 return false; 7270 } 7271 7272 // Fixed-length vectors are located in the corresponding scalable-vector 7273 // container types. 7274 if (ValVT.isFixedLengthVector()) 7275 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 7276 7277 // Split arguments might be passed indirectly, so keep track of the pending 7278 // values. Split vectors are passed via a mix of registers and indirectly, so 7279 // treat them as we would any other argument. 7280 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 7281 LocVT = XLenVT; 7282 LocInfo = CCValAssign::Indirect; 7283 PendingLocs.push_back( 7284 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 7285 PendingArgFlags.push_back(ArgFlags); 7286 if (!ArgFlags.isSplitEnd()) { 7287 return false; 7288 } 7289 } 7290 7291 // If the split argument only had two elements, it should be passed directly 7292 // in registers or on the stack. 7293 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 7294 PendingLocs.size() <= 2) { 7295 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 7296 // Apply the normal calling convention rules to the first half of the 7297 // split argument. 7298 CCValAssign VA = PendingLocs[0]; 7299 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 7300 PendingLocs.clear(); 7301 PendingArgFlags.clear(); 7302 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 7303 ArgFlags); 7304 } 7305 7306 // Allocate to a register if possible, or else a stack slot. 7307 Register Reg; 7308 unsigned StoreSizeBytes = XLen / 8; 7309 Align StackAlign = Align(XLen / 8); 7310 7311 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 7312 Reg = State.AllocateReg(ArgFPR16s); 7313 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 7314 Reg = State.AllocateReg(ArgFPR32s); 7315 else if (ValVT == MVT::f64 && !UseGPRForF64) 7316 Reg = State.AllocateReg(ArgFPR64s); 7317 else if (ValVT.isVector()) { 7318 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 7319 if (!Reg) { 7320 // For return values, the vector must be passed fully via registers or 7321 // via the stack. 7322 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 7323 // but we're using all of them. 7324 if (IsRet) 7325 return true; 7326 // Try using a GPR to pass the address 7327 if ((Reg = State.AllocateReg(ArgGPRs))) { 7328 LocVT = XLenVT; 7329 LocInfo = CCValAssign::Indirect; 7330 } else if (ValVT.isScalableVector()) { 7331 report_fatal_error("Unable to pass scalable vector types on the stack"); 7332 } else { 7333 // Pass fixed-length vectors on the stack. 7334 LocVT = ValVT; 7335 StoreSizeBytes = ValVT.getStoreSize(); 7336 // Align vectors to their element sizes, being careful for vXi1 7337 // vectors. 7338 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 7339 } 7340 } 7341 } else { 7342 Reg = State.AllocateReg(ArgGPRs); 7343 } 7344 7345 unsigned StackOffset = 7346 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 7347 7348 // If we reach this point and PendingLocs is non-empty, we must be at the 7349 // end of a split argument that must be passed indirectly. 7350 if (!PendingLocs.empty()) { 7351 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 7352 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 7353 7354 for (auto &It : PendingLocs) { 7355 if (Reg) 7356 It.convertToReg(Reg); 7357 else 7358 It.convertToMem(StackOffset); 7359 State.addLoc(It); 7360 } 7361 PendingLocs.clear(); 7362 PendingArgFlags.clear(); 7363 return false; 7364 } 7365 7366 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 7367 (TLI.getSubtarget().hasStdExtV() && ValVT.isVector())) && 7368 "Expected an XLenVT or vector types at this stage"); 7369 7370 if (Reg) { 7371 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 7372 return false; 7373 } 7374 7375 // When a floating-point value is passed on the stack, no bit-conversion is 7376 // needed. 7377 if (ValVT.isFloatingPoint()) { 7378 LocVT = ValVT; 7379 LocInfo = CCValAssign::Full; 7380 } 7381 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 7382 return false; 7383 } 7384 7385 template <typename ArgTy> 7386 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 7387 for (const auto &ArgIdx : enumerate(Args)) { 7388 MVT ArgVT = ArgIdx.value().VT; 7389 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 7390 return ArgIdx.index(); 7391 } 7392 return None; 7393 } 7394 7395 void RISCVTargetLowering::analyzeInputArgs( 7396 MachineFunction &MF, CCState &CCInfo, 7397 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 7398 RISCVCCAssignFn Fn) const { 7399 unsigned NumArgs = Ins.size(); 7400 FunctionType *FType = MF.getFunction().getFunctionType(); 7401 7402 Optional<unsigned> FirstMaskArgument; 7403 if (Subtarget.hasStdExtV()) 7404 FirstMaskArgument = preAssignMask(Ins); 7405 7406 for (unsigned i = 0; i != NumArgs; ++i) { 7407 MVT ArgVT = Ins[i].VT; 7408 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 7409 7410 Type *ArgTy = nullptr; 7411 if (IsRet) 7412 ArgTy = FType->getReturnType(); 7413 else if (Ins[i].isOrigArg()) 7414 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 7415 7416 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 7417 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 7418 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 7419 FirstMaskArgument)) { 7420 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 7421 << EVT(ArgVT).getEVTString() << '\n'); 7422 llvm_unreachable(nullptr); 7423 } 7424 } 7425 } 7426 7427 void RISCVTargetLowering::analyzeOutputArgs( 7428 MachineFunction &MF, CCState &CCInfo, 7429 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 7430 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 7431 unsigned NumArgs = Outs.size(); 7432 7433 Optional<unsigned> FirstMaskArgument; 7434 if (Subtarget.hasStdExtV()) 7435 FirstMaskArgument = preAssignMask(Outs); 7436 7437 for (unsigned i = 0; i != NumArgs; i++) { 7438 MVT ArgVT = Outs[i].VT; 7439 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 7440 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 7441 7442 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 7443 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 7444 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 7445 FirstMaskArgument)) { 7446 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 7447 << EVT(ArgVT).getEVTString() << "\n"); 7448 llvm_unreachable(nullptr); 7449 } 7450 } 7451 } 7452 7453 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 7454 // values. 7455 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 7456 const CCValAssign &VA, const SDLoc &DL, 7457 const RISCVSubtarget &Subtarget) { 7458 switch (VA.getLocInfo()) { 7459 default: 7460 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 7461 case CCValAssign::Full: 7462 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 7463 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 7464 break; 7465 case CCValAssign::BCvt: 7466 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 7467 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 7468 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 7469 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 7470 else 7471 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 7472 break; 7473 } 7474 return Val; 7475 } 7476 7477 // The caller is responsible for loading the full value if the argument is 7478 // passed with CCValAssign::Indirect. 7479 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 7480 const CCValAssign &VA, const SDLoc &DL, 7481 const RISCVTargetLowering &TLI) { 7482 MachineFunction &MF = DAG.getMachineFunction(); 7483 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7484 EVT LocVT = VA.getLocVT(); 7485 SDValue Val; 7486 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 7487 Register VReg = RegInfo.createVirtualRegister(RC); 7488 RegInfo.addLiveIn(VA.getLocReg(), VReg); 7489 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 7490 7491 if (VA.getLocInfo() == CCValAssign::Indirect) 7492 return Val; 7493 7494 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 7495 } 7496 7497 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 7498 const CCValAssign &VA, const SDLoc &DL, 7499 const RISCVSubtarget &Subtarget) { 7500 EVT LocVT = VA.getLocVT(); 7501 7502 switch (VA.getLocInfo()) { 7503 default: 7504 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 7505 case CCValAssign::Full: 7506 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 7507 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 7508 break; 7509 case CCValAssign::BCvt: 7510 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 7511 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 7512 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 7513 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 7514 else 7515 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 7516 break; 7517 } 7518 return Val; 7519 } 7520 7521 // The caller is responsible for loading the full value if the argument is 7522 // passed with CCValAssign::Indirect. 7523 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 7524 const CCValAssign &VA, const SDLoc &DL) { 7525 MachineFunction &MF = DAG.getMachineFunction(); 7526 MachineFrameInfo &MFI = MF.getFrameInfo(); 7527 EVT LocVT = VA.getLocVT(); 7528 EVT ValVT = VA.getValVT(); 7529 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 7530 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 7531 /*Immutable=*/true); 7532 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7533 SDValue Val; 7534 7535 ISD::LoadExtType ExtType; 7536 switch (VA.getLocInfo()) { 7537 default: 7538 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 7539 case CCValAssign::Full: 7540 case CCValAssign::Indirect: 7541 case CCValAssign::BCvt: 7542 ExtType = ISD::NON_EXTLOAD; 7543 break; 7544 } 7545 Val = DAG.getExtLoad( 7546 ExtType, DL, LocVT, Chain, FIN, 7547 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 7548 return Val; 7549 } 7550 7551 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 7552 const CCValAssign &VA, const SDLoc &DL) { 7553 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 7554 "Unexpected VA"); 7555 MachineFunction &MF = DAG.getMachineFunction(); 7556 MachineFrameInfo &MFI = MF.getFrameInfo(); 7557 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7558 7559 if (VA.isMemLoc()) { 7560 // f64 is passed on the stack. 7561 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 7562 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 7563 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 7564 MachinePointerInfo::getFixedStack(MF, FI)); 7565 } 7566 7567 assert(VA.isRegLoc() && "Expected register VA assignment"); 7568 7569 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 7570 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 7571 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 7572 SDValue Hi; 7573 if (VA.getLocReg() == RISCV::X17) { 7574 // Second half of f64 is passed on the stack. 7575 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 7576 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 7577 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 7578 MachinePointerInfo::getFixedStack(MF, FI)); 7579 } else { 7580 // Second half of f64 is passed in another GPR. 7581 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 7582 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 7583 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 7584 } 7585 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 7586 } 7587 7588 // FastCC has less than 1% performance improvement for some particular 7589 // benchmark. But theoretically, it may has benenfit for some cases. 7590 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 7591 unsigned ValNo, MVT ValVT, MVT LocVT, 7592 CCValAssign::LocInfo LocInfo, 7593 ISD::ArgFlagsTy ArgFlags, CCState &State, 7594 bool IsFixed, bool IsRet, Type *OrigTy, 7595 const RISCVTargetLowering &TLI, 7596 Optional<unsigned> FirstMaskArgument) { 7597 7598 // X5 and X6 might be used for save-restore libcall. 7599 static const MCPhysReg GPRList[] = { 7600 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 7601 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 7602 RISCV::X29, RISCV::X30, RISCV::X31}; 7603 7604 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 7605 if (unsigned Reg = State.AllocateReg(GPRList)) { 7606 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 7607 return false; 7608 } 7609 } 7610 7611 if (LocVT == MVT::f16) { 7612 static const MCPhysReg FPR16List[] = { 7613 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 7614 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 7615 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 7616 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 7617 if (unsigned Reg = State.AllocateReg(FPR16List)) { 7618 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 7619 return false; 7620 } 7621 } 7622 7623 if (LocVT == MVT::f32) { 7624 static const MCPhysReg FPR32List[] = { 7625 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 7626 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 7627 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 7628 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 7629 if (unsigned Reg = State.AllocateReg(FPR32List)) { 7630 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 7631 return false; 7632 } 7633 } 7634 7635 if (LocVT == MVT::f64) { 7636 static const MCPhysReg FPR64List[] = { 7637 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 7638 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 7639 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 7640 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 7641 if (unsigned Reg = State.AllocateReg(FPR64List)) { 7642 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 7643 return false; 7644 } 7645 } 7646 7647 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 7648 unsigned Offset4 = State.AllocateStack(4, Align(4)); 7649 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 7650 return false; 7651 } 7652 7653 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 7654 unsigned Offset5 = State.AllocateStack(8, Align(8)); 7655 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 7656 return false; 7657 } 7658 7659 if (LocVT.isVector()) { 7660 if (unsigned Reg = 7661 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 7662 // Fixed-length vectors are located in the corresponding scalable-vector 7663 // container types. 7664 if (ValVT.isFixedLengthVector()) 7665 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 7666 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 7667 } else { 7668 // Try and pass the address via a "fast" GPR. 7669 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 7670 LocInfo = CCValAssign::Indirect; 7671 LocVT = TLI.getSubtarget().getXLenVT(); 7672 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 7673 } else if (ValVT.isFixedLengthVector()) { 7674 auto StackAlign = 7675 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 7676 unsigned StackOffset = 7677 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 7678 State.addLoc( 7679 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 7680 } else { 7681 // Can't pass scalable vectors on the stack. 7682 return true; 7683 } 7684 } 7685 7686 return false; 7687 } 7688 7689 return true; // CC didn't match. 7690 } 7691 7692 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 7693 CCValAssign::LocInfo LocInfo, 7694 ISD::ArgFlagsTy ArgFlags, CCState &State) { 7695 7696 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 7697 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 7698 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 7699 static const MCPhysReg GPRList[] = { 7700 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 7701 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 7702 if (unsigned Reg = State.AllocateReg(GPRList)) { 7703 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 7704 return false; 7705 } 7706 } 7707 7708 if (LocVT == MVT::f32) { 7709 // Pass in STG registers: F1, ..., F6 7710 // fs0 ... fs5 7711 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 7712 RISCV::F18_F, RISCV::F19_F, 7713 RISCV::F20_F, RISCV::F21_F}; 7714 if (unsigned Reg = State.AllocateReg(FPR32List)) { 7715 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 7716 return false; 7717 } 7718 } 7719 7720 if (LocVT == MVT::f64) { 7721 // Pass in STG registers: D1, ..., D6 7722 // fs6 ... fs11 7723 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 7724 RISCV::F24_D, RISCV::F25_D, 7725 RISCV::F26_D, RISCV::F27_D}; 7726 if (unsigned Reg = State.AllocateReg(FPR64List)) { 7727 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 7728 return false; 7729 } 7730 } 7731 7732 report_fatal_error("No registers left in GHC calling convention"); 7733 return true; 7734 } 7735 7736 // Transform physical registers into virtual registers. 7737 SDValue RISCVTargetLowering::LowerFormalArguments( 7738 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 7739 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 7740 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7741 7742 MachineFunction &MF = DAG.getMachineFunction(); 7743 7744 switch (CallConv) { 7745 default: 7746 report_fatal_error("Unsupported calling convention"); 7747 case CallingConv::C: 7748 case CallingConv::Fast: 7749 break; 7750 case CallingConv::GHC: 7751 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 7752 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 7753 report_fatal_error( 7754 "GHC calling convention requires the F and D instruction set extensions"); 7755 } 7756 7757 const Function &Func = MF.getFunction(); 7758 if (Func.hasFnAttribute("interrupt")) { 7759 if (!Func.arg_empty()) 7760 report_fatal_error( 7761 "Functions with the interrupt attribute cannot have arguments!"); 7762 7763 StringRef Kind = 7764 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 7765 7766 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 7767 report_fatal_error( 7768 "Function interrupt attribute argument not supported!"); 7769 } 7770 7771 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7772 MVT XLenVT = Subtarget.getXLenVT(); 7773 unsigned XLenInBytes = Subtarget.getXLen() / 8; 7774 // Used with vargs to acumulate store chains. 7775 std::vector<SDValue> OutChains; 7776 7777 // Assign locations to all of the incoming arguments. 7778 SmallVector<CCValAssign, 16> ArgLocs; 7779 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 7780 7781 if (CallConv == CallingConv::GHC) 7782 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 7783 else 7784 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 7785 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 7786 : CC_RISCV); 7787 7788 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 7789 CCValAssign &VA = ArgLocs[i]; 7790 SDValue ArgValue; 7791 // Passing f64 on RV32D with a soft float ABI must be handled as a special 7792 // case. 7793 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 7794 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 7795 else if (VA.isRegLoc()) 7796 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 7797 else 7798 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 7799 7800 if (VA.getLocInfo() == CCValAssign::Indirect) { 7801 // If the original argument was split and passed by reference (e.g. i128 7802 // on RV32), we need to load all parts of it here (using the same 7803 // address). Vectors may be partly split to registers and partly to the 7804 // stack, in which case the base address is partly offset and subsequent 7805 // stores are relative to that. 7806 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 7807 MachinePointerInfo())); 7808 unsigned ArgIndex = Ins[i].OrigArgIndex; 7809 unsigned ArgPartOffset = Ins[i].PartOffset; 7810 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 7811 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 7812 CCValAssign &PartVA = ArgLocs[i + 1]; 7813 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 7814 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 7815 if (PartVA.getValVT().isScalableVector()) 7816 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 7817 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 7818 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 7819 MachinePointerInfo())); 7820 ++i; 7821 } 7822 continue; 7823 } 7824 InVals.push_back(ArgValue); 7825 } 7826 7827 if (IsVarArg) { 7828 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 7829 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 7830 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 7831 MachineFrameInfo &MFI = MF.getFrameInfo(); 7832 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7833 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 7834 7835 // Offset of the first variable argument from stack pointer, and size of 7836 // the vararg save area. For now, the varargs save area is either zero or 7837 // large enough to hold a0-a7. 7838 int VaArgOffset, VarArgsSaveSize; 7839 7840 // If all registers are allocated, then all varargs must be passed on the 7841 // stack and we don't need to save any argregs. 7842 if (ArgRegs.size() == Idx) { 7843 VaArgOffset = CCInfo.getNextStackOffset(); 7844 VarArgsSaveSize = 0; 7845 } else { 7846 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 7847 VaArgOffset = -VarArgsSaveSize; 7848 } 7849 7850 // Record the frame index of the first variable argument 7851 // which is a value necessary to VASTART. 7852 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 7853 RVFI->setVarArgsFrameIndex(FI); 7854 7855 // If saving an odd number of registers then create an extra stack slot to 7856 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 7857 // offsets to even-numbered registered remain 2*XLEN-aligned. 7858 if (Idx % 2) { 7859 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 7860 VarArgsSaveSize += XLenInBytes; 7861 } 7862 7863 // Copy the integer registers that may have been used for passing varargs 7864 // to the vararg save area. 7865 for (unsigned I = Idx; I < ArgRegs.size(); 7866 ++I, VaArgOffset += XLenInBytes) { 7867 const Register Reg = RegInfo.createVirtualRegister(RC); 7868 RegInfo.addLiveIn(ArgRegs[I], Reg); 7869 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 7870 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 7871 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 7872 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 7873 MachinePointerInfo::getFixedStack(MF, FI)); 7874 cast<StoreSDNode>(Store.getNode()) 7875 ->getMemOperand() 7876 ->setValue((Value *)nullptr); 7877 OutChains.push_back(Store); 7878 } 7879 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 7880 } 7881 7882 // All stores are grouped in one node to allow the matching between 7883 // the size of Ins and InVals. This only happens for vararg functions. 7884 if (!OutChains.empty()) { 7885 OutChains.push_back(Chain); 7886 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 7887 } 7888 7889 return Chain; 7890 } 7891 7892 /// isEligibleForTailCallOptimization - Check whether the call is eligible 7893 /// for tail call optimization. 7894 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 7895 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 7896 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 7897 const SmallVector<CCValAssign, 16> &ArgLocs) const { 7898 7899 auto &Callee = CLI.Callee; 7900 auto CalleeCC = CLI.CallConv; 7901 auto &Outs = CLI.Outs; 7902 auto &Caller = MF.getFunction(); 7903 auto CallerCC = Caller.getCallingConv(); 7904 7905 // Exception-handling functions need a special set of instructions to 7906 // indicate a return to the hardware. Tail-calling another function would 7907 // probably break this. 7908 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 7909 // should be expanded as new function attributes are introduced. 7910 if (Caller.hasFnAttribute("interrupt")) 7911 return false; 7912 7913 // Do not tail call opt if the stack is used to pass parameters. 7914 if (CCInfo.getNextStackOffset() != 0) 7915 return false; 7916 7917 // Do not tail call opt if any parameters need to be passed indirectly. 7918 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 7919 // passed indirectly. So the address of the value will be passed in a 7920 // register, or if not available, then the address is put on the stack. In 7921 // order to pass indirectly, space on the stack often needs to be allocated 7922 // in order to store the value. In this case the CCInfo.getNextStackOffset() 7923 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 7924 // are passed CCValAssign::Indirect. 7925 for (auto &VA : ArgLocs) 7926 if (VA.getLocInfo() == CCValAssign::Indirect) 7927 return false; 7928 7929 // Do not tail call opt if either caller or callee uses struct return 7930 // semantics. 7931 auto IsCallerStructRet = Caller.hasStructRetAttr(); 7932 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 7933 if (IsCallerStructRet || IsCalleeStructRet) 7934 return false; 7935 7936 // Externally-defined functions with weak linkage should not be 7937 // tail-called. The behaviour of branch instructions in this situation (as 7938 // used for tail calls) is implementation-defined, so we cannot rely on the 7939 // linker replacing the tail call with a return. 7940 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 7941 const GlobalValue *GV = G->getGlobal(); 7942 if (GV->hasExternalWeakLinkage()) 7943 return false; 7944 } 7945 7946 // The callee has to preserve all registers the caller needs to preserve. 7947 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 7948 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 7949 if (CalleeCC != CallerCC) { 7950 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 7951 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 7952 return false; 7953 } 7954 7955 // Byval parameters hand the function a pointer directly into the stack area 7956 // we want to reuse during a tail call. Working around this *is* possible 7957 // but less efficient and uglier in LowerCall. 7958 for (auto &Arg : Outs) 7959 if (Arg.Flags.isByVal()) 7960 return false; 7961 7962 return true; 7963 } 7964 7965 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 7966 return DAG.getDataLayout().getPrefTypeAlign( 7967 VT.getTypeForEVT(*DAG.getContext())); 7968 } 7969 7970 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 7971 // and output parameter nodes. 7972 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 7973 SmallVectorImpl<SDValue> &InVals) const { 7974 SelectionDAG &DAG = CLI.DAG; 7975 SDLoc &DL = CLI.DL; 7976 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 7977 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 7978 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 7979 SDValue Chain = CLI.Chain; 7980 SDValue Callee = CLI.Callee; 7981 bool &IsTailCall = CLI.IsTailCall; 7982 CallingConv::ID CallConv = CLI.CallConv; 7983 bool IsVarArg = CLI.IsVarArg; 7984 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7985 MVT XLenVT = Subtarget.getXLenVT(); 7986 7987 MachineFunction &MF = DAG.getMachineFunction(); 7988 7989 // Analyze the operands of the call, assigning locations to each operand. 7990 SmallVector<CCValAssign, 16> ArgLocs; 7991 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 7992 7993 if (CallConv == CallingConv::GHC) 7994 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 7995 else 7996 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 7997 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 7998 : CC_RISCV); 7999 8000 // Check if it's really possible to do a tail call. 8001 if (IsTailCall) 8002 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 8003 8004 if (IsTailCall) 8005 ++NumTailCalls; 8006 else if (CLI.CB && CLI.CB->isMustTailCall()) 8007 report_fatal_error("failed to perform tail call elimination on a call " 8008 "site marked musttail"); 8009 8010 // Get a count of how many bytes are to be pushed on the stack. 8011 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 8012 8013 // Create local copies for byval args 8014 SmallVector<SDValue, 8> ByValArgs; 8015 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 8016 ISD::ArgFlagsTy Flags = Outs[i].Flags; 8017 if (!Flags.isByVal()) 8018 continue; 8019 8020 SDValue Arg = OutVals[i]; 8021 unsigned Size = Flags.getByValSize(); 8022 Align Alignment = Flags.getNonZeroByValAlign(); 8023 8024 int FI = 8025 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 8026 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8027 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 8028 8029 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 8030 /*IsVolatile=*/false, 8031 /*AlwaysInline=*/false, IsTailCall, 8032 MachinePointerInfo(), MachinePointerInfo()); 8033 ByValArgs.push_back(FIPtr); 8034 } 8035 8036 if (!IsTailCall) 8037 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 8038 8039 // Copy argument values to their designated locations. 8040 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 8041 SmallVector<SDValue, 8> MemOpChains; 8042 SDValue StackPtr; 8043 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 8044 CCValAssign &VA = ArgLocs[i]; 8045 SDValue ArgValue = OutVals[i]; 8046 ISD::ArgFlagsTy Flags = Outs[i].Flags; 8047 8048 // Handle passing f64 on RV32D with a soft float ABI as a special case. 8049 bool IsF64OnRV32DSoftABI = 8050 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 8051 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 8052 SDValue SplitF64 = DAG.getNode( 8053 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 8054 SDValue Lo = SplitF64.getValue(0); 8055 SDValue Hi = SplitF64.getValue(1); 8056 8057 Register RegLo = VA.getLocReg(); 8058 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 8059 8060 if (RegLo == RISCV::X17) { 8061 // Second half of f64 is passed on the stack. 8062 // Work out the address of the stack slot. 8063 if (!StackPtr.getNode()) 8064 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 8065 // Emit the store. 8066 MemOpChains.push_back( 8067 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 8068 } else { 8069 // Second half of f64 is passed in another GPR. 8070 assert(RegLo < RISCV::X31 && "Invalid register pair"); 8071 Register RegHigh = RegLo + 1; 8072 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 8073 } 8074 continue; 8075 } 8076 8077 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 8078 // as any other MemLoc. 8079 8080 // Promote the value if needed. 8081 // For now, only handle fully promoted and indirect arguments. 8082 if (VA.getLocInfo() == CCValAssign::Indirect) { 8083 // Store the argument in a stack slot and pass its address. 8084 Align StackAlign = 8085 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 8086 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 8087 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 8088 // If the original argument was split (e.g. i128), we need 8089 // to store the required parts of it here (and pass just one address). 8090 // Vectors may be partly split to registers and partly to the stack, in 8091 // which case the base address is partly offset and subsequent stores are 8092 // relative to that. 8093 unsigned ArgIndex = Outs[i].OrigArgIndex; 8094 unsigned ArgPartOffset = Outs[i].PartOffset; 8095 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8096 // Calculate the total size to store. We don't have access to what we're 8097 // actually storing other than performing the loop and collecting the 8098 // info. 8099 SmallVector<std::pair<SDValue, SDValue>> Parts; 8100 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 8101 SDValue PartValue = OutVals[i + 1]; 8102 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 8103 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8104 EVT PartVT = PartValue.getValueType(); 8105 if (PartVT.isScalableVector()) 8106 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8107 StoredSize += PartVT.getStoreSize(); 8108 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 8109 Parts.push_back(std::make_pair(PartValue, Offset)); 8110 ++i; 8111 } 8112 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 8113 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 8114 MemOpChains.push_back( 8115 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 8116 MachinePointerInfo::getFixedStack(MF, FI))); 8117 for (const auto &Part : Parts) { 8118 SDValue PartValue = Part.first; 8119 SDValue PartOffset = Part.second; 8120 SDValue Address = 8121 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 8122 MemOpChains.push_back( 8123 DAG.getStore(Chain, DL, PartValue, Address, 8124 MachinePointerInfo::getFixedStack(MF, FI))); 8125 } 8126 ArgValue = SpillSlot; 8127 } else { 8128 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 8129 } 8130 8131 // Use local copy if it is a byval arg. 8132 if (Flags.isByVal()) 8133 ArgValue = ByValArgs[j++]; 8134 8135 if (VA.isRegLoc()) { 8136 // Queue up the argument copies and emit them at the end. 8137 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 8138 } else { 8139 assert(VA.isMemLoc() && "Argument not register or memory"); 8140 assert(!IsTailCall && "Tail call not allowed if stack is used " 8141 "for passing parameters"); 8142 8143 // Work out the address of the stack slot. 8144 if (!StackPtr.getNode()) 8145 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 8146 SDValue Address = 8147 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 8148 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 8149 8150 // Emit the store. 8151 MemOpChains.push_back( 8152 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 8153 } 8154 } 8155 8156 // Join the stores, which are independent of one another. 8157 if (!MemOpChains.empty()) 8158 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 8159 8160 SDValue Glue; 8161 8162 // Build a sequence of copy-to-reg nodes, chained and glued together. 8163 for (auto &Reg : RegsToPass) { 8164 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 8165 Glue = Chain.getValue(1); 8166 } 8167 8168 // Validate that none of the argument registers have been marked as 8169 // reserved, if so report an error. Do the same for the return address if this 8170 // is not a tailcall. 8171 validateCCReservedRegs(RegsToPass, MF); 8172 if (!IsTailCall && 8173 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 8174 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 8175 MF.getFunction(), 8176 "Return address register required, but has been reserved."}); 8177 8178 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 8179 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 8180 // split it and then direct call can be matched by PseudoCALL. 8181 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 8182 const GlobalValue *GV = S->getGlobal(); 8183 8184 unsigned OpFlags = RISCVII::MO_CALL; 8185 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 8186 OpFlags = RISCVII::MO_PLT; 8187 8188 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 8189 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 8190 unsigned OpFlags = RISCVII::MO_CALL; 8191 8192 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 8193 nullptr)) 8194 OpFlags = RISCVII::MO_PLT; 8195 8196 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 8197 } 8198 8199 // The first call operand is the chain and the second is the target address. 8200 SmallVector<SDValue, 8> Ops; 8201 Ops.push_back(Chain); 8202 Ops.push_back(Callee); 8203 8204 // Add argument registers to the end of the list so that they are 8205 // known live into the call. 8206 for (auto &Reg : RegsToPass) 8207 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 8208 8209 if (!IsTailCall) { 8210 // Add a register mask operand representing the call-preserved registers. 8211 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 8212 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 8213 assert(Mask && "Missing call preserved mask for calling convention"); 8214 Ops.push_back(DAG.getRegisterMask(Mask)); 8215 } 8216 8217 // Glue the call to the argument copies, if any. 8218 if (Glue.getNode()) 8219 Ops.push_back(Glue); 8220 8221 // Emit the call. 8222 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8223 8224 if (IsTailCall) { 8225 MF.getFrameInfo().setHasTailCall(); 8226 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 8227 } 8228 8229 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 8230 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 8231 Glue = Chain.getValue(1); 8232 8233 // Mark the end of the call, which is glued to the call itself. 8234 Chain = DAG.getCALLSEQ_END(Chain, 8235 DAG.getConstant(NumBytes, DL, PtrVT, true), 8236 DAG.getConstant(0, DL, PtrVT, true), 8237 Glue, DL); 8238 Glue = Chain.getValue(1); 8239 8240 // Assign locations to each value returned by this call. 8241 SmallVector<CCValAssign, 16> RVLocs; 8242 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 8243 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 8244 8245 // Copy all of the result registers out of their specified physreg. 8246 for (auto &VA : RVLocs) { 8247 // Copy the value out 8248 SDValue RetValue = 8249 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 8250 // Glue the RetValue to the end of the call sequence 8251 Chain = RetValue.getValue(1); 8252 Glue = RetValue.getValue(2); 8253 8254 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 8255 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 8256 SDValue RetValue2 = 8257 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 8258 Chain = RetValue2.getValue(1); 8259 Glue = RetValue2.getValue(2); 8260 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 8261 RetValue2); 8262 } 8263 8264 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 8265 8266 InVals.push_back(RetValue); 8267 } 8268 8269 return Chain; 8270 } 8271 8272 bool RISCVTargetLowering::CanLowerReturn( 8273 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 8274 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 8275 SmallVector<CCValAssign, 16> RVLocs; 8276 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 8277 8278 Optional<unsigned> FirstMaskArgument; 8279 if (Subtarget.hasStdExtV()) 8280 FirstMaskArgument = preAssignMask(Outs); 8281 8282 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 8283 MVT VT = Outs[i].VT; 8284 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 8285 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8286 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 8287 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 8288 *this, FirstMaskArgument)) 8289 return false; 8290 } 8291 return true; 8292 } 8293 8294 SDValue 8295 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 8296 bool IsVarArg, 8297 const SmallVectorImpl<ISD::OutputArg> &Outs, 8298 const SmallVectorImpl<SDValue> &OutVals, 8299 const SDLoc &DL, SelectionDAG &DAG) const { 8300 const MachineFunction &MF = DAG.getMachineFunction(); 8301 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 8302 8303 // Stores the assignment of the return value to a location. 8304 SmallVector<CCValAssign, 16> RVLocs; 8305 8306 // Info about the registers and stack slot. 8307 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 8308 *DAG.getContext()); 8309 8310 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 8311 nullptr, CC_RISCV); 8312 8313 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 8314 report_fatal_error("GHC functions return void only"); 8315 8316 SDValue Glue; 8317 SmallVector<SDValue, 4> RetOps(1, Chain); 8318 8319 // Copy the result values into the output registers. 8320 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 8321 SDValue Val = OutVals[i]; 8322 CCValAssign &VA = RVLocs[i]; 8323 assert(VA.isRegLoc() && "Can only return in registers!"); 8324 8325 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 8326 // Handle returning f64 on RV32D with a soft float ABI. 8327 assert(VA.isRegLoc() && "Expected return via registers"); 8328 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 8329 DAG.getVTList(MVT::i32, MVT::i32), Val); 8330 SDValue Lo = SplitF64.getValue(0); 8331 SDValue Hi = SplitF64.getValue(1); 8332 Register RegLo = VA.getLocReg(); 8333 assert(RegLo < RISCV::X31 && "Invalid register pair"); 8334 Register RegHi = RegLo + 1; 8335 8336 if (STI.isRegisterReservedByUser(RegLo) || 8337 STI.isRegisterReservedByUser(RegHi)) 8338 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 8339 MF.getFunction(), 8340 "Return value register required, but has been reserved."}); 8341 8342 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 8343 Glue = Chain.getValue(1); 8344 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 8345 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 8346 Glue = Chain.getValue(1); 8347 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 8348 } else { 8349 // Handle a 'normal' return. 8350 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 8351 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 8352 8353 if (STI.isRegisterReservedByUser(VA.getLocReg())) 8354 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 8355 MF.getFunction(), 8356 "Return value register required, but has been reserved."}); 8357 8358 // Guarantee that all emitted copies are stuck together. 8359 Glue = Chain.getValue(1); 8360 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 8361 } 8362 } 8363 8364 RetOps[0] = Chain; // Update chain. 8365 8366 // Add the glue node if we have it. 8367 if (Glue.getNode()) { 8368 RetOps.push_back(Glue); 8369 } 8370 8371 unsigned RetOpc = RISCVISD::RET_FLAG; 8372 // Interrupt service routines use different return instructions. 8373 const Function &Func = DAG.getMachineFunction().getFunction(); 8374 if (Func.hasFnAttribute("interrupt")) { 8375 if (!Func.getReturnType()->isVoidTy()) 8376 report_fatal_error( 8377 "Functions with the interrupt attribute must have void return type!"); 8378 8379 MachineFunction &MF = DAG.getMachineFunction(); 8380 StringRef Kind = 8381 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 8382 8383 if (Kind == "user") 8384 RetOpc = RISCVISD::URET_FLAG; 8385 else if (Kind == "supervisor") 8386 RetOpc = RISCVISD::SRET_FLAG; 8387 else 8388 RetOpc = RISCVISD::MRET_FLAG; 8389 } 8390 8391 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 8392 } 8393 8394 void RISCVTargetLowering::validateCCReservedRegs( 8395 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 8396 MachineFunction &MF) const { 8397 const Function &F = MF.getFunction(); 8398 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 8399 8400 if (llvm::any_of(Regs, [&STI](auto Reg) { 8401 return STI.isRegisterReservedByUser(Reg.first); 8402 })) 8403 F.getContext().diagnose(DiagnosticInfoUnsupported{ 8404 F, "Argument register required, but has been reserved."}); 8405 } 8406 8407 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 8408 return CI->isTailCall(); 8409 } 8410 8411 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 8412 #define NODE_NAME_CASE(NODE) \ 8413 case RISCVISD::NODE: \ 8414 return "RISCVISD::" #NODE; 8415 // clang-format off 8416 switch ((RISCVISD::NodeType)Opcode) { 8417 case RISCVISD::FIRST_NUMBER: 8418 break; 8419 NODE_NAME_CASE(RET_FLAG) 8420 NODE_NAME_CASE(URET_FLAG) 8421 NODE_NAME_CASE(SRET_FLAG) 8422 NODE_NAME_CASE(MRET_FLAG) 8423 NODE_NAME_CASE(CALL) 8424 NODE_NAME_CASE(SELECT_CC) 8425 NODE_NAME_CASE(BR_CC) 8426 NODE_NAME_CASE(BuildPairF64) 8427 NODE_NAME_CASE(SplitF64) 8428 NODE_NAME_CASE(TAIL) 8429 NODE_NAME_CASE(MULHSU) 8430 NODE_NAME_CASE(SLLW) 8431 NODE_NAME_CASE(SRAW) 8432 NODE_NAME_CASE(SRLW) 8433 NODE_NAME_CASE(DIVW) 8434 NODE_NAME_CASE(DIVUW) 8435 NODE_NAME_CASE(REMUW) 8436 NODE_NAME_CASE(ROLW) 8437 NODE_NAME_CASE(RORW) 8438 NODE_NAME_CASE(CLZW) 8439 NODE_NAME_CASE(CTZW) 8440 NODE_NAME_CASE(FSLW) 8441 NODE_NAME_CASE(FSRW) 8442 NODE_NAME_CASE(FSL) 8443 NODE_NAME_CASE(FSR) 8444 NODE_NAME_CASE(FMV_H_X) 8445 NODE_NAME_CASE(FMV_X_ANYEXTH) 8446 NODE_NAME_CASE(FMV_W_X_RV64) 8447 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 8448 NODE_NAME_CASE(FCVT_X_RTZ) 8449 NODE_NAME_CASE(FCVT_XU_RTZ) 8450 NODE_NAME_CASE(FCVT_W_RTZ_RV64) 8451 NODE_NAME_CASE(FCVT_WU_RTZ_RV64) 8452 NODE_NAME_CASE(READ_CYCLE_WIDE) 8453 NODE_NAME_CASE(GREV) 8454 NODE_NAME_CASE(GREVW) 8455 NODE_NAME_CASE(GORC) 8456 NODE_NAME_CASE(GORCW) 8457 NODE_NAME_CASE(SHFL) 8458 NODE_NAME_CASE(SHFLW) 8459 NODE_NAME_CASE(UNSHFL) 8460 NODE_NAME_CASE(UNSHFLW) 8461 NODE_NAME_CASE(BCOMPRESS) 8462 NODE_NAME_CASE(BCOMPRESSW) 8463 NODE_NAME_CASE(BDECOMPRESS) 8464 NODE_NAME_CASE(BDECOMPRESSW) 8465 NODE_NAME_CASE(VMV_V_X_VL) 8466 NODE_NAME_CASE(VFMV_V_F_VL) 8467 NODE_NAME_CASE(VMV_X_S) 8468 NODE_NAME_CASE(VMV_S_X_VL) 8469 NODE_NAME_CASE(VFMV_S_F_VL) 8470 NODE_NAME_CASE(SPLAT_VECTOR_I64) 8471 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 8472 NODE_NAME_CASE(READ_VLENB) 8473 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 8474 NODE_NAME_CASE(VSLIDEUP_VL) 8475 NODE_NAME_CASE(VSLIDE1UP_VL) 8476 NODE_NAME_CASE(VSLIDEDOWN_VL) 8477 NODE_NAME_CASE(VSLIDE1DOWN_VL) 8478 NODE_NAME_CASE(VID_VL) 8479 NODE_NAME_CASE(VFNCVT_ROD_VL) 8480 NODE_NAME_CASE(VECREDUCE_ADD_VL) 8481 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 8482 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 8483 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 8484 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 8485 NODE_NAME_CASE(VECREDUCE_AND_VL) 8486 NODE_NAME_CASE(VECREDUCE_OR_VL) 8487 NODE_NAME_CASE(VECREDUCE_XOR_VL) 8488 NODE_NAME_CASE(VECREDUCE_FADD_VL) 8489 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 8490 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 8491 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 8492 NODE_NAME_CASE(ADD_VL) 8493 NODE_NAME_CASE(AND_VL) 8494 NODE_NAME_CASE(MUL_VL) 8495 NODE_NAME_CASE(OR_VL) 8496 NODE_NAME_CASE(SDIV_VL) 8497 NODE_NAME_CASE(SHL_VL) 8498 NODE_NAME_CASE(SREM_VL) 8499 NODE_NAME_CASE(SRA_VL) 8500 NODE_NAME_CASE(SRL_VL) 8501 NODE_NAME_CASE(SUB_VL) 8502 NODE_NAME_CASE(UDIV_VL) 8503 NODE_NAME_CASE(UREM_VL) 8504 NODE_NAME_CASE(XOR_VL) 8505 NODE_NAME_CASE(SADDSAT_VL) 8506 NODE_NAME_CASE(UADDSAT_VL) 8507 NODE_NAME_CASE(SSUBSAT_VL) 8508 NODE_NAME_CASE(USUBSAT_VL) 8509 NODE_NAME_CASE(FADD_VL) 8510 NODE_NAME_CASE(FSUB_VL) 8511 NODE_NAME_CASE(FMUL_VL) 8512 NODE_NAME_CASE(FDIV_VL) 8513 NODE_NAME_CASE(FNEG_VL) 8514 NODE_NAME_CASE(FABS_VL) 8515 NODE_NAME_CASE(FSQRT_VL) 8516 NODE_NAME_CASE(FMA_VL) 8517 NODE_NAME_CASE(FCOPYSIGN_VL) 8518 NODE_NAME_CASE(SMIN_VL) 8519 NODE_NAME_CASE(SMAX_VL) 8520 NODE_NAME_CASE(UMIN_VL) 8521 NODE_NAME_CASE(UMAX_VL) 8522 NODE_NAME_CASE(FMINNUM_VL) 8523 NODE_NAME_CASE(FMAXNUM_VL) 8524 NODE_NAME_CASE(MULHS_VL) 8525 NODE_NAME_CASE(MULHU_VL) 8526 NODE_NAME_CASE(FP_TO_SINT_VL) 8527 NODE_NAME_CASE(FP_TO_UINT_VL) 8528 NODE_NAME_CASE(SINT_TO_FP_VL) 8529 NODE_NAME_CASE(UINT_TO_FP_VL) 8530 NODE_NAME_CASE(FP_EXTEND_VL) 8531 NODE_NAME_CASE(FP_ROUND_VL) 8532 NODE_NAME_CASE(VWMUL_VL) 8533 NODE_NAME_CASE(VWMULU_VL) 8534 NODE_NAME_CASE(SETCC_VL) 8535 NODE_NAME_CASE(VSELECT_VL) 8536 NODE_NAME_CASE(VMAND_VL) 8537 NODE_NAME_CASE(VMOR_VL) 8538 NODE_NAME_CASE(VMXOR_VL) 8539 NODE_NAME_CASE(VMCLR_VL) 8540 NODE_NAME_CASE(VMSET_VL) 8541 NODE_NAME_CASE(VRGATHER_VX_VL) 8542 NODE_NAME_CASE(VRGATHER_VV_VL) 8543 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 8544 NODE_NAME_CASE(VSEXT_VL) 8545 NODE_NAME_CASE(VZEXT_VL) 8546 NODE_NAME_CASE(VPOPC_VL) 8547 NODE_NAME_CASE(VLE_VL) 8548 NODE_NAME_CASE(VSE_VL) 8549 NODE_NAME_CASE(READ_CSR) 8550 NODE_NAME_CASE(WRITE_CSR) 8551 NODE_NAME_CASE(SWAP_CSR) 8552 } 8553 // clang-format on 8554 return nullptr; 8555 #undef NODE_NAME_CASE 8556 } 8557 8558 /// getConstraintType - Given a constraint letter, return the type of 8559 /// constraint it is for this target. 8560 RISCVTargetLowering::ConstraintType 8561 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 8562 if (Constraint.size() == 1) { 8563 switch (Constraint[0]) { 8564 default: 8565 break; 8566 case 'f': 8567 return C_RegisterClass; 8568 case 'I': 8569 case 'J': 8570 case 'K': 8571 return C_Immediate; 8572 case 'A': 8573 return C_Memory; 8574 case 'S': // A symbolic address 8575 return C_Other; 8576 } 8577 } else { 8578 if (Constraint == "vr" || Constraint == "vm") 8579 return C_RegisterClass; 8580 } 8581 return TargetLowering::getConstraintType(Constraint); 8582 } 8583 8584 std::pair<unsigned, const TargetRegisterClass *> 8585 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 8586 StringRef Constraint, 8587 MVT VT) const { 8588 // First, see if this is a constraint that directly corresponds to a 8589 // RISCV register class. 8590 if (Constraint.size() == 1) { 8591 switch (Constraint[0]) { 8592 case 'r': 8593 return std::make_pair(0U, &RISCV::GPRRegClass); 8594 case 'f': 8595 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 8596 return std::make_pair(0U, &RISCV::FPR16RegClass); 8597 if (Subtarget.hasStdExtF() && VT == MVT::f32) 8598 return std::make_pair(0U, &RISCV::FPR32RegClass); 8599 if (Subtarget.hasStdExtD() && VT == MVT::f64) 8600 return std::make_pair(0U, &RISCV::FPR64RegClass); 8601 break; 8602 default: 8603 break; 8604 } 8605 } else { 8606 if (Constraint == "vr") { 8607 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 8608 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 8609 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 8610 return std::make_pair(0U, RC); 8611 } 8612 } else if (Constraint == "vm") { 8613 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 8614 return std::make_pair(0U, &RISCV::VMRegClass); 8615 } 8616 } 8617 8618 // Clang will correctly decode the usage of register name aliases into their 8619 // official names. However, other frontends like `rustc` do not. This allows 8620 // users of these frontends to use the ABI names for registers in LLVM-style 8621 // register constraints. 8622 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 8623 .Case("{zero}", RISCV::X0) 8624 .Case("{ra}", RISCV::X1) 8625 .Case("{sp}", RISCV::X2) 8626 .Case("{gp}", RISCV::X3) 8627 .Case("{tp}", RISCV::X4) 8628 .Case("{t0}", RISCV::X5) 8629 .Case("{t1}", RISCV::X6) 8630 .Case("{t2}", RISCV::X7) 8631 .Cases("{s0}", "{fp}", RISCV::X8) 8632 .Case("{s1}", RISCV::X9) 8633 .Case("{a0}", RISCV::X10) 8634 .Case("{a1}", RISCV::X11) 8635 .Case("{a2}", RISCV::X12) 8636 .Case("{a3}", RISCV::X13) 8637 .Case("{a4}", RISCV::X14) 8638 .Case("{a5}", RISCV::X15) 8639 .Case("{a6}", RISCV::X16) 8640 .Case("{a7}", RISCV::X17) 8641 .Case("{s2}", RISCV::X18) 8642 .Case("{s3}", RISCV::X19) 8643 .Case("{s4}", RISCV::X20) 8644 .Case("{s5}", RISCV::X21) 8645 .Case("{s6}", RISCV::X22) 8646 .Case("{s7}", RISCV::X23) 8647 .Case("{s8}", RISCV::X24) 8648 .Case("{s9}", RISCV::X25) 8649 .Case("{s10}", RISCV::X26) 8650 .Case("{s11}", RISCV::X27) 8651 .Case("{t3}", RISCV::X28) 8652 .Case("{t4}", RISCV::X29) 8653 .Case("{t5}", RISCV::X30) 8654 .Case("{t6}", RISCV::X31) 8655 .Default(RISCV::NoRegister); 8656 if (XRegFromAlias != RISCV::NoRegister) 8657 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 8658 8659 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 8660 // TableGen record rather than the AsmName to choose registers for InlineAsm 8661 // constraints, plus we want to match those names to the widest floating point 8662 // register type available, manually select floating point registers here. 8663 // 8664 // The second case is the ABI name of the register, so that frontends can also 8665 // use the ABI names in register constraint lists. 8666 if (Subtarget.hasStdExtF()) { 8667 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 8668 .Cases("{f0}", "{ft0}", RISCV::F0_F) 8669 .Cases("{f1}", "{ft1}", RISCV::F1_F) 8670 .Cases("{f2}", "{ft2}", RISCV::F2_F) 8671 .Cases("{f3}", "{ft3}", RISCV::F3_F) 8672 .Cases("{f4}", "{ft4}", RISCV::F4_F) 8673 .Cases("{f5}", "{ft5}", RISCV::F5_F) 8674 .Cases("{f6}", "{ft6}", RISCV::F6_F) 8675 .Cases("{f7}", "{ft7}", RISCV::F7_F) 8676 .Cases("{f8}", "{fs0}", RISCV::F8_F) 8677 .Cases("{f9}", "{fs1}", RISCV::F9_F) 8678 .Cases("{f10}", "{fa0}", RISCV::F10_F) 8679 .Cases("{f11}", "{fa1}", RISCV::F11_F) 8680 .Cases("{f12}", "{fa2}", RISCV::F12_F) 8681 .Cases("{f13}", "{fa3}", RISCV::F13_F) 8682 .Cases("{f14}", "{fa4}", RISCV::F14_F) 8683 .Cases("{f15}", "{fa5}", RISCV::F15_F) 8684 .Cases("{f16}", "{fa6}", RISCV::F16_F) 8685 .Cases("{f17}", "{fa7}", RISCV::F17_F) 8686 .Cases("{f18}", "{fs2}", RISCV::F18_F) 8687 .Cases("{f19}", "{fs3}", RISCV::F19_F) 8688 .Cases("{f20}", "{fs4}", RISCV::F20_F) 8689 .Cases("{f21}", "{fs5}", RISCV::F21_F) 8690 .Cases("{f22}", "{fs6}", RISCV::F22_F) 8691 .Cases("{f23}", "{fs7}", RISCV::F23_F) 8692 .Cases("{f24}", "{fs8}", RISCV::F24_F) 8693 .Cases("{f25}", "{fs9}", RISCV::F25_F) 8694 .Cases("{f26}", "{fs10}", RISCV::F26_F) 8695 .Cases("{f27}", "{fs11}", RISCV::F27_F) 8696 .Cases("{f28}", "{ft8}", RISCV::F28_F) 8697 .Cases("{f29}", "{ft9}", RISCV::F29_F) 8698 .Cases("{f30}", "{ft10}", RISCV::F30_F) 8699 .Cases("{f31}", "{ft11}", RISCV::F31_F) 8700 .Default(RISCV::NoRegister); 8701 if (FReg != RISCV::NoRegister) { 8702 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 8703 if (Subtarget.hasStdExtD()) { 8704 unsigned RegNo = FReg - RISCV::F0_F; 8705 unsigned DReg = RISCV::F0_D + RegNo; 8706 return std::make_pair(DReg, &RISCV::FPR64RegClass); 8707 } 8708 return std::make_pair(FReg, &RISCV::FPR32RegClass); 8709 } 8710 } 8711 8712 if (Subtarget.hasStdExtV()) { 8713 Register VReg = StringSwitch<Register>(Constraint.lower()) 8714 .Case("{v0}", RISCV::V0) 8715 .Case("{v1}", RISCV::V1) 8716 .Case("{v2}", RISCV::V2) 8717 .Case("{v3}", RISCV::V3) 8718 .Case("{v4}", RISCV::V4) 8719 .Case("{v5}", RISCV::V5) 8720 .Case("{v6}", RISCV::V6) 8721 .Case("{v7}", RISCV::V7) 8722 .Case("{v8}", RISCV::V8) 8723 .Case("{v9}", RISCV::V9) 8724 .Case("{v10}", RISCV::V10) 8725 .Case("{v11}", RISCV::V11) 8726 .Case("{v12}", RISCV::V12) 8727 .Case("{v13}", RISCV::V13) 8728 .Case("{v14}", RISCV::V14) 8729 .Case("{v15}", RISCV::V15) 8730 .Case("{v16}", RISCV::V16) 8731 .Case("{v17}", RISCV::V17) 8732 .Case("{v18}", RISCV::V18) 8733 .Case("{v19}", RISCV::V19) 8734 .Case("{v20}", RISCV::V20) 8735 .Case("{v21}", RISCV::V21) 8736 .Case("{v22}", RISCV::V22) 8737 .Case("{v23}", RISCV::V23) 8738 .Case("{v24}", RISCV::V24) 8739 .Case("{v25}", RISCV::V25) 8740 .Case("{v26}", RISCV::V26) 8741 .Case("{v27}", RISCV::V27) 8742 .Case("{v28}", RISCV::V28) 8743 .Case("{v29}", RISCV::V29) 8744 .Case("{v30}", RISCV::V30) 8745 .Case("{v31}", RISCV::V31) 8746 .Default(RISCV::NoRegister); 8747 if (VReg != RISCV::NoRegister) { 8748 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 8749 return std::make_pair(VReg, &RISCV::VMRegClass); 8750 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 8751 return std::make_pair(VReg, &RISCV::VRRegClass); 8752 for (const auto *RC : 8753 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 8754 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 8755 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 8756 return std::make_pair(VReg, RC); 8757 } 8758 } 8759 } 8760 } 8761 8762 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 8763 } 8764 8765 unsigned 8766 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 8767 // Currently only support length 1 constraints. 8768 if (ConstraintCode.size() == 1) { 8769 switch (ConstraintCode[0]) { 8770 case 'A': 8771 return InlineAsm::Constraint_A; 8772 default: 8773 break; 8774 } 8775 } 8776 8777 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 8778 } 8779 8780 void RISCVTargetLowering::LowerAsmOperandForConstraint( 8781 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 8782 SelectionDAG &DAG) const { 8783 // Currently only support length 1 constraints. 8784 if (Constraint.length() == 1) { 8785 switch (Constraint[0]) { 8786 case 'I': 8787 // Validate & create a 12-bit signed immediate operand. 8788 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 8789 uint64_t CVal = C->getSExtValue(); 8790 if (isInt<12>(CVal)) 8791 Ops.push_back( 8792 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 8793 } 8794 return; 8795 case 'J': 8796 // Validate & create an integer zero operand. 8797 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 8798 if (C->getZExtValue() == 0) 8799 Ops.push_back( 8800 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 8801 return; 8802 case 'K': 8803 // Validate & create a 5-bit unsigned immediate operand. 8804 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 8805 uint64_t CVal = C->getZExtValue(); 8806 if (isUInt<5>(CVal)) 8807 Ops.push_back( 8808 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 8809 } 8810 return; 8811 case 'S': 8812 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 8813 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 8814 GA->getValueType(0))); 8815 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 8816 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 8817 BA->getValueType(0))); 8818 } 8819 return; 8820 default: 8821 break; 8822 } 8823 } 8824 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 8825 } 8826 8827 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 8828 Instruction *Inst, 8829 AtomicOrdering Ord) const { 8830 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 8831 return Builder.CreateFence(Ord); 8832 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 8833 return Builder.CreateFence(AtomicOrdering::Release); 8834 return nullptr; 8835 } 8836 8837 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 8838 Instruction *Inst, 8839 AtomicOrdering Ord) const { 8840 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 8841 return Builder.CreateFence(AtomicOrdering::Acquire); 8842 return nullptr; 8843 } 8844 8845 TargetLowering::AtomicExpansionKind 8846 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 8847 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 8848 // point operations can't be used in an lr/sc sequence without breaking the 8849 // forward-progress guarantee. 8850 if (AI->isFloatingPointOperation()) 8851 return AtomicExpansionKind::CmpXChg; 8852 8853 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 8854 if (Size == 8 || Size == 16) 8855 return AtomicExpansionKind::MaskedIntrinsic; 8856 return AtomicExpansionKind::None; 8857 } 8858 8859 static Intrinsic::ID 8860 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 8861 if (XLen == 32) { 8862 switch (BinOp) { 8863 default: 8864 llvm_unreachable("Unexpected AtomicRMW BinOp"); 8865 case AtomicRMWInst::Xchg: 8866 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 8867 case AtomicRMWInst::Add: 8868 return Intrinsic::riscv_masked_atomicrmw_add_i32; 8869 case AtomicRMWInst::Sub: 8870 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 8871 case AtomicRMWInst::Nand: 8872 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 8873 case AtomicRMWInst::Max: 8874 return Intrinsic::riscv_masked_atomicrmw_max_i32; 8875 case AtomicRMWInst::Min: 8876 return Intrinsic::riscv_masked_atomicrmw_min_i32; 8877 case AtomicRMWInst::UMax: 8878 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 8879 case AtomicRMWInst::UMin: 8880 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 8881 } 8882 } 8883 8884 if (XLen == 64) { 8885 switch (BinOp) { 8886 default: 8887 llvm_unreachable("Unexpected AtomicRMW BinOp"); 8888 case AtomicRMWInst::Xchg: 8889 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 8890 case AtomicRMWInst::Add: 8891 return Intrinsic::riscv_masked_atomicrmw_add_i64; 8892 case AtomicRMWInst::Sub: 8893 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 8894 case AtomicRMWInst::Nand: 8895 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 8896 case AtomicRMWInst::Max: 8897 return Intrinsic::riscv_masked_atomicrmw_max_i64; 8898 case AtomicRMWInst::Min: 8899 return Intrinsic::riscv_masked_atomicrmw_min_i64; 8900 case AtomicRMWInst::UMax: 8901 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 8902 case AtomicRMWInst::UMin: 8903 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 8904 } 8905 } 8906 8907 llvm_unreachable("Unexpected XLen\n"); 8908 } 8909 8910 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 8911 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 8912 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 8913 unsigned XLen = Subtarget.getXLen(); 8914 Value *Ordering = 8915 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 8916 Type *Tys[] = {AlignedAddr->getType()}; 8917 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 8918 AI->getModule(), 8919 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 8920 8921 if (XLen == 64) { 8922 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 8923 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 8924 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 8925 } 8926 8927 Value *Result; 8928 8929 // Must pass the shift amount needed to sign extend the loaded value prior 8930 // to performing a signed comparison for min/max. ShiftAmt is the number of 8931 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 8932 // is the number of bits to left+right shift the value in order to 8933 // sign-extend. 8934 if (AI->getOperation() == AtomicRMWInst::Min || 8935 AI->getOperation() == AtomicRMWInst::Max) { 8936 const DataLayout &DL = AI->getModule()->getDataLayout(); 8937 unsigned ValWidth = 8938 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 8939 Value *SextShamt = 8940 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 8941 Result = Builder.CreateCall(LrwOpScwLoop, 8942 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 8943 } else { 8944 Result = 8945 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 8946 } 8947 8948 if (XLen == 64) 8949 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 8950 return Result; 8951 } 8952 8953 TargetLowering::AtomicExpansionKind 8954 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 8955 AtomicCmpXchgInst *CI) const { 8956 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 8957 if (Size == 8 || Size == 16) 8958 return AtomicExpansionKind::MaskedIntrinsic; 8959 return AtomicExpansionKind::None; 8960 } 8961 8962 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 8963 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 8964 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 8965 unsigned XLen = Subtarget.getXLen(); 8966 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 8967 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 8968 if (XLen == 64) { 8969 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 8970 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 8971 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 8972 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 8973 } 8974 Type *Tys[] = {AlignedAddr->getType()}; 8975 Function *MaskedCmpXchg = 8976 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 8977 Value *Result = Builder.CreateCall( 8978 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 8979 if (XLen == 64) 8980 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 8981 return Result; 8982 } 8983 8984 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 8985 return false; 8986 } 8987 8988 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 8989 EVT VT) const { 8990 VT = VT.getScalarType(); 8991 8992 if (!VT.isSimple()) 8993 return false; 8994 8995 switch (VT.getSimpleVT().SimpleTy) { 8996 case MVT::f16: 8997 return Subtarget.hasStdExtZfh(); 8998 case MVT::f32: 8999 return Subtarget.hasStdExtF(); 9000 case MVT::f64: 9001 return Subtarget.hasStdExtD(); 9002 default: 9003 break; 9004 } 9005 9006 return false; 9007 } 9008 9009 Register RISCVTargetLowering::getExceptionPointerRegister( 9010 const Constant *PersonalityFn) const { 9011 return RISCV::X10; 9012 } 9013 9014 Register RISCVTargetLowering::getExceptionSelectorRegister( 9015 const Constant *PersonalityFn) const { 9016 return RISCV::X11; 9017 } 9018 9019 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 9020 // Return false to suppress the unnecessary extensions if the LibCall 9021 // arguments or return value is f32 type for LP64 ABI. 9022 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 9023 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 9024 return false; 9025 9026 return true; 9027 } 9028 9029 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 9030 if (Subtarget.is64Bit() && Type == MVT::i32) 9031 return true; 9032 9033 return IsSigned; 9034 } 9035 9036 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 9037 SDValue C) const { 9038 // Check integral scalar types. 9039 if (VT.isScalarInteger()) { 9040 // Omit the optimization if the sub target has the M extension and the data 9041 // size exceeds XLen. 9042 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 9043 return false; 9044 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 9045 // Break the MUL to a SLLI and an ADD/SUB. 9046 const APInt &Imm = ConstNode->getAPIntValue(); 9047 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 9048 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 9049 return true; 9050 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 9051 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 9052 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 9053 (Imm - 8).isPowerOf2())) 9054 return true; 9055 // Omit the following optimization if the sub target has the M extension 9056 // and the data size >= XLen. 9057 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 9058 return false; 9059 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 9060 // a pair of LUI/ADDI. 9061 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 9062 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 9063 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 9064 (1 - ImmS).isPowerOf2()) 9065 return true; 9066 } 9067 } 9068 } 9069 9070 return false; 9071 } 9072 9073 bool RISCVTargetLowering::isMulAddWithConstProfitable( 9074 const SDValue &AddNode, const SDValue &ConstNode) const { 9075 // Let the DAGCombiner decide for vectors. 9076 EVT VT = AddNode.getValueType(); 9077 if (VT.isVector()) 9078 return true; 9079 9080 // Let the DAGCombiner decide for larger types. 9081 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 9082 return true; 9083 9084 // It is worse if c1 is simm12 while c1*c2 is not. 9085 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 9086 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 9087 const APInt &C1 = C1Node->getAPIntValue(); 9088 const APInt &C2 = C2Node->getAPIntValue(); 9089 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 9090 return false; 9091 9092 // Default to true and let the DAGCombiner decide. 9093 return true; 9094 } 9095 9096 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 9097 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 9098 bool *Fast) const { 9099 if (!VT.isVector()) 9100 return false; 9101 9102 EVT ElemVT = VT.getVectorElementType(); 9103 if (Alignment >= ElemVT.getStoreSize()) { 9104 if (Fast) 9105 *Fast = true; 9106 return true; 9107 } 9108 9109 return false; 9110 } 9111 9112 bool RISCVTargetLowering::splitValueIntoRegisterParts( 9113 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 9114 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 9115 bool IsABIRegCopy = CC.hasValue(); 9116 EVT ValueVT = Val.getValueType(); 9117 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 9118 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 9119 // and cast to f32. 9120 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 9121 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 9122 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 9123 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 9124 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 9125 Parts[0] = Val; 9126 return true; 9127 } 9128 9129 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 9130 LLVMContext &Context = *DAG.getContext(); 9131 EVT ValueEltVT = ValueVT.getVectorElementType(); 9132 EVT PartEltVT = PartVT.getVectorElementType(); 9133 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 9134 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 9135 if (PartVTBitSize % ValueVTBitSize == 0) { 9136 // If the element types are different, bitcast to the same element type of 9137 // PartVT first. 9138 if (ValueEltVT != PartEltVT) { 9139 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 9140 assert(Count != 0 && "The number of element should not be zero."); 9141 EVT SameEltTypeVT = 9142 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 9143 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 9144 } 9145 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 9146 Val, DAG.getConstant(0, DL, Subtarget.getXLenVT())); 9147 Parts[0] = Val; 9148 return true; 9149 } 9150 } 9151 return false; 9152 } 9153 9154 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 9155 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 9156 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 9157 bool IsABIRegCopy = CC.hasValue(); 9158 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 9159 SDValue Val = Parts[0]; 9160 9161 // Cast the f32 to i32, truncate to i16, and cast back to f16. 9162 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 9163 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 9164 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 9165 return Val; 9166 } 9167 9168 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 9169 LLVMContext &Context = *DAG.getContext(); 9170 SDValue Val = Parts[0]; 9171 EVT ValueEltVT = ValueVT.getVectorElementType(); 9172 EVT PartEltVT = PartVT.getVectorElementType(); 9173 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 9174 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 9175 if (PartVTBitSize % ValueVTBitSize == 0) { 9176 EVT SameEltTypeVT = ValueVT; 9177 // If the element types are different, convert it to the same element type 9178 // of PartVT. 9179 if (ValueEltVT != PartEltVT) { 9180 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 9181 assert(Count != 0 && "The number of element should not be zero."); 9182 SameEltTypeVT = 9183 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 9184 } 9185 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val, 9186 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 9187 if (ValueEltVT != PartEltVT) 9188 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 9189 return Val; 9190 } 9191 } 9192 return SDValue(); 9193 } 9194 9195 #define GET_REGISTER_MATCHER 9196 #include "RISCVGenAsmMatcher.inc" 9197 9198 Register 9199 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 9200 const MachineFunction &MF) const { 9201 Register Reg = MatchRegisterAltName(RegName); 9202 if (Reg == RISCV::NoRegister) 9203 Reg = MatchRegisterName(RegName); 9204 if (Reg == RISCV::NoRegister) 9205 report_fatal_error( 9206 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 9207 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 9208 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 9209 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 9210 StringRef(RegName) + "\".")); 9211 return Reg; 9212 } 9213 9214 namespace llvm { 9215 namespace RISCVVIntrinsicsTable { 9216 9217 #define GET_RISCVVIntrinsicsTable_IMPL 9218 #include "RISCVGenSearchableTables.inc" 9219 9220 } // namespace RISCVVIntrinsicsTable 9221 9222 } // namespace llvm 9223