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