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