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