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/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 116 assert(Size <= 512 && isPowerOf2_32(Size)); 117 const TargetRegisterClass *RC; 118 if (Size <= 64) 119 RC = &RISCV::VRRegClass; 120 else if (Size == 128) 121 RC = &RISCV::VRM2RegClass; 122 else if (Size == 256) 123 RC = &RISCV::VRM4RegClass; 124 else 125 RC = &RISCV::VRM8RegClass; 126 127 addRegisterClass(VT, RC); 128 }; 129 130 for (MVT VT : BoolVecVTs) 131 addRegClassForRVV(VT); 132 for (MVT VT : IntVecVTs) { 133 if (VT.getVectorElementType() == MVT::i64 && 134 !Subtarget.hasVInstructionsI64()) 135 continue; 136 addRegClassForRVV(VT); 137 } 138 139 if (Subtarget.hasVInstructionsF16()) 140 for (MVT VT : F16VecVTs) 141 addRegClassForRVV(VT); 142 143 if (Subtarget.hasVInstructionsF32()) 144 for (MVT VT : F32VecVTs) 145 addRegClassForRVV(VT); 146 147 if (Subtarget.hasVInstructionsF64()) 148 for (MVT VT : F64VecVTs) 149 addRegClassForRVV(VT); 150 151 if (Subtarget.useRVVForFixedLengthVectors()) { 152 auto addRegClassForFixedVectors = [this](MVT VT) { 153 MVT ContainerVT = getContainerForFixedLengthVector(VT); 154 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 155 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 156 addRegisterClass(VT, TRI.getRegClass(RCID)); 157 }; 158 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 159 if (useRVVForFixedLengthVectorVT(VT)) 160 addRegClassForFixedVectors(VT); 161 162 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 163 if (useRVVForFixedLengthVectorVT(VT)) 164 addRegClassForFixedVectors(VT); 165 } 166 } 167 168 // Compute derived properties from the register classes. 169 computeRegisterProperties(STI.getRegisterInfo()); 170 171 setStackPointerRegisterToSaveRestore(RISCV::X2); 172 173 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 174 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 175 176 // TODO: add all necessary setOperationAction calls. 177 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 178 179 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 180 setOperationAction(ISD::BR_CC, XLenVT, Expand); 181 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 182 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 183 184 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 185 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 186 187 setOperationAction(ISD::VASTART, MVT::Other, Custom); 188 setOperationAction(ISD::VAARG, MVT::Other, Expand); 189 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 190 setOperationAction(ISD::VAEND, MVT::Other, Expand); 191 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 193 if (!Subtarget.hasStdExtZbb()) { 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 196 } 197 198 if (Subtarget.is64Bit()) { 199 setOperationAction(ISD::ADD, MVT::i32, Custom); 200 setOperationAction(ISD::SUB, MVT::i32, Custom); 201 setOperationAction(ISD::SHL, MVT::i32, Custom); 202 setOperationAction(ISD::SRA, MVT::i32, Custom); 203 setOperationAction(ISD::SRL, MVT::i32, Custom); 204 205 setOperationAction(ISD::UADDO, MVT::i32, Custom); 206 setOperationAction(ISD::USUBO, MVT::i32, Custom); 207 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 208 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 209 } else { 210 setLibcallName(RTLIB::SHL_I128, nullptr); 211 setLibcallName(RTLIB::SRL_I128, nullptr); 212 setLibcallName(RTLIB::SRA_I128, nullptr); 213 setLibcallName(RTLIB::MUL_I128, nullptr); 214 setLibcallName(RTLIB::MULO_I64, nullptr); 215 } 216 217 if (!Subtarget.hasStdExtM()) { 218 setOperationAction(ISD::MUL, XLenVT, Expand); 219 setOperationAction(ISD::MULHS, XLenVT, Expand); 220 setOperationAction(ISD::MULHU, XLenVT, Expand); 221 setOperationAction(ISD::SDIV, XLenVT, Expand); 222 setOperationAction(ISD::UDIV, XLenVT, Expand); 223 setOperationAction(ISD::SREM, XLenVT, Expand); 224 setOperationAction(ISD::UREM, XLenVT, Expand); 225 } else { 226 if (Subtarget.is64Bit()) { 227 setOperationAction(ISD::MUL, MVT::i32, Custom); 228 setOperationAction(ISD::MUL, MVT::i128, Custom); 229 230 setOperationAction(ISD::SDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UDIV, MVT::i8, Custom); 232 setOperationAction(ISD::UREM, MVT::i8, Custom); 233 setOperationAction(ISD::SDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UDIV, MVT::i16, Custom); 235 setOperationAction(ISD::UREM, MVT::i16, Custom); 236 setOperationAction(ISD::SDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UDIV, MVT::i32, Custom); 238 setOperationAction(ISD::UREM, MVT::i32, Custom); 239 } else { 240 setOperationAction(ISD::MUL, MVT::i64, Custom); 241 } 242 } 243 244 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 246 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 247 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 248 249 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 251 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 252 253 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 254 Subtarget.hasStdExtZbkb()) { 255 if (Subtarget.is64Bit()) { 256 setOperationAction(ISD::ROTL, MVT::i32, Custom); 257 setOperationAction(ISD::ROTR, MVT::i32, Custom); 258 } 259 } else { 260 setOperationAction(ISD::ROTL, XLenVT, Expand); 261 setOperationAction(ISD::ROTR, XLenVT, Expand); 262 } 263 264 if (Subtarget.hasStdExtZbp()) { 265 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 266 // more combining. 267 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 268 setOperationAction(ISD::BSWAP, XLenVT, Custom); 269 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 270 // BSWAP i8 doesn't exist. 271 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 272 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 273 274 if (Subtarget.is64Bit()) { 275 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 276 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 277 } 278 } else { 279 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 280 // pattern match it directly in isel. 281 setOperationAction(ISD::BSWAP, XLenVT, 282 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 283 ? Legal 284 : Expand); 285 // Zbkb can use rev8+brev8 to implement bitreverse. 286 setOperationAction(ISD::BITREVERSE, XLenVT, 287 Subtarget.hasStdExtZbkb() ? Custom : Expand); 288 } 289 290 if (Subtarget.hasStdExtZbb()) { 291 setOperationAction(ISD::SMIN, XLenVT, Legal); 292 setOperationAction(ISD::SMAX, XLenVT, Legal); 293 setOperationAction(ISD::UMIN, XLenVT, Legal); 294 setOperationAction(ISD::UMAX, XLenVT, Legal); 295 296 if (Subtarget.is64Bit()) { 297 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 298 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 299 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 300 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 301 } 302 } else { 303 setOperationAction(ISD::CTTZ, XLenVT, Expand); 304 setOperationAction(ISD::CTLZ, XLenVT, Expand); 305 setOperationAction(ISD::CTPOP, XLenVT, Expand); 306 } 307 308 if (Subtarget.hasStdExtZbt()) { 309 setOperationAction(ISD::FSHL, XLenVT, Custom); 310 setOperationAction(ISD::FSHR, XLenVT, Custom); 311 setOperationAction(ISD::SELECT, XLenVT, Legal); 312 313 if (Subtarget.is64Bit()) { 314 setOperationAction(ISD::FSHL, MVT::i32, Custom); 315 setOperationAction(ISD::FSHR, MVT::i32, Custom); 316 } 317 } else { 318 setOperationAction(ISD::SELECT, XLenVT, Custom); 319 } 320 321 static const ISD::CondCode FPCCToExpand[] = { 322 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 323 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 324 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 325 326 static const ISD::NodeType FPOpToExpand[] = { 327 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 328 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 329 330 if (Subtarget.hasStdExtZfh()) 331 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 332 333 if (Subtarget.hasStdExtZfh()) { 334 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 335 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 336 setOperationAction(ISD::LRINT, MVT::f16, Legal); 337 setOperationAction(ISD::LLRINT, MVT::f16, Legal); 338 setOperationAction(ISD::LROUND, MVT::f16, Legal); 339 setOperationAction(ISD::LLROUND, MVT::f16, Legal); 340 setOperationAction(ISD::STRICT_LRINT, MVT::f16, Legal); 341 setOperationAction(ISD::STRICT_LLRINT, MVT::f16, Legal); 342 setOperationAction(ISD::STRICT_LROUND, MVT::f16, Legal); 343 setOperationAction(ISD::STRICT_LLROUND, MVT::f16, Legal); 344 setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal); 345 setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal); 346 setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal); 347 setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal); 348 setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal); 349 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 350 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 351 setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal); 352 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Legal); 353 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Legal); 354 for (auto CC : FPCCToExpand) 355 setCondCodeAction(CC, MVT::f16, Expand); 356 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 357 setOperationAction(ISD::SELECT, MVT::f16, Custom); 358 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 359 360 setOperationAction(ISD::FREM, MVT::f16, Promote); 361 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 362 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 363 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 364 setOperationAction(ISD::FRINT, MVT::f16, Promote); 365 setOperationAction(ISD::FROUND, MVT::f16, Promote); 366 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 367 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 368 setOperationAction(ISD::FPOW, MVT::f16, Promote); 369 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 370 setOperationAction(ISD::FCOS, MVT::f16, Promote); 371 setOperationAction(ISD::FSIN, MVT::f16, Promote); 372 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 373 setOperationAction(ISD::FEXP, MVT::f16, Promote); 374 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 375 setOperationAction(ISD::FLOG, MVT::f16, Promote); 376 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 377 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 378 379 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 380 // complete support for all operations in LegalizeDAG. 381 382 // We need to custom promote this. 383 if (Subtarget.is64Bit()) 384 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 385 } 386 387 if (Subtarget.hasStdExtF()) { 388 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 389 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 390 setOperationAction(ISD::LRINT, MVT::f32, Legal); 391 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 392 setOperationAction(ISD::LROUND, MVT::f32, Legal); 393 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 394 setOperationAction(ISD::STRICT_LRINT, MVT::f32, Legal); 395 setOperationAction(ISD::STRICT_LLRINT, MVT::f32, Legal); 396 setOperationAction(ISD::STRICT_LROUND, MVT::f32, Legal); 397 setOperationAction(ISD::STRICT_LLROUND, MVT::f32, Legal); 398 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 399 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 400 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 401 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 402 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 403 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 404 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 405 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 406 for (auto CC : FPCCToExpand) 407 setCondCodeAction(CC, MVT::f32, Expand); 408 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 409 setOperationAction(ISD::SELECT, MVT::f32, Custom); 410 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 411 for (auto Op : FPOpToExpand) 412 setOperationAction(Op, MVT::f32, Expand); 413 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 414 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 415 } 416 417 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 418 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 419 420 if (Subtarget.hasStdExtD()) { 421 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 422 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 423 setOperationAction(ISD::LRINT, MVT::f64, Legal); 424 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 425 setOperationAction(ISD::LROUND, MVT::f64, Legal); 426 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 427 setOperationAction(ISD::STRICT_LRINT, MVT::f64, Legal); 428 setOperationAction(ISD::STRICT_LLRINT, MVT::f64, Legal); 429 setOperationAction(ISD::STRICT_LROUND, MVT::f64, Legal); 430 setOperationAction(ISD::STRICT_LLROUND, MVT::f64, Legal); 431 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 432 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 433 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 434 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 435 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 436 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 437 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 438 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 439 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 440 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 441 for (auto CC : FPCCToExpand) 442 setCondCodeAction(CC, MVT::f64, Expand); 443 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 444 setOperationAction(ISD::SELECT, MVT::f64, Custom); 445 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 446 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 447 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 448 for (auto Op : FPOpToExpand) 449 setOperationAction(Op, MVT::f64, Expand); 450 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 451 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 452 } 453 454 if (Subtarget.is64Bit()) { 455 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 456 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 457 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 458 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 459 } 460 461 if (Subtarget.hasStdExtF()) { 462 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 463 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 464 465 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 466 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 467 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 468 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 469 470 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 471 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 472 } 473 474 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 475 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 476 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 477 setOperationAction(ISD::JumpTable, XLenVT, Custom); 478 479 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 480 481 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 482 // Unfortunately this can't be determined just from the ISA naming string. 483 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 484 Subtarget.is64Bit() ? Legal : Custom); 485 486 setOperationAction(ISD::TRAP, MVT::Other, Legal); 487 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 488 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 489 if (Subtarget.is64Bit()) 490 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 491 492 if (Subtarget.hasStdExtA()) { 493 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 494 setMinCmpXchgSizeInBits(32); 495 } else { 496 setMaxAtomicSizeInBitsSupported(0); 497 } 498 499 setBooleanContents(ZeroOrOneBooleanContent); 500 501 if (Subtarget.hasVInstructions()) { 502 setBooleanVectorContents(ZeroOrOneBooleanContent); 503 504 setOperationAction(ISD::VSCALE, XLenVT, Custom); 505 506 // RVV intrinsics may have illegal operands. 507 // We also need to custom legalize vmv.x.s. 508 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 509 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 510 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 511 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 512 if (Subtarget.is64Bit()) { 513 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 514 } else { 515 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 516 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 517 } 518 519 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 520 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 521 522 static const unsigned IntegerVPOps[] = { 523 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 524 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 525 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 526 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 527 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 528 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 529 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 530 ISD::VP_MERGE, ISD::VP_SELECT}; 531 532 static const unsigned FloatingPointVPOps[] = { 533 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 534 ISD::VP_FDIV, ISD::VP_FNEG, ISD::VP_FMA, 535 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN, 536 ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, ISD::VP_SELECT}; 537 538 if (!Subtarget.is64Bit()) { 539 // We must custom-lower certain vXi64 operations on RV32 due to the vector 540 // element type being illegal. 541 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 542 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 543 544 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 545 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 546 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 547 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 548 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 549 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 550 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 551 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 552 553 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 554 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 555 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 556 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 557 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 558 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 559 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 560 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 561 } 562 563 for (MVT VT : BoolVecVTs) { 564 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 565 566 // Mask VTs are custom-expanded into a series of standard nodes 567 setOperationAction(ISD::TRUNCATE, VT, Custom); 568 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 569 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 570 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 571 572 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 573 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 574 575 setOperationAction(ISD::SELECT, VT, Custom); 576 setOperationAction(ISD::SELECT_CC, VT, Expand); 577 setOperationAction(ISD::VSELECT, VT, Expand); 578 setOperationAction(ISD::VP_MERGE, VT, Expand); 579 setOperationAction(ISD::VP_SELECT, VT, Expand); 580 581 setOperationAction(ISD::VP_AND, VT, Custom); 582 setOperationAction(ISD::VP_OR, VT, Custom); 583 setOperationAction(ISD::VP_XOR, VT, Custom); 584 585 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 586 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 587 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 588 589 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 590 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 591 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 592 593 // RVV has native int->float & float->int conversions where the 594 // element type sizes are within one power-of-two of each other. Any 595 // wider distances between type sizes have to be lowered as sequences 596 // which progressively narrow the gap in stages. 597 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 598 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 599 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 600 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 601 602 // Expand all extending loads to types larger than this, and truncating 603 // stores from types larger than this. 604 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 605 setTruncStoreAction(OtherVT, VT, Expand); 606 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 607 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 608 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 609 } 610 } 611 612 for (MVT VT : IntVecVTs) { 613 if (VT.getVectorElementType() == MVT::i64 && 614 !Subtarget.hasVInstructionsI64()) 615 continue; 616 617 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 618 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 619 620 // Vectors implement MULHS/MULHU. 621 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 622 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 623 624 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 625 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 626 setOperationAction(ISD::MULHU, VT, Expand); 627 setOperationAction(ISD::MULHS, VT, Expand); 628 } 629 630 setOperationAction(ISD::SMIN, VT, Legal); 631 setOperationAction(ISD::SMAX, VT, Legal); 632 setOperationAction(ISD::UMIN, VT, Legal); 633 setOperationAction(ISD::UMAX, VT, Legal); 634 635 setOperationAction(ISD::ROTL, VT, Expand); 636 setOperationAction(ISD::ROTR, VT, Expand); 637 638 setOperationAction(ISD::CTTZ, VT, Expand); 639 setOperationAction(ISD::CTLZ, VT, Expand); 640 setOperationAction(ISD::CTPOP, VT, Expand); 641 642 setOperationAction(ISD::BSWAP, VT, Expand); 643 644 // Custom-lower extensions and truncations from/to mask types. 645 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 646 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 647 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 648 649 // RVV has native int->float & float->int conversions where the 650 // element type sizes are within one power-of-two of each other. Any 651 // wider distances between type sizes have to be lowered as sequences 652 // which progressively narrow the gap in stages. 653 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 654 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 655 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 656 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 657 658 setOperationAction(ISD::SADDSAT, VT, Legal); 659 setOperationAction(ISD::UADDSAT, VT, Legal); 660 setOperationAction(ISD::SSUBSAT, VT, Legal); 661 setOperationAction(ISD::USUBSAT, VT, Legal); 662 663 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 664 // nodes which truncate by one power of two at a time. 665 setOperationAction(ISD::TRUNCATE, VT, Custom); 666 667 // Custom-lower insert/extract operations to simplify patterns. 668 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 669 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 670 671 // Custom-lower reduction operations to set up the corresponding custom 672 // nodes' operands. 673 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 674 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 675 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 676 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 677 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 678 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 679 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 680 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 681 682 for (unsigned VPOpc : IntegerVPOps) 683 setOperationAction(VPOpc, VT, Custom); 684 685 setOperationAction(ISD::LOAD, VT, Custom); 686 setOperationAction(ISD::STORE, VT, Custom); 687 688 setOperationAction(ISD::MLOAD, VT, Custom); 689 setOperationAction(ISD::MSTORE, VT, Custom); 690 setOperationAction(ISD::MGATHER, VT, Custom); 691 setOperationAction(ISD::MSCATTER, VT, Custom); 692 693 setOperationAction(ISD::VP_LOAD, VT, Custom); 694 setOperationAction(ISD::VP_STORE, VT, Custom); 695 setOperationAction(ISD::VP_GATHER, VT, Custom); 696 setOperationAction(ISD::VP_SCATTER, VT, Custom); 697 698 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 699 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 700 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 701 702 setOperationAction(ISD::SELECT, VT, Custom); 703 setOperationAction(ISD::SELECT_CC, VT, Expand); 704 705 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 706 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 707 708 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 709 setTruncStoreAction(VT, OtherVT, Expand); 710 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 711 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 712 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 713 } 714 715 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 716 // type that can represent the value exactly. 717 if (VT.getVectorElementType() != MVT::i64) { 718 MVT FloatEltVT = 719 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 720 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 721 if (isTypeLegal(FloatVT)) { 722 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 723 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 724 } 725 } 726 } 727 728 // Expand various CCs to best match the RVV ISA, which natively supports UNE 729 // but no other unordered comparisons, and supports all ordered comparisons 730 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 731 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 732 // and we pattern-match those back to the "original", swapping operands once 733 // more. This way we catch both operations and both "vf" and "fv" forms with 734 // fewer patterns. 735 static const ISD::CondCode VFPCCToExpand[] = { 736 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 737 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 738 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 739 }; 740 741 // Sets common operation actions on RVV floating-point vector types. 742 const auto SetCommonVFPActions = [&](MVT VT) { 743 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 744 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 745 // sizes are within one power-of-two of each other. Therefore conversions 746 // between vXf16 and vXf64 must be lowered as sequences which convert via 747 // vXf32. 748 setOperationAction(ISD::FP_ROUND, VT, Custom); 749 setOperationAction(ISD::FP_EXTEND, VT, Custom); 750 // Custom-lower insert/extract operations to simplify patterns. 751 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 752 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 753 // Expand various condition codes (explained above). 754 for (auto CC : VFPCCToExpand) 755 setCondCodeAction(CC, VT, Expand); 756 757 setOperationAction(ISD::FMINNUM, VT, Legal); 758 setOperationAction(ISD::FMAXNUM, VT, Legal); 759 760 setOperationAction(ISD::FTRUNC, VT, Custom); 761 setOperationAction(ISD::FCEIL, VT, Custom); 762 setOperationAction(ISD::FFLOOR, VT, Custom); 763 setOperationAction(ISD::FROUND, VT, Custom); 764 765 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 766 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 767 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 768 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 769 770 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 771 772 setOperationAction(ISD::LOAD, VT, Custom); 773 setOperationAction(ISD::STORE, VT, Custom); 774 775 setOperationAction(ISD::MLOAD, VT, Custom); 776 setOperationAction(ISD::MSTORE, VT, Custom); 777 setOperationAction(ISD::MGATHER, VT, Custom); 778 setOperationAction(ISD::MSCATTER, VT, Custom); 779 780 setOperationAction(ISD::VP_LOAD, VT, Custom); 781 setOperationAction(ISD::VP_STORE, VT, Custom); 782 setOperationAction(ISD::VP_GATHER, VT, Custom); 783 setOperationAction(ISD::VP_SCATTER, VT, Custom); 784 785 setOperationAction(ISD::SELECT, VT, Custom); 786 setOperationAction(ISD::SELECT_CC, VT, Expand); 787 788 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 789 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 790 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 791 792 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 793 794 for (unsigned VPOpc : FloatingPointVPOps) 795 setOperationAction(VPOpc, VT, Custom); 796 }; 797 798 // Sets common extload/truncstore actions on RVV floating-point vector 799 // types. 800 const auto SetCommonVFPExtLoadTruncStoreActions = 801 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 802 for (auto SmallVT : SmallerVTs) { 803 setTruncStoreAction(VT, SmallVT, Expand); 804 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 805 } 806 }; 807 808 if (Subtarget.hasVInstructionsF16()) 809 for (MVT VT : F16VecVTs) 810 SetCommonVFPActions(VT); 811 812 for (MVT VT : F32VecVTs) { 813 if (Subtarget.hasVInstructionsF32()) 814 SetCommonVFPActions(VT); 815 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 816 } 817 818 for (MVT VT : F64VecVTs) { 819 if (Subtarget.hasVInstructionsF64()) 820 SetCommonVFPActions(VT); 821 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 822 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 823 } 824 825 if (Subtarget.useRVVForFixedLengthVectors()) { 826 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 827 if (!useRVVForFixedLengthVectorVT(VT)) 828 continue; 829 830 // By default everything must be expanded. 831 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 832 setOperationAction(Op, VT, Expand); 833 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 834 setTruncStoreAction(VT, OtherVT, Expand); 835 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 836 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 837 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 838 } 839 840 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 841 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 842 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 843 844 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 845 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 846 847 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 848 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 849 850 setOperationAction(ISD::LOAD, VT, Custom); 851 setOperationAction(ISD::STORE, VT, Custom); 852 853 setOperationAction(ISD::SETCC, VT, Custom); 854 855 setOperationAction(ISD::SELECT, VT, Custom); 856 857 setOperationAction(ISD::TRUNCATE, VT, Custom); 858 859 setOperationAction(ISD::BITCAST, VT, Custom); 860 861 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 862 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 863 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 864 865 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 866 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 867 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 868 869 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 870 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 871 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 872 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 873 874 // Operations below are different for between masks and other vectors. 875 if (VT.getVectorElementType() == MVT::i1) { 876 setOperationAction(ISD::VP_AND, VT, Custom); 877 setOperationAction(ISD::VP_OR, VT, Custom); 878 setOperationAction(ISD::VP_XOR, VT, Custom); 879 setOperationAction(ISD::AND, VT, Custom); 880 setOperationAction(ISD::OR, VT, Custom); 881 setOperationAction(ISD::XOR, VT, Custom); 882 continue; 883 } 884 885 // Use SPLAT_VECTOR to prevent type legalization from destroying the 886 // splats when type legalizing i64 scalar on RV32. 887 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 888 // improvements first. 889 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 890 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 891 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 892 } 893 894 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 895 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 896 897 setOperationAction(ISD::MLOAD, VT, Custom); 898 setOperationAction(ISD::MSTORE, VT, Custom); 899 setOperationAction(ISD::MGATHER, VT, Custom); 900 setOperationAction(ISD::MSCATTER, VT, Custom); 901 902 setOperationAction(ISD::VP_LOAD, VT, Custom); 903 setOperationAction(ISD::VP_STORE, VT, Custom); 904 setOperationAction(ISD::VP_GATHER, VT, Custom); 905 setOperationAction(ISD::VP_SCATTER, VT, Custom); 906 907 setOperationAction(ISD::ADD, VT, Custom); 908 setOperationAction(ISD::MUL, VT, Custom); 909 setOperationAction(ISD::SUB, VT, Custom); 910 setOperationAction(ISD::AND, VT, Custom); 911 setOperationAction(ISD::OR, VT, Custom); 912 setOperationAction(ISD::XOR, VT, Custom); 913 setOperationAction(ISD::SDIV, VT, Custom); 914 setOperationAction(ISD::SREM, VT, Custom); 915 setOperationAction(ISD::UDIV, VT, Custom); 916 setOperationAction(ISD::UREM, VT, Custom); 917 setOperationAction(ISD::SHL, VT, Custom); 918 setOperationAction(ISD::SRA, VT, Custom); 919 setOperationAction(ISD::SRL, VT, Custom); 920 921 setOperationAction(ISD::SMIN, VT, Custom); 922 setOperationAction(ISD::SMAX, VT, Custom); 923 setOperationAction(ISD::UMIN, VT, Custom); 924 setOperationAction(ISD::UMAX, VT, Custom); 925 setOperationAction(ISD::ABS, VT, Custom); 926 927 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 928 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 929 setOperationAction(ISD::MULHS, VT, Custom); 930 setOperationAction(ISD::MULHU, VT, Custom); 931 } 932 933 setOperationAction(ISD::SADDSAT, VT, Custom); 934 setOperationAction(ISD::UADDSAT, VT, Custom); 935 setOperationAction(ISD::SSUBSAT, VT, Custom); 936 setOperationAction(ISD::USUBSAT, VT, Custom); 937 938 setOperationAction(ISD::VSELECT, VT, Custom); 939 setOperationAction(ISD::SELECT_CC, VT, Expand); 940 941 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 942 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 943 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 944 945 // Custom-lower reduction operations to set up the corresponding custom 946 // nodes' operands. 947 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 948 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 949 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 950 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 951 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 952 953 for (unsigned VPOpc : IntegerVPOps) 954 setOperationAction(VPOpc, VT, Custom); 955 956 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 957 // type that can represent the value exactly. 958 if (VT.getVectorElementType() != MVT::i64) { 959 MVT FloatEltVT = 960 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 961 EVT FloatVT = 962 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 963 if (isTypeLegal(FloatVT)) { 964 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 965 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 966 } 967 } 968 } 969 970 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 971 if (!useRVVForFixedLengthVectorVT(VT)) 972 continue; 973 974 // By default everything must be expanded. 975 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 976 setOperationAction(Op, VT, Expand); 977 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 978 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 979 setTruncStoreAction(VT, OtherVT, Expand); 980 } 981 982 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 983 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 984 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 985 986 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 987 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 988 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 989 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 991 992 setOperationAction(ISD::LOAD, VT, Custom); 993 setOperationAction(ISD::STORE, VT, Custom); 994 setOperationAction(ISD::MLOAD, VT, Custom); 995 setOperationAction(ISD::MSTORE, VT, Custom); 996 setOperationAction(ISD::MGATHER, VT, Custom); 997 setOperationAction(ISD::MSCATTER, VT, Custom); 998 999 setOperationAction(ISD::VP_LOAD, VT, Custom); 1000 setOperationAction(ISD::VP_STORE, VT, Custom); 1001 setOperationAction(ISD::VP_GATHER, VT, Custom); 1002 setOperationAction(ISD::VP_SCATTER, VT, Custom); 1003 1004 setOperationAction(ISD::FADD, VT, Custom); 1005 setOperationAction(ISD::FSUB, VT, Custom); 1006 setOperationAction(ISD::FMUL, VT, Custom); 1007 setOperationAction(ISD::FDIV, VT, Custom); 1008 setOperationAction(ISD::FNEG, VT, Custom); 1009 setOperationAction(ISD::FABS, VT, Custom); 1010 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 1011 setOperationAction(ISD::FSQRT, VT, Custom); 1012 setOperationAction(ISD::FMA, VT, Custom); 1013 setOperationAction(ISD::FMINNUM, VT, Custom); 1014 setOperationAction(ISD::FMAXNUM, VT, Custom); 1015 1016 setOperationAction(ISD::FP_ROUND, VT, Custom); 1017 setOperationAction(ISD::FP_EXTEND, VT, Custom); 1018 1019 setOperationAction(ISD::FTRUNC, VT, Custom); 1020 setOperationAction(ISD::FCEIL, VT, Custom); 1021 setOperationAction(ISD::FFLOOR, VT, Custom); 1022 setOperationAction(ISD::FROUND, VT, Custom); 1023 1024 for (auto CC : VFPCCToExpand) 1025 setCondCodeAction(CC, VT, Expand); 1026 1027 setOperationAction(ISD::VSELECT, VT, Custom); 1028 setOperationAction(ISD::SELECT, VT, Custom); 1029 setOperationAction(ISD::SELECT_CC, VT, Expand); 1030 1031 setOperationAction(ISD::BITCAST, VT, Custom); 1032 1033 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1034 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1035 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1036 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1037 1038 for (unsigned VPOpc : FloatingPointVPOps) 1039 setOperationAction(VPOpc, VT, Custom); 1040 } 1041 1042 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1043 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1044 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1045 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1046 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1047 if (Subtarget.hasStdExtZfh()) 1048 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1049 if (Subtarget.hasStdExtF()) 1050 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1051 if (Subtarget.hasStdExtD()) 1052 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1053 } 1054 } 1055 1056 // Function alignments. 1057 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1058 setMinFunctionAlignment(FunctionAlignment); 1059 setPrefFunctionAlignment(FunctionAlignment); 1060 1061 setMinimumJumpTableEntries(5); 1062 1063 // Jumps are expensive, compared to logic 1064 setJumpIsExpensive(); 1065 1066 setTargetDAGCombine(ISD::ADD); 1067 setTargetDAGCombine(ISD::SUB); 1068 setTargetDAGCombine(ISD::AND); 1069 setTargetDAGCombine(ISD::OR); 1070 setTargetDAGCombine(ISD::XOR); 1071 setTargetDAGCombine(ISD::ROTL); 1072 setTargetDAGCombine(ISD::ROTR); 1073 setTargetDAGCombine(ISD::ANY_EXTEND); 1074 if (Subtarget.hasStdExtF()) { 1075 setTargetDAGCombine(ISD::ZERO_EXTEND); 1076 setTargetDAGCombine(ISD::FP_TO_SINT); 1077 setTargetDAGCombine(ISD::FP_TO_UINT); 1078 setTargetDAGCombine(ISD::FP_TO_SINT_SAT); 1079 setTargetDAGCombine(ISD::FP_TO_UINT_SAT); 1080 } 1081 if (Subtarget.hasVInstructions()) { 1082 setTargetDAGCombine(ISD::FCOPYSIGN); 1083 setTargetDAGCombine(ISD::MGATHER); 1084 setTargetDAGCombine(ISD::MSCATTER); 1085 setTargetDAGCombine(ISD::VP_GATHER); 1086 setTargetDAGCombine(ISD::VP_SCATTER); 1087 setTargetDAGCombine(ISD::SRA); 1088 setTargetDAGCombine(ISD::SRL); 1089 setTargetDAGCombine(ISD::SHL); 1090 setTargetDAGCombine(ISD::STORE); 1091 setTargetDAGCombine(ISD::SPLAT_VECTOR); 1092 } 1093 1094 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1095 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1096 } 1097 1098 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1099 LLVMContext &Context, 1100 EVT VT) const { 1101 if (!VT.isVector()) 1102 return getPointerTy(DL); 1103 if (Subtarget.hasVInstructions() && 1104 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1105 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1106 return VT.changeVectorElementTypeToInteger(); 1107 } 1108 1109 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1110 return Subtarget.getXLenVT(); 1111 } 1112 1113 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1114 const CallInst &I, 1115 MachineFunction &MF, 1116 unsigned Intrinsic) const { 1117 auto &DL = I.getModule()->getDataLayout(); 1118 switch (Intrinsic) { 1119 default: 1120 return false; 1121 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1122 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1123 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1124 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1125 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1126 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1127 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1128 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1129 case Intrinsic::riscv_masked_cmpxchg_i32: 1130 Info.opc = ISD::INTRINSIC_W_CHAIN; 1131 Info.memVT = MVT::i32; 1132 Info.ptrVal = I.getArgOperand(0); 1133 Info.offset = 0; 1134 Info.align = Align(4); 1135 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1136 MachineMemOperand::MOVolatile; 1137 return true; 1138 case Intrinsic::riscv_masked_strided_load: 1139 Info.opc = ISD::INTRINSIC_W_CHAIN; 1140 Info.ptrVal = I.getArgOperand(1); 1141 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1142 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1143 Info.size = MemoryLocation::UnknownSize; 1144 Info.flags |= MachineMemOperand::MOLoad; 1145 return true; 1146 case Intrinsic::riscv_masked_strided_store: 1147 Info.opc = ISD::INTRINSIC_VOID; 1148 Info.ptrVal = I.getArgOperand(1); 1149 Info.memVT = 1150 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1151 Info.align = Align( 1152 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1153 8); 1154 Info.size = MemoryLocation::UnknownSize; 1155 Info.flags |= MachineMemOperand::MOStore; 1156 return true; 1157 } 1158 } 1159 1160 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1161 const AddrMode &AM, Type *Ty, 1162 unsigned AS, 1163 Instruction *I) const { 1164 // No global is ever allowed as a base. 1165 if (AM.BaseGV) 1166 return false; 1167 1168 // Require a 12-bit signed offset. 1169 if (!isInt<12>(AM.BaseOffs)) 1170 return false; 1171 1172 switch (AM.Scale) { 1173 case 0: // "r+i" or just "i", depending on HasBaseReg. 1174 break; 1175 case 1: 1176 if (!AM.HasBaseReg) // allow "r+i". 1177 break; 1178 return false; // disallow "r+r" or "r+r+i". 1179 default: 1180 return false; 1181 } 1182 1183 return true; 1184 } 1185 1186 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1187 return isInt<12>(Imm); 1188 } 1189 1190 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1191 return isInt<12>(Imm); 1192 } 1193 1194 // On RV32, 64-bit integers are split into their high and low parts and held 1195 // in two different registers, so the trunc is free since the low register can 1196 // just be used. 1197 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1198 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1199 return false; 1200 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1201 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1202 return (SrcBits == 64 && DestBits == 32); 1203 } 1204 1205 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1206 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1207 !SrcVT.isInteger() || !DstVT.isInteger()) 1208 return false; 1209 unsigned SrcBits = SrcVT.getSizeInBits(); 1210 unsigned DestBits = DstVT.getSizeInBits(); 1211 return (SrcBits == 64 && DestBits == 32); 1212 } 1213 1214 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1215 // Zexts are free if they can be combined with a load. 1216 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1217 // poorly with type legalization of compares preferring sext. 1218 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1219 EVT MemVT = LD->getMemoryVT(); 1220 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1221 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1222 LD->getExtensionType() == ISD::ZEXTLOAD)) 1223 return true; 1224 } 1225 1226 return TargetLowering::isZExtFree(Val, VT2); 1227 } 1228 1229 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1230 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1231 } 1232 1233 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1234 return Subtarget.hasStdExtZbb(); 1235 } 1236 1237 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1238 return Subtarget.hasStdExtZbb(); 1239 } 1240 1241 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1242 EVT VT = Y.getValueType(); 1243 1244 // FIXME: Support vectors once we have tests. 1245 if (VT.isVector()) 1246 return false; 1247 1248 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1249 Subtarget.hasStdExtZbkb()) && 1250 !isa<ConstantSDNode>(Y); 1251 } 1252 1253 /// Check if sinking \p I's operands to I's basic block is profitable, because 1254 /// the operands can be folded into a target instruction, e.g. 1255 /// splats of scalars can fold into vector instructions. 1256 bool RISCVTargetLowering::shouldSinkOperands( 1257 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1258 using namespace llvm::PatternMatch; 1259 1260 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1261 return false; 1262 1263 auto IsSinker = [&](Instruction *I, int Operand) { 1264 switch (I->getOpcode()) { 1265 case Instruction::Add: 1266 case Instruction::Sub: 1267 case Instruction::Mul: 1268 case Instruction::And: 1269 case Instruction::Or: 1270 case Instruction::Xor: 1271 case Instruction::FAdd: 1272 case Instruction::FSub: 1273 case Instruction::FMul: 1274 case Instruction::FDiv: 1275 case Instruction::ICmp: 1276 case Instruction::FCmp: 1277 return true; 1278 case Instruction::Shl: 1279 case Instruction::LShr: 1280 case Instruction::AShr: 1281 case Instruction::UDiv: 1282 case Instruction::SDiv: 1283 case Instruction::URem: 1284 case Instruction::SRem: 1285 return Operand == 1; 1286 case Instruction::Call: 1287 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1288 switch (II->getIntrinsicID()) { 1289 case Intrinsic::fma: 1290 return Operand == 0 || Operand == 1; 1291 // FIXME: Our patterns can only match vx/vf instructions when the splat 1292 // it on the RHS, because TableGen doesn't recognize our VP operations 1293 // as commutative. 1294 case Intrinsic::vp_add: 1295 case Intrinsic::vp_mul: 1296 case Intrinsic::vp_and: 1297 case Intrinsic::vp_or: 1298 case Intrinsic::vp_xor: 1299 case Intrinsic::vp_fadd: 1300 case Intrinsic::vp_fmul: 1301 case Intrinsic::vp_shl: 1302 case Intrinsic::vp_lshr: 1303 case Intrinsic::vp_ashr: 1304 case Intrinsic::vp_udiv: 1305 case Intrinsic::vp_sdiv: 1306 case Intrinsic::vp_urem: 1307 case Intrinsic::vp_srem: 1308 return Operand == 1; 1309 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1310 // explicit patterns for both LHS and RHS (as 'vr' versions). 1311 case Intrinsic::vp_sub: 1312 case Intrinsic::vp_fsub: 1313 case Intrinsic::vp_fdiv: 1314 return Operand == 0 || Operand == 1; 1315 default: 1316 return false; 1317 } 1318 } 1319 return false; 1320 default: 1321 return false; 1322 } 1323 }; 1324 1325 for (auto OpIdx : enumerate(I->operands())) { 1326 if (!IsSinker(I, OpIdx.index())) 1327 continue; 1328 1329 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1330 // Make sure we are not already sinking this operand 1331 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1332 continue; 1333 1334 // We are looking for a splat that can be sunk. 1335 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1336 m_Undef(), m_ZeroMask()))) 1337 continue; 1338 1339 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1340 // and vector registers 1341 for (Use &U : Op->uses()) { 1342 Instruction *Insn = cast<Instruction>(U.getUser()); 1343 if (!IsSinker(Insn, U.getOperandNo())) 1344 return false; 1345 } 1346 1347 Ops.push_back(&Op->getOperandUse(0)); 1348 Ops.push_back(&OpIdx.value()); 1349 } 1350 return true; 1351 } 1352 1353 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1354 bool ForCodeSize) const { 1355 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1356 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1357 return false; 1358 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1359 return false; 1360 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1361 return false; 1362 return Imm.isZero(); 1363 } 1364 1365 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1366 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1367 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1368 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1369 } 1370 1371 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1372 CallingConv::ID CC, 1373 EVT VT) const { 1374 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1375 // We might still end up using a GPR but that will be decided based on ABI. 1376 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1377 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1378 return MVT::f32; 1379 1380 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1381 } 1382 1383 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1384 CallingConv::ID CC, 1385 EVT VT) const { 1386 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1387 // We might still end up using a GPR but that will be decided based on ABI. 1388 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1389 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1390 return 1; 1391 1392 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1393 } 1394 1395 // Changes the condition code and swaps operands if necessary, so the SetCC 1396 // operation matches one of the comparisons supported directly by branches 1397 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1398 // with 1/-1. 1399 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1400 ISD::CondCode &CC, SelectionDAG &DAG) { 1401 // Convert X > -1 to X >= 0. 1402 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1403 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1404 CC = ISD::SETGE; 1405 return; 1406 } 1407 // Convert X < 1 to 0 >= X. 1408 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1409 RHS = LHS; 1410 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1411 CC = ISD::SETGE; 1412 return; 1413 } 1414 1415 switch (CC) { 1416 default: 1417 break; 1418 case ISD::SETGT: 1419 case ISD::SETLE: 1420 case ISD::SETUGT: 1421 case ISD::SETULE: 1422 CC = ISD::getSetCCSwappedOperands(CC); 1423 std::swap(LHS, RHS); 1424 break; 1425 } 1426 } 1427 1428 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1429 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1430 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1431 if (VT.getVectorElementType() == MVT::i1) 1432 KnownSize *= 8; 1433 1434 switch (KnownSize) { 1435 default: 1436 llvm_unreachable("Invalid LMUL."); 1437 case 8: 1438 return RISCVII::VLMUL::LMUL_F8; 1439 case 16: 1440 return RISCVII::VLMUL::LMUL_F4; 1441 case 32: 1442 return RISCVII::VLMUL::LMUL_F2; 1443 case 64: 1444 return RISCVII::VLMUL::LMUL_1; 1445 case 128: 1446 return RISCVII::VLMUL::LMUL_2; 1447 case 256: 1448 return RISCVII::VLMUL::LMUL_4; 1449 case 512: 1450 return RISCVII::VLMUL::LMUL_8; 1451 } 1452 } 1453 1454 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1455 switch (LMul) { 1456 default: 1457 llvm_unreachable("Invalid LMUL."); 1458 case RISCVII::VLMUL::LMUL_F8: 1459 case RISCVII::VLMUL::LMUL_F4: 1460 case RISCVII::VLMUL::LMUL_F2: 1461 case RISCVII::VLMUL::LMUL_1: 1462 return RISCV::VRRegClassID; 1463 case RISCVII::VLMUL::LMUL_2: 1464 return RISCV::VRM2RegClassID; 1465 case RISCVII::VLMUL::LMUL_4: 1466 return RISCV::VRM4RegClassID; 1467 case RISCVII::VLMUL::LMUL_8: 1468 return RISCV::VRM8RegClassID; 1469 } 1470 } 1471 1472 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1473 RISCVII::VLMUL LMUL = getLMUL(VT); 1474 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1475 LMUL == RISCVII::VLMUL::LMUL_F4 || 1476 LMUL == RISCVII::VLMUL::LMUL_F2 || 1477 LMUL == RISCVII::VLMUL::LMUL_1) { 1478 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1479 "Unexpected subreg numbering"); 1480 return RISCV::sub_vrm1_0 + Index; 1481 } 1482 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1483 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1484 "Unexpected subreg numbering"); 1485 return RISCV::sub_vrm2_0 + Index; 1486 } 1487 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1488 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1489 "Unexpected subreg numbering"); 1490 return RISCV::sub_vrm4_0 + Index; 1491 } 1492 llvm_unreachable("Invalid vector type."); 1493 } 1494 1495 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1496 if (VT.getVectorElementType() == MVT::i1) 1497 return RISCV::VRRegClassID; 1498 return getRegClassIDForLMUL(getLMUL(VT)); 1499 } 1500 1501 // Attempt to decompose a subvector insert/extract between VecVT and 1502 // SubVecVT via subregister indices. Returns the subregister index that 1503 // can perform the subvector insert/extract with the given element index, as 1504 // well as the index corresponding to any leftover subvectors that must be 1505 // further inserted/extracted within the register class for SubVecVT. 1506 std::pair<unsigned, unsigned> 1507 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1508 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1509 const RISCVRegisterInfo *TRI) { 1510 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1511 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1512 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1513 "Register classes not ordered"); 1514 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1515 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1516 // Try to compose a subregister index that takes us from the incoming 1517 // LMUL>1 register class down to the outgoing one. At each step we half 1518 // the LMUL: 1519 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1520 // Note that this is not guaranteed to find a subregister index, such as 1521 // when we are extracting from one VR type to another. 1522 unsigned SubRegIdx = RISCV::NoSubRegister; 1523 for (const unsigned RCID : 1524 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1525 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1526 VecVT = VecVT.getHalfNumVectorElementsVT(); 1527 bool IsHi = 1528 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1529 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1530 getSubregIndexByMVT(VecVT, IsHi)); 1531 if (IsHi) 1532 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1533 } 1534 return {SubRegIdx, InsertExtractIdx}; 1535 } 1536 1537 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1538 // stores for those types. 1539 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1540 return !Subtarget.useRVVForFixedLengthVectors() || 1541 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1542 } 1543 1544 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1545 if (ScalarTy->isPointerTy()) 1546 return true; 1547 1548 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1549 ScalarTy->isIntegerTy(32)) 1550 return true; 1551 1552 if (ScalarTy->isIntegerTy(64)) 1553 return Subtarget.hasVInstructionsI64(); 1554 1555 if (ScalarTy->isHalfTy()) 1556 return Subtarget.hasVInstructionsF16(); 1557 if (ScalarTy->isFloatTy()) 1558 return Subtarget.hasVInstructionsF32(); 1559 if (ScalarTy->isDoubleTy()) 1560 return Subtarget.hasVInstructionsF64(); 1561 1562 return false; 1563 } 1564 1565 static SDValue getVLOperand(SDValue Op) { 1566 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1567 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1568 "Unexpected opcode"); 1569 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1570 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1571 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1572 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1573 if (!II) 1574 return SDValue(); 1575 return Op.getOperand(II->VLOperand + 1 + HasChain); 1576 } 1577 1578 static bool useRVVForFixedLengthVectorVT(MVT VT, 1579 const RISCVSubtarget &Subtarget) { 1580 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1581 if (!Subtarget.useRVVForFixedLengthVectors()) 1582 return false; 1583 1584 // We only support a set of vector types with a consistent maximum fixed size 1585 // across all supported vector element types to avoid legalization issues. 1586 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1587 // fixed-length vector type we support is 1024 bytes. 1588 if (VT.getFixedSizeInBits() > 1024 * 8) 1589 return false; 1590 1591 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1592 1593 MVT EltVT = VT.getVectorElementType(); 1594 1595 // Don't use RVV for vectors we cannot scalarize if required. 1596 switch (EltVT.SimpleTy) { 1597 // i1 is supported but has different rules. 1598 default: 1599 return false; 1600 case MVT::i1: 1601 // Masks can only use a single register. 1602 if (VT.getVectorNumElements() > MinVLen) 1603 return false; 1604 MinVLen /= 8; 1605 break; 1606 case MVT::i8: 1607 case MVT::i16: 1608 case MVT::i32: 1609 break; 1610 case MVT::i64: 1611 if (!Subtarget.hasVInstructionsI64()) 1612 return false; 1613 break; 1614 case MVT::f16: 1615 if (!Subtarget.hasVInstructionsF16()) 1616 return false; 1617 break; 1618 case MVT::f32: 1619 if (!Subtarget.hasVInstructionsF32()) 1620 return false; 1621 break; 1622 case MVT::f64: 1623 if (!Subtarget.hasVInstructionsF64()) 1624 return false; 1625 break; 1626 } 1627 1628 // Reject elements larger than ELEN. 1629 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1630 return false; 1631 1632 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1633 // Don't use RVV for types that don't fit. 1634 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1635 return false; 1636 1637 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1638 // the base fixed length RVV support in place. 1639 if (!VT.isPow2VectorType()) 1640 return false; 1641 1642 return true; 1643 } 1644 1645 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1646 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1647 } 1648 1649 // Return the largest legal scalable vector type that matches VT's element type. 1650 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1651 const RISCVSubtarget &Subtarget) { 1652 // This may be called before legal types are setup. 1653 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1654 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1655 "Expected legal fixed length vector!"); 1656 1657 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1658 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1659 1660 MVT EltVT = VT.getVectorElementType(); 1661 switch (EltVT.SimpleTy) { 1662 default: 1663 llvm_unreachable("unexpected element type for RVV container"); 1664 case MVT::i1: 1665 case MVT::i8: 1666 case MVT::i16: 1667 case MVT::i32: 1668 case MVT::i64: 1669 case MVT::f16: 1670 case MVT::f32: 1671 case MVT::f64: { 1672 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1673 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1674 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1675 unsigned NumElts = 1676 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1677 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1678 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1679 return MVT::getScalableVectorVT(EltVT, NumElts); 1680 } 1681 } 1682 } 1683 1684 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1685 const RISCVSubtarget &Subtarget) { 1686 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1687 Subtarget); 1688 } 1689 1690 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1691 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1692 } 1693 1694 // Grow V to consume an entire RVV register. 1695 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1696 const RISCVSubtarget &Subtarget) { 1697 assert(VT.isScalableVector() && 1698 "Expected to convert into a scalable vector!"); 1699 assert(V.getValueType().isFixedLengthVector() && 1700 "Expected a fixed length vector operand!"); 1701 SDLoc DL(V); 1702 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1703 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1704 } 1705 1706 // Shrink V so it's just big enough to maintain a VT's worth of data. 1707 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1708 const RISCVSubtarget &Subtarget) { 1709 assert(VT.isFixedLengthVector() && 1710 "Expected to convert into a fixed length vector!"); 1711 assert(V.getValueType().isScalableVector() && 1712 "Expected a scalable vector operand!"); 1713 SDLoc DL(V); 1714 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1715 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1716 } 1717 1718 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1719 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1720 // the vector type that it is contained in. 1721 static std::pair<SDValue, SDValue> 1722 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1723 const RISCVSubtarget &Subtarget) { 1724 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1725 MVT XLenVT = Subtarget.getXLenVT(); 1726 SDValue VL = VecVT.isFixedLengthVector() 1727 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1728 : DAG.getRegister(RISCV::X0, XLenVT); 1729 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1730 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1731 return {Mask, VL}; 1732 } 1733 1734 // As above but assuming the given type is a scalable vector type. 1735 static std::pair<SDValue, SDValue> 1736 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1737 const RISCVSubtarget &Subtarget) { 1738 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1739 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1740 } 1741 1742 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1743 // of either is (currently) supported. This can get us into an infinite loop 1744 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1745 // as a ..., etc. 1746 // Until either (or both) of these can reliably lower any node, reporting that 1747 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1748 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1749 // which is not desirable. 1750 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1751 EVT VT, unsigned DefinedValues) const { 1752 return false; 1753 } 1754 1755 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1756 const RISCVSubtarget &Subtarget) { 1757 // RISCV FP-to-int conversions saturate to the destination register size, but 1758 // don't produce 0 for nan. We can use a conversion instruction and fix the 1759 // nan case with a compare and a select. 1760 SDValue Src = Op.getOperand(0); 1761 1762 EVT DstVT = Op.getValueType(); 1763 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1764 1765 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1766 unsigned Opc; 1767 if (SatVT == DstVT) 1768 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1769 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1770 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1771 else 1772 return SDValue(); 1773 // FIXME: Support other SatVTs by clamping before or after the conversion. 1774 1775 SDLoc DL(Op); 1776 SDValue FpToInt = DAG.getNode( 1777 Opc, DL, DstVT, Src, 1778 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1779 1780 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1781 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1782 } 1783 1784 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1785 // and back. Taking care to avoid converting values that are nan or already 1786 // correct. 1787 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1788 // have FRM dependencies modeled yet. 1789 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1790 MVT VT = Op.getSimpleValueType(); 1791 assert(VT.isVector() && "Unexpected type"); 1792 1793 SDLoc DL(Op); 1794 1795 // Freeze the source since we are increasing the number of uses. 1796 SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0)); 1797 1798 // Truncate to integer and convert back to FP. 1799 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1800 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1801 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1802 1803 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1804 1805 if (Op.getOpcode() == ISD::FCEIL) { 1806 // If the truncated value is the greater than or equal to the original 1807 // value, we've computed the ceil. Otherwise, we went the wrong way and 1808 // need to increase by 1. 1809 // FIXME: This should use a masked operation. Handle here or in isel? 1810 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1811 DAG.getConstantFP(1.0, DL, VT)); 1812 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1813 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1814 } else if (Op.getOpcode() == ISD::FFLOOR) { 1815 // If the truncated value is the less than or equal to the original value, 1816 // we've computed the floor. Otherwise, we went the wrong way and need to 1817 // decrease by 1. 1818 // FIXME: This should use a masked operation. Handle here or in isel? 1819 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1820 DAG.getConstantFP(1.0, DL, VT)); 1821 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1822 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1823 } 1824 1825 // Restore the original sign so that -0.0 is preserved. 1826 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1827 1828 // Determine the largest integer that can be represented exactly. This and 1829 // values larger than it don't have any fractional bits so don't need to 1830 // be converted. 1831 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1832 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1833 APFloat MaxVal = APFloat(FltSem); 1834 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1835 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1836 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1837 1838 // If abs(Src) was larger than MaxVal or nan, keep it. 1839 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1840 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1841 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1842 } 1843 1844 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1845 // This mode isn't supported in vector hardware on RISCV. But as long as we 1846 // aren't compiling with trapping math, we can emulate this with 1847 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1848 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1849 // dependencies modeled yet. 1850 // FIXME: Use masked operations to avoid final merge. 1851 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1852 MVT VT = Op.getSimpleValueType(); 1853 assert(VT.isVector() && "Unexpected type"); 1854 1855 SDLoc DL(Op); 1856 1857 // Freeze the source since we are increasing the number of uses. 1858 SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0)); 1859 1860 // We do the conversion on the absolute value and fix the sign at the end. 1861 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1862 1863 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1864 bool Ignored; 1865 APFloat Point5Pred = APFloat(0.5f); 1866 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1867 Point5Pred.next(/*nextDown*/ true); 1868 1869 // Add the adjustment. 1870 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1871 DAG.getConstantFP(Point5Pred, DL, VT)); 1872 1873 // Truncate to integer and convert back to fp. 1874 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1875 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1876 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1877 1878 // Restore the original sign. 1879 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1880 1881 // Determine the largest integer that can be represented exactly. This and 1882 // values larger than it don't have any fractional bits so don't need to 1883 // be converted. 1884 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1885 APFloat MaxVal = APFloat(FltSem); 1886 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1887 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1888 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1889 1890 // If abs(Src) was larger than MaxVal or nan, keep it. 1891 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1892 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1893 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1894 } 1895 1896 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1897 const RISCVSubtarget &Subtarget) { 1898 MVT VT = Op.getSimpleValueType(); 1899 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1900 1901 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1902 1903 SDLoc DL(Op); 1904 SDValue Mask, VL; 1905 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1906 1907 unsigned Opc = 1908 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1909 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1910 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1911 } 1912 1913 struct VIDSequence { 1914 int64_t StepNumerator; 1915 unsigned StepDenominator; 1916 int64_t Addend; 1917 }; 1918 1919 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1920 // to the (non-zero) step S and start value X. This can be then lowered as the 1921 // RVV sequence (VID * S) + X, for example. 1922 // The step S is represented as an integer numerator divided by a positive 1923 // denominator. Note that the implementation currently only identifies 1924 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1925 // cannot detect 2/3, for example. 1926 // Note that this method will also match potentially unappealing index 1927 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1928 // determine whether this is worth generating code for. 1929 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1930 unsigned NumElts = Op.getNumOperands(); 1931 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1932 if (!Op.getValueType().isInteger()) 1933 return None; 1934 1935 Optional<unsigned> SeqStepDenom; 1936 Optional<int64_t> SeqStepNum, SeqAddend; 1937 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1938 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1939 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1940 // Assume undef elements match the sequence; we just have to be careful 1941 // when interpolating across them. 1942 if (Op.getOperand(Idx).isUndef()) 1943 continue; 1944 // The BUILD_VECTOR must be all constants. 1945 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1946 return None; 1947 1948 uint64_t Val = Op.getConstantOperandVal(Idx) & 1949 maskTrailingOnes<uint64_t>(EltSizeInBits); 1950 1951 if (PrevElt) { 1952 // Calculate the step since the last non-undef element, and ensure 1953 // it's consistent across the entire sequence. 1954 unsigned IdxDiff = Idx - PrevElt->second; 1955 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1956 1957 // A zero-value value difference means that we're somewhere in the middle 1958 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1959 // step change before evaluating the sequence. 1960 if (ValDiff != 0) { 1961 int64_t Remainder = ValDiff % IdxDiff; 1962 // Normalize the step if it's greater than 1. 1963 if (Remainder != ValDiff) { 1964 // The difference must cleanly divide the element span. 1965 if (Remainder != 0) 1966 return None; 1967 ValDiff /= IdxDiff; 1968 IdxDiff = 1; 1969 } 1970 1971 if (!SeqStepNum) 1972 SeqStepNum = ValDiff; 1973 else if (ValDiff != SeqStepNum) 1974 return None; 1975 1976 if (!SeqStepDenom) 1977 SeqStepDenom = IdxDiff; 1978 else if (IdxDiff != *SeqStepDenom) 1979 return None; 1980 } 1981 } 1982 1983 // Record and/or check any addend. 1984 if (SeqStepNum && SeqStepDenom) { 1985 uint64_t ExpectedVal = 1986 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1987 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1988 if (!SeqAddend) 1989 SeqAddend = Addend; 1990 else if (SeqAddend != Addend) 1991 return None; 1992 } 1993 1994 // Record this non-undef element for later. 1995 if (!PrevElt || PrevElt->first != Val) 1996 PrevElt = std::make_pair(Val, Idx); 1997 } 1998 // We need to have logged both a step and an addend for this to count as 1999 // a legal index sequence. 2000 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 2001 return None; 2002 2003 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 2004 } 2005 2006 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 2007 // and lower it as a VRGATHER_VX_VL from the source vector. 2008 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 2009 SelectionDAG &DAG, 2010 const RISCVSubtarget &Subtarget) { 2011 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 2012 return SDValue(); 2013 SDValue Vec = SplatVal.getOperand(0); 2014 // Only perform this optimization on vectors of the same size for simplicity. 2015 if (Vec.getValueType() != VT) 2016 return SDValue(); 2017 SDValue Idx = SplatVal.getOperand(1); 2018 // The index must be a legal type. 2019 if (Idx.getValueType() != Subtarget.getXLenVT()) 2020 return SDValue(); 2021 2022 MVT ContainerVT = VT; 2023 if (VT.isFixedLengthVector()) { 2024 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2025 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2026 } 2027 2028 SDValue Mask, VL; 2029 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2030 2031 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2032 Idx, Mask, VL); 2033 2034 if (!VT.isFixedLengthVector()) 2035 return Gather; 2036 2037 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2038 } 2039 2040 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2041 const RISCVSubtarget &Subtarget) { 2042 MVT VT = Op.getSimpleValueType(); 2043 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2044 2045 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2046 2047 SDLoc DL(Op); 2048 SDValue Mask, VL; 2049 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2050 2051 MVT XLenVT = Subtarget.getXLenVT(); 2052 unsigned NumElts = Op.getNumOperands(); 2053 2054 if (VT.getVectorElementType() == MVT::i1) { 2055 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2056 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2057 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2058 } 2059 2060 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2061 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2062 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2063 } 2064 2065 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2066 // scalar integer chunks whose bit-width depends on the number of mask 2067 // bits and XLEN. 2068 // First, determine the most appropriate scalar integer type to use. This 2069 // is at most XLenVT, but may be shrunk to a smaller vector element type 2070 // according to the size of the final vector - use i8 chunks rather than 2071 // XLenVT if we're producing a v8i1. This results in more consistent 2072 // codegen across RV32 and RV64. 2073 unsigned NumViaIntegerBits = 2074 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2075 NumViaIntegerBits = std::min(NumViaIntegerBits, 2076 Subtarget.getMaxELENForFixedLengthVectors()); 2077 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2078 // If we have to use more than one INSERT_VECTOR_ELT then this 2079 // optimization is likely to increase code size; avoid peforming it in 2080 // such a case. We can use a load from a constant pool in this case. 2081 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2082 return SDValue(); 2083 // Now we can create our integer vector type. Note that it may be larger 2084 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2085 MVT IntegerViaVecVT = 2086 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2087 divideCeil(NumElts, NumViaIntegerBits)); 2088 2089 uint64_t Bits = 0; 2090 unsigned BitPos = 0, IntegerEltIdx = 0; 2091 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2092 2093 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2094 // Once we accumulate enough bits to fill our scalar type, insert into 2095 // our vector and clear our accumulated data. 2096 if (I != 0 && I % NumViaIntegerBits == 0) { 2097 if (NumViaIntegerBits <= 32) 2098 Bits = SignExtend64(Bits, 32); 2099 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2100 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2101 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2102 Bits = 0; 2103 BitPos = 0; 2104 IntegerEltIdx++; 2105 } 2106 SDValue V = Op.getOperand(I); 2107 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2108 Bits |= ((uint64_t)BitValue << BitPos); 2109 } 2110 2111 // Insert the (remaining) scalar value into position in our integer 2112 // vector type. 2113 if (NumViaIntegerBits <= 32) 2114 Bits = SignExtend64(Bits, 32); 2115 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2116 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2117 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2118 2119 if (NumElts < NumViaIntegerBits) { 2120 // If we're producing a smaller vector than our minimum legal integer 2121 // type, bitcast to the equivalent (known-legal) mask type, and extract 2122 // our final mask. 2123 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2124 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2125 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2126 DAG.getConstant(0, DL, XLenVT)); 2127 } else { 2128 // Else we must have produced an integer type with the same size as the 2129 // mask type; bitcast for the final result. 2130 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2131 Vec = DAG.getBitcast(VT, Vec); 2132 } 2133 2134 return Vec; 2135 } 2136 2137 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2138 // vector type, we have a legal equivalently-sized i8 type, so we can use 2139 // that. 2140 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2141 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2142 2143 SDValue WideVec; 2144 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2145 // For a splat, perform a scalar truncate before creating the wider 2146 // vector. 2147 assert(Splat.getValueType() == XLenVT && 2148 "Unexpected type for i1 splat value"); 2149 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2150 DAG.getConstant(1, DL, XLenVT)); 2151 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2152 } else { 2153 SmallVector<SDValue, 8> Ops(Op->op_values()); 2154 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2155 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2156 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2157 } 2158 2159 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2160 } 2161 2162 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2163 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2164 return Gather; 2165 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2166 : RISCVISD::VMV_V_X_VL; 2167 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 2168 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2169 } 2170 2171 // Try and match index sequences, which we can lower to the vid instruction 2172 // with optional modifications. An all-undef vector is matched by 2173 // getSplatValue, above. 2174 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2175 int64_t StepNumerator = SimpleVID->StepNumerator; 2176 unsigned StepDenominator = SimpleVID->StepDenominator; 2177 int64_t Addend = SimpleVID->Addend; 2178 2179 assert(StepNumerator != 0 && "Invalid step"); 2180 bool Negate = false; 2181 int64_t SplatStepVal = StepNumerator; 2182 unsigned StepOpcode = ISD::MUL; 2183 if (StepNumerator != 1) { 2184 if (isPowerOf2_64(std::abs(StepNumerator))) { 2185 Negate = StepNumerator < 0; 2186 StepOpcode = ISD::SHL; 2187 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2188 } 2189 } 2190 2191 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2192 // threshold since it's the immediate value many RVV instructions accept. 2193 // There is no vmul.vi instruction so ensure multiply constant can fit in 2194 // a single addi instruction. 2195 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2196 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2197 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2198 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2199 // Convert right out of the scalable type so we can use standard ISD 2200 // nodes for the rest of the computation. If we used scalable types with 2201 // these, we'd lose the fixed-length vector info and generate worse 2202 // vsetvli code. 2203 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2204 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2205 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2206 SDValue SplatStep = DAG.getSplatVector( 2207 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2208 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2209 } 2210 if (StepDenominator != 1) { 2211 SDValue SplatStep = DAG.getSplatVector( 2212 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2213 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2214 } 2215 if (Addend != 0 || Negate) { 2216 SDValue SplatAddend = 2217 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2218 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2219 } 2220 return VID; 2221 } 2222 } 2223 2224 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2225 // when re-interpreted as a vector with a larger element type. For example, 2226 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2227 // could be instead splat as 2228 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2229 // TODO: This optimization could also work on non-constant splats, but it 2230 // would require bit-manipulation instructions to construct the splat value. 2231 SmallVector<SDValue> Sequence; 2232 unsigned EltBitSize = VT.getScalarSizeInBits(); 2233 const auto *BV = cast<BuildVectorSDNode>(Op); 2234 if (VT.isInteger() && EltBitSize < 64 && 2235 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2236 BV->getRepeatedSequence(Sequence) && 2237 (Sequence.size() * EltBitSize) <= 64) { 2238 unsigned SeqLen = Sequence.size(); 2239 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2240 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2241 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2242 ViaIntVT == MVT::i64) && 2243 "Unexpected sequence type"); 2244 2245 unsigned EltIdx = 0; 2246 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2247 uint64_t SplatValue = 0; 2248 // Construct the amalgamated value which can be splatted as this larger 2249 // vector type. 2250 for (const auto &SeqV : Sequence) { 2251 if (!SeqV.isUndef()) 2252 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2253 << (EltIdx * EltBitSize)); 2254 EltIdx++; 2255 } 2256 2257 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2258 // achieve better constant materializion. 2259 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2260 SplatValue = SignExtend64(SplatValue, 32); 2261 2262 // Since we can't introduce illegal i64 types at this stage, we can only 2263 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2264 // way we can use RVV instructions to splat. 2265 assert((ViaIntVT.bitsLE(XLenVT) || 2266 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2267 "Unexpected bitcast sequence"); 2268 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2269 SDValue ViaVL = 2270 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2271 MVT ViaContainerVT = 2272 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2273 SDValue Splat = 2274 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2275 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2276 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2277 return DAG.getBitcast(VT, Splat); 2278 } 2279 } 2280 2281 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2282 // which constitute a large proportion of the elements. In such cases we can 2283 // splat a vector with the dominant element and make up the shortfall with 2284 // INSERT_VECTOR_ELTs. 2285 // Note that this includes vectors of 2 elements by association. The 2286 // upper-most element is the "dominant" one, allowing us to use a splat to 2287 // "insert" the upper element, and an insert of the lower element at position 2288 // 0, which improves codegen. 2289 SDValue DominantValue; 2290 unsigned MostCommonCount = 0; 2291 DenseMap<SDValue, unsigned> ValueCounts; 2292 unsigned NumUndefElts = 2293 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2294 2295 // Track the number of scalar loads we know we'd be inserting, estimated as 2296 // any non-zero floating-point constant. Other kinds of element are either 2297 // already in registers or are materialized on demand. The threshold at which 2298 // a vector load is more desirable than several scalar materializion and 2299 // vector-insertion instructions is not known. 2300 unsigned NumScalarLoads = 0; 2301 2302 for (SDValue V : Op->op_values()) { 2303 if (V.isUndef()) 2304 continue; 2305 2306 ValueCounts.insert(std::make_pair(V, 0)); 2307 unsigned &Count = ValueCounts[V]; 2308 2309 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2310 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2311 2312 // Is this value dominant? In case of a tie, prefer the highest element as 2313 // it's cheaper to insert near the beginning of a vector than it is at the 2314 // end. 2315 if (++Count >= MostCommonCount) { 2316 DominantValue = V; 2317 MostCommonCount = Count; 2318 } 2319 } 2320 2321 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2322 unsigned NumDefElts = NumElts - NumUndefElts; 2323 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2324 2325 // Don't perform this optimization when optimizing for size, since 2326 // materializing elements and inserting them tends to cause code bloat. 2327 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2328 ((MostCommonCount > DominantValueCountThreshold) || 2329 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2330 // Start by splatting the most common element. 2331 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2332 2333 DenseSet<SDValue> Processed{DominantValue}; 2334 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2335 for (const auto &OpIdx : enumerate(Op->ops())) { 2336 const SDValue &V = OpIdx.value(); 2337 if (V.isUndef() || !Processed.insert(V).second) 2338 continue; 2339 if (ValueCounts[V] == 1) { 2340 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2341 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2342 } else { 2343 // Blend in all instances of this value using a VSELECT, using a 2344 // mask where each bit signals whether that element is the one 2345 // we're after. 2346 SmallVector<SDValue> Ops; 2347 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2348 return DAG.getConstant(V == V1, DL, XLenVT); 2349 }); 2350 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2351 DAG.getBuildVector(SelMaskTy, DL, Ops), 2352 DAG.getSplatBuildVector(VT, DL, V), Vec); 2353 } 2354 } 2355 2356 return Vec; 2357 } 2358 2359 return SDValue(); 2360 } 2361 2362 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 2363 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 2364 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2365 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2366 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2367 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2368 // node in order to try and match RVV vector/scalar instructions. 2369 if ((LoC >> 31) == HiC) 2370 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2371 2372 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2373 // vmv.v.x whose EEW = 32 to lower it. 2374 auto *Const = dyn_cast<ConstantSDNode>(VL); 2375 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2376 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2377 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2378 // access the subtarget here now. 2379 auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT, Lo, 2380 DAG.getRegister(RISCV::X0, MVT::i32)); 2381 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2382 } 2383 } 2384 2385 // Fall back to a stack store and stride x0 vector load. 2386 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2387 } 2388 2389 // Called by type legalization to handle splat of i64 on RV32. 2390 // FIXME: We can optimize this when the type has sign or zero bits in one 2391 // of the halves. 2392 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2393 SDValue VL, SelectionDAG &DAG) { 2394 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2395 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2396 DAG.getConstant(0, DL, MVT::i32)); 2397 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2398 DAG.getConstant(1, DL, MVT::i32)); 2399 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2400 } 2401 2402 // This function lowers a splat of a scalar operand Splat with the vector 2403 // length VL. It ensures the final sequence is type legal, which is useful when 2404 // lowering a splat after type legalization. 2405 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2406 SelectionDAG &DAG, 2407 const RISCVSubtarget &Subtarget) { 2408 if (VT.isFloatingPoint()) { 2409 // If VL is 1, we could use vfmv.s.f. 2410 if (isOneConstant(VL)) 2411 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT), 2412 Scalar, VL); 2413 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2414 } 2415 2416 MVT XLenVT = Subtarget.getXLenVT(); 2417 2418 // Simplest case is that the operand needs to be promoted to XLenVT. 2419 if (Scalar.getValueType().bitsLE(XLenVT)) { 2420 // If the operand is a constant, sign extend to increase our chances 2421 // of being able to use a .vi instruction. ANY_EXTEND would become a 2422 // a zero extend and the simm5 check in isel would fail. 2423 // FIXME: Should we ignore the upper bits in isel instead? 2424 unsigned ExtOpc = 2425 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2426 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2427 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2428 // If VL is 1 and the scalar value won't benefit from immediate, we could 2429 // use vmv.s.x. 2430 if (isOneConstant(VL) && 2431 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2432 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar, 2433 VL); 2434 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2435 } 2436 2437 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2438 "Unexpected scalar for splat lowering!"); 2439 2440 if (isOneConstant(VL) && isNullConstant(Scalar)) 2441 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), 2442 DAG.getConstant(0, DL, XLenVT), VL); 2443 2444 // Otherwise use the more complicated splatting algorithm. 2445 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2446 } 2447 2448 // Is the mask a slidedown that shifts in undefs. 2449 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) { 2450 int Size = Mask.size(); 2451 2452 // Elements shifted in should be undef. 2453 auto CheckUndefs = [&](int Shift) { 2454 for (int i = Size - Shift; i != Size; ++i) 2455 if (Mask[i] >= 0) 2456 return false; 2457 return true; 2458 }; 2459 2460 // Elements should be shifted or undef. 2461 auto MatchShift = [&](int Shift) { 2462 for (int i = 0; i != Size - Shift; ++i) 2463 if (Mask[i] >= 0 && Mask[i] != Shift + i) 2464 return false; 2465 return true; 2466 }; 2467 2468 // Try all possible shifts. 2469 for (int Shift = 1; Shift != Size; ++Shift) 2470 if (CheckUndefs(Shift) && MatchShift(Shift)) 2471 return Shift; 2472 2473 // No match. 2474 return -1; 2475 } 2476 2477 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2478 const RISCVSubtarget &Subtarget) { 2479 // We need to be able to widen elements to the next larger integer type. 2480 if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors()) 2481 return false; 2482 2483 int Size = Mask.size(); 2484 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2485 2486 int Srcs[] = {-1, -1}; 2487 for (int i = 0; i != Size; ++i) { 2488 // Ignore undef elements. 2489 if (Mask[i] < 0) 2490 continue; 2491 2492 // Is this an even or odd element. 2493 int Pol = i % 2; 2494 2495 // Ensure we consistently use the same source for this element polarity. 2496 int Src = Mask[i] / Size; 2497 if (Srcs[Pol] < 0) 2498 Srcs[Pol] = Src; 2499 if (Srcs[Pol] != Src) 2500 return false; 2501 2502 // Make sure the element within the source is appropriate for this element 2503 // in the destination. 2504 int Elt = Mask[i] % Size; 2505 if (Elt != i / 2) 2506 return false; 2507 } 2508 2509 // We need to find a source for each polarity and they can't be the same. 2510 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2511 return false; 2512 2513 // Swap the sources if the second source was in the even polarity. 2514 SwapSources = Srcs[0] > Srcs[1]; 2515 2516 return true; 2517 } 2518 2519 static int isElementRotate(SDValue &V1, SDValue &V2, ArrayRef<int> Mask) { 2520 int Size = Mask.size(); 2521 2522 // We need to detect various ways of spelling a rotation: 2523 // [11, 12, 13, 14, 15, 0, 1, 2] 2524 // [-1, 12, 13, 14, -1, -1, 1, -1] 2525 // [-1, -1, -1, -1, -1, -1, 1, 2] 2526 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2527 // [-1, 4, 5, 6, -1, -1, 9, -1] 2528 // [-1, 4, 5, 6, -1, -1, -1, -1] 2529 int Rotation = 0; 2530 SDValue Lo, Hi; 2531 for (int i = 0; i != Size; ++i) { 2532 int M = Mask[i]; 2533 if (M < 0) 2534 continue; 2535 2536 // Determine where a rotate vector would have started. 2537 int StartIdx = i - (M % Size); 2538 // The identity rotation isn't interesting, stop. 2539 if (StartIdx == 0) 2540 return -1; 2541 2542 // If we found the tail of a vector the rotation must be the missing 2543 // front. If we found the head of a vector, it must be how much of the 2544 // head. 2545 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2546 2547 if (Rotation == 0) 2548 Rotation = CandidateRotation; 2549 else if (Rotation != CandidateRotation) 2550 // The rotations don't match, so we can't match this mask. 2551 return -1; 2552 2553 // Compute which value this mask is pointing at. 2554 SDValue MaskV = M < Size ? V1 : V2; 2555 2556 // Compute which of the two target values this index should be assigned to. 2557 // This reflects whether the high elements are remaining or the low elemnts 2558 // are remaining. 2559 SDValue &TargetV = StartIdx < 0 ? Hi : Lo; 2560 2561 // Either set up this value if we've not encountered it before, or check 2562 // that it remains consistent. 2563 if (!TargetV) 2564 TargetV = MaskV; 2565 else if (TargetV != MaskV) 2566 // This may be a rotation, but it pulls from the inputs in some 2567 // unsupported interleaving. 2568 return -1; 2569 } 2570 2571 // Check that we successfully analyzed the mask, and normalize the results. 2572 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2573 assert((Lo || Hi) && "Failed to find a rotated input vector!"); 2574 2575 // Make sure we've found a value for both halves. 2576 if (!Lo || !Hi) 2577 return -1; 2578 2579 V1 = Lo; 2580 V2 = Hi; 2581 2582 return Rotation; 2583 } 2584 2585 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2586 const RISCVSubtarget &Subtarget) { 2587 SDValue V1 = Op.getOperand(0); 2588 SDValue V2 = Op.getOperand(1); 2589 SDLoc DL(Op); 2590 MVT XLenVT = Subtarget.getXLenVT(); 2591 MVT VT = Op.getSimpleValueType(); 2592 unsigned NumElts = VT.getVectorNumElements(); 2593 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2594 2595 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2596 2597 SDValue TrueMask, VL; 2598 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2599 2600 if (SVN->isSplat()) { 2601 const int Lane = SVN->getSplatIndex(); 2602 if (Lane >= 0) { 2603 MVT SVT = VT.getVectorElementType(); 2604 2605 // Turn splatted vector load into a strided load with an X0 stride. 2606 SDValue V = V1; 2607 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2608 // with undef. 2609 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2610 int Offset = Lane; 2611 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2612 int OpElements = 2613 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2614 V = V.getOperand(Offset / OpElements); 2615 Offset %= OpElements; 2616 } 2617 2618 // We need to ensure the load isn't atomic or volatile. 2619 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2620 auto *Ld = cast<LoadSDNode>(V); 2621 Offset *= SVT.getStoreSize(); 2622 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2623 TypeSize::Fixed(Offset), DL); 2624 2625 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2626 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2627 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2628 SDValue IntID = 2629 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2630 SDValue Ops[] = {Ld->getChain(), 2631 IntID, 2632 DAG.getUNDEF(ContainerVT), 2633 NewAddr, 2634 DAG.getRegister(RISCV::X0, XLenVT), 2635 VL}; 2636 SDValue NewLoad = DAG.getMemIntrinsicNode( 2637 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2638 DAG.getMachineFunction().getMachineMemOperand( 2639 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2640 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2641 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2642 } 2643 2644 // Otherwise use a scalar load and splat. This will give the best 2645 // opportunity to fold a splat into the operation. ISel can turn it into 2646 // the x0 strided load if we aren't able to fold away the select. 2647 if (SVT.isFloatingPoint()) 2648 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2649 Ld->getPointerInfo().getWithOffset(Offset), 2650 Ld->getOriginalAlign(), 2651 Ld->getMemOperand()->getFlags()); 2652 else 2653 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2654 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2655 Ld->getOriginalAlign(), 2656 Ld->getMemOperand()->getFlags()); 2657 DAG.makeEquivalentMemoryOrdering(Ld, V); 2658 2659 unsigned Opc = 2660 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2661 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2662 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2663 } 2664 2665 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2666 assert(Lane < (int)NumElts && "Unexpected lane!"); 2667 SDValue Gather = 2668 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2669 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2670 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2671 } 2672 } 2673 2674 ArrayRef<int> Mask = SVN->getMask(); 2675 2676 // Try to match as a slidedown. 2677 int SlideAmt = matchShuffleAsSlideDown(Mask); 2678 if (SlideAmt >= 0) { 2679 // TODO: Should we reduce the VL to account for the upper undef elements? 2680 // Requires additional vsetvlis, but might be faster to execute. 2681 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2682 SDValue SlideDown = 2683 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 2684 DAG.getUNDEF(ContainerVT), V1, 2685 DAG.getConstant(SlideAmt, DL, XLenVT), 2686 TrueMask, VL); 2687 return convertFromScalableVector(VT, SlideDown, DAG, Subtarget); 2688 } 2689 2690 // Match shuffles that concatenate two vectors, rotate the concatenation, 2691 // and then extract the original number of elements from the rotated result. 2692 // This is equivalent to vector.splice or X86's PALIGNR instruction. Lower 2693 // it to a SLIDEDOWN and a SLIDEUP. 2694 // FIXME: We don't really need it to be a concatenation. We just need two 2695 // regions with contiguous elements that need to be shifted down and up. 2696 int Rotation = isElementRotate(V1, V2, Mask); 2697 if (Rotation > 0) { 2698 // We found a rotation. We need to slide V1 down by Rotation. Using 2699 // (NumElts - Rotation) for VL. Then we need to slide V2 up by 2700 // (NumElts - Rotation) using NumElts for VL. 2701 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2702 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2703 2704 unsigned InvRotate = NumElts - Rotation; 2705 SDValue SlideDown = 2706 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 2707 DAG.getUNDEF(ContainerVT), V2, 2708 DAG.getConstant(Rotation, DL, XLenVT), 2709 TrueMask, DAG.getConstant(InvRotate, DL, XLenVT)); 2710 SDValue SlideUp = 2711 DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, SlideDown, V1, 2712 DAG.getConstant(InvRotate, DL, XLenVT), 2713 TrueMask, VL); 2714 return convertFromScalableVector(VT, SlideUp, DAG, Subtarget); 2715 } 2716 2717 // Detect an interleave shuffle and lower to 2718 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2719 bool SwapSources; 2720 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2721 // Swap sources if needed. 2722 if (SwapSources) 2723 std::swap(V1, V2); 2724 2725 // Extract the lower half of the vectors. 2726 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2727 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2728 DAG.getConstant(0, DL, XLenVT)); 2729 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2730 DAG.getConstant(0, DL, XLenVT)); 2731 2732 // Double the element width and halve the number of elements in an int type. 2733 unsigned EltBits = VT.getScalarSizeInBits(); 2734 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2735 MVT WideIntVT = 2736 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2737 // Convert this to a scalable vector. We need to base this on the 2738 // destination size to ensure there's always a type with a smaller LMUL. 2739 MVT WideIntContainerVT = 2740 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2741 2742 // Convert sources to scalable vectors with the same element count as the 2743 // larger type. 2744 MVT HalfContainerVT = MVT::getVectorVT( 2745 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2746 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2747 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2748 2749 // Cast sources to integer. 2750 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2751 MVT IntHalfVT = 2752 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2753 V1 = DAG.getBitcast(IntHalfVT, V1); 2754 V2 = DAG.getBitcast(IntHalfVT, V2); 2755 2756 // Freeze V2 since we use it twice and we need to be sure that the add and 2757 // multiply see the same value. 2758 V2 = DAG.getNode(ISD::FREEZE, DL, IntHalfVT, V2); 2759 2760 // Recreate TrueMask using the widened type's element count. 2761 MVT MaskVT = 2762 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2763 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2764 2765 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2766 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2767 V2, TrueMask, VL); 2768 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2769 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2770 DAG.getAllOnesConstant(DL, XLenVT)); 2771 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2772 V2, Multiplier, TrueMask, VL); 2773 // Add the new copies to our previous addition giving us 2^eltbits copies of 2774 // V2. This is equivalent to shifting V2 left by eltbits. This should 2775 // combine with the vwmulu.vv above to form vwmaccu.vv. 2776 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2777 TrueMask, VL); 2778 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2779 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2780 // vector VT. 2781 ContainerVT = 2782 MVT::getVectorVT(VT.getVectorElementType(), 2783 WideIntContainerVT.getVectorElementCount() * 2); 2784 Add = DAG.getBitcast(ContainerVT, Add); 2785 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2786 } 2787 2788 // Detect shuffles which can be re-expressed as vector selects; these are 2789 // shuffles in which each element in the destination is taken from an element 2790 // at the corresponding index in either source vectors. 2791 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2792 int MaskIndex = MaskIdx.value(); 2793 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2794 }); 2795 2796 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2797 2798 SmallVector<SDValue> MaskVals; 2799 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2800 // merged with a second vrgather. 2801 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2802 2803 // By default we preserve the original operand order, and use a mask to 2804 // select LHS as true and RHS as false. However, since RVV vector selects may 2805 // feature splats but only on the LHS, we may choose to invert our mask and 2806 // instead select between RHS and LHS. 2807 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2808 bool InvertMask = IsSelect == SwapOps; 2809 2810 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2811 // half. 2812 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2813 2814 // Now construct the mask that will be used by the vselect or blended 2815 // vrgather operation. For vrgathers, construct the appropriate indices into 2816 // each vector. 2817 for (int MaskIndex : Mask) { 2818 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2819 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2820 if (!IsSelect) { 2821 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2822 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2823 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2824 : DAG.getUNDEF(XLenVT)); 2825 GatherIndicesRHS.push_back( 2826 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2827 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2828 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2829 ++LHSIndexCounts[MaskIndex]; 2830 if (!IsLHSOrUndefIndex) 2831 ++RHSIndexCounts[MaskIndex - NumElts]; 2832 } 2833 } 2834 2835 if (SwapOps) { 2836 std::swap(V1, V2); 2837 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2838 } 2839 2840 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2841 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2842 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2843 2844 if (IsSelect) 2845 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2846 2847 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2848 // On such a large vector we're unable to use i8 as the index type. 2849 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2850 // may involve vector splitting if we're already at LMUL=8, or our 2851 // user-supplied maximum fixed-length LMUL. 2852 return SDValue(); 2853 } 2854 2855 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2856 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2857 MVT IndexVT = VT.changeTypeToInteger(); 2858 // Since we can't introduce illegal index types at this stage, use i16 and 2859 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2860 // than XLenVT. 2861 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2862 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2863 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2864 } 2865 2866 MVT IndexContainerVT = 2867 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2868 2869 SDValue Gather; 2870 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2871 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2872 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2873 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2874 } else { 2875 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2876 // If only one index is used, we can use a "splat" vrgather. 2877 // TODO: We can splat the most-common index and fix-up any stragglers, if 2878 // that's beneficial. 2879 if (LHSIndexCounts.size() == 1) { 2880 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2881 Gather = 2882 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2883 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2884 } else { 2885 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2886 LHSIndices = 2887 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2888 2889 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2890 TrueMask, VL); 2891 } 2892 } 2893 2894 // If a second vector operand is used by this shuffle, blend it in with an 2895 // additional vrgather. 2896 if (!V2.isUndef()) { 2897 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2898 // If only one index is used, we can use a "splat" vrgather. 2899 // TODO: We can splat the most-common index and fix-up any stragglers, if 2900 // that's beneficial. 2901 if (RHSIndexCounts.size() == 1) { 2902 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2903 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2904 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2905 } else { 2906 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2907 RHSIndices = 2908 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2909 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2910 VL); 2911 } 2912 2913 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2914 SelectMask = 2915 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2916 2917 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2918 Gather, VL); 2919 } 2920 2921 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2922 } 2923 2924 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2925 // Support splats for any type. These should type legalize well. 2926 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2927 return true; 2928 2929 // Only support legal VTs for other shuffles for now. 2930 if (!isTypeLegal(VT)) 2931 return false; 2932 2933 MVT SVT = VT.getSimpleVT(); 2934 2935 bool SwapSources; 2936 return (matchShuffleAsSlideDown(M) >= 0) || 2937 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2938 } 2939 2940 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2941 SDLoc DL, SelectionDAG &DAG, 2942 const RISCVSubtarget &Subtarget) { 2943 if (VT.isScalableVector()) 2944 return DAG.getFPExtendOrRound(Op, DL, VT); 2945 assert(VT.isFixedLengthVector() && 2946 "Unexpected value type for RVV FP extend/round lowering"); 2947 SDValue Mask, VL; 2948 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2949 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2950 ? RISCVISD::FP_EXTEND_VL 2951 : RISCVISD::FP_ROUND_VL; 2952 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2953 } 2954 2955 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2956 // the exponent. 2957 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2958 MVT VT = Op.getSimpleValueType(); 2959 unsigned EltSize = VT.getScalarSizeInBits(); 2960 SDValue Src = Op.getOperand(0); 2961 SDLoc DL(Op); 2962 2963 // We need a FP type that can represent the value. 2964 // TODO: Use f16 for i8 when possible? 2965 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2966 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2967 2968 // Legal types should have been checked in the RISCVTargetLowering 2969 // constructor. 2970 // TODO: Splitting may make sense in some cases. 2971 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2972 "Expected legal float type!"); 2973 2974 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2975 // The trailing zero count is equal to log2 of this single bit value. 2976 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2977 SDValue Neg = 2978 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2979 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2980 } 2981 2982 // We have a legal FP type, convert to it. 2983 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2984 // Bitcast to integer and shift the exponent to the LSB. 2985 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2986 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2987 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2988 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2989 DAG.getConstant(ShiftAmt, DL, IntVT)); 2990 // Truncate back to original type to allow vnsrl. 2991 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2992 // The exponent contains log2 of the value in biased form. 2993 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2994 2995 // For trailing zeros, we just need to subtract the bias. 2996 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2997 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2998 DAG.getConstant(ExponentBias, DL, VT)); 2999 3000 // For leading zeros, we need to remove the bias and convert from log2 to 3001 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 3002 unsigned Adjust = ExponentBias + (EltSize - 1); 3003 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 3004 } 3005 3006 // While RVV has alignment restrictions, we should always be able to load as a 3007 // legal equivalently-sized byte-typed vector instead. This method is 3008 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 3009 // the load is already correctly-aligned, it returns SDValue(). 3010 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 3011 SelectionDAG &DAG) const { 3012 auto *Load = cast<LoadSDNode>(Op); 3013 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 3014 3015 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3016 Load->getMemoryVT(), 3017 *Load->getMemOperand())) 3018 return SDValue(); 3019 3020 SDLoc DL(Op); 3021 MVT VT = Op.getSimpleValueType(); 3022 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3023 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3024 "Unexpected unaligned RVV load type"); 3025 MVT NewVT = 3026 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3027 assert(NewVT.isValid() && 3028 "Expecting equally-sized RVV vector types to be legal"); 3029 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 3030 Load->getPointerInfo(), Load->getOriginalAlign(), 3031 Load->getMemOperand()->getFlags()); 3032 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 3033 } 3034 3035 // While RVV has alignment restrictions, we should always be able to store as a 3036 // legal equivalently-sized byte-typed vector instead. This method is 3037 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 3038 // returns SDValue() if the store is already correctly aligned. 3039 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 3040 SelectionDAG &DAG) const { 3041 auto *Store = cast<StoreSDNode>(Op); 3042 assert(Store && Store->getValue().getValueType().isVector() && 3043 "Expected vector store"); 3044 3045 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3046 Store->getMemoryVT(), 3047 *Store->getMemOperand())) 3048 return SDValue(); 3049 3050 SDLoc DL(Op); 3051 SDValue StoredVal = Store->getValue(); 3052 MVT VT = StoredVal.getSimpleValueType(); 3053 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3054 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3055 "Unexpected unaligned RVV store type"); 3056 MVT NewVT = 3057 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3058 assert(NewVT.isValid() && 3059 "Expecting equally-sized RVV vector types to be legal"); 3060 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3061 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3062 Store->getPointerInfo(), Store->getOriginalAlign(), 3063 Store->getMemOperand()->getFlags()); 3064 } 3065 3066 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3067 SelectionDAG &DAG) const { 3068 switch (Op.getOpcode()) { 3069 default: 3070 report_fatal_error("unimplemented operand"); 3071 case ISD::GlobalAddress: 3072 return lowerGlobalAddress(Op, DAG); 3073 case ISD::BlockAddress: 3074 return lowerBlockAddress(Op, DAG); 3075 case ISD::ConstantPool: 3076 return lowerConstantPool(Op, DAG); 3077 case ISD::JumpTable: 3078 return lowerJumpTable(Op, DAG); 3079 case ISD::GlobalTLSAddress: 3080 return lowerGlobalTLSAddress(Op, DAG); 3081 case ISD::SELECT: 3082 return lowerSELECT(Op, DAG); 3083 case ISD::BRCOND: 3084 return lowerBRCOND(Op, DAG); 3085 case ISD::VASTART: 3086 return lowerVASTART(Op, DAG); 3087 case ISD::FRAMEADDR: 3088 return lowerFRAMEADDR(Op, DAG); 3089 case ISD::RETURNADDR: 3090 return lowerRETURNADDR(Op, DAG); 3091 case ISD::SHL_PARTS: 3092 return lowerShiftLeftParts(Op, DAG); 3093 case ISD::SRA_PARTS: 3094 return lowerShiftRightParts(Op, DAG, true); 3095 case ISD::SRL_PARTS: 3096 return lowerShiftRightParts(Op, DAG, false); 3097 case ISD::BITCAST: { 3098 SDLoc DL(Op); 3099 EVT VT = Op.getValueType(); 3100 SDValue Op0 = Op.getOperand(0); 3101 EVT Op0VT = Op0.getValueType(); 3102 MVT XLenVT = Subtarget.getXLenVT(); 3103 if (VT.isFixedLengthVector()) { 3104 // We can handle fixed length vector bitcasts with a simple replacement 3105 // in isel. 3106 if (Op0VT.isFixedLengthVector()) 3107 return Op; 3108 // When bitcasting from scalar to fixed-length vector, insert the scalar 3109 // into a one-element vector of the result type, and perform a vector 3110 // bitcast. 3111 if (!Op0VT.isVector()) { 3112 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3113 if (!isTypeLegal(BVT)) 3114 return SDValue(); 3115 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3116 DAG.getUNDEF(BVT), Op0, 3117 DAG.getConstant(0, DL, XLenVT))); 3118 } 3119 return SDValue(); 3120 } 3121 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3122 // thus: bitcast the vector to a one-element vector type whose element type 3123 // is the same as the result type, and extract the first element. 3124 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3125 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3126 if (!isTypeLegal(BVT)) 3127 return SDValue(); 3128 SDValue BVec = DAG.getBitcast(BVT, Op0); 3129 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3130 DAG.getConstant(0, DL, XLenVT)); 3131 } 3132 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3133 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3134 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3135 return FPConv; 3136 } 3137 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3138 Subtarget.hasStdExtF()) { 3139 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3140 SDValue FPConv = 3141 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3142 return FPConv; 3143 } 3144 return SDValue(); 3145 } 3146 case ISD::INTRINSIC_WO_CHAIN: 3147 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3148 case ISD::INTRINSIC_W_CHAIN: 3149 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3150 case ISD::INTRINSIC_VOID: 3151 return LowerINTRINSIC_VOID(Op, DAG); 3152 case ISD::BSWAP: 3153 case ISD::BITREVERSE: { 3154 MVT VT = Op.getSimpleValueType(); 3155 SDLoc DL(Op); 3156 if (Subtarget.hasStdExtZbp()) { 3157 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3158 // Start with the maximum immediate value which is the bitwidth - 1. 3159 unsigned Imm = VT.getSizeInBits() - 1; 3160 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3161 if (Op.getOpcode() == ISD::BSWAP) 3162 Imm &= ~0x7U; 3163 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3164 DAG.getConstant(Imm, DL, VT)); 3165 } 3166 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3167 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3168 // Expand bitreverse to a bswap(rev8) followed by brev8. 3169 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3170 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3171 // as brev8 by an isel pattern. 3172 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3173 DAG.getConstant(7, DL, VT)); 3174 } 3175 case ISD::FSHL: 3176 case ISD::FSHR: { 3177 MVT VT = Op.getSimpleValueType(); 3178 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3179 SDLoc DL(Op); 3180 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3181 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3182 // accidentally setting the extra bit. 3183 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3184 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3185 DAG.getConstant(ShAmtWidth, DL, VT)); 3186 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3187 // instruction use different orders. fshl will return its first operand for 3188 // shift of zero, fshr will return its second operand. fsl and fsr both 3189 // return rs1 so the ISD nodes need to have different operand orders. 3190 // Shift amount is in rs2. 3191 SDValue Op0 = Op.getOperand(0); 3192 SDValue Op1 = Op.getOperand(1); 3193 unsigned Opc = RISCVISD::FSL; 3194 if (Op.getOpcode() == ISD::FSHR) { 3195 std::swap(Op0, Op1); 3196 Opc = RISCVISD::FSR; 3197 } 3198 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3199 } 3200 case ISD::TRUNCATE: { 3201 SDLoc DL(Op); 3202 MVT VT = Op.getSimpleValueType(); 3203 // Only custom-lower vector truncates 3204 if (!VT.isVector()) 3205 return Op; 3206 3207 // Truncates to mask types are handled differently 3208 if (VT.getVectorElementType() == MVT::i1) 3209 return lowerVectorMaskTrunc(Op, DAG); 3210 3211 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3212 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3213 // truncate by one power of two at a time. 3214 MVT DstEltVT = VT.getVectorElementType(); 3215 3216 SDValue Src = Op.getOperand(0); 3217 MVT SrcVT = Src.getSimpleValueType(); 3218 MVT SrcEltVT = SrcVT.getVectorElementType(); 3219 3220 assert(DstEltVT.bitsLT(SrcEltVT) && 3221 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3222 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3223 "Unexpected vector truncate lowering"); 3224 3225 MVT ContainerVT = SrcVT; 3226 if (SrcVT.isFixedLengthVector()) { 3227 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3228 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3229 } 3230 3231 SDValue Result = Src; 3232 SDValue Mask, VL; 3233 std::tie(Mask, VL) = 3234 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3235 LLVMContext &Context = *DAG.getContext(); 3236 const ElementCount Count = ContainerVT.getVectorElementCount(); 3237 do { 3238 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3239 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3240 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3241 Mask, VL); 3242 } while (SrcEltVT != DstEltVT); 3243 3244 if (SrcVT.isFixedLengthVector()) 3245 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3246 3247 return Result; 3248 } 3249 case ISD::ANY_EXTEND: 3250 case ISD::ZERO_EXTEND: 3251 if (Op.getOperand(0).getValueType().isVector() && 3252 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3253 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3254 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3255 case ISD::SIGN_EXTEND: 3256 if (Op.getOperand(0).getValueType().isVector() && 3257 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3258 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3259 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3260 case ISD::SPLAT_VECTOR_PARTS: 3261 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3262 case ISD::INSERT_VECTOR_ELT: 3263 return lowerINSERT_VECTOR_ELT(Op, DAG); 3264 case ISD::EXTRACT_VECTOR_ELT: 3265 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3266 case ISD::VSCALE: { 3267 MVT VT = Op.getSimpleValueType(); 3268 SDLoc DL(Op); 3269 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3270 // We define our scalable vector types for lmul=1 to use a 64 bit known 3271 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3272 // vscale as VLENB / 8. 3273 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3274 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3275 report_fatal_error("Support for VLEN==32 is incomplete."); 3276 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3277 // We assume VLENB is a multiple of 8. We manually choose the best shift 3278 // here because SimplifyDemandedBits isn't always able to simplify it. 3279 uint64_t Val = Op.getConstantOperandVal(0); 3280 if (isPowerOf2_64(Val)) { 3281 uint64_t Log2 = Log2_64(Val); 3282 if (Log2 < 3) 3283 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3284 DAG.getConstant(3 - Log2, DL, VT)); 3285 if (Log2 > 3) 3286 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3287 DAG.getConstant(Log2 - 3, DL, VT)); 3288 return VLENB; 3289 } 3290 // If the multiplier is a multiple of 8, scale it down to avoid needing 3291 // to shift the VLENB value. 3292 if ((Val % 8) == 0) 3293 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3294 DAG.getConstant(Val / 8, DL, VT)); 3295 } 3296 3297 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3298 DAG.getConstant(3, DL, VT)); 3299 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3300 } 3301 case ISD::FPOWI: { 3302 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3303 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3304 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3305 Op.getOperand(1).getValueType() == MVT::i32) { 3306 SDLoc DL(Op); 3307 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3308 SDValue Powi = 3309 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3310 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3311 DAG.getIntPtrConstant(0, DL)); 3312 } 3313 return SDValue(); 3314 } 3315 case ISD::FP_EXTEND: { 3316 // RVV can only do fp_extend to types double the size as the source. We 3317 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3318 // via f32. 3319 SDLoc DL(Op); 3320 MVT VT = Op.getSimpleValueType(); 3321 SDValue Src = Op.getOperand(0); 3322 MVT SrcVT = Src.getSimpleValueType(); 3323 3324 // Prepare any fixed-length vector operands. 3325 MVT ContainerVT = VT; 3326 if (SrcVT.isFixedLengthVector()) { 3327 ContainerVT = getContainerForFixedLengthVector(VT); 3328 MVT SrcContainerVT = 3329 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3330 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3331 } 3332 3333 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3334 SrcVT.getVectorElementType() != MVT::f16) { 3335 // For scalable vectors, we only need to close the gap between 3336 // vXf16->vXf64. 3337 if (!VT.isFixedLengthVector()) 3338 return Op; 3339 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3340 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3341 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3342 } 3343 3344 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3345 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3346 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3347 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3348 3349 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3350 DL, DAG, Subtarget); 3351 if (VT.isFixedLengthVector()) 3352 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3353 return Extend; 3354 } 3355 case ISD::FP_ROUND: { 3356 // RVV can only do fp_round to types half the size as the source. We 3357 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3358 // conversion instruction. 3359 SDLoc DL(Op); 3360 MVT VT = Op.getSimpleValueType(); 3361 SDValue Src = Op.getOperand(0); 3362 MVT SrcVT = Src.getSimpleValueType(); 3363 3364 // Prepare any fixed-length vector operands. 3365 MVT ContainerVT = VT; 3366 if (VT.isFixedLengthVector()) { 3367 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3368 ContainerVT = 3369 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3370 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3371 } 3372 3373 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3374 SrcVT.getVectorElementType() != MVT::f64) { 3375 // For scalable vectors, we only need to close the gap between 3376 // vXf64<->vXf16. 3377 if (!VT.isFixedLengthVector()) 3378 return Op; 3379 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3380 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3381 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3382 } 3383 3384 SDValue Mask, VL; 3385 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3386 3387 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3388 SDValue IntermediateRound = 3389 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3390 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3391 DL, DAG, Subtarget); 3392 3393 if (VT.isFixedLengthVector()) 3394 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3395 return Round; 3396 } 3397 case ISD::FP_TO_SINT: 3398 case ISD::FP_TO_UINT: 3399 case ISD::SINT_TO_FP: 3400 case ISD::UINT_TO_FP: { 3401 // RVV can only do fp<->int conversions to types half/double the size as 3402 // the source. We custom-lower any conversions that do two hops into 3403 // sequences. 3404 MVT VT = Op.getSimpleValueType(); 3405 if (!VT.isVector()) 3406 return Op; 3407 SDLoc DL(Op); 3408 SDValue Src = Op.getOperand(0); 3409 MVT EltVT = VT.getVectorElementType(); 3410 MVT SrcVT = Src.getSimpleValueType(); 3411 MVT SrcEltVT = SrcVT.getVectorElementType(); 3412 unsigned EltSize = EltVT.getSizeInBits(); 3413 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3414 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3415 "Unexpected vector element types"); 3416 3417 bool IsInt2FP = SrcEltVT.isInteger(); 3418 // Widening conversions 3419 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 3420 if (IsInt2FP) { 3421 // Do a regular integer sign/zero extension then convert to float. 3422 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 3423 VT.getVectorElementCount()); 3424 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3425 ? ISD::ZERO_EXTEND 3426 : ISD::SIGN_EXTEND; 3427 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3428 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3429 } 3430 // FP2Int 3431 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3432 // Do one doubling fp_extend then complete the operation by converting 3433 // to int. 3434 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3435 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3436 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3437 } 3438 3439 // Narrowing conversions 3440 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 3441 if (IsInt2FP) { 3442 // One narrowing int_to_fp, then an fp_round. 3443 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3444 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3445 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3446 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3447 } 3448 // FP2Int 3449 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3450 // representable by the integer, the result is poison. 3451 MVT IVecVT = 3452 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3453 VT.getVectorElementCount()); 3454 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3455 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3456 } 3457 3458 // Scalable vectors can exit here. Patterns will handle equally-sized 3459 // conversions halving/doubling ones. 3460 if (!VT.isFixedLengthVector()) 3461 return Op; 3462 3463 // For fixed-length vectors we lower to a custom "VL" node. 3464 unsigned RVVOpc = 0; 3465 switch (Op.getOpcode()) { 3466 default: 3467 llvm_unreachable("Impossible opcode"); 3468 case ISD::FP_TO_SINT: 3469 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3470 break; 3471 case ISD::FP_TO_UINT: 3472 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3473 break; 3474 case ISD::SINT_TO_FP: 3475 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3476 break; 3477 case ISD::UINT_TO_FP: 3478 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3479 break; 3480 } 3481 3482 MVT ContainerVT, SrcContainerVT; 3483 // Derive the reference container type from the larger vector type. 3484 if (SrcEltSize > EltSize) { 3485 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3486 ContainerVT = 3487 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3488 } else { 3489 ContainerVT = getContainerForFixedLengthVector(VT); 3490 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3491 } 3492 3493 SDValue Mask, VL; 3494 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3495 3496 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3497 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3498 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3499 } 3500 case ISD::FP_TO_SINT_SAT: 3501 case ISD::FP_TO_UINT_SAT: 3502 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3503 case ISD::FTRUNC: 3504 case ISD::FCEIL: 3505 case ISD::FFLOOR: 3506 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3507 case ISD::FROUND: 3508 return lowerFROUND(Op, DAG); 3509 case ISD::VECREDUCE_ADD: 3510 case ISD::VECREDUCE_UMAX: 3511 case ISD::VECREDUCE_SMAX: 3512 case ISD::VECREDUCE_UMIN: 3513 case ISD::VECREDUCE_SMIN: 3514 return lowerVECREDUCE(Op, DAG); 3515 case ISD::VECREDUCE_AND: 3516 case ISD::VECREDUCE_OR: 3517 case ISD::VECREDUCE_XOR: 3518 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3519 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3520 return lowerVECREDUCE(Op, DAG); 3521 case ISD::VECREDUCE_FADD: 3522 case ISD::VECREDUCE_SEQ_FADD: 3523 case ISD::VECREDUCE_FMIN: 3524 case ISD::VECREDUCE_FMAX: 3525 return lowerFPVECREDUCE(Op, DAG); 3526 case ISD::VP_REDUCE_ADD: 3527 case ISD::VP_REDUCE_UMAX: 3528 case ISD::VP_REDUCE_SMAX: 3529 case ISD::VP_REDUCE_UMIN: 3530 case ISD::VP_REDUCE_SMIN: 3531 case ISD::VP_REDUCE_FADD: 3532 case ISD::VP_REDUCE_SEQ_FADD: 3533 case ISD::VP_REDUCE_FMIN: 3534 case ISD::VP_REDUCE_FMAX: 3535 return lowerVPREDUCE(Op, DAG); 3536 case ISD::VP_REDUCE_AND: 3537 case ISD::VP_REDUCE_OR: 3538 case ISD::VP_REDUCE_XOR: 3539 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3540 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3541 return lowerVPREDUCE(Op, DAG); 3542 case ISD::INSERT_SUBVECTOR: 3543 return lowerINSERT_SUBVECTOR(Op, DAG); 3544 case ISD::EXTRACT_SUBVECTOR: 3545 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3546 case ISD::STEP_VECTOR: 3547 return lowerSTEP_VECTOR(Op, DAG); 3548 case ISD::VECTOR_REVERSE: 3549 return lowerVECTOR_REVERSE(Op, DAG); 3550 case ISD::BUILD_VECTOR: 3551 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3552 case ISD::SPLAT_VECTOR: 3553 if (Op.getValueType().getVectorElementType() == MVT::i1) 3554 return lowerVectorMaskSplat(Op, DAG); 3555 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3556 case ISD::VECTOR_SHUFFLE: 3557 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3558 case ISD::CONCAT_VECTORS: { 3559 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3560 // better than going through the stack, as the default expansion does. 3561 SDLoc DL(Op); 3562 MVT VT = Op.getSimpleValueType(); 3563 unsigned NumOpElts = 3564 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3565 SDValue Vec = DAG.getUNDEF(VT); 3566 for (const auto &OpIdx : enumerate(Op->ops())) { 3567 SDValue SubVec = OpIdx.value(); 3568 // Don't insert undef subvectors. 3569 if (SubVec.isUndef()) 3570 continue; 3571 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3572 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3573 } 3574 return Vec; 3575 } 3576 case ISD::LOAD: 3577 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3578 return V; 3579 if (Op.getValueType().isFixedLengthVector()) 3580 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3581 return Op; 3582 case ISD::STORE: 3583 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3584 return V; 3585 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3586 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3587 return Op; 3588 case ISD::MLOAD: 3589 case ISD::VP_LOAD: 3590 return lowerMaskedLoad(Op, DAG); 3591 case ISD::MSTORE: 3592 case ISD::VP_STORE: 3593 return lowerMaskedStore(Op, DAG); 3594 case ISD::SETCC: 3595 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3596 case ISD::ADD: 3597 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3598 case ISD::SUB: 3599 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3600 case ISD::MUL: 3601 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3602 case ISD::MULHS: 3603 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3604 case ISD::MULHU: 3605 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3606 case ISD::AND: 3607 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3608 RISCVISD::AND_VL); 3609 case ISD::OR: 3610 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3611 RISCVISD::OR_VL); 3612 case ISD::XOR: 3613 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3614 RISCVISD::XOR_VL); 3615 case ISD::SDIV: 3616 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3617 case ISD::SREM: 3618 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3619 case ISD::UDIV: 3620 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3621 case ISD::UREM: 3622 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3623 case ISD::SHL: 3624 case ISD::SRA: 3625 case ISD::SRL: 3626 if (Op.getSimpleValueType().isFixedLengthVector()) 3627 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3628 // This can be called for an i32 shift amount that needs to be promoted. 3629 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3630 "Unexpected custom legalisation"); 3631 return SDValue(); 3632 case ISD::SADDSAT: 3633 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3634 case ISD::UADDSAT: 3635 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3636 case ISD::SSUBSAT: 3637 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3638 case ISD::USUBSAT: 3639 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3640 case ISD::FADD: 3641 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3642 case ISD::FSUB: 3643 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3644 case ISD::FMUL: 3645 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3646 case ISD::FDIV: 3647 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3648 case ISD::FNEG: 3649 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3650 case ISD::FABS: 3651 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3652 case ISD::FSQRT: 3653 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3654 case ISD::FMA: 3655 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3656 case ISD::SMIN: 3657 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3658 case ISD::SMAX: 3659 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3660 case ISD::UMIN: 3661 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3662 case ISD::UMAX: 3663 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3664 case ISD::FMINNUM: 3665 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3666 case ISD::FMAXNUM: 3667 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3668 case ISD::ABS: 3669 return lowerABS(Op, DAG); 3670 case ISD::CTLZ_ZERO_UNDEF: 3671 case ISD::CTTZ_ZERO_UNDEF: 3672 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3673 case ISD::VSELECT: 3674 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3675 case ISD::FCOPYSIGN: 3676 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3677 case ISD::MGATHER: 3678 case ISD::VP_GATHER: 3679 return lowerMaskedGather(Op, DAG); 3680 case ISD::MSCATTER: 3681 case ISD::VP_SCATTER: 3682 return lowerMaskedScatter(Op, DAG); 3683 case ISD::FLT_ROUNDS_: 3684 return lowerGET_ROUNDING(Op, DAG); 3685 case ISD::SET_ROUNDING: 3686 return lowerSET_ROUNDING(Op, DAG); 3687 case ISD::VP_SELECT: 3688 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3689 case ISD::VP_MERGE: 3690 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3691 case ISD::VP_ADD: 3692 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3693 case ISD::VP_SUB: 3694 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3695 case ISD::VP_MUL: 3696 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3697 case ISD::VP_SDIV: 3698 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3699 case ISD::VP_UDIV: 3700 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3701 case ISD::VP_SREM: 3702 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3703 case ISD::VP_UREM: 3704 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3705 case ISD::VP_AND: 3706 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3707 case ISD::VP_OR: 3708 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3709 case ISD::VP_XOR: 3710 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3711 case ISD::VP_ASHR: 3712 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3713 case ISD::VP_LSHR: 3714 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3715 case ISD::VP_SHL: 3716 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3717 case ISD::VP_FADD: 3718 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3719 case ISD::VP_FSUB: 3720 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3721 case ISD::VP_FMUL: 3722 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3723 case ISD::VP_FDIV: 3724 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3725 case ISD::VP_FNEG: 3726 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3727 case ISD::VP_FMA: 3728 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3729 } 3730 } 3731 3732 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3733 SelectionDAG &DAG, unsigned Flags) { 3734 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3735 } 3736 3737 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3738 SelectionDAG &DAG, unsigned Flags) { 3739 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3740 Flags); 3741 } 3742 3743 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3744 SelectionDAG &DAG, unsigned Flags) { 3745 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3746 N->getOffset(), Flags); 3747 } 3748 3749 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3750 SelectionDAG &DAG, unsigned Flags) { 3751 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3752 } 3753 3754 template <class NodeTy> 3755 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3756 bool IsLocal) const { 3757 SDLoc DL(N); 3758 EVT Ty = getPointerTy(DAG.getDataLayout()); 3759 3760 if (isPositionIndependent()) { 3761 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3762 if (IsLocal) 3763 // Use PC-relative addressing to access the symbol. This generates the 3764 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3765 // %pcrel_lo(auipc)). 3766 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3767 3768 // Use PC-relative addressing to access the GOT for this symbol, then load 3769 // the address from the GOT. This generates the pattern (PseudoLA sym), 3770 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3771 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3772 } 3773 3774 switch (getTargetMachine().getCodeModel()) { 3775 default: 3776 report_fatal_error("Unsupported code model for lowering"); 3777 case CodeModel::Small: { 3778 // Generate a sequence for accessing addresses within the first 2 GiB of 3779 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3780 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3781 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3782 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3783 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3784 } 3785 case CodeModel::Medium: { 3786 // Generate a sequence for accessing addresses within any 2GiB range within 3787 // the address space. This generates the pattern (PseudoLLA sym), which 3788 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3789 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3790 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3791 } 3792 } 3793 } 3794 3795 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3796 SelectionDAG &DAG) const { 3797 SDLoc DL(Op); 3798 EVT Ty = Op.getValueType(); 3799 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3800 int64_t Offset = N->getOffset(); 3801 MVT XLenVT = Subtarget.getXLenVT(); 3802 3803 const GlobalValue *GV = N->getGlobal(); 3804 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3805 SDValue Addr = getAddr(N, DAG, IsLocal); 3806 3807 // In order to maximise the opportunity for common subexpression elimination, 3808 // emit a separate ADD node for the global address offset instead of folding 3809 // it in the global address node. Later peephole optimisations may choose to 3810 // fold it back in when profitable. 3811 if (Offset != 0) 3812 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3813 DAG.getConstant(Offset, DL, XLenVT)); 3814 return Addr; 3815 } 3816 3817 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3818 SelectionDAG &DAG) const { 3819 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3820 3821 return getAddr(N, DAG); 3822 } 3823 3824 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3825 SelectionDAG &DAG) const { 3826 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3827 3828 return getAddr(N, DAG); 3829 } 3830 3831 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3832 SelectionDAG &DAG) const { 3833 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3834 3835 return getAddr(N, DAG); 3836 } 3837 3838 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3839 SelectionDAG &DAG, 3840 bool UseGOT) const { 3841 SDLoc DL(N); 3842 EVT Ty = getPointerTy(DAG.getDataLayout()); 3843 const GlobalValue *GV = N->getGlobal(); 3844 MVT XLenVT = Subtarget.getXLenVT(); 3845 3846 if (UseGOT) { 3847 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3848 // load the address from the GOT and add the thread pointer. This generates 3849 // the pattern (PseudoLA_TLS_IE sym), which expands to 3850 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3851 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3852 SDValue Load = 3853 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3854 3855 // Add the thread pointer. 3856 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3857 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3858 } 3859 3860 // Generate a sequence for accessing the address relative to the thread 3861 // pointer, with the appropriate adjustment for the thread pointer offset. 3862 // This generates the pattern 3863 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3864 SDValue AddrHi = 3865 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3866 SDValue AddrAdd = 3867 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3868 SDValue AddrLo = 3869 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3870 3871 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3872 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3873 SDValue MNAdd = SDValue( 3874 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3875 0); 3876 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3877 } 3878 3879 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3880 SelectionDAG &DAG) const { 3881 SDLoc DL(N); 3882 EVT Ty = getPointerTy(DAG.getDataLayout()); 3883 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3884 const GlobalValue *GV = N->getGlobal(); 3885 3886 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3887 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3888 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3889 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3890 SDValue Load = 3891 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3892 3893 // Prepare argument list to generate call. 3894 ArgListTy Args; 3895 ArgListEntry Entry; 3896 Entry.Node = Load; 3897 Entry.Ty = CallTy; 3898 Args.push_back(Entry); 3899 3900 // Setup call to __tls_get_addr. 3901 TargetLowering::CallLoweringInfo CLI(DAG); 3902 CLI.setDebugLoc(DL) 3903 .setChain(DAG.getEntryNode()) 3904 .setLibCallee(CallingConv::C, CallTy, 3905 DAG.getExternalSymbol("__tls_get_addr", Ty), 3906 std::move(Args)); 3907 3908 return LowerCallTo(CLI).first; 3909 } 3910 3911 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3912 SelectionDAG &DAG) const { 3913 SDLoc DL(Op); 3914 EVT Ty = Op.getValueType(); 3915 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3916 int64_t Offset = N->getOffset(); 3917 MVT XLenVT = Subtarget.getXLenVT(); 3918 3919 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3920 3921 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3922 CallingConv::GHC) 3923 report_fatal_error("In GHC calling convention TLS is not supported"); 3924 3925 SDValue Addr; 3926 switch (Model) { 3927 case TLSModel::LocalExec: 3928 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3929 break; 3930 case TLSModel::InitialExec: 3931 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3932 break; 3933 case TLSModel::LocalDynamic: 3934 case TLSModel::GeneralDynamic: 3935 Addr = getDynamicTLSAddr(N, DAG); 3936 break; 3937 } 3938 3939 // In order to maximise the opportunity for common subexpression elimination, 3940 // emit a separate ADD node for the global address offset instead of folding 3941 // it in the global address node. Later peephole optimisations may choose to 3942 // fold it back in when profitable. 3943 if (Offset != 0) 3944 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3945 DAG.getConstant(Offset, DL, XLenVT)); 3946 return Addr; 3947 } 3948 3949 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3950 SDValue CondV = Op.getOperand(0); 3951 SDValue TrueV = Op.getOperand(1); 3952 SDValue FalseV = Op.getOperand(2); 3953 SDLoc DL(Op); 3954 MVT VT = Op.getSimpleValueType(); 3955 MVT XLenVT = Subtarget.getXLenVT(); 3956 3957 // Lower vector SELECTs to VSELECTs by splatting the condition. 3958 if (VT.isVector()) { 3959 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3960 SDValue CondSplat = VT.isScalableVector() 3961 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3962 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3963 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3964 } 3965 3966 // If the result type is XLenVT and CondV is the output of a SETCC node 3967 // which also operated on XLenVT inputs, then merge the SETCC node into the 3968 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3969 // compare+branch instructions. i.e.: 3970 // (select (setcc lhs, rhs, cc), truev, falsev) 3971 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3972 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3973 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3974 SDValue LHS = CondV.getOperand(0); 3975 SDValue RHS = CondV.getOperand(1); 3976 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3977 ISD::CondCode CCVal = CC->get(); 3978 3979 // Special case for a select of 2 constants that have a diffence of 1. 3980 // Normally this is done by DAGCombine, but if the select is introduced by 3981 // type legalization or op legalization, we miss it. Restricting to SETLT 3982 // case for now because that is what signed saturating add/sub need. 3983 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3984 // but we would probably want to swap the true/false values if the condition 3985 // is SETGE/SETLE to avoid an XORI. 3986 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3987 CCVal == ISD::SETLT) { 3988 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3989 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3990 if (TrueVal - 1 == FalseVal) 3991 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3992 if (TrueVal + 1 == FalseVal) 3993 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3994 } 3995 3996 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3997 3998 SDValue TargetCC = DAG.getCondCode(CCVal); 3999 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 4000 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 4001 } 4002 4003 // Otherwise: 4004 // (select condv, truev, falsev) 4005 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 4006 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4007 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 4008 4009 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 4010 4011 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 4012 } 4013 4014 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4015 SDValue CondV = Op.getOperand(1); 4016 SDLoc DL(Op); 4017 MVT XLenVT = Subtarget.getXLenVT(); 4018 4019 if (CondV.getOpcode() == ISD::SETCC && 4020 CondV.getOperand(0).getValueType() == XLenVT) { 4021 SDValue LHS = CondV.getOperand(0); 4022 SDValue RHS = CondV.getOperand(1); 4023 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 4024 4025 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 4026 4027 SDValue TargetCC = DAG.getCondCode(CCVal); 4028 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 4029 LHS, RHS, TargetCC, Op.getOperand(2)); 4030 } 4031 4032 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 4033 CondV, DAG.getConstant(0, DL, XLenVT), 4034 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 4035 } 4036 4037 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 4038 MachineFunction &MF = DAG.getMachineFunction(); 4039 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 4040 4041 SDLoc DL(Op); 4042 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 4043 getPointerTy(MF.getDataLayout())); 4044 4045 // vastart just stores the address of the VarArgsFrameIndex slot into the 4046 // memory location argument. 4047 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4048 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 4049 MachinePointerInfo(SV)); 4050 } 4051 4052 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 4053 SelectionDAG &DAG) const { 4054 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4055 MachineFunction &MF = DAG.getMachineFunction(); 4056 MachineFrameInfo &MFI = MF.getFrameInfo(); 4057 MFI.setFrameAddressIsTaken(true); 4058 Register FrameReg = RI.getFrameRegister(MF); 4059 int XLenInBytes = Subtarget.getXLen() / 8; 4060 4061 EVT VT = Op.getValueType(); 4062 SDLoc DL(Op); 4063 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 4064 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4065 while (Depth--) { 4066 int Offset = -(XLenInBytes * 2); 4067 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 4068 DAG.getIntPtrConstant(Offset, DL)); 4069 FrameAddr = 4070 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 4071 } 4072 return FrameAddr; 4073 } 4074 4075 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 4076 SelectionDAG &DAG) const { 4077 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4078 MachineFunction &MF = DAG.getMachineFunction(); 4079 MachineFrameInfo &MFI = MF.getFrameInfo(); 4080 MFI.setReturnAddressIsTaken(true); 4081 MVT XLenVT = Subtarget.getXLenVT(); 4082 int XLenInBytes = Subtarget.getXLen() / 8; 4083 4084 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4085 return SDValue(); 4086 4087 EVT VT = Op.getValueType(); 4088 SDLoc DL(Op); 4089 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4090 if (Depth) { 4091 int Off = -XLenInBytes; 4092 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 4093 SDValue Offset = DAG.getConstant(Off, DL, VT); 4094 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4095 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4096 MachinePointerInfo()); 4097 } 4098 4099 // Return the value of the return address register, marking it an implicit 4100 // live-in. 4101 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 4102 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 4103 } 4104 4105 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4106 SelectionDAG &DAG) const { 4107 SDLoc DL(Op); 4108 SDValue Lo = Op.getOperand(0); 4109 SDValue Hi = Op.getOperand(1); 4110 SDValue Shamt = Op.getOperand(2); 4111 EVT VT = Lo.getValueType(); 4112 4113 // if Shamt-XLEN < 0: // Shamt < XLEN 4114 // Lo = Lo << Shamt 4115 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4116 // else: 4117 // Lo = 0 4118 // Hi = Lo << (Shamt-XLEN) 4119 4120 SDValue Zero = DAG.getConstant(0, DL, VT); 4121 SDValue One = DAG.getConstant(1, DL, VT); 4122 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4123 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4124 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4125 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4126 4127 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4128 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4129 SDValue ShiftRightLo = 4130 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4131 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4132 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4133 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4134 4135 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4136 4137 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4138 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4139 4140 SDValue Parts[2] = {Lo, Hi}; 4141 return DAG.getMergeValues(Parts, DL); 4142 } 4143 4144 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4145 bool IsSRA) const { 4146 SDLoc DL(Op); 4147 SDValue Lo = Op.getOperand(0); 4148 SDValue Hi = Op.getOperand(1); 4149 SDValue Shamt = Op.getOperand(2); 4150 EVT VT = Lo.getValueType(); 4151 4152 // SRA expansion: 4153 // if Shamt-XLEN < 0: // Shamt < XLEN 4154 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4155 // Hi = Hi >>s Shamt 4156 // else: 4157 // Lo = Hi >>s (Shamt-XLEN); 4158 // Hi = Hi >>s (XLEN-1) 4159 // 4160 // SRL expansion: 4161 // if Shamt-XLEN < 0: // Shamt < XLEN 4162 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4163 // Hi = Hi >>u Shamt 4164 // else: 4165 // Lo = Hi >>u (Shamt-XLEN); 4166 // Hi = 0; 4167 4168 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4169 4170 SDValue Zero = DAG.getConstant(0, DL, VT); 4171 SDValue One = DAG.getConstant(1, DL, VT); 4172 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4173 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4174 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4175 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4176 4177 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4178 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4179 SDValue ShiftLeftHi = 4180 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4181 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4182 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4183 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4184 SDValue HiFalse = 4185 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4186 4187 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4188 4189 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4190 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4191 4192 SDValue Parts[2] = {Lo, Hi}; 4193 return DAG.getMergeValues(Parts, DL); 4194 } 4195 4196 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4197 // legal equivalently-sized i8 type, so we can use that as a go-between. 4198 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4199 SelectionDAG &DAG) const { 4200 SDLoc DL(Op); 4201 MVT VT = Op.getSimpleValueType(); 4202 SDValue SplatVal = Op.getOperand(0); 4203 // All-zeros or all-ones splats are handled specially. 4204 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4205 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4206 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4207 } 4208 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4209 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4210 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4211 } 4212 MVT XLenVT = Subtarget.getXLenVT(); 4213 assert(SplatVal.getValueType() == XLenVT && 4214 "Unexpected type for i1 splat value"); 4215 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4216 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4217 DAG.getConstant(1, DL, XLenVT)); 4218 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4219 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4220 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4221 } 4222 4223 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4224 // illegal (currently only vXi64 RV32). 4225 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4226 // them to VMV_V_X_VL. 4227 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4228 SelectionDAG &DAG) const { 4229 SDLoc DL(Op); 4230 MVT VecVT = Op.getSimpleValueType(); 4231 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4232 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4233 4234 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4235 SDValue Lo = Op.getOperand(0); 4236 SDValue Hi = Op.getOperand(1); 4237 4238 if (VecVT.isFixedLengthVector()) { 4239 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4240 SDLoc DL(Op); 4241 SDValue Mask, VL; 4242 std::tie(Mask, VL) = 4243 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4244 4245 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 4246 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4247 } 4248 4249 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4250 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4251 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4252 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4253 // node in order to try and match RVV vector/scalar instructions. 4254 if ((LoC >> 31) == HiC) 4255 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, Lo, 4256 DAG.getRegister(RISCV::X0, MVT::i32)); 4257 } 4258 4259 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4260 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4261 isa<ConstantSDNode>(Hi.getOperand(1)) && 4262 Hi.getConstantOperandVal(1) == 31) 4263 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, Lo, 4264 DAG.getRegister(RISCV::X0, MVT::i32)); 4265 4266 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4267 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 4268 DAG.getRegister(RISCV::X0, MVT::i32)); 4269 } 4270 4271 // Custom-lower extensions from mask vectors by using a vselect either with 1 4272 // for zero/any-extension or -1 for sign-extension: 4273 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4274 // Note that any-extension is lowered identically to zero-extension. 4275 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4276 int64_t ExtTrueVal) const { 4277 SDLoc DL(Op); 4278 MVT VecVT = Op.getSimpleValueType(); 4279 SDValue Src = Op.getOperand(0); 4280 // Only custom-lower extensions from mask types 4281 assert(Src.getValueType().isVector() && 4282 Src.getValueType().getVectorElementType() == MVT::i1); 4283 4284 MVT XLenVT = Subtarget.getXLenVT(); 4285 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4286 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4287 4288 if (VecVT.isScalableVector()) { 4289 // Be careful not to introduce illegal scalar types at this stage, and be 4290 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 4291 // illegal and must be expanded. Since we know that the constants are 4292 // sign-extended 32-bit values, we use VMV_V_X_VL directly. 4293 bool IsRV32E64 = 4294 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 4295 4296 if (!IsRV32E64) { 4297 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 4298 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 4299 } else { 4300 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, SplatZero, 4301 DAG.getRegister(RISCV::X0, XLenVT)); 4302 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, SplatTrueVal, 4303 DAG.getRegister(RISCV::X0, XLenVT)); 4304 } 4305 4306 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4307 } 4308 4309 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4310 MVT I1ContainerVT = 4311 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4312 4313 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4314 4315 SDValue Mask, VL; 4316 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4317 4318 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 4319 SplatTrueVal = 4320 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 4321 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4322 SplatTrueVal, SplatZero, VL); 4323 4324 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4325 } 4326 4327 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4328 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4329 MVT ExtVT = Op.getSimpleValueType(); 4330 // Only custom-lower extensions from fixed-length vector types. 4331 if (!ExtVT.isFixedLengthVector()) 4332 return Op; 4333 MVT VT = Op.getOperand(0).getSimpleValueType(); 4334 // Grab the canonical container type for the extended type. Infer the smaller 4335 // type from that to ensure the same number of vector elements, as we know 4336 // the LMUL will be sufficient to hold the smaller type. 4337 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4338 // Get the extended container type manually to ensure the same number of 4339 // vector elements between source and dest. 4340 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4341 ContainerExtVT.getVectorElementCount()); 4342 4343 SDValue Op1 = 4344 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4345 4346 SDLoc DL(Op); 4347 SDValue Mask, VL; 4348 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4349 4350 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4351 4352 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4353 } 4354 4355 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4356 // setcc operation: 4357 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4358 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 4359 SelectionDAG &DAG) const { 4360 SDLoc DL(Op); 4361 EVT MaskVT = Op.getValueType(); 4362 // Only expect to custom-lower truncations to mask types 4363 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4364 "Unexpected type for vector mask lowering"); 4365 SDValue Src = Op.getOperand(0); 4366 MVT VecVT = Src.getSimpleValueType(); 4367 4368 // If this is a fixed vector, we need to convert it to a scalable vector. 4369 MVT ContainerVT = VecVT; 4370 if (VecVT.isFixedLengthVector()) { 4371 ContainerVT = getContainerForFixedLengthVector(VecVT); 4372 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4373 } 4374 4375 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4376 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4377 4378 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 4379 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 4380 4381 if (VecVT.isScalableVector()) { 4382 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 4383 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 4384 } 4385 4386 SDValue Mask, VL; 4387 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4388 4389 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4390 SDValue Trunc = 4391 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4392 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4393 DAG.getCondCode(ISD::SETNE), Mask, VL); 4394 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4395 } 4396 4397 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4398 // first position of a vector, and that vector is slid up to the insert index. 4399 // By limiting the active vector length to index+1 and merging with the 4400 // original vector (with an undisturbed tail policy for elements >= VL), we 4401 // achieve the desired result of leaving all elements untouched except the one 4402 // at VL-1, which is replaced with the desired value. 4403 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4404 SelectionDAG &DAG) const { 4405 SDLoc DL(Op); 4406 MVT VecVT = Op.getSimpleValueType(); 4407 SDValue Vec = Op.getOperand(0); 4408 SDValue Val = Op.getOperand(1); 4409 SDValue Idx = Op.getOperand(2); 4410 4411 if (VecVT.getVectorElementType() == MVT::i1) { 4412 // FIXME: For now we just promote to an i8 vector and insert into that, 4413 // but this is probably not optimal. 4414 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4415 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4416 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4417 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4418 } 4419 4420 MVT ContainerVT = VecVT; 4421 // If the operand is a fixed-length vector, convert to a scalable one. 4422 if (VecVT.isFixedLengthVector()) { 4423 ContainerVT = getContainerForFixedLengthVector(VecVT); 4424 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4425 } 4426 4427 MVT XLenVT = Subtarget.getXLenVT(); 4428 4429 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4430 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4431 // Even i64-element vectors on RV32 can be lowered without scalar 4432 // legalization if the most-significant 32 bits of the value are not affected 4433 // by the sign-extension of the lower 32 bits. 4434 // TODO: We could also catch sign extensions of a 32-bit value. 4435 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4436 const auto *CVal = cast<ConstantSDNode>(Val); 4437 if (isInt<32>(CVal->getSExtValue())) { 4438 IsLegalInsert = true; 4439 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4440 } 4441 } 4442 4443 SDValue Mask, VL; 4444 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4445 4446 SDValue ValInVec; 4447 4448 if (IsLegalInsert) { 4449 unsigned Opc = 4450 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4451 if (isNullConstant(Idx)) { 4452 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4453 if (!VecVT.isFixedLengthVector()) 4454 return Vec; 4455 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4456 } 4457 ValInVec = 4458 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4459 } else { 4460 // On RV32, i64-element vectors must be specially handled to place the 4461 // value at element 0, by using two vslide1up instructions in sequence on 4462 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4463 // this. 4464 SDValue One = DAG.getConstant(1, DL, XLenVT); 4465 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4466 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4467 MVT I32ContainerVT = 4468 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4469 SDValue I32Mask = 4470 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4471 // Limit the active VL to two. 4472 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4473 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4474 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4475 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 4476 InsertI64VL); 4477 // First slide in the hi value, then the lo in underneath it. 4478 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4479 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4480 I32Mask, InsertI64VL); 4481 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4482 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4483 I32Mask, InsertI64VL); 4484 // Bitcast back to the right container type. 4485 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4486 } 4487 4488 // Now that the value is in a vector, slide it into position. 4489 SDValue InsertVL = 4490 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4491 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4492 ValInVec, Idx, Mask, InsertVL); 4493 if (!VecVT.isFixedLengthVector()) 4494 return Slideup; 4495 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4496 } 4497 4498 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4499 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4500 // types this is done using VMV_X_S to allow us to glean information about the 4501 // sign bits of the result. 4502 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4503 SelectionDAG &DAG) const { 4504 SDLoc DL(Op); 4505 SDValue Idx = Op.getOperand(1); 4506 SDValue Vec = Op.getOperand(0); 4507 EVT EltVT = Op.getValueType(); 4508 MVT VecVT = Vec.getSimpleValueType(); 4509 MVT XLenVT = Subtarget.getXLenVT(); 4510 4511 if (VecVT.getVectorElementType() == MVT::i1) { 4512 if (VecVT.isFixedLengthVector()) { 4513 unsigned NumElts = VecVT.getVectorNumElements(); 4514 if (NumElts >= 8) { 4515 MVT WideEltVT; 4516 unsigned WidenVecLen; 4517 SDValue ExtractElementIdx; 4518 SDValue ExtractBitIdx; 4519 unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors(); 4520 MVT LargestEltVT = MVT::getIntegerVT( 4521 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4522 if (NumElts <= LargestEltVT.getSizeInBits()) { 4523 assert(isPowerOf2_32(NumElts) && 4524 "the number of elements should be power of 2"); 4525 WideEltVT = MVT::getIntegerVT(NumElts); 4526 WidenVecLen = 1; 4527 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4528 ExtractBitIdx = Idx; 4529 } else { 4530 WideEltVT = LargestEltVT; 4531 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4532 // extract element index = index / element width 4533 ExtractElementIdx = DAG.getNode( 4534 ISD::SRL, DL, XLenVT, Idx, 4535 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4536 // mask bit index = index % element width 4537 ExtractBitIdx = DAG.getNode( 4538 ISD::AND, DL, XLenVT, Idx, 4539 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4540 } 4541 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4542 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4543 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4544 Vec, ExtractElementIdx); 4545 // Extract the bit from GPR. 4546 SDValue ShiftRight = 4547 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4548 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4549 DAG.getConstant(1, DL, XLenVT)); 4550 } 4551 } 4552 // Otherwise, promote to an i8 vector and extract from that. 4553 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4554 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4555 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4556 } 4557 4558 // If this is a fixed vector, we need to convert it to a scalable vector. 4559 MVT ContainerVT = VecVT; 4560 if (VecVT.isFixedLengthVector()) { 4561 ContainerVT = getContainerForFixedLengthVector(VecVT); 4562 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4563 } 4564 4565 // If the index is 0, the vector is already in the right position. 4566 if (!isNullConstant(Idx)) { 4567 // Use a VL of 1 to avoid processing more elements than we need. 4568 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4569 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4570 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4571 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4572 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4573 } 4574 4575 if (!EltVT.isInteger()) { 4576 // Floating-point extracts are handled in TableGen. 4577 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4578 DAG.getConstant(0, DL, XLenVT)); 4579 } 4580 4581 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4582 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4583 } 4584 4585 // Some RVV intrinsics may claim that they want an integer operand to be 4586 // promoted or expanded. 4587 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 4588 const RISCVSubtarget &Subtarget) { 4589 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4590 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4591 "Unexpected opcode"); 4592 4593 if (!Subtarget.hasVInstructions()) 4594 return SDValue(); 4595 4596 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4597 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4598 SDLoc DL(Op); 4599 4600 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4601 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4602 if (!II || !II->hasSplatOperand()) 4603 return SDValue(); 4604 4605 unsigned SplatOp = II->SplatOperand + 1 + HasChain; 4606 assert(SplatOp < Op.getNumOperands()); 4607 4608 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4609 SDValue &ScalarOp = Operands[SplatOp]; 4610 MVT OpVT = ScalarOp.getSimpleValueType(); 4611 MVT XLenVT = Subtarget.getXLenVT(); 4612 4613 // If this isn't a scalar, or its type is XLenVT we're done. 4614 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4615 return SDValue(); 4616 4617 // Simplest case is that the operand needs to be promoted to XLenVT. 4618 if (OpVT.bitsLT(XLenVT)) { 4619 // If the operand is a constant, sign extend to increase our chances 4620 // of being able to use a .vi instruction. ANY_EXTEND would become a 4621 // a zero extend and the simm5 check in isel would fail. 4622 // FIXME: Should we ignore the upper bits in isel instead? 4623 unsigned ExtOpc = 4624 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4625 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4626 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4627 } 4628 4629 // Use the previous operand to get the vXi64 VT. The result might be a mask 4630 // VT for compares. Using the previous operand assumes that the previous 4631 // operand will never have a smaller element size than a scalar operand and 4632 // that a widening operation never uses SEW=64. 4633 // NOTE: If this fails the below assert, we can probably just find the 4634 // element count from any operand or result and use it to construct the VT. 4635 assert(II->SplatOperand > 0 && "Unexpected splat operand!"); 4636 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4637 4638 // The more complex case is when the scalar is larger than XLenVT. 4639 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4640 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4641 4642 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4643 // on the instruction to sign-extend since SEW>XLEN. 4644 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4645 if (isInt<32>(CVal->getSExtValue())) { 4646 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4647 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4648 } 4649 } 4650 4651 // We need to convert the scalar to a splat vector. 4652 // FIXME: Can we implicitly truncate the scalar if it is known to 4653 // be sign extended? 4654 SDValue VL = getVLOperand(Op); 4655 assert(VL.getValueType() == XLenVT); 4656 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 4657 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4658 } 4659 4660 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4661 SelectionDAG &DAG) const { 4662 unsigned IntNo = Op.getConstantOperandVal(0); 4663 SDLoc DL(Op); 4664 MVT XLenVT = Subtarget.getXLenVT(); 4665 4666 switch (IntNo) { 4667 default: 4668 break; // Don't custom lower most intrinsics. 4669 case Intrinsic::thread_pointer: { 4670 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4671 return DAG.getRegister(RISCV::X4, PtrVT); 4672 } 4673 case Intrinsic::riscv_orc_b: 4674 case Intrinsic::riscv_brev8: { 4675 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4676 unsigned Opc = 4677 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4678 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4679 DAG.getConstant(7, DL, XLenVT)); 4680 } 4681 case Intrinsic::riscv_grev: 4682 case Intrinsic::riscv_gorc: { 4683 unsigned Opc = 4684 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4685 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4686 } 4687 case Intrinsic::riscv_zip: 4688 case Intrinsic::riscv_unzip: { 4689 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4690 // For i32 the immdiate is 15. For i64 the immediate is 31. 4691 unsigned Opc = 4692 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4693 unsigned BitWidth = Op.getValueSizeInBits(); 4694 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4695 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4696 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4697 } 4698 case Intrinsic::riscv_shfl: 4699 case Intrinsic::riscv_unshfl: { 4700 unsigned Opc = 4701 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4702 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4703 } 4704 case Intrinsic::riscv_bcompress: 4705 case Intrinsic::riscv_bdecompress: { 4706 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4707 : RISCVISD::BDECOMPRESS; 4708 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4709 } 4710 case Intrinsic::riscv_bfp: 4711 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4712 Op.getOperand(2)); 4713 case Intrinsic::riscv_fsl: 4714 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4715 Op.getOperand(2), Op.getOperand(3)); 4716 case Intrinsic::riscv_fsr: 4717 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4718 Op.getOperand(2), Op.getOperand(3)); 4719 case Intrinsic::riscv_vmv_x_s: 4720 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4721 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4722 Op.getOperand(1)); 4723 case Intrinsic::riscv_vmv_v_x: 4724 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4725 Op.getSimpleValueType(), DL, DAG, Subtarget); 4726 case Intrinsic::riscv_vfmv_v_f: 4727 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4728 Op.getOperand(1), Op.getOperand(2)); 4729 case Intrinsic::riscv_vmv_s_x: { 4730 SDValue Scalar = Op.getOperand(2); 4731 4732 if (Scalar.getValueType().bitsLE(XLenVT)) { 4733 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4734 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4735 Op.getOperand(1), Scalar, Op.getOperand(3)); 4736 } 4737 4738 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4739 4740 // This is an i64 value that lives in two scalar registers. We have to 4741 // insert this in a convoluted way. First we build vXi64 splat containing 4742 // the/ two values that we assemble using some bit math. Next we'll use 4743 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4744 // to merge element 0 from our splat into the source vector. 4745 // FIXME: This is probably not the best way to do this, but it is 4746 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4747 // point. 4748 // sw lo, (a0) 4749 // sw hi, 4(a0) 4750 // vlse vX, (a0) 4751 // 4752 // vid.v vVid 4753 // vmseq.vx mMask, vVid, 0 4754 // vmerge.vvm vDest, vSrc, vVal, mMask 4755 MVT VT = Op.getSimpleValueType(); 4756 SDValue Vec = Op.getOperand(1); 4757 SDValue VL = getVLOperand(Op); 4758 4759 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 4760 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4761 DAG.getConstant(0, DL, MVT::i32), VL); 4762 4763 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4764 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4765 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4766 SDValue SelectCond = 4767 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4768 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4769 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4770 Vec, VL); 4771 } 4772 case Intrinsic::riscv_vslide1up: 4773 case Intrinsic::riscv_vslide1down: 4774 case Intrinsic::riscv_vslide1up_mask: 4775 case Intrinsic::riscv_vslide1down_mask: { 4776 // We need to special case these when the scalar is larger than XLen. 4777 unsigned NumOps = Op.getNumOperands(); 4778 bool IsMasked = NumOps == 7; 4779 SDValue Scalar = Op.getOperand(3); 4780 if (Scalar.getValueType().bitsLE(XLenVT)) 4781 break; 4782 4783 // Splatting a sign extended constant is fine. 4784 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4785 if (isInt<32>(CVal->getSExtValue())) 4786 break; 4787 4788 MVT VT = Op.getSimpleValueType(); 4789 assert(VT.getVectorElementType() == MVT::i64 && 4790 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4791 4792 // Convert the vector source to the equivalent nxvXi32 vector. 4793 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4794 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(2)); 4795 4796 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4797 DAG.getConstant(0, DL, XLenVT)); 4798 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4799 DAG.getConstant(1, DL, XLenVT)); 4800 4801 // Double the VL since we halved SEW. 4802 SDValue VL = getVLOperand(Op); 4803 SDValue I32VL = 4804 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4805 4806 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4807 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4808 4809 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4810 // instructions. 4811 SDValue Passthru = DAG.getBitcast(I32VT, Op.getOperand(1)); 4812 if (!IsMasked) { 4813 if (IntNo == Intrinsic::riscv_vslide1up) { 4814 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4815 ScalarHi, I32Mask, I32VL); 4816 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4817 ScalarLo, I32Mask, I32VL); 4818 } else { 4819 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4820 ScalarLo, I32Mask, I32VL); 4821 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4822 ScalarHi, I32Mask, I32VL); 4823 } 4824 } else { 4825 // TODO Those VSLIDE1 could be TAMA because we use vmerge to select 4826 // maskedoff 4827 SDValue Undef = DAG.getUNDEF(I32VT); 4828 if (IntNo == Intrinsic::riscv_vslide1up_mask) { 4829 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec, 4830 ScalarHi, I32Mask, I32VL); 4831 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec, 4832 ScalarLo, I32Mask, I32VL); 4833 } else { 4834 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec, 4835 ScalarLo, I32Mask, I32VL); 4836 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec, 4837 ScalarHi, I32Mask, I32VL); 4838 } 4839 } 4840 4841 // Convert back to nxvXi64. 4842 Vec = DAG.getBitcast(VT, Vec); 4843 4844 if (!IsMasked) 4845 return Vec; 4846 // Apply mask after the operation. 4847 SDValue Mask = Op.getOperand(NumOps - 3); 4848 SDValue MaskedOff = Op.getOperand(1); 4849 // Assume Policy operand is the last operand. 4850 uint64_t Policy = Op.getConstantOperandVal(NumOps - 1); 4851 // We don't need to select maskedoff if it's undef. 4852 if (MaskedOff.isUndef()) 4853 return Vec; 4854 // TAMU 4855 if (Policy == RISCVII::TAIL_AGNOSTIC) 4856 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4857 VL); 4858 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4859 // It's fine because vmerge does not care mask policy. 4860 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4861 } 4862 } 4863 4864 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4865 } 4866 4867 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4868 SelectionDAG &DAG) const { 4869 unsigned IntNo = Op.getConstantOperandVal(1); 4870 switch (IntNo) { 4871 default: 4872 break; 4873 case Intrinsic::riscv_masked_strided_load: { 4874 SDLoc DL(Op); 4875 MVT XLenVT = Subtarget.getXLenVT(); 4876 4877 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4878 // the selection of the masked intrinsics doesn't do this for us. 4879 SDValue Mask = Op.getOperand(5); 4880 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4881 4882 MVT VT = Op->getSimpleValueType(0); 4883 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4884 4885 SDValue PassThru = Op.getOperand(2); 4886 if (!IsUnmasked) { 4887 MVT MaskVT = 4888 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4889 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4890 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4891 } 4892 4893 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4894 4895 SDValue IntID = DAG.getTargetConstant( 4896 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4897 XLenVT); 4898 4899 auto *Load = cast<MemIntrinsicSDNode>(Op); 4900 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4901 if (IsUnmasked) 4902 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4903 else 4904 Ops.push_back(PassThru); 4905 Ops.push_back(Op.getOperand(3)); // Ptr 4906 Ops.push_back(Op.getOperand(4)); // Stride 4907 if (!IsUnmasked) 4908 Ops.push_back(Mask); 4909 Ops.push_back(VL); 4910 if (!IsUnmasked) { 4911 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4912 Ops.push_back(Policy); 4913 } 4914 4915 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4916 SDValue Result = 4917 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4918 Load->getMemoryVT(), Load->getMemOperand()); 4919 SDValue Chain = Result.getValue(1); 4920 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4921 return DAG.getMergeValues({Result, Chain}, DL); 4922 } 4923 } 4924 4925 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4926 } 4927 4928 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4929 SelectionDAG &DAG) const { 4930 unsigned IntNo = Op.getConstantOperandVal(1); 4931 switch (IntNo) { 4932 default: 4933 break; 4934 case Intrinsic::riscv_masked_strided_store: { 4935 SDLoc DL(Op); 4936 MVT XLenVT = Subtarget.getXLenVT(); 4937 4938 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4939 // the selection of the masked intrinsics doesn't do this for us. 4940 SDValue Mask = Op.getOperand(5); 4941 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4942 4943 SDValue Val = Op.getOperand(2); 4944 MVT VT = Val.getSimpleValueType(); 4945 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4946 4947 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4948 if (!IsUnmasked) { 4949 MVT MaskVT = 4950 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4951 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4952 } 4953 4954 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4955 4956 SDValue IntID = DAG.getTargetConstant( 4957 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4958 XLenVT); 4959 4960 auto *Store = cast<MemIntrinsicSDNode>(Op); 4961 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4962 Ops.push_back(Val); 4963 Ops.push_back(Op.getOperand(3)); // Ptr 4964 Ops.push_back(Op.getOperand(4)); // Stride 4965 if (!IsUnmasked) 4966 Ops.push_back(Mask); 4967 Ops.push_back(VL); 4968 4969 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4970 Ops, Store->getMemoryVT(), 4971 Store->getMemOperand()); 4972 } 4973 } 4974 4975 return SDValue(); 4976 } 4977 4978 static MVT getLMUL1VT(MVT VT) { 4979 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4980 "Unexpected vector MVT"); 4981 return MVT::getScalableVectorVT( 4982 VT.getVectorElementType(), 4983 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4984 } 4985 4986 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4987 switch (ISDOpcode) { 4988 default: 4989 llvm_unreachable("Unhandled reduction"); 4990 case ISD::VECREDUCE_ADD: 4991 return RISCVISD::VECREDUCE_ADD_VL; 4992 case ISD::VECREDUCE_UMAX: 4993 return RISCVISD::VECREDUCE_UMAX_VL; 4994 case ISD::VECREDUCE_SMAX: 4995 return RISCVISD::VECREDUCE_SMAX_VL; 4996 case ISD::VECREDUCE_UMIN: 4997 return RISCVISD::VECREDUCE_UMIN_VL; 4998 case ISD::VECREDUCE_SMIN: 4999 return RISCVISD::VECREDUCE_SMIN_VL; 5000 case ISD::VECREDUCE_AND: 5001 return RISCVISD::VECREDUCE_AND_VL; 5002 case ISD::VECREDUCE_OR: 5003 return RISCVISD::VECREDUCE_OR_VL; 5004 case ISD::VECREDUCE_XOR: 5005 return RISCVISD::VECREDUCE_XOR_VL; 5006 } 5007 } 5008 5009 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5010 SelectionDAG &DAG, 5011 bool IsVP) const { 5012 SDLoc DL(Op); 5013 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5014 MVT VecVT = Vec.getSimpleValueType(); 5015 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5016 Op.getOpcode() == ISD::VECREDUCE_OR || 5017 Op.getOpcode() == ISD::VECREDUCE_XOR || 5018 Op.getOpcode() == ISD::VP_REDUCE_AND || 5019 Op.getOpcode() == ISD::VP_REDUCE_OR || 5020 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5021 "Unexpected reduction lowering"); 5022 5023 MVT XLenVT = Subtarget.getXLenVT(); 5024 assert(Op.getValueType() == XLenVT && 5025 "Expected reduction output to be legalized to XLenVT"); 5026 5027 MVT ContainerVT = VecVT; 5028 if (VecVT.isFixedLengthVector()) { 5029 ContainerVT = getContainerForFixedLengthVector(VecVT); 5030 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5031 } 5032 5033 SDValue Mask, VL; 5034 if (IsVP) { 5035 Mask = Op.getOperand(2); 5036 VL = Op.getOperand(3); 5037 } else { 5038 std::tie(Mask, VL) = 5039 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5040 } 5041 5042 unsigned BaseOpc; 5043 ISD::CondCode CC; 5044 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5045 5046 switch (Op.getOpcode()) { 5047 default: 5048 llvm_unreachable("Unhandled reduction"); 5049 case ISD::VECREDUCE_AND: 5050 case ISD::VP_REDUCE_AND: { 5051 // vcpop ~x == 0 5052 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5053 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5054 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5055 CC = ISD::SETEQ; 5056 BaseOpc = ISD::AND; 5057 break; 5058 } 5059 case ISD::VECREDUCE_OR: 5060 case ISD::VP_REDUCE_OR: 5061 // vcpop x != 0 5062 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5063 CC = ISD::SETNE; 5064 BaseOpc = ISD::OR; 5065 break; 5066 case ISD::VECREDUCE_XOR: 5067 case ISD::VP_REDUCE_XOR: { 5068 // ((vcpop x) & 1) != 0 5069 SDValue One = DAG.getConstant(1, DL, XLenVT); 5070 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5071 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5072 CC = ISD::SETNE; 5073 BaseOpc = ISD::XOR; 5074 break; 5075 } 5076 } 5077 5078 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5079 5080 if (!IsVP) 5081 return SetCC; 5082 5083 // Now include the start value in the operation. 5084 // Note that we must return the start value when no elements are operated 5085 // upon. The vcpop instructions we've emitted in each case above will return 5086 // 0 for an inactive vector, and so we've already received the neutral value: 5087 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5088 // can simply include the start value. 5089 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5090 } 5091 5092 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5093 SelectionDAG &DAG) const { 5094 SDLoc DL(Op); 5095 SDValue Vec = Op.getOperand(0); 5096 EVT VecEVT = Vec.getValueType(); 5097 5098 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5099 5100 // Due to ordering in legalize types we may have a vector type that needs to 5101 // be split. Do that manually so we can get down to a legal type. 5102 while (getTypeAction(*DAG.getContext(), VecEVT) == 5103 TargetLowering::TypeSplitVector) { 5104 SDValue Lo, Hi; 5105 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5106 VecEVT = Lo.getValueType(); 5107 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5108 } 5109 5110 // TODO: The type may need to be widened rather than split. Or widened before 5111 // it can be split. 5112 if (!isTypeLegal(VecEVT)) 5113 return SDValue(); 5114 5115 MVT VecVT = VecEVT.getSimpleVT(); 5116 MVT VecEltVT = VecVT.getVectorElementType(); 5117 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5118 5119 MVT ContainerVT = VecVT; 5120 if (VecVT.isFixedLengthVector()) { 5121 ContainerVT = getContainerForFixedLengthVector(VecVT); 5122 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5123 } 5124 5125 MVT M1VT = getLMUL1VT(ContainerVT); 5126 MVT XLenVT = Subtarget.getXLenVT(); 5127 5128 SDValue Mask, VL; 5129 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5130 5131 SDValue NeutralElem = 5132 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5133 SDValue IdentitySplat = lowerScalarSplat( 5134 NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 5135 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5136 IdentitySplat, Mask, VL); 5137 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5138 DAG.getConstant(0, DL, XLenVT)); 5139 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5140 } 5141 5142 // Given a reduction op, this function returns the matching reduction opcode, 5143 // the vector SDValue and the scalar SDValue required to lower this to a 5144 // RISCVISD node. 5145 static std::tuple<unsigned, SDValue, SDValue> 5146 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5147 SDLoc DL(Op); 5148 auto Flags = Op->getFlags(); 5149 unsigned Opcode = Op.getOpcode(); 5150 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5151 switch (Opcode) { 5152 default: 5153 llvm_unreachable("Unhandled reduction"); 5154 case ISD::VECREDUCE_FADD: { 5155 // Use positive zero if we can. It is cheaper to materialize. 5156 SDValue Zero = 5157 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5158 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5159 } 5160 case ISD::VECREDUCE_SEQ_FADD: 5161 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5162 Op.getOperand(0)); 5163 case ISD::VECREDUCE_FMIN: 5164 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5165 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5166 case ISD::VECREDUCE_FMAX: 5167 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5168 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5169 } 5170 } 5171 5172 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5173 SelectionDAG &DAG) const { 5174 SDLoc DL(Op); 5175 MVT VecEltVT = Op.getSimpleValueType(); 5176 5177 unsigned RVVOpcode; 5178 SDValue VectorVal, ScalarVal; 5179 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5180 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5181 MVT VecVT = VectorVal.getSimpleValueType(); 5182 5183 MVT ContainerVT = VecVT; 5184 if (VecVT.isFixedLengthVector()) { 5185 ContainerVT = getContainerForFixedLengthVector(VecVT); 5186 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5187 } 5188 5189 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5190 MVT XLenVT = Subtarget.getXLenVT(); 5191 5192 SDValue Mask, VL; 5193 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5194 5195 SDValue ScalarSplat = lowerScalarSplat( 5196 ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 5197 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5198 VectorVal, ScalarSplat, Mask, VL); 5199 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5200 DAG.getConstant(0, DL, XLenVT)); 5201 } 5202 5203 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5204 switch (ISDOpcode) { 5205 default: 5206 llvm_unreachable("Unhandled reduction"); 5207 case ISD::VP_REDUCE_ADD: 5208 return RISCVISD::VECREDUCE_ADD_VL; 5209 case ISD::VP_REDUCE_UMAX: 5210 return RISCVISD::VECREDUCE_UMAX_VL; 5211 case ISD::VP_REDUCE_SMAX: 5212 return RISCVISD::VECREDUCE_SMAX_VL; 5213 case ISD::VP_REDUCE_UMIN: 5214 return RISCVISD::VECREDUCE_UMIN_VL; 5215 case ISD::VP_REDUCE_SMIN: 5216 return RISCVISD::VECREDUCE_SMIN_VL; 5217 case ISD::VP_REDUCE_AND: 5218 return RISCVISD::VECREDUCE_AND_VL; 5219 case ISD::VP_REDUCE_OR: 5220 return RISCVISD::VECREDUCE_OR_VL; 5221 case ISD::VP_REDUCE_XOR: 5222 return RISCVISD::VECREDUCE_XOR_VL; 5223 case ISD::VP_REDUCE_FADD: 5224 return RISCVISD::VECREDUCE_FADD_VL; 5225 case ISD::VP_REDUCE_SEQ_FADD: 5226 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5227 case ISD::VP_REDUCE_FMAX: 5228 return RISCVISD::VECREDUCE_FMAX_VL; 5229 case ISD::VP_REDUCE_FMIN: 5230 return RISCVISD::VECREDUCE_FMIN_VL; 5231 } 5232 } 5233 5234 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5235 SelectionDAG &DAG) const { 5236 SDLoc DL(Op); 5237 SDValue Vec = Op.getOperand(1); 5238 EVT VecEVT = Vec.getValueType(); 5239 5240 // TODO: The type may need to be widened rather than split. Or widened before 5241 // it can be split. 5242 if (!isTypeLegal(VecEVT)) 5243 return SDValue(); 5244 5245 MVT VecVT = VecEVT.getSimpleVT(); 5246 MVT VecEltVT = VecVT.getVectorElementType(); 5247 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5248 5249 MVT ContainerVT = VecVT; 5250 if (VecVT.isFixedLengthVector()) { 5251 ContainerVT = getContainerForFixedLengthVector(VecVT); 5252 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5253 } 5254 5255 SDValue VL = Op.getOperand(3); 5256 SDValue Mask = Op.getOperand(2); 5257 5258 MVT M1VT = getLMUL1VT(ContainerVT); 5259 MVT XLenVT = Subtarget.getXLenVT(); 5260 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5261 5262 SDValue StartSplat = 5263 lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT, 5264 DL, DAG, Subtarget); 5265 SDValue Reduction = 5266 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5267 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5268 DAG.getConstant(0, DL, XLenVT)); 5269 if (!VecVT.isInteger()) 5270 return Elt0; 5271 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5272 } 5273 5274 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5275 SelectionDAG &DAG) const { 5276 SDValue Vec = Op.getOperand(0); 5277 SDValue SubVec = Op.getOperand(1); 5278 MVT VecVT = Vec.getSimpleValueType(); 5279 MVT SubVecVT = SubVec.getSimpleValueType(); 5280 5281 SDLoc DL(Op); 5282 MVT XLenVT = Subtarget.getXLenVT(); 5283 unsigned OrigIdx = Op.getConstantOperandVal(2); 5284 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5285 5286 // We don't have the ability to slide mask vectors up indexed by their i1 5287 // elements; the smallest we can do is i8. Often we are able to bitcast to 5288 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5289 // into a scalable one, we might not necessarily have enough scalable 5290 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5291 if (SubVecVT.getVectorElementType() == MVT::i1 && 5292 (OrigIdx != 0 || !Vec.isUndef())) { 5293 if (VecVT.getVectorMinNumElements() >= 8 && 5294 SubVecVT.getVectorMinNumElements() >= 8) { 5295 assert(OrigIdx % 8 == 0 && "Invalid index"); 5296 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5297 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5298 "Unexpected mask vector lowering"); 5299 OrigIdx /= 8; 5300 SubVecVT = 5301 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5302 SubVecVT.isScalableVector()); 5303 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5304 VecVT.isScalableVector()); 5305 Vec = DAG.getBitcast(VecVT, Vec); 5306 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5307 } else { 5308 // We can't slide this mask vector up indexed by its i1 elements. 5309 // This poses a problem when we wish to insert a scalable vector which 5310 // can't be re-expressed as a larger type. Just choose the slow path and 5311 // extend to a larger type, then truncate back down. 5312 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5313 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5314 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5315 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5316 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5317 Op.getOperand(2)); 5318 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5319 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5320 } 5321 } 5322 5323 // If the subvector vector is a fixed-length type, we cannot use subregister 5324 // manipulation to simplify the codegen; we don't know which register of a 5325 // LMUL group contains the specific subvector as we only know the minimum 5326 // register size. Therefore we must slide the vector group up the full 5327 // amount. 5328 if (SubVecVT.isFixedLengthVector()) { 5329 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5330 return Op; 5331 MVT ContainerVT = VecVT; 5332 if (VecVT.isFixedLengthVector()) { 5333 ContainerVT = getContainerForFixedLengthVector(VecVT); 5334 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5335 } 5336 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5337 DAG.getUNDEF(ContainerVT), SubVec, 5338 DAG.getConstant(0, DL, XLenVT)); 5339 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5340 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5341 return DAG.getBitcast(Op.getValueType(), SubVec); 5342 } 5343 SDValue Mask = 5344 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5345 // Set the vector length to only the number of elements we care about. Note 5346 // that for slideup this includes the offset. 5347 SDValue VL = 5348 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5349 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5350 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5351 SubVec, SlideupAmt, Mask, VL); 5352 if (VecVT.isFixedLengthVector()) 5353 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5354 return DAG.getBitcast(Op.getValueType(), Slideup); 5355 } 5356 5357 unsigned SubRegIdx, RemIdx; 5358 std::tie(SubRegIdx, RemIdx) = 5359 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5360 VecVT, SubVecVT, OrigIdx, TRI); 5361 5362 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5363 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5364 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5365 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5366 5367 // 1. If the Idx has been completely eliminated and this subvector's size is 5368 // a vector register or a multiple thereof, or the surrounding elements are 5369 // undef, then this is a subvector insert which naturally aligns to a vector 5370 // register. These can easily be handled using subregister manipulation. 5371 // 2. If the subvector is smaller than a vector register, then the insertion 5372 // must preserve the undisturbed elements of the register. We do this by 5373 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5374 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5375 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5376 // LMUL=1 type back into the larger vector (resolving to another subregister 5377 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5378 // to avoid allocating a large register group to hold our subvector. 5379 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5380 return Op; 5381 5382 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5383 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5384 // (in our case undisturbed). This means we can set up a subvector insertion 5385 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5386 // size of the subvector. 5387 MVT InterSubVT = VecVT; 5388 SDValue AlignedExtract = Vec; 5389 unsigned AlignedIdx = OrigIdx - RemIdx; 5390 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5391 InterSubVT = getLMUL1VT(VecVT); 5392 // Extract a subvector equal to the nearest full vector register type. This 5393 // should resolve to a EXTRACT_SUBREG instruction. 5394 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5395 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5396 } 5397 5398 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5399 // For scalable vectors this must be further multiplied by vscale. 5400 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5401 5402 SDValue Mask, VL; 5403 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5404 5405 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5406 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5407 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5408 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5409 5410 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5411 DAG.getUNDEF(InterSubVT), SubVec, 5412 DAG.getConstant(0, DL, XLenVT)); 5413 5414 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5415 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5416 5417 // If required, insert this subvector back into the correct vector register. 5418 // This should resolve to an INSERT_SUBREG instruction. 5419 if (VecVT.bitsGT(InterSubVT)) 5420 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5421 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5422 5423 // We might have bitcast from a mask type: cast back to the original type if 5424 // required. 5425 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5426 } 5427 5428 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5429 SelectionDAG &DAG) const { 5430 SDValue Vec = Op.getOperand(0); 5431 MVT SubVecVT = Op.getSimpleValueType(); 5432 MVT VecVT = Vec.getSimpleValueType(); 5433 5434 SDLoc DL(Op); 5435 MVT XLenVT = Subtarget.getXLenVT(); 5436 unsigned OrigIdx = Op.getConstantOperandVal(1); 5437 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5438 5439 // We don't have the ability to slide mask vectors down indexed by their i1 5440 // elements; the smallest we can do is i8. Often we are able to bitcast to 5441 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5442 // from a scalable one, we might not necessarily have enough scalable 5443 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5444 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5445 if (VecVT.getVectorMinNumElements() >= 8 && 5446 SubVecVT.getVectorMinNumElements() >= 8) { 5447 assert(OrigIdx % 8 == 0 && "Invalid index"); 5448 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5449 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5450 "Unexpected mask vector lowering"); 5451 OrigIdx /= 8; 5452 SubVecVT = 5453 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5454 SubVecVT.isScalableVector()); 5455 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5456 VecVT.isScalableVector()); 5457 Vec = DAG.getBitcast(VecVT, Vec); 5458 } else { 5459 // We can't slide this mask vector down, indexed by its i1 elements. 5460 // This poses a problem when we wish to extract a scalable vector which 5461 // can't be re-expressed as a larger type. Just choose the slow path and 5462 // extend to a larger type, then truncate back down. 5463 // TODO: We could probably improve this when extracting certain fixed 5464 // from fixed, where we can extract as i8 and shift the correct element 5465 // right to reach the desired subvector? 5466 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5467 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5468 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5469 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5470 Op.getOperand(1)); 5471 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5472 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5473 } 5474 } 5475 5476 // If the subvector vector is a fixed-length type, we cannot use subregister 5477 // manipulation to simplify the codegen; we don't know which register of a 5478 // LMUL group contains the specific subvector as we only know the minimum 5479 // register size. Therefore we must slide the vector group down the full 5480 // amount. 5481 if (SubVecVT.isFixedLengthVector()) { 5482 // With an index of 0 this is a cast-like subvector, which can be performed 5483 // with subregister operations. 5484 if (OrigIdx == 0) 5485 return Op; 5486 MVT ContainerVT = VecVT; 5487 if (VecVT.isFixedLengthVector()) { 5488 ContainerVT = getContainerForFixedLengthVector(VecVT); 5489 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5490 } 5491 SDValue Mask = 5492 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5493 // Set the vector length to only the number of elements we care about. This 5494 // avoids sliding down elements we're going to discard straight away. 5495 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5496 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5497 SDValue Slidedown = 5498 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5499 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5500 // Now we can use a cast-like subvector extract to get the result. 5501 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5502 DAG.getConstant(0, DL, XLenVT)); 5503 return DAG.getBitcast(Op.getValueType(), Slidedown); 5504 } 5505 5506 unsigned SubRegIdx, RemIdx; 5507 std::tie(SubRegIdx, RemIdx) = 5508 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5509 VecVT, SubVecVT, OrigIdx, TRI); 5510 5511 // If the Idx has been completely eliminated then this is a subvector extract 5512 // which naturally aligns to a vector register. These can easily be handled 5513 // using subregister manipulation. 5514 if (RemIdx == 0) 5515 return Op; 5516 5517 // Else we must shift our vector register directly to extract the subvector. 5518 // Do this using VSLIDEDOWN. 5519 5520 // If the vector type is an LMUL-group type, extract a subvector equal to the 5521 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5522 // instruction. 5523 MVT InterSubVT = VecVT; 5524 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5525 InterSubVT = getLMUL1VT(VecVT); 5526 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5527 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5528 } 5529 5530 // Slide this vector register down by the desired number of elements in order 5531 // to place the desired subvector starting at element 0. 5532 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5533 // For scalable vectors this must be further multiplied by vscale. 5534 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5535 5536 SDValue Mask, VL; 5537 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5538 SDValue Slidedown = 5539 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5540 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5541 5542 // Now the vector is in the right position, extract our final subvector. This 5543 // should resolve to a COPY. 5544 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5545 DAG.getConstant(0, DL, XLenVT)); 5546 5547 // We might have bitcast from a mask type: cast back to the original type if 5548 // required. 5549 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5550 } 5551 5552 // Lower step_vector to the vid instruction. Any non-identity step value must 5553 // be accounted for my manual expansion. 5554 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5555 SelectionDAG &DAG) const { 5556 SDLoc DL(Op); 5557 MVT VT = Op.getSimpleValueType(); 5558 MVT XLenVT = Subtarget.getXLenVT(); 5559 SDValue Mask, VL; 5560 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5561 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5562 uint64_t StepValImm = Op.getConstantOperandVal(0); 5563 if (StepValImm != 1) { 5564 if (isPowerOf2_64(StepValImm)) { 5565 SDValue StepVal = 5566 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 5567 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5568 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5569 } else { 5570 SDValue StepVal = lowerScalarSplat( 5571 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 5572 DL, DAG, Subtarget); 5573 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5574 } 5575 } 5576 return StepVec; 5577 } 5578 5579 // Implement vector_reverse using vrgather.vv with indices determined by 5580 // subtracting the id of each element from (VLMAX-1). This will convert 5581 // the indices like so: 5582 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5583 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5584 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5585 SelectionDAG &DAG) const { 5586 SDLoc DL(Op); 5587 MVT VecVT = Op.getSimpleValueType(); 5588 unsigned EltSize = VecVT.getScalarSizeInBits(); 5589 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5590 5591 unsigned MaxVLMAX = 0; 5592 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5593 if (VectorBitsMax != 0) 5594 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5595 5596 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5597 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5598 5599 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5600 // to use vrgatherei16.vv. 5601 // TODO: It's also possible to use vrgatherei16.vv for other types to 5602 // decrease register width for the index calculation. 5603 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5604 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5605 // Reverse each half, then reassemble them in reverse order. 5606 // NOTE: It's also possible that after splitting that VLMAX no longer 5607 // requires vrgatherei16.vv. 5608 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5609 SDValue Lo, Hi; 5610 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5611 EVT LoVT, HiVT; 5612 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5613 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5614 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5615 // Reassemble the low and high pieces reversed. 5616 // FIXME: This is a CONCAT_VECTORS. 5617 SDValue Res = 5618 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5619 DAG.getIntPtrConstant(0, DL)); 5620 return DAG.getNode( 5621 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5622 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5623 } 5624 5625 // Just promote the int type to i16 which will double the LMUL. 5626 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5627 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5628 } 5629 5630 MVT XLenVT = Subtarget.getXLenVT(); 5631 SDValue Mask, VL; 5632 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5633 5634 // Calculate VLMAX-1 for the desired SEW. 5635 unsigned MinElts = VecVT.getVectorMinNumElements(); 5636 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5637 DAG.getConstant(MinElts, DL, XLenVT)); 5638 SDValue VLMinus1 = 5639 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5640 5641 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5642 bool IsRV32E64 = 5643 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5644 SDValue SplatVL; 5645 if (!IsRV32E64) 5646 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5647 else 5648 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, VLMinus1, 5649 DAG.getRegister(RISCV::X0, XLenVT)); 5650 5651 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5652 SDValue Indices = 5653 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5654 5655 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5656 } 5657 5658 SDValue 5659 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5660 SelectionDAG &DAG) const { 5661 SDLoc DL(Op); 5662 auto *Load = cast<LoadSDNode>(Op); 5663 5664 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5665 Load->getMemoryVT(), 5666 *Load->getMemOperand()) && 5667 "Expecting a correctly-aligned load"); 5668 5669 MVT VT = Op.getSimpleValueType(); 5670 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5671 5672 SDValue VL = 5673 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5674 5675 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5676 SDValue NewLoad = DAG.getMemIntrinsicNode( 5677 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5678 Load->getMemoryVT(), Load->getMemOperand()); 5679 5680 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5681 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5682 } 5683 5684 SDValue 5685 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5686 SelectionDAG &DAG) const { 5687 SDLoc DL(Op); 5688 auto *Store = cast<StoreSDNode>(Op); 5689 5690 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5691 Store->getMemoryVT(), 5692 *Store->getMemOperand()) && 5693 "Expecting a correctly-aligned store"); 5694 5695 SDValue StoreVal = Store->getValue(); 5696 MVT VT = StoreVal.getSimpleValueType(); 5697 5698 // If the size less than a byte, we need to pad with zeros to make a byte. 5699 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5700 VT = MVT::v8i1; 5701 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5702 DAG.getConstant(0, DL, VT), StoreVal, 5703 DAG.getIntPtrConstant(0, DL)); 5704 } 5705 5706 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5707 5708 SDValue VL = 5709 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5710 5711 SDValue NewValue = 5712 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5713 return DAG.getMemIntrinsicNode( 5714 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5715 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5716 Store->getMemoryVT(), Store->getMemOperand()); 5717 } 5718 5719 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5720 SelectionDAG &DAG) const { 5721 SDLoc DL(Op); 5722 MVT VT = Op.getSimpleValueType(); 5723 5724 const auto *MemSD = cast<MemSDNode>(Op); 5725 EVT MemVT = MemSD->getMemoryVT(); 5726 MachineMemOperand *MMO = MemSD->getMemOperand(); 5727 SDValue Chain = MemSD->getChain(); 5728 SDValue BasePtr = MemSD->getBasePtr(); 5729 5730 SDValue Mask, PassThru, VL; 5731 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5732 Mask = VPLoad->getMask(); 5733 PassThru = DAG.getUNDEF(VT); 5734 VL = VPLoad->getVectorLength(); 5735 } else { 5736 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5737 Mask = MLoad->getMask(); 5738 PassThru = MLoad->getPassThru(); 5739 } 5740 5741 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5742 5743 MVT XLenVT = Subtarget.getXLenVT(); 5744 5745 MVT ContainerVT = VT; 5746 if (VT.isFixedLengthVector()) { 5747 ContainerVT = getContainerForFixedLengthVector(VT); 5748 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5749 if (!IsUnmasked) { 5750 MVT MaskVT = 5751 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5752 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5753 } 5754 } 5755 5756 if (!VL) 5757 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5758 5759 unsigned IntID = 5760 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5761 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5762 if (IsUnmasked) 5763 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5764 else 5765 Ops.push_back(PassThru); 5766 Ops.push_back(BasePtr); 5767 if (!IsUnmasked) 5768 Ops.push_back(Mask); 5769 Ops.push_back(VL); 5770 if (!IsUnmasked) 5771 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5772 5773 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5774 5775 SDValue Result = 5776 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5777 Chain = Result.getValue(1); 5778 5779 if (VT.isFixedLengthVector()) 5780 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5781 5782 return DAG.getMergeValues({Result, Chain}, DL); 5783 } 5784 5785 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5786 SelectionDAG &DAG) const { 5787 SDLoc DL(Op); 5788 5789 const auto *MemSD = cast<MemSDNode>(Op); 5790 EVT MemVT = MemSD->getMemoryVT(); 5791 MachineMemOperand *MMO = MemSD->getMemOperand(); 5792 SDValue Chain = MemSD->getChain(); 5793 SDValue BasePtr = MemSD->getBasePtr(); 5794 SDValue Val, Mask, VL; 5795 5796 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5797 Val = VPStore->getValue(); 5798 Mask = VPStore->getMask(); 5799 VL = VPStore->getVectorLength(); 5800 } else { 5801 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5802 Val = MStore->getValue(); 5803 Mask = MStore->getMask(); 5804 } 5805 5806 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5807 5808 MVT VT = Val.getSimpleValueType(); 5809 MVT XLenVT = Subtarget.getXLenVT(); 5810 5811 MVT ContainerVT = VT; 5812 if (VT.isFixedLengthVector()) { 5813 ContainerVT = getContainerForFixedLengthVector(VT); 5814 5815 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5816 if (!IsUnmasked) { 5817 MVT MaskVT = 5818 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5819 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5820 } 5821 } 5822 5823 if (!VL) 5824 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5825 5826 unsigned IntID = 5827 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5828 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5829 Ops.push_back(Val); 5830 Ops.push_back(BasePtr); 5831 if (!IsUnmasked) 5832 Ops.push_back(Mask); 5833 Ops.push_back(VL); 5834 5835 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5836 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5837 } 5838 5839 SDValue 5840 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5841 SelectionDAG &DAG) const { 5842 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5843 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5844 5845 MVT VT = Op.getSimpleValueType(); 5846 5847 SDValue Op1 = 5848 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5849 SDValue Op2 = 5850 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5851 5852 SDLoc DL(Op); 5853 SDValue VL = 5854 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5855 5856 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5857 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5858 5859 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5860 Op.getOperand(2), Mask, VL); 5861 5862 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5863 } 5864 5865 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5866 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5867 MVT VT = Op.getSimpleValueType(); 5868 5869 if (VT.getVectorElementType() == MVT::i1) 5870 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5871 5872 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5873 } 5874 5875 SDValue 5876 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5877 SelectionDAG &DAG) const { 5878 unsigned Opc; 5879 switch (Op.getOpcode()) { 5880 default: llvm_unreachable("Unexpected opcode!"); 5881 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5882 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5883 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5884 } 5885 5886 return lowerToScalableOp(Op, DAG, Opc); 5887 } 5888 5889 // Lower vector ABS to smax(X, sub(0, X)). 5890 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5891 SDLoc DL(Op); 5892 MVT VT = Op.getSimpleValueType(); 5893 SDValue X = Op.getOperand(0); 5894 5895 assert(VT.isFixedLengthVector() && "Unexpected type"); 5896 5897 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5898 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5899 5900 SDValue Mask, VL; 5901 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5902 5903 SDValue SplatZero = 5904 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5905 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5906 SDValue NegX = 5907 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5908 SDValue Max = 5909 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5910 5911 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5912 } 5913 5914 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5915 SDValue Op, SelectionDAG &DAG) const { 5916 SDLoc DL(Op); 5917 MVT VT = Op.getSimpleValueType(); 5918 SDValue Mag = Op.getOperand(0); 5919 SDValue Sign = Op.getOperand(1); 5920 assert(Mag.getValueType() == Sign.getValueType() && 5921 "Can only handle COPYSIGN with matching types."); 5922 5923 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5924 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5925 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5926 5927 SDValue Mask, VL; 5928 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5929 5930 SDValue CopySign = 5931 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5932 5933 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5934 } 5935 5936 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5937 SDValue Op, SelectionDAG &DAG) const { 5938 MVT VT = Op.getSimpleValueType(); 5939 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5940 5941 MVT I1ContainerVT = 5942 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5943 5944 SDValue CC = 5945 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5946 SDValue Op1 = 5947 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5948 SDValue Op2 = 5949 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5950 5951 SDLoc DL(Op); 5952 SDValue Mask, VL; 5953 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5954 5955 SDValue Select = 5956 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5957 5958 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5959 } 5960 5961 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5962 unsigned NewOpc, 5963 bool HasMask) const { 5964 MVT VT = Op.getSimpleValueType(); 5965 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5966 5967 // Create list of operands by converting existing ones to scalable types. 5968 SmallVector<SDValue, 6> Ops; 5969 for (const SDValue &V : Op->op_values()) { 5970 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5971 5972 // Pass through non-vector operands. 5973 if (!V.getValueType().isVector()) { 5974 Ops.push_back(V); 5975 continue; 5976 } 5977 5978 // "cast" fixed length vector to a scalable vector. 5979 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5980 "Only fixed length vectors are supported!"); 5981 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5982 } 5983 5984 SDLoc DL(Op); 5985 SDValue Mask, VL; 5986 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5987 if (HasMask) 5988 Ops.push_back(Mask); 5989 Ops.push_back(VL); 5990 5991 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5992 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5993 } 5994 5995 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5996 // * Operands of each node are assumed to be in the same order. 5997 // * The EVL operand is promoted from i32 to i64 on RV64. 5998 // * Fixed-length vectors are converted to their scalable-vector container 5999 // types. 6000 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6001 unsigned RISCVISDOpc) const { 6002 SDLoc DL(Op); 6003 MVT VT = Op.getSimpleValueType(); 6004 SmallVector<SDValue, 4> Ops; 6005 6006 for (const auto &OpIdx : enumerate(Op->ops())) { 6007 SDValue V = OpIdx.value(); 6008 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6009 // Pass through operands which aren't fixed-length vectors. 6010 if (!V.getValueType().isFixedLengthVector()) { 6011 Ops.push_back(V); 6012 continue; 6013 } 6014 // "cast" fixed length vector to a scalable vector. 6015 MVT OpVT = V.getSimpleValueType(); 6016 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6017 assert(useRVVForFixedLengthVectorVT(OpVT) && 6018 "Only fixed length vectors are supported!"); 6019 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6020 } 6021 6022 if (!VT.isFixedLengthVector()) 6023 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6024 6025 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6026 6027 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6028 6029 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6030 } 6031 6032 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6033 unsigned MaskOpc, 6034 unsigned VecOpc) const { 6035 MVT VT = Op.getSimpleValueType(); 6036 if (VT.getVectorElementType() != MVT::i1) 6037 return lowerVPOp(Op, DAG, VecOpc); 6038 6039 // It is safe to drop mask parameter as masked-off elements are undef. 6040 SDValue Op1 = Op->getOperand(0); 6041 SDValue Op2 = Op->getOperand(1); 6042 SDValue VL = Op->getOperand(3); 6043 6044 MVT ContainerVT = VT; 6045 const bool IsFixed = VT.isFixedLengthVector(); 6046 if (IsFixed) { 6047 ContainerVT = getContainerForFixedLengthVector(VT); 6048 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6049 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6050 } 6051 6052 SDLoc DL(Op); 6053 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6054 if (!IsFixed) 6055 return Val; 6056 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6057 } 6058 6059 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6060 // matched to a RVV indexed load. The RVV indexed load instructions only 6061 // support the "unsigned unscaled" addressing mode; indices are implicitly 6062 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6063 // signed or scaled indexing is extended to the XLEN value type and scaled 6064 // accordingly. 6065 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6066 SelectionDAG &DAG) const { 6067 SDLoc DL(Op); 6068 MVT VT = Op.getSimpleValueType(); 6069 6070 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6071 EVT MemVT = MemSD->getMemoryVT(); 6072 MachineMemOperand *MMO = MemSD->getMemOperand(); 6073 SDValue Chain = MemSD->getChain(); 6074 SDValue BasePtr = MemSD->getBasePtr(); 6075 6076 ISD::LoadExtType LoadExtType; 6077 SDValue Index, Mask, PassThru, VL; 6078 6079 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6080 Index = VPGN->getIndex(); 6081 Mask = VPGN->getMask(); 6082 PassThru = DAG.getUNDEF(VT); 6083 VL = VPGN->getVectorLength(); 6084 // VP doesn't support extending loads. 6085 LoadExtType = ISD::NON_EXTLOAD; 6086 } else { 6087 // Else it must be a MGATHER. 6088 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6089 Index = MGN->getIndex(); 6090 Mask = MGN->getMask(); 6091 PassThru = MGN->getPassThru(); 6092 LoadExtType = MGN->getExtensionType(); 6093 } 6094 6095 MVT IndexVT = Index.getSimpleValueType(); 6096 MVT XLenVT = Subtarget.getXLenVT(); 6097 6098 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6099 "Unexpected VTs!"); 6100 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6101 // Targets have to explicitly opt-in for extending vector loads. 6102 assert(LoadExtType == ISD::NON_EXTLOAD && 6103 "Unexpected extending MGATHER/VP_GATHER"); 6104 (void)LoadExtType; 6105 6106 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6107 // the selection of the masked intrinsics doesn't do this for us. 6108 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6109 6110 MVT ContainerVT = VT; 6111 if (VT.isFixedLengthVector()) { 6112 // We need to use the larger of the result and index type to determine the 6113 // scalable type to use so we don't increase LMUL for any operand/result. 6114 if (VT.bitsGE(IndexVT)) { 6115 ContainerVT = getContainerForFixedLengthVector(VT); 6116 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6117 ContainerVT.getVectorElementCount()); 6118 } else { 6119 IndexVT = getContainerForFixedLengthVector(IndexVT); 6120 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6121 IndexVT.getVectorElementCount()); 6122 } 6123 6124 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6125 6126 if (!IsUnmasked) { 6127 MVT MaskVT = 6128 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6129 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6130 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6131 } 6132 } 6133 6134 if (!VL) 6135 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6136 6137 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6138 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6139 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6140 VL); 6141 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6142 TrueMask, VL); 6143 } 6144 6145 unsigned IntID = 6146 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6147 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6148 if (IsUnmasked) 6149 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6150 else 6151 Ops.push_back(PassThru); 6152 Ops.push_back(BasePtr); 6153 Ops.push_back(Index); 6154 if (!IsUnmasked) 6155 Ops.push_back(Mask); 6156 Ops.push_back(VL); 6157 if (!IsUnmasked) 6158 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6159 6160 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6161 SDValue Result = 6162 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6163 Chain = Result.getValue(1); 6164 6165 if (VT.isFixedLengthVector()) 6166 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6167 6168 return DAG.getMergeValues({Result, Chain}, DL); 6169 } 6170 6171 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6172 // matched to a RVV indexed store. The RVV indexed store instructions only 6173 // support the "unsigned unscaled" addressing mode; indices are implicitly 6174 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6175 // signed or scaled indexing is extended to the XLEN value type and scaled 6176 // accordingly. 6177 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6178 SelectionDAG &DAG) const { 6179 SDLoc DL(Op); 6180 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6181 EVT MemVT = MemSD->getMemoryVT(); 6182 MachineMemOperand *MMO = MemSD->getMemOperand(); 6183 SDValue Chain = MemSD->getChain(); 6184 SDValue BasePtr = MemSD->getBasePtr(); 6185 6186 bool IsTruncatingStore = false; 6187 SDValue Index, Mask, Val, VL; 6188 6189 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6190 Index = VPSN->getIndex(); 6191 Mask = VPSN->getMask(); 6192 Val = VPSN->getValue(); 6193 VL = VPSN->getVectorLength(); 6194 // VP doesn't support truncating stores. 6195 IsTruncatingStore = false; 6196 } else { 6197 // Else it must be a MSCATTER. 6198 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6199 Index = MSN->getIndex(); 6200 Mask = MSN->getMask(); 6201 Val = MSN->getValue(); 6202 IsTruncatingStore = MSN->isTruncatingStore(); 6203 } 6204 6205 MVT VT = Val.getSimpleValueType(); 6206 MVT IndexVT = Index.getSimpleValueType(); 6207 MVT XLenVT = Subtarget.getXLenVT(); 6208 6209 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6210 "Unexpected VTs!"); 6211 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6212 // Targets have to explicitly opt-in for extending vector loads and 6213 // truncating vector stores. 6214 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6215 (void)IsTruncatingStore; 6216 6217 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6218 // the selection of the masked intrinsics doesn't do this for us. 6219 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6220 6221 MVT ContainerVT = VT; 6222 if (VT.isFixedLengthVector()) { 6223 // We need to use the larger of the value and index type to determine the 6224 // scalable type to use so we don't increase LMUL for any operand/result. 6225 if (VT.bitsGE(IndexVT)) { 6226 ContainerVT = getContainerForFixedLengthVector(VT); 6227 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6228 ContainerVT.getVectorElementCount()); 6229 } else { 6230 IndexVT = getContainerForFixedLengthVector(IndexVT); 6231 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6232 IndexVT.getVectorElementCount()); 6233 } 6234 6235 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6236 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6237 6238 if (!IsUnmasked) { 6239 MVT MaskVT = 6240 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6241 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6242 } 6243 } 6244 6245 if (!VL) 6246 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6247 6248 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6249 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6250 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6251 VL); 6252 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6253 TrueMask, VL); 6254 } 6255 6256 unsigned IntID = 6257 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6258 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6259 Ops.push_back(Val); 6260 Ops.push_back(BasePtr); 6261 Ops.push_back(Index); 6262 if (!IsUnmasked) 6263 Ops.push_back(Mask); 6264 Ops.push_back(VL); 6265 6266 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6267 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6268 } 6269 6270 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6271 SelectionDAG &DAG) const { 6272 const MVT XLenVT = Subtarget.getXLenVT(); 6273 SDLoc DL(Op); 6274 SDValue Chain = Op->getOperand(0); 6275 SDValue SysRegNo = DAG.getTargetConstant( 6276 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6277 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6278 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6279 6280 // Encoding used for rounding mode in RISCV differs from that used in 6281 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6282 // table, which consists of a sequence of 4-bit fields, each representing 6283 // corresponding FLT_ROUNDS mode. 6284 static const int Table = 6285 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6286 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6287 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6288 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6289 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6290 6291 SDValue Shift = 6292 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6293 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6294 DAG.getConstant(Table, DL, XLenVT), Shift); 6295 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6296 DAG.getConstant(7, DL, XLenVT)); 6297 6298 return DAG.getMergeValues({Masked, Chain}, DL); 6299 } 6300 6301 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6302 SelectionDAG &DAG) const { 6303 const MVT XLenVT = Subtarget.getXLenVT(); 6304 SDLoc DL(Op); 6305 SDValue Chain = Op->getOperand(0); 6306 SDValue RMValue = Op->getOperand(1); 6307 SDValue SysRegNo = DAG.getTargetConstant( 6308 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6309 6310 // Encoding used for rounding mode in RISCV differs from that used in 6311 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6312 // a table, which consists of a sequence of 4-bit fields, each representing 6313 // corresponding RISCV mode. 6314 static const unsigned Table = 6315 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6316 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6317 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6318 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6319 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6320 6321 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6322 DAG.getConstant(2, DL, XLenVT)); 6323 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6324 DAG.getConstant(Table, DL, XLenVT), Shift); 6325 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6326 DAG.getConstant(0x7, DL, XLenVT)); 6327 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6328 RMValue); 6329 } 6330 6331 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6332 switch (IntNo) { 6333 default: 6334 llvm_unreachable("Unexpected Intrinsic"); 6335 case Intrinsic::riscv_grev: 6336 return RISCVISD::GREVW; 6337 case Intrinsic::riscv_gorc: 6338 return RISCVISD::GORCW; 6339 case Intrinsic::riscv_bcompress: 6340 return RISCVISD::BCOMPRESSW; 6341 case Intrinsic::riscv_bdecompress: 6342 return RISCVISD::BDECOMPRESSW; 6343 case Intrinsic::riscv_bfp: 6344 return RISCVISD::BFPW; 6345 case Intrinsic::riscv_fsl: 6346 return RISCVISD::FSLW; 6347 case Intrinsic::riscv_fsr: 6348 return RISCVISD::FSRW; 6349 } 6350 } 6351 6352 // Converts the given intrinsic to a i64 operation with any extension. 6353 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6354 unsigned IntNo) { 6355 SDLoc DL(N); 6356 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6357 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6358 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6359 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6360 // ReplaceNodeResults requires we maintain the same type for the return value. 6361 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6362 } 6363 6364 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6365 // form of the given Opcode. 6366 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6367 switch (Opcode) { 6368 default: 6369 llvm_unreachable("Unexpected opcode"); 6370 case ISD::SHL: 6371 return RISCVISD::SLLW; 6372 case ISD::SRA: 6373 return RISCVISD::SRAW; 6374 case ISD::SRL: 6375 return RISCVISD::SRLW; 6376 case ISD::SDIV: 6377 return RISCVISD::DIVW; 6378 case ISD::UDIV: 6379 return RISCVISD::DIVUW; 6380 case ISD::UREM: 6381 return RISCVISD::REMUW; 6382 case ISD::ROTL: 6383 return RISCVISD::ROLW; 6384 case ISD::ROTR: 6385 return RISCVISD::RORW; 6386 case RISCVISD::GREV: 6387 return RISCVISD::GREVW; 6388 case RISCVISD::GORC: 6389 return RISCVISD::GORCW; 6390 } 6391 } 6392 6393 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6394 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6395 // otherwise be promoted to i64, making it difficult to select the 6396 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6397 // type i8/i16/i32 is lost. 6398 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6399 unsigned ExtOpc = ISD::ANY_EXTEND) { 6400 SDLoc DL(N); 6401 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6402 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6403 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6404 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6405 // ReplaceNodeResults requires we maintain the same type for the return value. 6406 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6407 } 6408 6409 // Converts the given 32-bit operation to a i64 operation with signed extension 6410 // semantic to reduce the signed extension instructions. 6411 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6412 SDLoc DL(N); 6413 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6414 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6415 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6416 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6417 DAG.getValueType(MVT::i32)); 6418 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6419 } 6420 6421 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6422 SmallVectorImpl<SDValue> &Results, 6423 SelectionDAG &DAG) const { 6424 SDLoc DL(N); 6425 switch (N->getOpcode()) { 6426 default: 6427 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6428 case ISD::STRICT_FP_TO_SINT: 6429 case ISD::STRICT_FP_TO_UINT: 6430 case ISD::FP_TO_SINT: 6431 case ISD::FP_TO_UINT: { 6432 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6433 "Unexpected custom legalisation"); 6434 bool IsStrict = N->isStrictFPOpcode(); 6435 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6436 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6437 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6438 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6439 TargetLowering::TypeSoftenFloat) { 6440 if (!isTypeLegal(Op0.getValueType())) 6441 return; 6442 if (IsStrict) { 6443 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6444 : RISCVISD::STRICT_FCVT_WU_RV64; 6445 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6446 SDValue Res = DAG.getNode( 6447 Opc, DL, VTs, N->getOperand(0), Op0, 6448 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6449 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6450 Results.push_back(Res.getValue(1)); 6451 return; 6452 } 6453 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6454 SDValue Res = 6455 DAG.getNode(Opc, DL, MVT::i64, Op0, 6456 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6457 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6458 return; 6459 } 6460 // If the FP type needs to be softened, emit a library call using the 'si' 6461 // version. If we left it to default legalization we'd end up with 'di'. If 6462 // the FP type doesn't need to be softened just let generic type 6463 // legalization promote the result type. 6464 RTLIB::Libcall LC; 6465 if (IsSigned) 6466 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6467 else 6468 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6469 MakeLibCallOptions CallOptions; 6470 EVT OpVT = Op0.getValueType(); 6471 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6472 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6473 SDValue Result; 6474 std::tie(Result, Chain) = 6475 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6476 Results.push_back(Result); 6477 if (IsStrict) 6478 Results.push_back(Chain); 6479 break; 6480 } 6481 case ISD::READCYCLECOUNTER: { 6482 assert(!Subtarget.is64Bit() && 6483 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6484 6485 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6486 SDValue RCW = 6487 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6488 6489 Results.push_back( 6490 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6491 Results.push_back(RCW.getValue(2)); 6492 break; 6493 } 6494 case ISD::MUL: { 6495 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6496 unsigned XLen = Subtarget.getXLen(); 6497 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6498 if (Size > XLen) { 6499 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6500 SDValue LHS = N->getOperand(0); 6501 SDValue RHS = N->getOperand(1); 6502 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6503 6504 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6505 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6506 // We need exactly one side to be unsigned. 6507 if (LHSIsU == RHSIsU) 6508 return; 6509 6510 auto MakeMULPair = [&](SDValue S, SDValue U) { 6511 MVT XLenVT = Subtarget.getXLenVT(); 6512 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6513 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6514 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6515 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6516 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6517 }; 6518 6519 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6520 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6521 6522 // The other operand should be signed, but still prefer MULH when 6523 // possible. 6524 if (RHSIsU && LHSIsS && !RHSIsS) 6525 Results.push_back(MakeMULPair(LHS, RHS)); 6526 else if (LHSIsU && RHSIsS && !LHSIsS) 6527 Results.push_back(MakeMULPair(RHS, LHS)); 6528 6529 return; 6530 } 6531 LLVM_FALLTHROUGH; 6532 } 6533 case ISD::ADD: 6534 case ISD::SUB: 6535 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6536 "Unexpected custom legalisation"); 6537 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6538 break; 6539 case ISD::SHL: 6540 case ISD::SRA: 6541 case ISD::SRL: 6542 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6543 "Unexpected custom legalisation"); 6544 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6545 Results.push_back(customLegalizeToWOp(N, DAG)); 6546 break; 6547 } 6548 6549 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6550 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6551 // shift amount. 6552 if (N->getOpcode() == ISD::SHL) { 6553 SDLoc DL(N); 6554 SDValue NewOp0 = 6555 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6556 SDValue NewOp1 = 6557 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6558 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6559 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6560 DAG.getValueType(MVT::i32)); 6561 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6562 } 6563 6564 break; 6565 case ISD::ROTL: 6566 case ISD::ROTR: 6567 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6568 "Unexpected custom legalisation"); 6569 Results.push_back(customLegalizeToWOp(N, DAG)); 6570 break; 6571 case ISD::CTTZ: 6572 case ISD::CTTZ_ZERO_UNDEF: 6573 case ISD::CTLZ: 6574 case ISD::CTLZ_ZERO_UNDEF: { 6575 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6576 "Unexpected custom legalisation"); 6577 6578 SDValue NewOp0 = 6579 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6580 bool IsCTZ = 6581 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6582 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6583 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6584 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6585 return; 6586 } 6587 case ISD::SDIV: 6588 case ISD::UDIV: 6589 case ISD::UREM: { 6590 MVT VT = N->getSimpleValueType(0); 6591 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6592 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6593 "Unexpected custom legalisation"); 6594 // Don't promote division/remainder by constant since we should expand those 6595 // to multiply by magic constant. 6596 // FIXME: What if the expansion is disabled for minsize. 6597 if (N->getOperand(1).getOpcode() == ISD::Constant) 6598 return; 6599 6600 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6601 // the upper 32 bits. For other types we need to sign or zero extend 6602 // based on the opcode. 6603 unsigned ExtOpc = ISD::ANY_EXTEND; 6604 if (VT != MVT::i32) 6605 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6606 : ISD::ZERO_EXTEND; 6607 6608 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6609 break; 6610 } 6611 case ISD::UADDO: 6612 case ISD::USUBO: { 6613 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6614 "Unexpected custom legalisation"); 6615 bool IsAdd = N->getOpcode() == ISD::UADDO; 6616 // Create an ADDW or SUBW. 6617 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6618 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6619 SDValue Res = 6620 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6621 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6622 DAG.getValueType(MVT::i32)); 6623 6624 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6625 // Since the inputs are sign extended from i32, this is equivalent to 6626 // comparing the lower 32 bits. 6627 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6628 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6629 IsAdd ? ISD::SETULT : ISD::SETUGT); 6630 6631 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6632 Results.push_back(Overflow); 6633 return; 6634 } 6635 case ISD::UADDSAT: 6636 case ISD::USUBSAT: { 6637 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6638 "Unexpected custom legalisation"); 6639 if (Subtarget.hasStdExtZbb()) { 6640 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6641 // sign extend allows overflow of the lower 32 bits to be detected on 6642 // the promoted size. 6643 SDValue LHS = 6644 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6645 SDValue RHS = 6646 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6647 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6648 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6649 return; 6650 } 6651 6652 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6653 // promotion for UADDO/USUBO. 6654 Results.push_back(expandAddSubSat(N, DAG)); 6655 return; 6656 } 6657 case ISD::BITCAST: { 6658 EVT VT = N->getValueType(0); 6659 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6660 SDValue Op0 = N->getOperand(0); 6661 EVT Op0VT = Op0.getValueType(); 6662 MVT XLenVT = Subtarget.getXLenVT(); 6663 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6664 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6665 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6666 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6667 Subtarget.hasStdExtF()) { 6668 SDValue FPConv = 6669 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6670 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6671 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6672 isTypeLegal(Op0VT)) { 6673 // Custom-legalize bitcasts from fixed-length vector types to illegal 6674 // scalar types in order to improve codegen. Bitcast the vector to a 6675 // one-element vector type whose element type is the same as the result 6676 // type, and extract the first element. 6677 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6678 if (isTypeLegal(BVT)) { 6679 SDValue BVec = DAG.getBitcast(BVT, Op0); 6680 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6681 DAG.getConstant(0, DL, XLenVT))); 6682 } 6683 } 6684 break; 6685 } 6686 case RISCVISD::GREV: 6687 case RISCVISD::GORC: { 6688 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6689 "Unexpected custom legalisation"); 6690 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6691 // This is similar to customLegalizeToWOp, except that we pass the second 6692 // operand (a TargetConstant) straight through: it is already of type 6693 // XLenVT. 6694 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6695 SDValue NewOp0 = 6696 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6697 SDValue NewOp1 = 6698 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6699 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6700 // ReplaceNodeResults requires we maintain the same type for the return 6701 // value. 6702 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6703 break; 6704 } 6705 case RISCVISD::SHFL: { 6706 // There is no SHFLIW instruction, but we can just promote the operation. 6707 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6708 "Unexpected custom legalisation"); 6709 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6710 SDValue NewOp0 = 6711 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6712 SDValue NewOp1 = 6713 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6714 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6715 // ReplaceNodeResults requires we maintain the same type for the return 6716 // value. 6717 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6718 break; 6719 } 6720 case ISD::BSWAP: 6721 case ISD::BITREVERSE: { 6722 MVT VT = N->getSimpleValueType(0); 6723 MVT XLenVT = Subtarget.getXLenVT(); 6724 assert((VT == MVT::i8 || VT == MVT::i16 || 6725 (VT == MVT::i32 && Subtarget.is64Bit())) && 6726 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6727 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6728 unsigned Imm = VT.getSizeInBits() - 1; 6729 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6730 if (N->getOpcode() == ISD::BSWAP) 6731 Imm &= ~0x7U; 6732 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6733 SDValue GREVI = 6734 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6735 // ReplaceNodeResults requires we maintain the same type for the return 6736 // value. 6737 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6738 break; 6739 } 6740 case ISD::FSHL: 6741 case ISD::FSHR: { 6742 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6743 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6744 SDValue NewOp0 = 6745 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6746 SDValue NewOp1 = 6747 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6748 SDValue NewShAmt = 6749 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6750 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6751 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6752 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6753 DAG.getConstant(0x1f, DL, MVT::i64)); 6754 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6755 // instruction use different orders. fshl will return its first operand for 6756 // shift of zero, fshr will return its second operand. fsl and fsr both 6757 // return rs1 so the ISD nodes need to have different operand orders. 6758 // Shift amount is in rs2. 6759 unsigned Opc = RISCVISD::FSLW; 6760 if (N->getOpcode() == ISD::FSHR) { 6761 std::swap(NewOp0, NewOp1); 6762 Opc = RISCVISD::FSRW; 6763 } 6764 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6765 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6766 break; 6767 } 6768 case ISD::EXTRACT_VECTOR_ELT: { 6769 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6770 // type is illegal (currently only vXi64 RV32). 6771 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6772 // transferred to the destination register. We issue two of these from the 6773 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6774 // first element. 6775 SDValue Vec = N->getOperand(0); 6776 SDValue Idx = N->getOperand(1); 6777 6778 // The vector type hasn't been legalized yet so we can't issue target 6779 // specific nodes if it needs legalization. 6780 // FIXME: We would manually legalize if it's important. 6781 if (!isTypeLegal(Vec.getValueType())) 6782 return; 6783 6784 MVT VecVT = Vec.getSimpleValueType(); 6785 6786 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6787 VecVT.getVectorElementType() == MVT::i64 && 6788 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6789 6790 // If this is a fixed vector, we need to convert it to a scalable vector. 6791 MVT ContainerVT = VecVT; 6792 if (VecVT.isFixedLengthVector()) { 6793 ContainerVT = getContainerForFixedLengthVector(VecVT); 6794 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6795 } 6796 6797 MVT XLenVT = Subtarget.getXLenVT(); 6798 6799 // Use a VL of 1 to avoid processing more elements than we need. 6800 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6801 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6802 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6803 6804 // Unless the index is known to be 0, we must slide the vector down to get 6805 // the desired element into index 0. 6806 if (!isNullConstant(Idx)) { 6807 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6808 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6809 } 6810 6811 // Extract the lower XLEN bits of the correct vector element. 6812 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6813 6814 // To extract the upper XLEN bits of the vector element, shift the first 6815 // element right by 32 bits and re-extract the lower XLEN bits. 6816 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6817 DAG.getConstant(32, DL, XLenVT), VL); 6818 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6819 ThirtyTwoV, Mask, VL); 6820 6821 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6822 6823 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6824 break; 6825 } 6826 case ISD::INTRINSIC_WO_CHAIN: { 6827 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6828 switch (IntNo) { 6829 default: 6830 llvm_unreachable( 6831 "Don't know how to custom type legalize this intrinsic!"); 6832 case Intrinsic::riscv_grev: 6833 case Intrinsic::riscv_gorc: 6834 case Intrinsic::riscv_bcompress: 6835 case Intrinsic::riscv_bdecompress: 6836 case Intrinsic::riscv_bfp: { 6837 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6838 "Unexpected custom legalisation"); 6839 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6840 break; 6841 } 6842 case Intrinsic::riscv_fsl: 6843 case Intrinsic::riscv_fsr: { 6844 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6845 "Unexpected custom legalisation"); 6846 SDValue NewOp1 = 6847 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6848 SDValue NewOp2 = 6849 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6850 SDValue NewOp3 = 6851 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 6852 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 6853 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 6854 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6855 break; 6856 } 6857 case Intrinsic::riscv_orc_b: { 6858 // Lower to the GORCI encoding for orc.b with the operand extended. 6859 SDValue NewOp = 6860 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6861 // If Zbp is enabled, use GORCIW which will sign extend the result. 6862 unsigned Opc = 6863 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6864 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6865 DAG.getConstant(7, DL, MVT::i64)); 6866 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6867 return; 6868 } 6869 case Intrinsic::riscv_shfl: 6870 case Intrinsic::riscv_unshfl: { 6871 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6872 "Unexpected custom legalisation"); 6873 SDValue NewOp1 = 6874 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6875 SDValue NewOp2 = 6876 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6877 unsigned Opc = 6878 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6879 // There is no (UN)SHFLIW. If the control word is a constant, we can use 6880 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 6881 // will be shuffled the same way as the lower 32 bit half, but the two 6882 // halves won't cross. 6883 if (isa<ConstantSDNode>(NewOp2)) { 6884 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6885 DAG.getConstant(0xf, DL, MVT::i64)); 6886 Opc = 6887 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6888 } 6889 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6890 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6891 break; 6892 } 6893 case Intrinsic::riscv_vmv_x_s: { 6894 EVT VT = N->getValueType(0); 6895 MVT XLenVT = Subtarget.getXLenVT(); 6896 if (VT.bitsLT(XLenVT)) { 6897 // Simple case just extract using vmv.x.s and truncate. 6898 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6899 Subtarget.getXLenVT(), N->getOperand(1)); 6900 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6901 return; 6902 } 6903 6904 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6905 "Unexpected custom legalization"); 6906 6907 // We need to do the move in two steps. 6908 SDValue Vec = N->getOperand(1); 6909 MVT VecVT = Vec.getSimpleValueType(); 6910 6911 // First extract the lower XLEN bits of the element. 6912 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6913 6914 // To extract the upper XLEN bits of the vector element, shift the first 6915 // element right by 32 bits and re-extract the lower XLEN bits. 6916 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6917 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6918 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6919 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 6920 DAG.getConstant(32, DL, XLenVT), VL); 6921 SDValue LShr32 = 6922 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6923 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6924 6925 Results.push_back( 6926 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6927 break; 6928 } 6929 } 6930 break; 6931 } 6932 case ISD::VECREDUCE_ADD: 6933 case ISD::VECREDUCE_AND: 6934 case ISD::VECREDUCE_OR: 6935 case ISD::VECREDUCE_XOR: 6936 case ISD::VECREDUCE_SMAX: 6937 case ISD::VECREDUCE_UMAX: 6938 case ISD::VECREDUCE_SMIN: 6939 case ISD::VECREDUCE_UMIN: 6940 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6941 Results.push_back(V); 6942 break; 6943 case ISD::VP_REDUCE_ADD: 6944 case ISD::VP_REDUCE_AND: 6945 case ISD::VP_REDUCE_OR: 6946 case ISD::VP_REDUCE_XOR: 6947 case ISD::VP_REDUCE_SMAX: 6948 case ISD::VP_REDUCE_UMAX: 6949 case ISD::VP_REDUCE_SMIN: 6950 case ISD::VP_REDUCE_UMIN: 6951 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6952 Results.push_back(V); 6953 break; 6954 case ISD::FLT_ROUNDS_: { 6955 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6956 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6957 Results.push_back(Res.getValue(0)); 6958 Results.push_back(Res.getValue(1)); 6959 break; 6960 } 6961 } 6962 } 6963 6964 // A structure to hold one of the bit-manipulation patterns below. Together, a 6965 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6966 // (or (and (shl x, 1), 0xAAAAAAAA), 6967 // (and (srl x, 1), 0x55555555)) 6968 struct RISCVBitmanipPat { 6969 SDValue Op; 6970 unsigned ShAmt; 6971 bool IsSHL; 6972 6973 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6974 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6975 } 6976 }; 6977 6978 // Matches patterns of the form 6979 // (and (shl x, C2), (C1 << C2)) 6980 // (and (srl x, C2), C1) 6981 // (shl (and x, C1), C2) 6982 // (srl (and x, (C1 << C2)), C2) 6983 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6984 // The expected masks for each shift amount are specified in BitmanipMasks where 6985 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6986 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6987 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6988 // XLen is 64. 6989 static Optional<RISCVBitmanipPat> 6990 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6991 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6992 "Unexpected number of masks"); 6993 Optional<uint64_t> Mask; 6994 // Optionally consume a mask around the shift operation. 6995 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6996 Mask = Op.getConstantOperandVal(1); 6997 Op = Op.getOperand(0); 6998 } 6999 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7000 return None; 7001 bool IsSHL = Op.getOpcode() == ISD::SHL; 7002 7003 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7004 return None; 7005 uint64_t ShAmt = Op.getConstantOperandVal(1); 7006 7007 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7008 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7009 return None; 7010 // If we don't have enough masks for 64 bit, then we must be trying to 7011 // match SHFL so we're only allowed to shift 1/4 of the width. 7012 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7013 return None; 7014 7015 SDValue Src = Op.getOperand(0); 7016 7017 // The expected mask is shifted left when the AND is found around SHL 7018 // patterns. 7019 // ((x >> 1) & 0x55555555) 7020 // ((x << 1) & 0xAAAAAAAA) 7021 bool SHLExpMask = IsSHL; 7022 7023 if (!Mask) { 7024 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7025 // the mask is all ones: consume that now. 7026 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7027 Mask = Src.getConstantOperandVal(1); 7028 Src = Src.getOperand(0); 7029 // The expected mask is now in fact shifted left for SRL, so reverse the 7030 // decision. 7031 // ((x & 0xAAAAAAAA) >> 1) 7032 // ((x & 0x55555555) << 1) 7033 SHLExpMask = !SHLExpMask; 7034 } else { 7035 // Use a default shifted mask of all-ones if there's no AND, truncated 7036 // down to the expected width. This simplifies the logic later on. 7037 Mask = maskTrailingOnes<uint64_t>(Width); 7038 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7039 } 7040 } 7041 7042 unsigned MaskIdx = Log2_32(ShAmt); 7043 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7044 7045 if (SHLExpMask) 7046 ExpMask <<= ShAmt; 7047 7048 if (Mask != ExpMask) 7049 return None; 7050 7051 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7052 } 7053 7054 // Matches any of the following bit-manipulation patterns: 7055 // (and (shl x, 1), (0x55555555 << 1)) 7056 // (and (srl x, 1), 0x55555555) 7057 // (shl (and x, 0x55555555), 1) 7058 // (srl (and x, (0x55555555 << 1)), 1) 7059 // where the shift amount and mask may vary thus: 7060 // [1] = 0x55555555 / 0xAAAAAAAA 7061 // [2] = 0x33333333 / 0xCCCCCCCC 7062 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7063 // [8] = 0x00FF00FF / 0xFF00FF00 7064 // [16] = 0x0000FFFF / 0xFFFFFFFF 7065 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7066 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7067 // These are the unshifted masks which we use to match bit-manipulation 7068 // patterns. They may be shifted left in certain circumstances. 7069 static const uint64_t BitmanipMasks[] = { 7070 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7071 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7072 7073 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7074 } 7075 7076 // Match the following pattern as a GREVI(W) operation 7077 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7078 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7079 const RISCVSubtarget &Subtarget) { 7080 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7081 EVT VT = Op.getValueType(); 7082 7083 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7084 auto LHS = matchGREVIPat(Op.getOperand(0)); 7085 auto RHS = matchGREVIPat(Op.getOperand(1)); 7086 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7087 SDLoc DL(Op); 7088 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7089 DAG.getConstant(LHS->ShAmt, DL, VT)); 7090 } 7091 } 7092 return SDValue(); 7093 } 7094 7095 // Matches any the following pattern as a GORCI(W) operation 7096 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7097 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7098 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7099 // Note that with the variant of 3., 7100 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7101 // the inner pattern will first be matched as GREVI and then the outer 7102 // pattern will be matched to GORC via the first rule above. 7103 // 4. (or (rotl/rotr x, bitwidth/2), x) 7104 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7105 const RISCVSubtarget &Subtarget) { 7106 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7107 EVT VT = Op.getValueType(); 7108 7109 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7110 SDLoc DL(Op); 7111 SDValue Op0 = Op.getOperand(0); 7112 SDValue Op1 = Op.getOperand(1); 7113 7114 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7115 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7116 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7117 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7118 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7119 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7120 if ((Reverse.getOpcode() == ISD::ROTL || 7121 Reverse.getOpcode() == ISD::ROTR) && 7122 Reverse.getOperand(0) == X && 7123 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7124 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7125 if (RotAmt == (VT.getSizeInBits() / 2)) 7126 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7127 DAG.getConstant(RotAmt, DL, VT)); 7128 } 7129 return SDValue(); 7130 }; 7131 7132 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7133 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7134 return V; 7135 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7136 return V; 7137 7138 // OR is commutable so canonicalize its OR operand to the left 7139 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7140 std::swap(Op0, Op1); 7141 if (Op0.getOpcode() != ISD::OR) 7142 return SDValue(); 7143 SDValue OrOp0 = Op0.getOperand(0); 7144 SDValue OrOp1 = Op0.getOperand(1); 7145 auto LHS = matchGREVIPat(OrOp0); 7146 // OR is commutable so swap the operands and try again: x might have been 7147 // on the left 7148 if (!LHS) { 7149 std::swap(OrOp0, OrOp1); 7150 LHS = matchGREVIPat(OrOp0); 7151 } 7152 auto RHS = matchGREVIPat(Op1); 7153 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7154 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7155 DAG.getConstant(LHS->ShAmt, DL, VT)); 7156 } 7157 } 7158 return SDValue(); 7159 } 7160 7161 // Matches any of the following bit-manipulation patterns: 7162 // (and (shl x, 1), (0x22222222 << 1)) 7163 // (and (srl x, 1), 0x22222222) 7164 // (shl (and x, 0x22222222), 1) 7165 // (srl (and x, (0x22222222 << 1)), 1) 7166 // where the shift amount and mask may vary thus: 7167 // [1] = 0x22222222 / 0x44444444 7168 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7169 // [4] = 0x00F000F0 / 0x0F000F00 7170 // [8] = 0x0000FF00 / 0x00FF0000 7171 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7172 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7173 // These are the unshifted masks which we use to match bit-manipulation 7174 // patterns. They may be shifted left in certain circumstances. 7175 static const uint64_t BitmanipMasks[] = { 7176 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7177 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7178 7179 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7180 } 7181 7182 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7183 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7184 const RISCVSubtarget &Subtarget) { 7185 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7186 EVT VT = Op.getValueType(); 7187 7188 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7189 return SDValue(); 7190 7191 SDValue Op0 = Op.getOperand(0); 7192 SDValue Op1 = Op.getOperand(1); 7193 7194 // Or is commutable so canonicalize the second OR to the LHS. 7195 if (Op0.getOpcode() != ISD::OR) 7196 std::swap(Op0, Op1); 7197 if (Op0.getOpcode() != ISD::OR) 7198 return SDValue(); 7199 7200 // We found an inner OR, so our operands are the operands of the inner OR 7201 // and the other operand of the outer OR. 7202 SDValue A = Op0.getOperand(0); 7203 SDValue B = Op0.getOperand(1); 7204 SDValue C = Op1; 7205 7206 auto Match1 = matchSHFLPat(A); 7207 auto Match2 = matchSHFLPat(B); 7208 7209 // If neither matched, we failed. 7210 if (!Match1 && !Match2) 7211 return SDValue(); 7212 7213 // We had at least one match. if one failed, try the remaining C operand. 7214 if (!Match1) { 7215 std::swap(A, C); 7216 Match1 = matchSHFLPat(A); 7217 if (!Match1) 7218 return SDValue(); 7219 } else if (!Match2) { 7220 std::swap(B, C); 7221 Match2 = matchSHFLPat(B); 7222 if (!Match2) 7223 return SDValue(); 7224 } 7225 assert(Match1 && Match2); 7226 7227 // Make sure our matches pair up. 7228 if (!Match1->formsPairWith(*Match2)) 7229 return SDValue(); 7230 7231 // All the remains is to make sure C is an AND with the same input, that masks 7232 // out the bits that are being shuffled. 7233 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7234 C.getOperand(0) != Match1->Op) 7235 return SDValue(); 7236 7237 uint64_t Mask = C.getConstantOperandVal(1); 7238 7239 static const uint64_t BitmanipMasks[] = { 7240 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7241 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7242 }; 7243 7244 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7245 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7246 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7247 7248 if (Mask != ExpMask) 7249 return SDValue(); 7250 7251 SDLoc DL(Op); 7252 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7253 DAG.getConstant(Match1->ShAmt, DL, VT)); 7254 } 7255 7256 // Optimize (add (shl x, c0), (shl y, c1)) -> 7257 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7258 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7259 const RISCVSubtarget &Subtarget) { 7260 // Perform this optimization only in the zba extension. 7261 if (!Subtarget.hasStdExtZba()) 7262 return SDValue(); 7263 7264 // Skip for vector types and larger types. 7265 EVT VT = N->getValueType(0); 7266 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7267 return SDValue(); 7268 7269 // The two operand nodes must be SHL and have no other use. 7270 SDValue N0 = N->getOperand(0); 7271 SDValue N1 = N->getOperand(1); 7272 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7273 !N0->hasOneUse() || !N1->hasOneUse()) 7274 return SDValue(); 7275 7276 // Check c0 and c1. 7277 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7278 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7279 if (!N0C || !N1C) 7280 return SDValue(); 7281 int64_t C0 = N0C->getSExtValue(); 7282 int64_t C1 = N1C->getSExtValue(); 7283 if (C0 <= 0 || C1 <= 0) 7284 return SDValue(); 7285 7286 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7287 int64_t Bits = std::min(C0, C1); 7288 int64_t Diff = std::abs(C0 - C1); 7289 if (Diff != 1 && Diff != 2 && Diff != 3) 7290 return SDValue(); 7291 7292 // Build nodes. 7293 SDLoc DL(N); 7294 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7295 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7296 SDValue NA0 = 7297 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7298 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7299 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7300 } 7301 7302 // Combine 7303 // ROTR ((GREV x, 24), 16) -> (GREVI x, 8) 7304 // ROTL ((GREV x, 24), 16) -> (GREVI x, 8) 7305 // RORW ((GREVW x, 24), 16) -> (GREVIW x, 8) 7306 // ROLW ((GREVW x, 24), 16) -> (GREVIW x, 8) 7307 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG) { 7308 SDValue Src = N->getOperand(0); 7309 SDLoc DL(N); 7310 unsigned Opc; 7311 7312 if ((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL) && 7313 Src.getOpcode() == RISCVISD::GREV) 7314 Opc = RISCVISD::GREV; 7315 else if ((N->getOpcode() == RISCVISD::RORW || 7316 N->getOpcode() == RISCVISD::ROLW) && 7317 Src.getOpcode() == RISCVISD::GREVW) 7318 Opc = RISCVISD::GREVW; 7319 else 7320 return SDValue(); 7321 7322 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7323 !isa<ConstantSDNode>(Src.getOperand(1))) 7324 return SDValue(); 7325 7326 unsigned ShAmt1 = N->getConstantOperandVal(1); 7327 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7328 if (ShAmt1 != 16 && ShAmt2 != 24) 7329 return SDValue(); 7330 7331 Src = Src.getOperand(0); 7332 return DAG.getNode(Opc, DL, N->getValueType(0), Src, 7333 DAG.getConstant(8, DL, N->getOperand(1).getValueType())); 7334 } 7335 7336 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7337 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7338 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7339 // not undo itself, but they are redundant. 7340 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7341 SDValue Src = N->getOperand(0); 7342 7343 if (Src.getOpcode() != N->getOpcode()) 7344 return SDValue(); 7345 7346 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7347 !isa<ConstantSDNode>(Src.getOperand(1))) 7348 return SDValue(); 7349 7350 unsigned ShAmt1 = N->getConstantOperandVal(1); 7351 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7352 Src = Src.getOperand(0); 7353 7354 unsigned CombinedShAmt; 7355 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 7356 CombinedShAmt = ShAmt1 | ShAmt2; 7357 else 7358 CombinedShAmt = ShAmt1 ^ ShAmt2; 7359 7360 if (CombinedShAmt == 0) 7361 return Src; 7362 7363 SDLoc DL(N); 7364 return DAG.getNode( 7365 N->getOpcode(), DL, N->getValueType(0), Src, 7366 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7367 } 7368 7369 // Combine a constant select operand into its use: 7370 // 7371 // (and (select cond, -1, c), x) 7372 // -> (select cond, x, (and x, c)) [AllOnes=1] 7373 // (or (select cond, 0, c), x) 7374 // -> (select cond, x, (or x, c)) [AllOnes=0] 7375 // (xor (select cond, 0, c), x) 7376 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7377 // (add (select cond, 0, c), x) 7378 // -> (select cond, x, (add x, c)) [AllOnes=0] 7379 // (sub x, (select cond, 0, c)) 7380 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7381 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7382 SelectionDAG &DAG, bool AllOnes) { 7383 EVT VT = N->getValueType(0); 7384 7385 // Skip vectors. 7386 if (VT.isVector()) 7387 return SDValue(); 7388 7389 if ((Slct.getOpcode() != ISD::SELECT && 7390 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7391 !Slct.hasOneUse()) 7392 return SDValue(); 7393 7394 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7395 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7396 }; 7397 7398 bool SwapSelectOps; 7399 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7400 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7401 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7402 SDValue NonConstantVal; 7403 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7404 SwapSelectOps = false; 7405 NonConstantVal = FalseVal; 7406 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7407 SwapSelectOps = true; 7408 NonConstantVal = TrueVal; 7409 } else 7410 return SDValue(); 7411 7412 // Slct is now know to be the desired identity constant when CC is true. 7413 TrueVal = OtherOp; 7414 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7415 // Unless SwapSelectOps says the condition should be false. 7416 if (SwapSelectOps) 7417 std::swap(TrueVal, FalseVal); 7418 7419 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7420 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7421 {Slct.getOperand(0), Slct.getOperand(1), 7422 Slct.getOperand(2), TrueVal, FalseVal}); 7423 7424 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7425 {Slct.getOperand(0), TrueVal, FalseVal}); 7426 } 7427 7428 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7429 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7430 bool AllOnes) { 7431 SDValue N0 = N->getOperand(0); 7432 SDValue N1 = N->getOperand(1); 7433 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7434 return Result; 7435 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7436 return Result; 7437 return SDValue(); 7438 } 7439 7440 // Transform (add (mul x, c0), c1) -> 7441 // (add (mul (add x, c1/c0), c0), c1%c0). 7442 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7443 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7444 // to an infinite loop in DAGCombine if transformed. 7445 // Or transform (add (mul x, c0), c1) -> 7446 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7447 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7448 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7449 // lead to an infinite loop in DAGCombine if transformed. 7450 // Or transform (add (mul x, c0), c1) -> 7451 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7452 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7453 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7454 // lead to an infinite loop in DAGCombine if transformed. 7455 // Or transform (add (mul x, c0), c1) -> 7456 // (mul (add x, c1/c0), c0). 7457 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7458 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7459 const RISCVSubtarget &Subtarget) { 7460 // Skip for vector types and larger types. 7461 EVT VT = N->getValueType(0); 7462 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7463 return SDValue(); 7464 // The first operand node must be a MUL and has no other use. 7465 SDValue N0 = N->getOperand(0); 7466 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7467 return SDValue(); 7468 // Check if c0 and c1 match above conditions. 7469 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7470 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7471 if (!N0C || !N1C) 7472 return SDValue(); 7473 int64_t C0 = N0C->getSExtValue(); 7474 int64_t C1 = N1C->getSExtValue(); 7475 int64_t CA, CB; 7476 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7477 return SDValue(); 7478 // Search for proper CA (non-zero) and CB that both are simm12. 7479 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7480 !isInt<12>(C0 * (C1 / C0))) { 7481 CA = C1 / C0; 7482 CB = C1 % C0; 7483 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7484 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7485 CA = C1 / C0 + 1; 7486 CB = C1 % C0 - C0; 7487 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7488 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7489 CA = C1 / C0 - 1; 7490 CB = C1 % C0 + C0; 7491 } else 7492 return SDValue(); 7493 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7494 SDLoc DL(N); 7495 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7496 DAG.getConstant(CA, DL, VT)); 7497 SDValue New1 = 7498 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7499 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7500 } 7501 7502 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7503 const RISCVSubtarget &Subtarget) { 7504 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7505 return V; 7506 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7507 return V; 7508 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7509 // (select lhs, rhs, cc, x, (add x, y)) 7510 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7511 } 7512 7513 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7514 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7515 // (select lhs, rhs, cc, x, (sub x, y)) 7516 SDValue N0 = N->getOperand(0); 7517 SDValue N1 = N->getOperand(1); 7518 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7519 } 7520 7521 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7522 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7523 // (select lhs, rhs, cc, x, (and x, y)) 7524 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7525 } 7526 7527 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7528 const RISCVSubtarget &Subtarget) { 7529 if (Subtarget.hasStdExtZbp()) { 7530 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7531 return GREV; 7532 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7533 return GORC; 7534 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7535 return SHFL; 7536 } 7537 7538 // fold (or (select cond, 0, y), x) -> 7539 // (select cond, x, (or x, y)) 7540 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7541 } 7542 7543 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7544 // fold (xor (select cond, 0, y), x) -> 7545 // (select cond, x, (xor x, y)) 7546 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7547 } 7548 7549 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 7550 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 7551 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 7552 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 7553 // ADDW/SUBW/MULW. 7554 static SDValue performANY_EXTENDCombine(SDNode *N, 7555 TargetLowering::DAGCombinerInfo &DCI, 7556 const RISCVSubtarget &Subtarget) { 7557 if (!Subtarget.is64Bit()) 7558 return SDValue(); 7559 7560 SelectionDAG &DAG = DCI.DAG; 7561 7562 SDValue Src = N->getOperand(0); 7563 EVT VT = N->getValueType(0); 7564 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 7565 return SDValue(); 7566 7567 // The opcode must be one that can implicitly sign_extend. 7568 // FIXME: Additional opcodes. 7569 switch (Src.getOpcode()) { 7570 default: 7571 return SDValue(); 7572 case ISD::MUL: 7573 if (!Subtarget.hasStdExtM()) 7574 return SDValue(); 7575 LLVM_FALLTHROUGH; 7576 case ISD::ADD: 7577 case ISD::SUB: 7578 break; 7579 } 7580 7581 // Only handle cases where the result is used by a CopyToReg. That likely 7582 // means the value is a liveout of the basic block. This helps prevent 7583 // infinite combine loops like PR51206. 7584 if (none_of(N->uses(), 7585 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 7586 return SDValue(); 7587 7588 SmallVector<SDNode *, 4> SetCCs; 7589 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 7590 UE = Src.getNode()->use_end(); 7591 UI != UE; ++UI) { 7592 SDNode *User = *UI; 7593 if (User == N) 7594 continue; 7595 if (UI.getUse().getResNo() != Src.getResNo()) 7596 continue; 7597 // All i32 setccs are legalized by sign extending operands. 7598 if (User->getOpcode() == ISD::SETCC) { 7599 SetCCs.push_back(User); 7600 continue; 7601 } 7602 // We don't know if we can extend this user. 7603 break; 7604 } 7605 7606 // If we don't have any SetCCs, this isn't worthwhile. 7607 if (SetCCs.empty()) 7608 return SDValue(); 7609 7610 SDLoc DL(N); 7611 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 7612 DCI.CombineTo(N, SExt); 7613 7614 // Promote all the setccs. 7615 for (SDNode *SetCC : SetCCs) { 7616 SmallVector<SDValue, 4> Ops; 7617 7618 for (unsigned j = 0; j != 2; ++j) { 7619 SDValue SOp = SetCC->getOperand(j); 7620 if (SOp == Src) 7621 Ops.push_back(SExt); 7622 else 7623 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 7624 } 7625 7626 Ops.push_back(SetCC->getOperand(2)); 7627 DCI.CombineTo(SetCC, 7628 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7629 } 7630 return SDValue(N, 0); 7631 } 7632 7633 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7634 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7635 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7636 bool Commute = false) { 7637 assert((N->getOpcode() == RISCVISD::ADD_VL || 7638 N->getOpcode() == RISCVISD::SUB_VL) && 7639 "Unexpected opcode"); 7640 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7641 SDValue Op0 = N->getOperand(0); 7642 SDValue Op1 = N->getOperand(1); 7643 if (Commute) 7644 std::swap(Op0, Op1); 7645 7646 MVT VT = N->getSimpleValueType(0); 7647 7648 // Determine the narrow size for a widening add/sub. 7649 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7650 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7651 VT.getVectorElementCount()); 7652 7653 SDValue Mask = N->getOperand(2); 7654 SDValue VL = N->getOperand(3); 7655 7656 SDLoc DL(N); 7657 7658 // If the RHS is a sext or zext, we can form a widening op. 7659 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7660 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7661 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7662 unsigned ExtOpc = Op1.getOpcode(); 7663 Op1 = Op1.getOperand(0); 7664 // Re-introduce narrower extends if needed. 7665 if (Op1.getValueType() != NarrowVT) 7666 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7667 7668 unsigned WOpc; 7669 if (ExtOpc == RISCVISD::VSEXT_VL) 7670 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7671 else 7672 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7673 7674 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7675 } 7676 7677 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7678 // sext/zext? 7679 7680 return SDValue(); 7681 } 7682 7683 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7684 // vwsub(u).vv/vx. 7685 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7686 SDValue Op0 = N->getOperand(0); 7687 SDValue Op1 = N->getOperand(1); 7688 SDValue Mask = N->getOperand(2); 7689 SDValue VL = N->getOperand(3); 7690 7691 MVT VT = N->getSimpleValueType(0); 7692 MVT NarrowVT = Op1.getSimpleValueType(); 7693 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 7694 7695 unsigned VOpc; 7696 switch (N->getOpcode()) { 7697 default: llvm_unreachable("Unexpected opcode"); 7698 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 7699 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 7700 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 7701 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 7702 } 7703 7704 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 7705 N->getOpcode() == RISCVISD::VWSUB_W_VL; 7706 7707 SDLoc DL(N); 7708 7709 // If the LHS is a sext or zext, we can narrow this op to the same size as 7710 // the RHS. 7711 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 7712 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 7713 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 7714 unsigned ExtOpc = Op0.getOpcode(); 7715 Op0 = Op0.getOperand(0); 7716 // Re-introduce narrower extends if needed. 7717 if (Op0.getValueType() != NarrowVT) 7718 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7719 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 7720 } 7721 7722 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 7723 N->getOpcode() == RISCVISD::VWADDU_W_VL; 7724 7725 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 7726 // to commute and use a vwadd(u).vx instead. 7727 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 7728 Op0.getOperand(1) == VL) { 7729 Op0 = Op0.getOperand(0); 7730 7731 // See if have enough sign bits or zero bits in the scalar to use a 7732 // widening add/sub by splatting to smaller element size. 7733 unsigned EltBits = VT.getScalarSizeInBits(); 7734 unsigned ScalarBits = Op0.getValueSizeInBits(); 7735 // Make sure we're getting all element bits from the scalar register. 7736 // FIXME: Support implicit sign extension of vmv.v.x? 7737 if (ScalarBits < EltBits) 7738 return SDValue(); 7739 7740 if (IsSigned) { 7741 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 7742 return SDValue(); 7743 } else { 7744 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7745 if (!DAG.MaskedValueIsZero(Op0, Mask)) 7746 return SDValue(); 7747 } 7748 7749 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op0, VL); 7750 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 7751 } 7752 7753 return SDValue(); 7754 } 7755 7756 // Try to form VWMUL, VWMULU or VWMULSU. 7757 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 7758 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 7759 bool Commute) { 7760 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7761 SDValue Op0 = N->getOperand(0); 7762 SDValue Op1 = N->getOperand(1); 7763 if (Commute) 7764 std::swap(Op0, Op1); 7765 7766 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7767 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7768 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 7769 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7770 return SDValue(); 7771 7772 SDValue Mask = N->getOperand(2); 7773 SDValue VL = N->getOperand(3); 7774 7775 // Make sure the mask and VL match. 7776 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7777 return SDValue(); 7778 7779 MVT VT = N->getSimpleValueType(0); 7780 7781 // Determine the narrow size for a widening multiply. 7782 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7783 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7784 VT.getVectorElementCount()); 7785 7786 SDLoc DL(N); 7787 7788 // See if the other operand is the same opcode. 7789 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 7790 if (!Op1.hasOneUse()) 7791 return SDValue(); 7792 7793 // Make sure the mask and VL match. 7794 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7795 return SDValue(); 7796 7797 Op1 = Op1.getOperand(0); 7798 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7799 // The operand is a splat of a scalar. 7800 7801 // The VL must be the same. 7802 if (Op1.getOperand(1) != VL) 7803 return SDValue(); 7804 7805 // Get the scalar value. 7806 Op1 = Op1.getOperand(0); 7807 7808 // See if have enough sign bits or zero bits in the scalar to use a 7809 // widening multiply by splatting to smaller element size. 7810 unsigned EltBits = VT.getScalarSizeInBits(); 7811 unsigned ScalarBits = Op1.getValueSizeInBits(); 7812 // Make sure we're getting all element bits from the scalar register. 7813 // FIXME: Support implicit sign extension of vmv.v.x? 7814 if (ScalarBits < EltBits) 7815 return SDValue(); 7816 7817 // If the LHS is a sign extend, try to use vwmul. 7818 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 7819 // Can use vwmul. 7820 } else { 7821 // Otherwise try to use vwmulu or vwmulsu. 7822 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7823 if (DAG.MaskedValueIsZero(Op1, Mask)) 7824 IsVWMULSU = IsSignExt; 7825 else 7826 return SDValue(); 7827 } 7828 7829 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 7830 } else 7831 return SDValue(); 7832 7833 Op0 = Op0.getOperand(0); 7834 7835 // Re-introduce narrower extends if needed. 7836 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7837 if (Op0.getValueType() != NarrowVT) 7838 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7839 // vwmulsu requires second operand to be zero extended. 7840 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 7841 if (Op1.getValueType() != NarrowVT) 7842 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7843 7844 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 7845 if (!IsVWMULSU) 7846 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7847 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7848 } 7849 7850 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 7851 switch (Op.getOpcode()) { 7852 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 7853 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 7854 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 7855 case ISD::FCEIL: return RISCVFPRndMode::RUP; 7856 case ISD::FROUND: return RISCVFPRndMode::RMM; 7857 } 7858 7859 return RISCVFPRndMode::Invalid; 7860 } 7861 7862 // Fold 7863 // (fp_to_int (froundeven X)) -> fcvt X, rne 7864 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7865 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7866 // (fp_to_int (fceil X)) -> fcvt X, rup 7867 // (fp_to_int (fround X)) -> fcvt X, rmm 7868 static SDValue performFP_TO_INTCombine(SDNode *N, 7869 TargetLowering::DAGCombinerInfo &DCI, 7870 const RISCVSubtarget &Subtarget) { 7871 SelectionDAG &DAG = DCI.DAG; 7872 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7873 MVT XLenVT = Subtarget.getXLenVT(); 7874 7875 // Only handle XLen or i32 types. Other types narrower than XLen will 7876 // eventually be legalized to XLenVT. 7877 EVT VT = N->getValueType(0); 7878 if (VT != MVT::i32 && VT != XLenVT) 7879 return SDValue(); 7880 7881 SDValue Src = N->getOperand(0); 7882 7883 // Ensure the FP type is also legal. 7884 if (!TLI.isTypeLegal(Src.getValueType())) 7885 return SDValue(); 7886 7887 // Don't do this for f16 with Zfhmin and not Zfh. 7888 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7889 return SDValue(); 7890 7891 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7892 if (FRM == RISCVFPRndMode::Invalid) 7893 return SDValue(); 7894 7895 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7896 7897 unsigned Opc; 7898 if (VT == XLenVT) 7899 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7900 else 7901 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7902 7903 SDLoc DL(N); 7904 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 7905 DAG.getTargetConstant(FRM, DL, XLenVT)); 7906 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 7907 } 7908 7909 // Fold 7910 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 7911 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 7912 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 7913 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 7914 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 7915 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 7916 TargetLowering::DAGCombinerInfo &DCI, 7917 const RISCVSubtarget &Subtarget) { 7918 SelectionDAG &DAG = DCI.DAG; 7919 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7920 MVT XLenVT = Subtarget.getXLenVT(); 7921 7922 // Only handle XLen types. Other types narrower than XLen will eventually be 7923 // legalized to XLenVT. 7924 EVT DstVT = N->getValueType(0); 7925 if (DstVT != XLenVT) 7926 return SDValue(); 7927 7928 SDValue Src = N->getOperand(0); 7929 7930 // Ensure the FP type is also legal. 7931 if (!TLI.isTypeLegal(Src.getValueType())) 7932 return SDValue(); 7933 7934 // Don't do this for f16 with Zfhmin and not Zfh. 7935 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7936 return SDValue(); 7937 7938 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7939 7940 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7941 if (FRM == RISCVFPRndMode::Invalid) 7942 return SDValue(); 7943 7944 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 7945 7946 unsigned Opc; 7947 if (SatVT == DstVT) 7948 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7949 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 7950 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7951 else 7952 return SDValue(); 7953 // FIXME: Support other SatVTs by clamping before or after the conversion. 7954 7955 Src = Src.getOperand(0); 7956 7957 SDLoc DL(N); 7958 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 7959 DAG.getTargetConstant(FRM, DL, XLenVT)); 7960 7961 // RISCV FP-to-int conversions saturate to the destination register size, but 7962 // don't produce 0 for nan. 7963 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 7964 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 7965 } 7966 7967 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 7968 DAGCombinerInfo &DCI) const { 7969 SelectionDAG &DAG = DCI.DAG; 7970 7971 // Helper to call SimplifyDemandedBits on an operand of N where only some low 7972 // bits are demanded. N will be added to the Worklist if it was not deleted. 7973 // Caller should return SDValue(N, 0) if this returns true. 7974 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 7975 SDValue Op = N->getOperand(OpNo); 7976 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 7977 if (!SimplifyDemandedBits(Op, Mask, DCI)) 7978 return false; 7979 7980 if (N->getOpcode() != ISD::DELETED_NODE) 7981 DCI.AddToWorklist(N); 7982 return true; 7983 }; 7984 7985 switch (N->getOpcode()) { 7986 default: 7987 break; 7988 case RISCVISD::SplitF64: { 7989 SDValue Op0 = N->getOperand(0); 7990 // If the input to SplitF64 is just BuildPairF64 then the operation is 7991 // redundant. Instead, use BuildPairF64's operands directly. 7992 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 7993 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 7994 7995 if (Op0->isUndef()) { 7996 SDValue Lo = DAG.getUNDEF(MVT::i32); 7997 SDValue Hi = DAG.getUNDEF(MVT::i32); 7998 return DCI.CombineTo(N, Lo, Hi); 7999 } 8000 8001 SDLoc DL(N); 8002 8003 // It's cheaper to materialise two 32-bit integers than to load a double 8004 // from the constant pool and transfer it to integer registers through the 8005 // stack. 8006 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8007 APInt V = C->getValueAPF().bitcastToAPInt(); 8008 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8009 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8010 return DCI.CombineTo(N, Lo, Hi); 8011 } 8012 8013 // This is a target-specific version of a DAGCombine performed in 8014 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8015 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8016 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8017 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8018 !Op0.getNode()->hasOneUse()) 8019 break; 8020 SDValue NewSplitF64 = 8021 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8022 Op0.getOperand(0)); 8023 SDValue Lo = NewSplitF64.getValue(0); 8024 SDValue Hi = NewSplitF64.getValue(1); 8025 APInt SignBit = APInt::getSignMask(32); 8026 if (Op0.getOpcode() == ISD::FNEG) { 8027 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8028 DAG.getConstant(SignBit, DL, MVT::i32)); 8029 return DCI.CombineTo(N, Lo, NewHi); 8030 } 8031 assert(Op0.getOpcode() == ISD::FABS); 8032 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8033 DAG.getConstant(~SignBit, DL, MVT::i32)); 8034 return DCI.CombineTo(N, Lo, NewHi); 8035 } 8036 case RISCVISD::SLLW: 8037 case RISCVISD::SRAW: 8038 case RISCVISD::SRLW: 8039 case RISCVISD::ROLW: 8040 case RISCVISD::RORW: { 8041 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8042 if (SimplifyDemandedLowBitsHelper(0, 32) || 8043 SimplifyDemandedLowBitsHelper(1, 5)) 8044 return SDValue(N, 0); 8045 8046 return combineROTR_ROTL_RORW_ROLW(N, DAG); 8047 } 8048 case ISD::ROTR: 8049 case ISD::ROTL: 8050 return combineROTR_ROTL_RORW_ROLW(N, DAG); 8051 case RISCVISD::CLZW: 8052 case RISCVISD::CTZW: { 8053 // Only the lower 32 bits of the first operand are read 8054 if (SimplifyDemandedLowBitsHelper(0, 32)) 8055 return SDValue(N, 0); 8056 break; 8057 } 8058 case RISCVISD::GREV: 8059 case RISCVISD::GORC: { 8060 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8061 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8062 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8063 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8064 return SDValue(N, 0); 8065 8066 return combineGREVI_GORCI(N, DAG); 8067 } 8068 case RISCVISD::GREVW: 8069 case RISCVISD::GORCW: { 8070 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8071 if (SimplifyDemandedLowBitsHelper(0, 32) || 8072 SimplifyDemandedLowBitsHelper(1, 5)) 8073 return SDValue(N, 0); 8074 8075 return combineGREVI_GORCI(N, DAG); 8076 } 8077 case RISCVISD::SHFL: 8078 case RISCVISD::UNSHFL: { 8079 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8080 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8081 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8082 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8083 return SDValue(N, 0); 8084 8085 break; 8086 } 8087 case RISCVISD::SHFLW: 8088 case RISCVISD::UNSHFLW: { 8089 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8090 if (SimplifyDemandedLowBitsHelper(0, 32) || 8091 SimplifyDemandedLowBitsHelper(1, 4)) 8092 return SDValue(N, 0); 8093 8094 break; 8095 } 8096 case RISCVISD::BCOMPRESSW: 8097 case RISCVISD::BDECOMPRESSW: { 8098 // Only the lower 32 bits of LHS and RHS are read. 8099 if (SimplifyDemandedLowBitsHelper(0, 32) || 8100 SimplifyDemandedLowBitsHelper(1, 32)) 8101 return SDValue(N, 0); 8102 8103 break; 8104 } 8105 case RISCVISD::FMV_X_ANYEXTH: 8106 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8107 SDLoc DL(N); 8108 SDValue Op0 = N->getOperand(0); 8109 MVT VT = N->getSimpleValueType(0); 8110 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8111 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8112 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8113 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8114 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8115 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8116 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8117 assert(Op0.getOperand(0).getValueType() == VT && 8118 "Unexpected value type!"); 8119 return Op0.getOperand(0); 8120 } 8121 8122 // This is a target-specific version of a DAGCombine performed in 8123 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8124 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8125 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8126 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8127 !Op0.getNode()->hasOneUse()) 8128 break; 8129 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8130 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8131 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8132 if (Op0.getOpcode() == ISD::FNEG) 8133 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8134 DAG.getConstant(SignBit, DL, VT)); 8135 8136 assert(Op0.getOpcode() == ISD::FABS); 8137 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8138 DAG.getConstant(~SignBit, DL, VT)); 8139 } 8140 case ISD::ADD: 8141 return performADDCombine(N, DAG, Subtarget); 8142 case ISD::SUB: 8143 return performSUBCombine(N, DAG); 8144 case ISD::AND: 8145 return performANDCombine(N, DAG); 8146 case ISD::OR: 8147 return performORCombine(N, DAG, Subtarget); 8148 case ISD::XOR: 8149 return performXORCombine(N, DAG); 8150 case ISD::ANY_EXTEND: 8151 return performANY_EXTENDCombine(N, DCI, Subtarget); 8152 case ISD::ZERO_EXTEND: 8153 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8154 // type legalization. This is safe because fp_to_uint produces poison if 8155 // it overflows. 8156 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8157 SDValue Src = N->getOperand(0); 8158 if (Src.getOpcode() == ISD::FP_TO_UINT && 8159 isTypeLegal(Src.getOperand(0).getValueType())) 8160 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8161 Src.getOperand(0)); 8162 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8163 isTypeLegal(Src.getOperand(1).getValueType())) { 8164 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8165 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8166 Src.getOperand(0), Src.getOperand(1)); 8167 DCI.CombineTo(N, Res); 8168 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8169 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8170 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8171 } 8172 } 8173 return SDValue(); 8174 case RISCVISD::SELECT_CC: { 8175 // Transform 8176 SDValue LHS = N->getOperand(0); 8177 SDValue RHS = N->getOperand(1); 8178 SDValue TrueV = N->getOperand(3); 8179 SDValue FalseV = N->getOperand(4); 8180 8181 // If the True and False values are the same, we don't need a select_cc. 8182 if (TrueV == FalseV) 8183 return TrueV; 8184 8185 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8186 if (!ISD::isIntEqualitySetCC(CCVal)) 8187 break; 8188 8189 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8190 // (select_cc X, Y, lt, trueV, falseV) 8191 // Sometimes the setcc is introduced after select_cc has been formed. 8192 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8193 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8194 // If we're looking for eq 0 instead of ne 0, we need to invert the 8195 // condition. 8196 bool Invert = CCVal == ISD::SETEQ; 8197 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8198 if (Invert) 8199 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8200 8201 SDLoc DL(N); 8202 RHS = LHS.getOperand(1); 8203 LHS = LHS.getOperand(0); 8204 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8205 8206 SDValue TargetCC = DAG.getCondCode(CCVal); 8207 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8208 {LHS, RHS, TargetCC, TrueV, FalseV}); 8209 } 8210 8211 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8212 // (select_cc X, Y, eq/ne, trueV, falseV) 8213 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8214 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8215 {LHS.getOperand(0), LHS.getOperand(1), 8216 N->getOperand(2), TrueV, FalseV}); 8217 // (select_cc X, 1, setne, trueV, falseV) -> 8218 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8219 // This can occur when legalizing some floating point comparisons. 8220 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8221 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8222 SDLoc DL(N); 8223 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8224 SDValue TargetCC = DAG.getCondCode(CCVal); 8225 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8226 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8227 {LHS, RHS, TargetCC, TrueV, FalseV}); 8228 } 8229 8230 break; 8231 } 8232 case RISCVISD::BR_CC: { 8233 SDValue LHS = N->getOperand(1); 8234 SDValue RHS = N->getOperand(2); 8235 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8236 if (!ISD::isIntEqualitySetCC(CCVal)) 8237 break; 8238 8239 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8240 // (br_cc X, Y, lt, dest) 8241 // Sometimes the setcc is introduced after br_cc has been formed. 8242 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8243 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8244 // If we're looking for eq 0 instead of ne 0, we need to invert the 8245 // condition. 8246 bool Invert = CCVal == ISD::SETEQ; 8247 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8248 if (Invert) 8249 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8250 8251 SDLoc DL(N); 8252 RHS = LHS.getOperand(1); 8253 LHS = LHS.getOperand(0); 8254 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8255 8256 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8257 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8258 N->getOperand(4)); 8259 } 8260 8261 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8262 // (br_cc X, Y, eq/ne, trueV, falseV) 8263 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8264 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8265 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8266 N->getOperand(3), N->getOperand(4)); 8267 8268 // (br_cc X, 1, setne, br_cc) -> 8269 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8270 // This can occur when legalizing some floating point comparisons. 8271 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8272 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8273 SDLoc DL(N); 8274 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8275 SDValue TargetCC = DAG.getCondCode(CCVal); 8276 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8277 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8278 N->getOperand(0), LHS, RHS, TargetCC, 8279 N->getOperand(4)); 8280 } 8281 break; 8282 } 8283 case ISD::FP_TO_SINT: 8284 case ISD::FP_TO_UINT: 8285 return performFP_TO_INTCombine(N, DCI, Subtarget); 8286 case ISD::FP_TO_SINT_SAT: 8287 case ISD::FP_TO_UINT_SAT: 8288 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8289 case ISD::FCOPYSIGN: { 8290 EVT VT = N->getValueType(0); 8291 if (!VT.isVector()) 8292 break; 8293 // There is a form of VFSGNJ which injects the negated sign of its second 8294 // operand. Try and bubble any FNEG up after the extend/round to produce 8295 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8296 // TRUNC=1. 8297 SDValue In2 = N->getOperand(1); 8298 // Avoid cases where the extend/round has multiple uses, as duplicating 8299 // those is typically more expensive than removing a fneg. 8300 if (!In2.hasOneUse()) 8301 break; 8302 if (In2.getOpcode() != ISD::FP_EXTEND && 8303 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8304 break; 8305 In2 = In2.getOperand(0); 8306 if (In2.getOpcode() != ISD::FNEG) 8307 break; 8308 SDLoc DL(N); 8309 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8310 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8311 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8312 } 8313 case ISD::MGATHER: 8314 case ISD::MSCATTER: 8315 case ISD::VP_GATHER: 8316 case ISD::VP_SCATTER: { 8317 if (!DCI.isBeforeLegalize()) 8318 break; 8319 SDValue Index, ScaleOp; 8320 bool IsIndexScaled = false; 8321 bool IsIndexSigned = false; 8322 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8323 Index = VPGSN->getIndex(); 8324 ScaleOp = VPGSN->getScale(); 8325 IsIndexScaled = VPGSN->isIndexScaled(); 8326 IsIndexSigned = VPGSN->isIndexSigned(); 8327 } else { 8328 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8329 Index = MGSN->getIndex(); 8330 ScaleOp = MGSN->getScale(); 8331 IsIndexScaled = MGSN->isIndexScaled(); 8332 IsIndexSigned = MGSN->isIndexSigned(); 8333 } 8334 EVT IndexVT = Index.getValueType(); 8335 MVT XLenVT = Subtarget.getXLenVT(); 8336 // RISCV indexed loads only support the "unsigned unscaled" addressing 8337 // mode, so anything else must be manually legalized. 8338 bool NeedsIdxLegalization = 8339 IsIndexScaled || 8340 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8341 if (!NeedsIdxLegalization) 8342 break; 8343 8344 SDLoc DL(N); 8345 8346 // Any index legalization should first promote to XLenVT, so we don't lose 8347 // bits when scaling. This may create an illegal index type so we let 8348 // LLVM's legalization take care of the splitting. 8349 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8350 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8351 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8352 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8353 DL, IndexVT, Index); 8354 } 8355 8356 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8357 if (IsIndexScaled && Scale != 1) { 8358 // Manually scale the indices by the element size. 8359 // TODO: Sanitize the scale operand here? 8360 // TODO: For VP nodes, should we use VP_SHL here? 8361 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8362 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8363 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8364 } 8365 8366 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8367 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8368 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8369 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8370 VPGN->getScale(), VPGN->getMask(), 8371 VPGN->getVectorLength()}, 8372 VPGN->getMemOperand(), NewIndexTy); 8373 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8374 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8375 {VPSN->getChain(), VPSN->getValue(), 8376 VPSN->getBasePtr(), Index, VPSN->getScale(), 8377 VPSN->getMask(), VPSN->getVectorLength()}, 8378 VPSN->getMemOperand(), NewIndexTy); 8379 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8380 return DAG.getMaskedGather( 8381 N->getVTList(), MGN->getMemoryVT(), DL, 8382 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8383 MGN->getBasePtr(), Index, MGN->getScale()}, 8384 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8385 const auto *MSN = cast<MaskedScatterSDNode>(N); 8386 return DAG.getMaskedScatter( 8387 N->getVTList(), MSN->getMemoryVT(), DL, 8388 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8389 Index, MSN->getScale()}, 8390 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8391 } 8392 case RISCVISD::SRA_VL: 8393 case RISCVISD::SRL_VL: 8394 case RISCVISD::SHL_VL: { 8395 SDValue ShAmt = N->getOperand(1); 8396 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8397 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8398 SDLoc DL(N); 8399 SDValue VL = N->getOperand(3); 8400 EVT VT = N->getValueType(0); 8401 ShAmt = 8402 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 8403 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8404 N->getOperand(2), N->getOperand(3)); 8405 } 8406 break; 8407 } 8408 case ISD::SRA: 8409 case ISD::SRL: 8410 case ISD::SHL: { 8411 SDValue ShAmt = N->getOperand(1); 8412 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8413 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8414 SDLoc DL(N); 8415 EVT VT = N->getValueType(0); 8416 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), 8417 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8418 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8419 } 8420 break; 8421 } 8422 case RISCVISD::ADD_VL: 8423 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8424 return V; 8425 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8426 case RISCVISD::SUB_VL: 8427 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8428 case RISCVISD::VWADD_W_VL: 8429 case RISCVISD::VWADDU_W_VL: 8430 case RISCVISD::VWSUB_W_VL: 8431 case RISCVISD::VWSUBU_W_VL: 8432 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8433 case RISCVISD::MUL_VL: 8434 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8435 return V; 8436 // Mul is commutative. 8437 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8438 case ISD::STORE: { 8439 auto *Store = cast<StoreSDNode>(N); 8440 SDValue Val = Store->getValue(); 8441 // Combine store of vmv.x.s to vse with VL of 1. 8442 // FIXME: Support FP. 8443 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8444 SDValue Src = Val.getOperand(0); 8445 EVT VecVT = Src.getValueType(); 8446 EVT MemVT = Store->getMemoryVT(); 8447 // The memory VT and the element type must match. 8448 if (VecVT.getVectorElementType() == MemVT) { 8449 SDLoc DL(N); 8450 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8451 return DAG.getStoreVP( 8452 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8453 DAG.getConstant(1, DL, MaskVT), 8454 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8455 Store->getMemOperand(), Store->getAddressingMode(), 8456 Store->isTruncatingStore(), /*IsCompress*/ false); 8457 } 8458 } 8459 8460 break; 8461 } 8462 case ISD::SPLAT_VECTOR: { 8463 EVT VT = N->getValueType(0); 8464 // Only perform this combine on legal MVT types. 8465 if (!isTypeLegal(VT)) 8466 break; 8467 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8468 DAG, Subtarget)) 8469 return Gather; 8470 break; 8471 } 8472 case RISCVISD::VMV_V_X_VL: { 8473 // VMV.V.X only demands the vector element bitwidth from the scalar input. 8474 unsigned ScalarSize = N->getOperand(0).getValueSizeInBits(); 8475 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8476 if (ScalarSize > EltWidth) 8477 if (SimplifyDemandedLowBitsHelper(0, EltWidth)) 8478 return SDValue(N, 0); 8479 8480 break; 8481 } 8482 } 8483 8484 return SDValue(); 8485 } 8486 8487 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8488 const SDNode *N, CombineLevel Level) const { 8489 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8490 // materialised in fewer instructions than `(OP _, c1)`: 8491 // 8492 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8493 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8494 SDValue N0 = N->getOperand(0); 8495 EVT Ty = N0.getValueType(); 8496 if (Ty.isScalarInteger() && 8497 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8498 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8499 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8500 if (C1 && C2) { 8501 const APInt &C1Int = C1->getAPIntValue(); 8502 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8503 8504 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8505 // and the combine should happen, to potentially allow further combines 8506 // later. 8507 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8508 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8509 return true; 8510 8511 // We can materialise `c1` in an add immediate, so it's "free", and the 8512 // combine should be prevented. 8513 if (C1Int.getMinSignedBits() <= 64 && 8514 isLegalAddImmediate(C1Int.getSExtValue())) 8515 return false; 8516 8517 // Neither constant will fit into an immediate, so find materialisation 8518 // costs. 8519 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8520 Subtarget.getFeatureBits(), 8521 /*CompressionCost*/true); 8522 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8523 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8524 /*CompressionCost*/true); 8525 8526 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8527 // combine should be prevented. 8528 if (C1Cost < ShiftedC1Cost) 8529 return false; 8530 } 8531 } 8532 return true; 8533 } 8534 8535 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8536 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8537 TargetLoweringOpt &TLO) const { 8538 // Delay this optimization as late as possible. 8539 if (!TLO.LegalOps) 8540 return false; 8541 8542 EVT VT = Op.getValueType(); 8543 if (VT.isVector()) 8544 return false; 8545 8546 // Only handle AND for now. 8547 if (Op.getOpcode() != ISD::AND) 8548 return false; 8549 8550 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8551 if (!C) 8552 return false; 8553 8554 const APInt &Mask = C->getAPIntValue(); 8555 8556 // Clear all non-demanded bits initially. 8557 APInt ShrunkMask = Mask & DemandedBits; 8558 8559 // Try to make a smaller immediate by setting undemanded bits. 8560 8561 APInt ExpandedMask = Mask | ~DemandedBits; 8562 8563 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8564 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8565 }; 8566 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8567 if (NewMask == Mask) 8568 return true; 8569 SDLoc DL(Op); 8570 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8571 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8572 return TLO.CombineTo(Op, NewOp); 8573 }; 8574 8575 // If the shrunk mask fits in sign extended 12 bits, let the target 8576 // independent code apply it. 8577 if (ShrunkMask.isSignedIntN(12)) 8578 return false; 8579 8580 // Preserve (and X, 0xffff) when zext.h is supported. 8581 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8582 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8583 if (IsLegalMask(NewMask)) 8584 return UseMask(NewMask); 8585 } 8586 8587 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8588 if (VT == MVT::i64) { 8589 APInt NewMask = APInt(64, 0xffffffff); 8590 if (IsLegalMask(NewMask)) 8591 return UseMask(NewMask); 8592 } 8593 8594 // For the remaining optimizations, we need to be able to make a negative 8595 // number through a combination of mask and undemanded bits. 8596 if (!ExpandedMask.isNegative()) 8597 return false; 8598 8599 // What is the fewest number of bits we need to represent the negative number. 8600 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8601 8602 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8603 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8604 APInt NewMask = ShrunkMask; 8605 if (MinSignedBits <= 12) 8606 NewMask.setBitsFrom(11); 8607 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8608 NewMask.setBitsFrom(31); 8609 else 8610 return false; 8611 8612 // Check that our new mask is a subset of the demanded mask. 8613 assert(IsLegalMask(NewMask)); 8614 return UseMask(NewMask); 8615 } 8616 8617 static void computeGREV(APInt &Src, unsigned ShAmt) { 8618 ShAmt &= Src.getBitWidth() - 1; 8619 uint64_t x = Src.getZExtValue(); 8620 if (ShAmt & 1) 8621 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 8622 if (ShAmt & 2) 8623 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 8624 if (ShAmt & 4) 8625 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 8626 if (ShAmt & 8) 8627 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 8628 if (ShAmt & 16) 8629 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 8630 if (ShAmt & 32) 8631 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 8632 Src = x; 8633 } 8634 8635 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8636 KnownBits &Known, 8637 const APInt &DemandedElts, 8638 const SelectionDAG &DAG, 8639 unsigned Depth) const { 8640 unsigned BitWidth = Known.getBitWidth(); 8641 unsigned Opc = Op.getOpcode(); 8642 assert((Opc >= ISD::BUILTIN_OP_END || 8643 Opc == ISD::INTRINSIC_WO_CHAIN || 8644 Opc == ISD::INTRINSIC_W_CHAIN || 8645 Opc == ISD::INTRINSIC_VOID) && 8646 "Should use MaskedValueIsZero if you don't know whether Op" 8647 " is a target node!"); 8648 8649 Known.resetAll(); 8650 switch (Opc) { 8651 default: break; 8652 case RISCVISD::SELECT_CC: { 8653 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8654 // If we don't know any bits, early out. 8655 if (Known.isUnknown()) 8656 break; 8657 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8658 8659 // Only known if known in both the LHS and RHS. 8660 Known = KnownBits::commonBits(Known, Known2); 8661 break; 8662 } 8663 case RISCVISD::REMUW: { 8664 KnownBits Known2; 8665 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8666 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8667 // We only care about the lower 32 bits. 8668 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8669 // Restore the original width by sign extending. 8670 Known = Known.sext(BitWidth); 8671 break; 8672 } 8673 case RISCVISD::DIVUW: { 8674 KnownBits Known2; 8675 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8676 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8677 // We only care about the lower 32 bits. 8678 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8679 // Restore the original width by sign extending. 8680 Known = Known.sext(BitWidth); 8681 break; 8682 } 8683 case RISCVISD::CTZW: { 8684 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8685 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 8686 unsigned LowBits = Log2_32(PossibleTZ) + 1; 8687 Known.Zero.setBitsFrom(LowBits); 8688 break; 8689 } 8690 case RISCVISD::CLZW: { 8691 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8692 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 8693 unsigned LowBits = Log2_32(PossibleLZ) + 1; 8694 Known.Zero.setBitsFrom(LowBits); 8695 break; 8696 } 8697 case RISCVISD::GREV: 8698 case RISCVISD::GREVW: { 8699 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8700 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8701 if (Opc == RISCVISD::GREVW) 8702 Known = Known.trunc(32); 8703 unsigned ShAmt = C->getZExtValue(); 8704 computeGREV(Known.Zero, ShAmt); 8705 computeGREV(Known.One, ShAmt); 8706 if (Opc == RISCVISD::GREVW) 8707 Known = Known.sext(BitWidth); 8708 } 8709 break; 8710 } 8711 case RISCVISD::READ_VLENB: { 8712 // If we know the minimum VLen from Zvl extensions, we can use that to 8713 // determine the trailing zeros of VLENB. 8714 // FIXME: Limit to 128 bit vectors until we have more testing. 8715 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 8716 if (MinVLenB > 0) 8717 Known.Zero.setLowBits(Log2_32(MinVLenB)); 8718 // We assume VLENB is no more than 65536 / 8 bytes. 8719 Known.Zero.setBitsFrom(14); 8720 break; 8721 } 8722 case ISD::INTRINSIC_W_CHAIN: 8723 case ISD::INTRINSIC_WO_CHAIN: { 8724 unsigned IntNo = 8725 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 8726 switch (IntNo) { 8727 default: 8728 // We can't do anything for most intrinsics. 8729 break; 8730 case Intrinsic::riscv_vsetvli: 8731 case Intrinsic::riscv_vsetvlimax: 8732 case Intrinsic::riscv_vsetvli_opt: 8733 case Intrinsic::riscv_vsetvlimax_opt: 8734 // Assume that VL output is positive and would fit in an int32_t. 8735 // TODO: VLEN might be capped at 16 bits in a future V spec update. 8736 if (BitWidth >= 32) 8737 Known.Zero.setBitsFrom(31); 8738 break; 8739 } 8740 break; 8741 } 8742 } 8743 } 8744 8745 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 8746 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 8747 unsigned Depth) const { 8748 switch (Op.getOpcode()) { 8749 default: 8750 break; 8751 case RISCVISD::SELECT_CC: { 8752 unsigned Tmp = 8753 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 8754 if (Tmp == 1) return 1; // Early out. 8755 unsigned Tmp2 = 8756 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 8757 return std::min(Tmp, Tmp2); 8758 } 8759 case RISCVISD::SLLW: 8760 case RISCVISD::SRAW: 8761 case RISCVISD::SRLW: 8762 case RISCVISD::DIVW: 8763 case RISCVISD::DIVUW: 8764 case RISCVISD::REMUW: 8765 case RISCVISD::ROLW: 8766 case RISCVISD::RORW: 8767 case RISCVISD::GREVW: 8768 case RISCVISD::GORCW: 8769 case RISCVISD::FSLW: 8770 case RISCVISD::FSRW: 8771 case RISCVISD::SHFLW: 8772 case RISCVISD::UNSHFLW: 8773 case RISCVISD::BCOMPRESSW: 8774 case RISCVISD::BDECOMPRESSW: 8775 case RISCVISD::BFPW: 8776 case RISCVISD::FCVT_W_RV64: 8777 case RISCVISD::FCVT_WU_RV64: 8778 case RISCVISD::STRICT_FCVT_W_RV64: 8779 case RISCVISD::STRICT_FCVT_WU_RV64: 8780 // TODO: As the result is sign-extended, this is conservatively correct. A 8781 // more precise answer could be calculated for SRAW depending on known 8782 // bits in the shift amount. 8783 return 33; 8784 case RISCVISD::SHFL: 8785 case RISCVISD::UNSHFL: { 8786 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 8787 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 8788 // will stay within the upper 32 bits. If there were more than 32 sign bits 8789 // before there will be at least 33 sign bits after. 8790 if (Op.getValueType() == MVT::i64 && 8791 isa<ConstantSDNode>(Op.getOperand(1)) && 8792 (Op.getConstantOperandVal(1) & 0x10) == 0) { 8793 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 8794 if (Tmp > 32) 8795 return 33; 8796 } 8797 break; 8798 } 8799 case RISCVISD::VMV_X_S: { 8800 // The number of sign bits of the scalar result is computed by obtaining the 8801 // element type of the input vector operand, subtracting its width from the 8802 // XLEN, and then adding one (sign bit within the element type). If the 8803 // element type is wider than XLen, the least-significant XLEN bits are 8804 // taken. 8805 unsigned XLen = Subtarget.getXLen(); 8806 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 8807 if (EltBits <= XLen) 8808 return XLen - EltBits + 1; 8809 break; 8810 } 8811 } 8812 8813 return 1; 8814 } 8815 8816 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 8817 MachineBasicBlock *BB) { 8818 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 8819 8820 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 8821 // Should the count have wrapped while it was being read, we need to try 8822 // again. 8823 // ... 8824 // read: 8825 // rdcycleh x3 # load high word of cycle 8826 // rdcycle x2 # load low word of cycle 8827 // rdcycleh x4 # load high word of cycle 8828 // bne x3, x4, read # check if high word reads match, otherwise try again 8829 // ... 8830 8831 MachineFunction &MF = *BB->getParent(); 8832 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8833 MachineFunction::iterator It = ++BB->getIterator(); 8834 8835 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8836 MF.insert(It, LoopMBB); 8837 8838 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8839 MF.insert(It, DoneMBB); 8840 8841 // Transfer the remainder of BB and its successor edges to DoneMBB. 8842 DoneMBB->splice(DoneMBB->begin(), BB, 8843 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8844 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 8845 8846 BB->addSuccessor(LoopMBB); 8847 8848 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8849 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8850 Register LoReg = MI.getOperand(0).getReg(); 8851 Register HiReg = MI.getOperand(1).getReg(); 8852 DebugLoc DL = MI.getDebugLoc(); 8853 8854 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 8855 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 8856 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8857 .addReg(RISCV::X0); 8858 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 8859 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 8860 .addReg(RISCV::X0); 8861 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 8862 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8863 .addReg(RISCV::X0); 8864 8865 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 8866 .addReg(HiReg) 8867 .addReg(ReadAgainReg) 8868 .addMBB(LoopMBB); 8869 8870 LoopMBB->addSuccessor(LoopMBB); 8871 LoopMBB->addSuccessor(DoneMBB); 8872 8873 MI.eraseFromParent(); 8874 8875 return DoneMBB; 8876 } 8877 8878 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 8879 MachineBasicBlock *BB) { 8880 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 8881 8882 MachineFunction &MF = *BB->getParent(); 8883 DebugLoc DL = MI.getDebugLoc(); 8884 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8885 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8886 Register LoReg = MI.getOperand(0).getReg(); 8887 Register HiReg = MI.getOperand(1).getReg(); 8888 Register SrcReg = MI.getOperand(2).getReg(); 8889 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 8890 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8891 8892 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 8893 RI); 8894 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8895 MachineMemOperand *MMOLo = 8896 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 8897 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8898 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 8899 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 8900 .addFrameIndex(FI) 8901 .addImm(0) 8902 .addMemOperand(MMOLo); 8903 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 8904 .addFrameIndex(FI) 8905 .addImm(4) 8906 .addMemOperand(MMOHi); 8907 MI.eraseFromParent(); // The pseudo instruction is gone now. 8908 return BB; 8909 } 8910 8911 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 8912 MachineBasicBlock *BB) { 8913 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 8914 "Unexpected instruction"); 8915 8916 MachineFunction &MF = *BB->getParent(); 8917 DebugLoc DL = MI.getDebugLoc(); 8918 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8919 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8920 Register DstReg = MI.getOperand(0).getReg(); 8921 Register LoReg = MI.getOperand(1).getReg(); 8922 Register HiReg = MI.getOperand(2).getReg(); 8923 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 8924 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8925 8926 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8927 MachineMemOperand *MMOLo = 8928 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 8929 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8930 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 8931 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8932 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 8933 .addFrameIndex(FI) 8934 .addImm(0) 8935 .addMemOperand(MMOLo); 8936 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8937 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 8938 .addFrameIndex(FI) 8939 .addImm(4) 8940 .addMemOperand(MMOHi); 8941 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 8942 MI.eraseFromParent(); // The pseudo instruction is gone now. 8943 return BB; 8944 } 8945 8946 static bool isSelectPseudo(MachineInstr &MI) { 8947 switch (MI.getOpcode()) { 8948 default: 8949 return false; 8950 case RISCV::Select_GPR_Using_CC_GPR: 8951 case RISCV::Select_FPR16_Using_CC_GPR: 8952 case RISCV::Select_FPR32_Using_CC_GPR: 8953 case RISCV::Select_FPR64_Using_CC_GPR: 8954 return true; 8955 } 8956 } 8957 8958 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 8959 unsigned RelOpcode, unsigned EqOpcode, 8960 const RISCVSubtarget &Subtarget) { 8961 DebugLoc DL = MI.getDebugLoc(); 8962 Register DstReg = MI.getOperand(0).getReg(); 8963 Register Src1Reg = MI.getOperand(1).getReg(); 8964 Register Src2Reg = MI.getOperand(2).getReg(); 8965 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 8966 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 8967 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 8968 8969 // Save the current FFLAGS. 8970 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 8971 8972 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 8973 .addReg(Src1Reg) 8974 .addReg(Src2Reg); 8975 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8976 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 8977 8978 // Restore the FFLAGS. 8979 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 8980 .addReg(SavedFFlags, RegState::Kill); 8981 8982 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 8983 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 8984 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 8985 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 8986 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8987 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 8988 8989 // Erase the pseudoinstruction. 8990 MI.eraseFromParent(); 8991 return BB; 8992 } 8993 8994 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 8995 MachineBasicBlock *BB, 8996 const RISCVSubtarget &Subtarget) { 8997 // To "insert" Select_* instructions, we actually have to insert the triangle 8998 // control-flow pattern. The incoming instructions know the destination vreg 8999 // to set, the condition code register to branch on, the true/false values to 9000 // select between, and the condcode to use to select the appropriate branch. 9001 // 9002 // We produce the following control flow: 9003 // HeadMBB 9004 // | \ 9005 // | IfFalseMBB 9006 // | / 9007 // TailMBB 9008 // 9009 // When we find a sequence of selects we attempt to optimize their emission 9010 // by sharing the control flow. Currently we only handle cases where we have 9011 // multiple selects with the exact same condition (same LHS, RHS and CC). 9012 // The selects may be interleaved with other instructions if the other 9013 // instructions meet some requirements we deem safe: 9014 // - They are debug instructions. Otherwise, 9015 // - They do not have side-effects, do not access memory and their inputs do 9016 // not depend on the results of the select pseudo-instructions. 9017 // The TrueV/FalseV operands of the selects cannot depend on the result of 9018 // previous selects in the sequence. 9019 // These conditions could be further relaxed. See the X86 target for a 9020 // related approach and more information. 9021 Register LHS = MI.getOperand(1).getReg(); 9022 Register RHS = MI.getOperand(2).getReg(); 9023 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9024 9025 SmallVector<MachineInstr *, 4> SelectDebugValues; 9026 SmallSet<Register, 4> SelectDests; 9027 SelectDests.insert(MI.getOperand(0).getReg()); 9028 9029 MachineInstr *LastSelectPseudo = &MI; 9030 9031 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9032 SequenceMBBI != E; ++SequenceMBBI) { 9033 if (SequenceMBBI->isDebugInstr()) 9034 continue; 9035 else if (isSelectPseudo(*SequenceMBBI)) { 9036 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9037 SequenceMBBI->getOperand(2).getReg() != RHS || 9038 SequenceMBBI->getOperand(3).getImm() != CC || 9039 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9040 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9041 break; 9042 LastSelectPseudo = &*SequenceMBBI; 9043 SequenceMBBI->collectDebugValues(SelectDebugValues); 9044 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9045 } else { 9046 if (SequenceMBBI->hasUnmodeledSideEffects() || 9047 SequenceMBBI->mayLoadOrStore()) 9048 break; 9049 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9050 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9051 })) 9052 break; 9053 } 9054 } 9055 9056 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9057 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9058 DebugLoc DL = MI.getDebugLoc(); 9059 MachineFunction::iterator I = ++BB->getIterator(); 9060 9061 MachineBasicBlock *HeadMBB = BB; 9062 MachineFunction *F = BB->getParent(); 9063 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9064 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9065 9066 F->insert(I, IfFalseMBB); 9067 F->insert(I, TailMBB); 9068 9069 // Transfer debug instructions associated with the selects to TailMBB. 9070 for (MachineInstr *DebugInstr : SelectDebugValues) { 9071 TailMBB->push_back(DebugInstr->removeFromParent()); 9072 } 9073 9074 // Move all instructions after the sequence to TailMBB. 9075 TailMBB->splice(TailMBB->end(), HeadMBB, 9076 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9077 // Update machine-CFG edges by transferring all successors of the current 9078 // block to the new block which will contain the Phi nodes for the selects. 9079 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9080 // Set the successors for HeadMBB. 9081 HeadMBB->addSuccessor(IfFalseMBB); 9082 HeadMBB->addSuccessor(TailMBB); 9083 9084 // Insert appropriate branch. 9085 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9086 .addReg(LHS) 9087 .addReg(RHS) 9088 .addMBB(TailMBB); 9089 9090 // IfFalseMBB just falls through to TailMBB. 9091 IfFalseMBB->addSuccessor(TailMBB); 9092 9093 // Create PHIs for all of the select pseudo-instructions. 9094 auto SelectMBBI = MI.getIterator(); 9095 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9096 auto InsertionPoint = TailMBB->begin(); 9097 while (SelectMBBI != SelectEnd) { 9098 auto Next = std::next(SelectMBBI); 9099 if (isSelectPseudo(*SelectMBBI)) { 9100 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9101 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9102 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9103 .addReg(SelectMBBI->getOperand(4).getReg()) 9104 .addMBB(HeadMBB) 9105 .addReg(SelectMBBI->getOperand(5).getReg()) 9106 .addMBB(IfFalseMBB); 9107 SelectMBBI->eraseFromParent(); 9108 } 9109 SelectMBBI = Next; 9110 } 9111 9112 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9113 return TailMBB; 9114 } 9115 9116 MachineBasicBlock * 9117 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9118 MachineBasicBlock *BB) const { 9119 switch (MI.getOpcode()) { 9120 default: 9121 llvm_unreachable("Unexpected instr type to insert"); 9122 case RISCV::ReadCycleWide: 9123 assert(!Subtarget.is64Bit() && 9124 "ReadCycleWrite is only to be used on riscv32"); 9125 return emitReadCycleWidePseudo(MI, BB); 9126 case RISCV::Select_GPR_Using_CC_GPR: 9127 case RISCV::Select_FPR16_Using_CC_GPR: 9128 case RISCV::Select_FPR32_Using_CC_GPR: 9129 case RISCV::Select_FPR64_Using_CC_GPR: 9130 return emitSelectPseudo(MI, BB, Subtarget); 9131 case RISCV::BuildPairF64Pseudo: 9132 return emitBuildPairF64Pseudo(MI, BB); 9133 case RISCV::SplitF64Pseudo: 9134 return emitSplitF64Pseudo(MI, BB); 9135 case RISCV::PseudoQuietFLE_H: 9136 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9137 case RISCV::PseudoQuietFLT_H: 9138 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9139 case RISCV::PseudoQuietFLE_S: 9140 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9141 case RISCV::PseudoQuietFLT_S: 9142 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9143 case RISCV::PseudoQuietFLE_D: 9144 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9145 case RISCV::PseudoQuietFLT_D: 9146 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9147 } 9148 } 9149 9150 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9151 SDNode *Node) const { 9152 // Add FRM dependency to any instructions with dynamic rounding mode. 9153 unsigned Opc = MI.getOpcode(); 9154 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9155 if (Idx < 0) 9156 return; 9157 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9158 return; 9159 // If the instruction already reads FRM, don't add another read. 9160 if (MI.readsRegister(RISCV::FRM)) 9161 return; 9162 MI.addOperand( 9163 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9164 } 9165 9166 // Calling Convention Implementation. 9167 // The expectations for frontend ABI lowering vary from target to target. 9168 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9169 // details, but this is a longer term goal. For now, we simply try to keep the 9170 // role of the frontend as simple and well-defined as possible. The rules can 9171 // be summarised as: 9172 // * Never split up large scalar arguments. We handle them here. 9173 // * If a hardfloat calling convention is being used, and the struct may be 9174 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9175 // available, then pass as two separate arguments. If either the GPRs or FPRs 9176 // are exhausted, then pass according to the rule below. 9177 // * If a struct could never be passed in registers or directly in a stack 9178 // slot (as it is larger than 2*XLEN and the floating point rules don't 9179 // apply), then pass it using a pointer with the byval attribute. 9180 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9181 // word-sized array or a 2*XLEN scalar (depending on alignment). 9182 // * The frontend can determine whether a struct is returned by reference or 9183 // not based on its size and fields. If it will be returned by reference, the 9184 // frontend must modify the prototype so a pointer with the sret annotation is 9185 // passed as the first argument. This is not necessary for large scalar 9186 // returns. 9187 // * Struct return values and varargs should be coerced to structs containing 9188 // register-size fields in the same situations they would be for fixed 9189 // arguments. 9190 9191 static const MCPhysReg ArgGPRs[] = { 9192 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9193 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9194 }; 9195 static const MCPhysReg ArgFPR16s[] = { 9196 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9197 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9198 }; 9199 static const MCPhysReg ArgFPR32s[] = { 9200 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9201 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9202 }; 9203 static const MCPhysReg ArgFPR64s[] = { 9204 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9205 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9206 }; 9207 // This is an interim calling convention and it may be changed in the future. 9208 static const MCPhysReg ArgVRs[] = { 9209 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9210 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9211 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9212 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9213 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9214 RISCV::V20M2, RISCV::V22M2}; 9215 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9216 RISCV::V20M4}; 9217 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9218 9219 // Pass a 2*XLEN argument that has been split into two XLEN values through 9220 // registers or the stack as necessary. 9221 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9222 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9223 MVT ValVT2, MVT LocVT2, 9224 ISD::ArgFlagsTy ArgFlags2) { 9225 unsigned XLenInBytes = XLen / 8; 9226 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9227 // At least one half can be passed via register. 9228 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9229 VA1.getLocVT(), CCValAssign::Full)); 9230 } else { 9231 // Both halves must be passed on the stack, with proper alignment. 9232 Align StackAlign = 9233 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9234 State.addLoc( 9235 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9236 State.AllocateStack(XLenInBytes, StackAlign), 9237 VA1.getLocVT(), CCValAssign::Full)); 9238 State.addLoc(CCValAssign::getMem( 9239 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9240 LocVT2, CCValAssign::Full)); 9241 return false; 9242 } 9243 9244 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9245 // The second half can also be passed via register. 9246 State.addLoc( 9247 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9248 } else { 9249 // The second half is passed via the stack, without additional alignment. 9250 State.addLoc(CCValAssign::getMem( 9251 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9252 LocVT2, CCValAssign::Full)); 9253 } 9254 9255 return false; 9256 } 9257 9258 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9259 Optional<unsigned> FirstMaskArgument, 9260 CCState &State, const RISCVTargetLowering &TLI) { 9261 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9262 if (RC == &RISCV::VRRegClass) { 9263 // Assign the first mask argument to V0. 9264 // This is an interim calling convention and it may be changed in the 9265 // future. 9266 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9267 return State.AllocateReg(RISCV::V0); 9268 return State.AllocateReg(ArgVRs); 9269 } 9270 if (RC == &RISCV::VRM2RegClass) 9271 return State.AllocateReg(ArgVRM2s); 9272 if (RC == &RISCV::VRM4RegClass) 9273 return State.AllocateReg(ArgVRM4s); 9274 if (RC == &RISCV::VRM8RegClass) 9275 return State.AllocateReg(ArgVRM8s); 9276 llvm_unreachable("Unhandled register class for ValueType"); 9277 } 9278 9279 // Implements the RISC-V calling convention. Returns true upon failure. 9280 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9281 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9282 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9283 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9284 Optional<unsigned> FirstMaskArgument) { 9285 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9286 assert(XLen == 32 || XLen == 64); 9287 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9288 9289 // Any return value split in to more than two values can't be returned 9290 // directly. Vectors are returned via the available vector registers. 9291 if (!LocVT.isVector() && IsRet && ValNo > 1) 9292 return true; 9293 9294 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9295 // variadic argument, or if no F16/F32 argument registers are available. 9296 bool UseGPRForF16_F32 = true; 9297 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9298 // variadic argument, or if no F64 argument registers are available. 9299 bool UseGPRForF64 = true; 9300 9301 switch (ABI) { 9302 default: 9303 llvm_unreachable("Unexpected ABI"); 9304 case RISCVABI::ABI_ILP32: 9305 case RISCVABI::ABI_LP64: 9306 break; 9307 case RISCVABI::ABI_ILP32F: 9308 case RISCVABI::ABI_LP64F: 9309 UseGPRForF16_F32 = !IsFixed; 9310 break; 9311 case RISCVABI::ABI_ILP32D: 9312 case RISCVABI::ABI_LP64D: 9313 UseGPRForF16_F32 = !IsFixed; 9314 UseGPRForF64 = !IsFixed; 9315 break; 9316 } 9317 9318 // FPR16, FPR32, and FPR64 alias each other. 9319 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9320 UseGPRForF16_F32 = true; 9321 UseGPRForF64 = true; 9322 } 9323 9324 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9325 // similar local variables rather than directly checking against the target 9326 // ABI. 9327 9328 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9329 LocVT = XLenVT; 9330 LocInfo = CCValAssign::BCvt; 9331 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9332 LocVT = MVT::i64; 9333 LocInfo = CCValAssign::BCvt; 9334 } 9335 9336 // If this is a variadic argument, the RISC-V calling convention requires 9337 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9338 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9339 // be used regardless of whether the original argument was split during 9340 // legalisation or not. The argument will not be passed by registers if the 9341 // original type is larger than 2*XLEN, so the register alignment rule does 9342 // not apply. 9343 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9344 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9345 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9346 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9347 // Skip 'odd' register if necessary. 9348 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9349 State.AllocateReg(ArgGPRs); 9350 } 9351 9352 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9353 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9354 State.getPendingArgFlags(); 9355 9356 assert(PendingLocs.size() == PendingArgFlags.size() && 9357 "PendingLocs and PendingArgFlags out of sync"); 9358 9359 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9360 // registers are exhausted. 9361 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9362 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9363 "Can't lower f64 if it is split"); 9364 // Depending on available argument GPRS, f64 may be passed in a pair of 9365 // GPRs, split between a GPR and the stack, or passed completely on the 9366 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9367 // cases. 9368 Register Reg = State.AllocateReg(ArgGPRs); 9369 LocVT = MVT::i32; 9370 if (!Reg) { 9371 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9372 State.addLoc( 9373 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9374 return false; 9375 } 9376 if (!State.AllocateReg(ArgGPRs)) 9377 State.AllocateStack(4, Align(4)); 9378 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9379 return false; 9380 } 9381 9382 // Fixed-length vectors are located in the corresponding scalable-vector 9383 // container types. 9384 if (ValVT.isFixedLengthVector()) 9385 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9386 9387 // Split arguments might be passed indirectly, so keep track of the pending 9388 // values. Split vectors are passed via a mix of registers and indirectly, so 9389 // treat them as we would any other argument. 9390 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9391 LocVT = XLenVT; 9392 LocInfo = CCValAssign::Indirect; 9393 PendingLocs.push_back( 9394 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9395 PendingArgFlags.push_back(ArgFlags); 9396 if (!ArgFlags.isSplitEnd()) { 9397 return false; 9398 } 9399 } 9400 9401 // If the split argument only had two elements, it should be passed directly 9402 // in registers or on the stack. 9403 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9404 PendingLocs.size() <= 2) { 9405 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9406 // Apply the normal calling convention rules to the first half of the 9407 // split argument. 9408 CCValAssign VA = PendingLocs[0]; 9409 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9410 PendingLocs.clear(); 9411 PendingArgFlags.clear(); 9412 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9413 ArgFlags); 9414 } 9415 9416 // Allocate to a register if possible, or else a stack slot. 9417 Register Reg; 9418 unsigned StoreSizeBytes = XLen / 8; 9419 Align StackAlign = Align(XLen / 8); 9420 9421 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9422 Reg = State.AllocateReg(ArgFPR16s); 9423 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9424 Reg = State.AllocateReg(ArgFPR32s); 9425 else if (ValVT == MVT::f64 && !UseGPRForF64) 9426 Reg = State.AllocateReg(ArgFPR64s); 9427 else if (ValVT.isVector()) { 9428 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9429 if (!Reg) { 9430 // For return values, the vector must be passed fully via registers or 9431 // via the stack. 9432 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9433 // but we're using all of them. 9434 if (IsRet) 9435 return true; 9436 // Try using a GPR to pass the address 9437 if ((Reg = State.AllocateReg(ArgGPRs))) { 9438 LocVT = XLenVT; 9439 LocInfo = CCValAssign::Indirect; 9440 } else if (ValVT.isScalableVector()) { 9441 LocVT = XLenVT; 9442 LocInfo = CCValAssign::Indirect; 9443 } else { 9444 // Pass fixed-length vectors on the stack. 9445 LocVT = ValVT; 9446 StoreSizeBytes = ValVT.getStoreSize(); 9447 // Align vectors to their element sizes, being careful for vXi1 9448 // vectors. 9449 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9450 } 9451 } 9452 } else { 9453 Reg = State.AllocateReg(ArgGPRs); 9454 } 9455 9456 unsigned StackOffset = 9457 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9458 9459 // If we reach this point and PendingLocs is non-empty, we must be at the 9460 // end of a split argument that must be passed indirectly. 9461 if (!PendingLocs.empty()) { 9462 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9463 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9464 9465 for (auto &It : PendingLocs) { 9466 if (Reg) 9467 It.convertToReg(Reg); 9468 else 9469 It.convertToMem(StackOffset); 9470 State.addLoc(It); 9471 } 9472 PendingLocs.clear(); 9473 PendingArgFlags.clear(); 9474 return false; 9475 } 9476 9477 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9478 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9479 "Expected an XLenVT or vector types at this stage"); 9480 9481 if (Reg) { 9482 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9483 return false; 9484 } 9485 9486 // When a floating-point value is passed on the stack, no bit-conversion is 9487 // needed. 9488 if (ValVT.isFloatingPoint()) { 9489 LocVT = ValVT; 9490 LocInfo = CCValAssign::Full; 9491 } 9492 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9493 return false; 9494 } 9495 9496 template <typename ArgTy> 9497 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9498 for (const auto &ArgIdx : enumerate(Args)) { 9499 MVT ArgVT = ArgIdx.value().VT; 9500 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9501 return ArgIdx.index(); 9502 } 9503 return None; 9504 } 9505 9506 void RISCVTargetLowering::analyzeInputArgs( 9507 MachineFunction &MF, CCState &CCInfo, 9508 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9509 RISCVCCAssignFn Fn) const { 9510 unsigned NumArgs = Ins.size(); 9511 FunctionType *FType = MF.getFunction().getFunctionType(); 9512 9513 Optional<unsigned> FirstMaskArgument; 9514 if (Subtarget.hasVInstructions()) 9515 FirstMaskArgument = preAssignMask(Ins); 9516 9517 for (unsigned i = 0; i != NumArgs; ++i) { 9518 MVT ArgVT = Ins[i].VT; 9519 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9520 9521 Type *ArgTy = nullptr; 9522 if (IsRet) 9523 ArgTy = FType->getReturnType(); 9524 else if (Ins[i].isOrigArg()) 9525 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9526 9527 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9528 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9529 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9530 FirstMaskArgument)) { 9531 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9532 << EVT(ArgVT).getEVTString() << '\n'); 9533 llvm_unreachable(nullptr); 9534 } 9535 } 9536 } 9537 9538 void RISCVTargetLowering::analyzeOutputArgs( 9539 MachineFunction &MF, CCState &CCInfo, 9540 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9541 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9542 unsigned NumArgs = Outs.size(); 9543 9544 Optional<unsigned> FirstMaskArgument; 9545 if (Subtarget.hasVInstructions()) 9546 FirstMaskArgument = preAssignMask(Outs); 9547 9548 for (unsigned i = 0; i != NumArgs; i++) { 9549 MVT ArgVT = Outs[i].VT; 9550 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9551 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9552 9553 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9554 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9555 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9556 FirstMaskArgument)) { 9557 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9558 << EVT(ArgVT).getEVTString() << "\n"); 9559 llvm_unreachable(nullptr); 9560 } 9561 } 9562 } 9563 9564 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9565 // values. 9566 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9567 const CCValAssign &VA, const SDLoc &DL, 9568 const RISCVSubtarget &Subtarget) { 9569 switch (VA.getLocInfo()) { 9570 default: 9571 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9572 case CCValAssign::Full: 9573 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9574 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9575 break; 9576 case CCValAssign::BCvt: 9577 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9578 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9579 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9580 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9581 else 9582 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9583 break; 9584 } 9585 return Val; 9586 } 9587 9588 // The caller is responsible for loading the full value if the argument is 9589 // passed with CCValAssign::Indirect. 9590 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9591 const CCValAssign &VA, const SDLoc &DL, 9592 const RISCVTargetLowering &TLI) { 9593 MachineFunction &MF = DAG.getMachineFunction(); 9594 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9595 EVT LocVT = VA.getLocVT(); 9596 SDValue Val; 9597 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9598 Register VReg = RegInfo.createVirtualRegister(RC); 9599 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9600 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9601 9602 if (VA.getLocInfo() == CCValAssign::Indirect) 9603 return Val; 9604 9605 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9606 } 9607 9608 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9609 const CCValAssign &VA, const SDLoc &DL, 9610 const RISCVSubtarget &Subtarget) { 9611 EVT LocVT = VA.getLocVT(); 9612 9613 switch (VA.getLocInfo()) { 9614 default: 9615 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9616 case CCValAssign::Full: 9617 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9618 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9619 break; 9620 case CCValAssign::BCvt: 9621 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9622 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9623 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9624 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9625 else 9626 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9627 break; 9628 } 9629 return Val; 9630 } 9631 9632 // The caller is responsible for loading the full value if the argument is 9633 // passed with CCValAssign::Indirect. 9634 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9635 const CCValAssign &VA, const SDLoc &DL) { 9636 MachineFunction &MF = DAG.getMachineFunction(); 9637 MachineFrameInfo &MFI = MF.getFrameInfo(); 9638 EVT LocVT = VA.getLocVT(); 9639 EVT ValVT = VA.getValVT(); 9640 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9641 if (ValVT.isScalableVector()) { 9642 // When the value is a scalable vector, we save the pointer which points to 9643 // the scalable vector value in the stack. The ValVT will be the pointer 9644 // type, instead of the scalable vector type. 9645 ValVT = LocVT; 9646 } 9647 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9648 /*IsImmutable=*/true); 9649 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9650 SDValue Val; 9651 9652 ISD::LoadExtType ExtType; 9653 switch (VA.getLocInfo()) { 9654 default: 9655 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9656 case CCValAssign::Full: 9657 case CCValAssign::Indirect: 9658 case CCValAssign::BCvt: 9659 ExtType = ISD::NON_EXTLOAD; 9660 break; 9661 } 9662 Val = DAG.getExtLoad( 9663 ExtType, DL, LocVT, Chain, FIN, 9664 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9665 return Val; 9666 } 9667 9668 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9669 const CCValAssign &VA, const SDLoc &DL) { 9670 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9671 "Unexpected VA"); 9672 MachineFunction &MF = DAG.getMachineFunction(); 9673 MachineFrameInfo &MFI = MF.getFrameInfo(); 9674 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9675 9676 if (VA.isMemLoc()) { 9677 // f64 is passed on the stack. 9678 int FI = 9679 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9680 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9681 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9682 MachinePointerInfo::getFixedStack(MF, FI)); 9683 } 9684 9685 assert(VA.isRegLoc() && "Expected register VA assignment"); 9686 9687 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9688 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 9689 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 9690 SDValue Hi; 9691 if (VA.getLocReg() == RISCV::X17) { 9692 // Second half of f64 is passed on the stack. 9693 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 9694 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9695 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 9696 MachinePointerInfo::getFixedStack(MF, FI)); 9697 } else { 9698 // Second half of f64 is passed in another GPR. 9699 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9700 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 9701 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 9702 } 9703 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 9704 } 9705 9706 // FastCC has less than 1% performance improvement for some particular 9707 // benchmark. But theoretically, it may has benenfit for some cases. 9708 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 9709 unsigned ValNo, MVT ValVT, MVT LocVT, 9710 CCValAssign::LocInfo LocInfo, 9711 ISD::ArgFlagsTy ArgFlags, CCState &State, 9712 bool IsFixed, bool IsRet, Type *OrigTy, 9713 const RISCVTargetLowering &TLI, 9714 Optional<unsigned> FirstMaskArgument) { 9715 9716 // X5 and X6 might be used for save-restore libcall. 9717 static const MCPhysReg GPRList[] = { 9718 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 9719 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 9720 RISCV::X29, RISCV::X30, RISCV::X31}; 9721 9722 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9723 if (unsigned Reg = State.AllocateReg(GPRList)) { 9724 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9725 return false; 9726 } 9727 } 9728 9729 if (LocVT == MVT::f16) { 9730 static const MCPhysReg FPR16List[] = { 9731 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 9732 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 9733 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 9734 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 9735 if (unsigned Reg = State.AllocateReg(FPR16List)) { 9736 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9737 return false; 9738 } 9739 } 9740 9741 if (LocVT == MVT::f32) { 9742 static const MCPhysReg FPR32List[] = { 9743 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 9744 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 9745 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 9746 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 9747 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9748 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9749 return false; 9750 } 9751 } 9752 9753 if (LocVT == MVT::f64) { 9754 static const MCPhysReg FPR64List[] = { 9755 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 9756 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 9757 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 9758 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 9759 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9760 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9761 return false; 9762 } 9763 } 9764 9765 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 9766 unsigned Offset4 = State.AllocateStack(4, Align(4)); 9767 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 9768 return false; 9769 } 9770 9771 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 9772 unsigned Offset5 = State.AllocateStack(8, Align(8)); 9773 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 9774 return false; 9775 } 9776 9777 if (LocVT.isVector()) { 9778 if (unsigned Reg = 9779 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 9780 // Fixed-length vectors are located in the corresponding scalable-vector 9781 // container types. 9782 if (ValVT.isFixedLengthVector()) 9783 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9784 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9785 } else { 9786 // Try and pass the address via a "fast" GPR. 9787 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 9788 LocInfo = CCValAssign::Indirect; 9789 LocVT = TLI.getSubtarget().getXLenVT(); 9790 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 9791 } else if (ValVT.isFixedLengthVector()) { 9792 auto StackAlign = 9793 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9794 unsigned StackOffset = 9795 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 9796 State.addLoc( 9797 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9798 } else { 9799 // Can't pass scalable vectors on the stack. 9800 return true; 9801 } 9802 } 9803 9804 return false; 9805 } 9806 9807 return true; // CC didn't match. 9808 } 9809 9810 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9811 CCValAssign::LocInfo LocInfo, 9812 ISD::ArgFlagsTy ArgFlags, CCState &State) { 9813 9814 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9815 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 9816 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 9817 static const MCPhysReg GPRList[] = { 9818 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 9819 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 9820 if (unsigned Reg = State.AllocateReg(GPRList)) { 9821 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9822 return false; 9823 } 9824 } 9825 9826 if (LocVT == MVT::f32) { 9827 // Pass in STG registers: F1, ..., F6 9828 // fs0 ... fs5 9829 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 9830 RISCV::F18_F, RISCV::F19_F, 9831 RISCV::F20_F, RISCV::F21_F}; 9832 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9833 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9834 return false; 9835 } 9836 } 9837 9838 if (LocVT == MVT::f64) { 9839 // Pass in STG registers: D1, ..., D6 9840 // fs6 ... fs11 9841 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 9842 RISCV::F24_D, RISCV::F25_D, 9843 RISCV::F26_D, RISCV::F27_D}; 9844 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9845 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9846 return false; 9847 } 9848 } 9849 9850 report_fatal_error("No registers left in GHC calling convention"); 9851 return true; 9852 } 9853 9854 // Transform physical registers into virtual registers. 9855 SDValue RISCVTargetLowering::LowerFormalArguments( 9856 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 9857 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 9858 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 9859 9860 MachineFunction &MF = DAG.getMachineFunction(); 9861 9862 switch (CallConv) { 9863 default: 9864 report_fatal_error("Unsupported calling convention"); 9865 case CallingConv::C: 9866 case CallingConv::Fast: 9867 break; 9868 case CallingConv::GHC: 9869 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 9870 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 9871 report_fatal_error( 9872 "GHC calling convention requires the F and D instruction set extensions"); 9873 } 9874 9875 const Function &Func = MF.getFunction(); 9876 if (Func.hasFnAttribute("interrupt")) { 9877 if (!Func.arg_empty()) 9878 report_fatal_error( 9879 "Functions with the interrupt attribute cannot have arguments!"); 9880 9881 StringRef Kind = 9882 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9883 9884 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 9885 report_fatal_error( 9886 "Function interrupt attribute argument not supported!"); 9887 } 9888 9889 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9890 MVT XLenVT = Subtarget.getXLenVT(); 9891 unsigned XLenInBytes = Subtarget.getXLen() / 8; 9892 // Used with vargs to acumulate store chains. 9893 std::vector<SDValue> OutChains; 9894 9895 // Assign locations to all of the incoming arguments. 9896 SmallVector<CCValAssign, 16> ArgLocs; 9897 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9898 9899 if (CallConv == CallingConv::GHC) 9900 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 9901 else 9902 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 9903 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9904 : CC_RISCV); 9905 9906 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 9907 CCValAssign &VA = ArgLocs[i]; 9908 SDValue ArgValue; 9909 // Passing f64 on RV32D with a soft float ABI must be handled as a special 9910 // case. 9911 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 9912 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 9913 else if (VA.isRegLoc()) 9914 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 9915 else 9916 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 9917 9918 if (VA.getLocInfo() == CCValAssign::Indirect) { 9919 // If the original argument was split and passed by reference (e.g. i128 9920 // on RV32), we need to load all parts of it here (using the same 9921 // address). Vectors may be partly split to registers and partly to the 9922 // stack, in which case the base address is partly offset and subsequent 9923 // stores are relative to that. 9924 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 9925 MachinePointerInfo())); 9926 unsigned ArgIndex = Ins[i].OrigArgIndex; 9927 unsigned ArgPartOffset = Ins[i].PartOffset; 9928 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9929 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 9930 CCValAssign &PartVA = ArgLocs[i + 1]; 9931 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 9932 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9933 if (PartVA.getValVT().isScalableVector()) 9934 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9935 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 9936 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 9937 MachinePointerInfo())); 9938 ++i; 9939 } 9940 continue; 9941 } 9942 InVals.push_back(ArgValue); 9943 } 9944 9945 if (IsVarArg) { 9946 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 9947 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 9948 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 9949 MachineFrameInfo &MFI = MF.getFrameInfo(); 9950 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9951 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 9952 9953 // Offset of the first variable argument from stack pointer, and size of 9954 // the vararg save area. For now, the varargs save area is either zero or 9955 // large enough to hold a0-a7. 9956 int VaArgOffset, VarArgsSaveSize; 9957 9958 // If all registers are allocated, then all varargs must be passed on the 9959 // stack and we don't need to save any argregs. 9960 if (ArgRegs.size() == Idx) { 9961 VaArgOffset = CCInfo.getNextStackOffset(); 9962 VarArgsSaveSize = 0; 9963 } else { 9964 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 9965 VaArgOffset = -VarArgsSaveSize; 9966 } 9967 9968 // Record the frame index of the first variable argument 9969 // which is a value necessary to VASTART. 9970 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9971 RVFI->setVarArgsFrameIndex(FI); 9972 9973 // If saving an odd number of registers then create an extra stack slot to 9974 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 9975 // offsets to even-numbered registered remain 2*XLEN-aligned. 9976 if (Idx % 2) { 9977 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 9978 VarArgsSaveSize += XLenInBytes; 9979 } 9980 9981 // Copy the integer registers that may have been used for passing varargs 9982 // to the vararg save area. 9983 for (unsigned I = Idx; I < ArgRegs.size(); 9984 ++I, VaArgOffset += XLenInBytes) { 9985 const Register Reg = RegInfo.createVirtualRegister(RC); 9986 RegInfo.addLiveIn(ArgRegs[I], Reg); 9987 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 9988 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9989 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9990 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 9991 MachinePointerInfo::getFixedStack(MF, FI)); 9992 cast<StoreSDNode>(Store.getNode()) 9993 ->getMemOperand() 9994 ->setValue((Value *)nullptr); 9995 OutChains.push_back(Store); 9996 } 9997 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 9998 } 9999 10000 // All stores are grouped in one node to allow the matching between 10001 // the size of Ins and InVals. This only happens for vararg functions. 10002 if (!OutChains.empty()) { 10003 OutChains.push_back(Chain); 10004 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10005 } 10006 10007 return Chain; 10008 } 10009 10010 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10011 /// for tail call optimization. 10012 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10013 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10014 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10015 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10016 10017 auto &Callee = CLI.Callee; 10018 auto CalleeCC = CLI.CallConv; 10019 auto &Outs = CLI.Outs; 10020 auto &Caller = MF.getFunction(); 10021 auto CallerCC = Caller.getCallingConv(); 10022 10023 // Exception-handling functions need a special set of instructions to 10024 // indicate a return to the hardware. Tail-calling another function would 10025 // probably break this. 10026 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10027 // should be expanded as new function attributes are introduced. 10028 if (Caller.hasFnAttribute("interrupt")) 10029 return false; 10030 10031 // Do not tail call opt if the stack is used to pass parameters. 10032 if (CCInfo.getNextStackOffset() != 0) 10033 return false; 10034 10035 // Do not tail call opt if any parameters need to be passed indirectly. 10036 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10037 // passed indirectly. So the address of the value will be passed in a 10038 // register, or if not available, then the address is put on the stack. In 10039 // order to pass indirectly, space on the stack often needs to be allocated 10040 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10041 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10042 // are passed CCValAssign::Indirect. 10043 for (auto &VA : ArgLocs) 10044 if (VA.getLocInfo() == CCValAssign::Indirect) 10045 return false; 10046 10047 // Do not tail call opt if either caller or callee uses struct return 10048 // semantics. 10049 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10050 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10051 if (IsCallerStructRet || IsCalleeStructRet) 10052 return false; 10053 10054 // Externally-defined functions with weak linkage should not be 10055 // tail-called. The behaviour of branch instructions in this situation (as 10056 // used for tail calls) is implementation-defined, so we cannot rely on the 10057 // linker replacing the tail call with a return. 10058 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10059 const GlobalValue *GV = G->getGlobal(); 10060 if (GV->hasExternalWeakLinkage()) 10061 return false; 10062 } 10063 10064 // The callee has to preserve all registers the caller needs to preserve. 10065 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10066 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10067 if (CalleeCC != CallerCC) { 10068 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10069 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10070 return false; 10071 } 10072 10073 // Byval parameters hand the function a pointer directly into the stack area 10074 // we want to reuse during a tail call. Working around this *is* possible 10075 // but less efficient and uglier in LowerCall. 10076 for (auto &Arg : Outs) 10077 if (Arg.Flags.isByVal()) 10078 return false; 10079 10080 return true; 10081 } 10082 10083 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10084 return DAG.getDataLayout().getPrefTypeAlign( 10085 VT.getTypeForEVT(*DAG.getContext())); 10086 } 10087 10088 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10089 // and output parameter nodes. 10090 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10091 SmallVectorImpl<SDValue> &InVals) const { 10092 SelectionDAG &DAG = CLI.DAG; 10093 SDLoc &DL = CLI.DL; 10094 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10095 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10096 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10097 SDValue Chain = CLI.Chain; 10098 SDValue Callee = CLI.Callee; 10099 bool &IsTailCall = CLI.IsTailCall; 10100 CallingConv::ID CallConv = CLI.CallConv; 10101 bool IsVarArg = CLI.IsVarArg; 10102 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10103 MVT XLenVT = Subtarget.getXLenVT(); 10104 10105 MachineFunction &MF = DAG.getMachineFunction(); 10106 10107 // Analyze the operands of the call, assigning locations to each operand. 10108 SmallVector<CCValAssign, 16> ArgLocs; 10109 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10110 10111 if (CallConv == CallingConv::GHC) 10112 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10113 else 10114 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10115 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10116 : CC_RISCV); 10117 10118 // Check if it's really possible to do a tail call. 10119 if (IsTailCall) 10120 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10121 10122 if (IsTailCall) 10123 ++NumTailCalls; 10124 else if (CLI.CB && CLI.CB->isMustTailCall()) 10125 report_fatal_error("failed to perform tail call elimination on a call " 10126 "site marked musttail"); 10127 10128 // Get a count of how many bytes are to be pushed on the stack. 10129 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10130 10131 // Create local copies for byval args 10132 SmallVector<SDValue, 8> ByValArgs; 10133 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10134 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10135 if (!Flags.isByVal()) 10136 continue; 10137 10138 SDValue Arg = OutVals[i]; 10139 unsigned Size = Flags.getByValSize(); 10140 Align Alignment = Flags.getNonZeroByValAlign(); 10141 10142 int FI = 10143 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10144 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10145 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10146 10147 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10148 /*IsVolatile=*/false, 10149 /*AlwaysInline=*/false, IsTailCall, 10150 MachinePointerInfo(), MachinePointerInfo()); 10151 ByValArgs.push_back(FIPtr); 10152 } 10153 10154 if (!IsTailCall) 10155 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10156 10157 // Copy argument values to their designated locations. 10158 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10159 SmallVector<SDValue, 8> MemOpChains; 10160 SDValue StackPtr; 10161 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10162 CCValAssign &VA = ArgLocs[i]; 10163 SDValue ArgValue = OutVals[i]; 10164 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10165 10166 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10167 bool IsF64OnRV32DSoftABI = 10168 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10169 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10170 SDValue SplitF64 = DAG.getNode( 10171 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10172 SDValue Lo = SplitF64.getValue(0); 10173 SDValue Hi = SplitF64.getValue(1); 10174 10175 Register RegLo = VA.getLocReg(); 10176 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10177 10178 if (RegLo == RISCV::X17) { 10179 // Second half of f64 is passed on the stack. 10180 // Work out the address of the stack slot. 10181 if (!StackPtr.getNode()) 10182 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10183 // Emit the store. 10184 MemOpChains.push_back( 10185 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10186 } else { 10187 // Second half of f64 is passed in another GPR. 10188 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10189 Register RegHigh = RegLo + 1; 10190 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10191 } 10192 continue; 10193 } 10194 10195 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10196 // as any other MemLoc. 10197 10198 // Promote the value if needed. 10199 // For now, only handle fully promoted and indirect arguments. 10200 if (VA.getLocInfo() == CCValAssign::Indirect) { 10201 // Store the argument in a stack slot and pass its address. 10202 Align StackAlign = 10203 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10204 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10205 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10206 // If the original argument was split (e.g. i128), we need 10207 // to store the required parts of it here (and pass just one address). 10208 // Vectors may be partly split to registers and partly to the stack, in 10209 // which case the base address is partly offset and subsequent stores are 10210 // relative to that. 10211 unsigned ArgIndex = Outs[i].OrigArgIndex; 10212 unsigned ArgPartOffset = Outs[i].PartOffset; 10213 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10214 // Calculate the total size to store. We don't have access to what we're 10215 // actually storing other than performing the loop and collecting the 10216 // info. 10217 SmallVector<std::pair<SDValue, SDValue>> Parts; 10218 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10219 SDValue PartValue = OutVals[i + 1]; 10220 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10221 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10222 EVT PartVT = PartValue.getValueType(); 10223 if (PartVT.isScalableVector()) 10224 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10225 StoredSize += PartVT.getStoreSize(); 10226 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10227 Parts.push_back(std::make_pair(PartValue, Offset)); 10228 ++i; 10229 } 10230 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10231 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10232 MemOpChains.push_back( 10233 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10234 MachinePointerInfo::getFixedStack(MF, FI))); 10235 for (const auto &Part : Parts) { 10236 SDValue PartValue = Part.first; 10237 SDValue PartOffset = Part.second; 10238 SDValue Address = 10239 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10240 MemOpChains.push_back( 10241 DAG.getStore(Chain, DL, PartValue, Address, 10242 MachinePointerInfo::getFixedStack(MF, FI))); 10243 } 10244 ArgValue = SpillSlot; 10245 } else { 10246 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10247 } 10248 10249 // Use local copy if it is a byval arg. 10250 if (Flags.isByVal()) 10251 ArgValue = ByValArgs[j++]; 10252 10253 if (VA.isRegLoc()) { 10254 // Queue up the argument copies and emit them at the end. 10255 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10256 } else { 10257 assert(VA.isMemLoc() && "Argument not register or memory"); 10258 assert(!IsTailCall && "Tail call not allowed if stack is used " 10259 "for passing parameters"); 10260 10261 // Work out the address of the stack slot. 10262 if (!StackPtr.getNode()) 10263 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10264 SDValue Address = 10265 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10266 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10267 10268 // Emit the store. 10269 MemOpChains.push_back( 10270 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10271 } 10272 } 10273 10274 // Join the stores, which are independent of one another. 10275 if (!MemOpChains.empty()) 10276 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10277 10278 SDValue Glue; 10279 10280 // Build a sequence of copy-to-reg nodes, chained and glued together. 10281 for (auto &Reg : RegsToPass) { 10282 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10283 Glue = Chain.getValue(1); 10284 } 10285 10286 // Validate that none of the argument registers have been marked as 10287 // reserved, if so report an error. Do the same for the return address if this 10288 // is not a tailcall. 10289 validateCCReservedRegs(RegsToPass, MF); 10290 if (!IsTailCall && 10291 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10292 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10293 MF.getFunction(), 10294 "Return address register required, but has been reserved."}); 10295 10296 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10297 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10298 // split it and then direct call can be matched by PseudoCALL. 10299 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10300 const GlobalValue *GV = S->getGlobal(); 10301 10302 unsigned OpFlags = RISCVII::MO_CALL; 10303 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10304 OpFlags = RISCVII::MO_PLT; 10305 10306 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10307 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10308 unsigned OpFlags = RISCVII::MO_CALL; 10309 10310 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10311 nullptr)) 10312 OpFlags = RISCVII::MO_PLT; 10313 10314 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10315 } 10316 10317 // The first call operand is the chain and the second is the target address. 10318 SmallVector<SDValue, 8> Ops; 10319 Ops.push_back(Chain); 10320 Ops.push_back(Callee); 10321 10322 // Add argument registers to the end of the list so that they are 10323 // known live into the call. 10324 for (auto &Reg : RegsToPass) 10325 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10326 10327 if (!IsTailCall) { 10328 // Add a register mask operand representing the call-preserved registers. 10329 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10330 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10331 assert(Mask && "Missing call preserved mask for calling convention"); 10332 Ops.push_back(DAG.getRegisterMask(Mask)); 10333 } 10334 10335 // Glue the call to the argument copies, if any. 10336 if (Glue.getNode()) 10337 Ops.push_back(Glue); 10338 10339 // Emit the call. 10340 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10341 10342 if (IsTailCall) { 10343 MF.getFrameInfo().setHasTailCall(); 10344 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10345 } 10346 10347 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10348 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10349 Glue = Chain.getValue(1); 10350 10351 // Mark the end of the call, which is glued to the call itself. 10352 Chain = DAG.getCALLSEQ_END(Chain, 10353 DAG.getConstant(NumBytes, DL, PtrVT, true), 10354 DAG.getConstant(0, DL, PtrVT, true), 10355 Glue, DL); 10356 Glue = Chain.getValue(1); 10357 10358 // Assign locations to each value returned by this call. 10359 SmallVector<CCValAssign, 16> RVLocs; 10360 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10361 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10362 10363 // Copy all of the result registers out of their specified physreg. 10364 for (auto &VA : RVLocs) { 10365 // Copy the value out 10366 SDValue RetValue = 10367 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10368 // Glue the RetValue to the end of the call sequence 10369 Chain = RetValue.getValue(1); 10370 Glue = RetValue.getValue(2); 10371 10372 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10373 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10374 SDValue RetValue2 = 10375 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10376 Chain = RetValue2.getValue(1); 10377 Glue = RetValue2.getValue(2); 10378 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10379 RetValue2); 10380 } 10381 10382 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10383 10384 InVals.push_back(RetValue); 10385 } 10386 10387 return Chain; 10388 } 10389 10390 bool RISCVTargetLowering::CanLowerReturn( 10391 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10392 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10393 SmallVector<CCValAssign, 16> RVLocs; 10394 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10395 10396 Optional<unsigned> FirstMaskArgument; 10397 if (Subtarget.hasVInstructions()) 10398 FirstMaskArgument = preAssignMask(Outs); 10399 10400 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10401 MVT VT = Outs[i].VT; 10402 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10403 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10404 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10405 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10406 *this, FirstMaskArgument)) 10407 return false; 10408 } 10409 return true; 10410 } 10411 10412 SDValue 10413 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10414 bool IsVarArg, 10415 const SmallVectorImpl<ISD::OutputArg> &Outs, 10416 const SmallVectorImpl<SDValue> &OutVals, 10417 const SDLoc &DL, SelectionDAG &DAG) const { 10418 const MachineFunction &MF = DAG.getMachineFunction(); 10419 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10420 10421 // Stores the assignment of the return value to a location. 10422 SmallVector<CCValAssign, 16> RVLocs; 10423 10424 // Info about the registers and stack slot. 10425 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10426 *DAG.getContext()); 10427 10428 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10429 nullptr, CC_RISCV); 10430 10431 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10432 report_fatal_error("GHC functions return void only"); 10433 10434 SDValue Glue; 10435 SmallVector<SDValue, 4> RetOps(1, Chain); 10436 10437 // Copy the result values into the output registers. 10438 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10439 SDValue Val = OutVals[i]; 10440 CCValAssign &VA = RVLocs[i]; 10441 assert(VA.isRegLoc() && "Can only return in registers!"); 10442 10443 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10444 // Handle returning f64 on RV32D with a soft float ABI. 10445 assert(VA.isRegLoc() && "Expected return via registers"); 10446 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10447 DAG.getVTList(MVT::i32, MVT::i32), Val); 10448 SDValue Lo = SplitF64.getValue(0); 10449 SDValue Hi = SplitF64.getValue(1); 10450 Register RegLo = VA.getLocReg(); 10451 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10452 Register RegHi = RegLo + 1; 10453 10454 if (STI.isRegisterReservedByUser(RegLo) || 10455 STI.isRegisterReservedByUser(RegHi)) 10456 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10457 MF.getFunction(), 10458 "Return value register required, but has been reserved."}); 10459 10460 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10461 Glue = Chain.getValue(1); 10462 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10463 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10464 Glue = Chain.getValue(1); 10465 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10466 } else { 10467 // Handle a 'normal' return. 10468 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10469 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10470 10471 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10472 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10473 MF.getFunction(), 10474 "Return value register required, but has been reserved."}); 10475 10476 // Guarantee that all emitted copies are stuck together. 10477 Glue = Chain.getValue(1); 10478 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10479 } 10480 } 10481 10482 RetOps[0] = Chain; // Update chain. 10483 10484 // Add the glue node if we have it. 10485 if (Glue.getNode()) { 10486 RetOps.push_back(Glue); 10487 } 10488 10489 unsigned RetOpc = RISCVISD::RET_FLAG; 10490 // Interrupt service routines use different return instructions. 10491 const Function &Func = DAG.getMachineFunction().getFunction(); 10492 if (Func.hasFnAttribute("interrupt")) { 10493 if (!Func.getReturnType()->isVoidTy()) 10494 report_fatal_error( 10495 "Functions with the interrupt attribute must have void return type!"); 10496 10497 MachineFunction &MF = DAG.getMachineFunction(); 10498 StringRef Kind = 10499 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10500 10501 if (Kind == "user") 10502 RetOpc = RISCVISD::URET_FLAG; 10503 else if (Kind == "supervisor") 10504 RetOpc = RISCVISD::SRET_FLAG; 10505 else 10506 RetOpc = RISCVISD::MRET_FLAG; 10507 } 10508 10509 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10510 } 10511 10512 void RISCVTargetLowering::validateCCReservedRegs( 10513 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10514 MachineFunction &MF) const { 10515 const Function &F = MF.getFunction(); 10516 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10517 10518 if (llvm::any_of(Regs, [&STI](auto Reg) { 10519 return STI.isRegisterReservedByUser(Reg.first); 10520 })) 10521 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10522 F, "Argument register required, but has been reserved."}); 10523 } 10524 10525 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10526 return CI->isTailCall(); 10527 } 10528 10529 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10530 #define NODE_NAME_CASE(NODE) \ 10531 case RISCVISD::NODE: \ 10532 return "RISCVISD::" #NODE; 10533 // clang-format off 10534 switch ((RISCVISD::NodeType)Opcode) { 10535 case RISCVISD::FIRST_NUMBER: 10536 break; 10537 NODE_NAME_CASE(RET_FLAG) 10538 NODE_NAME_CASE(URET_FLAG) 10539 NODE_NAME_CASE(SRET_FLAG) 10540 NODE_NAME_CASE(MRET_FLAG) 10541 NODE_NAME_CASE(CALL) 10542 NODE_NAME_CASE(SELECT_CC) 10543 NODE_NAME_CASE(BR_CC) 10544 NODE_NAME_CASE(BuildPairF64) 10545 NODE_NAME_CASE(SplitF64) 10546 NODE_NAME_CASE(TAIL) 10547 NODE_NAME_CASE(MULHSU) 10548 NODE_NAME_CASE(SLLW) 10549 NODE_NAME_CASE(SRAW) 10550 NODE_NAME_CASE(SRLW) 10551 NODE_NAME_CASE(DIVW) 10552 NODE_NAME_CASE(DIVUW) 10553 NODE_NAME_CASE(REMUW) 10554 NODE_NAME_CASE(ROLW) 10555 NODE_NAME_CASE(RORW) 10556 NODE_NAME_CASE(CLZW) 10557 NODE_NAME_CASE(CTZW) 10558 NODE_NAME_CASE(FSLW) 10559 NODE_NAME_CASE(FSRW) 10560 NODE_NAME_CASE(FSL) 10561 NODE_NAME_CASE(FSR) 10562 NODE_NAME_CASE(FMV_H_X) 10563 NODE_NAME_CASE(FMV_X_ANYEXTH) 10564 NODE_NAME_CASE(FMV_W_X_RV64) 10565 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10566 NODE_NAME_CASE(FCVT_X) 10567 NODE_NAME_CASE(FCVT_XU) 10568 NODE_NAME_CASE(FCVT_W_RV64) 10569 NODE_NAME_CASE(FCVT_WU_RV64) 10570 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10571 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10572 NODE_NAME_CASE(READ_CYCLE_WIDE) 10573 NODE_NAME_CASE(GREV) 10574 NODE_NAME_CASE(GREVW) 10575 NODE_NAME_CASE(GORC) 10576 NODE_NAME_CASE(GORCW) 10577 NODE_NAME_CASE(SHFL) 10578 NODE_NAME_CASE(SHFLW) 10579 NODE_NAME_CASE(UNSHFL) 10580 NODE_NAME_CASE(UNSHFLW) 10581 NODE_NAME_CASE(BFP) 10582 NODE_NAME_CASE(BFPW) 10583 NODE_NAME_CASE(BCOMPRESS) 10584 NODE_NAME_CASE(BCOMPRESSW) 10585 NODE_NAME_CASE(BDECOMPRESS) 10586 NODE_NAME_CASE(BDECOMPRESSW) 10587 NODE_NAME_CASE(VMV_V_X_VL) 10588 NODE_NAME_CASE(VFMV_V_F_VL) 10589 NODE_NAME_CASE(VMV_X_S) 10590 NODE_NAME_CASE(VMV_S_X_VL) 10591 NODE_NAME_CASE(VFMV_S_F_VL) 10592 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10593 NODE_NAME_CASE(READ_VLENB) 10594 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10595 NODE_NAME_CASE(VSLIDEUP_VL) 10596 NODE_NAME_CASE(VSLIDE1UP_VL) 10597 NODE_NAME_CASE(VSLIDEDOWN_VL) 10598 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10599 NODE_NAME_CASE(VID_VL) 10600 NODE_NAME_CASE(VFNCVT_ROD_VL) 10601 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10602 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10603 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10604 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10605 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10606 NODE_NAME_CASE(VECREDUCE_AND_VL) 10607 NODE_NAME_CASE(VECREDUCE_OR_VL) 10608 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10609 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10610 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10611 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10612 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10613 NODE_NAME_CASE(ADD_VL) 10614 NODE_NAME_CASE(AND_VL) 10615 NODE_NAME_CASE(MUL_VL) 10616 NODE_NAME_CASE(OR_VL) 10617 NODE_NAME_CASE(SDIV_VL) 10618 NODE_NAME_CASE(SHL_VL) 10619 NODE_NAME_CASE(SREM_VL) 10620 NODE_NAME_CASE(SRA_VL) 10621 NODE_NAME_CASE(SRL_VL) 10622 NODE_NAME_CASE(SUB_VL) 10623 NODE_NAME_CASE(UDIV_VL) 10624 NODE_NAME_CASE(UREM_VL) 10625 NODE_NAME_CASE(XOR_VL) 10626 NODE_NAME_CASE(SADDSAT_VL) 10627 NODE_NAME_CASE(UADDSAT_VL) 10628 NODE_NAME_CASE(SSUBSAT_VL) 10629 NODE_NAME_CASE(USUBSAT_VL) 10630 NODE_NAME_CASE(FADD_VL) 10631 NODE_NAME_CASE(FSUB_VL) 10632 NODE_NAME_CASE(FMUL_VL) 10633 NODE_NAME_CASE(FDIV_VL) 10634 NODE_NAME_CASE(FNEG_VL) 10635 NODE_NAME_CASE(FABS_VL) 10636 NODE_NAME_CASE(FSQRT_VL) 10637 NODE_NAME_CASE(FMA_VL) 10638 NODE_NAME_CASE(FCOPYSIGN_VL) 10639 NODE_NAME_CASE(SMIN_VL) 10640 NODE_NAME_CASE(SMAX_VL) 10641 NODE_NAME_CASE(UMIN_VL) 10642 NODE_NAME_CASE(UMAX_VL) 10643 NODE_NAME_CASE(FMINNUM_VL) 10644 NODE_NAME_CASE(FMAXNUM_VL) 10645 NODE_NAME_CASE(MULHS_VL) 10646 NODE_NAME_CASE(MULHU_VL) 10647 NODE_NAME_CASE(FP_TO_SINT_VL) 10648 NODE_NAME_CASE(FP_TO_UINT_VL) 10649 NODE_NAME_CASE(SINT_TO_FP_VL) 10650 NODE_NAME_CASE(UINT_TO_FP_VL) 10651 NODE_NAME_CASE(FP_EXTEND_VL) 10652 NODE_NAME_CASE(FP_ROUND_VL) 10653 NODE_NAME_CASE(VWMUL_VL) 10654 NODE_NAME_CASE(VWMULU_VL) 10655 NODE_NAME_CASE(VWMULSU_VL) 10656 NODE_NAME_CASE(VWADD_VL) 10657 NODE_NAME_CASE(VWADDU_VL) 10658 NODE_NAME_CASE(VWSUB_VL) 10659 NODE_NAME_CASE(VWSUBU_VL) 10660 NODE_NAME_CASE(VWADD_W_VL) 10661 NODE_NAME_CASE(VWADDU_W_VL) 10662 NODE_NAME_CASE(VWSUB_W_VL) 10663 NODE_NAME_CASE(VWSUBU_W_VL) 10664 NODE_NAME_CASE(SETCC_VL) 10665 NODE_NAME_CASE(VSELECT_VL) 10666 NODE_NAME_CASE(VP_MERGE_VL) 10667 NODE_NAME_CASE(VMAND_VL) 10668 NODE_NAME_CASE(VMOR_VL) 10669 NODE_NAME_CASE(VMXOR_VL) 10670 NODE_NAME_CASE(VMCLR_VL) 10671 NODE_NAME_CASE(VMSET_VL) 10672 NODE_NAME_CASE(VRGATHER_VX_VL) 10673 NODE_NAME_CASE(VRGATHER_VV_VL) 10674 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10675 NODE_NAME_CASE(VSEXT_VL) 10676 NODE_NAME_CASE(VZEXT_VL) 10677 NODE_NAME_CASE(VCPOP_VL) 10678 NODE_NAME_CASE(VLE_VL) 10679 NODE_NAME_CASE(VSE_VL) 10680 NODE_NAME_CASE(READ_CSR) 10681 NODE_NAME_CASE(WRITE_CSR) 10682 NODE_NAME_CASE(SWAP_CSR) 10683 } 10684 // clang-format on 10685 return nullptr; 10686 #undef NODE_NAME_CASE 10687 } 10688 10689 /// getConstraintType - Given a constraint letter, return the type of 10690 /// constraint it is for this target. 10691 RISCVTargetLowering::ConstraintType 10692 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 10693 if (Constraint.size() == 1) { 10694 switch (Constraint[0]) { 10695 default: 10696 break; 10697 case 'f': 10698 return C_RegisterClass; 10699 case 'I': 10700 case 'J': 10701 case 'K': 10702 return C_Immediate; 10703 case 'A': 10704 return C_Memory; 10705 case 'S': // A symbolic address 10706 return C_Other; 10707 } 10708 } else { 10709 if (Constraint == "vr" || Constraint == "vm") 10710 return C_RegisterClass; 10711 } 10712 return TargetLowering::getConstraintType(Constraint); 10713 } 10714 10715 std::pair<unsigned, const TargetRegisterClass *> 10716 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10717 StringRef Constraint, 10718 MVT VT) const { 10719 // First, see if this is a constraint that directly corresponds to a 10720 // RISCV register class. 10721 if (Constraint.size() == 1) { 10722 switch (Constraint[0]) { 10723 case 'r': 10724 // TODO: Support fixed vectors up to XLen for P extension? 10725 if (VT.isVector()) 10726 break; 10727 return std::make_pair(0U, &RISCV::GPRRegClass); 10728 case 'f': 10729 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 10730 return std::make_pair(0U, &RISCV::FPR16RegClass); 10731 if (Subtarget.hasStdExtF() && VT == MVT::f32) 10732 return std::make_pair(0U, &RISCV::FPR32RegClass); 10733 if (Subtarget.hasStdExtD() && VT == MVT::f64) 10734 return std::make_pair(0U, &RISCV::FPR64RegClass); 10735 break; 10736 default: 10737 break; 10738 } 10739 } else if (Constraint == "vr") { 10740 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 10741 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10742 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 10743 return std::make_pair(0U, RC); 10744 } 10745 } else if (Constraint == "vm") { 10746 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 10747 return std::make_pair(0U, &RISCV::VMV0RegClass); 10748 } 10749 10750 // Clang will correctly decode the usage of register name aliases into their 10751 // official names. However, other frontends like `rustc` do not. This allows 10752 // users of these frontends to use the ABI names for registers in LLVM-style 10753 // register constraints. 10754 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 10755 .Case("{zero}", RISCV::X0) 10756 .Case("{ra}", RISCV::X1) 10757 .Case("{sp}", RISCV::X2) 10758 .Case("{gp}", RISCV::X3) 10759 .Case("{tp}", RISCV::X4) 10760 .Case("{t0}", RISCV::X5) 10761 .Case("{t1}", RISCV::X6) 10762 .Case("{t2}", RISCV::X7) 10763 .Cases("{s0}", "{fp}", RISCV::X8) 10764 .Case("{s1}", RISCV::X9) 10765 .Case("{a0}", RISCV::X10) 10766 .Case("{a1}", RISCV::X11) 10767 .Case("{a2}", RISCV::X12) 10768 .Case("{a3}", RISCV::X13) 10769 .Case("{a4}", RISCV::X14) 10770 .Case("{a5}", RISCV::X15) 10771 .Case("{a6}", RISCV::X16) 10772 .Case("{a7}", RISCV::X17) 10773 .Case("{s2}", RISCV::X18) 10774 .Case("{s3}", RISCV::X19) 10775 .Case("{s4}", RISCV::X20) 10776 .Case("{s5}", RISCV::X21) 10777 .Case("{s6}", RISCV::X22) 10778 .Case("{s7}", RISCV::X23) 10779 .Case("{s8}", RISCV::X24) 10780 .Case("{s9}", RISCV::X25) 10781 .Case("{s10}", RISCV::X26) 10782 .Case("{s11}", RISCV::X27) 10783 .Case("{t3}", RISCV::X28) 10784 .Case("{t4}", RISCV::X29) 10785 .Case("{t5}", RISCV::X30) 10786 .Case("{t6}", RISCV::X31) 10787 .Default(RISCV::NoRegister); 10788 if (XRegFromAlias != RISCV::NoRegister) 10789 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 10790 10791 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 10792 // TableGen record rather than the AsmName to choose registers for InlineAsm 10793 // constraints, plus we want to match those names to the widest floating point 10794 // register type available, manually select floating point registers here. 10795 // 10796 // The second case is the ABI name of the register, so that frontends can also 10797 // use the ABI names in register constraint lists. 10798 if (Subtarget.hasStdExtF()) { 10799 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 10800 .Cases("{f0}", "{ft0}", RISCV::F0_F) 10801 .Cases("{f1}", "{ft1}", RISCV::F1_F) 10802 .Cases("{f2}", "{ft2}", RISCV::F2_F) 10803 .Cases("{f3}", "{ft3}", RISCV::F3_F) 10804 .Cases("{f4}", "{ft4}", RISCV::F4_F) 10805 .Cases("{f5}", "{ft5}", RISCV::F5_F) 10806 .Cases("{f6}", "{ft6}", RISCV::F6_F) 10807 .Cases("{f7}", "{ft7}", RISCV::F7_F) 10808 .Cases("{f8}", "{fs0}", RISCV::F8_F) 10809 .Cases("{f9}", "{fs1}", RISCV::F9_F) 10810 .Cases("{f10}", "{fa0}", RISCV::F10_F) 10811 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10812 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10813 .Cases("{f13}", "{fa3}", RISCV::F13_F) 10814 .Cases("{f14}", "{fa4}", RISCV::F14_F) 10815 .Cases("{f15}", "{fa5}", RISCV::F15_F) 10816 .Cases("{f16}", "{fa6}", RISCV::F16_F) 10817 .Cases("{f17}", "{fa7}", RISCV::F17_F) 10818 .Cases("{f18}", "{fs2}", RISCV::F18_F) 10819 .Cases("{f19}", "{fs3}", RISCV::F19_F) 10820 .Cases("{f20}", "{fs4}", RISCV::F20_F) 10821 .Cases("{f21}", "{fs5}", RISCV::F21_F) 10822 .Cases("{f22}", "{fs6}", RISCV::F22_F) 10823 .Cases("{f23}", "{fs7}", RISCV::F23_F) 10824 .Cases("{f24}", "{fs8}", RISCV::F24_F) 10825 .Cases("{f25}", "{fs9}", RISCV::F25_F) 10826 .Cases("{f26}", "{fs10}", RISCV::F26_F) 10827 .Cases("{f27}", "{fs11}", RISCV::F27_F) 10828 .Cases("{f28}", "{ft8}", RISCV::F28_F) 10829 .Cases("{f29}", "{ft9}", RISCV::F29_F) 10830 .Cases("{f30}", "{ft10}", RISCV::F30_F) 10831 .Cases("{f31}", "{ft11}", RISCV::F31_F) 10832 .Default(RISCV::NoRegister); 10833 if (FReg != RISCV::NoRegister) { 10834 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 10835 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 10836 unsigned RegNo = FReg - RISCV::F0_F; 10837 unsigned DReg = RISCV::F0_D + RegNo; 10838 return std::make_pair(DReg, &RISCV::FPR64RegClass); 10839 } 10840 if (VT == MVT::f32 || VT == MVT::Other) 10841 return std::make_pair(FReg, &RISCV::FPR32RegClass); 10842 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 10843 unsigned RegNo = FReg - RISCV::F0_F; 10844 unsigned HReg = RISCV::F0_H + RegNo; 10845 return std::make_pair(HReg, &RISCV::FPR16RegClass); 10846 } 10847 } 10848 } 10849 10850 if (Subtarget.hasVInstructions()) { 10851 Register VReg = StringSwitch<Register>(Constraint.lower()) 10852 .Case("{v0}", RISCV::V0) 10853 .Case("{v1}", RISCV::V1) 10854 .Case("{v2}", RISCV::V2) 10855 .Case("{v3}", RISCV::V3) 10856 .Case("{v4}", RISCV::V4) 10857 .Case("{v5}", RISCV::V5) 10858 .Case("{v6}", RISCV::V6) 10859 .Case("{v7}", RISCV::V7) 10860 .Case("{v8}", RISCV::V8) 10861 .Case("{v9}", RISCV::V9) 10862 .Case("{v10}", RISCV::V10) 10863 .Case("{v11}", RISCV::V11) 10864 .Case("{v12}", RISCV::V12) 10865 .Case("{v13}", RISCV::V13) 10866 .Case("{v14}", RISCV::V14) 10867 .Case("{v15}", RISCV::V15) 10868 .Case("{v16}", RISCV::V16) 10869 .Case("{v17}", RISCV::V17) 10870 .Case("{v18}", RISCV::V18) 10871 .Case("{v19}", RISCV::V19) 10872 .Case("{v20}", RISCV::V20) 10873 .Case("{v21}", RISCV::V21) 10874 .Case("{v22}", RISCV::V22) 10875 .Case("{v23}", RISCV::V23) 10876 .Case("{v24}", RISCV::V24) 10877 .Case("{v25}", RISCV::V25) 10878 .Case("{v26}", RISCV::V26) 10879 .Case("{v27}", RISCV::V27) 10880 .Case("{v28}", RISCV::V28) 10881 .Case("{v29}", RISCV::V29) 10882 .Case("{v30}", RISCV::V30) 10883 .Case("{v31}", RISCV::V31) 10884 .Default(RISCV::NoRegister); 10885 if (VReg != RISCV::NoRegister) { 10886 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 10887 return std::make_pair(VReg, &RISCV::VMRegClass); 10888 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 10889 return std::make_pair(VReg, &RISCV::VRRegClass); 10890 for (const auto *RC : 10891 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10892 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 10893 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 10894 return std::make_pair(VReg, RC); 10895 } 10896 } 10897 } 10898 } 10899 10900 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10901 } 10902 10903 unsigned 10904 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 10905 // Currently only support length 1 constraints. 10906 if (ConstraintCode.size() == 1) { 10907 switch (ConstraintCode[0]) { 10908 case 'A': 10909 return InlineAsm::Constraint_A; 10910 default: 10911 break; 10912 } 10913 } 10914 10915 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 10916 } 10917 10918 void RISCVTargetLowering::LowerAsmOperandForConstraint( 10919 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 10920 SelectionDAG &DAG) const { 10921 // Currently only support length 1 constraints. 10922 if (Constraint.length() == 1) { 10923 switch (Constraint[0]) { 10924 case 'I': 10925 // Validate & create a 12-bit signed immediate operand. 10926 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10927 uint64_t CVal = C->getSExtValue(); 10928 if (isInt<12>(CVal)) 10929 Ops.push_back( 10930 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10931 } 10932 return; 10933 case 'J': 10934 // Validate & create an integer zero operand. 10935 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 10936 if (C->getZExtValue() == 0) 10937 Ops.push_back( 10938 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 10939 return; 10940 case 'K': 10941 // Validate & create a 5-bit unsigned immediate operand. 10942 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10943 uint64_t CVal = C->getZExtValue(); 10944 if (isUInt<5>(CVal)) 10945 Ops.push_back( 10946 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10947 } 10948 return; 10949 case 'S': 10950 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 10951 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 10952 GA->getValueType(0))); 10953 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 10954 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 10955 BA->getValueType(0))); 10956 } 10957 return; 10958 default: 10959 break; 10960 } 10961 } 10962 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 10963 } 10964 10965 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 10966 Instruction *Inst, 10967 AtomicOrdering Ord) const { 10968 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 10969 return Builder.CreateFence(Ord); 10970 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 10971 return Builder.CreateFence(AtomicOrdering::Release); 10972 return nullptr; 10973 } 10974 10975 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 10976 Instruction *Inst, 10977 AtomicOrdering Ord) const { 10978 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 10979 return Builder.CreateFence(AtomicOrdering::Acquire); 10980 return nullptr; 10981 } 10982 10983 TargetLowering::AtomicExpansionKind 10984 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10985 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 10986 // point operations can't be used in an lr/sc sequence without breaking the 10987 // forward-progress guarantee. 10988 if (AI->isFloatingPointOperation()) 10989 return AtomicExpansionKind::CmpXChg; 10990 10991 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10992 if (Size == 8 || Size == 16) 10993 return AtomicExpansionKind::MaskedIntrinsic; 10994 return AtomicExpansionKind::None; 10995 } 10996 10997 static Intrinsic::ID 10998 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 10999 if (XLen == 32) { 11000 switch (BinOp) { 11001 default: 11002 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11003 case AtomicRMWInst::Xchg: 11004 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11005 case AtomicRMWInst::Add: 11006 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11007 case AtomicRMWInst::Sub: 11008 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11009 case AtomicRMWInst::Nand: 11010 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11011 case AtomicRMWInst::Max: 11012 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11013 case AtomicRMWInst::Min: 11014 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11015 case AtomicRMWInst::UMax: 11016 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11017 case AtomicRMWInst::UMin: 11018 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11019 } 11020 } 11021 11022 if (XLen == 64) { 11023 switch (BinOp) { 11024 default: 11025 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11026 case AtomicRMWInst::Xchg: 11027 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11028 case AtomicRMWInst::Add: 11029 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11030 case AtomicRMWInst::Sub: 11031 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11032 case AtomicRMWInst::Nand: 11033 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11034 case AtomicRMWInst::Max: 11035 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11036 case AtomicRMWInst::Min: 11037 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11038 case AtomicRMWInst::UMax: 11039 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11040 case AtomicRMWInst::UMin: 11041 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11042 } 11043 } 11044 11045 llvm_unreachable("Unexpected XLen\n"); 11046 } 11047 11048 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11049 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11050 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11051 unsigned XLen = Subtarget.getXLen(); 11052 Value *Ordering = 11053 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11054 Type *Tys[] = {AlignedAddr->getType()}; 11055 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11056 AI->getModule(), 11057 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11058 11059 if (XLen == 64) { 11060 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11061 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11062 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11063 } 11064 11065 Value *Result; 11066 11067 // Must pass the shift amount needed to sign extend the loaded value prior 11068 // to performing a signed comparison for min/max. ShiftAmt is the number of 11069 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11070 // is the number of bits to left+right shift the value in order to 11071 // sign-extend. 11072 if (AI->getOperation() == AtomicRMWInst::Min || 11073 AI->getOperation() == AtomicRMWInst::Max) { 11074 const DataLayout &DL = AI->getModule()->getDataLayout(); 11075 unsigned ValWidth = 11076 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11077 Value *SextShamt = 11078 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11079 Result = Builder.CreateCall(LrwOpScwLoop, 11080 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11081 } else { 11082 Result = 11083 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11084 } 11085 11086 if (XLen == 64) 11087 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11088 return Result; 11089 } 11090 11091 TargetLowering::AtomicExpansionKind 11092 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11093 AtomicCmpXchgInst *CI) const { 11094 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11095 if (Size == 8 || Size == 16) 11096 return AtomicExpansionKind::MaskedIntrinsic; 11097 return AtomicExpansionKind::None; 11098 } 11099 11100 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11101 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11102 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11103 unsigned XLen = Subtarget.getXLen(); 11104 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11105 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11106 if (XLen == 64) { 11107 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11108 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11109 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11110 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11111 } 11112 Type *Tys[] = {AlignedAddr->getType()}; 11113 Function *MaskedCmpXchg = 11114 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11115 Value *Result = Builder.CreateCall( 11116 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11117 if (XLen == 64) 11118 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11119 return Result; 11120 } 11121 11122 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11123 return false; 11124 } 11125 11126 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11127 EVT VT) const { 11128 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11129 return false; 11130 11131 switch (FPVT.getSimpleVT().SimpleTy) { 11132 case MVT::f16: 11133 return Subtarget.hasStdExtZfh(); 11134 case MVT::f32: 11135 return Subtarget.hasStdExtF(); 11136 case MVT::f64: 11137 return Subtarget.hasStdExtD(); 11138 default: 11139 return false; 11140 } 11141 } 11142 11143 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11144 // If we are using the small code model, we can reduce size of jump table 11145 // entry to 4 bytes. 11146 if (Subtarget.is64Bit() && !isPositionIndependent() && 11147 getTargetMachine().getCodeModel() == CodeModel::Small) { 11148 return MachineJumpTableInfo::EK_Custom32; 11149 } 11150 return TargetLowering::getJumpTableEncoding(); 11151 } 11152 11153 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11154 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11155 unsigned uid, MCContext &Ctx) const { 11156 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11157 getTargetMachine().getCodeModel() == CodeModel::Small); 11158 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11159 } 11160 11161 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11162 EVT VT) const { 11163 VT = VT.getScalarType(); 11164 11165 if (!VT.isSimple()) 11166 return false; 11167 11168 switch (VT.getSimpleVT().SimpleTy) { 11169 case MVT::f16: 11170 return Subtarget.hasStdExtZfh(); 11171 case MVT::f32: 11172 return Subtarget.hasStdExtF(); 11173 case MVT::f64: 11174 return Subtarget.hasStdExtD(); 11175 default: 11176 break; 11177 } 11178 11179 return false; 11180 } 11181 11182 Register RISCVTargetLowering::getExceptionPointerRegister( 11183 const Constant *PersonalityFn) const { 11184 return RISCV::X10; 11185 } 11186 11187 Register RISCVTargetLowering::getExceptionSelectorRegister( 11188 const Constant *PersonalityFn) const { 11189 return RISCV::X11; 11190 } 11191 11192 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11193 // Return false to suppress the unnecessary extensions if the LibCall 11194 // arguments or return value is f32 type for LP64 ABI. 11195 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11196 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11197 return false; 11198 11199 return true; 11200 } 11201 11202 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11203 if (Subtarget.is64Bit() && Type == MVT::i32) 11204 return true; 11205 11206 return IsSigned; 11207 } 11208 11209 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11210 SDValue C) const { 11211 // Check integral scalar types. 11212 if (VT.isScalarInteger()) { 11213 // Omit the optimization if the sub target has the M extension and the data 11214 // size exceeds XLen. 11215 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11216 return false; 11217 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11218 // Break the MUL to a SLLI and an ADD/SUB. 11219 const APInt &Imm = ConstNode->getAPIntValue(); 11220 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11221 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11222 return true; 11223 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11224 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11225 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11226 (Imm - 8).isPowerOf2())) 11227 return true; 11228 // Omit the following optimization if the sub target has the M extension 11229 // and the data size >= XLen. 11230 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11231 return false; 11232 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11233 // a pair of LUI/ADDI. 11234 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11235 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11236 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11237 (1 - ImmS).isPowerOf2()) 11238 return true; 11239 } 11240 } 11241 } 11242 11243 return false; 11244 } 11245 11246 bool RISCVTargetLowering::isMulAddWithConstProfitable( 11247 const SDValue &AddNode, const SDValue &ConstNode) const { 11248 // Let the DAGCombiner decide for vectors. 11249 EVT VT = AddNode.getValueType(); 11250 if (VT.isVector()) 11251 return true; 11252 11253 // Let the DAGCombiner decide for larger types. 11254 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11255 return true; 11256 11257 // It is worse if c1 is simm12 while c1*c2 is not. 11258 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11259 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11260 const APInt &C1 = C1Node->getAPIntValue(); 11261 const APInt &C2 = C2Node->getAPIntValue(); 11262 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11263 return false; 11264 11265 // Default to true and let the DAGCombiner decide. 11266 return true; 11267 } 11268 11269 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11270 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11271 bool *Fast) const { 11272 if (!VT.isVector()) 11273 return false; 11274 11275 EVT ElemVT = VT.getVectorElementType(); 11276 if (Alignment >= ElemVT.getStoreSize()) { 11277 if (Fast) 11278 *Fast = true; 11279 return true; 11280 } 11281 11282 return false; 11283 } 11284 11285 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11286 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11287 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11288 bool IsABIRegCopy = CC.hasValue(); 11289 EVT ValueVT = Val.getValueType(); 11290 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11291 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11292 // and cast to f32. 11293 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11294 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11295 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11296 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11297 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11298 Parts[0] = Val; 11299 return true; 11300 } 11301 11302 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11303 LLVMContext &Context = *DAG.getContext(); 11304 EVT ValueEltVT = ValueVT.getVectorElementType(); 11305 EVT PartEltVT = PartVT.getVectorElementType(); 11306 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11307 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11308 if (PartVTBitSize % ValueVTBitSize == 0) { 11309 assert(PartVTBitSize >= ValueVTBitSize); 11310 // If the element types are different, bitcast to the same element type of 11311 // PartVT first. 11312 // Give an example here, we want copy a <vscale x 1 x i8> value to 11313 // <vscale x 4 x i16>. 11314 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11315 // subvector, then we can bitcast to <vscale x 4 x i16>. 11316 if (ValueEltVT != PartEltVT) { 11317 if (PartVTBitSize > ValueVTBitSize) { 11318 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11319 assert(Count != 0 && "The number of element should not be zero."); 11320 EVT SameEltTypeVT = 11321 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11322 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11323 DAG.getUNDEF(SameEltTypeVT), Val, 11324 DAG.getVectorIdxConstant(0, DL)); 11325 } 11326 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11327 } else { 11328 Val = 11329 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11330 Val, DAG.getVectorIdxConstant(0, DL)); 11331 } 11332 Parts[0] = Val; 11333 return true; 11334 } 11335 } 11336 return false; 11337 } 11338 11339 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11340 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11341 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11342 bool IsABIRegCopy = CC.hasValue(); 11343 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11344 SDValue Val = Parts[0]; 11345 11346 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11347 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11348 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11349 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11350 return Val; 11351 } 11352 11353 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11354 LLVMContext &Context = *DAG.getContext(); 11355 SDValue Val = Parts[0]; 11356 EVT ValueEltVT = ValueVT.getVectorElementType(); 11357 EVT PartEltVT = PartVT.getVectorElementType(); 11358 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11359 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11360 if (PartVTBitSize % ValueVTBitSize == 0) { 11361 assert(PartVTBitSize >= ValueVTBitSize); 11362 EVT SameEltTypeVT = ValueVT; 11363 // If the element types are different, convert it to the same element type 11364 // of PartVT. 11365 // Give an example here, we want copy a <vscale x 1 x i8> value from 11366 // <vscale x 4 x i16>. 11367 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11368 // then we can extract <vscale x 1 x i8>. 11369 if (ValueEltVT != PartEltVT) { 11370 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11371 assert(Count != 0 && "The number of element should not be zero."); 11372 SameEltTypeVT = 11373 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11374 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11375 } 11376 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11377 DAG.getVectorIdxConstant(0, DL)); 11378 return Val; 11379 } 11380 } 11381 return SDValue(); 11382 } 11383 11384 SDValue 11385 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11386 SelectionDAG &DAG, 11387 SmallVectorImpl<SDNode *> &Created) const { 11388 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11389 if (isIntDivCheap(N->getValueType(0), Attr)) 11390 return SDValue(N, 0); // Lower SDIV as SDIV 11391 11392 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11393 "Unexpected divisor!"); 11394 11395 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11396 if (!Subtarget.hasStdExtZbt()) 11397 return SDValue(); 11398 11399 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11400 // Besides, more critical path instructions will be generated when dividing 11401 // by 2. So we keep using the original DAGs for these cases. 11402 unsigned Lg2 = Divisor.countTrailingZeros(); 11403 if (Lg2 == 1 || Lg2 >= 12) 11404 return SDValue(); 11405 11406 // fold (sdiv X, pow2) 11407 EVT VT = N->getValueType(0); 11408 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11409 return SDValue(); 11410 11411 SDLoc DL(N); 11412 SDValue N0 = N->getOperand(0); 11413 SDValue Zero = DAG.getConstant(0, DL, VT); 11414 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11415 11416 // Add (N0 < 0) ? Pow2 - 1 : 0; 11417 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11418 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11419 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11420 11421 Created.push_back(Cmp.getNode()); 11422 Created.push_back(Add.getNode()); 11423 Created.push_back(Sel.getNode()); 11424 11425 // Divide by pow2. 11426 SDValue SRA = 11427 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11428 11429 // If we're dividing by a positive value, we're done. Otherwise, we must 11430 // negate the result. 11431 if (Divisor.isNonNegative()) 11432 return SRA; 11433 11434 Created.push_back(SRA.getNode()); 11435 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11436 } 11437 11438 #define GET_REGISTER_MATCHER 11439 #include "RISCVGenAsmMatcher.inc" 11440 11441 Register 11442 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11443 const MachineFunction &MF) const { 11444 Register Reg = MatchRegisterAltName(RegName); 11445 if (Reg == RISCV::NoRegister) 11446 Reg = MatchRegisterName(RegName); 11447 if (Reg == RISCV::NoRegister) 11448 report_fatal_error( 11449 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11450 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11451 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11452 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11453 StringRef(RegName) + "\".")); 11454 return Reg; 11455 } 11456 11457 namespace llvm { 11458 namespace RISCVVIntrinsicsTable { 11459 11460 #define GET_RISCVVIntrinsicsTable_IMPL 11461 #include "RISCVGenSearchableTables.inc" 11462 11463 } // namespace RISCVVIntrinsicsTable 11464 11465 } // namespace llvm 11466