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