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