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