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_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 535 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, 536 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 764 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 765 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 766 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 767 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 768 769 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 770 771 setOperationAction(ISD::LOAD, VT, Custom); 772 setOperationAction(ISD::STORE, VT, Custom); 773 774 setOperationAction(ISD::MLOAD, VT, Custom); 775 setOperationAction(ISD::MSTORE, VT, Custom); 776 setOperationAction(ISD::MGATHER, VT, Custom); 777 setOperationAction(ISD::MSCATTER, VT, Custom); 778 779 setOperationAction(ISD::VP_LOAD, VT, Custom); 780 setOperationAction(ISD::VP_STORE, VT, Custom); 781 setOperationAction(ISD::VP_GATHER, VT, Custom); 782 setOperationAction(ISD::VP_SCATTER, VT, Custom); 783 784 setOperationAction(ISD::SELECT, VT, Custom); 785 setOperationAction(ISD::SELECT_CC, VT, Expand); 786 787 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 788 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 789 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 790 791 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 792 793 for (unsigned VPOpc : FloatingPointVPOps) 794 setOperationAction(VPOpc, VT, Custom); 795 }; 796 797 // Sets common extload/truncstore actions on RVV floating-point vector 798 // types. 799 const auto SetCommonVFPExtLoadTruncStoreActions = 800 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 801 for (auto SmallVT : SmallerVTs) { 802 setTruncStoreAction(VT, SmallVT, Expand); 803 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 804 } 805 }; 806 807 if (Subtarget.hasVInstructionsF16()) 808 for (MVT VT : F16VecVTs) 809 SetCommonVFPActions(VT); 810 811 for (MVT VT : F32VecVTs) { 812 if (Subtarget.hasVInstructionsF32()) 813 SetCommonVFPActions(VT); 814 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 815 } 816 817 for (MVT VT : F64VecVTs) { 818 if (Subtarget.hasVInstructionsF64()) 819 SetCommonVFPActions(VT); 820 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 821 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 822 } 823 824 if (Subtarget.useRVVForFixedLengthVectors()) { 825 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 826 if (!useRVVForFixedLengthVectorVT(VT)) 827 continue; 828 829 // By default everything must be expanded. 830 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 831 setOperationAction(Op, VT, Expand); 832 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 833 setTruncStoreAction(VT, OtherVT, Expand); 834 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 835 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 836 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 837 } 838 839 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 840 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 841 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 842 843 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 844 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 845 846 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 847 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 848 849 setOperationAction(ISD::LOAD, VT, Custom); 850 setOperationAction(ISD::STORE, VT, Custom); 851 852 setOperationAction(ISD::SETCC, VT, Custom); 853 854 setOperationAction(ISD::SELECT, VT, Custom); 855 856 setOperationAction(ISD::TRUNCATE, VT, Custom); 857 858 setOperationAction(ISD::BITCAST, VT, Custom); 859 860 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 861 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 862 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 863 864 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 865 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 866 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 867 868 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 869 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 870 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 871 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 872 873 // Operations below are different for between masks and other vectors. 874 if (VT.getVectorElementType() == MVT::i1) { 875 setOperationAction(ISD::VP_AND, VT, Custom); 876 setOperationAction(ISD::VP_OR, VT, Custom); 877 setOperationAction(ISD::VP_XOR, VT, Custom); 878 setOperationAction(ISD::AND, VT, Custom); 879 setOperationAction(ISD::OR, VT, Custom); 880 setOperationAction(ISD::XOR, VT, Custom); 881 continue; 882 } 883 884 // Use SPLAT_VECTOR to prevent type legalization from destroying the 885 // splats when type legalizing i64 scalar on RV32. 886 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 887 // improvements first. 888 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 889 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 890 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 891 } 892 893 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 894 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 895 896 setOperationAction(ISD::MLOAD, VT, Custom); 897 setOperationAction(ISD::MSTORE, VT, Custom); 898 setOperationAction(ISD::MGATHER, VT, Custom); 899 setOperationAction(ISD::MSCATTER, VT, Custom); 900 901 setOperationAction(ISD::VP_LOAD, VT, Custom); 902 setOperationAction(ISD::VP_STORE, VT, Custom); 903 setOperationAction(ISD::VP_GATHER, VT, Custom); 904 setOperationAction(ISD::VP_SCATTER, VT, Custom); 905 906 setOperationAction(ISD::ADD, VT, Custom); 907 setOperationAction(ISD::MUL, VT, Custom); 908 setOperationAction(ISD::SUB, VT, Custom); 909 setOperationAction(ISD::AND, VT, Custom); 910 setOperationAction(ISD::OR, VT, Custom); 911 setOperationAction(ISD::XOR, VT, Custom); 912 setOperationAction(ISD::SDIV, VT, Custom); 913 setOperationAction(ISD::SREM, VT, Custom); 914 setOperationAction(ISD::UDIV, VT, Custom); 915 setOperationAction(ISD::UREM, VT, Custom); 916 setOperationAction(ISD::SHL, VT, Custom); 917 setOperationAction(ISD::SRA, VT, Custom); 918 setOperationAction(ISD::SRL, VT, Custom); 919 920 setOperationAction(ISD::SMIN, VT, Custom); 921 setOperationAction(ISD::SMAX, VT, Custom); 922 setOperationAction(ISD::UMIN, VT, Custom); 923 setOperationAction(ISD::UMAX, VT, Custom); 924 setOperationAction(ISD::ABS, VT, Custom); 925 926 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 927 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 928 setOperationAction(ISD::MULHS, VT, Custom); 929 setOperationAction(ISD::MULHU, VT, Custom); 930 } 931 932 setOperationAction(ISD::SADDSAT, VT, Custom); 933 setOperationAction(ISD::UADDSAT, VT, Custom); 934 setOperationAction(ISD::SSUBSAT, VT, Custom); 935 setOperationAction(ISD::USUBSAT, VT, Custom); 936 937 setOperationAction(ISD::VSELECT, VT, Custom); 938 setOperationAction(ISD::SELECT_CC, VT, Expand); 939 940 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 941 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 942 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 943 944 // Custom-lower reduction operations to set up the corresponding custom 945 // nodes' operands. 946 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 947 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 948 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 949 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 950 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 951 952 for (unsigned VPOpc : IntegerVPOps) 953 setOperationAction(VPOpc, VT, Custom); 954 955 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 956 // type that can represent the value exactly. 957 if (VT.getVectorElementType() != MVT::i64) { 958 MVT FloatEltVT = 959 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 960 EVT FloatVT = 961 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 962 if (isTypeLegal(FloatVT)) { 963 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 964 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 965 } 966 } 967 } 968 969 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 970 if (!useRVVForFixedLengthVectorVT(VT)) 971 continue; 972 973 // By default everything must be expanded. 974 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 975 setOperationAction(Op, VT, Expand); 976 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 977 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 978 setTruncStoreAction(VT, OtherVT, Expand); 979 } 980 981 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 982 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 983 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 984 985 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 986 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 987 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 988 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 990 991 setOperationAction(ISD::LOAD, VT, Custom); 992 setOperationAction(ISD::STORE, VT, Custom); 993 setOperationAction(ISD::MLOAD, VT, Custom); 994 setOperationAction(ISD::MSTORE, VT, Custom); 995 setOperationAction(ISD::MGATHER, VT, Custom); 996 setOperationAction(ISD::MSCATTER, VT, Custom); 997 998 setOperationAction(ISD::VP_LOAD, VT, Custom); 999 setOperationAction(ISD::VP_STORE, VT, Custom); 1000 setOperationAction(ISD::VP_GATHER, VT, Custom); 1001 setOperationAction(ISD::VP_SCATTER, VT, Custom); 1002 1003 setOperationAction(ISD::FADD, VT, Custom); 1004 setOperationAction(ISD::FSUB, VT, Custom); 1005 setOperationAction(ISD::FMUL, VT, Custom); 1006 setOperationAction(ISD::FDIV, VT, Custom); 1007 setOperationAction(ISD::FNEG, VT, Custom); 1008 setOperationAction(ISD::FABS, VT, Custom); 1009 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 1010 setOperationAction(ISD::FSQRT, VT, Custom); 1011 setOperationAction(ISD::FMA, VT, Custom); 1012 setOperationAction(ISD::FMINNUM, VT, Custom); 1013 setOperationAction(ISD::FMAXNUM, VT, Custom); 1014 1015 setOperationAction(ISD::FP_ROUND, VT, Custom); 1016 setOperationAction(ISD::FP_EXTEND, VT, Custom); 1017 1018 setOperationAction(ISD::FTRUNC, VT, Custom); 1019 setOperationAction(ISD::FCEIL, VT, Custom); 1020 setOperationAction(ISD::FFLOOR, VT, Custom); 1021 1022 for (auto CC : VFPCCToExpand) 1023 setCondCodeAction(CC, VT, Expand); 1024 1025 setOperationAction(ISD::VSELECT, VT, Custom); 1026 setOperationAction(ISD::SELECT, VT, Custom); 1027 setOperationAction(ISD::SELECT_CC, VT, Expand); 1028 1029 setOperationAction(ISD::BITCAST, VT, Custom); 1030 1031 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1032 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1033 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1034 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1035 1036 for (unsigned VPOpc : FloatingPointVPOps) 1037 setOperationAction(VPOpc, VT, Custom); 1038 } 1039 1040 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1041 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1042 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1043 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1044 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1045 if (Subtarget.hasStdExtZfh()) 1046 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1047 if (Subtarget.hasStdExtF()) 1048 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1049 if (Subtarget.hasStdExtD()) 1050 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1051 } 1052 } 1053 1054 // Function alignments. 1055 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1056 setMinFunctionAlignment(FunctionAlignment); 1057 setPrefFunctionAlignment(FunctionAlignment); 1058 1059 setMinimumJumpTableEntries(5); 1060 1061 // Jumps are expensive, compared to logic 1062 setJumpIsExpensive(); 1063 1064 setTargetDAGCombine(ISD::ADD); 1065 setTargetDAGCombine(ISD::SUB); 1066 setTargetDAGCombine(ISD::AND); 1067 setTargetDAGCombine(ISD::OR); 1068 setTargetDAGCombine(ISD::XOR); 1069 setTargetDAGCombine(ISD::ANY_EXTEND); 1070 if (Subtarget.hasStdExtF()) { 1071 setTargetDAGCombine(ISD::ZERO_EXTEND); 1072 setTargetDAGCombine(ISD::FP_TO_SINT); 1073 setTargetDAGCombine(ISD::FP_TO_UINT); 1074 setTargetDAGCombine(ISD::FP_TO_SINT_SAT); 1075 setTargetDAGCombine(ISD::FP_TO_UINT_SAT); 1076 } 1077 if (Subtarget.hasVInstructions()) { 1078 setTargetDAGCombine(ISD::FCOPYSIGN); 1079 setTargetDAGCombine(ISD::MGATHER); 1080 setTargetDAGCombine(ISD::MSCATTER); 1081 setTargetDAGCombine(ISD::VP_GATHER); 1082 setTargetDAGCombine(ISD::VP_SCATTER); 1083 setTargetDAGCombine(ISD::SRA); 1084 setTargetDAGCombine(ISD::SRL); 1085 setTargetDAGCombine(ISD::SHL); 1086 setTargetDAGCombine(ISD::STORE); 1087 } 1088 1089 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1090 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1091 } 1092 1093 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1094 LLVMContext &Context, 1095 EVT VT) const { 1096 if (!VT.isVector()) 1097 return getPointerTy(DL); 1098 if (Subtarget.hasVInstructions() && 1099 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1100 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1101 return VT.changeVectorElementTypeToInteger(); 1102 } 1103 1104 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1105 return Subtarget.getXLenVT(); 1106 } 1107 1108 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1109 const CallInst &I, 1110 MachineFunction &MF, 1111 unsigned Intrinsic) const { 1112 auto &DL = I.getModule()->getDataLayout(); 1113 switch (Intrinsic) { 1114 default: 1115 return false; 1116 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1117 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1118 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1119 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1120 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1121 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1122 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1123 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1124 case Intrinsic::riscv_masked_cmpxchg_i32: 1125 Info.opc = ISD::INTRINSIC_W_CHAIN; 1126 Info.memVT = MVT::i32; 1127 Info.ptrVal = I.getArgOperand(0); 1128 Info.offset = 0; 1129 Info.align = Align(4); 1130 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1131 MachineMemOperand::MOVolatile; 1132 return true; 1133 case Intrinsic::riscv_masked_strided_load: 1134 Info.opc = ISD::INTRINSIC_W_CHAIN; 1135 Info.ptrVal = I.getArgOperand(1); 1136 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1137 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1138 Info.size = MemoryLocation::UnknownSize; 1139 Info.flags |= MachineMemOperand::MOLoad; 1140 return true; 1141 case Intrinsic::riscv_masked_strided_store: 1142 Info.opc = ISD::INTRINSIC_VOID; 1143 Info.ptrVal = I.getArgOperand(1); 1144 Info.memVT = 1145 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1146 Info.align = Align( 1147 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1148 8); 1149 Info.size = MemoryLocation::UnknownSize; 1150 Info.flags |= MachineMemOperand::MOStore; 1151 return true; 1152 } 1153 } 1154 1155 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1156 const AddrMode &AM, Type *Ty, 1157 unsigned AS, 1158 Instruction *I) const { 1159 // No global is ever allowed as a base. 1160 if (AM.BaseGV) 1161 return false; 1162 1163 // Require a 12-bit signed offset. 1164 if (!isInt<12>(AM.BaseOffs)) 1165 return false; 1166 1167 switch (AM.Scale) { 1168 case 0: // "r+i" or just "i", depending on HasBaseReg. 1169 break; 1170 case 1: 1171 if (!AM.HasBaseReg) // allow "r+i". 1172 break; 1173 return false; // disallow "r+r" or "r+r+i". 1174 default: 1175 return false; 1176 } 1177 1178 return true; 1179 } 1180 1181 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1182 return isInt<12>(Imm); 1183 } 1184 1185 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1186 return isInt<12>(Imm); 1187 } 1188 1189 // On RV32, 64-bit integers are split into their high and low parts and held 1190 // in two different registers, so the trunc is free since the low register can 1191 // just be used. 1192 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1193 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1194 return false; 1195 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1196 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1197 return (SrcBits == 64 && DestBits == 32); 1198 } 1199 1200 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1201 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1202 !SrcVT.isInteger() || !DstVT.isInteger()) 1203 return false; 1204 unsigned SrcBits = SrcVT.getSizeInBits(); 1205 unsigned DestBits = DstVT.getSizeInBits(); 1206 return (SrcBits == 64 && DestBits == 32); 1207 } 1208 1209 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1210 // Zexts are free if they can be combined with a load. 1211 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1212 // poorly with type legalization of compares preferring sext. 1213 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1214 EVT MemVT = LD->getMemoryVT(); 1215 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1216 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1217 LD->getExtensionType() == ISD::ZEXTLOAD)) 1218 return true; 1219 } 1220 1221 return TargetLowering::isZExtFree(Val, VT2); 1222 } 1223 1224 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1225 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1226 } 1227 1228 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1229 return Subtarget.hasStdExtZbb(); 1230 } 1231 1232 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1233 return Subtarget.hasStdExtZbb(); 1234 } 1235 1236 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1237 EVT VT = Y.getValueType(); 1238 1239 // FIXME: Support vectors once we have tests. 1240 if (VT.isVector()) 1241 return false; 1242 1243 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1244 Subtarget.hasStdExtZbkb()) && 1245 !isa<ConstantSDNode>(Y); 1246 } 1247 1248 /// Check if sinking \p I's operands to I's basic block is profitable, because 1249 /// the operands can be folded into a target instruction, e.g. 1250 /// splats of scalars can fold into vector instructions. 1251 bool RISCVTargetLowering::shouldSinkOperands( 1252 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1253 using namespace llvm::PatternMatch; 1254 1255 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1256 return false; 1257 1258 auto IsSinker = [&](Instruction *I, int Operand) { 1259 switch (I->getOpcode()) { 1260 case Instruction::Add: 1261 case Instruction::Sub: 1262 case Instruction::Mul: 1263 case Instruction::And: 1264 case Instruction::Or: 1265 case Instruction::Xor: 1266 case Instruction::FAdd: 1267 case Instruction::FSub: 1268 case Instruction::FMul: 1269 case Instruction::FDiv: 1270 case Instruction::ICmp: 1271 case Instruction::FCmp: 1272 return true; 1273 case Instruction::Shl: 1274 case Instruction::LShr: 1275 case Instruction::AShr: 1276 case Instruction::UDiv: 1277 case Instruction::SDiv: 1278 case Instruction::URem: 1279 case Instruction::SRem: 1280 return Operand == 1; 1281 case Instruction::Call: 1282 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1283 switch (II->getIntrinsicID()) { 1284 case Intrinsic::fma: 1285 return Operand == 0 || Operand == 1; 1286 // FIXME: Our patterns can only match vx/vf instructions when the splat 1287 // it on the RHS, because TableGen doesn't recognize our VP operations 1288 // as commutative. 1289 case Intrinsic::vp_add: 1290 case Intrinsic::vp_mul: 1291 case Intrinsic::vp_and: 1292 case Intrinsic::vp_or: 1293 case Intrinsic::vp_xor: 1294 case Intrinsic::vp_fadd: 1295 case Intrinsic::vp_fmul: 1296 case Intrinsic::vp_shl: 1297 case Intrinsic::vp_lshr: 1298 case Intrinsic::vp_ashr: 1299 case Intrinsic::vp_udiv: 1300 case Intrinsic::vp_sdiv: 1301 case Intrinsic::vp_urem: 1302 case Intrinsic::vp_srem: 1303 return Operand == 1; 1304 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1305 // explicit patterns for both LHS and RHS (as 'vr' versions). 1306 case Intrinsic::vp_sub: 1307 case Intrinsic::vp_fsub: 1308 case Intrinsic::vp_fdiv: 1309 return Operand == 0 || Operand == 1; 1310 default: 1311 return false; 1312 } 1313 } 1314 return false; 1315 default: 1316 return false; 1317 } 1318 }; 1319 1320 for (auto OpIdx : enumerate(I->operands())) { 1321 if (!IsSinker(I, OpIdx.index())) 1322 continue; 1323 1324 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1325 // Make sure we are not already sinking this operand 1326 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1327 continue; 1328 1329 // We are looking for a splat that can be sunk. 1330 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1331 m_Undef(), m_ZeroMask()))) 1332 continue; 1333 1334 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1335 // and vector registers 1336 for (Use &U : Op->uses()) { 1337 Instruction *Insn = cast<Instruction>(U.getUser()); 1338 if (!IsSinker(Insn, U.getOperandNo())) 1339 return false; 1340 } 1341 1342 Ops.push_back(&Op->getOperandUse(0)); 1343 Ops.push_back(&OpIdx.value()); 1344 } 1345 return true; 1346 } 1347 1348 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1349 bool ForCodeSize) const { 1350 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1351 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1352 return false; 1353 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1354 return false; 1355 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1356 return false; 1357 return Imm.isZero(); 1358 } 1359 1360 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1361 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1362 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1363 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1364 } 1365 1366 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1367 CallingConv::ID CC, 1368 EVT VT) const { 1369 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1370 // We might still end up using a GPR but that will be decided based on ABI. 1371 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1372 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1373 return MVT::f32; 1374 1375 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1376 } 1377 1378 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1379 CallingConv::ID CC, 1380 EVT VT) const { 1381 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1382 // We might still end up using a GPR but that will be decided based on ABI. 1383 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1384 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1385 return 1; 1386 1387 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1388 } 1389 1390 // Changes the condition code and swaps operands if necessary, so the SetCC 1391 // operation matches one of the comparisons supported directly by branches 1392 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1393 // with 1/-1. 1394 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1395 ISD::CondCode &CC, SelectionDAG &DAG) { 1396 // Convert X > -1 to X >= 0. 1397 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1398 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1399 CC = ISD::SETGE; 1400 return; 1401 } 1402 // Convert X < 1 to 0 >= X. 1403 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1404 RHS = LHS; 1405 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1406 CC = ISD::SETGE; 1407 return; 1408 } 1409 1410 switch (CC) { 1411 default: 1412 break; 1413 case ISD::SETGT: 1414 case ISD::SETLE: 1415 case ISD::SETUGT: 1416 case ISD::SETULE: 1417 CC = ISD::getSetCCSwappedOperands(CC); 1418 std::swap(LHS, RHS); 1419 break; 1420 } 1421 } 1422 1423 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1424 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1425 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1426 if (VT.getVectorElementType() == MVT::i1) 1427 KnownSize *= 8; 1428 1429 switch (KnownSize) { 1430 default: 1431 llvm_unreachable("Invalid LMUL."); 1432 case 8: 1433 return RISCVII::VLMUL::LMUL_F8; 1434 case 16: 1435 return RISCVII::VLMUL::LMUL_F4; 1436 case 32: 1437 return RISCVII::VLMUL::LMUL_F2; 1438 case 64: 1439 return RISCVII::VLMUL::LMUL_1; 1440 case 128: 1441 return RISCVII::VLMUL::LMUL_2; 1442 case 256: 1443 return RISCVII::VLMUL::LMUL_4; 1444 case 512: 1445 return RISCVII::VLMUL::LMUL_8; 1446 } 1447 } 1448 1449 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1450 switch (LMul) { 1451 default: 1452 llvm_unreachable("Invalid LMUL."); 1453 case RISCVII::VLMUL::LMUL_F8: 1454 case RISCVII::VLMUL::LMUL_F4: 1455 case RISCVII::VLMUL::LMUL_F2: 1456 case RISCVII::VLMUL::LMUL_1: 1457 return RISCV::VRRegClassID; 1458 case RISCVII::VLMUL::LMUL_2: 1459 return RISCV::VRM2RegClassID; 1460 case RISCVII::VLMUL::LMUL_4: 1461 return RISCV::VRM4RegClassID; 1462 case RISCVII::VLMUL::LMUL_8: 1463 return RISCV::VRM8RegClassID; 1464 } 1465 } 1466 1467 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1468 RISCVII::VLMUL LMUL = getLMUL(VT); 1469 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1470 LMUL == RISCVII::VLMUL::LMUL_F4 || 1471 LMUL == RISCVII::VLMUL::LMUL_F2 || 1472 LMUL == RISCVII::VLMUL::LMUL_1) { 1473 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1474 "Unexpected subreg numbering"); 1475 return RISCV::sub_vrm1_0 + Index; 1476 } 1477 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1478 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1479 "Unexpected subreg numbering"); 1480 return RISCV::sub_vrm2_0 + Index; 1481 } 1482 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1483 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1484 "Unexpected subreg numbering"); 1485 return RISCV::sub_vrm4_0 + Index; 1486 } 1487 llvm_unreachable("Invalid vector type."); 1488 } 1489 1490 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1491 if (VT.getVectorElementType() == MVT::i1) 1492 return RISCV::VRRegClassID; 1493 return getRegClassIDForLMUL(getLMUL(VT)); 1494 } 1495 1496 // Attempt to decompose a subvector insert/extract between VecVT and 1497 // SubVecVT via subregister indices. Returns the subregister index that 1498 // can perform the subvector insert/extract with the given element index, as 1499 // well as the index corresponding to any leftover subvectors that must be 1500 // further inserted/extracted within the register class for SubVecVT. 1501 std::pair<unsigned, unsigned> 1502 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1503 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1504 const RISCVRegisterInfo *TRI) { 1505 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1506 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1507 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1508 "Register classes not ordered"); 1509 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1510 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1511 // Try to compose a subregister index that takes us from the incoming 1512 // LMUL>1 register class down to the outgoing one. At each step we half 1513 // the LMUL: 1514 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1515 // Note that this is not guaranteed to find a subregister index, such as 1516 // when we are extracting from one VR type to another. 1517 unsigned SubRegIdx = RISCV::NoSubRegister; 1518 for (const unsigned RCID : 1519 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1520 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1521 VecVT = VecVT.getHalfNumVectorElementsVT(); 1522 bool IsHi = 1523 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1524 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1525 getSubregIndexByMVT(VecVT, IsHi)); 1526 if (IsHi) 1527 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1528 } 1529 return {SubRegIdx, InsertExtractIdx}; 1530 } 1531 1532 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1533 // stores for those types. 1534 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1535 return !Subtarget.useRVVForFixedLengthVectors() || 1536 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1537 } 1538 1539 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1540 if (ScalarTy->isPointerTy()) 1541 return true; 1542 1543 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1544 ScalarTy->isIntegerTy(32)) 1545 return true; 1546 1547 if (ScalarTy->isIntegerTy(64)) 1548 return Subtarget.hasVInstructionsI64(); 1549 1550 if (ScalarTy->isHalfTy()) 1551 return Subtarget.hasVInstructionsF16(); 1552 if (ScalarTy->isFloatTy()) 1553 return Subtarget.hasVInstructionsF32(); 1554 if (ScalarTy->isDoubleTy()) 1555 return Subtarget.hasVInstructionsF64(); 1556 1557 return false; 1558 } 1559 1560 static SDValue getVLOperand(SDValue Op) { 1561 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1562 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1563 "Unexpected opcode"); 1564 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1565 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1566 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1567 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1568 if (!II) 1569 return SDValue(); 1570 return Op.getOperand(II->VLOperand + 1 + HasChain); 1571 } 1572 1573 static bool useRVVForFixedLengthVectorVT(MVT VT, 1574 const RISCVSubtarget &Subtarget) { 1575 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1576 if (!Subtarget.useRVVForFixedLengthVectors()) 1577 return false; 1578 1579 // We only support a set of vector types with a consistent maximum fixed size 1580 // across all supported vector element types to avoid legalization issues. 1581 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1582 // fixed-length vector type we support is 1024 bytes. 1583 if (VT.getFixedSizeInBits() > 1024 * 8) 1584 return false; 1585 1586 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1587 1588 MVT EltVT = VT.getVectorElementType(); 1589 1590 // Don't use RVV for vectors we cannot scalarize if required. 1591 switch (EltVT.SimpleTy) { 1592 // i1 is supported but has different rules. 1593 default: 1594 return false; 1595 case MVT::i1: 1596 // Masks can only use a single register. 1597 if (VT.getVectorNumElements() > MinVLen) 1598 return false; 1599 MinVLen /= 8; 1600 break; 1601 case MVT::i8: 1602 case MVT::i16: 1603 case MVT::i32: 1604 break; 1605 case MVT::i64: 1606 if (!Subtarget.hasVInstructionsI64()) 1607 return false; 1608 break; 1609 case MVT::f16: 1610 if (!Subtarget.hasVInstructionsF16()) 1611 return false; 1612 break; 1613 case MVT::f32: 1614 if (!Subtarget.hasVInstructionsF32()) 1615 return false; 1616 break; 1617 case MVT::f64: 1618 if (!Subtarget.hasVInstructionsF64()) 1619 return false; 1620 break; 1621 } 1622 1623 // Reject elements larger than ELEN. 1624 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1625 return false; 1626 1627 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1628 // Don't use RVV for types that don't fit. 1629 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1630 return false; 1631 1632 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1633 // the base fixed length RVV support in place. 1634 if (!VT.isPow2VectorType()) 1635 return false; 1636 1637 return true; 1638 } 1639 1640 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1641 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1642 } 1643 1644 // Return the largest legal scalable vector type that matches VT's element type. 1645 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1646 const RISCVSubtarget &Subtarget) { 1647 // This may be called before legal types are setup. 1648 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1649 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1650 "Expected legal fixed length vector!"); 1651 1652 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1653 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1654 1655 MVT EltVT = VT.getVectorElementType(); 1656 switch (EltVT.SimpleTy) { 1657 default: 1658 llvm_unreachable("unexpected element type for RVV container"); 1659 case MVT::i1: 1660 case MVT::i8: 1661 case MVT::i16: 1662 case MVT::i32: 1663 case MVT::i64: 1664 case MVT::f16: 1665 case MVT::f32: 1666 case MVT::f64: { 1667 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1668 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1669 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1670 unsigned NumElts = 1671 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1672 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1673 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1674 return MVT::getScalableVectorVT(EltVT, NumElts); 1675 } 1676 } 1677 } 1678 1679 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1680 const RISCVSubtarget &Subtarget) { 1681 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1682 Subtarget); 1683 } 1684 1685 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1686 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1687 } 1688 1689 // Grow V to consume an entire RVV register. 1690 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1691 const RISCVSubtarget &Subtarget) { 1692 assert(VT.isScalableVector() && 1693 "Expected to convert into a scalable vector!"); 1694 assert(V.getValueType().isFixedLengthVector() && 1695 "Expected a fixed length vector operand!"); 1696 SDLoc DL(V); 1697 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1698 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1699 } 1700 1701 // Shrink V so it's just big enough to maintain a VT's worth of data. 1702 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1703 const RISCVSubtarget &Subtarget) { 1704 assert(VT.isFixedLengthVector() && 1705 "Expected to convert into a fixed length vector!"); 1706 assert(V.getValueType().isScalableVector() && 1707 "Expected a scalable vector operand!"); 1708 SDLoc DL(V); 1709 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1710 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1711 } 1712 1713 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1714 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1715 // the vector type that it is contained in. 1716 static std::pair<SDValue, SDValue> 1717 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1718 const RISCVSubtarget &Subtarget) { 1719 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1720 MVT XLenVT = Subtarget.getXLenVT(); 1721 SDValue VL = VecVT.isFixedLengthVector() 1722 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1723 : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT); 1724 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1725 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1726 return {Mask, VL}; 1727 } 1728 1729 // As above but assuming the given type is a scalable vector type. 1730 static std::pair<SDValue, SDValue> 1731 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1732 const RISCVSubtarget &Subtarget) { 1733 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1734 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1735 } 1736 1737 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1738 // of either is (currently) supported. This can get us into an infinite loop 1739 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1740 // as a ..., etc. 1741 // Until either (or both) of these can reliably lower any node, reporting that 1742 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1743 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1744 // which is not desirable. 1745 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1746 EVT VT, unsigned DefinedValues) const { 1747 return false; 1748 } 1749 1750 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1751 // Only splats are currently supported. 1752 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1753 return true; 1754 1755 return false; 1756 } 1757 1758 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1759 const RISCVSubtarget &Subtarget) { 1760 // RISCV FP-to-int conversions saturate to the destination register size, but 1761 // don't produce 0 for nan. We can use a conversion instruction and fix the 1762 // nan case with a compare and a select. 1763 SDValue Src = Op.getOperand(0); 1764 1765 EVT DstVT = Op.getValueType(); 1766 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1767 1768 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1769 unsigned Opc; 1770 if (SatVT == DstVT) 1771 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1772 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1773 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1774 else 1775 return SDValue(); 1776 // FIXME: Support other SatVTs by clamping before or after the conversion. 1777 1778 SDLoc DL(Op); 1779 SDValue FpToInt = DAG.getNode( 1780 Opc, DL, DstVT, Src, 1781 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1782 1783 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1784 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1785 } 1786 1787 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1788 // and back. Taking care to avoid converting values that are nan or already 1789 // correct. 1790 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1791 // have FRM dependencies modeled yet. 1792 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1793 MVT VT = Op.getSimpleValueType(); 1794 assert(VT.isVector() && "Unexpected type"); 1795 1796 SDLoc DL(Op); 1797 1798 // Freeze the source since we are increasing the number of uses. 1799 SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0)); 1800 1801 // Truncate to integer and convert back to FP. 1802 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1803 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1804 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1805 1806 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1807 1808 if (Op.getOpcode() == ISD::FCEIL) { 1809 // If the truncated value is the greater than or equal to the original 1810 // value, we've computed the ceil. Otherwise, we went the wrong way and 1811 // need to increase by 1. 1812 // FIXME: This should use a masked operation. Handle here or in isel? 1813 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1814 DAG.getConstantFP(1.0, DL, VT)); 1815 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1816 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1817 } else if (Op.getOpcode() == ISD::FFLOOR) { 1818 // If the truncated value is the less than or equal to the original value, 1819 // we've computed the floor. Otherwise, we went the wrong way and need to 1820 // decrease by 1. 1821 // FIXME: This should use a masked operation. Handle here or in isel? 1822 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1823 DAG.getConstantFP(1.0, DL, VT)); 1824 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1825 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1826 } 1827 1828 // Restore the original sign so that -0.0 is preserved. 1829 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1830 1831 // Determine the largest integer that can be represented exactly. This and 1832 // values larger than it don't have any fractional bits so don't need to 1833 // be converted. 1834 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1835 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1836 APFloat MaxVal = APFloat(FltSem); 1837 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1838 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1839 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1840 1841 // If abs(Src) was larger than MaxVal or nan, keep it. 1842 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1843 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1844 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1845 } 1846 1847 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1848 const RISCVSubtarget &Subtarget) { 1849 MVT VT = Op.getSimpleValueType(); 1850 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1851 1852 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1853 1854 SDLoc DL(Op); 1855 SDValue Mask, VL; 1856 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1857 1858 unsigned Opc = 1859 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1860 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1861 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1862 } 1863 1864 struct VIDSequence { 1865 int64_t StepNumerator; 1866 unsigned StepDenominator; 1867 int64_t Addend; 1868 }; 1869 1870 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1871 // to the (non-zero) step S and start value X. This can be then lowered as the 1872 // RVV sequence (VID * S) + X, for example. 1873 // The step S is represented as an integer numerator divided by a positive 1874 // denominator. Note that the implementation currently only identifies 1875 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1876 // cannot detect 2/3, for example. 1877 // Note that this method will also match potentially unappealing index 1878 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1879 // determine whether this is worth generating code for. 1880 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1881 unsigned NumElts = Op.getNumOperands(); 1882 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1883 if (!Op.getValueType().isInteger()) 1884 return None; 1885 1886 Optional<unsigned> SeqStepDenom; 1887 Optional<int64_t> SeqStepNum, SeqAddend; 1888 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1889 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1890 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1891 // Assume undef elements match the sequence; we just have to be careful 1892 // when interpolating across them. 1893 if (Op.getOperand(Idx).isUndef()) 1894 continue; 1895 // The BUILD_VECTOR must be all constants. 1896 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1897 return None; 1898 1899 uint64_t Val = Op.getConstantOperandVal(Idx) & 1900 maskTrailingOnes<uint64_t>(EltSizeInBits); 1901 1902 if (PrevElt) { 1903 // Calculate the step since the last non-undef element, and ensure 1904 // it's consistent across the entire sequence. 1905 unsigned IdxDiff = Idx - PrevElt->second; 1906 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1907 1908 // A zero-value value difference means that we're somewhere in the middle 1909 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1910 // step change before evaluating the sequence. 1911 if (ValDiff != 0) { 1912 int64_t Remainder = ValDiff % IdxDiff; 1913 // Normalize the step if it's greater than 1. 1914 if (Remainder != ValDiff) { 1915 // The difference must cleanly divide the element span. 1916 if (Remainder != 0) 1917 return None; 1918 ValDiff /= IdxDiff; 1919 IdxDiff = 1; 1920 } 1921 1922 if (!SeqStepNum) 1923 SeqStepNum = ValDiff; 1924 else if (ValDiff != SeqStepNum) 1925 return None; 1926 1927 if (!SeqStepDenom) 1928 SeqStepDenom = IdxDiff; 1929 else if (IdxDiff != *SeqStepDenom) 1930 return None; 1931 } 1932 } 1933 1934 // Record and/or check any addend. 1935 if (SeqStepNum && SeqStepDenom) { 1936 uint64_t ExpectedVal = 1937 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1938 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1939 if (!SeqAddend) 1940 SeqAddend = Addend; 1941 else if (SeqAddend != Addend) 1942 return None; 1943 } 1944 1945 // Record this non-undef element for later. 1946 if (!PrevElt || PrevElt->first != Val) 1947 PrevElt = std::make_pair(Val, Idx); 1948 } 1949 // We need to have logged both a step and an addend for this to count as 1950 // a legal index sequence. 1951 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1952 return None; 1953 1954 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1955 } 1956 1957 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1958 const RISCVSubtarget &Subtarget) { 1959 MVT VT = Op.getSimpleValueType(); 1960 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1961 1962 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1963 1964 SDLoc DL(Op); 1965 SDValue Mask, VL; 1966 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1967 1968 MVT XLenVT = Subtarget.getXLenVT(); 1969 unsigned NumElts = Op.getNumOperands(); 1970 1971 if (VT.getVectorElementType() == MVT::i1) { 1972 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1973 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1974 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1975 } 1976 1977 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1978 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1979 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1980 } 1981 1982 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1983 // scalar integer chunks whose bit-width depends on the number of mask 1984 // bits and XLEN. 1985 // First, determine the most appropriate scalar integer type to use. This 1986 // is at most XLenVT, but may be shrunk to a smaller vector element type 1987 // according to the size of the final vector - use i8 chunks rather than 1988 // XLenVT if we're producing a v8i1. This results in more consistent 1989 // codegen across RV32 and RV64. 1990 unsigned NumViaIntegerBits = 1991 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1992 NumViaIntegerBits = std::min(NumViaIntegerBits, 1993 Subtarget.getMaxELENForFixedLengthVectors()); 1994 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1995 // If we have to use more than one INSERT_VECTOR_ELT then this 1996 // optimization is likely to increase code size; avoid peforming it in 1997 // such a case. We can use a load from a constant pool in this case. 1998 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1999 return SDValue(); 2000 // Now we can create our integer vector type. Note that it may be larger 2001 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2002 MVT IntegerViaVecVT = 2003 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2004 divideCeil(NumElts, NumViaIntegerBits)); 2005 2006 uint64_t Bits = 0; 2007 unsigned BitPos = 0, IntegerEltIdx = 0; 2008 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2009 2010 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2011 // Once we accumulate enough bits to fill our scalar type, insert into 2012 // our vector and clear our accumulated data. 2013 if (I != 0 && I % NumViaIntegerBits == 0) { 2014 if (NumViaIntegerBits <= 32) 2015 Bits = SignExtend64(Bits, 32); 2016 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2017 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2018 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2019 Bits = 0; 2020 BitPos = 0; 2021 IntegerEltIdx++; 2022 } 2023 SDValue V = Op.getOperand(I); 2024 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2025 Bits |= ((uint64_t)BitValue << BitPos); 2026 } 2027 2028 // Insert the (remaining) scalar value into position in our integer 2029 // vector type. 2030 if (NumViaIntegerBits <= 32) 2031 Bits = SignExtend64(Bits, 32); 2032 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2033 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2034 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2035 2036 if (NumElts < NumViaIntegerBits) { 2037 // If we're producing a smaller vector than our minimum legal integer 2038 // type, bitcast to the equivalent (known-legal) mask type, and extract 2039 // our final mask. 2040 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2041 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2042 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2043 DAG.getConstant(0, DL, XLenVT)); 2044 } else { 2045 // Else we must have produced an integer type with the same size as the 2046 // mask type; bitcast for the final result. 2047 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2048 Vec = DAG.getBitcast(VT, Vec); 2049 } 2050 2051 return Vec; 2052 } 2053 2054 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2055 // vector type, we have a legal equivalently-sized i8 type, so we can use 2056 // that. 2057 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2058 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2059 2060 SDValue WideVec; 2061 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2062 // For a splat, perform a scalar truncate before creating the wider 2063 // vector. 2064 assert(Splat.getValueType() == XLenVT && 2065 "Unexpected type for i1 splat value"); 2066 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2067 DAG.getConstant(1, DL, XLenVT)); 2068 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2069 } else { 2070 SmallVector<SDValue, 8> Ops(Op->op_values()); 2071 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2072 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2073 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2074 } 2075 2076 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2077 } 2078 2079 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2080 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2081 : RISCVISD::VMV_V_X_VL; 2082 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 2083 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2084 } 2085 2086 // Try and match index sequences, which we can lower to the vid instruction 2087 // with optional modifications. An all-undef vector is matched by 2088 // getSplatValue, above. 2089 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2090 int64_t StepNumerator = SimpleVID->StepNumerator; 2091 unsigned StepDenominator = SimpleVID->StepDenominator; 2092 int64_t Addend = SimpleVID->Addend; 2093 2094 assert(StepNumerator != 0 && "Invalid step"); 2095 bool Negate = false; 2096 int64_t SplatStepVal = StepNumerator; 2097 unsigned StepOpcode = ISD::MUL; 2098 if (StepNumerator != 1) { 2099 if (isPowerOf2_64(std::abs(StepNumerator))) { 2100 Negate = StepNumerator < 0; 2101 StepOpcode = ISD::SHL; 2102 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2103 } 2104 } 2105 2106 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2107 // threshold since it's the immediate value many RVV instructions accept. 2108 // There is no vmul.vi instruction so ensure multiply constant can fit in 2109 // a single addi instruction. 2110 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2111 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2112 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2113 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2114 // Convert right out of the scalable type so we can use standard ISD 2115 // nodes for the rest of the computation. If we used scalable types with 2116 // these, we'd lose the fixed-length vector info and generate worse 2117 // vsetvli code. 2118 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2119 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2120 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2121 SDValue SplatStep = DAG.getSplatVector( 2122 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2123 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2124 } 2125 if (StepDenominator != 1) { 2126 SDValue SplatStep = DAG.getSplatVector( 2127 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2128 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2129 } 2130 if (Addend != 0 || Negate) { 2131 SDValue SplatAddend = 2132 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2133 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2134 } 2135 return VID; 2136 } 2137 } 2138 2139 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2140 // when re-interpreted as a vector with a larger element type. For example, 2141 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2142 // could be instead splat as 2143 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2144 // TODO: This optimization could also work on non-constant splats, but it 2145 // would require bit-manipulation instructions to construct the splat value. 2146 SmallVector<SDValue> Sequence; 2147 unsigned EltBitSize = VT.getScalarSizeInBits(); 2148 const auto *BV = cast<BuildVectorSDNode>(Op); 2149 if (VT.isInteger() && EltBitSize < 64 && 2150 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2151 BV->getRepeatedSequence(Sequence) && 2152 (Sequence.size() * EltBitSize) <= 64) { 2153 unsigned SeqLen = Sequence.size(); 2154 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2155 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2156 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2157 ViaIntVT == MVT::i64) && 2158 "Unexpected sequence type"); 2159 2160 unsigned EltIdx = 0; 2161 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2162 uint64_t SplatValue = 0; 2163 // Construct the amalgamated value which can be splatted as this larger 2164 // vector type. 2165 for (const auto &SeqV : Sequence) { 2166 if (!SeqV.isUndef()) 2167 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2168 << (EltIdx * EltBitSize)); 2169 EltIdx++; 2170 } 2171 2172 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2173 // achieve better constant materializion. 2174 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2175 SplatValue = SignExtend64(SplatValue, 32); 2176 2177 // Since we can't introduce illegal i64 types at this stage, we can only 2178 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2179 // way we can use RVV instructions to splat. 2180 assert((ViaIntVT.bitsLE(XLenVT) || 2181 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2182 "Unexpected bitcast sequence"); 2183 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2184 SDValue ViaVL = 2185 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2186 MVT ViaContainerVT = 2187 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2188 SDValue Splat = 2189 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2190 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2191 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2192 return DAG.getBitcast(VT, Splat); 2193 } 2194 } 2195 2196 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2197 // which constitute a large proportion of the elements. In such cases we can 2198 // splat a vector with the dominant element and make up the shortfall with 2199 // INSERT_VECTOR_ELTs. 2200 // Note that this includes vectors of 2 elements by association. The 2201 // upper-most element is the "dominant" one, allowing us to use a splat to 2202 // "insert" the upper element, and an insert of the lower element at position 2203 // 0, which improves codegen. 2204 SDValue DominantValue; 2205 unsigned MostCommonCount = 0; 2206 DenseMap<SDValue, unsigned> ValueCounts; 2207 unsigned NumUndefElts = 2208 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2209 2210 // Track the number of scalar loads we know we'd be inserting, estimated as 2211 // any non-zero floating-point constant. Other kinds of element are either 2212 // already in registers or are materialized on demand. The threshold at which 2213 // a vector load is more desirable than several scalar materializion and 2214 // vector-insertion instructions is not known. 2215 unsigned NumScalarLoads = 0; 2216 2217 for (SDValue V : Op->op_values()) { 2218 if (V.isUndef()) 2219 continue; 2220 2221 ValueCounts.insert(std::make_pair(V, 0)); 2222 unsigned &Count = ValueCounts[V]; 2223 2224 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2225 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2226 2227 // Is this value dominant? In case of a tie, prefer the highest element as 2228 // it's cheaper to insert near the beginning of a vector than it is at the 2229 // end. 2230 if (++Count >= MostCommonCount) { 2231 DominantValue = V; 2232 MostCommonCount = Count; 2233 } 2234 } 2235 2236 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2237 unsigned NumDefElts = NumElts - NumUndefElts; 2238 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2239 2240 // Don't perform this optimization when optimizing for size, since 2241 // materializing elements and inserting them tends to cause code bloat. 2242 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2243 ((MostCommonCount > DominantValueCountThreshold) || 2244 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2245 // Start by splatting the most common element. 2246 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2247 2248 DenseSet<SDValue> Processed{DominantValue}; 2249 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2250 for (const auto &OpIdx : enumerate(Op->ops())) { 2251 const SDValue &V = OpIdx.value(); 2252 if (V.isUndef() || !Processed.insert(V).second) 2253 continue; 2254 if (ValueCounts[V] == 1) { 2255 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2256 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2257 } else { 2258 // Blend in all instances of this value using a VSELECT, using a 2259 // mask where each bit signals whether that element is the one 2260 // we're after. 2261 SmallVector<SDValue> Ops; 2262 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2263 return DAG.getConstant(V == V1, DL, XLenVT); 2264 }); 2265 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2266 DAG.getBuildVector(SelMaskTy, DL, Ops), 2267 DAG.getSplatBuildVector(VT, DL, V), Vec); 2268 } 2269 } 2270 2271 return Vec; 2272 } 2273 2274 return SDValue(); 2275 } 2276 2277 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 2278 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 2279 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2280 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2281 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2282 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2283 // node in order to try and match RVV vector/scalar instructions. 2284 if ((LoC >> 31) == HiC) 2285 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2286 2287 // If vl is equal to VLMax and Hi constant is equal to Lo, we could use 2288 // vmv.v.x whose EEW = 32 to lower it. 2289 auto *Const = dyn_cast<ConstantSDNode>(VL); 2290 if (LoC == HiC && Const && Const->getSExtValue() == RISCV::VLMaxSentinel) { 2291 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2292 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2293 // access the subtarget here now. 2294 auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT, Lo, VL); 2295 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2296 } 2297 } 2298 2299 // Fall back to a stack store and stride x0 vector load. 2300 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2301 } 2302 2303 // Called by type legalization to handle splat of i64 on RV32. 2304 // FIXME: We can optimize this when the type has sign or zero bits in one 2305 // of the halves. 2306 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2307 SDValue VL, SelectionDAG &DAG) { 2308 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2309 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2310 DAG.getConstant(0, DL, MVT::i32)); 2311 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2312 DAG.getConstant(1, DL, MVT::i32)); 2313 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2314 } 2315 2316 // This function lowers a splat of a scalar operand Splat with the vector 2317 // length VL. It ensures the final sequence is type legal, which is useful when 2318 // lowering a splat after type legalization. 2319 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2320 SelectionDAG &DAG, 2321 const RISCVSubtarget &Subtarget) { 2322 if (VT.isFloatingPoint()) { 2323 // If VL is 1, we could use vfmv.s.f. 2324 if (isOneConstant(VL)) 2325 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT), 2326 Scalar, VL); 2327 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2328 } 2329 2330 MVT XLenVT = Subtarget.getXLenVT(); 2331 2332 // Simplest case is that the operand needs to be promoted to XLenVT. 2333 if (Scalar.getValueType().bitsLE(XLenVT)) { 2334 // If the operand is a constant, sign extend to increase our chances 2335 // of being able to use a .vi instruction. ANY_EXTEND would become a 2336 // a zero extend and the simm5 check in isel would fail. 2337 // FIXME: Should we ignore the upper bits in isel instead? 2338 unsigned ExtOpc = 2339 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2340 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2341 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2342 // If VL is 1 and the scalar value won't benefit from immediate, we could 2343 // use vmv.s.x. 2344 if (isOneConstant(VL) && 2345 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2346 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar, 2347 VL); 2348 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2349 } 2350 2351 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2352 "Unexpected scalar for splat lowering!"); 2353 2354 if (isOneConstant(VL) && isNullConstant(Scalar)) 2355 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), 2356 DAG.getConstant(0, DL, XLenVT), VL); 2357 2358 // Otherwise use the more complicated splatting algorithm. 2359 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2360 } 2361 2362 // Is the mask a slidedown that shifts in undefs. 2363 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) { 2364 int Size = Mask.size(); 2365 2366 // Elements shifted in should be undef. 2367 auto CheckUndefs = [&](int Shift) { 2368 for (int i = Size - Shift; i != Size; ++i) 2369 if (Mask[i] >= 0) 2370 return false; 2371 return true; 2372 }; 2373 2374 // Elements should be shifted or undef. 2375 auto MatchShift = [&](int Shift) { 2376 for (int i = 0; i != Size - Shift; ++i) 2377 if (Mask[i] >= 0 && Mask[i] != Shift + i) 2378 return false; 2379 return true; 2380 }; 2381 2382 // Try all possible shifts. 2383 for (int Shift = 1; Shift != Size; ++Shift) 2384 if (CheckUndefs(Shift) && MatchShift(Shift)) 2385 return Shift; 2386 2387 // No match. 2388 return -1; 2389 } 2390 2391 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2392 const RISCVSubtarget &Subtarget) { 2393 // We need to be able to widen elements to the next larger integer type. 2394 if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors()) 2395 return false; 2396 2397 int Size = Mask.size(); 2398 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2399 2400 int Srcs[] = {-1, -1}; 2401 for (int i = 0; i != Size; ++i) { 2402 // Ignore undef elements. 2403 if (Mask[i] < 0) 2404 continue; 2405 2406 // Is this an even or odd element. 2407 int Pol = i % 2; 2408 2409 // Ensure we consistently use the same source for this element polarity. 2410 int Src = Mask[i] / Size; 2411 if (Srcs[Pol] < 0) 2412 Srcs[Pol] = Src; 2413 if (Srcs[Pol] != Src) 2414 return false; 2415 2416 // Make sure the element within the source is appropriate for this element 2417 // in the destination. 2418 int Elt = Mask[i] % Size; 2419 if (Elt != i / 2) 2420 return false; 2421 } 2422 2423 // We need to find a source for each polarity and they can't be the same. 2424 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2425 return false; 2426 2427 // Swap the sources if the second source was in the even polarity. 2428 SwapSources = Srcs[0] > Srcs[1]; 2429 2430 return true; 2431 } 2432 2433 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2434 const RISCVSubtarget &Subtarget) { 2435 SDValue V1 = Op.getOperand(0); 2436 SDValue V2 = Op.getOperand(1); 2437 SDLoc DL(Op); 2438 MVT XLenVT = Subtarget.getXLenVT(); 2439 MVT VT = Op.getSimpleValueType(); 2440 unsigned NumElts = VT.getVectorNumElements(); 2441 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2442 2443 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2444 2445 SDValue TrueMask, VL; 2446 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2447 2448 if (SVN->isSplat()) { 2449 const int Lane = SVN->getSplatIndex(); 2450 if (Lane >= 0) { 2451 MVT SVT = VT.getVectorElementType(); 2452 2453 // Turn splatted vector load into a strided load with an X0 stride. 2454 SDValue V = V1; 2455 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2456 // with undef. 2457 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2458 int Offset = Lane; 2459 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2460 int OpElements = 2461 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2462 V = V.getOperand(Offset / OpElements); 2463 Offset %= OpElements; 2464 } 2465 2466 // We need to ensure the load isn't atomic or volatile. 2467 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2468 auto *Ld = cast<LoadSDNode>(V); 2469 Offset *= SVT.getStoreSize(); 2470 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2471 TypeSize::Fixed(Offset), DL); 2472 2473 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2474 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2475 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2476 SDValue IntID = 2477 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2478 SDValue Ops[] = {Ld->getChain(), 2479 IntID, 2480 DAG.getUNDEF(ContainerVT), 2481 NewAddr, 2482 DAG.getRegister(RISCV::X0, XLenVT), 2483 VL}; 2484 SDValue NewLoad = DAG.getMemIntrinsicNode( 2485 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2486 DAG.getMachineFunction().getMachineMemOperand( 2487 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2488 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2489 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2490 } 2491 2492 // Otherwise use a scalar load and splat. This will give the best 2493 // opportunity to fold a splat into the operation. ISel can turn it into 2494 // the x0 strided load if we aren't able to fold away the select. 2495 if (SVT.isFloatingPoint()) 2496 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2497 Ld->getPointerInfo().getWithOffset(Offset), 2498 Ld->getOriginalAlign(), 2499 Ld->getMemOperand()->getFlags()); 2500 else 2501 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2502 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2503 Ld->getOriginalAlign(), 2504 Ld->getMemOperand()->getFlags()); 2505 DAG.makeEquivalentMemoryOrdering(Ld, V); 2506 2507 unsigned Opc = 2508 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2509 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2510 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2511 } 2512 2513 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2514 assert(Lane < (int)NumElts && "Unexpected lane!"); 2515 SDValue Gather = 2516 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2517 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2518 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2519 } 2520 } 2521 2522 ArrayRef<int> Mask = SVN->getMask(); 2523 2524 // Try to match as a slidedown. 2525 int SlideAmt = matchShuffleAsSlideDown(Mask); 2526 if (SlideAmt >= 0) { 2527 // TODO: Should we reduce the VL to account for the upper undef elements? 2528 // Requires additional vsetvlis, but might be faster to execute. 2529 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2530 SDValue SlideDown = 2531 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 2532 DAG.getUNDEF(ContainerVT), V1, 2533 DAG.getConstant(SlideAmt, DL, XLenVT), 2534 TrueMask, VL); 2535 return convertFromScalableVector(VT, SlideDown, DAG, Subtarget); 2536 } 2537 2538 // Detect an interleave shuffle and lower to 2539 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2540 bool SwapSources; 2541 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2542 // Swap sources if needed. 2543 if (SwapSources) 2544 std::swap(V1, V2); 2545 2546 // Extract the lower half of the vectors. 2547 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2548 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2549 DAG.getConstant(0, DL, XLenVT)); 2550 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2551 DAG.getConstant(0, DL, XLenVT)); 2552 2553 // Double the element width and halve the number of elements in an int type. 2554 unsigned EltBits = VT.getScalarSizeInBits(); 2555 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2556 MVT WideIntVT = 2557 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2558 // Convert this to a scalable vector. We need to base this on the 2559 // destination size to ensure there's always a type with a smaller LMUL. 2560 MVT WideIntContainerVT = 2561 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2562 2563 // Convert sources to scalable vectors with the same element count as the 2564 // larger type. 2565 MVT HalfContainerVT = MVT::getVectorVT( 2566 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2567 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2568 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2569 2570 // Cast sources to integer. 2571 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2572 MVT IntHalfVT = 2573 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2574 V1 = DAG.getBitcast(IntHalfVT, V1); 2575 V2 = DAG.getBitcast(IntHalfVT, V2); 2576 2577 // Freeze V2 since we use it twice and we need to be sure that the add and 2578 // multiply see the same value. 2579 V2 = DAG.getNode(ISD::FREEZE, DL, IntHalfVT, V2); 2580 2581 // Recreate TrueMask using the widened type's element count. 2582 MVT MaskVT = 2583 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2584 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2585 2586 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2587 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2588 V2, TrueMask, VL); 2589 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2590 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2591 DAG.getAllOnesConstant(DL, XLenVT)); 2592 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2593 V2, Multiplier, TrueMask, VL); 2594 // Add the new copies to our previous addition giving us 2^eltbits copies of 2595 // V2. This is equivalent to shifting V2 left by eltbits. This should 2596 // combine with the vwmulu.vv above to form vwmaccu.vv. 2597 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2598 TrueMask, VL); 2599 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2600 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2601 // vector VT. 2602 ContainerVT = 2603 MVT::getVectorVT(VT.getVectorElementType(), 2604 WideIntContainerVT.getVectorElementCount() * 2); 2605 Add = DAG.getBitcast(ContainerVT, Add); 2606 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2607 } 2608 2609 // Detect shuffles which can be re-expressed as vector selects; these are 2610 // shuffles in which each element in the destination is taken from an element 2611 // at the corresponding index in either source vectors. 2612 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2613 int MaskIndex = MaskIdx.value(); 2614 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2615 }); 2616 2617 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2618 2619 SmallVector<SDValue> MaskVals; 2620 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2621 // merged with a second vrgather. 2622 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2623 2624 // By default we preserve the original operand order, and use a mask to 2625 // select LHS as true and RHS as false. However, since RVV vector selects may 2626 // feature splats but only on the LHS, we may choose to invert our mask and 2627 // instead select between RHS and LHS. 2628 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2629 bool InvertMask = IsSelect == SwapOps; 2630 2631 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2632 // half. 2633 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2634 2635 // Now construct the mask that will be used by the vselect or blended 2636 // vrgather operation. For vrgathers, construct the appropriate indices into 2637 // each vector. 2638 for (int MaskIndex : Mask) { 2639 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2640 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2641 if (!IsSelect) { 2642 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2643 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2644 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2645 : DAG.getUNDEF(XLenVT)); 2646 GatherIndicesRHS.push_back( 2647 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2648 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2649 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2650 ++LHSIndexCounts[MaskIndex]; 2651 if (!IsLHSOrUndefIndex) 2652 ++RHSIndexCounts[MaskIndex - NumElts]; 2653 } 2654 } 2655 2656 if (SwapOps) { 2657 std::swap(V1, V2); 2658 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2659 } 2660 2661 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2662 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2663 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2664 2665 if (IsSelect) 2666 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2667 2668 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2669 // On such a large vector we're unable to use i8 as the index type. 2670 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2671 // may involve vector splitting if we're already at LMUL=8, or our 2672 // user-supplied maximum fixed-length LMUL. 2673 return SDValue(); 2674 } 2675 2676 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2677 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2678 MVT IndexVT = VT.changeTypeToInteger(); 2679 // Since we can't introduce illegal index types at this stage, use i16 and 2680 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2681 // than XLenVT. 2682 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2683 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2684 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2685 } 2686 2687 MVT IndexContainerVT = 2688 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2689 2690 SDValue Gather; 2691 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2692 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2693 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2694 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2695 } else { 2696 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2697 // If only one index is used, we can use a "splat" vrgather. 2698 // TODO: We can splat the most-common index and fix-up any stragglers, if 2699 // that's beneficial. 2700 if (LHSIndexCounts.size() == 1) { 2701 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2702 Gather = 2703 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2704 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2705 } else { 2706 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2707 LHSIndices = 2708 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2709 2710 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2711 TrueMask, VL); 2712 } 2713 } 2714 2715 // If a second vector operand is used by this shuffle, blend it in with an 2716 // additional vrgather. 2717 if (!V2.isUndef()) { 2718 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2719 // If only one index is used, we can use a "splat" vrgather. 2720 // TODO: We can splat the most-common index and fix-up any stragglers, if 2721 // that's beneficial. 2722 if (RHSIndexCounts.size() == 1) { 2723 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2724 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2725 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2726 } else { 2727 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2728 RHSIndices = 2729 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2730 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2731 VL); 2732 } 2733 2734 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2735 SelectMask = 2736 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2737 2738 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2739 Gather, VL); 2740 } 2741 2742 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2743 } 2744 2745 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2746 SDLoc DL, SelectionDAG &DAG, 2747 const RISCVSubtarget &Subtarget) { 2748 if (VT.isScalableVector()) 2749 return DAG.getFPExtendOrRound(Op, DL, VT); 2750 assert(VT.isFixedLengthVector() && 2751 "Unexpected value type for RVV FP extend/round lowering"); 2752 SDValue Mask, VL; 2753 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2754 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2755 ? RISCVISD::FP_EXTEND_VL 2756 : RISCVISD::FP_ROUND_VL; 2757 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2758 } 2759 2760 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2761 // the exponent. 2762 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2763 MVT VT = Op.getSimpleValueType(); 2764 unsigned EltSize = VT.getScalarSizeInBits(); 2765 SDValue Src = Op.getOperand(0); 2766 SDLoc DL(Op); 2767 2768 // We need a FP type that can represent the value. 2769 // TODO: Use f16 for i8 when possible? 2770 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2771 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2772 2773 // Legal types should have been checked in the RISCVTargetLowering 2774 // constructor. 2775 // TODO: Splitting may make sense in some cases. 2776 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2777 "Expected legal float type!"); 2778 2779 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2780 // The trailing zero count is equal to log2 of this single bit value. 2781 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2782 SDValue Neg = 2783 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2784 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2785 } 2786 2787 // We have a legal FP type, convert to it. 2788 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2789 // Bitcast to integer and shift the exponent to the LSB. 2790 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2791 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2792 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2793 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2794 DAG.getConstant(ShiftAmt, DL, IntVT)); 2795 // Truncate back to original type to allow vnsrl. 2796 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2797 // The exponent contains log2 of the value in biased form. 2798 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2799 2800 // For trailing zeros, we just need to subtract the bias. 2801 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2802 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2803 DAG.getConstant(ExponentBias, DL, VT)); 2804 2805 // For leading zeros, we need to remove the bias and convert from log2 to 2806 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2807 unsigned Adjust = ExponentBias + (EltSize - 1); 2808 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2809 } 2810 2811 // While RVV has alignment restrictions, we should always be able to load as a 2812 // legal equivalently-sized byte-typed vector instead. This method is 2813 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2814 // the load is already correctly-aligned, it returns SDValue(). 2815 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2816 SelectionDAG &DAG) const { 2817 auto *Load = cast<LoadSDNode>(Op); 2818 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2819 2820 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2821 Load->getMemoryVT(), 2822 *Load->getMemOperand())) 2823 return SDValue(); 2824 2825 SDLoc DL(Op); 2826 MVT VT = Op.getSimpleValueType(); 2827 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2828 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2829 "Unexpected unaligned RVV load type"); 2830 MVT NewVT = 2831 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2832 assert(NewVT.isValid() && 2833 "Expecting equally-sized RVV vector types to be legal"); 2834 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2835 Load->getPointerInfo(), Load->getOriginalAlign(), 2836 Load->getMemOperand()->getFlags()); 2837 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2838 } 2839 2840 // While RVV has alignment restrictions, we should always be able to store as a 2841 // legal equivalently-sized byte-typed vector instead. This method is 2842 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2843 // returns SDValue() if the store is already correctly aligned. 2844 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2845 SelectionDAG &DAG) const { 2846 auto *Store = cast<StoreSDNode>(Op); 2847 assert(Store && Store->getValue().getValueType().isVector() && 2848 "Expected vector store"); 2849 2850 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2851 Store->getMemoryVT(), 2852 *Store->getMemOperand())) 2853 return SDValue(); 2854 2855 SDLoc DL(Op); 2856 SDValue StoredVal = Store->getValue(); 2857 MVT VT = StoredVal.getSimpleValueType(); 2858 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2859 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2860 "Unexpected unaligned RVV store type"); 2861 MVT NewVT = 2862 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2863 assert(NewVT.isValid() && 2864 "Expecting equally-sized RVV vector types to be legal"); 2865 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2866 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2867 Store->getPointerInfo(), Store->getOriginalAlign(), 2868 Store->getMemOperand()->getFlags()); 2869 } 2870 2871 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2872 SelectionDAG &DAG) const { 2873 switch (Op.getOpcode()) { 2874 default: 2875 report_fatal_error("unimplemented operand"); 2876 case ISD::GlobalAddress: 2877 return lowerGlobalAddress(Op, DAG); 2878 case ISD::BlockAddress: 2879 return lowerBlockAddress(Op, DAG); 2880 case ISD::ConstantPool: 2881 return lowerConstantPool(Op, DAG); 2882 case ISD::JumpTable: 2883 return lowerJumpTable(Op, DAG); 2884 case ISD::GlobalTLSAddress: 2885 return lowerGlobalTLSAddress(Op, DAG); 2886 case ISD::SELECT: 2887 return lowerSELECT(Op, DAG); 2888 case ISD::BRCOND: 2889 return lowerBRCOND(Op, DAG); 2890 case ISD::VASTART: 2891 return lowerVASTART(Op, DAG); 2892 case ISD::FRAMEADDR: 2893 return lowerFRAMEADDR(Op, DAG); 2894 case ISD::RETURNADDR: 2895 return lowerRETURNADDR(Op, DAG); 2896 case ISD::SHL_PARTS: 2897 return lowerShiftLeftParts(Op, DAG); 2898 case ISD::SRA_PARTS: 2899 return lowerShiftRightParts(Op, DAG, true); 2900 case ISD::SRL_PARTS: 2901 return lowerShiftRightParts(Op, DAG, false); 2902 case ISD::BITCAST: { 2903 SDLoc DL(Op); 2904 EVT VT = Op.getValueType(); 2905 SDValue Op0 = Op.getOperand(0); 2906 EVT Op0VT = Op0.getValueType(); 2907 MVT XLenVT = Subtarget.getXLenVT(); 2908 if (VT.isFixedLengthVector()) { 2909 // We can handle fixed length vector bitcasts with a simple replacement 2910 // in isel. 2911 if (Op0VT.isFixedLengthVector()) 2912 return Op; 2913 // When bitcasting from scalar to fixed-length vector, insert the scalar 2914 // into a one-element vector of the result type, and perform a vector 2915 // bitcast. 2916 if (!Op0VT.isVector()) { 2917 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2918 if (!isTypeLegal(BVT)) 2919 return SDValue(); 2920 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2921 DAG.getUNDEF(BVT), Op0, 2922 DAG.getConstant(0, DL, XLenVT))); 2923 } 2924 return SDValue(); 2925 } 2926 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2927 // thus: bitcast the vector to a one-element vector type whose element type 2928 // is the same as the result type, and extract the first element. 2929 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2930 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2931 if (!isTypeLegal(BVT)) 2932 return SDValue(); 2933 SDValue BVec = DAG.getBitcast(BVT, Op0); 2934 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2935 DAG.getConstant(0, DL, XLenVT)); 2936 } 2937 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2938 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2939 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2940 return FPConv; 2941 } 2942 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2943 Subtarget.hasStdExtF()) { 2944 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2945 SDValue FPConv = 2946 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2947 return FPConv; 2948 } 2949 return SDValue(); 2950 } 2951 case ISD::INTRINSIC_WO_CHAIN: 2952 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2953 case ISD::INTRINSIC_W_CHAIN: 2954 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2955 case ISD::INTRINSIC_VOID: 2956 return LowerINTRINSIC_VOID(Op, DAG); 2957 case ISD::BSWAP: 2958 case ISD::BITREVERSE: { 2959 MVT VT = Op.getSimpleValueType(); 2960 SDLoc DL(Op); 2961 if (Subtarget.hasStdExtZbp()) { 2962 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2963 // Start with the maximum immediate value which is the bitwidth - 1. 2964 unsigned Imm = VT.getSizeInBits() - 1; 2965 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2966 if (Op.getOpcode() == ISD::BSWAP) 2967 Imm &= ~0x7U; 2968 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2969 DAG.getConstant(Imm, DL, VT)); 2970 } 2971 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 2972 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 2973 // Expand bitreverse to a bswap(rev8) followed by brev8. 2974 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 2975 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 2976 // as brev8 by an isel pattern. 2977 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 2978 DAG.getConstant(7, DL, VT)); 2979 } 2980 case ISD::FSHL: 2981 case ISD::FSHR: { 2982 MVT VT = Op.getSimpleValueType(); 2983 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2984 SDLoc DL(Op); 2985 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2986 // use log(XLen) bits. Mask the shift amount accordingly to prevent 2987 // accidentally setting the extra bit. 2988 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2989 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2990 DAG.getConstant(ShAmtWidth, DL, VT)); 2991 // fshl and fshr concatenate their operands in the same order. fsr and fsl 2992 // instruction use different orders. fshl will return its first operand for 2993 // shift of zero, fshr will return its second operand. fsl and fsr both 2994 // return rs1 so the ISD nodes need to have different operand orders. 2995 // Shift amount is in rs2. 2996 SDValue Op0 = Op.getOperand(0); 2997 SDValue Op1 = Op.getOperand(1); 2998 unsigned Opc = RISCVISD::FSL; 2999 if (Op.getOpcode() == ISD::FSHR) { 3000 std::swap(Op0, Op1); 3001 Opc = RISCVISD::FSR; 3002 } 3003 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3004 } 3005 case ISD::TRUNCATE: { 3006 SDLoc DL(Op); 3007 MVT VT = Op.getSimpleValueType(); 3008 // Only custom-lower vector truncates 3009 if (!VT.isVector()) 3010 return Op; 3011 3012 // Truncates to mask types are handled differently 3013 if (VT.getVectorElementType() == MVT::i1) 3014 return lowerVectorMaskTrunc(Op, DAG); 3015 3016 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3017 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3018 // truncate by one power of two at a time. 3019 MVT DstEltVT = VT.getVectorElementType(); 3020 3021 SDValue Src = Op.getOperand(0); 3022 MVT SrcVT = Src.getSimpleValueType(); 3023 MVT SrcEltVT = SrcVT.getVectorElementType(); 3024 3025 assert(DstEltVT.bitsLT(SrcEltVT) && 3026 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3027 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3028 "Unexpected vector truncate lowering"); 3029 3030 MVT ContainerVT = SrcVT; 3031 if (SrcVT.isFixedLengthVector()) { 3032 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3033 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3034 } 3035 3036 SDValue Result = Src; 3037 SDValue Mask, VL; 3038 std::tie(Mask, VL) = 3039 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3040 LLVMContext &Context = *DAG.getContext(); 3041 const ElementCount Count = ContainerVT.getVectorElementCount(); 3042 do { 3043 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3044 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3045 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3046 Mask, VL); 3047 } while (SrcEltVT != DstEltVT); 3048 3049 if (SrcVT.isFixedLengthVector()) 3050 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3051 3052 return Result; 3053 } 3054 case ISD::ANY_EXTEND: 3055 case ISD::ZERO_EXTEND: 3056 if (Op.getOperand(0).getValueType().isVector() && 3057 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3058 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3059 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3060 case ISD::SIGN_EXTEND: 3061 if (Op.getOperand(0).getValueType().isVector() && 3062 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3063 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3064 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3065 case ISD::SPLAT_VECTOR_PARTS: 3066 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3067 case ISD::INSERT_VECTOR_ELT: 3068 return lowerINSERT_VECTOR_ELT(Op, DAG); 3069 case ISD::EXTRACT_VECTOR_ELT: 3070 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3071 case ISD::VSCALE: { 3072 MVT VT = Op.getSimpleValueType(); 3073 SDLoc DL(Op); 3074 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3075 // We define our scalable vector types for lmul=1 to use a 64 bit known 3076 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3077 // vscale as VLENB / 8. 3078 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3079 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3080 // We assume VLENB is a multiple of 8. We manually choose the best shift 3081 // here because SimplifyDemandedBits isn't always able to simplify it. 3082 uint64_t Val = Op.getConstantOperandVal(0); 3083 if (isPowerOf2_64(Val)) { 3084 uint64_t Log2 = Log2_64(Val); 3085 if (Log2 < 3) 3086 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3087 DAG.getConstant(3 - Log2, DL, VT)); 3088 if (Log2 > 3) 3089 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3090 DAG.getConstant(Log2 - 3, DL, VT)); 3091 return VLENB; 3092 } 3093 // If the multiplier is a multiple of 8, scale it down to avoid needing 3094 // to shift the VLENB value. 3095 if ((Val % 8) == 0) 3096 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3097 DAG.getConstant(Val / 8, DL, VT)); 3098 } 3099 3100 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3101 DAG.getConstant(3, DL, VT)); 3102 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3103 } 3104 case ISD::FPOWI: { 3105 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3106 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3107 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3108 Op.getOperand(1).getValueType() == MVT::i32) { 3109 SDLoc DL(Op); 3110 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3111 SDValue Powi = 3112 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3113 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3114 DAG.getIntPtrConstant(0, DL)); 3115 } 3116 return SDValue(); 3117 } 3118 case ISD::FP_EXTEND: { 3119 // RVV can only do fp_extend to types double the size as the source. We 3120 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3121 // via f32. 3122 SDLoc DL(Op); 3123 MVT VT = Op.getSimpleValueType(); 3124 SDValue Src = Op.getOperand(0); 3125 MVT SrcVT = Src.getSimpleValueType(); 3126 3127 // Prepare any fixed-length vector operands. 3128 MVT ContainerVT = VT; 3129 if (SrcVT.isFixedLengthVector()) { 3130 ContainerVT = getContainerForFixedLengthVector(VT); 3131 MVT SrcContainerVT = 3132 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3133 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3134 } 3135 3136 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3137 SrcVT.getVectorElementType() != MVT::f16) { 3138 // For scalable vectors, we only need to close the gap between 3139 // vXf16->vXf64. 3140 if (!VT.isFixedLengthVector()) 3141 return Op; 3142 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3143 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3144 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3145 } 3146 3147 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3148 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3149 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3150 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3151 3152 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3153 DL, DAG, Subtarget); 3154 if (VT.isFixedLengthVector()) 3155 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3156 return Extend; 3157 } 3158 case ISD::FP_ROUND: { 3159 // RVV can only do fp_round to types half the size as the source. We 3160 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3161 // conversion instruction. 3162 SDLoc DL(Op); 3163 MVT VT = Op.getSimpleValueType(); 3164 SDValue Src = Op.getOperand(0); 3165 MVT SrcVT = Src.getSimpleValueType(); 3166 3167 // Prepare any fixed-length vector operands. 3168 MVT ContainerVT = VT; 3169 if (VT.isFixedLengthVector()) { 3170 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3171 ContainerVT = 3172 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3173 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3174 } 3175 3176 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3177 SrcVT.getVectorElementType() != MVT::f64) { 3178 // For scalable vectors, we only need to close the gap between 3179 // vXf64<->vXf16. 3180 if (!VT.isFixedLengthVector()) 3181 return Op; 3182 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3183 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3184 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3185 } 3186 3187 SDValue Mask, VL; 3188 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3189 3190 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3191 SDValue IntermediateRound = 3192 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3193 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3194 DL, DAG, Subtarget); 3195 3196 if (VT.isFixedLengthVector()) 3197 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3198 return Round; 3199 } 3200 case ISD::FP_TO_SINT: 3201 case ISD::FP_TO_UINT: 3202 case ISD::SINT_TO_FP: 3203 case ISD::UINT_TO_FP: { 3204 // RVV can only do fp<->int conversions to types half/double the size as 3205 // the source. We custom-lower any conversions that do two hops into 3206 // sequences. 3207 MVT VT = Op.getSimpleValueType(); 3208 if (!VT.isVector()) 3209 return Op; 3210 SDLoc DL(Op); 3211 SDValue Src = Op.getOperand(0); 3212 MVT EltVT = VT.getVectorElementType(); 3213 MVT SrcVT = Src.getSimpleValueType(); 3214 MVT SrcEltVT = SrcVT.getVectorElementType(); 3215 unsigned EltSize = EltVT.getSizeInBits(); 3216 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3217 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3218 "Unexpected vector element types"); 3219 3220 bool IsInt2FP = SrcEltVT.isInteger(); 3221 // Widening conversions 3222 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 3223 if (IsInt2FP) { 3224 // Do a regular integer sign/zero extension then convert to float. 3225 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 3226 VT.getVectorElementCount()); 3227 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3228 ? ISD::ZERO_EXTEND 3229 : ISD::SIGN_EXTEND; 3230 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3231 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3232 } 3233 // FP2Int 3234 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3235 // Do one doubling fp_extend then complete the operation by converting 3236 // to int. 3237 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3238 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3239 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3240 } 3241 3242 // Narrowing conversions 3243 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 3244 if (IsInt2FP) { 3245 // One narrowing int_to_fp, then an fp_round. 3246 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3247 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3248 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3249 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3250 } 3251 // FP2Int 3252 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3253 // representable by the integer, the result is poison. 3254 MVT IVecVT = 3255 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3256 VT.getVectorElementCount()); 3257 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3258 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3259 } 3260 3261 // Scalable vectors can exit here. Patterns will handle equally-sized 3262 // conversions halving/doubling ones. 3263 if (!VT.isFixedLengthVector()) 3264 return Op; 3265 3266 // For fixed-length vectors we lower to a custom "VL" node. 3267 unsigned RVVOpc = 0; 3268 switch (Op.getOpcode()) { 3269 default: 3270 llvm_unreachable("Impossible opcode"); 3271 case ISD::FP_TO_SINT: 3272 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3273 break; 3274 case ISD::FP_TO_UINT: 3275 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3276 break; 3277 case ISD::SINT_TO_FP: 3278 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3279 break; 3280 case ISD::UINT_TO_FP: 3281 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3282 break; 3283 } 3284 3285 MVT ContainerVT, SrcContainerVT; 3286 // Derive the reference container type from the larger vector type. 3287 if (SrcEltSize > EltSize) { 3288 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3289 ContainerVT = 3290 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3291 } else { 3292 ContainerVT = getContainerForFixedLengthVector(VT); 3293 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3294 } 3295 3296 SDValue Mask, VL; 3297 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3298 3299 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3300 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3301 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3302 } 3303 case ISD::FP_TO_SINT_SAT: 3304 case ISD::FP_TO_UINT_SAT: 3305 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3306 case ISD::FTRUNC: 3307 case ISD::FCEIL: 3308 case ISD::FFLOOR: 3309 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3310 case ISD::VECREDUCE_ADD: 3311 case ISD::VECREDUCE_UMAX: 3312 case ISD::VECREDUCE_SMAX: 3313 case ISD::VECREDUCE_UMIN: 3314 case ISD::VECREDUCE_SMIN: 3315 return lowerVECREDUCE(Op, DAG); 3316 case ISD::VECREDUCE_AND: 3317 case ISD::VECREDUCE_OR: 3318 case ISD::VECREDUCE_XOR: 3319 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3320 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3321 return lowerVECREDUCE(Op, DAG); 3322 case ISD::VECREDUCE_FADD: 3323 case ISD::VECREDUCE_SEQ_FADD: 3324 case ISD::VECREDUCE_FMIN: 3325 case ISD::VECREDUCE_FMAX: 3326 return lowerFPVECREDUCE(Op, DAG); 3327 case ISD::VP_REDUCE_ADD: 3328 case ISD::VP_REDUCE_UMAX: 3329 case ISD::VP_REDUCE_SMAX: 3330 case ISD::VP_REDUCE_UMIN: 3331 case ISD::VP_REDUCE_SMIN: 3332 case ISD::VP_REDUCE_FADD: 3333 case ISD::VP_REDUCE_SEQ_FADD: 3334 case ISD::VP_REDUCE_FMIN: 3335 case ISD::VP_REDUCE_FMAX: 3336 return lowerVPREDUCE(Op, DAG); 3337 case ISD::VP_REDUCE_AND: 3338 case ISD::VP_REDUCE_OR: 3339 case ISD::VP_REDUCE_XOR: 3340 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3341 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3342 return lowerVPREDUCE(Op, DAG); 3343 case ISD::INSERT_SUBVECTOR: 3344 return lowerINSERT_SUBVECTOR(Op, DAG); 3345 case ISD::EXTRACT_SUBVECTOR: 3346 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3347 case ISD::STEP_VECTOR: 3348 return lowerSTEP_VECTOR(Op, DAG); 3349 case ISD::VECTOR_REVERSE: 3350 return lowerVECTOR_REVERSE(Op, DAG); 3351 case ISD::BUILD_VECTOR: 3352 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3353 case ISD::SPLAT_VECTOR: 3354 if (Op.getValueType().getVectorElementType() == MVT::i1) 3355 return lowerVectorMaskSplat(Op, DAG); 3356 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3357 case ISD::VECTOR_SHUFFLE: 3358 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3359 case ISD::CONCAT_VECTORS: { 3360 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3361 // better than going through the stack, as the default expansion does. 3362 SDLoc DL(Op); 3363 MVT VT = Op.getSimpleValueType(); 3364 unsigned NumOpElts = 3365 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3366 SDValue Vec = DAG.getUNDEF(VT); 3367 for (const auto &OpIdx : enumerate(Op->ops())) { 3368 SDValue SubVec = OpIdx.value(); 3369 // Don't insert undef subvectors. 3370 if (SubVec.isUndef()) 3371 continue; 3372 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3373 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3374 } 3375 return Vec; 3376 } 3377 case ISD::LOAD: 3378 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3379 return V; 3380 if (Op.getValueType().isFixedLengthVector()) 3381 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3382 return Op; 3383 case ISD::STORE: 3384 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3385 return V; 3386 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3387 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3388 return Op; 3389 case ISD::MLOAD: 3390 case ISD::VP_LOAD: 3391 return lowerMaskedLoad(Op, DAG); 3392 case ISD::MSTORE: 3393 case ISD::VP_STORE: 3394 return lowerMaskedStore(Op, DAG); 3395 case ISD::SETCC: 3396 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3397 case ISD::ADD: 3398 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3399 case ISD::SUB: 3400 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3401 case ISD::MUL: 3402 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3403 case ISD::MULHS: 3404 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3405 case ISD::MULHU: 3406 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3407 case ISD::AND: 3408 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3409 RISCVISD::AND_VL); 3410 case ISD::OR: 3411 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3412 RISCVISD::OR_VL); 3413 case ISD::XOR: 3414 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3415 RISCVISD::XOR_VL); 3416 case ISD::SDIV: 3417 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3418 case ISD::SREM: 3419 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3420 case ISD::UDIV: 3421 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3422 case ISD::UREM: 3423 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3424 case ISD::SHL: 3425 case ISD::SRA: 3426 case ISD::SRL: 3427 if (Op.getSimpleValueType().isFixedLengthVector()) 3428 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3429 // This can be called for an i32 shift amount that needs to be promoted. 3430 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3431 "Unexpected custom legalisation"); 3432 return SDValue(); 3433 case ISD::SADDSAT: 3434 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3435 case ISD::UADDSAT: 3436 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3437 case ISD::SSUBSAT: 3438 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3439 case ISD::USUBSAT: 3440 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3441 case ISD::FADD: 3442 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3443 case ISD::FSUB: 3444 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3445 case ISD::FMUL: 3446 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3447 case ISD::FDIV: 3448 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3449 case ISD::FNEG: 3450 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3451 case ISD::FABS: 3452 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3453 case ISD::FSQRT: 3454 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3455 case ISD::FMA: 3456 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3457 case ISD::SMIN: 3458 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3459 case ISD::SMAX: 3460 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3461 case ISD::UMIN: 3462 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3463 case ISD::UMAX: 3464 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3465 case ISD::FMINNUM: 3466 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3467 case ISD::FMAXNUM: 3468 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3469 case ISD::ABS: 3470 return lowerABS(Op, DAG); 3471 case ISD::CTLZ_ZERO_UNDEF: 3472 case ISD::CTTZ_ZERO_UNDEF: 3473 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3474 case ISD::VSELECT: 3475 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3476 case ISD::FCOPYSIGN: 3477 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3478 case ISD::MGATHER: 3479 case ISD::VP_GATHER: 3480 return lowerMaskedGather(Op, DAG); 3481 case ISD::MSCATTER: 3482 case ISD::VP_SCATTER: 3483 return lowerMaskedScatter(Op, DAG); 3484 case ISD::FLT_ROUNDS_: 3485 return lowerGET_ROUNDING(Op, DAG); 3486 case ISD::SET_ROUNDING: 3487 return lowerSET_ROUNDING(Op, DAG); 3488 case ISD::VP_SELECT: 3489 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3490 case ISD::VP_MERGE: 3491 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3492 case ISD::VP_ADD: 3493 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3494 case ISD::VP_SUB: 3495 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3496 case ISD::VP_MUL: 3497 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3498 case ISD::VP_SDIV: 3499 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3500 case ISD::VP_UDIV: 3501 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3502 case ISD::VP_SREM: 3503 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3504 case ISD::VP_UREM: 3505 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3506 case ISD::VP_AND: 3507 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3508 case ISD::VP_OR: 3509 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3510 case ISD::VP_XOR: 3511 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3512 case ISD::VP_ASHR: 3513 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3514 case ISD::VP_LSHR: 3515 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3516 case ISD::VP_SHL: 3517 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3518 case ISD::VP_FADD: 3519 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3520 case ISD::VP_FSUB: 3521 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3522 case ISD::VP_FMUL: 3523 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3524 case ISD::VP_FDIV: 3525 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3526 } 3527 } 3528 3529 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3530 SelectionDAG &DAG, unsigned Flags) { 3531 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3532 } 3533 3534 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3535 SelectionDAG &DAG, unsigned Flags) { 3536 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3537 Flags); 3538 } 3539 3540 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3541 SelectionDAG &DAG, unsigned Flags) { 3542 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3543 N->getOffset(), Flags); 3544 } 3545 3546 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3547 SelectionDAG &DAG, unsigned Flags) { 3548 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3549 } 3550 3551 template <class NodeTy> 3552 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3553 bool IsLocal) const { 3554 SDLoc DL(N); 3555 EVT Ty = getPointerTy(DAG.getDataLayout()); 3556 3557 if (isPositionIndependent()) { 3558 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3559 if (IsLocal) 3560 // Use PC-relative addressing to access the symbol. This generates the 3561 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3562 // %pcrel_lo(auipc)). 3563 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3564 3565 // Use PC-relative addressing to access the GOT for this symbol, then load 3566 // the address from the GOT. This generates the pattern (PseudoLA sym), 3567 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3568 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3569 } 3570 3571 switch (getTargetMachine().getCodeModel()) { 3572 default: 3573 report_fatal_error("Unsupported code model for lowering"); 3574 case CodeModel::Small: { 3575 // Generate a sequence for accessing addresses within the first 2 GiB of 3576 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3577 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3578 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3579 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3580 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3581 } 3582 case CodeModel::Medium: { 3583 // Generate a sequence for accessing addresses within any 2GiB range within 3584 // the address space. This generates the pattern (PseudoLLA sym), which 3585 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3586 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3587 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3588 } 3589 } 3590 } 3591 3592 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3593 SelectionDAG &DAG) const { 3594 SDLoc DL(Op); 3595 EVT Ty = Op.getValueType(); 3596 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3597 int64_t Offset = N->getOffset(); 3598 MVT XLenVT = Subtarget.getXLenVT(); 3599 3600 const GlobalValue *GV = N->getGlobal(); 3601 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3602 SDValue Addr = getAddr(N, DAG, IsLocal); 3603 3604 // In order to maximise the opportunity for common subexpression elimination, 3605 // emit a separate ADD node for the global address offset instead of folding 3606 // it in the global address node. Later peephole optimisations may choose to 3607 // fold it back in when profitable. 3608 if (Offset != 0) 3609 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3610 DAG.getConstant(Offset, DL, XLenVT)); 3611 return Addr; 3612 } 3613 3614 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3615 SelectionDAG &DAG) const { 3616 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3617 3618 return getAddr(N, DAG); 3619 } 3620 3621 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3622 SelectionDAG &DAG) const { 3623 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3624 3625 return getAddr(N, DAG); 3626 } 3627 3628 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3629 SelectionDAG &DAG) const { 3630 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3631 3632 return getAddr(N, DAG); 3633 } 3634 3635 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3636 SelectionDAG &DAG, 3637 bool UseGOT) const { 3638 SDLoc DL(N); 3639 EVT Ty = getPointerTy(DAG.getDataLayout()); 3640 const GlobalValue *GV = N->getGlobal(); 3641 MVT XLenVT = Subtarget.getXLenVT(); 3642 3643 if (UseGOT) { 3644 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3645 // load the address from the GOT and add the thread pointer. This generates 3646 // the pattern (PseudoLA_TLS_IE sym), which expands to 3647 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3648 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3649 SDValue Load = 3650 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3651 3652 // Add the thread pointer. 3653 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3654 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3655 } 3656 3657 // Generate a sequence for accessing the address relative to the thread 3658 // pointer, with the appropriate adjustment for the thread pointer offset. 3659 // This generates the pattern 3660 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3661 SDValue AddrHi = 3662 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3663 SDValue AddrAdd = 3664 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3665 SDValue AddrLo = 3666 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3667 3668 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3669 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3670 SDValue MNAdd = SDValue( 3671 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3672 0); 3673 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3674 } 3675 3676 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3677 SelectionDAG &DAG) const { 3678 SDLoc DL(N); 3679 EVT Ty = getPointerTy(DAG.getDataLayout()); 3680 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3681 const GlobalValue *GV = N->getGlobal(); 3682 3683 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3684 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3685 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3686 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3687 SDValue Load = 3688 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3689 3690 // Prepare argument list to generate call. 3691 ArgListTy Args; 3692 ArgListEntry Entry; 3693 Entry.Node = Load; 3694 Entry.Ty = CallTy; 3695 Args.push_back(Entry); 3696 3697 // Setup call to __tls_get_addr. 3698 TargetLowering::CallLoweringInfo CLI(DAG); 3699 CLI.setDebugLoc(DL) 3700 .setChain(DAG.getEntryNode()) 3701 .setLibCallee(CallingConv::C, CallTy, 3702 DAG.getExternalSymbol("__tls_get_addr", Ty), 3703 std::move(Args)); 3704 3705 return LowerCallTo(CLI).first; 3706 } 3707 3708 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3709 SelectionDAG &DAG) const { 3710 SDLoc DL(Op); 3711 EVT Ty = Op.getValueType(); 3712 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3713 int64_t Offset = N->getOffset(); 3714 MVT XLenVT = Subtarget.getXLenVT(); 3715 3716 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3717 3718 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3719 CallingConv::GHC) 3720 report_fatal_error("In GHC calling convention TLS is not supported"); 3721 3722 SDValue Addr; 3723 switch (Model) { 3724 case TLSModel::LocalExec: 3725 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3726 break; 3727 case TLSModel::InitialExec: 3728 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3729 break; 3730 case TLSModel::LocalDynamic: 3731 case TLSModel::GeneralDynamic: 3732 Addr = getDynamicTLSAddr(N, DAG); 3733 break; 3734 } 3735 3736 // In order to maximise the opportunity for common subexpression elimination, 3737 // emit a separate ADD node for the global address offset instead of folding 3738 // it in the global address node. Later peephole optimisations may choose to 3739 // fold it back in when profitable. 3740 if (Offset != 0) 3741 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3742 DAG.getConstant(Offset, DL, XLenVT)); 3743 return Addr; 3744 } 3745 3746 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3747 SDValue CondV = Op.getOperand(0); 3748 SDValue TrueV = Op.getOperand(1); 3749 SDValue FalseV = Op.getOperand(2); 3750 SDLoc DL(Op); 3751 MVT VT = Op.getSimpleValueType(); 3752 MVT XLenVT = Subtarget.getXLenVT(); 3753 3754 // Lower vector SELECTs to VSELECTs by splatting the condition. 3755 if (VT.isVector()) { 3756 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3757 SDValue CondSplat = VT.isScalableVector() 3758 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3759 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3760 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3761 } 3762 3763 // If the result type is XLenVT and CondV is the output of a SETCC node 3764 // which also operated on XLenVT inputs, then merge the SETCC node into the 3765 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3766 // compare+branch instructions. i.e.: 3767 // (select (setcc lhs, rhs, cc), truev, falsev) 3768 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3769 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3770 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3771 SDValue LHS = CondV.getOperand(0); 3772 SDValue RHS = CondV.getOperand(1); 3773 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3774 ISD::CondCode CCVal = CC->get(); 3775 3776 // Special case for a select of 2 constants that have a diffence of 1. 3777 // Normally this is done by DAGCombine, but if the select is introduced by 3778 // type legalization or op legalization, we miss it. Restricting to SETLT 3779 // case for now because that is what signed saturating add/sub need. 3780 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3781 // but we would probably want to swap the true/false values if the condition 3782 // is SETGE/SETLE to avoid an XORI. 3783 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3784 CCVal == ISD::SETLT) { 3785 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3786 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3787 if (TrueVal - 1 == FalseVal) 3788 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3789 if (TrueVal + 1 == FalseVal) 3790 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3791 } 3792 3793 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3794 3795 SDValue TargetCC = DAG.getCondCode(CCVal); 3796 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3797 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3798 } 3799 3800 // Otherwise: 3801 // (select condv, truev, falsev) 3802 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3803 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3804 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3805 3806 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3807 3808 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3809 } 3810 3811 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3812 SDValue CondV = Op.getOperand(1); 3813 SDLoc DL(Op); 3814 MVT XLenVT = Subtarget.getXLenVT(); 3815 3816 if (CondV.getOpcode() == ISD::SETCC && 3817 CondV.getOperand(0).getValueType() == XLenVT) { 3818 SDValue LHS = CondV.getOperand(0); 3819 SDValue RHS = CondV.getOperand(1); 3820 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3821 3822 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3823 3824 SDValue TargetCC = DAG.getCondCode(CCVal); 3825 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3826 LHS, RHS, TargetCC, Op.getOperand(2)); 3827 } 3828 3829 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3830 CondV, DAG.getConstant(0, DL, XLenVT), 3831 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3832 } 3833 3834 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3835 MachineFunction &MF = DAG.getMachineFunction(); 3836 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3837 3838 SDLoc DL(Op); 3839 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3840 getPointerTy(MF.getDataLayout())); 3841 3842 // vastart just stores the address of the VarArgsFrameIndex slot into the 3843 // memory location argument. 3844 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3845 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3846 MachinePointerInfo(SV)); 3847 } 3848 3849 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3850 SelectionDAG &DAG) const { 3851 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3852 MachineFunction &MF = DAG.getMachineFunction(); 3853 MachineFrameInfo &MFI = MF.getFrameInfo(); 3854 MFI.setFrameAddressIsTaken(true); 3855 Register FrameReg = RI.getFrameRegister(MF); 3856 int XLenInBytes = Subtarget.getXLen() / 8; 3857 3858 EVT VT = Op.getValueType(); 3859 SDLoc DL(Op); 3860 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3861 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3862 while (Depth--) { 3863 int Offset = -(XLenInBytes * 2); 3864 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3865 DAG.getIntPtrConstant(Offset, DL)); 3866 FrameAddr = 3867 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3868 } 3869 return FrameAddr; 3870 } 3871 3872 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3873 SelectionDAG &DAG) const { 3874 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3875 MachineFunction &MF = DAG.getMachineFunction(); 3876 MachineFrameInfo &MFI = MF.getFrameInfo(); 3877 MFI.setReturnAddressIsTaken(true); 3878 MVT XLenVT = Subtarget.getXLenVT(); 3879 int XLenInBytes = Subtarget.getXLen() / 8; 3880 3881 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3882 return SDValue(); 3883 3884 EVT VT = Op.getValueType(); 3885 SDLoc DL(Op); 3886 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3887 if (Depth) { 3888 int Off = -XLenInBytes; 3889 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3890 SDValue Offset = DAG.getConstant(Off, DL, VT); 3891 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3892 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3893 MachinePointerInfo()); 3894 } 3895 3896 // Return the value of the return address register, marking it an implicit 3897 // live-in. 3898 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3899 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3900 } 3901 3902 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3903 SelectionDAG &DAG) const { 3904 SDLoc DL(Op); 3905 SDValue Lo = Op.getOperand(0); 3906 SDValue Hi = Op.getOperand(1); 3907 SDValue Shamt = Op.getOperand(2); 3908 EVT VT = Lo.getValueType(); 3909 3910 // if Shamt-XLEN < 0: // Shamt < XLEN 3911 // Lo = Lo << Shamt 3912 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3913 // else: 3914 // Lo = 0 3915 // Hi = Lo << (Shamt-XLEN) 3916 3917 SDValue Zero = DAG.getConstant(0, DL, VT); 3918 SDValue One = DAG.getConstant(1, DL, VT); 3919 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3920 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3921 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3922 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3923 3924 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3925 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3926 SDValue ShiftRightLo = 3927 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3928 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3929 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3930 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3931 3932 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3933 3934 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3935 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3936 3937 SDValue Parts[2] = {Lo, Hi}; 3938 return DAG.getMergeValues(Parts, DL); 3939 } 3940 3941 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3942 bool IsSRA) const { 3943 SDLoc DL(Op); 3944 SDValue Lo = Op.getOperand(0); 3945 SDValue Hi = Op.getOperand(1); 3946 SDValue Shamt = Op.getOperand(2); 3947 EVT VT = Lo.getValueType(); 3948 3949 // SRA expansion: 3950 // if Shamt-XLEN < 0: // Shamt < XLEN 3951 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3952 // Hi = Hi >>s Shamt 3953 // else: 3954 // Lo = Hi >>s (Shamt-XLEN); 3955 // Hi = Hi >>s (XLEN-1) 3956 // 3957 // SRL expansion: 3958 // if Shamt-XLEN < 0: // Shamt < XLEN 3959 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3960 // Hi = Hi >>u Shamt 3961 // else: 3962 // Lo = Hi >>u (Shamt-XLEN); 3963 // Hi = 0; 3964 3965 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3966 3967 SDValue Zero = DAG.getConstant(0, DL, VT); 3968 SDValue One = DAG.getConstant(1, DL, VT); 3969 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3970 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3971 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3972 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3973 3974 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3975 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3976 SDValue ShiftLeftHi = 3977 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3978 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3979 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3980 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3981 SDValue HiFalse = 3982 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3983 3984 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3985 3986 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3987 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3988 3989 SDValue Parts[2] = {Lo, Hi}; 3990 return DAG.getMergeValues(Parts, DL); 3991 } 3992 3993 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3994 // legal equivalently-sized i8 type, so we can use that as a go-between. 3995 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3996 SelectionDAG &DAG) const { 3997 SDLoc DL(Op); 3998 MVT VT = Op.getSimpleValueType(); 3999 SDValue SplatVal = Op.getOperand(0); 4000 // All-zeros or all-ones splats are handled specially. 4001 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4002 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4003 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4004 } 4005 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4006 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4007 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4008 } 4009 MVT XLenVT = Subtarget.getXLenVT(); 4010 assert(SplatVal.getValueType() == XLenVT && 4011 "Unexpected type for i1 splat value"); 4012 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4013 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4014 DAG.getConstant(1, DL, XLenVT)); 4015 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4016 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4017 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4018 } 4019 4020 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4021 // illegal (currently only vXi64 RV32). 4022 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4023 // them to SPLAT_VECTOR_I64 4024 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4025 SelectionDAG &DAG) const { 4026 SDLoc DL(Op); 4027 MVT VecVT = Op.getSimpleValueType(); 4028 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4029 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4030 4031 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4032 SDValue Lo = Op.getOperand(0); 4033 SDValue Hi = Op.getOperand(1); 4034 4035 if (VecVT.isFixedLengthVector()) { 4036 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4037 SDLoc DL(Op); 4038 SDValue Mask, VL; 4039 std::tie(Mask, VL) = 4040 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4041 4042 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 4043 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4044 } 4045 4046 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4047 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4048 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4049 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4050 // node in order to try and match RVV vector/scalar instructions. 4051 if ((LoC >> 31) == HiC) 4052 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 4053 } 4054 4055 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4056 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4057 isa<ConstantSDNode>(Hi.getOperand(1)) && 4058 Hi.getConstantOperandVal(1) == 31) 4059 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 4060 4061 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4062 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 4063 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64)); 4064 } 4065 4066 // Custom-lower extensions from mask vectors by using a vselect either with 1 4067 // for zero/any-extension or -1 for sign-extension: 4068 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4069 // Note that any-extension is lowered identically to zero-extension. 4070 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4071 int64_t ExtTrueVal) const { 4072 SDLoc DL(Op); 4073 MVT VecVT = Op.getSimpleValueType(); 4074 SDValue Src = Op.getOperand(0); 4075 // Only custom-lower extensions from mask types 4076 assert(Src.getValueType().isVector() && 4077 Src.getValueType().getVectorElementType() == MVT::i1); 4078 4079 MVT XLenVT = Subtarget.getXLenVT(); 4080 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4081 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4082 4083 if (VecVT.isScalableVector()) { 4084 // Be careful not to introduce illegal scalar types at this stage, and be 4085 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 4086 // illegal and must be expanded. Since we know that the constants are 4087 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 4088 bool IsRV32E64 = 4089 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 4090 4091 if (!IsRV32E64) { 4092 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 4093 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 4094 } else { 4095 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 4096 SplatTrueVal = 4097 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 4098 } 4099 4100 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4101 } 4102 4103 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4104 MVT I1ContainerVT = 4105 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4106 4107 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4108 4109 SDValue Mask, VL; 4110 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4111 4112 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 4113 SplatTrueVal = 4114 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 4115 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4116 SplatTrueVal, SplatZero, VL); 4117 4118 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4119 } 4120 4121 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4122 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4123 MVT ExtVT = Op.getSimpleValueType(); 4124 // Only custom-lower extensions from fixed-length vector types. 4125 if (!ExtVT.isFixedLengthVector()) 4126 return Op; 4127 MVT VT = Op.getOperand(0).getSimpleValueType(); 4128 // Grab the canonical container type for the extended type. Infer the smaller 4129 // type from that to ensure the same number of vector elements, as we know 4130 // the LMUL will be sufficient to hold the smaller type. 4131 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4132 // Get the extended container type manually to ensure the same number of 4133 // vector elements between source and dest. 4134 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4135 ContainerExtVT.getVectorElementCount()); 4136 4137 SDValue Op1 = 4138 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4139 4140 SDLoc DL(Op); 4141 SDValue Mask, VL; 4142 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4143 4144 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4145 4146 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4147 } 4148 4149 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4150 // setcc operation: 4151 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4152 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 4153 SelectionDAG &DAG) const { 4154 SDLoc DL(Op); 4155 EVT MaskVT = Op.getValueType(); 4156 // Only expect to custom-lower truncations to mask types 4157 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4158 "Unexpected type for vector mask lowering"); 4159 SDValue Src = Op.getOperand(0); 4160 MVT VecVT = Src.getSimpleValueType(); 4161 4162 // If this is a fixed vector, we need to convert it to a scalable vector. 4163 MVT ContainerVT = VecVT; 4164 if (VecVT.isFixedLengthVector()) { 4165 ContainerVT = getContainerForFixedLengthVector(VecVT); 4166 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4167 } 4168 4169 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4170 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4171 4172 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 4173 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 4174 4175 if (VecVT.isScalableVector()) { 4176 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 4177 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 4178 } 4179 4180 SDValue Mask, VL; 4181 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4182 4183 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4184 SDValue Trunc = 4185 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4186 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4187 DAG.getCondCode(ISD::SETNE), Mask, VL); 4188 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4189 } 4190 4191 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4192 // first position of a vector, and that vector is slid up to the insert index. 4193 // By limiting the active vector length to index+1 and merging with the 4194 // original vector (with an undisturbed tail policy for elements >= VL), we 4195 // achieve the desired result of leaving all elements untouched except the one 4196 // at VL-1, which is replaced with the desired value. 4197 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4198 SelectionDAG &DAG) const { 4199 SDLoc DL(Op); 4200 MVT VecVT = Op.getSimpleValueType(); 4201 SDValue Vec = Op.getOperand(0); 4202 SDValue Val = Op.getOperand(1); 4203 SDValue Idx = Op.getOperand(2); 4204 4205 if (VecVT.getVectorElementType() == MVT::i1) { 4206 // FIXME: For now we just promote to an i8 vector and insert into that, 4207 // but this is probably not optimal. 4208 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4209 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4210 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4211 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4212 } 4213 4214 MVT ContainerVT = VecVT; 4215 // If the operand is a fixed-length vector, convert to a scalable one. 4216 if (VecVT.isFixedLengthVector()) { 4217 ContainerVT = getContainerForFixedLengthVector(VecVT); 4218 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4219 } 4220 4221 MVT XLenVT = Subtarget.getXLenVT(); 4222 4223 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4224 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4225 // Even i64-element vectors on RV32 can be lowered without scalar 4226 // legalization if the most-significant 32 bits of the value are not affected 4227 // by the sign-extension of the lower 32 bits. 4228 // TODO: We could also catch sign extensions of a 32-bit value. 4229 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4230 const auto *CVal = cast<ConstantSDNode>(Val); 4231 if (isInt<32>(CVal->getSExtValue())) { 4232 IsLegalInsert = true; 4233 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4234 } 4235 } 4236 4237 SDValue Mask, VL; 4238 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4239 4240 SDValue ValInVec; 4241 4242 if (IsLegalInsert) { 4243 unsigned Opc = 4244 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4245 if (isNullConstant(Idx)) { 4246 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4247 if (!VecVT.isFixedLengthVector()) 4248 return Vec; 4249 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4250 } 4251 ValInVec = 4252 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4253 } else { 4254 // On RV32, i64-element vectors must be specially handled to place the 4255 // value at element 0, by using two vslide1up instructions in sequence on 4256 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4257 // this. 4258 SDValue One = DAG.getConstant(1, DL, XLenVT); 4259 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4260 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4261 MVT I32ContainerVT = 4262 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4263 SDValue I32Mask = 4264 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4265 // Limit the active VL to two. 4266 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4267 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4268 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4269 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 4270 InsertI64VL); 4271 // First slide in the hi value, then the lo in underneath it. 4272 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 4273 ValHi, I32Mask, InsertI64VL); 4274 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 4275 ValLo, I32Mask, InsertI64VL); 4276 // Bitcast back to the right container type. 4277 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4278 } 4279 4280 // Now that the value is in a vector, slide it into position. 4281 SDValue InsertVL = 4282 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4283 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4284 ValInVec, Idx, Mask, InsertVL); 4285 if (!VecVT.isFixedLengthVector()) 4286 return Slideup; 4287 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4288 } 4289 4290 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4291 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4292 // types this is done using VMV_X_S to allow us to glean information about the 4293 // sign bits of the result. 4294 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4295 SelectionDAG &DAG) const { 4296 SDLoc DL(Op); 4297 SDValue Idx = Op.getOperand(1); 4298 SDValue Vec = Op.getOperand(0); 4299 EVT EltVT = Op.getValueType(); 4300 MVT VecVT = Vec.getSimpleValueType(); 4301 MVT XLenVT = Subtarget.getXLenVT(); 4302 4303 if (VecVT.getVectorElementType() == MVT::i1) { 4304 if (VecVT.isFixedLengthVector()) { 4305 unsigned NumElts = VecVT.getVectorNumElements(); 4306 if (NumElts >= 8) { 4307 MVT WideEltVT; 4308 unsigned WidenVecLen; 4309 SDValue ExtractElementIdx; 4310 SDValue ExtractBitIdx; 4311 unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors(); 4312 MVT LargestEltVT = MVT::getIntegerVT( 4313 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4314 if (NumElts <= LargestEltVT.getSizeInBits()) { 4315 assert(isPowerOf2_32(NumElts) && 4316 "the number of elements should be power of 2"); 4317 WideEltVT = MVT::getIntegerVT(NumElts); 4318 WidenVecLen = 1; 4319 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4320 ExtractBitIdx = Idx; 4321 } else { 4322 WideEltVT = LargestEltVT; 4323 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4324 // extract element index = index / element width 4325 ExtractElementIdx = DAG.getNode( 4326 ISD::SRL, DL, XLenVT, Idx, 4327 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4328 // mask bit index = index % element width 4329 ExtractBitIdx = DAG.getNode( 4330 ISD::AND, DL, XLenVT, Idx, 4331 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4332 } 4333 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4334 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4335 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4336 Vec, ExtractElementIdx); 4337 // Extract the bit from GPR. 4338 SDValue ShiftRight = 4339 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4340 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4341 DAG.getConstant(1, DL, XLenVT)); 4342 } 4343 } 4344 // Otherwise, promote to an i8 vector and extract from that. 4345 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4346 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4347 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4348 } 4349 4350 // If this is a fixed vector, we need to convert it to a scalable vector. 4351 MVT ContainerVT = VecVT; 4352 if (VecVT.isFixedLengthVector()) { 4353 ContainerVT = getContainerForFixedLengthVector(VecVT); 4354 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4355 } 4356 4357 // If the index is 0, the vector is already in the right position. 4358 if (!isNullConstant(Idx)) { 4359 // Use a VL of 1 to avoid processing more elements than we need. 4360 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4361 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4362 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4363 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4364 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4365 } 4366 4367 if (!EltVT.isInteger()) { 4368 // Floating-point extracts are handled in TableGen. 4369 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4370 DAG.getConstant(0, DL, XLenVT)); 4371 } 4372 4373 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4374 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4375 } 4376 4377 // Some RVV intrinsics may claim that they want an integer operand to be 4378 // promoted or expanded. 4379 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 4380 const RISCVSubtarget &Subtarget) { 4381 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4382 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4383 "Unexpected opcode"); 4384 4385 if (!Subtarget.hasVInstructions()) 4386 return SDValue(); 4387 4388 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4389 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4390 SDLoc DL(Op); 4391 4392 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4393 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4394 if (!II || !II->hasSplatOperand()) 4395 return SDValue(); 4396 4397 unsigned SplatOp = II->SplatOperand + 1 + HasChain; 4398 assert(SplatOp < Op.getNumOperands()); 4399 4400 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4401 SDValue &ScalarOp = Operands[SplatOp]; 4402 MVT OpVT = ScalarOp.getSimpleValueType(); 4403 MVT XLenVT = Subtarget.getXLenVT(); 4404 4405 // If this isn't a scalar, or its type is XLenVT we're done. 4406 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4407 return SDValue(); 4408 4409 // Simplest case is that the operand needs to be promoted to XLenVT. 4410 if (OpVT.bitsLT(XLenVT)) { 4411 // If the operand is a constant, sign extend to increase our chances 4412 // of being able to use a .vi instruction. ANY_EXTEND would become a 4413 // a zero extend and the simm5 check in isel would fail. 4414 // FIXME: Should we ignore the upper bits in isel instead? 4415 unsigned ExtOpc = 4416 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4417 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4418 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4419 } 4420 4421 // Use the previous operand to get the vXi64 VT. The result might be a mask 4422 // VT for compares. Using the previous operand assumes that the previous 4423 // operand will never have a smaller element size than a scalar operand and 4424 // that a widening operation never uses SEW=64. 4425 // NOTE: If this fails the below assert, we can probably just find the 4426 // element count from any operand or result and use it to construct the VT. 4427 assert(II->SplatOperand > 0 && "Unexpected splat operand!"); 4428 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4429 4430 // The more complex case is when the scalar is larger than XLenVT. 4431 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4432 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4433 4434 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4435 // on the instruction to sign-extend since SEW>XLEN. 4436 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4437 if (isInt<32>(CVal->getSExtValue())) { 4438 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4439 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4440 } 4441 } 4442 4443 // We need to convert the scalar to a splat vector. 4444 // FIXME: Can we implicitly truncate the scalar if it is known to 4445 // be sign extended? 4446 SDValue VL = getVLOperand(Op); 4447 assert(VL.getValueType() == XLenVT); 4448 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 4449 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4450 } 4451 4452 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4453 SelectionDAG &DAG) const { 4454 unsigned IntNo = Op.getConstantOperandVal(0); 4455 SDLoc DL(Op); 4456 MVT XLenVT = Subtarget.getXLenVT(); 4457 4458 switch (IntNo) { 4459 default: 4460 break; // Don't custom lower most intrinsics. 4461 case Intrinsic::thread_pointer: { 4462 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4463 return DAG.getRegister(RISCV::X4, PtrVT); 4464 } 4465 case Intrinsic::riscv_orc_b: 4466 case Intrinsic::riscv_brev8: { 4467 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4468 unsigned Opc = 4469 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4470 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4471 DAG.getConstant(7, DL, XLenVT)); 4472 } 4473 case Intrinsic::riscv_grev: 4474 case Intrinsic::riscv_gorc: { 4475 unsigned Opc = 4476 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4477 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4478 } 4479 case Intrinsic::riscv_zip: 4480 case Intrinsic::riscv_unzip: { 4481 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4482 // For i32 the immdiate is 15. For i64 the immediate is 31. 4483 unsigned Opc = 4484 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4485 unsigned BitWidth = Op.getValueSizeInBits(); 4486 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4487 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4488 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4489 } 4490 case Intrinsic::riscv_shfl: 4491 case Intrinsic::riscv_unshfl: { 4492 unsigned Opc = 4493 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4494 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4495 } 4496 case Intrinsic::riscv_bcompress: 4497 case Intrinsic::riscv_bdecompress: { 4498 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4499 : RISCVISD::BDECOMPRESS; 4500 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4501 } 4502 case Intrinsic::riscv_bfp: 4503 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4504 Op.getOperand(2)); 4505 case Intrinsic::riscv_fsl: 4506 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4507 Op.getOperand(2), Op.getOperand(3)); 4508 case Intrinsic::riscv_fsr: 4509 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4510 Op.getOperand(2), Op.getOperand(3)); 4511 case Intrinsic::riscv_vmv_x_s: 4512 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4513 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4514 Op.getOperand(1)); 4515 case Intrinsic::riscv_vmv_v_x: 4516 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4517 Op.getSimpleValueType(), DL, DAG, Subtarget); 4518 case Intrinsic::riscv_vfmv_v_f: 4519 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4520 Op.getOperand(1), Op.getOperand(2)); 4521 case Intrinsic::riscv_vmv_s_x: { 4522 SDValue Scalar = Op.getOperand(2); 4523 4524 if (Scalar.getValueType().bitsLE(XLenVT)) { 4525 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4526 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4527 Op.getOperand(1), Scalar, Op.getOperand(3)); 4528 } 4529 4530 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4531 4532 // This is an i64 value that lives in two scalar registers. We have to 4533 // insert this in a convoluted way. First we build vXi64 splat containing 4534 // the/ two values that we assemble using some bit math. Next we'll use 4535 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4536 // to merge element 0 from our splat into the source vector. 4537 // FIXME: This is probably not the best way to do this, but it is 4538 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4539 // point. 4540 // sw lo, (a0) 4541 // sw hi, 4(a0) 4542 // vlse vX, (a0) 4543 // 4544 // vid.v vVid 4545 // vmseq.vx mMask, vVid, 0 4546 // vmerge.vvm vDest, vSrc, vVal, mMask 4547 MVT VT = Op.getSimpleValueType(); 4548 SDValue Vec = Op.getOperand(1); 4549 SDValue VL = getVLOperand(Op); 4550 4551 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 4552 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4553 DAG.getConstant(0, DL, MVT::i32), VL); 4554 4555 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4556 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4557 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4558 SDValue SelectCond = 4559 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4560 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4561 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4562 Vec, VL); 4563 } 4564 case Intrinsic::riscv_vslide1up: 4565 case Intrinsic::riscv_vslide1down: 4566 case Intrinsic::riscv_vslide1up_mask: 4567 case Intrinsic::riscv_vslide1down_mask: { 4568 // We need to special case these when the scalar is larger than XLen. 4569 unsigned NumOps = Op.getNumOperands(); 4570 bool IsMasked = NumOps == 7; 4571 unsigned OpOffset = IsMasked ? 1 : 0; 4572 SDValue Scalar = Op.getOperand(2 + OpOffset); 4573 if (Scalar.getValueType().bitsLE(XLenVT)) 4574 break; 4575 4576 // Splatting a sign extended constant is fine. 4577 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4578 if (isInt<32>(CVal->getSExtValue())) 4579 break; 4580 4581 MVT VT = Op.getSimpleValueType(); 4582 assert(VT.getVectorElementType() == MVT::i64 && 4583 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4584 4585 // Convert the vector source to the equivalent nxvXi32 vector. 4586 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4587 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 4588 4589 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4590 DAG.getConstant(0, DL, XLenVT)); 4591 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4592 DAG.getConstant(1, DL, XLenVT)); 4593 4594 // Double the VL since we halved SEW. 4595 SDValue VL = getVLOperand(Op); 4596 SDValue I32VL = 4597 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4598 4599 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4600 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4601 4602 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4603 // instructions. 4604 if (IntNo == Intrinsic::riscv_vslide1up || 4605 IntNo == Intrinsic::riscv_vslide1up_mask) { 4606 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 4607 I32Mask, I32VL); 4608 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 4609 I32Mask, I32VL); 4610 } else { 4611 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 4612 I32Mask, I32VL); 4613 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 4614 I32Mask, I32VL); 4615 } 4616 4617 // Convert back to nxvXi64. 4618 Vec = DAG.getBitcast(VT, Vec); 4619 4620 if (!IsMasked) 4621 return Vec; 4622 4623 // Apply mask after the operation. 4624 SDValue Mask = Op.getOperand(NumOps - 3); 4625 SDValue MaskedOff = Op.getOperand(1); 4626 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4627 } 4628 } 4629 4630 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4631 } 4632 4633 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4634 SelectionDAG &DAG) const { 4635 unsigned IntNo = Op.getConstantOperandVal(1); 4636 switch (IntNo) { 4637 default: 4638 break; 4639 case Intrinsic::riscv_masked_strided_load: { 4640 SDLoc DL(Op); 4641 MVT XLenVT = Subtarget.getXLenVT(); 4642 4643 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4644 // the selection of the masked intrinsics doesn't do this for us. 4645 SDValue Mask = Op.getOperand(5); 4646 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4647 4648 MVT VT = Op->getSimpleValueType(0); 4649 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4650 4651 SDValue PassThru = Op.getOperand(2); 4652 if (!IsUnmasked) { 4653 MVT MaskVT = 4654 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4655 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4656 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4657 } 4658 4659 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4660 4661 SDValue IntID = DAG.getTargetConstant( 4662 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4663 XLenVT); 4664 4665 auto *Load = cast<MemIntrinsicSDNode>(Op); 4666 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4667 if (IsUnmasked) 4668 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4669 else 4670 Ops.push_back(PassThru); 4671 Ops.push_back(Op.getOperand(3)); // Ptr 4672 Ops.push_back(Op.getOperand(4)); // Stride 4673 if (!IsUnmasked) 4674 Ops.push_back(Mask); 4675 Ops.push_back(VL); 4676 if (!IsUnmasked) { 4677 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4678 Ops.push_back(Policy); 4679 } 4680 4681 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4682 SDValue Result = 4683 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4684 Load->getMemoryVT(), Load->getMemOperand()); 4685 SDValue Chain = Result.getValue(1); 4686 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4687 return DAG.getMergeValues({Result, Chain}, DL); 4688 } 4689 } 4690 4691 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4692 } 4693 4694 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4695 SelectionDAG &DAG) const { 4696 unsigned IntNo = Op.getConstantOperandVal(1); 4697 switch (IntNo) { 4698 default: 4699 break; 4700 case Intrinsic::riscv_masked_strided_store: { 4701 SDLoc DL(Op); 4702 MVT XLenVT = Subtarget.getXLenVT(); 4703 4704 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4705 // the selection of the masked intrinsics doesn't do this for us. 4706 SDValue Mask = Op.getOperand(5); 4707 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4708 4709 SDValue Val = Op.getOperand(2); 4710 MVT VT = Val.getSimpleValueType(); 4711 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4712 4713 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4714 if (!IsUnmasked) { 4715 MVT MaskVT = 4716 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4717 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4718 } 4719 4720 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4721 4722 SDValue IntID = DAG.getTargetConstant( 4723 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4724 XLenVT); 4725 4726 auto *Store = cast<MemIntrinsicSDNode>(Op); 4727 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4728 Ops.push_back(Val); 4729 Ops.push_back(Op.getOperand(3)); // Ptr 4730 Ops.push_back(Op.getOperand(4)); // Stride 4731 if (!IsUnmasked) 4732 Ops.push_back(Mask); 4733 Ops.push_back(VL); 4734 4735 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4736 Ops, Store->getMemoryVT(), 4737 Store->getMemOperand()); 4738 } 4739 } 4740 4741 return SDValue(); 4742 } 4743 4744 static MVT getLMUL1VT(MVT VT) { 4745 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4746 "Unexpected vector MVT"); 4747 return MVT::getScalableVectorVT( 4748 VT.getVectorElementType(), 4749 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4750 } 4751 4752 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4753 switch (ISDOpcode) { 4754 default: 4755 llvm_unreachable("Unhandled reduction"); 4756 case ISD::VECREDUCE_ADD: 4757 return RISCVISD::VECREDUCE_ADD_VL; 4758 case ISD::VECREDUCE_UMAX: 4759 return RISCVISD::VECREDUCE_UMAX_VL; 4760 case ISD::VECREDUCE_SMAX: 4761 return RISCVISD::VECREDUCE_SMAX_VL; 4762 case ISD::VECREDUCE_UMIN: 4763 return RISCVISD::VECREDUCE_UMIN_VL; 4764 case ISD::VECREDUCE_SMIN: 4765 return RISCVISD::VECREDUCE_SMIN_VL; 4766 case ISD::VECREDUCE_AND: 4767 return RISCVISD::VECREDUCE_AND_VL; 4768 case ISD::VECREDUCE_OR: 4769 return RISCVISD::VECREDUCE_OR_VL; 4770 case ISD::VECREDUCE_XOR: 4771 return RISCVISD::VECREDUCE_XOR_VL; 4772 } 4773 } 4774 4775 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4776 SelectionDAG &DAG, 4777 bool IsVP) const { 4778 SDLoc DL(Op); 4779 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4780 MVT VecVT = Vec.getSimpleValueType(); 4781 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4782 Op.getOpcode() == ISD::VECREDUCE_OR || 4783 Op.getOpcode() == ISD::VECREDUCE_XOR || 4784 Op.getOpcode() == ISD::VP_REDUCE_AND || 4785 Op.getOpcode() == ISD::VP_REDUCE_OR || 4786 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4787 "Unexpected reduction lowering"); 4788 4789 MVT XLenVT = Subtarget.getXLenVT(); 4790 assert(Op.getValueType() == XLenVT && 4791 "Expected reduction output to be legalized to XLenVT"); 4792 4793 MVT ContainerVT = VecVT; 4794 if (VecVT.isFixedLengthVector()) { 4795 ContainerVT = getContainerForFixedLengthVector(VecVT); 4796 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4797 } 4798 4799 SDValue Mask, VL; 4800 if (IsVP) { 4801 Mask = Op.getOperand(2); 4802 VL = Op.getOperand(3); 4803 } else { 4804 std::tie(Mask, VL) = 4805 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4806 } 4807 4808 unsigned BaseOpc; 4809 ISD::CondCode CC; 4810 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4811 4812 switch (Op.getOpcode()) { 4813 default: 4814 llvm_unreachable("Unhandled reduction"); 4815 case ISD::VECREDUCE_AND: 4816 case ISD::VP_REDUCE_AND: { 4817 // vcpop ~x == 0 4818 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4819 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4820 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4821 CC = ISD::SETEQ; 4822 BaseOpc = ISD::AND; 4823 break; 4824 } 4825 case ISD::VECREDUCE_OR: 4826 case ISD::VP_REDUCE_OR: 4827 // vcpop x != 0 4828 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4829 CC = ISD::SETNE; 4830 BaseOpc = ISD::OR; 4831 break; 4832 case ISD::VECREDUCE_XOR: 4833 case ISD::VP_REDUCE_XOR: { 4834 // ((vcpop x) & 1) != 0 4835 SDValue One = DAG.getConstant(1, DL, XLenVT); 4836 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4837 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4838 CC = ISD::SETNE; 4839 BaseOpc = ISD::XOR; 4840 break; 4841 } 4842 } 4843 4844 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4845 4846 if (!IsVP) 4847 return SetCC; 4848 4849 // Now include the start value in the operation. 4850 // Note that we must return the start value when no elements are operated 4851 // upon. The vcpop instructions we've emitted in each case above will return 4852 // 0 for an inactive vector, and so we've already received the neutral value: 4853 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4854 // can simply include the start value. 4855 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4856 } 4857 4858 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4859 SelectionDAG &DAG) const { 4860 SDLoc DL(Op); 4861 SDValue Vec = Op.getOperand(0); 4862 EVT VecEVT = Vec.getValueType(); 4863 4864 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4865 4866 // Due to ordering in legalize types we may have a vector type that needs to 4867 // be split. Do that manually so we can get down to a legal type. 4868 while (getTypeAction(*DAG.getContext(), VecEVT) == 4869 TargetLowering::TypeSplitVector) { 4870 SDValue Lo, Hi; 4871 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4872 VecEVT = Lo.getValueType(); 4873 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4874 } 4875 4876 // TODO: The type may need to be widened rather than split. Or widened before 4877 // it can be split. 4878 if (!isTypeLegal(VecEVT)) 4879 return SDValue(); 4880 4881 MVT VecVT = VecEVT.getSimpleVT(); 4882 MVT VecEltVT = VecVT.getVectorElementType(); 4883 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4884 4885 MVT ContainerVT = VecVT; 4886 if (VecVT.isFixedLengthVector()) { 4887 ContainerVT = getContainerForFixedLengthVector(VecVT); 4888 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4889 } 4890 4891 MVT M1VT = getLMUL1VT(ContainerVT); 4892 MVT XLenVT = Subtarget.getXLenVT(); 4893 4894 SDValue Mask, VL; 4895 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4896 4897 SDValue NeutralElem = 4898 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4899 SDValue IdentitySplat = lowerScalarSplat( 4900 NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4901 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4902 IdentitySplat, Mask, VL); 4903 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4904 DAG.getConstant(0, DL, XLenVT)); 4905 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4906 } 4907 4908 // Given a reduction op, this function returns the matching reduction opcode, 4909 // the vector SDValue and the scalar SDValue required to lower this to a 4910 // RISCVISD node. 4911 static std::tuple<unsigned, SDValue, SDValue> 4912 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4913 SDLoc DL(Op); 4914 auto Flags = Op->getFlags(); 4915 unsigned Opcode = Op.getOpcode(); 4916 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4917 switch (Opcode) { 4918 default: 4919 llvm_unreachable("Unhandled reduction"); 4920 case ISD::VECREDUCE_FADD: { 4921 // Use positive zero if we can. It is cheaper to materialize. 4922 SDValue Zero = 4923 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 4924 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 4925 } 4926 case ISD::VECREDUCE_SEQ_FADD: 4927 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4928 Op.getOperand(0)); 4929 case ISD::VECREDUCE_FMIN: 4930 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4931 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4932 case ISD::VECREDUCE_FMAX: 4933 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4934 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4935 } 4936 } 4937 4938 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4939 SelectionDAG &DAG) const { 4940 SDLoc DL(Op); 4941 MVT VecEltVT = Op.getSimpleValueType(); 4942 4943 unsigned RVVOpcode; 4944 SDValue VectorVal, ScalarVal; 4945 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4946 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4947 MVT VecVT = VectorVal.getSimpleValueType(); 4948 4949 MVT ContainerVT = VecVT; 4950 if (VecVT.isFixedLengthVector()) { 4951 ContainerVT = getContainerForFixedLengthVector(VecVT); 4952 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4953 } 4954 4955 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4956 MVT XLenVT = Subtarget.getXLenVT(); 4957 4958 SDValue Mask, VL; 4959 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4960 4961 SDValue ScalarSplat = lowerScalarSplat( 4962 ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4963 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4964 VectorVal, ScalarSplat, Mask, VL); 4965 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4966 DAG.getConstant(0, DL, XLenVT)); 4967 } 4968 4969 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4970 switch (ISDOpcode) { 4971 default: 4972 llvm_unreachable("Unhandled reduction"); 4973 case ISD::VP_REDUCE_ADD: 4974 return RISCVISD::VECREDUCE_ADD_VL; 4975 case ISD::VP_REDUCE_UMAX: 4976 return RISCVISD::VECREDUCE_UMAX_VL; 4977 case ISD::VP_REDUCE_SMAX: 4978 return RISCVISD::VECREDUCE_SMAX_VL; 4979 case ISD::VP_REDUCE_UMIN: 4980 return RISCVISD::VECREDUCE_UMIN_VL; 4981 case ISD::VP_REDUCE_SMIN: 4982 return RISCVISD::VECREDUCE_SMIN_VL; 4983 case ISD::VP_REDUCE_AND: 4984 return RISCVISD::VECREDUCE_AND_VL; 4985 case ISD::VP_REDUCE_OR: 4986 return RISCVISD::VECREDUCE_OR_VL; 4987 case ISD::VP_REDUCE_XOR: 4988 return RISCVISD::VECREDUCE_XOR_VL; 4989 case ISD::VP_REDUCE_FADD: 4990 return RISCVISD::VECREDUCE_FADD_VL; 4991 case ISD::VP_REDUCE_SEQ_FADD: 4992 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 4993 case ISD::VP_REDUCE_FMAX: 4994 return RISCVISD::VECREDUCE_FMAX_VL; 4995 case ISD::VP_REDUCE_FMIN: 4996 return RISCVISD::VECREDUCE_FMIN_VL; 4997 } 4998 } 4999 5000 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5001 SelectionDAG &DAG) const { 5002 SDLoc DL(Op); 5003 SDValue Vec = Op.getOperand(1); 5004 EVT VecEVT = Vec.getValueType(); 5005 5006 // TODO: The type may need to be widened rather than split. Or widened before 5007 // it can be split. 5008 if (!isTypeLegal(VecEVT)) 5009 return SDValue(); 5010 5011 MVT VecVT = VecEVT.getSimpleVT(); 5012 MVT VecEltVT = VecVT.getVectorElementType(); 5013 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5014 5015 MVT ContainerVT = VecVT; 5016 if (VecVT.isFixedLengthVector()) { 5017 ContainerVT = getContainerForFixedLengthVector(VecVT); 5018 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5019 } 5020 5021 SDValue VL = Op.getOperand(3); 5022 SDValue Mask = Op.getOperand(2); 5023 5024 MVT M1VT = getLMUL1VT(ContainerVT); 5025 MVT XLenVT = Subtarget.getXLenVT(); 5026 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5027 5028 SDValue StartSplat = 5029 lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT, 5030 DL, DAG, Subtarget); 5031 SDValue Reduction = 5032 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5033 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5034 DAG.getConstant(0, DL, XLenVT)); 5035 if (!VecVT.isInteger()) 5036 return Elt0; 5037 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5038 } 5039 5040 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5041 SelectionDAG &DAG) const { 5042 SDValue Vec = Op.getOperand(0); 5043 SDValue SubVec = Op.getOperand(1); 5044 MVT VecVT = Vec.getSimpleValueType(); 5045 MVT SubVecVT = SubVec.getSimpleValueType(); 5046 5047 SDLoc DL(Op); 5048 MVT XLenVT = Subtarget.getXLenVT(); 5049 unsigned OrigIdx = Op.getConstantOperandVal(2); 5050 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5051 5052 // We don't have the ability to slide mask vectors up indexed by their i1 5053 // elements; the smallest we can do is i8. Often we are able to bitcast to 5054 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5055 // into a scalable one, we might not necessarily have enough scalable 5056 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5057 if (SubVecVT.getVectorElementType() == MVT::i1 && 5058 (OrigIdx != 0 || !Vec.isUndef())) { 5059 if (VecVT.getVectorMinNumElements() >= 8 && 5060 SubVecVT.getVectorMinNumElements() >= 8) { 5061 assert(OrigIdx % 8 == 0 && "Invalid index"); 5062 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5063 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5064 "Unexpected mask vector lowering"); 5065 OrigIdx /= 8; 5066 SubVecVT = 5067 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5068 SubVecVT.isScalableVector()); 5069 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5070 VecVT.isScalableVector()); 5071 Vec = DAG.getBitcast(VecVT, Vec); 5072 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5073 } else { 5074 // We can't slide this mask vector up indexed by its i1 elements. 5075 // This poses a problem when we wish to insert a scalable vector which 5076 // can't be re-expressed as a larger type. Just choose the slow path and 5077 // extend to a larger type, then truncate back down. 5078 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5079 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5080 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5081 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5082 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5083 Op.getOperand(2)); 5084 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5085 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5086 } 5087 } 5088 5089 // If the subvector vector is a fixed-length type, we cannot use subregister 5090 // manipulation to simplify the codegen; we don't know which register of a 5091 // LMUL group contains the specific subvector as we only know the minimum 5092 // register size. Therefore we must slide the vector group up the full 5093 // amount. 5094 if (SubVecVT.isFixedLengthVector()) { 5095 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5096 return Op; 5097 MVT ContainerVT = VecVT; 5098 if (VecVT.isFixedLengthVector()) { 5099 ContainerVT = getContainerForFixedLengthVector(VecVT); 5100 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5101 } 5102 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5103 DAG.getUNDEF(ContainerVT), SubVec, 5104 DAG.getConstant(0, DL, XLenVT)); 5105 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5106 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5107 return DAG.getBitcast(Op.getValueType(), SubVec); 5108 } 5109 SDValue Mask = 5110 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5111 // Set the vector length to only the number of elements we care about. Note 5112 // that for slideup this includes the offset. 5113 SDValue VL = 5114 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5115 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5116 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5117 SubVec, SlideupAmt, Mask, VL); 5118 if (VecVT.isFixedLengthVector()) 5119 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5120 return DAG.getBitcast(Op.getValueType(), Slideup); 5121 } 5122 5123 unsigned SubRegIdx, RemIdx; 5124 std::tie(SubRegIdx, RemIdx) = 5125 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5126 VecVT, SubVecVT, OrigIdx, TRI); 5127 5128 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5129 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5130 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5131 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5132 5133 // 1. If the Idx has been completely eliminated and this subvector's size is 5134 // a vector register or a multiple thereof, or the surrounding elements are 5135 // undef, then this is a subvector insert which naturally aligns to a vector 5136 // register. These can easily be handled using subregister manipulation. 5137 // 2. If the subvector is smaller than a vector register, then the insertion 5138 // must preserve the undisturbed elements of the register. We do this by 5139 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5140 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5141 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5142 // LMUL=1 type back into the larger vector (resolving to another subregister 5143 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5144 // to avoid allocating a large register group to hold our subvector. 5145 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5146 return Op; 5147 5148 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5149 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5150 // (in our case undisturbed). This means we can set up a subvector insertion 5151 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5152 // size of the subvector. 5153 MVT InterSubVT = VecVT; 5154 SDValue AlignedExtract = Vec; 5155 unsigned AlignedIdx = OrigIdx - RemIdx; 5156 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5157 InterSubVT = getLMUL1VT(VecVT); 5158 // Extract a subvector equal to the nearest full vector register type. This 5159 // should resolve to a EXTRACT_SUBREG instruction. 5160 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5161 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5162 } 5163 5164 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5165 // For scalable vectors this must be further multiplied by vscale. 5166 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5167 5168 SDValue Mask, VL; 5169 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5170 5171 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5172 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5173 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5174 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5175 5176 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5177 DAG.getUNDEF(InterSubVT), SubVec, 5178 DAG.getConstant(0, DL, XLenVT)); 5179 5180 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5181 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5182 5183 // If required, insert this subvector back into the correct vector register. 5184 // This should resolve to an INSERT_SUBREG instruction. 5185 if (VecVT.bitsGT(InterSubVT)) 5186 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5187 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5188 5189 // We might have bitcast from a mask type: cast back to the original type if 5190 // required. 5191 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5192 } 5193 5194 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5195 SelectionDAG &DAG) const { 5196 SDValue Vec = Op.getOperand(0); 5197 MVT SubVecVT = Op.getSimpleValueType(); 5198 MVT VecVT = Vec.getSimpleValueType(); 5199 5200 SDLoc DL(Op); 5201 MVT XLenVT = Subtarget.getXLenVT(); 5202 unsigned OrigIdx = Op.getConstantOperandVal(1); 5203 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5204 5205 // We don't have the ability to slide mask vectors down indexed by their i1 5206 // elements; the smallest we can do is i8. Often we are able to bitcast to 5207 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5208 // from a scalable one, we might not necessarily have enough scalable 5209 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5210 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5211 if (VecVT.getVectorMinNumElements() >= 8 && 5212 SubVecVT.getVectorMinNumElements() >= 8) { 5213 assert(OrigIdx % 8 == 0 && "Invalid index"); 5214 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5215 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5216 "Unexpected mask vector lowering"); 5217 OrigIdx /= 8; 5218 SubVecVT = 5219 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5220 SubVecVT.isScalableVector()); 5221 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5222 VecVT.isScalableVector()); 5223 Vec = DAG.getBitcast(VecVT, Vec); 5224 } else { 5225 // We can't slide this mask vector down, indexed by its i1 elements. 5226 // This poses a problem when we wish to extract a scalable vector which 5227 // can't be re-expressed as a larger type. Just choose the slow path and 5228 // extend to a larger type, then truncate back down. 5229 // TODO: We could probably improve this when extracting certain fixed 5230 // from fixed, where we can extract as i8 and shift the correct element 5231 // right to reach the desired subvector? 5232 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5233 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5234 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5235 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5236 Op.getOperand(1)); 5237 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5238 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5239 } 5240 } 5241 5242 // If the subvector vector is a fixed-length type, we cannot use subregister 5243 // manipulation to simplify the codegen; we don't know which register of a 5244 // LMUL group contains the specific subvector as we only know the minimum 5245 // register size. Therefore we must slide the vector group down the full 5246 // amount. 5247 if (SubVecVT.isFixedLengthVector()) { 5248 // With an index of 0 this is a cast-like subvector, which can be performed 5249 // with subregister operations. 5250 if (OrigIdx == 0) 5251 return Op; 5252 MVT ContainerVT = VecVT; 5253 if (VecVT.isFixedLengthVector()) { 5254 ContainerVT = getContainerForFixedLengthVector(VecVT); 5255 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5256 } 5257 SDValue Mask = 5258 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5259 // Set the vector length to only the number of elements we care about. This 5260 // avoids sliding down elements we're going to discard straight away. 5261 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5262 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5263 SDValue Slidedown = 5264 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5265 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5266 // Now we can use a cast-like subvector extract to get the result. 5267 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5268 DAG.getConstant(0, DL, XLenVT)); 5269 return DAG.getBitcast(Op.getValueType(), Slidedown); 5270 } 5271 5272 unsigned SubRegIdx, RemIdx; 5273 std::tie(SubRegIdx, RemIdx) = 5274 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5275 VecVT, SubVecVT, OrigIdx, TRI); 5276 5277 // If the Idx has been completely eliminated then this is a subvector extract 5278 // which naturally aligns to a vector register. These can easily be handled 5279 // using subregister manipulation. 5280 if (RemIdx == 0) 5281 return Op; 5282 5283 // Else we must shift our vector register directly to extract the subvector. 5284 // Do this using VSLIDEDOWN. 5285 5286 // If the vector type is an LMUL-group type, extract a subvector equal to the 5287 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5288 // instruction. 5289 MVT InterSubVT = VecVT; 5290 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5291 InterSubVT = getLMUL1VT(VecVT); 5292 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5293 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5294 } 5295 5296 // Slide this vector register down by the desired number of elements in order 5297 // to place the desired subvector starting at element 0. 5298 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5299 // For scalable vectors this must be further multiplied by vscale. 5300 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5301 5302 SDValue Mask, VL; 5303 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5304 SDValue Slidedown = 5305 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5306 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5307 5308 // Now the vector is in the right position, extract our final subvector. This 5309 // should resolve to a COPY. 5310 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5311 DAG.getConstant(0, DL, XLenVT)); 5312 5313 // We might have bitcast from a mask type: cast back to the original type if 5314 // required. 5315 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5316 } 5317 5318 // Lower step_vector to the vid instruction. Any non-identity step value must 5319 // be accounted for my manual expansion. 5320 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5321 SelectionDAG &DAG) const { 5322 SDLoc DL(Op); 5323 MVT VT = Op.getSimpleValueType(); 5324 MVT XLenVT = Subtarget.getXLenVT(); 5325 SDValue Mask, VL; 5326 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5327 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5328 uint64_t StepValImm = Op.getConstantOperandVal(0); 5329 if (StepValImm != 1) { 5330 if (isPowerOf2_64(StepValImm)) { 5331 SDValue StepVal = 5332 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 5333 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5334 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5335 } else { 5336 SDValue StepVal = lowerScalarSplat( 5337 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 5338 DL, DAG, Subtarget); 5339 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5340 } 5341 } 5342 return StepVec; 5343 } 5344 5345 // Implement vector_reverse using vrgather.vv with indices determined by 5346 // subtracting the id of each element from (VLMAX-1). This will convert 5347 // the indices like so: 5348 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5349 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5350 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5351 SelectionDAG &DAG) const { 5352 SDLoc DL(Op); 5353 MVT VecVT = Op.getSimpleValueType(); 5354 unsigned EltSize = VecVT.getScalarSizeInBits(); 5355 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5356 5357 unsigned MaxVLMAX = 0; 5358 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5359 if (VectorBitsMax != 0) 5360 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5361 5362 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5363 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5364 5365 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5366 // to use vrgatherei16.vv. 5367 // TODO: It's also possible to use vrgatherei16.vv for other types to 5368 // decrease register width for the index calculation. 5369 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5370 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5371 // Reverse each half, then reassemble them in reverse order. 5372 // NOTE: It's also possible that after splitting that VLMAX no longer 5373 // requires vrgatherei16.vv. 5374 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5375 SDValue Lo, Hi; 5376 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5377 EVT LoVT, HiVT; 5378 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5379 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5380 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5381 // Reassemble the low and high pieces reversed. 5382 // FIXME: This is a CONCAT_VECTORS. 5383 SDValue Res = 5384 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5385 DAG.getIntPtrConstant(0, DL)); 5386 return DAG.getNode( 5387 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5388 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5389 } 5390 5391 // Just promote the int type to i16 which will double the LMUL. 5392 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5393 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5394 } 5395 5396 MVT XLenVT = Subtarget.getXLenVT(); 5397 SDValue Mask, VL; 5398 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5399 5400 // Calculate VLMAX-1 for the desired SEW. 5401 unsigned MinElts = VecVT.getVectorMinNumElements(); 5402 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5403 DAG.getConstant(MinElts, DL, XLenVT)); 5404 SDValue VLMinus1 = 5405 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5406 5407 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5408 bool IsRV32E64 = 5409 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5410 SDValue SplatVL; 5411 if (!IsRV32E64) 5412 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5413 else 5414 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 5415 5416 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5417 SDValue Indices = 5418 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5419 5420 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5421 } 5422 5423 SDValue 5424 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5425 SelectionDAG &DAG) const { 5426 SDLoc DL(Op); 5427 auto *Load = cast<LoadSDNode>(Op); 5428 5429 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5430 Load->getMemoryVT(), 5431 *Load->getMemOperand()) && 5432 "Expecting a correctly-aligned load"); 5433 5434 MVT VT = Op.getSimpleValueType(); 5435 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5436 5437 SDValue VL = 5438 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5439 5440 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5441 SDValue NewLoad = DAG.getMemIntrinsicNode( 5442 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5443 Load->getMemoryVT(), Load->getMemOperand()); 5444 5445 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5446 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5447 } 5448 5449 SDValue 5450 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5451 SelectionDAG &DAG) const { 5452 SDLoc DL(Op); 5453 auto *Store = cast<StoreSDNode>(Op); 5454 5455 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5456 Store->getMemoryVT(), 5457 *Store->getMemOperand()) && 5458 "Expecting a correctly-aligned store"); 5459 5460 SDValue StoreVal = Store->getValue(); 5461 MVT VT = StoreVal.getSimpleValueType(); 5462 5463 // If the size less than a byte, we need to pad with zeros to make a byte. 5464 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5465 VT = MVT::v8i1; 5466 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5467 DAG.getConstant(0, DL, VT), StoreVal, 5468 DAG.getIntPtrConstant(0, DL)); 5469 } 5470 5471 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5472 5473 SDValue VL = 5474 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5475 5476 SDValue NewValue = 5477 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5478 return DAG.getMemIntrinsicNode( 5479 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5480 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5481 Store->getMemoryVT(), Store->getMemOperand()); 5482 } 5483 5484 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5485 SelectionDAG &DAG) const { 5486 SDLoc DL(Op); 5487 MVT VT = Op.getSimpleValueType(); 5488 5489 const auto *MemSD = cast<MemSDNode>(Op); 5490 EVT MemVT = MemSD->getMemoryVT(); 5491 MachineMemOperand *MMO = MemSD->getMemOperand(); 5492 SDValue Chain = MemSD->getChain(); 5493 SDValue BasePtr = MemSD->getBasePtr(); 5494 5495 SDValue Mask, PassThru, VL; 5496 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5497 Mask = VPLoad->getMask(); 5498 PassThru = DAG.getUNDEF(VT); 5499 VL = VPLoad->getVectorLength(); 5500 } else { 5501 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5502 Mask = MLoad->getMask(); 5503 PassThru = MLoad->getPassThru(); 5504 } 5505 5506 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5507 5508 MVT XLenVT = Subtarget.getXLenVT(); 5509 5510 MVT ContainerVT = VT; 5511 if (VT.isFixedLengthVector()) { 5512 ContainerVT = getContainerForFixedLengthVector(VT); 5513 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5514 if (!IsUnmasked) { 5515 MVT MaskVT = 5516 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5517 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5518 } 5519 } 5520 5521 if (!VL) 5522 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5523 5524 unsigned IntID = 5525 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5526 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5527 if (IsUnmasked) 5528 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5529 else 5530 Ops.push_back(PassThru); 5531 Ops.push_back(BasePtr); 5532 if (!IsUnmasked) 5533 Ops.push_back(Mask); 5534 Ops.push_back(VL); 5535 if (!IsUnmasked) 5536 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5537 5538 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5539 5540 SDValue Result = 5541 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5542 Chain = Result.getValue(1); 5543 5544 if (VT.isFixedLengthVector()) 5545 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5546 5547 return DAG.getMergeValues({Result, Chain}, DL); 5548 } 5549 5550 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5551 SelectionDAG &DAG) const { 5552 SDLoc DL(Op); 5553 5554 const auto *MemSD = cast<MemSDNode>(Op); 5555 EVT MemVT = MemSD->getMemoryVT(); 5556 MachineMemOperand *MMO = MemSD->getMemOperand(); 5557 SDValue Chain = MemSD->getChain(); 5558 SDValue BasePtr = MemSD->getBasePtr(); 5559 SDValue Val, Mask, VL; 5560 5561 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5562 Val = VPStore->getValue(); 5563 Mask = VPStore->getMask(); 5564 VL = VPStore->getVectorLength(); 5565 } else { 5566 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5567 Val = MStore->getValue(); 5568 Mask = MStore->getMask(); 5569 } 5570 5571 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5572 5573 MVT VT = Val.getSimpleValueType(); 5574 MVT XLenVT = Subtarget.getXLenVT(); 5575 5576 MVT ContainerVT = VT; 5577 if (VT.isFixedLengthVector()) { 5578 ContainerVT = getContainerForFixedLengthVector(VT); 5579 5580 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5581 if (!IsUnmasked) { 5582 MVT MaskVT = 5583 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5584 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5585 } 5586 } 5587 5588 if (!VL) 5589 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5590 5591 unsigned IntID = 5592 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5593 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5594 Ops.push_back(Val); 5595 Ops.push_back(BasePtr); 5596 if (!IsUnmasked) 5597 Ops.push_back(Mask); 5598 Ops.push_back(VL); 5599 5600 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5601 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5602 } 5603 5604 SDValue 5605 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5606 SelectionDAG &DAG) const { 5607 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5608 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5609 5610 MVT VT = Op.getSimpleValueType(); 5611 5612 SDValue Op1 = 5613 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5614 SDValue Op2 = 5615 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5616 5617 SDLoc DL(Op); 5618 SDValue VL = 5619 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5620 5621 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5622 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5623 5624 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5625 Op.getOperand(2), Mask, VL); 5626 5627 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5628 } 5629 5630 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5631 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5632 MVT VT = Op.getSimpleValueType(); 5633 5634 if (VT.getVectorElementType() == MVT::i1) 5635 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5636 5637 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5638 } 5639 5640 SDValue 5641 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5642 SelectionDAG &DAG) const { 5643 unsigned Opc; 5644 switch (Op.getOpcode()) { 5645 default: llvm_unreachable("Unexpected opcode!"); 5646 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5647 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5648 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5649 } 5650 5651 return lowerToScalableOp(Op, DAG, Opc); 5652 } 5653 5654 // Lower vector ABS to smax(X, sub(0, X)). 5655 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5656 SDLoc DL(Op); 5657 MVT VT = Op.getSimpleValueType(); 5658 SDValue X = Op.getOperand(0); 5659 5660 assert(VT.isFixedLengthVector() && "Unexpected type"); 5661 5662 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5663 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5664 5665 SDValue Mask, VL; 5666 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5667 5668 SDValue SplatZero = 5669 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5670 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5671 SDValue NegX = 5672 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5673 SDValue Max = 5674 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5675 5676 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5677 } 5678 5679 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5680 SDValue Op, SelectionDAG &DAG) const { 5681 SDLoc DL(Op); 5682 MVT VT = Op.getSimpleValueType(); 5683 SDValue Mag = Op.getOperand(0); 5684 SDValue Sign = Op.getOperand(1); 5685 assert(Mag.getValueType() == Sign.getValueType() && 5686 "Can only handle COPYSIGN with matching types."); 5687 5688 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5689 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5690 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5691 5692 SDValue Mask, VL; 5693 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5694 5695 SDValue CopySign = 5696 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5697 5698 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5699 } 5700 5701 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5702 SDValue Op, SelectionDAG &DAG) const { 5703 MVT VT = Op.getSimpleValueType(); 5704 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5705 5706 MVT I1ContainerVT = 5707 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5708 5709 SDValue CC = 5710 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5711 SDValue Op1 = 5712 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5713 SDValue Op2 = 5714 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5715 5716 SDLoc DL(Op); 5717 SDValue Mask, VL; 5718 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5719 5720 SDValue Select = 5721 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5722 5723 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5724 } 5725 5726 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5727 unsigned NewOpc, 5728 bool HasMask) const { 5729 MVT VT = Op.getSimpleValueType(); 5730 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5731 5732 // Create list of operands by converting existing ones to scalable types. 5733 SmallVector<SDValue, 6> Ops; 5734 for (const SDValue &V : Op->op_values()) { 5735 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5736 5737 // Pass through non-vector operands. 5738 if (!V.getValueType().isVector()) { 5739 Ops.push_back(V); 5740 continue; 5741 } 5742 5743 // "cast" fixed length vector to a scalable vector. 5744 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5745 "Only fixed length vectors are supported!"); 5746 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5747 } 5748 5749 SDLoc DL(Op); 5750 SDValue Mask, VL; 5751 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5752 if (HasMask) 5753 Ops.push_back(Mask); 5754 Ops.push_back(VL); 5755 5756 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5757 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5758 } 5759 5760 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5761 // * Operands of each node are assumed to be in the same order. 5762 // * The EVL operand is promoted from i32 to i64 on RV64. 5763 // * Fixed-length vectors are converted to their scalable-vector container 5764 // types. 5765 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5766 unsigned RISCVISDOpc) const { 5767 SDLoc DL(Op); 5768 MVT VT = Op.getSimpleValueType(); 5769 SmallVector<SDValue, 4> Ops; 5770 5771 for (const auto &OpIdx : enumerate(Op->ops())) { 5772 SDValue V = OpIdx.value(); 5773 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5774 // Pass through operands which aren't fixed-length vectors. 5775 if (!V.getValueType().isFixedLengthVector()) { 5776 Ops.push_back(V); 5777 continue; 5778 } 5779 // "cast" fixed length vector to a scalable vector. 5780 MVT OpVT = V.getSimpleValueType(); 5781 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5782 assert(useRVVForFixedLengthVectorVT(OpVT) && 5783 "Only fixed length vectors are supported!"); 5784 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5785 } 5786 5787 if (!VT.isFixedLengthVector()) 5788 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5789 5790 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5791 5792 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5793 5794 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5795 } 5796 5797 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 5798 unsigned MaskOpc, 5799 unsigned VecOpc) const { 5800 MVT VT = Op.getSimpleValueType(); 5801 if (VT.getVectorElementType() != MVT::i1) 5802 return lowerVPOp(Op, DAG, VecOpc); 5803 5804 // It is safe to drop mask parameter as masked-off elements are undef. 5805 SDValue Op1 = Op->getOperand(0); 5806 SDValue Op2 = Op->getOperand(1); 5807 SDValue VL = Op->getOperand(3); 5808 5809 MVT ContainerVT = VT; 5810 const bool IsFixed = VT.isFixedLengthVector(); 5811 if (IsFixed) { 5812 ContainerVT = getContainerForFixedLengthVector(VT); 5813 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 5814 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 5815 } 5816 5817 SDLoc DL(Op); 5818 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 5819 if (!IsFixed) 5820 return Val; 5821 return convertFromScalableVector(VT, Val, DAG, Subtarget); 5822 } 5823 5824 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5825 // matched to a RVV indexed load. The RVV indexed load instructions only 5826 // support the "unsigned unscaled" addressing mode; indices are implicitly 5827 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5828 // signed or scaled indexing is extended to the XLEN value type and scaled 5829 // accordingly. 5830 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5831 SelectionDAG &DAG) const { 5832 SDLoc DL(Op); 5833 MVT VT = Op.getSimpleValueType(); 5834 5835 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5836 EVT MemVT = MemSD->getMemoryVT(); 5837 MachineMemOperand *MMO = MemSD->getMemOperand(); 5838 SDValue Chain = MemSD->getChain(); 5839 SDValue BasePtr = MemSD->getBasePtr(); 5840 5841 ISD::LoadExtType LoadExtType; 5842 SDValue Index, Mask, PassThru, VL; 5843 5844 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5845 Index = VPGN->getIndex(); 5846 Mask = VPGN->getMask(); 5847 PassThru = DAG.getUNDEF(VT); 5848 VL = VPGN->getVectorLength(); 5849 // VP doesn't support extending loads. 5850 LoadExtType = ISD::NON_EXTLOAD; 5851 } else { 5852 // Else it must be a MGATHER. 5853 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5854 Index = MGN->getIndex(); 5855 Mask = MGN->getMask(); 5856 PassThru = MGN->getPassThru(); 5857 LoadExtType = MGN->getExtensionType(); 5858 } 5859 5860 MVT IndexVT = Index.getSimpleValueType(); 5861 MVT XLenVT = Subtarget.getXLenVT(); 5862 5863 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5864 "Unexpected VTs!"); 5865 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5866 // Targets have to explicitly opt-in for extending vector loads. 5867 assert(LoadExtType == ISD::NON_EXTLOAD && 5868 "Unexpected extending MGATHER/VP_GATHER"); 5869 (void)LoadExtType; 5870 5871 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5872 // the selection of the masked intrinsics doesn't do this for us. 5873 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5874 5875 MVT ContainerVT = VT; 5876 if (VT.isFixedLengthVector()) { 5877 // We need to use the larger of the result and index type to determine the 5878 // scalable type to use so we don't increase LMUL for any operand/result. 5879 if (VT.bitsGE(IndexVT)) { 5880 ContainerVT = getContainerForFixedLengthVector(VT); 5881 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5882 ContainerVT.getVectorElementCount()); 5883 } else { 5884 IndexVT = getContainerForFixedLengthVector(IndexVT); 5885 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5886 IndexVT.getVectorElementCount()); 5887 } 5888 5889 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5890 5891 if (!IsUnmasked) { 5892 MVT MaskVT = 5893 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5894 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5895 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5896 } 5897 } 5898 5899 if (!VL) 5900 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5901 5902 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 5903 IndexVT = IndexVT.changeVectorElementType(XLenVT); 5904 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 5905 VL); 5906 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 5907 TrueMask, VL); 5908 } 5909 5910 unsigned IntID = 5911 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5912 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5913 if (IsUnmasked) 5914 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5915 else 5916 Ops.push_back(PassThru); 5917 Ops.push_back(BasePtr); 5918 Ops.push_back(Index); 5919 if (!IsUnmasked) 5920 Ops.push_back(Mask); 5921 Ops.push_back(VL); 5922 if (!IsUnmasked) 5923 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5924 5925 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5926 SDValue Result = 5927 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5928 Chain = Result.getValue(1); 5929 5930 if (VT.isFixedLengthVector()) 5931 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5932 5933 return DAG.getMergeValues({Result, Chain}, DL); 5934 } 5935 5936 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5937 // matched to a RVV indexed store. The RVV indexed store instructions only 5938 // support the "unsigned unscaled" addressing mode; indices are implicitly 5939 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5940 // signed or scaled indexing is extended to the XLEN value type and scaled 5941 // accordingly. 5942 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5943 SelectionDAG &DAG) const { 5944 SDLoc DL(Op); 5945 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5946 EVT MemVT = MemSD->getMemoryVT(); 5947 MachineMemOperand *MMO = MemSD->getMemOperand(); 5948 SDValue Chain = MemSD->getChain(); 5949 SDValue BasePtr = MemSD->getBasePtr(); 5950 5951 bool IsTruncatingStore = false; 5952 SDValue Index, Mask, Val, VL; 5953 5954 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5955 Index = VPSN->getIndex(); 5956 Mask = VPSN->getMask(); 5957 Val = VPSN->getValue(); 5958 VL = VPSN->getVectorLength(); 5959 // VP doesn't support truncating stores. 5960 IsTruncatingStore = false; 5961 } else { 5962 // Else it must be a MSCATTER. 5963 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5964 Index = MSN->getIndex(); 5965 Mask = MSN->getMask(); 5966 Val = MSN->getValue(); 5967 IsTruncatingStore = MSN->isTruncatingStore(); 5968 } 5969 5970 MVT VT = Val.getSimpleValueType(); 5971 MVT IndexVT = Index.getSimpleValueType(); 5972 MVT XLenVT = Subtarget.getXLenVT(); 5973 5974 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5975 "Unexpected VTs!"); 5976 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5977 // Targets have to explicitly opt-in for extending vector loads and 5978 // truncating vector stores. 5979 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5980 (void)IsTruncatingStore; 5981 5982 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5983 // the selection of the masked intrinsics doesn't do this for us. 5984 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5985 5986 MVT ContainerVT = VT; 5987 if (VT.isFixedLengthVector()) { 5988 // We need to use the larger of the value and index type to determine the 5989 // scalable type to use so we don't increase LMUL for any operand/result. 5990 if (VT.bitsGE(IndexVT)) { 5991 ContainerVT = getContainerForFixedLengthVector(VT); 5992 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5993 ContainerVT.getVectorElementCount()); 5994 } else { 5995 IndexVT = getContainerForFixedLengthVector(IndexVT); 5996 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 5997 IndexVT.getVectorElementCount()); 5998 } 5999 6000 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6001 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6002 6003 if (!IsUnmasked) { 6004 MVT MaskVT = 6005 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6006 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6007 } 6008 } 6009 6010 if (!VL) 6011 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6012 6013 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6014 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6015 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6016 VL); 6017 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6018 TrueMask, VL); 6019 } 6020 6021 unsigned IntID = 6022 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6023 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6024 Ops.push_back(Val); 6025 Ops.push_back(BasePtr); 6026 Ops.push_back(Index); 6027 if (!IsUnmasked) 6028 Ops.push_back(Mask); 6029 Ops.push_back(VL); 6030 6031 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6032 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6033 } 6034 6035 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6036 SelectionDAG &DAG) const { 6037 const MVT XLenVT = Subtarget.getXLenVT(); 6038 SDLoc DL(Op); 6039 SDValue Chain = Op->getOperand(0); 6040 SDValue SysRegNo = DAG.getTargetConstant( 6041 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6042 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6043 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6044 6045 // Encoding used for rounding mode in RISCV differs from that used in 6046 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6047 // table, which consists of a sequence of 4-bit fields, each representing 6048 // corresponding FLT_ROUNDS mode. 6049 static const int Table = 6050 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6051 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6052 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6053 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6054 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6055 6056 SDValue Shift = 6057 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6058 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6059 DAG.getConstant(Table, DL, XLenVT), Shift); 6060 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6061 DAG.getConstant(7, DL, XLenVT)); 6062 6063 return DAG.getMergeValues({Masked, Chain}, DL); 6064 } 6065 6066 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6067 SelectionDAG &DAG) const { 6068 const MVT XLenVT = Subtarget.getXLenVT(); 6069 SDLoc DL(Op); 6070 SDValue Chain = Op->getOperand(0); 6071 SDValue RMValue = Op->getOperand(1); 6072 SDValue SysRegNo = DAG.getTargetConstant( 6073 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6074 6075 // Encoding used for rounding mode in RISCV differs from that used in 6076 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6077 // a table, which consists of a sequence of 4-bit fields, each representing 6078 // corresponding RISCV mode. 6079 static const unsigned Table = 6080 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6081 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6082 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6083 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6084 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6085 6086 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6087 DAG.getConstant(2, DL, XLenVT)); 6088 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6089 DAG.getConstant(Table, DL, XLenVT), Shift); 6090 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6091 DAG.getConstant(0x7, DL, XLenVT)); 6092 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6093 RMValue); 6094 } 6095 6096 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6097 switch (IntNo) { 6098 default: 6099 llvm_unreachable("Unexpected Intrinsic"); 6100 case Intrinsic::riscv_grev: 6101 return RISCVISD::GREVW; 6102 case Intrinsic::riscv_gorc: 6103 return RISCVISD::GORCW; 6104 case Intrinsic::riscv_bcompress: 6105 return RISCVISD::BCOMPRESSW; 6106 case Intrinsic::riscv_bdecompress: 6107 return RISCVISD::BDECOMPRESSW; 6108 case Intrinsic::riscv_bfp: 6109 return RISCVISD::BFPW; 6110 case Intrinsic::riscv_fsl: 6111 return RISCVISD::FSLW; 6112 case Intrinsic::riscv_fsr: 6113 return RISCVISD::FSRW; 6114 } 6115 } 6116 6117 // Converts the given intrinsic to a i64 operation with any extension. 6118 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6119 unsigned IntNo) { 6120 SDLoc DL(N); 6121 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6122 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6123 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6124 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6125 // ReplaceNodeResults requires we maintain the same type for the return value. 6126 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6127 } 6128 6129 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6130 // form of the given Opcode. 6131 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6132 switch (Opcode) { 6133 default: 6134 llvm_unreachable("Unexpected opcode"); 6135 case ISD::SHL: 6136 return RISCVISD::SLLW; 6137 case ISD::SRA: 6138 return RISCVISD::SRAW; 6139 case ISD::SRL: 6140 return RISCVISD::SRLW; 6141 case ISD::SDIV: 6142 return RISCVISD::DIVW; 6143 case ISD::UDIV: 6144 return RISCVISD::DIVUW; 6145 case ISD::UREM: 6146 return RISCVISD::REMUW; 6147 case ISD::ROTL: 6148 return RISCVISD::ROLW; 6149 case ISD::ROTR: 6150 return RISCVISD::RORW; 6151 case RISCVISD::GREV: 6152 return RISCVISD::GREVW; 6153 case RISCVISD::GORC: 6154 return RISCVISD::GORCW; 6155 } 6156 } 6157 6158 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6159 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6160 // otherwise be promoted to i64, making it difficult to select the 6161 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6162 // type i8/i16/i32 is lost. 6163 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6164 unsigned ExtOpc = ISD::ANY_EXTEND) { 6165 SDLoc DL(N); 6166 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6167 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6168 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6169 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6170 // ReplaceNodeResults requires we maintain the same type for the return value. 6171 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6172 } 6173 6174 // Converts the given 32-bit operation to a i64 operation with signed extension 6175 // semantic to reduce the signed extension instructions. 6176 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6177 SDLoc DL(N); 6178 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6179 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6180 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6181 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6182 DAG.getValueType(MVT::i32)); 6183 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6184 } 6185 6186 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6187 SmallVectorImpl<SDValue> &Results, 6188 SelectionDAG &DAG) const { 6189 SDLoc DL(N); 6190 switch (N->getOpcode()) { 6191 default: 6192 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6193 case ISD::STRICT_FP_TO_SINT: 6194 case ISD::STRICT_FP_TO_UINT: 6195 case ISD::FP_TO_SINT: 6196 case ISD::FP_TO_UINT: { 6197 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6198 "Unexpected custom legalisation"); 6199 bool IsStrict = N->isStrictFPOpcode(); 6200 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6201 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6202 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6203 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6204 TargetLowering::TypeSoftenFloat) { 6205 if (!isTypeLegal(Op0.getValueType())) 6206 return; 6207 if (IsStrict) { 6208 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6209 : RISCVISD::STRICT_FCVT_WU_RV64; 6210 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6211 SDValue Res = DAG.getNode( 6212 Opc, DL, VTs, N->getOperand(0), Op0, 6213 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6214 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6215 Results.push_back(Res.getValue(1)); 6216 return; 6217 } 6218 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6219 SDValue Res = 6220 DAG.getNode(Opc, DL, MVT::i64, Op0, 6221 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6222 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6223 return; 6224 } 6225 // If the FP type needs to be softened, emit a library call using the 'si' 6226 // version. If we left it to default legalization we'd end up with 'di'. If 6227 // the FP type doesn't need to be softened just let generic type 6228 // legalization promote the result type. 6229 RTLIB::Libcall LC; 6230 if (IsSigned) 6231 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6232 else 6233 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6234 MakeLibCallOptions CallOptions; 6235 EVT OpVT = Op0.getValueType(); 6236 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6237 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6238 SDValue Result; 6239 std::tie(Result, Chain) = 6240 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6241 Results.push_back(Result); 6242 if (IsStrict) 6243 Results.push_back(Chain); 6244 break; 6245 } 6246 case ISD::READCYCLECOUNTER: { 6247 assert(!Subtarget.is64Bit() && 6248 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6249 6250 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6251 SDValue RCW = 6252 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6253 6254 Results.push_back( 6255 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6256 Results.push_back(RCW.getValue(2)); 6257 break; 6258 } 6259 case ISD::MUL: { 6260 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6261 unsigned XLen = Subtarget.getXLen(); 6262 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6263 if (Size > XLen) { 6264 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6265 SDValue LHS = N->getOperand(0); 6266 SDValue RHS = N->getOperand(1); 6267 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6268 6269 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6270 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6271 // We need exactly one side to be unsigned. 6272 if (LHSIsU == RHSIsU) 6273 return; 6274 6275 auto MakeMULPair = [&](SDValue S, SDValue U) { 6276 MVT XLenVT = Subtarget.getXLenVT(); 6277 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6278 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6279 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6280 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6281 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6282 }; 6283 6284 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6285 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6286 6287 // The other operand should be signed, but still prefer MULH when 6288 // possible. 6289 if (RHSIsU && LHSIsS && !RHSIsS) 6290 Results.push_back(MakeMULPair(LHS, RHS)); 6291 else if (LHSIsU && RHSIsS && !LHSIsS) 6292 Results.push_back(MakeMULPair(RHS, LHS)); 6293 6294 return; 6295 } 6296 LLVM_FALLTHROUGH; 6297 } 6298 case ISD::ADD: 6299 case ISD::SUB: 6300 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6301 "Unexpected custom legalisation"); 6302 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6303 break; 6304 case ISD::SHL: 6305 case ISD::SRA: 6306 case ISD::SRL: 6307 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6308 "Unexpected custom legalisation"); 6309 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6310 Results.push_back(customLegalizeToWOp(N, DAG)); 6311 break; 6312 } 6313 6314 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6315 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6316 // shift amount. 6317 if (N->getOpcode() == ISD::SHL) { 6318 SDLoc DL(N); 6319 SDValue NewOp0 = 6320 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6321 SDValue NewOp1 = 6322 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6323 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6324 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6325 DAG.getValueType(MVT::i32)); 6326 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6327 } 6328 6329 break; 6330 case ISD::ROTL: 6331 case ISD::ROTR: 6332 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6333 "Unexpected custom legalisation"); 6334 Results.push_back(customLegalizeToWOp(N, DAG)); 6335 break; 6336 case ISD::CTTZ: 6337 case ISD::CTTZ_ZERO_UNDEF: 6338 case ISD::CTLZ: 6339 case ISD::CTLZ_ZERO_UNDEF: { 6340 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6341 "Unexpected custom legalisation"); 6342 6343 SDValue NewOp0 = 6344 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6345 bool IsCTZ = 6346 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6347 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6348 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6349 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6350 return; 6351 } 6352 case ISD::SDIV: 6353 case ISD::UDIV: 6354 case ISD::UREM: { 6355 MVT VT = N->getSimpleValueType(0); 6356 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6357 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6358 "Unexpected custom legalisation"); 6359 // Don't promote division/remainder by constant since we should expand those 6360 // to multiply by magic constant. 6361 // FIXME: What if the expansion is disabled for minsize. 6362 if (N->getOperand(1).getOpcode() == ISD::Constant) 6363 return; 6364 6365 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6366 // the upper 32 bits. For other types we need to sign or zero extend 6367 // based on the opcode. 6368 unsigned ExtOpc = ISD::ANY_EXTEND; 6369 if (VT != MVT::i32) 6370 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6371 : ISD::ZERO_EXTEND; 6372 6373 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6374 break; 6375 } 6376 case ISD::UADDO: 6377 case ISD::USUBO: { 6378 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6379 "Unexpected custom legalisation"); 6380 bool IsAdd = N->getOpcode() == ISD::UADDO; 6381 // Create an ADDW or SUBW. 6382 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6383 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6384 SDValue Res = 6385 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6386 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6387 DAG.getValueType(MVT::i32)); 6388 6389 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6390 // Since the inputs are sign extended from i32, this is equivalent to 6391 // comparing the lower 32 bits. 6392 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6393 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6394 IsAdd ? ISD::SETULT : ISD::SETUGT); 6395 6396 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6397 Results.push_back(Overflow); 6398 return; 6399 } 6400 case ISD::UADDSAT: 6401 case ISD::USUBSAT: { 6402 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6403 "Unexpected custom legalisation"); 6404 if (Subtarget.hasStdExtZbb()) { 6405 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6406 // sign extend allows overflow of the lower 32 bits to be detected on 6407 // the promoted size. 6408 SDValue LHS = 6409 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6410 SDValue RHS = 6411 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6412 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6413 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6414 return; 6415 } 6416 6417 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6418 // promotion for UADDO/USUBO. 6419 Results.push_back(expandAddSubSat(N, DAG)); 6420 return; 6421 } 6422 case ISD::BITCAST: { 6423 EVT VT = N->getValueType(0); 6424 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6425 SDValue Op0 = N->getOperand(0); 6426 EVT Op0VT = Op0.getValueType(); 6427 MVT XLenVT = Subtarget.getXLenVT(); 6428 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6429 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6430 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6431 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6432 Subtarget.hasStdExtF()) { 6433 SDValue FPConv = 6434 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6435 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6436 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6437 isTypeLegal(Op0VT)) { 6438 // Custom-legalize bitcasts from fixed-length vector types to illegal 6439 // scalar types in order to improve codegen. Bitcast the vector to a 6440 // one-element vector type whose element type is the same as the result 6441 // type, and extract the first element. 6442 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6443 if (isTypeLegal(BVT)) { 6444 SDValue BVec = DAG.getBitcast(BVT, Op0); 6445 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6446 DAG.getConstant(0, DL, XLenVT))); 6447 } 6448 } 6449 break; 6450 } 6451 case RISCVISD::GREV: 6452 case RISCVISD::GORC: { 6453 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6454 "Unexpected custom legalisation"); 6455 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6456 // This is similar to customLegalizeToWOp, except that we pass the second 6457 // operand (a TargetConstant) straight through: it is already of type 6458 // XLenVT. 6459 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6460 SDValue NewOp0 = 6461 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6462 SDValue NewOp1 = 6463 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6464 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6465 // ReplaceNodeResults requires we maintain the same type for the return 6466 // value. 6467 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6468 break; 6469 } 6470 case RISCVISD::SHFL: { 6471 // There is no SHFLIW instruction, but we can just promote the operation. 6472 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6473 "Unexpected custom legalisation"); 6474 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6475 SDValue NewOp0 = 6476 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6477 SDValue NewOp1 = 6478 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6479 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6480 // ReplaceNodeResults requires we maintain the same type for the return 6481 // value. 6482 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6483 break; 6484 } 6485 case ISD::BSWAP: 6486 case ISD::BITREVERSE: { 6487 MVT VT = N->getSimpleValueType(0); 6488 MVT XLenVT = Subtarget.getXLenVT(); 6489 assert((VT == MVT::i8 || VT == MVT::i16 || 6490 (VT == MVT::i32 && Subtarget.is64Bit())) && 6491 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6492 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6493 unsigned Imm = VT.getSizeInBits() - 1; 6494 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6495 if (N->getOpcode() == ISD::BSWAP) 6496 Imm &= ~0x7U; 6497 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6498 SDValue GREVI = 6499 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6500 // ReplaceNodeResults requires we maintain the same type for the return 6501 // value. 6502 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6503 break; 6504 } 6505 case ISD::FSHL: 6506 case ISD::FSHR: { 6507 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6508 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6509 SDValue NewOp0 = 6510 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6511 SDValue NewOp1 = 6512 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6513 SDValue NewShAmt = 6514 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6515 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6516 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6517 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6518 DAG.getConstant(0x1f, DL, MVT::i64)); 6519 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6520 // instruction use different orders. fshl will return its first operand for 6521 // shift of zero, fshr will return its second operand. fsl and fsr both 6522 // return rs1 so the ISD nodes need to have different operand orders. 6523 // Shift amount is in rs2. 6524 unsigned Opc = RISCVISD::FSLW; 6525 if (N->getOpcode() == ISD::FSHR) { 6526 std::swap(NewOp0, NewOp1); 6527 Opc = RISCVISD::FSRW; 6528 } 6529 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6530 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6531 break; 6532 } 6533 case ISD::EXTRACT_VECTOR_ELT: { 6534 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6535 // type is illegal (currently only vXi64 RV32). 6536 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6537 // transferred to the destination register. We issue two of these from the 6538 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6539 // first element. 6540 SDValue Vec = N->getOperand(0); 6541 SDValue Idx = N->getOperand(1); 6542 6543 // The vector type hasn't been legalized yet so we can't issue target 6544 // specific nodes if it needs legalization. 6545 // FIXME: We would manually legalize if it's important. 6546 if (!isTypeLegal(Vec.getValueType())) 6547 return; 6548 6549 MVT VecVT = Vec.getSimpleValueType(); 6550 6551 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6552 VecVT.getVectorElementType() == MVT::i64 && 6553 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6554 6555 // If this is a fixed vector, we need to convert it to a scalable vector. 6556 MVT ContainerVT = VecVT; 6557 if (VecVT.isFixedLengthVector()) { 6558 ContainerVT = getContainerForFixedLengthVector(VecVT); 6559 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6560 } 6561 6562 MVT XLenVT = Subtarget.getXLenVT(); 6563 6564 // Use a VL of 1 to avoid processing more elements than we need. 6565 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6566 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6567 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6568 6569 // Unless the index is known to be 0, we must slide the vector down to get 6570 // the desired element into index 0. 6571 if (!isNullConstant(Idx)) { 6572 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6573 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6574 } 6575 6576 // Extract the lower XLEN bits of the correct vector element. 6577 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6578 6579 // To extract the upper XLEN bits of the vector element, shift the first 6580 // element right by 32 bits and re-extract the lower XLEN bits. 6581 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6582 DAG.getConstant(32, DL, XLenVT), VL); 6583 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6584 ThirtyTwoV, Mask, VL); 6585 6586 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6587 6588 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6589 break; 6590 } 6591 case ISD::INTRINSIC_WO_CHAIN: { 6592 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6593 switch (IntNo) { 6594 default: 6595 llvm_unreachable( 6596 "Don't know how to custom type legalize this intrinsic!"); 6597 case Intrinsic::riscv_grev: 6598 case Intrinsic::riscv_gorc: 6599 case Intrinsic::riscv_bcompress: 6600 case Intrinsic::riscv_bdecompress: 6601 case Intrinsic::riscv_bfp: { 6602 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6603 "Unexpected custom legalisation"); 6604 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6605 break; 6606 } 6607 case Intrinsic::riscv_fsl: 6608 case Intrinsic::riscv_fsr: { 6609 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6610 "Unexpected custom legalisation"); 6611 SDValue NewOp1 = 6612 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6613 SDValue NewOp2 = 6614 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6615 SDValue NewOp3 = 6616 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 6617 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 6618 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 6619 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6620 break; 6621 } 6622 case Intrinsic::riscv_orc_b: { 6623 // Lower to the GORCI encoding for orc.b with the operand extended. 6624 SDValue NewOp = 6625 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6626 // If Zbp is enabled, use GORCIW which will sign extend the result. 6627 unsigned Opc = 6628 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6629 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6630 DAG.getConstant(7, DL, MVT::i64)); 6631 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6632 return; 6633 } 6634 case Intrinsic::riscv_shfl: 6635 case Intrinsic::riscv_unshfl: { 6636 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6637 "Unexpected custom legalisation"); 6638 SDValue NewOp1 = 6639 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6640 SDValue NewOp2 = 6641 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6642 unsigned Opc = 6643 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6644 // There is no (UN)SHFLIW. If the control word is a constant, we can use 6645 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 6646 // will be shuffled the same way as the lower 32 bit half, but the two 6647 // halves won't cross. 6648 if (isa<ConstantSDNode>(NewOp2)) { 6649 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6650 DAG.getConstant(0xf, DL, MVT::i64)); 6651 Opc = 6652 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6653 } 6654 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6655 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6656 break; 6657 } 6658 case Intrinsic::riscv_vmv_x_s: { 6659 EVT VT = N->getValueType(0); 6660 MVT XLenVT = Subtarget.getXLenVT(); 6661 if (VT.bitsLT(XLenVT)) { 6662 // Simple case just extract using vmv.x.s and truncate. 6663 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6664 Subtarget.getXLenVT(), N->getOperand(1)); 6665 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6666 return; 6667 } 6668 6669 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6670 "Unexpected custom legalization"); 6671 6672 // We need to do the move in two steps. 6673 SDValue Vec = N->getOperand(1); 6674 MVT VecVT = Vec.getSimpleValueType(); 6675 6676 // First extract the lower XLEN bits of the element. 6677 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6678 6679 // To extract the upper XLEN bits of the vector element, shift the first 6680 // element right by 32 bits and re-extract the lower XLEN bits. 6681 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6682 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6683 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6684 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 6685 DAG.getConstant(32, DL, XLenVT), VL); 6686 SDValue LShr32 = 6687 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6688 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6689 6690 Results.push_back( 6691 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6692 break; 6693 } 6694 } 6695 break; 6696 } 6697 case ISD::VECREDUCE_ADD: 6698 case ISD::VECREDUCE_AND: 6699 case ISD::VECREDUCE_OR: 6700 case ISD::VECREDUCE_XOR: 6701 case ISD::VECREDUCE_SMAX: 6702 case ISD::VECREDUCE_UMAX: 6703 case ISD::VECREDUCE_SMIN: 6704 case ISD::VECREDUCE_UMIN: 6705 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6706 Results.push_back(V); 6707 break; 6708 case ISD::VP_REDUCE_ADD: 6709 case ISD::VP_REDUCE_AND: 6710 case ISD::VP_REDUCE_OR: 6711 case ISD::VP_REDUCE_XOR: 6712 case ISD::VP_REDUCE_SMAX: 6713 case ISD::VP_REDUCE_UMAX: 6714 case ISD::VP_REDUCE_SMIN: 6715 case ISD::VP_REDUCE_UMIN: 6716 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6717 Results.push_back(V); 6718 break; 6719 case ISD::FLT_ROUNDS_: { 6720 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6721 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6722 Results.push_back(Res.getValue(0)); 6723 Results.push_back(Res.getValue(1)); 6724 break; 6725 } 6726 } 6727 } 6728 6729 // A structure to hold one of the bit-manipulation patterns below. Together, a 6730 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6731 // (or (and (shl x, 1), 0xAAAAAAAA), 6732 // (and (srl x, 1), 0x55555555)) 6733 struct RISCVBitmanipPat { 6734 SDValue Op; 6735 unsigned ShAmt; 6736 bool IsSHL; 6737 6738 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6739 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6740 } 6741 }; 6742 6743 // Matches patterns of the form 6744 // (and (shl x, C2), (C1 << C2)) 6745 // (and (srl x, C2), C1) 6746 // (shl (and x, C1), C2) 6747 // (srl (and x, (C1 << C2)), C2) 6748 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6749 // The expected masks for each shift amount are specified in BitmanipMasks where 6750 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6751 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6752 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6753 // XLen is 64. 6754 static Optional<RISCVBitmanipPat> 6755 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6756 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6757 "Unexpected number of masks"); 6758 Optional<uint64_t> Mask; 6759 // Optionally consume a mask around the shift operation. 6760 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6761 Mask = Op.getConstantOperandVal(1); 6762 Op = Op.getOperand(0); 6763 } 6764 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6765 return None; 6766 bool IsSHL = Op.getOpcode() == ISD::SHL; 6767 6768 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6769 return None; 6770 uint64_t ShAmt = Op.getConstantOperandVal(1); 6771 6772 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6773 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6774 return None; 6775 // If we don't have enough masks for 64 bit, then we must be trying to 6776 // match SHFL so we're only allowed to shift 1/4 of the width. 6777 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6778 return None; 6779 6780 SDValue Src = Op.getOperand(0); 6781 6782 // The expected mask is shifted left when the AND is found around SHL 6783 // patterns. 6784 // ((x >> 1) & 0x55555555) 6785 // ((x << 1) & 0xAAAAAAAA) 6786 bool SHLExpMask = IsSHL; 6787 6788 if (!Mask) { 6789 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6790 // the mask is all ones: consume that now. 6791 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6792 Mask = Src.getConstantOperandVal(1); 6793 Src = Src.getOperand(0); 6794 // The expected mask is now in fact shifted left for SRL, so reverse the 6795 // decision. 6796 // ((x & 0xAAAAAAAA) >> 1) 6797 // ((x & 0x55555555) << 1) 6798 SHLExpMask = !SHLExpMask; 6799 } else { 6800 // Use a default shifted mask of all-ones if there's no AND, truncated 6801 // down to the expected width. This simplifies the logic later on. 6802 Mask = maskTrailingOnes<uint64_t>(Width); 6803 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6804 } 6805 } 6806 6807 unsigned MaskIdx = Log2_32(ShAmt); 6808 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6809 6810 if (SHLExpMask) 6811 ExpMask <<= ShAmt; 6812 6813 if (Mask != ExpMask) 6814 return None; 6815 6816 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6817 } 6818 6819 // Matches any of the following bit-manipulation patterns: 6820 // (and (shl x, 1), (0x55555555 << 1)) 6821 // (and (srl x, 1), 0x55555555) 6822 // (shl (and x, 0x55555555), 1) 6823 // (srl (and x, (0x55555555 << 1)), 1) 6824 // where the shift amount and mask may vary thus: 6825 // [1] = 0x55555555 / 0xAAAAAAAA 6826 // [2] = 0x33333333 / 0xCCCCCCCC 6827 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6828 // [8] = 0x00FF00FF / 0xFF00FF00 6829 // [16] = 0x0000FFFF / 0xFFFFFFFF 6830 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6831 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6832 // These are the unshifted masks which we use to match bit-manipulation 6833 // patterns. They may be shifted left in certain circumstances. 6834 static const uint64_t BitmanipMasks[] = { 6835 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6836 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6837 6838 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6839 } 6840 6841 // Match the following pattern as a GREVI(W) operation 6842 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6843 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6844 const RISCVSubtarget &Subtarget) { 6845 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6846 EVT VT = Op.getValueType(); 6847 6848 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6849 auto LHS = matchGREVIPat(Op.getOperand(0)); 6850 auto RHS = matchGREVIPat(Op.getOperand(1)); 6851 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6852 SDLoc DL(Op); 6853 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6854 DAG.getConstant(LHS->ShAmt, DL, VT)); 6855 } 6856 } 6857 return SDValue(); 6858 } 6859 6860 // Matches any the following pattern as a GORCI(W) operation 6861 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6862 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6863 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6864 // Note that with the variant of 3., 6865 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6866 // the inner pattern will first be matched as GREVI and then the outer 6867 // pattern will be matched to GORC via the first rule above. 6868 // 4. (or (rotl/rotr x, bitwidth/2), x) 6869 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6870 const RISCVSubtarget &Subtarget) { 6871 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6872 EVT VT = Op.getValueType(); 6873 6874 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6875 SDLoc DL(Op); 6876 SDValue Op0 = Op.getOperand(0); 6877 SDValue Op1 = Op.getOperand(1); 6878 6879 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6880 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6881 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6882 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6883 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6884 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6885 if ((Reverse.getOpcode() == ISD::ROTL || 6886 Reverse.getOpcode() == ISD::ROTR) && 6887 Reverse.getOperand(0) == X && 6888 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6889 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6890 if (RotAmt == (VT.getSizeInBits() / 2)) 6891 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6892 DAG.getConstant(RotAmt, DL, VT)); 6893 } 6894 return SDValue(); 6895 }; 6896 6897 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6898 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6899 return V; 6900 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6901 return V; 6902 6903 // OR is commutable so canonicalize its OR operand to the left 6904 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6905 std::swap(Op0, Op1); 6906 if (Op0.getOpcode() != ISD::OR) 6907 return SDValue(); 6908 SDValue OrOp0 = Op0.getOperand(0); 6909 SDValue OrOp1 = Op0.getOperand(1); 6910 auto LHS = matchGREVIPat(OrOp0); 6911 // OR is commutable so swap the operands and try again: x might have been 6912 // on the left 6913 if (!LHS) { 6914 std::swap(OrOp0, OrOp1); 6915 LHS = matchGREVIPat(OrOp0); 6916 } 6917 auto RHS = matchGREVIPat(Op1); 6918 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6919 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6920 DAG.getConstant(LHS->ShAmt, DL, VT)); 6921 } 6922 } 6923 return SDValue(); 6924 } 6925 6926 // Matches any of the following bit-manipulation patterns: 6927 // (and (shl x, 1), (0x22222222 << 1)) 6928 // (and (srl x, 1), 0x22222222) 6929 // (shl (and x, 0x22222222), 1) 6930 // (srl (and x, (0x22222222 << 1)), 1) 6931 // where the shift amount and mask may vary thus: 6932 // [1] = 0x22222222 / 0x44444444 6933 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6934 // [4] = 0x00F000F0 / 0x0F000F00 6935 // [8] = 0x0000FF00 / 0x00FF0000 6936 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6937 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6938 // These are the unshifted masks which we use to match bit-manipulation 6939 // patterns. They may be shifted left in certain circumstances. 6940 static const uint64_t BitmanipMasks[] = { 6941 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6942 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6943 6944 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6945 } 6946 6947 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6948 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6949 const RISCVSubtarget &Subtarget) { 6950 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6951 EVT VT = Op.getValueType(); 6952 6953 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6954 return SDValue(); 6955 6956 SDValue Op0 = Op.getOperand(0); 6957 SDValue Op1 = Op.getOperand(1); 6958 6959 // Or is commutable so canonicalize the second OR to the LHS. 6960 if (Op0.getOpcode() != ISD::OR) 6961 std::swap(Op0, Op1); 6962 if (Op0.getOpcode() != ISD::OR) 6963 return SDValue(); 6964 6965 // We found an inner OR, so our operands are the operands of the inner OR 6966 // and the other operand of the outer OR. 6967 SDValue A = Op0.getOperand(0); 6968 SDValue B = Op0.getOperand(1); 6969 SDValue C = Op1; 6970 6971 auto Match1 = matchSHFLPat(A); 6972 auto Match2 = matchSHFLPat(B); 6973 6974 // If neither matched, we failed. 6975 if (!Match1 && !Match2) 6976 return SDValue(); 6977 6978 // We had at least one match. if one failed, try the remaining C operand. 6979 if (!Match1) { 6980 std::swap(A, C); 6981 Match1 = matchSHFLPat(A); 6982 if (!Match1) 6983 return SDValue(); 6984 } else if (!Match2) { 6985 std::swap(B, C); 6986 Match2 = matchSHFLPat(B); 6987 if (!Match2) 6988 return SDValue(); 6989 } 6990 assert(Match1 && Match2); 6991 6992 // Make sure our matches pair up. 6993 if (!Match1->formsPairWith(*Match2)) 6994 return SDValue(); 6995 6996 // All the remains is to make sure C is an AND with the same input, that masks 6997 // out the bits that are being shuffled. 6998 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 6999 C.getOperand(0) != Match1->Op) 7000 return SDValue(); 7001 7002 uint64_t Mask = C.getConstantOperandVal(1); 7003 7004 static const uint64_t BitmanipMasks[] = { 7005 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7006 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7007 }; 7008 7009 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7010 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7011 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7012 7013 if (Mask != ExpMask) 7014 return SDValue(); 7015 7016 SDLoc DL(Op); 7017 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7018 DAG.getConstant(Match1->ShAmt, DL, VT)); 7019 } 7020 7021 // Optimize (add (shl x, c0), (shl y, c1)) -> 7022 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7023 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7024 const RISCVSubtarget &Subtarget) { 7025 // Perform this optimization only in the zba extension. 7026 if (!Subtarget.hasStdExtZba()) 7027 return SDValue(); 7028 7029 // Skip for vector types and larger types. 7030 EVT VT = N->getValueType(0); 7031 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7032 return SDValue(); 7033 7034 // The two operand nodes must be SHL and have no other use. 7035 SDValue N0 = N->getOperand(0); 7036 SDValue N1 = N->getOperand(1); 7037 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7038 !N0->hasOneUse() || !N1->hasOneUse()) 7039 return SDValue(); 7040 7041 // Check c0 and c1. 7042 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7043 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7044 if (!N0C || !N1C) 7045 return SDValue(); 7046 int64_t C0 = N0C->getSExtValue(); 7047 int64_t C1 = N1C->getSExtValue(); 7048 if (C0 <= 0 || C1 <= 0) 7049 return SDValue(); 7050 7051 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7052 int64_t Bits = std::min(C0, C1); 7053 int64_t Diff = std::abs(C0 - C1); 7054 if (Diff != 1 && Diff != 2 && Diff != 3) 7055 return SDValue(); 7056 7057 // Build nodes. 7058 SDLoc DL(N); 7059 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7060 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7061 SDValue NA0 = 7062 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7063 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7064 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7065 } 7066 7067 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7068 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7069 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7070 // not undo itself, but they are redundant. 7071 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7072 SDValue Src = N->getOperand(0); 7073 7074 if (Src.getOpcode() != N->getOpcode()) 7075 return SDValue(); 7076 7077 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7078 !isa<ConstantSDNode>(Src.getOperand(1))) 7079 return SDValue(); 7080 7081 unsigned ShAmt1 = N->getConstantOperandVal(1); 7082 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7083 Src = Src.getOperand(0); 7084 7085 unsigned CombinedShAmt; 7086 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 7087 CombinedShAmt = ShAmt1 | ShAmt2; 7088 else 7089 CombinedShAmt = ShAmt1 ^ ShAmt2; 7090 7091 if (CombinedShAmt == 0) 7092 return Src; 7093 7094 SDLoc DL(N); 7095 return DAG.getNode( 7096 N->getOpcode(), DL, N->getValueType(0), Src, 7097 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7098 } 7099 7100 // Combine a constant select operand into its use: 7101 // 7102 // (and (select cond, -1, c), x) 7103 // -> (select cond, x, (and x, c)) [AllOnes=1] 7104 // (or (select cond, 0, c), x) 7105 // -> (select cond, x, (or x, c)) [AllOnes=0] 7106 // (xor (select cond, 0, c), x) 7107 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7108 // (add (select cond, 0, c), x) 7109 // -> (select cond, x, (add x, c)) [AllOnes=0] 7110 // (sub x, (select cond, 0, c)) 7111 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7112 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7113 SelectionDAG &DAG, bool AllOnes) { 7114 EVT VT = N->getValueType(0); 7115 7116 // Skip vectors. 7117 if (VT.isVector()) 7118 return SDValue(); 7119 7120 if ((Slct.getOpcode() != ISD::SELECT && 7121 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7122 !Slct.hasOneUse()) 7123 return SDValue(); 7124 7125 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7126 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7127 }; 7128 7129 bool SwapSelectOps; 7130 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7131 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7132 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7133 SDValue NonConstantVal; 7134 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7135 SwapSelectOps = false; 7136 NonConstantVal = FalseVal; 7137 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7138 SwapSelectOps = true; 7139 NonConstantVal = TrueVal; 7140 } else 7141 return SDValue(); 7142 7143 // Slct is now know to be the desired identity constant when CC is true. 7144 TrueVal = OtherOp; 7145 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7146 // Unless SwapSelectOps says the condition should be false. 7147 if (SwapSelectOps) 7148 std::swap(TrueVal, FalseVal); 7149 7150 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7151 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7152 {Slct.getOperand(0), Slct.getOperand(1), 7153 Slct.getOperand(2), TrueVal, FalseVal}); 7154 7155 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7156 {Slct.getOperand(0), TrueVal, FalseVal}); 7157 } 7158 7159 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7160 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7161 bool AllOnes) { 7162 SDValue N0 = N->getOperand(0); 7163 SDValue N1 = N->getOperand(1); 7164 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7165 return Result; 7166 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7167 return Result; 7168 return SDValue(); 7169 } 7170 7171 // Transform (add (mul x, c0), c1) -> 7172 // (add (mul (add x, c1/c0), c0), c1%c0). 7173 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7174 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7175 // to an infinite loop in DAGCombine if transformed. 7176 // Or transform (add (mul x, c0), c1) -> 7177 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7178 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7179 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7180 // lead to an infinite loop in DAGCombine if transformed. 7181 // Or transform (add (mul x, c0), c1) -> 7182 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7183 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7184 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7185 // lead to an infinite loop in DAGCombine if transformed. 7186 // Or transform (add (mul x, c0), c1) -> 7187 // (mul (add x, c1/c0), c0). 7188 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7189 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7190 const RISCVSubtarget &Subtarget) { 7191 // Skip for vector types and larger types. 7192 EVT VT = N->getValueType(0); 7193 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7194 return SDValue(); 7195 // The first operand node must be a MUL and has no other use. 7196 SDValue N0 = N->getOperand(0); 7197 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7198 return SDValue(); 7199 // Check if c0 and c1 match above conditions. 7200 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7201 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7202 if (!N0C || !N1C) 7203 return SDValue(); 7204 int64_t C0 = N0C->getSExtValue(); 7205 int64_t C1 = N1C->getSExtValue(); 7206 int64_t CA, CB; 7207 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7208 return SDValue(); 7209 // Search for proper CA (non-zero) and CB that both are simm12. 7210 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7211 !isInt<12>(C0 * (C1 / C0))) { 7212 CA = C1 / C0; 7213 CB = C1 % C0; 7214 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7215 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7216 CA = C1 / C0 + 1; 7217 CB = C1 % C0 - C0; 7218 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7219 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7220 CA = C1 / C0 - 1; 7221 CB = C1 % C0 + C0; 7222 } else 7223 return SDValue(); 7224 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7225 SDLoc DL(N); 7226 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7227 DAG.getConstant(CA, DL, VT)); 7228 SDValue New1 = 7229 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7230 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7231 } 7232 7233 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7234 const RISCVSubtarget &Subtarget) { 7235 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7236 return V; 7237 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7238 return V; 7239 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7240 // (select lhs, rhs, cc, x, (add x, y)) 7241 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7242 } 7243 7244 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7245 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7246 // (select lhs, rhs, cc, x, (sub x, y)) 7247 SDValue N0 = N->getOperand(0); 7248 SDValue N1 = N->getOperand(1); 7249 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7250 } 7251 7252 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7253 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7254 // (select lhs, rhs, cc, x, (and x, y)) 7255 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7256 } 7257 7258 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7259 const RISCVSubtarget &Subtarget) { 7260 if (Subtarget.hasStdExtZbp()) { 7261 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7262 return GREV; 7263 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7264 return GORC; 7265 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7266 return SHFL; 7267 } 7268 7269 // fold (or (select cond, 0, y), x) -> 7270 // (select cond, x, (or x, y)) 7271 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7272 } 7273 7274 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7275 // fold (xor (select cond, 0, y), x) -> 7276 // (select cond, x, (xor x, y)) 7277 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7278 } 7279 7280 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 7281 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 7282 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 7283 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 7284 // ADDW/SUBW/MULW. 7285 static SDValue performANY_EXTENDCombine(SDNode *N, 7286 TargetLowering::DAGCombinerInfo &DCI, 7287 const RISCVSubtarget &Subtarget) { 7288 if (!Subtarget.is64Bit()) 7289 return SDValue(); 7290 7291 SelectionDAG &DAG = DCI.DAG; 7292 7293 SDValue Src = N->getOperand(0); 7294 EVT VT = N->getValueType(0); 7295 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 7296 return SDValue(); 7297 7298 // The opcode must be one that can implicitly sign_extend. 7299 // FIXME: Additional opcodes. 7300 switch (Src.getOpcode()) { 7301 default: 7302 return SDValue(); 7303 case ISD::MUL: 7304 if (!Subtarget.hasStdExtM()) 7305 return SDValue(); 7306 LLVM_FALLTHROUGH; 7307 case ISD::ADD: 7308 case ISD::SUB: 7309 break; 7310 } 7311 7312 // Only handle cases where the result is used by a CopyToReg. That likely 7313 // means the value is a liveout of the basic block. This helps prevent 7314 // infinite combine loops like PR51206. 7315 if (none_of(N->uses(), 7316 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 7317 return SDValue(); 7318 7319 SmallVector<SDNode *, 4> SetCCs; 7320 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 7321 UE = Src.getNode()->use_end(); 7322 UI != UE; ++UI) { 7323 SDNode *User = *UI; 7324 if (User == N) 7325 continue; 7326 if (UI.getUse().getResNo() != Src.getResNo()) 7327 continue; 7328 // All i32 setccs are legalized by sign extending operands. 7329 if (User->getOpcode() == ISD::SETCC) { 7330 SetCCs.push_back(User); 7331 continue; 7332 } 7333 // We don't know if we can extend this user. 7334 break; 7335 } 7336 7337 // If we don't have any SetCCs, this isn't worthwhile. 7338 if (SetCCs.empty()) 7339 return SDValue(); 7340 7341 SDLoc DL(N); 7342 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 7343 DCI.CombineTo(N, SExt); 7344 7345 // Promote all the setccs. 7346 for (SDNode *SetCC : SetCCs) { 7347 SmallVector<SDValue, 4> Ops; 7348 7349 for (unsigned j = 0; j != 2; ++j) { 7350 SDValue SOp = SetCC->getOperand(j); 7351 if (SOp == Src) 7352 Ops.push_back(SExt); 7353 else 7354 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 7355 } 7356 7357 Ops.push_back(SetCC->getOperand(2)); 7358 DCI.CombineTo(SetCC, 7359 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7360 } 7361 return SDValue(N, 0); 7362 } 7363 7364 // Try to form VWMUL, VWMULU or VWMULSU. 7365 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 7366 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 7367 bool Commute) { 7368 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7369 SDValue Op0 = N->getOperand(0); 7370 SDValue Op1 = N->getOperand(1); 7371 if (Commute) 7372 std::swap(Op0, Op1); 7373 7374 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7375 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7376 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 7377 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7378 return SDValue(); 7379 7380 SDValue Mask = N->getOperand(2); 7381 SDValue VL = N->getOperand(3); 7382 7383 // Make sure the mask and VL match. 7384 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7385 return SDValue(); 7386 7387 MVT VT = N->getSimpleValueType(0); 7388 7389 // Determine the narrow size for a widening multiply. 7390 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7391 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7392 VT.getVectorElementCount()); 7393 7394 SDLoc DL(N); 7395 7396 // See if the other operand is the same opcode. 7397 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 7398 if (!Op1.hasOneUse()) 7399 return SDValue(); 7400 7401 // Make sure the mask and VL match. 7402 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7403 return SDValue(); 7404 7405 Op1 = Op1.getOperand(0); 7406 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7407 // The operand is a splat of a scalar. 7408 7409 // The VL must be the same. 7410 if (Op1.getOperand(1) != VL) 7411 return SDValue(); 7412 7413 // Get the scalar value. 7414 Op1 = Op1.getOperand(0); 7415 7416 // See if have enough sign bits or zero bits in the scalar to use a 7417 // widening multiply by splatting to smaller element size. 7418 unsigned EltBits = VT.getScalarSizeInBits(); 7419 unsigned ScalarBits = Op1.getValueSizeInBits(); 7420 // Make sure we're getting all element bits from the scalar register. 7421 // FIXME: Support implicit sign extension of vmv.v.x? 7422 if (ScalarBits < EltBits) 7423 return SDValue(); 7424 7425 if (IsSignExt) { 7426 if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize)) 7427 return SDValue(); 7428 } else { 7429 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7430 if (!DAG.MaskedValueIsZero(Op1, Mask)) 7431 return SDValue(); 7432 } 7433 7434 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 7435 } else 7436 return SDValue(); 7437 7438 Op0 = Op0.getOperand(0); 7439 7440 // Re-introduce narrower extends if needed. 7441 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7442 if (Op0.getValueType() != NarrowVT) 7443 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7444 if (Op1.getValueType() != NarrowVT) 7445 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7446 7447 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 7448 if (!IsVWMULSU) 7449 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7450 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7451 } 7452 7453 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 7454 switch (Op.getOpcode()) { 7455 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 7456 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 7457 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 7458 case ISD::FCEIL: return RISCVFPRndMode::RUP; 7459 case ISD::FROUND: return RISCVFPRndMode::RMM; 7460 } 7461 7462 return RISCVFPRndMode::Invalid; 7463 } 7464 7465 // Fold 7466 // (fp_to_int (froundeven X)) -> fcvt X, rne 7467 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7468 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7469 // (fp_to_int (fceil X)) -> fcvt X, rup 7470 // (fp_to_int (fround X)) -> fcvt X, rmm 7471 static SDValue performFP_TO_INTCombine(SDNode *N, 7472 TargetLowering::DAGCombinerInfo &DCI, 7473 const RISCVSubtarget &Subtarget) { 7474 SelectionDAG &DAG = DCI.DAG; 7475 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7476 MVT XLenVT = Subtarget.getXLenVT(); 7477 7478 // Only handle XLen or i32 types. Other types narrower than XLen will 7479 // eventually be legalized to XLenVT. 7480 EVT VT = N->getValueType(0); 7481 if (VT != MVT::i32 && VT != XLenVT) 7482 return SDValue(); 7483 7484 SDValue Src = N->getOperand(0); 7485 7486 // Ensure the FP type is also legal. 7487 if (!TLI.isTypeLegal(Src.getValueType())) 7488 return SDValue(); 7489 7490 // Don't do this for f16 with Zfhmin and not Zfh. 7491 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7492 return SDValue(); 7493 7494 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7495 if (FRM == RISCVFPRndMode::Invalid) 7496 return SDValue(); 7497 7498 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7499 7500 unsigned Opc; 7501 if (VT == XLenVT) 7502 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7503 else 7504 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7505 7506 SDLoc DL(N); 7507 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 7508 DAG.getTargetConstant(FRM, DL, XLenVT)); 7509 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 7510 } 7511 7512 // Fold 7513 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 7514 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 7515 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 7516 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 7517 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 7518 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 7519 TargetLowering::DAGCombinerInfo &DCI, 7520 const RISCVSubtarget &Subtarget) { 7521 SelectionDAG &DAG = DCI.DAG; 7522 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7523 MVT XLenVT = Subtarget.getXLenVT(); 7524 7525 // Only handle XLen types. Other types narrower than XLen will eventually be 7526 // legalized to XLenVT. 7527 EVT DstVT = N->getValueType(0); 7528 if (DstVT != XLenVT) 7529 return SDValue(); 7530 7531 SDValue Src = N->getOperand(0); 7532 7533 // Ensure the FP type is also legal. 7534 if (!TLI.isTypeLegal(Src.getValueType())) 7535 return SDValue(); 7536 7537 // Don't do this for f16 with Zfhmin and not Zfh. 7538 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7539 return SDValue(); 7540 7541 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7542 7543 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7544 if (FRM == RISCVFPRndMode::Invalid) 7545 return SDValue(); 7546 7547 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 7548 7549 unsigned Opc; 7550 if (SatVT == DstVT) 7551 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7552 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 7553 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7554 else 7555 return SDValue(); 7556 // FIXME: Support other SatVTs by clamping before or after the conversion. 7557 7558 Src = Src.getOperand(0); 7559 7560 SDLoc DL(N); 7561 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 7562 DAG.getTargetConstant(FRM, DL, XLenVT)); 7563 7564 // RISCV FP-to-int conversions saturate to the destination register size, but 7565 // don't produce 0 for nan. 7566 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 7567 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 7568 } 7569 7570 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 7571 DAGCombinerInfo &DCI) const { 7572 SelectionDAG &DAG = DCI.DAG; 7573 7574 // Helper to call SimplifyDemandedBits on an operand of N where only some low 7575 // bits are demanded. N will be added to the Worklist if it was not deleted. 7576 // Caller should return SDValue(N, 0) if this returns true. 7577 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 7578 SDValue Op = N->getOperand(OpNo); 7579 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 7580 if (!SimplifyDemandedBits(Op, Mask, DCI)) 7581 return false; 7582 7583 if (N->getOpcode() != ISD::DELETED_NODE) 7584 DCI.AddToWorklist(N); 7585 return true; 7586 }; 7587 7588 switch (N->getOpcode()) { 7589 default: 7590 break; 7591 case RISCVISD::SplitF64: { 7592 SDValue Op0 = N->getOperand(0); 7593 // If the input to SplitF64 is just BuildPairF64 then the operation is 7594 // redundant. Instead, use BuildPairF64's operands directly. 7595 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 7596 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 7597 7598 SDLoc DL(N); 7599 7600 // It's cheaper to materialise two 32-bit integers than to load a double 7601 // from the constant pool and transfer it to integer registers through the 7602 // stack. 7603 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 7604 APInt V = C->getValueAPF().bitcastToAPInt(); 7605 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 7606 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 7607 return DCI.CombineTo(N, Lo, Hi); 7608 } 7609 7610 // This is a target-specific version of a DAGCombine performed in 7611 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7612 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7613 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7614 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7615 !Op0.getNode()->hasOneUse()) 7616 break; 7617 SDValue NewSplitF64 = 7618 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 7619 Op0.getOperand(0)); 7620 SDValue Lo = NewSplitF64.getValue(0); 7621 SDValue Hi = NewSplitF64.getValue(1); 7622 APInt SignBit = APInt::getSignMask(32); 7623 if (Op0.getOpcode() == ISD::FNEG) { 7624 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 7625 DAG.getConstant(SignBit, DL, MVT::i32)); 7626 return DCI.CombineTo(N, Lo, NewHi); 7627 } 7628 assert(Op0.getOpcode() == ISD::FABS); 7629 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 7630 DAG.getConstant(~SignBit, DL, MVT::i32)); 7631 return DCI.CombineTo(N, Lo, NewHi); 7632 } 7633 case RISCVISD::SLLW: 7634 case RISCVISD::SRAW: 7635 case RISCVISD::SRLW: 7636 case RISCVISD::ROLW: 7637 case RISCVISD::RORW: { 7638 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7639 if (SimplifyDemandedLowBitsHelper(0, 32) || 7640 SimplifyDemandedLowBitsHelper(1, 5)) 7641 return SDValue(N, 0); 7642 break; 7643 } 7644 case RISCVISD::CLZW: 7645 case RISCVISD::CTZW: { 7646 // Only the lower 32 bits of the first operand are read 7647 if (SimplifyDemandedLowBitsHelper(0, 32)) 7648 return SDValue(N, 0); 7649 break; 7650 } 7651 case RISCVISD::GREV: 7652 case RISCVISD::GORC: { 7653 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 7654 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7655 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7656 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 7657 return SDValue(N, 0); 7658 7659 return combineGREVI_GORCI(N, DAG); 7660 } 7661 case RISCVISD::GREVW: 7662 case RISCVISD::GORCW: { 7663 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7664 if (SimplifyDemandedLowBitsHelper(0, 32) || 7665 SimplifyDemandedLowBitsHelper(1, 5)) 7666 return SDValue(N, 0); 7667 7668 return combineGREVI_GORCI(N, DAG); 7669 } 7670 case RISCVISD::SHFL: 7671 case RISCVISD::UNSHFL: { 7672 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 7673 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7674 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7675 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 7676 return SDValue(N, 0); 7677 7678 break; 7679 } 7680 case RISCVISD::SHFLW: 7681 case RISCVISD::UNSHFLW: { 7682 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 7683 SDValue LHS = N->getOperand(0); 7684 SDValue RHS = N->getOperand(1); 7685 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 7686 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4); 7687 if (SimplifyDemandedLowBitsHelper(0, 32) || 7688 SimplifyDemandedLowBitsHelper(1, 4)) 7689 return SDValue(N, 0); 7690 7691 break; 7692 } 7693 case RISCVISD::BCOMPRESSW: 7694 case RISCVISD::BDECOMPRESSW: { 7695 // Only the lower 32 bits of LHS and RHS are read. 7696 if (SimplifyDemandedLowBitsHelper(0, 32) || 7697 SimplifyDemandedLowBitsHelper(1, 32)) 7698 return SDValue(N, 0); 7699 7700 break; 7701 } 7702 case RISCVISD::FMV_X_ANYEXTH: 7703 case RISCVISD::FMV_X_ANYEXTW_RV64: { 7704 SDLoc DL(N); 7705 SDValue Op0 = N->getOperand(0); 7706 MVT VT = N->getSimpleValueType(0); 7707 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 7708 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 7709 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 7710 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 7711 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 7712 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7713 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 7714 assert(Op0.getOperand(0).getValueType() == VT && 7715 "Unexpected value type!"); 7716 return Op0.getOperand(0); 7717 } 7718 7719 // This is a target-specific version of a DAGCombine performed in 7720 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7721 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7722 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7723 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7724 !Op0.getNode()->hasOneUse()) 7725 break; 7726 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 7727 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 7728 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 7729 if (Op0.getOpcode() == ISD::FNEG) 7730 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 7731 DAG.getConstant(SignBit, DL, VT)); 7732 7733 assert(Op0.getOpcode() == ISD::FABS); 7734 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 7735 DAG.getConstant(~SignBit, DL, VT)); 7736 } 7737 case ISD::ADD: 7738 return performADDCombine(N, DAG, Subtarget); 7739 case ISD::SUB: 7740 return performSUBCombine(N, DAG); 7741 case ISD::AND: 7742 return performANDCombine(N, DAG); 7743 case ISD::OR: 7744 return performORCombine(N, DAG, Subtarget); 7745 case ISD::XOR: 7746 return performXORCombine(N, DAG); 7747 case ISD::ANY_EXTEND: 7748 return performANY_EXTENDCombine(N, DCI, Subtarget); 7749 case ISD::ZERO_EXTEND: 7750 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 7751 // type legalization. This is safe because fp_to_uint produces poison if 7752 // it overflows. 7753 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 7754 SDValue Src = N->getOperand(0); 7755 if (Src.getOpcode() == ISD::FP_TO_UINT && 7756 isTypeLegal(Src.getOperand(0).getValueType())) 7757 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 7758 Src.getOperand(0)); 7759 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 7760 isTypeLegal(Src.getOperand(1).getValueType())) { 7761 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 7762 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 7763 Src.getOperand(0), Src.getOperand(1)); 7764 DCI.CombineTo(N, Res); 7765 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 7766 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 7767 return SDValue(N, 0); // Return N so it doesn't get rechecked. 7768 } 7769 } 7770 return SDValue(); 7771 case RISCVISD::SELECT_CC: { 7772 // Transform 7773 SDValue LHS = N->getOperand(0); 7774 SDValue RHS = N->getOperand(1); 7775 SDValue TrueV = N->getOperand(3); 7776 SDValue FalseV = N->getOperand(4); 7777 7778 // If the True and False values are the same, we don't need a select_cc. 7779 if (TrueV == FalseV) 7780 return TrueV; 7781 7782 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 7783 if (!ISD::isIntEqualitySetCC(CCVal)) 7784 break; 7785 7786 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 7787 // (select_cc X, Y, lt, trueV, falseV) 7788 // Sometimes the setcc is introduced after select_cc has been formed. 7789 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7790 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7791 // If we're looking for eq 0 instead of ne 0, we need to invert the 7792 // condition. 7793 bool Invert = CCVal == ISD::SETEQ; 7794 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7795 if (Invert) 7796 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7797 7798 SDLoc DL(N); 7799 RHS = LHS.getOperand(1); 7800 LHS = LHS.getOperand(0); 7801 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7802 7803 SDValue TargetCC = DAG.getCondCode(CCVal); 7804 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7805 {LHS, RHS, TargetCC, TrueV, FalseV}); 7806 } 7807 7808 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 7809 // (select_cc X, Y, eq/ne, trueV, falseV) 7810 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7811 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 7812 {LHS.getOperand(0), LHS.getOperand(1), 7813 N->getOperand(2), TrueV, FalseV}); 7814 // (select_cc X, 1, setne, trueV, falseV) -> 7815 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 7816 // This can occur when legalizing some floating point comparisons. 7817 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7818 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7819 SDLoc DL(N); 7820 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7821 SDValue TargetCC = DAG.getCondCode(CCVal); 7822 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7823 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7824 {LHS, RHS, TargetCC, TrueV, FalseV}); 7825 } 7826 7827 break; 7828 } 7829 case RISCVISD::BR_CC: { 7830 SDValue LHS = N->getOperand(1); 7831 SDValue RHS = N->getOperand(2); 7832 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 7833 if (!ISD::isIntEqualitySetCC(CCVal)) 7834 break; 7835 7836 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 7837 // (br_cc X, Y, lt, dest) 7838 // Sometimes the setcc is introduced after br_cc has been formed. 7839 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7840 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7841 // If we're looking for eq 0 instead of ne 0, we need to invert the 7842 // condition. 7843 bool Invert = CCVal == ISD::SETEQ; 7844 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7845 if (Invert) 7846 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7847 7848 SDLoc DL(N); 7849 RHS = LHS.getOperand(1); 7850 LHS = LHS.getOperand(0); 7851 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7852 7853 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7854 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 7855 N->getOperand(4)); 7856 } 7857 7858 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 7859 // (br_cc X, Y, eq/ne, trueV, falseV) 7860 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7861 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 7862 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 7863 N->getOperand(3), N->getOperand(4)); 7864 7865 // (br_cc X, 1, setne, br_cc) -> 7866 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 7867 // This can occur when legalizing some floating point comparisons. 7868 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7869 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7870 SDLoc DL(N); 7871 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7872 SDValue TargetCC = DAG.getCondCode(CCVal); 7873 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7874 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7875 N->getOperand(0), LHS, RHS, TargetCC, 7876 N->getOperand(4)); 7877 } 7878 break; 7879 } 7880 case ISD::FP_TO_SINT: 7881 case ISD::FP_TO_UINT: 7882 return performFP_TO_INTCombine(N, DCI, Subtarget); 7883 case ISD::FP_TO_SINT_SAT: 7884 case ISD::FP_TO_UINT_SAT: 7885 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 7886 case ISD::FCOPYSIGN: { 7887 EVT VT = N->getValueType(0); 7888 if (!VT.isVector()) 7889 break; 7890 // There is a form of VFSGNJ which injects the negated sign of its second 7891 // operand. Try and bubble any FNEG up after the extend/round to produce 7892 // this optimized pattern. Avoid modifying cases where FP_ROUND and 7893 // TRUNC=1. 7894 SDValue In2 = N->getOperand(1); 7895 // Avoid cases where the extend/round has multiple uses, as duplicating 7896 // those is typically more expensive than removing a fneg. 7897 if (!In2.hasOneUse()) 7898 break; 7899 if (In2.getOpcode() != ISD::FP_EXTEND && 7900 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 7901 break; 7902 In2 = In2.getOperand(0); 7903 if (In2.getOpcode() != ISD::FNEG) 7904 break; 7905 SDLoc DL(N); 7906 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 7907 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 7908 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 7909 } 7910 case ISD::MGATHER: 7911 case ISD::MSCATTER: 7912 case ISD::VP_GATHER: 7913 case ISD::VP_SCATTER: { 7914 if (!DCI.isBeforeLegalize()) 7915 break; 7916 SDValue Index, ScaleOp; 7917 bool IsIndexScaled = false; 7918 bool IsIndexSigned = false; 7919 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 7920 Index = VPGSN->getIndex(); 7921 ScaleOp = VPGSN->getScale(); 7922 IsIndexScaled = VPGSN->isIndexScaled(); 7923 IsIndexSigned = VPGSN->isIndexSigned(); 7924 } else { 7925 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 7926 Index = MGSN->getIndex(); 7927 ScaleOp = MGSN->getScale(); 7928 IsIndexScaled = MGSN->isIndexScaled(); 7929 IsIndexSigned = MGSN->isIndexSigned(); 7930 } 7931 EVT IndexVT = Index.getValueType(); 7932 MVT XLenVT = Subtarget.getXLenVT(); 7933 // RISCV indexed loads only support the "unsigned unscaled" addressing 7934 // mode, so anything else must be manually legalized. 7935 bool NeedsIdxLegalization = 7936 IsIndexScaled || 7937 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 7938 if (!NeedsIdxLegalization) 7939 break; 7940 7941 SDLoc DL(N); 7942 7943 // Any index legalization should first promote to XLenVT, so we don't lose 7944 // bits when scaling. This may create an illegal index type so we let 7945 // LLVM's legalization take care of the splitting. 7946 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 7947 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 7948 IndexVT = IndexVT.changeVectorElementType(XLenVT); 7949 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 7950 DL, IndexVT, Index); 7951 } 7952 7953 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 7954 if (IsIndexScaled && Scale != 1) { 7955 // Manually scale the indices by the element size. 7956 // TODO: Sanitize the scale operand here? 7957 // TODO: For VP nodes, should we use VP_SHL here? 7958 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 7959 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 7960 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 7961 } 7962 7963 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 7964 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 7965 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 7966 {VPGN->getChain(), VPGN->getBasePtr(), Index, 7967 VPGN->getScale(), VPGN->getMask(), 7968 VPGN->getVectorLength()}, 7969 VPGN->getMemOperand(), NewIndexTy); 7970 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 7971 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 7972 {VPSN->getChain(), VPSN->getValue(), 7973 VPSN->getBasePtr(), Index, VPSN->getScale(), 7974 VPSN->getMask(), VPSN->getVectorLength()}, 7975 VPSN->getMemOperand(), NewIndexTy); 7976 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 7977 return DAG.getMaskedGather( 7978 N->getVTList(), MGN->getMemoryVT(), DL, 7979 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 7980 MGN->getBasePtr(), Index, MGN->getScale()}, 7981 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 7982 const auto *MSN = cast<MaskedScatterSDNode>(N); 7983 return DAG.getMaskedScatter( 7984 N->getVTList(), MSN->getMemoryVT(), DL, 7985 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 7986 Index, MSN->getScale()}, 7987 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 7988 } 7989 case RISCVISD::SRA_VL: 7990 case RISCVISD::SRL_VL: 7991 case RISCVISD::SHL_VL: { 7992 SDValue ShAmt = N->getOperand(1); 7993 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7994 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7995 SDLoc DL(N); 7996 SDValue VL = N->getOperand(3); 7997 EVT VT = N->getValueType(0); 7998 ShAmt = 7999 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 8000 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8001 N->getOperand(2), N->getOperand(3)); 8002 } 8003 break; 8004 } 8005 case ISD::SRA: 8006 case ISD::SRL: 8007 case ISD::SHL: { 8008 SDValue ShAmt = N->getOperand(1); 8009 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8010 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8011 SDLoc DL(N); 8012 EVT VT = N->getValueType(0); 8013 ShAmt = 8014 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 8015 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8016 } 8017 break; 8018 } 8019 case RISCVISD::MUL_VL: 8020 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8021 return V; 8022 // Mul is commutative. 8023 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8024 case ISD::STORE: { 8025 auto *Store = cast<StoreSDNode>(N); 8026 SDValue Val = Store->getValue(); 8027 // Combine store of vmv.x.s to vse with VL of 1. 8028 // FIXME: Support FP. 8029 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8030 SDValue Src = Val.getOperand(0); 8031 EVT VecVT = Src.getValueType(); 8032 EVT MemVT = Store->getMemoryVT(); 8033 // The memory VT and the element type must match. 8034 if (VecVT.getVectorElementType() == MemVT) { 8035 SDLoc DL(N); 8036 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8037 return DAG.getStoreVP( 8038 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8039 DAG.getConstant(1, DL, MaskVT), 8040 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8041 Store->getMemOperand(), Store->getAddressingMode(), 8042 Store->isTruncatingStore(), /*IsCompress*/ false); 8043 } 8044 } 8045 8046 break; 8047 } 8048 } 8049 8050 return SDValue(); 8051 } 8052 8053 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8054 const SDNode *N, CombineLevel Level) const { 8055 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8056 // materialised in fewer instructions than `(OP _, c1)`: 8057 // 8058 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8059 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8060 SDValue N0 = N->getOperand(0); 8061 EVT Ty = N0.getValueType(); 8062 if (Ty.isScalarInteger() && 8063 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8064 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8065 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8066 if (C1 && C2) { 8067 const APInt &C1Int = C1->getAPIntValue(); 8068 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8069 8070 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8071 // and the combine should happen, to potentially allow further combines 8072 // later. 8073 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8074 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8075 return true; 8076 8077 // We can materialise `c1` in an add immediate, so it's "free", and the 8078 // combine should be prevented. 8079 if (C1Int.getMinSignedBits() <= 64 && 8080 isLegalAddImmediate(C1Int.getSExtValue())) 8081 return false; 8082 8083 // Neither constant will fit into an immediate, so find materialisation 8084 // costs. 8085 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8086 Subtarget.getFeatureBits(), 8087 /*CompressionCost*/true); 8088 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8089 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8090 /*CompressionCost*/true); 8091 8092 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8093 // combine should be prevented. 8094 if (C1Cost < ShiftedC1Cost) 8095 return false; 8096 } 8097 } 8098 return true; 8099 } 8100 8101 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8102 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8103 TargetLoweringOpt &TLO) const { 8104 // Delay this optimization as late as possible. 8105 if (!TLO.LegalOps) 8106 return false; 8107 8108 EVT VT = Op.getValueType(); 8109 if (VT.isVector()) 8110 return false; 8111 8112 // Only handle AND for now. 8113 if (Op.getOpcode() != ISD::AND) 8114 return false; 8115 8116 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8117 if (!C) 8118 return false; 8119 8120 const APInt &Mask = C->getAPIntValue(); 8121 8122 // Clear all non-demanded bits initially. 8123 APInt ShrunkMask = Mask & DemandedBits; 8124 8125 // Try to make a smaller immediate by setting undemanded bits. 8126 8127 APInt ExpandedMask = Mask | ~DemandedBits; 8128 8129 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8130 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8131 }; 8132 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8133 if (NewMask == Mask) 8134 return true; 8135 SDLoc DL(Op); 8136 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8137 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8138 return TLO.CombineTo(Op, NewOp); 8139 }; 8140 8141 // If the shrunk mask fits in sign extended 12 bits, let the target 8142 // independent code apply it. 8143 if (ShrunkMask.isSignedIntN(12)) 8144 return false; 8145 8146 // Preserve (and X, 0xffff) when zext.h is supported. 8147 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8148 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8149 if (IsLegalMask(NewMask)) 8150 return UseMask(NewMask); 8151 } 8152 8153 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8154 if (VT == MVT::i64) { 8155 APInt NewMask = APInt(64, 0xffffffff); 8156 if (IsLegalMask(NewMask)) 8157 return UseMask(NewMask); 8158 } 8159 8160 // For the remaining optimizations, we need to be able to make a negative 8161 // number through a combination of mask and undemanded bits. 8162 if (!ExpandedMask.isNegative()) 8163 return false; 8164 8165 // What is the fewest number of bits we need to represent the negative number. 8166 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8167 8168 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8169 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8170 APInt NewMask = ShrunkMask; 8171 if (MinSignedBits <= 12) 8172 NewMask.setBitsFrom(11); 8173 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8174 NewMask.setBitsFrom(31); 8175 else 8176 return false; 8177 8178 // Check that our new mask is a subset of the demanded mask. 8179 assert(IsLegalMask(NewMask)); 8180 return UseMask(NewMask); 8181 } 8182 8183 static void computeGREV(APInt &Src, unsigned ShAmt) { 8184 ShAmt &= Src.getBitWidth() - 1; 8185 uint64_t x = Src.getZExtValue(); 8186 if (ShAmt & 1) 8187 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 8188 if (ShAmt & 2) 8189 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 8190 if (ShAmt & 4) 8191 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 8192 if (ShAmt & 8) 8193 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 8194 if (ShAmt & 16) 8195 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 8196 if (ShAmt & 32) 8197 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 8198 Src = x; 8199 } 8200 8201 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8202 KnownBits &Known, 8203 const APInt &DemandedElts, 8204 const SelectionDAG &DAG, 8205 unsigned Depth) const { 8206 unsigned BitWidth = Known.getBitWidth(); 8207 unsigned Opc = Op.getOpcode(); 8208 assert((Opc >= ISD::BUILTIN_OP_END || 8209 Opc == ISD::INTRINSIC_WO_CHAIN || 8210 Opc == ISD::INTRINSIC_W_CHAIN || 8211 Opc == ISD::INTRINSIC_VOID) && 8212 "Should use MaskedValueIsZero if you don't know whether Op" 8213 " is a target node!"); 8214 8215 Known.resetAll(); 8216 switch (Opc) { 8217 default: break; 8218 case RISCVISD::SELECT_CC: { 8219 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8220 // If we don't know any bits, early out. 8221 if (Known.isUnknown()) 8222 break; 8223 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8224 8225 // Only known if known in both the LHS and RHS. 8226 Known = KnownBits::commonBits(Known, Known2); 8227 break; 8228 } 8229 case RISCVISD::REMUW: { 8230 KnownBits Known2; 8231 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8232 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8233 // We only care about the lower 32 bits. 8234 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8235 // Restore the original width by sign extending. 8236 Known = Known.sext(BitWidth); 8237 break; 8238 } 8239 case RISCVISD::DIVUW: { 8240 KnownBits Known2; 8241 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8242 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8243 // We only care about the lower 32 bits. 8244 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8245 // Restore the original width by sign extending. 8246 Known = Known.sext(BitWidth); 8247 break; 8248 } 8249 case RISCVISD::CTZW: { 8250 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8251 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 8252 unsigned LowBits = Log2_32(PossibleTZ) + 1; 8253 Known.Zero.setBitsFrom(LowBits); 8254 break; 8255 } 8256 case RISCVISD::CLZW: { 8257 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8258 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 8259 unsigned LowBits = Log2_32(PossibleLZ) + 1; 8260 Known.Zero.setBitsFrom(LowBits); 8261 break; 8262 } 8263 case RISCVISD::GREV: 8264 case RISCVISD::GREVW: { 8265 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8266 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8267 if (Opc == RISCVISD::GREVW) 8268 Known = Known.trunc(32); 8269 unsigned ShAmt = C->getZExtValue(); 8270 computeGREV(Known.Zero, ShAmt); 8271 computeGREV(Known.One, ShAmt); 8272 if (Opc == RISCVISD::GREVW) 8273 Known = Known.sext(BitWidth); 8274 } 8275 break; 8276 } 8277 case RISCVISD::READ_VLENB: 8278 // We assume VLENB is at least 16 bytes. 8279 Known.Zero.setLowBits(4); 8280 // We assume VLENB is no more than 65536 / 8 bytes. 8281 Known.Zero.setBitsFrom(14); 8282 break; 8283 case ISD::INTRINSIC_W_CHAIN: 8284 case ISD::INTRINSIC_WO_CHAIN: { 8285 unsigned IntNo = 8286 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 8287 switch (IntNo) { 8288 default: 8289 // We can't do anything for most intrinsics. 8290 break; 8291 case Intrinsic::riscv_vsetvli: 8292 case Intrinsic::riscv_vsetvlimax: 8293 case Intrinsic::riscv_vsetvli_opt: 8294 case Intrinsic::riscv_vsetvlimax_opt: 8295 // Assume that VL output is positive and would fit in an int32_t. 8296 // TODO: VLEN might be capped at 16 bits in a future V spec update. 8297 if (BitWidth >= 32) 8298 Known.Zero.setBitsFrom(31); 8299 break; 8300 } 8301 break; 8302 } 8303 } 8304 } 8305 8306 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 8307 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 8308 unsigned Depth) const { 8309 switch (Op.getOpcode()) { 8310 default: 8311 break; 8312 case RISCVISD::SELECT_CC: { 8313 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 8314 if (Tmp == 1) return 1; // Early out. 8315 unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 8316 return std::min(Tmp, Tmp2); 8317 } 8318 case RISCVISD::SLLW: 8319 case RISCVISD::SRAW: 8320 case RISCVISD::SRLW: 8321 case RISCVISD::DIVW: 8322 case RISCVISD::DIVUW: 8323 case RISCVISD::REMUW: 8324 case RISCVISD::ROLW: 8325 case RISCVISD::RORW: 8326 case RISCVISD::GREVW: 8327 case RISCVISD::GORCW: 8328 case RISCVISD::FSLW: 8329 case RISCVISD::FSRW: 8330 case RISCVISD::SHFLW: 8331 case RISCVISD::UNSHFLW: 8332 case RISCVISD::BCOMPRESSW: 8333 case RISCVISD::BDECOMPRESSW: 8334 case RISCVISD::BFPW: 8335 case RISCVISD::FCVT_W_RV64: 8336 case RISCVISD::FCVT_WU_RV64: 8337 case RISCVISD::STRICT_FCVT_W_RV64: 8338 case RISCVISD::STRICT_FCVT_WU_RV64: 8339 // TODO: As the result is sign-extended, this is conservatively correct. A 8340 // more precise answer could be calculated for SRAW depending on known 8341 // bits in the shift amount. 8342 return 33; 8343 case RISCVISD::SHFL: 8344 case RISCVISD::UNSHFL: { 8345 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 8346 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 8347 // will stay within the upper 32 bits. If there were more than 32 sign bits 8348 // before there will be at least 33 sign bits after. 8349 if (Op.getValueType() == MVT::i64 && 8350 isa<ConstantSDNode>(Op.getOperand(1)) && 8351 (Op.getConstantOperandVal(1) & 0x10) == 0) { 8352 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 8353 if (Tmp > 32) 8354 return 33; 8355 } 8356 break; 8357 } 8358 case RISCVISD::VMV_X_S: 8359 // The number of sign bits of the scalar result is computed by obtaining the 8360 // element type of the input vector operand, subtracting its width from the 8361 // XLEN, and then adding one (sign bit within the element type). If the 8362 // element type is wider than XLen, the least-significant XLEN bits are 8363 // taken. 8364 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 8365 return 1; 8366 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 8367 } 8368 8369 return 1; 8370 } 8371 8372 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 8373 MachineBasicBlock *BB) { 8374 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 8375 8376 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 8377 // Should the count have wrapped while it was being read, we need to try 8378 // again. 8379 // ... 8380 // read: 8381 // rdcycleh x3 # load high word of cycle 8382 // rdcycle x2 # load low word of cycle 8383 // rdcycleh x4 # load high word of cycle 8384 // bne x3, x4, read # check if high word reads match, otherwise try again 8385 // ... 8386 8387 MachineFunction &MF = *BB->getParent(); 8388 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8389 MachineFunction::iterator It = ++BB->getIterator(); 8390 8391 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8392 MF.insert(It, LoopMBB); 8393 8394 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8395 MF.insert(It, DoneMBB); 8396 8397 // Transfer the remainder of BB and its successor edges to DoneMBB. 8398 DoneMBB->splice(DoneMBB->begin(), BB, 8399 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8400 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 8401 8402 BB->addSuccessor(LoopMBB); 8403 8404 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8405 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8406 Register LoReg = MI.getOperand(0).getReg(); 8407 Register HiReg = MI.getOperand(1).getReg(); 8408 DebugLoc DL = MI.getDebugLoc(); 8409 8410 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 8411 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 8412 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8413 .addReg(RISCV::X0); 8414 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 8415 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 8416 .addReg(RISCV::X0); 8417 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 8418 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8419 .addReg(RISCV::X0); 8420 8421 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 8422 .addReg(HiReg) 8423 .addReg(ReadAgainReg) 8424 .addMBB(LoopMBB); 8425 8426 LoopMBB->addSuccessor(LoopMBB); 8427 LoopMBB->addSuccessor(DoneMBB); 8428 8429 MI.eraseFromParent(); 8430 8431 return DoneMBB; 8432 } 8433 8434 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 8435 MachineBasicBlock *BB) { 8436 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 8437 8438 MachineFunction &MF = *BB->getParent(); 8439 DebugLoc DL = MI.getDebugLoc(); 8440 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8441 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8442 Register LoReg = MI.getOperand(0).getReg(); 8443 Register HiReg = MI.getOperand(1).getReg(); 8444 Register SrcReg = MI.getOperand(2).getReg(); 8445 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 8446 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8447 8448 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 8449 RI); 8450 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8451 MachineMemOperand *MMOLo = 8452 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 8453 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8454 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 8455 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 8456 .addFrameIndex(FI) 8457 .addImm(0) 8458 .addMemOperand(MMOLo); 8459 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 8460 .addFrameIndex(FI) 8461 .addImm(4) 8462 .addMemOperand(MMOHi); 8463 MI.eraseFromParent(); // The pseudo instruction is gone now. 8464 return BB; 8465 } 8466 8467 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 8468 MachineBasicBlock *BB) { 8469 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 8470 "Unexpected instruction"); 8471 8472 MachineFunction &MF = *BB->getParent(); 8473 DebugLoc DL = MI.getDebugLoc(); 8474 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8475 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8476 Register DstReg = MI.getOperand(0).getReg(); 8477 Register LoReg = MI.getOperand(1).getReg(); 8478 Register HiReg = MI.getOperand(2).getReg(); 8479 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 8480 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8481 8482 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8483 MachineMemOperand *MMOLo = 8484 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 8485 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8486 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 8487 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8488 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 8489 .addFrameIndex(FI) 8490 .addImm(0) 8491 .addMemOperand(MMOLo); 8492 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8493 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 8494 .addFrameIndex(FI) 8495 .addImm(4) 8496 .addMemOperand(MMOHi); 8497 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 8498 MI.eraseFromParent(); // The pseudo instruction is gone now. 8499 return BB; 8500 } 8501 8502 static bool isSelectPseudo(MachineInstr &MI) { 8503 switch (MI.getOpcode()) { 8504 default: 8505 return false; 8506 case RISCV::Select_GPR_Using_CC_GPR: 8507 case RISCV::Select_FPR16_Using_CC_GPR: 8508 case RISCV::Select_FPR32_Using_CC_GPR: 8509 case RISCV::Select_FPR64_Using_CC_GPR: 8510 return true; 8511 } 8512 } 8513 8514 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 8515 unsigned RelOpcode, unsigned EqOpcode, 8516 const RISCVSubtarget &Subtarget) { 8517 DebugLoc DL = MI.getDebugLoc(); 8518 Register DstReg = MI.getOperand(0).getReg(); 8519 Register Src1Reg = MI.getOperand(1).getReg(); 8520 Register Src2Reg = MI.getOperand(2).getReg(); 8521 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 8522 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 8523 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 8524 8525 // Save the current FFLAGS. 8526 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 8527 8528 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 8529 .addReg(Src1Reg) 8530 .addReg(Src2Reg); 8531 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8532 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 8533 8534 // Restore the FFLAGS. 8535 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 8536 .addReg(SavedFFlags, RegState::Kill); 8537 8538 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 8539 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 8540 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 8541 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 8542 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8543 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 8544 8545 // Erase the pseudoinstruction. 8546 MI.eraseFromParent(); 8547 return BB; 8548 } 8549 8550 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 8551 MachineBasicBlock *BB, 8552 const RISCVSubtarget &Subtarget) { 8553 // To "insert" Select_* instructions, we actually have to insert the triangle 8554 // control-flow pattern. The incoming instructions know the destination vreg 8555 // to set, the condition code register to branch on, the true/false values to 8556 // select between, and the condcode to use to select the appropriate branch. 8557 // 8558 // We produce the following control flow: 8559 // HeadMBB 8560 // | \ 8561 // | IfFalseMBB 8562 // | / 8563 // TailMBB 8564 // 8565 // When we find a sequence of selects we attempt to optimize their emission 8566 // by sharing the control flow. Currently we only handle cases where we have 8567 // multiple selects with the exact same condition (same LHS, RHS and CC). 8568 // The selects may be interleaved with other instructions if the other 8569 // instructions meet some requirements we deem safe: 8570 // - They are debug instructions. Otherwise, 8571 // - They do not have side-effects, do not access memory and their inputs do 8572 // not depend on the results of the select pseudo-instructions. 8573 // The TrueV/FalseV operands of the selects cannot depend on the result of 8574 // previous selects in the sequence. 8575 // These conditions could be further relaxed. See the X86 target for a 8576 // related approach and more information. 8577 Register LHS = MI.getOperand(1).getReg(); 8578 Register RHS = MI.getOperand(2).getReg(); 8579 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 8580 8581 SmallVector<MachineInstr *, 4> SelectDebugValues; 8582 SmallSet<Register, 4> SelectDests; 8583 SelectDests.insert(MI.getOperand(0).getReg()); 8584 8585 MachineInstr *LastSelectPseudo = &MI; 8586 8587 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 8588 SequenceMBBI != E; ++SequenceMBBI) { 8589 if (SequenceMBBI->isDebugInstr()) 8590 continue; 8591 else if (isSelectPseudo(*SequenceMBBI)) { 8592 if (SequenceMBBI->getOperand(1).getReg() != LHS || 8593 SequenceMBBI->getOperand(2).getReg() != RHS || 8594 SequenceMBBI->getOperand(3).getImm() != CC || 8595 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 8596 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 8597 break; 8598 LastSelectPseudo = &*SequenceMBBI; 8599 SequenceMBBI->collectDebugValues(SelectDebugValues); 8600 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 8601 } else { 8602 if (SequenceMBBI->hasUnmodeledSideEffects() || 8603 SequenceMBBI->mayLoadOrStore()) 8604 break; 8605 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 8606 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 8607 })) 8608 break; 8609 } 8610 } 8611 8612 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 8613 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8614 DebugLoc DL = MI.getDebugLoc(); 8615 MachineFunction::iterator I = ++BB->getIterator(); 8616 8617 MachineBasicBlock *HeadMBB = BB; 8618 MachineFunction *F = BB->getParent(); 8619 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 8620 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 8621 8622 F->insert(I, IfFalseMBB); 8623 F->insert(I, TailMBB); 8624 8625 // Transfer debug instructions associated with the selects to TailMBB. 8626 for (MachineInstr *DebugInstr : SelectDebugValues) { 8627 TailMBB->push_back(DebugInstr->removeFromParent()); 8628 } 8629 8630 // Move all instructions after the sequence to TailMBB. 8631 TailMBB->splice(TailMBB->end(), HeadMBB, 8632 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 8633 // Update machine-CFG edges by transferring all successors of the current 8634 // block to the new block which will contain the Phi nodes for the selects. 8635 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 8636 // Set the successors for HeadMBB. 8637 HeadMBB->addSuccessor(IfFalseMBB); 8638 HeadMBB->addSuccessor(TailMBB); 8639 8640 // Insert appropriate branch. 8641 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 8642 .addReg(LHS) 8643 .addReg(RHS) 8644 .addMBB(TailMBB); 8645 8646 // IfFalseMBB just falls through to TailMBB. 8647 IfFalseMBB->addSuccessor(TailMBB); 8648 8649 // Create PHIs for all of the select pseudo-instructions. 8650 auto SelectMBBI = MI.getIterator(); 8651 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 8652 auto InsertionPoint = TailMBB->begin(); 8653 while (SelectMBBI != SelectEnd) { 8654 auto Next = std::next(SelectMBBI); 8655 if (isSelectPseudo(*SelectMBBI)) { 8656 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 8657 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 8658 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 8659 .addReg(SelectMBBI->getOperand(4).getReg()) 8660 .addMBB(HeadMBB) 8661 .addReg(SelectMBBI->getOperand(5).getReg()) 8662 .addMBB(IfFalseMBB); 8663 SelectMBBI->eraseFromParent(); 8664 } 8665 SelectMBBI = Next; 8666 } 8667 8668 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 8669 return TailMBB; 8670 } 8671 8672 MachineBasicBlock * 8673 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8674 MachineBasicBlock *BB) const { 8675 switch (MI.getOpcode()) { 8676 default: 8677 llvm_unreachable("Unexpected instr type to insert"); 8678 case RISCV::ReadCycleWide: 8679 assert(!Subtarget.is64Bit() && 8680 "ReadCycleWrite is only to be used on riscv32"); 8681 return emitReadCycleWidePseudo(MI, BB); 8682 case RISCV::Select_GPR_Using_CC_GPR: 8683 case RISCV::Select_FPR16_Using_CC_GPR: 8684 case RISCV::Select_FPR32_Using_CC_GPR: 8685 case RISCV::Select_FPR64_Using_CC_GPR: 8686 return emitSelectPseudo(MI, BB, Subtarget); 8687 case RISCV::BuildPairF64Pseudo: 8688 return emitBuildPairF64Pseudo(MI, BB); 8689 case RISCV::SplitF64Pseudo: 8690 return emitSplitF64Pseudo(MI, BB); 8691 case RISCV::PseudoQuietFLE_H: 8692 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 8693 case RISCV::PseudoQuietFLT_H: 8694 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 8695 case RISCV::PseudoQuietFLE_S: 8696 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 8697 case RISCV::PseudoQuietFLT_S: 8698 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 8699 case RISCV::PseudoQuietFLE_D: 8700 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 8701 case RISCV::PseudoQuietFLT_D: 8702 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 8703 } 8704 } 8705 8706 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 8707 SDNode *Node) const { 8708 // Add FRM dependency to any instructions with dynamic rounding mode. 8709 unsigned Opc = MI.getOpcode(); 8710 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 8711 if (Idx < 0) 8712 return; 8713 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 8714 return; 8715 // If the instruction already reads FRM, don't add another read. 8716 if (MI.readsRegister(RISCV::FRM)) 8717 return; 8718 MI.addOperand( 8719 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 8720 } 8721 8722 // Calling Convention Implementation. 8723 // The expectations for frontend ABI lowering vary from target to target. 8724 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 8725 // details, but this is a longer term goal. For now, we simply try to keep the 8726 // role of the frontend as simple and well-defined as possible. The rules can 8727 // be summarised as: 8728 // * Never split up large scalar arguments. We handle them here. 8729 // * If a hardfloat calling convention is being used, and the struct may be 8730 // passed in a pair of registers (fp+fp, int+fp), and both registers are 8731 // available, then pass as two separate arguments. If either the GPRs or FPRs 8732 // are exhausted, then pass according to the rule below. 8733 // * If a struct could never be passed in registers or directly in a stack 8734 // slot (as it is larger than 2*XLEN and the floating point rules don't 8735 // apply), then pass it using a pointer with the byval attribute. 8736 // * If a struct is less than 2*XLEN, then coerce to either a two-element 8737 // word-sized array or a 2*XLEN scalar (depending on alignment). 8738 // * The frontend can determine whether a struct is returned by reference or 8739 // not based on its size and fields. If it will be returned by reference, the 8740 // frontend must modify the prototype so a pointer with the sret annotation is 8741 // passed as the first argument. This is not necessary for large scalar 8742 // returns. 8743 // * Struct return values and varargs should be coerced to structs containing 8744 // register-size fields in the same situations they would be for fixed 8745 // arguments. 8746 8747 static const MCPhysReg ArgGPRs[] = { 8748 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 8749 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 8750 }; 8751 static const MCPhysReg ArgFPR16s[] = { 8752 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 8753 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 8754 }; 8755 static const MCPhysReg ArgFPR32s[] = { 8756 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 8757 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 8758 }; 8759 static const MCPhysReg ArgFPR64s[] = { 8760 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 8761 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 8762 }; 8763 // This is an interim calling convention and it may be changed in the future. 8764 static const MCPhysReg ArgVRs[] = { 8765 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 8766 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 8767 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 8768 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 8769 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 8770 RISCV::V20M2, RISCV::V22M2}; 8771 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 8772 RISCV::V20M4}; 8773 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 8774 8775 // Pass a 2*XLEN argument that has been split into two XLEN values through 8776 // registers or the stack as necessary. 8777 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 8778 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 8779 MVT ValVT2, MVT LocVT2, 8780 ISD::ArgFlagsTy ArgFlags2) { 8781 unsigned XLenInBytes = XLen / 8; 8782 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8783 // At least one half can be passed via register. 8784 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 8785 VA1.getLocVT(), CCValAssign::Full)); 8786 } else { 8787 // Both halves must be passed on the stack, with proper alignment. 8788 Align StackAlign = 8789 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 8790 State.addLoc( 8791 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 8792 State.AllocateStack(XLenInBytes, StackAlign), 8793 VA1.getLocVT(), CCValAssign::Full)); 8794 State.addLoc(CCValAssign::getMem( 8795 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8796 LocVT2, CCValAssign::Full)); 8797 return false; 8798 } 8799 8800 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8801 // The second half can also be passed via register. 8802 State.addLoc( 8803 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 8804 } else { 8805 // The second half is passed via the stack, without additional alignment. 8806 State.addLoc(CCValAssign::getMem( 8807 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8808 LocVT2, CCValAssign::Full)); 8809 } 8810 8811 return false; 8812 } 8813 8814 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 8815 Optional<unsigned> FirstMaskArgument, 8816 CCState &State, const RISCVTargetLowering &TLI) { 8817 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 8818 if (RC == &RISCV::VRRegClass) { 8819 // Assign the first mask argument to V0. 8820 // This is an interim calling convention and it may be changed in the 8821 // future. 8822 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 8823 return State.AllocateReg(RISCV::V0); 8824 return State.AllocateReg(ArgVRs); 8825 } 8826 if (RC == &RISCV::VRM2RegClass) 8827 return State.AllocateReg(ArgVRM2s); 8828 if (RC == &RISCV::VRM4RegClass) 8829 return State.AllocateReg(ArgVRM4s); 8830 if (RC == &RISCV::VRM8RegClass) 8831 return State.AllocateReg(ArgVRM8s); 8832 llvm_unreachable("Unhandled register class for ValueType"); 8833 } 8834 8835 // Implements the RISC-V calling convention. Returns true upon failure. 8836 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 8837 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 8838 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 8839 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 8840 Optional<unsigned> FirstMaskArgument) { 8841 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 8842 assert(XLen == 32 || XLen == 64); 8843 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 8844 8845 // Any return value split in to more than two values can't be returned 8846 // directly. Vectors are returned via the available vector registers. 8847 if (!LocVT.isVector() && IsRet && ValNo > 1) 8848 return true; 8849 8850 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 8851 // variadic argument, or if no F16/F32 argument registers are available. 8852 bool UseGPRForF16_F32 = true; 8853 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 8854 // variadic argument, or if no F64 argument registers are available. 8855 bool UseGPRForF64 = true; 8856 8857 switch (ABI) { 8858 default: 8859 llvm_unreachable("Unexpected ABI"); 8860 case RISCVABI::ABI_ILP32: 8861 case RISCVABI::ABI_LP64: 8862 break; 8863 case RISCVABI::ABI_ILP32F: 8864 case RISCVABI::ABI_LP64F: 8865 UseGPRForF16_F32 = !IsFixed; 8866 break; 8867 case RISCVABI::ABI_ILP32D: 8868 case RISCVABI::ABI_LP64D: 8869 UseGPRForF16_F32 = !IsFixed; 8870 UseGPRForF64 = !IsFixed; 8871 break; 8872 } 8873 8874 // FPR16, FPR32, and FPR64 alias each other. 8875 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 8876 UseGPRForF16_F32 = true; 8877 UseGPRForF64 = true; 8878 } 8879 8880 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 8881 // similar local variables rather than directly checking against the target 8882 // ABI. 8883 8884 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 8885 LocVT = XLenVT; 8886 LocInfo = CCValAssign::BCvt; 8887 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 8888 LocVT = MVT::i64; 8889 LocInfo = CCValAssign::BCvt; 8890 } 8891 8892 // If this is a variadic argument, the RISC-V calling convention requires 8893 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 8894 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 8895 // be used regardless of whether the original argument was split during 8896 // legalisation or not. The argument will not be passed by registers if the 8897 // original type is larger than 2*XLEN, so the register alignment rule does 8898 // not apply. 8899 unsigned TwoXLenInBytes = (2 * XLen) / 8; 8900 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 8901 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 8902 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 8903 // Skip 'odd' register if necessary. 8904 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 8905 State.AllocateReg(ArgGPRs); 8906 } 8907 8908 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 8909 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 8910 State.getPendingArgFlags(); 8911 8912 assert(PendingLocs.size() == PendingArgFlags.size() && 8913 "PendingLocs and PendingArgFlags out of sync"); 8914 8915 // Handle passing f64 on RV32D with a soft float ABI or when floating point 8916 // registers are exhausted. 8917 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 8918 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 8919 "Can't lower f64 if it is split"); 8920 // Depending on available argument GPRS, f64 may be passed in a pair of 8921 // GPRs, split between a GPR and the stack, or passed completely on the 8922 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 8923 // cases. 8924 Register Reg = State.AllocateReg(ArgGPRs); 8925 LocVT = MVT::i32; 8926 if (!Reg) { 8927 unsigned StackOffset = State.AllocateStack(8, Align(8)); 8928 State.addLoc( 8929 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8930 return false; 8931 } 8932 if (!State.AllocateReg(ArgGPRs)) 8933 State.AllocateStack(4, Align(4)); 8934 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8935 return false; 8936 } 8937 8938 // Fixed-length vectors are located in the corresponding scalable-vector 8939 // container types. 8940 if (ValVT.isFixedLengthVector()) 8941 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8942 8943 // Split arguments might be passed indirectly, so keep track of the pending 8944 // values. Split vectors are passed via a mix of registers and indirectly, so 8945 // treat them as we would any other argument. 8946 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 8947 LocVT = XLenVT; 8948 LocInfo = CCValAssign::Indirect; 8949 PendingLocs.push_back( 8950 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 8951 PendingArgFlags.push_back(ArgFlags); 8952 if (!ArgFlags.isSplitEnd()) { 8953 return false; 8954 } 8955 } 8956 8957 // If the split argument only had two elements, it should be passed directly 8958 // in registers or on the stack. 8959 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 8960 PendingLocs.size() <= 2) { 8961 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 8962 // Apply the normal calling convention rules to the first half of the 8963 // split argument. 8964 CCValAssign VA = PendingLocs[0]; 8965 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 8966 PendingLocs.clear(); 8967 PendingArgFlags.clear(); 8968 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 8969 ArgFlags); 8970 } 8971 8972 // Allocate to a register if possible, or else a stack slot. 8973 Register Reg; 8974 unsigned StoreSizeBytes = XLen / 8; 8975 Align StackAlign = Align(XLen / 8); 8976 8977 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 8978 Reg = State.AllocateReg(ArgFPR16s); 8979 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 8980 Reg = State.AllocateReg(ArgFPR32s); 8981 else if (ValVT == MVT::f64 && !UseGPRForF64) 8982 Reg = State.AllocateReg(ArgFPR64s); 8983 else if (ValVT.isVector()) { 8984 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 8985 if (!Reg) { 8986 // For return values, the vector must be passed fully via registers or 8987 // via the stack. 8988 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 8989 // but we're using all of them. 8990 if (IsRet) 8991 return true; 8992 // Try using a GPR to pass the address 8993 if ((Reg = State.AllocateReg(ArgGPRs))) { 8994 LocVT = XLenVT; 8995 LocInfo = CCValAssign::Indirect; 8996 } else if (ValVT.isScalableVector()) { 8997 LocVT = XLenVT; 8998 LocInfo = CCValAssign::Indirect; 8999 } else { 9000 // Pass fixed-length vectors on the stack. 9001 LocVT = ValVT; 9002 StoreSizeBytes = ValVT.getStoreSize(); 9003 // Align vectors to their element sizes, being careful for vXi1 9004 // vectors. 9005 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9006 } 9007 } 9008 } else { 9009 Reg = State.AllocateReg(ArgGPRs); 9010 } 9011 9012 unsigned StackOffset = 9013 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9014 9015 // If we reach this point and PendingLocs is non-empty, we must be at the 9016 // end of a split argument that must be passed indirectly. 9017 if (!PendingLocs.empty()) { 9018 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9019 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9020 9021 for (auto &It : PendingLocs) { 9022 if (Reg) 9023 It.convertToReg(Reg); 9024 else 9025 It.convertToMem(StackOffset); 9026 State.addLoc(It); 9027 } 9028 PendingLocs.clear(); 9029 PendingArgFlags.clear(); 9030 return false; 9031 } 9032 9033 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9034 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9035 "Expected an XLenVT or vector types at this stage"); 9036 9037 if (Reg) { 9038 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9039 return false; 9040 } 9041 9042 // When a floating-point value is passed on the stack, no bit-conversion is 9043 // needed. 9044 if (ValVT.isFloatingPoint()) { 9045 LocVT = ValVT; 9046 LocInfo = CCValAssign::Full; 9047 } 9048 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9049 return false; 9050 } 9051 9052 template <typename ArgTy> 9053 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9054 for (const auto &ArgIdx : enumerate(Args)) { 9055 MVT ArgVT = ArgIdx.value().VT; 9056 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9057 return ArgIdx.index(); 9058 } 9059 return None; 9060 } 9061 9062 void RISCVTargetLowering::analyzeInputArgs( 9063 MachineFunction &MF, CCState &CCInfo, 9064 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9065 RISCVCCAssignFn Fn) const { 9066 unsigned NumArgs = Ins.size(); 9067 FunctionType *FType = MF.getFunction().getFunctionType(); 9068 9069 Optional<unsigned> FirstMaskArgument; 9070 if (Subtarget.hasVInstructions()) 9071 FirstMaskArgument = preAssignMask(Ins); 9072 9073 for (unsigned i = 0; i != NumArgs; ++i) { 9074 MVT ArgVT = Ins[i].VT; 9075 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9076 9077 Type *ArgTy = nullptr; 9078 if (IsRet) 9079 ArgTy = FType->getReturnType(); 9080 else if (Ins[i].isOrigArg()) 9081 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9082 9083 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9084 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9085 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9086 FirstMaskArgument)) { 9087 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9088 << EVT(ArgVT).getEVTString() << '\n'); 9089 llvm_unreachable(nullptr); 9090 } 9091 } 9092 } 9093 9094 void RISCVTargetLowering::analyzeOutputArgs( 9095 MachineFunction &MF, CCState &CCInfo, 9096 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9097 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9098 unsigned NumArgs = Outs.size(); 9099 9100 Optional<unsigned> FirstMaskArgument; 9101 if (Subtarget.hasVInstructions()) 9102 FirstMaskArgument = preAssignMask(Outs); 9103 9104 for (unsigned i = 0; i != NumArgs; i++) { 9105 MVT ArgVT = Outs[i].VT; 9106 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9107 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9108 9109 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9110 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9111 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9112 FirstMaskArgument)) { 9113 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9114 << EVT(ArgVT).getEVTString() << "\n"); 9115 llvm_unreachable(nullptr); 9116 } 9117 } 9118 } 9119 9120 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9121 // values. 9122 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9123 const CCValAssign &VA, const SDLoc &DL, 9124 const RISCVSubtarget &Subtarget) { 9125 switch (VA.getLocInfo()) { 9126 default: 9127 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9128 case CCValAssign::Full: 9129 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9130 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9131 break; 9132 case CCValAssign::BCvt: 9133 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9134 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9135 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9136 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9137 else 9138 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9139 break; 9140 } 9141 return Val; 9142 } 9143 9144 // The caller is responsible for loading the full value if the argument is 9145 // passed with CCValAssign::Indirect. 9146 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9147 const CCValAssign &VA, const SDLoc &DL, 9148 const RISCVTargetLowering &TLI) { 9149 MachineFunction &MF = DAG.getMachineFunction(); 9150 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9151 EVT LocVT = VA.getLocVT(); 9152 SDValue Val; 9153 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9154 Register VReg = RegInfo.createVirtualRegister(RC); 9155 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9156 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9157 9158 if (VA.getLocInfo() == CCValAssign::Indirect) 9159 return Val; 9160 9161 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9162 } 9163 9164 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9165 const CCValAssign &VA, const SDLoc &DL, 9166 const RISCVSubtarget &Subtarget) { 9167 EVT LocVT = VA.getLocVT(); 9168 9169 switch (VA.getLocInfo()) { 9170 default: 9171 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9172 case CCValAssign::Full: 9173 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9174 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9175 break; 9176 case CCValAssign::BCvt: 9177 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9178 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9179 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9180 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9181 else 9182 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9183 break; 9184 } 9185 return Val; 9186 } 9187 9188 // The caller is responsible for loading the full value if the argument is 9189 // passed with CCValAssign::Indirect. 9190 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9191 const CCValAssign &VA, const SDLoc &DL) { 9192 MachineFunction &MF = DAG.getMachineFunction(); 9193 MachineFrameInfo &MFI = MF.getFrameInfo(); 9194 EVT LocVT = VA.getLocVT(); 9195 EVT ValVT = VA.getValVT(); 9196 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9197 if (ValVT.isScalableVector()) { 9198 // When the value is a scalable vector, we save the pointer which points to 9199 // the scalable vector value in the stack. The ValVT will be the pointer 9200 // type, instead of the scalable vector type. 9201 ValVT = LocVT; 9202 } 9203 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9204 /*IsImmutable=*/true); 9205 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9206 SDValue Val; 9207 9208 ISD::LoadExtType ExtType; 9209 switch (VA.getLocInfo()) { 9210 default: 9211 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9212 case CCValAssign::Full: 9213 case CCValAssign::Indirect: 9214 case CCValAssign::BCvt: 9215 ExtType = ISD::NON_EXTLOAD; 9216 break; 9217 } 9218 Val = DAG.getExtLoad( 9219 ExtType, DL, LocVT, Chain, FIN, 9220 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9221 return Val; 9222 } 9223 9224 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9225 const CCValAssign &VA, const SDLoc &DL) { 9226 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9227 "Unexpected VA"); 9228 MachineFunction &MF = DAG.getMachineFunction(); 9229 MachineFrameInfo &MFI = MF.getFrameInfo(); 9230 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9231 9232 if (VA.isMemLoc()) { 9233 // f64 is passed on the stack. 9234 int FI = 9235 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9236 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9237 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9238 MachinePointerInfo::getFixedStack(MF, FI)); 9239 } 9240 9241 assert(VA.isRegLoc() && "Expected register VA assignment"); 9242 9243 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9244 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 9245 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 9246 SDValue Hi; 9247 if (VA.getLocReg() == RISCV::X17) { 9248 // Second half of f64 is passed on the stack. 9249 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 9250 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9251 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 9252 MachinePointerInfo::getFixedStack(MF, FI)); 9253 } else { 9254 // Second half of f64 is passed in another GPR. 9255 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9256 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 9257 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 9258 } 9259 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 9260 } 9261 9262 // FastCC has less than 1% performance improvement for some particular 9263 // benchmark. But theoretically, it may has benenfit for some cases. 9264 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 9265 unsigned ValNo, MVT ValVT, MVT LocVT, 9266 CCValAssign::LocInfo LocInfo, 9267 ISD::ArgFlagsTy ArgFlags, CCState &State, 9268 bool IsFixed, bool IsRet, Type *OrigTy, 9269 const RISCVTargetLowering &TLI, 9270 Optional<unsigned> FirstMaskArgument) { 9271 9272 // X5 and X6 might be used for save-restore libcall. 9273 static const MCPhysReg GPRList[] = { 9274 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 9275 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 9276 RISCV::X29, RISCV::X30, RISCV::X31}; 9277 9278 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9279 if (unsigned Reg = State.AllocateReg(GPRList)) { 9280 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9281 return false; 9282 } 9283 } 9284 9285 if (LocVT == MVT::f16) { 9286 static const MCPhysReg FPR16List[] = { 9287 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 9288 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 9289 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 9290 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 9291 if (unsigned Reg = State.AllocateReg(FPR16List)) { 9292 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9293 return false; 9294 } 9295 } 9296 9297 if (LocVT == MVT::f32) { 9298 static const MCPhysReg FPR32List[] = { 9299 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 9300 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 9301 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 9302 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 9303 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9304 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9305 return false; 9306 } 9307 } 9308 9309 if (LocVT == MVT::f64) { 9310 static const MCPhysReg FPR64List[] = { 9311 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 9312 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 9313 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 9314 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 9315 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9316 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9317 return false; 9318 } 9319 } 9320 9321 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 9322 unsigned Offset4 = State.AllocateStack(4, Align(4)); 9323 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 9324 return false; 9325 } 9326 9327 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 9328 unsigned Offset5 = State.AllocateStack(8, Align(8)); 9329 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 9330 return false; 9331 } 9332 9333 if (LocVT.isVector()) { 9334 if (unsigned Reg = 9335 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 9336 // Fixed-length vectors are located in the corresponding scalable-vector 9337 // container types. 9338 if (ValVT.isFixedLengthVector()) 9339 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9340 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9341 } else { 9342 // Try and pass the address via a "fast" GPR. 9343 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 9344 LocInfo = CCValAssign::Indirect; 9345 LocVT = TLI.getSubtarget().getXLenVT(); 9346 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 9347 } else if (ValVT.isFixedLengthVector()) { 9348 auto StackAlign = 9349 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9350 unsigned StackOffset = 9351 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 9352 State.addLoc( 9353 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9354 } else { 9355 // Can't pass scalable vectors on the stack. 9356 return true; 9357 } 9358 } 9359 9360 return false; 9361 } 9362 9363 return true; // CC didn't match. 9364 } 9365 9366 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9367 CCValAssign::LocInfo LocInfo, 9368 ISD::ArgFlagsTy ArgFlags, CCState &State) { 9369 9370 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9371 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 9372 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 9373 static const MCPhysReg GPRList[] = { 9374 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 9375 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 9376 if (unsigned Reg = State.AllocateReg(GPRList)) { 9377 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9378 return false; 9379 } 9380 } 9381 9382 if (LocVT == MVT::f32) { 9383 // Pass in STG registers: F1, ..., F6 9384 // fs0 ... fs5 9385 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 9386 RISCV::F18_F, RISCV::F19_F, 9387 RISCV::F20_F, RISCV::F21_F}; 9388 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9389 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9390 return false; 9391 } 9392 } 9393 9394 if (LocVT == MVT::f64) { 9395 // Pass in STG registers: D1, ..., D6 9396 // fs6 ... fs11 9397 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 9398 RISCV::F24_D, RISCV::F25_D, 9399 RISCV::F26_D, RISCV::F27_D}; 9400 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9401 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9402 return false; 9403 } 9404 } 9405 9406 report_fatal_error("No registers left in GHC calling convention"); 9407 return true; 9408 } 9409 9410 // Transform physical registers into virtual registers. 9411 SDValue RISCVTargetLowering::LowerFormalArguments( 9412 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 9413 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 9414 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 9415 9416 MachineFunction &MF = DAG.getMachineFunction(); 9417 9418 switch (CallConv) { 9419 default: 9420 report_fatal_error("Unsupported calling convention"); 9421 case CallingConv::C: 9422 case CallingConv::Fast: 9423 break; 9424 case CallingConv::GHC: 9425 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 9426 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 9427 report_fatal_error( 9428 "GHC calling convention requires the F and D instruction set extensions"); 9429 } 9430 9431 const Function &Func = MF.getFunction(); 9432 if (Func.hasFnAttribute("interrupt")) { 9433 if (!Func.arg_empty()) 9434 report_fatal_error( 9435 "Functions with the interrupt attribute cannot have arguments!"); 9436 9437 StringRef Kind = 9438 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9439 9440 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 9441 report_fatal_error( 9442 "Function interrupt attribute argument not supported!"); 9443 } 9444 9445 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9446 MVT XLenVT = Subtarget.getXLenVT(); 9447 unsigned XLenInBytes = Subtarget.getXLen() / 8; 9448 // Used with vargs to acumulate store chains. 9449 std::vector<SDValue> OutChains; 9450 9451 // Assign locations to all of the incoming arguments. 9452 SmallVector<CCValAssign, 16> ArgLocs; 9453 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9454 9455 if (CallConv == CallingConv::GHC) 9456 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 9457 else 9458 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 9459 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9460 : CC_RISCV); 9461 9462 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 9463 CCValAssign &VA = ArgLocs[i]; 9464 SDValue ArgValue; 9465 // Passing f64 on RV32D with a soft float ABI must be handled as a special 9466 // case. 9467 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 9468 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 9469 else if (VA.isRegLoc()) 9470 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 9471 else 9472 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 9473 9474 if (VA.getLocInfo() == CCValAssign::Indirect) { 9475 // If the original argument was split and passed by reference (e.g. i128 9476 // on RV32), we need to load all parts of it here (using the same 9477 // address). Vectors may be partly split to registers and partly to the 9478 // stack, in which case the base address is partly offset and subsequent 9479 // stores are relative to that. 9480 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 9481 MachinePointerInfo())); 9482 unsigned ArgIndex = Ins[i].OrigArgIndex; 9483 unsigned ArgPartOffset = Ins[i].PartOffset; 9484 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9485 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 9486 CCValAssign &PartVA = ArgLocs[i + 1]; 9487 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 9488 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9489 if (PartVA.getValVT().isScalableVector()) 9490 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9491 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 9492 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 9493 MachinePointerInfo())); 9494 ++i; 9495 } 9496 continue; 9497 } 9498 InVals.push_back(ArgValue); 9499 } 9500 9501 if (IsVarArg) { 9502 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 9503 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 9504 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 9505 MachineFrameInfo &MFI = MF.getFrameInfo(); 9506 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9507 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 9508 9509 // Offset of the first variable argument from stack pointer, and size of 9510 // the vararg save area. For now, the varargs save area is either zero or 9511 // large enough to hold a0-a7. 9512 int VaArgOffset, VarArgsSaveSize; 9513 9514 // If all registers are allocated, then all varargs must be passed on the 9515 // stack and we don't need to save any argregs. 9516 if (ArgRegs.size() == Idx) { 9517 VaArgOffset = CCInfo.getNextStackOffset(); 9518 VarArgsSaveSize = 0; 9519 } else { 9520 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 9521 VaArgOffset = -VarArgsSaveSize; 9522 } 9523 9524 // Record the frame index of the first variable argument 9525 // which is a value necessary to VASTART. 9526 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9527 RVFI->setVarArgsFrameIndex(FI); 9528 9529 // If saving an odd number of registers then create an extra stack slot to 9530 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 9531 // offsets to even-numbered registered remain 2*XLEN-aligned. 9532 if (Idx % 2) { 9533 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 9534 VarArgsSaveSize += XLenInBytes; 9535 } 9536 9537 // Copy the integer registers that may have been used for passing varargs 9538 // to the vararg save area. 9539 for (unsigned I = Idx; I < ArgRegs.size(); 9540 ++I, VaArgOffset += XLenInBytes) { 9541 const Register Reg = RegInfo.createVirtualRegister(RC); 9542 RegInfo.addLiveIn(ArgRegs[I], Reg); 9543 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 9544 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9545 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9546 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 9547 MachinePointerInfo::getFixedStack(MF, FI)); 9548 cast<StoreSDNode>(Store.getNode()) 9549 ->getMemOperand() 9550 ->setValue((Value *)nullptr); 9551 OutChains.push_back(Store); 9552 } 9553 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 9554 } 9555 9556 // All stores are grouped in one node to allow the matching between 9557 // the size of Ins and InVals. This only happens for vararg functions. 9558 if (!OutChains.empty()) { 9559 OutChains.push_back(Chain); 9560 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 9561 } 9562 9563 return Chain; 9564 } 9565 9566 /// isEligibleForTailCallOptimization - Check whether the call is eligible 9567 /// for tail call optimization. 9568 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 9569 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 9570 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 9571 const SmallVector<CCValAssign, 16> &ArgLocs) const { 9572 9573 auto &Callee = CLI.Callee; 9574 auto CalleeCC = CLI.CallConv; 9575 auto &Outs = CLI.Outs; 9576 auto &Caller = MF.getFunction(); 9577 auto CallerCC = Caller.getCallingConv(); 9578 9579 // Exception-handling functions need a special set of instructions to 9580 // indicate a return to the hardware. Tail-calling another function would 9581 // probably break this. 9582 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 9583 // should be expanded as new function attributes are introduced. 9584 if (Caller.hasFnAttribute("interrupt")) 9585 return false; 9586 9587 // Do not tail call opt if the stack is used to pass parameters. 9588 if (CCInfo.getNextStackOffset() != 0) 9589 return false; 9590 9591 // Do not tail call opt if any parameters need to be passed indirectly. 9592 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 9593 // passed indirectly. So the address of the value will be passed in a 9594 // register, or if not available, then the address is put on the stack. In 9595 // order to pass indirectly, space on the stack often needs to be allocated 9596 // in order to store the value. In this case the CCInfo.getNextStackOffset() 9597 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 9598 // are passed CCValAssign::Indirect. 9599 for (auto &VA : ArgLocs) 9600 if (VA.getLocInfo() == CCValAssign::Indirect) 9601 return false; 9602 9603 // Do not tail call opt if either caller or callee uses struct return 9604 // semantics. 9605 auto IsCallerStructRet = Caller.hasStructRetAttr(); 9606 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 9607 if (IsCallerStructRet || IsCalleeStructRet) 9608 return false; 9609 9610 // Externally-defined functions with weak linkage should not be 9611 // tail-called. The behaviour of branch instructions in this situation (as 9612 // used for tail calls) is implementation-defined, so we cannot rely on the 9613 // linker replacing the tail call with a return. 9614 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 9615 const GlobalValue *GV = G->getGlobal(); 9616 if (GV->hasExternalWeakLinkage()) 9617 return false; 9618 } 9619 9620 // The callee has to preserve all registers the caller needs to preserve. 9621 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9622 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 9623 if (CalleeCC != CallerCC) { 9624 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 9625 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 9626 return false; 9627 } 9628 9629 // Byval parameters hand the function a pointer directly into the stack area 9630 // we want to reuse during a tail call. Working around this *is* possible 9631 // but less efficient and uglier in LowerCall. 9632 for (auto &Arg : Outs) 9633 if (Arg.Flags.isByVal()) 9634 return false; 9635 9636 return true; 9637 } 9638 9639 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 9640 return DAG.getDataLayout().getPrefTypeAlign( 9641 VT.getTypeForEVT(*DAG.getContext())); 9642 } 9643 9644 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 9645 // and output parameter nodes. 9646 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 9647 SmallVectorImpl<SDValue> &InVals) const { 9648 SelectionDAG &DAG = CLI.DAG; 9649 SDLoc &DL = CLI.DL; 9650 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 9651 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 9652 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 9653 SDValue Chain = CLI.Chain; 9654 SDValue Callee = CLI.Callee; 9655 bool &IsTailCall = CLI.IsTailCall; 9656 CallingConv::ID CallConv = CLI.CallConv; 9657 bool IsVarArg = CLI.IsVarArg; 9658 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9659 MVT XLenVT = Subtarget.getXLenVT(); 9660 9661 MachineFunction &MF = DAG.getMachineFunction(); 9662 9663 // Analyze the operands of the call, assigning locations to each operand. 9664 SmallVector<CCValAssign, 16> ArgLocs; 9665 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9666 9667 if (CallConv == CallingConv::GHC) 9668 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 9669 else 9670 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 9671 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9672 : CC_RISCV); 9673 9674 // Check if it's really possible to do a tail call. 9675 if (IsTailCall) 9676 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 9677 9678 if (IsTailCall) 9679 ++NumTailCalls; 9680 else if (CLI.CB && CLI.CB->isMustTailCall()) 9681 report_fatal_error("failed to perform tail call elimination on a call " 9682 "site marked musttail"); 9683 9684 // Get a count of how many bytes are to be pushed on the stack. 9685 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 9686 9687 // Create local copies for byval args 9688 SmallVector<SDValue, 8> ByValArgs; 9689 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9690 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9691 if (!Flags.isByVal()) 9692 continue; 9693 9694 SDValue Arg = OutVals[i]; 9695 unsigned Size = Flags.getByValSize(); 9696 Align Alignment = Flags.getNonZeroByValAlign(); 9697 9698 int FI = 9699 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 9700 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9701 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 9702 9703 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 9704 /*IsVolatile=*/false, 9705 /*AlwaysInline=*/false, IsTailCall, 9706 MachinePointerInfo(), MachinePointerInfo()); 9707 ByValArgs.push_back(FIPtr); 9708 } 9709 9710 if (!IsTailCall) 9711 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 9712 9713 // Copy argument values to their designated locations. 9714 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 9715 SmallVector<SDValue, 8> MemOpChains; 9716 SDValue StackPtr; 9717 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 9718 CCValAssign &VA = ArgLocs[i]; 9719 SDValue ArgValue = OutVals[i]; 9720 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9721 9722 // Handle passing f64 on RV32D with a soft float ABI as a special case. 9723 bool IsF64OnRV32DSoftABI = 9724 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 9725 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 9726 SDValue SplitF64 = DAG.getNode( 9727 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 9728 SDValue Lo = SplitF64.getValue(0); 9729 SDValue Hi = SplitF64.getValue(1); 9730 9731 Register RegLo = VA.getLocReg(); 9732 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 9733 9734 if (RegLo == RISCV::X17) { 9735 // Second half of f64 is passed on the stack. 9736 // Work out the address of the stack slot. 9737 if (!StackPtr.getNode()) 9738 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9739 // Emit the store. 9740 MemOpChains.push_back( 9741 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 9742 } else { 9743 // Second half of f64 is passed in another GPR. 9744 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9745 Register RegHigh = RegLo + 1; 9746 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 9747 } 9748 continue; 9749 } 9750 9751 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 9752 // as any other MemLoc. 9753 9754 // Promote the value if needed. 9755 // For now, only handle fully promoted and indirect arguments. 9756 if (VA.getLocInfo() == CCValAssign::Indirect) { 9757 // Store the argument in a stack slot and pass its address. 9758 Align StackAlign = 9759 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 9760 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 9761 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 9762 // If the original argument was split (e.g. i128), we need 9763 // to store the required parts of it here (and pass just one address). 9764 // Vectors may be partly split to registers and partly to the stack, in 9765 // which case the base address is partly offset and subsequent stores are 9766 // relative to that. 9767 unsigned ArgIndex = Outs[i].OrigArgIndex; 9768 unsigned ArgPartOffset = Outs[i].PartOffset; 9769 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9770 // Calculate the total size to store. We don't have access to what we're 9771 // actually storing other than performing the loop and collecting the 9772 // info. 9773 SmallVector<std::pair<SDValue, SDValue>> Parts; 9774 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 9775 SDValue PartValue = OutVals[i + 1]; 9776 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 9777 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9778 EVT PartVT = PartValue.getValueType(); 9779 if (PartVT.isScalableVector()) 9780 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9781 StoredSize += PartVT.getStoreSize(); 9782 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 9783 Parts.push_back(std::make_pair(PartValue, Offset)); 9784 ++i; 9785 } 9786 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 9787 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 9788 MemOpChains.push_back( 9789 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 9790 MachinePointerInfo::getFixedStack(MF, FI))); 9791 for (const auto &Part : Parts) { 9792 SDValue PartValue = Part.first; 9793 SDValue PartOffset = Part.second; 9794 SDValue Address = 9795 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 9796 MemOpChains.push_back( 9797 DAG.getStore(Chain, DL, PartValue, Address, 9798 MachinePointerInfo::getFixedStack(MF, FI))); 9799 } 9800 ArgValue = SpillSlot; 9801 } else { 9802 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 9803 } 9804 9805 // Use local copy if it is a byval arg. 9806 if (Flags.isByVal()) 9807 ArgValue = ByValArgs[j++]; 9808 9809 if (VA.isRegLoc()) { 9810 // Queue up the argument copies and emit them at the end. 9811 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 9812 } else { 9813 assert(VA.isMemLoc() && "Argument not register or memory"); 9814 assert(!IsTailCall && "Tail call not allowed if stack is used " 9815 "for passing parameters"); 9816 9817 // Work out the address of the stack slot. 9818 if (!StackPtr.getNode()) 9819 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9820 SDValue Address = 9821 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 9822 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 9823 9824 // Emit the store. 9825 MemOpChains.push_back( 9826 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 9827 } 9828 } 9829 9830 // Join the stores, which are independent of one another. 9831 if (!MemOpChains.empty()) 9832 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 9833 9834 SDValue Glue; 9835 9836 // Build a sequence of copy-to-reg nodes, chained and glued together. 9837 for (auto &Reg : RegsToPass) { 9838 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 9839 Glue = Chain.getValue(1); 9840 } 9841 9842 // Validate that none of the argument registers have been marked as 9843 // reserved, if so report an error. Do the same for the return address if this 9844 // is not a tailcall. 9845 validateCCReservedRegs(RegsToPass, MF); 9846 if (!IsTailCall && 9847 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 9848 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9849 MF.getFunction(), 9850 "Return address register required, but has been reserved."}); 9851 9852 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 9853 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 9854 // split it and then direct call can be matched by PseudoCALL. 9855 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 9856 const GlobalValue *GV = S->getGlobal(); 9857 9858 unsigned OpFlags = RISCVII::MO_CALL; 9859 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 9860 OpFlags = RISCVII::MO_PLT; 9861 9862 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 9863 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 9864 unsigned OpFlags = RISCVII::MO_CALL; 9865 9866 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 9867 nullptr)) 9868 OpFlags = RISCVII::MO_PLT; 9869 9870 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 9871 } 9872 9873 // The first call operand is the chain and the second is the target address. 9874 SmallVector<SDValue, 8> Ops; 9875 Ops.push_back(Chain); 9876 Ops.push_back(Callee); 9877 9878 // Add argument registers to the end of the list so that they are 9879 // known live into the call. 9880 for (auto &Reg : RegsToPass) 9881 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 9882 9883 if (!IsTailCall) { 9884 // Add a register mask operand representing the call-preserved registers. 9885 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9886 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 9887 assert(Mask && "Missing call preserved mask for calling convention"); 9888 Ops.push_back(DAG.getRegisterMask(Mask)); 9889 } 9890 9891 // Glue the call to the argument copies, if any. 9892 if (Glue.getNode()) 9893 Ops.push_back(Glue); 9894 9895 // Emit the call. 9896 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9897 9898 if (IsTailCall) { 9899 MF.getFrameInfo().setHasTailCall(); 9900 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 9901 } 9902 9903 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 9904 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 9905 Glue = Chain.getValue(1); 9906 9907 // Mark the end of the call, which is glued to the call itself. 9908 Chain = DAG.getCALLSEQ_END(Chain, 9909 DAG.getConstant(NumBytes, DL, PtrVT, true), 9910 DAG.getConstant(0, DL, PtrVT, true), 9911 Glue, DL); 9912 Glue = Chain.getValue(1); 9913 9914 // Assign locations to each value returned by this call. 9915 SmallVector<CCValAssign, 16> RVLocs; 9916 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 9917 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 9918 9919 // Copy all of the result registers out of their specified physreg. 9920 for (auto &VA : RVLocs) { 9921 // Copy the value out 9922 SDValue RetValue = 9923 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 9924 // Glue the RetValue to the end of the call sequence 9925 Chain = RetValue.getValue(1); 9926 Glue = RetValue.getValue(2); 9927 9928 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9929 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 9930 SDValue RetValue2 = 9931 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 9932 Chain = RetValue2.getValue(1); 9933 Glue = RetValue2.getValue(2); 9934 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 9935 RetValue2); 9936 } 9937 9938 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 9939 9940 InVals.push_back(RetValue); 9941 } 9942 9943 return Chain; 9944 } 9945 9946 bool RISCVTargetLowering::CanLowerReturn( 9947 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 9948 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 9949 SmallVector<CCValAssign, 16> RVLocs; 9950 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 9951 9952 Optional<unsigned> FirstMaskArgument; 9953 if (Subtarget.hasVInstructions()) 9954 FirstMaskArgument = preAssignMask(Outs); 9955 9956 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9957 MVT VT = Outs[i].VT; 9958 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9959 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9960 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 9961 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 9962 *this, FirstMaskArgument)) 9963 return false; 9964 } 9965 return true; 9966 } 9967 9968 SDValue 9969 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 9970 bool IsVarArg, 9971 const SmallVectorImpl<ISD::OutputArg> &Outs, 9972 const SmallVectorImpl<SDValue> &OutVals, 9973 const SDLoc &DL, SelectionDAG &DAG) const { 9974 const MachineFunction &MF = DAG.getMachineFunction(); 9975 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9976 9977 // Stores the assignment of the return value to a location. 9978 SmallVector<CCValAssign, 16> RVLocs; 9979 9980 // Info about the registers and stack slot. 9981 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 9982 *DAG.getContext()); 9983 9984 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 9985 nullptr, CC_RISCV); 9986 9987 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 9988 report_fatal_error("GHC functions return void only"); 9989 9990 SDValue Glue; 9991 SmallVector<SDValue, 4> RetOps(1, Chain); 9992 9993 // Copy the result values into the output registers. 9994 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 9995 SDValue Val = OutVals[i]; 9996 CCValAssign &VA = RVLocs[i]; 9997 assert(VA.isRegLoc() && "Can only return in registers!"); 9998 9999 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10000 // Handle returning f64 on RV32D with a soft float ABI. 10001 assert(VA.isRegLoc() && "Expected return via registers"); 10002 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10003 DAG.getVTList(MVT::i32, MVT::i32), Val); 10004 SDValue Lo = SplitF64.getValue(0); 10005 SDValue Hi = SplitF64.getValue(1); 10006 Register RegLo = VA.getLocReg(); 10007 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10008 Register RegHi = RegLo + 1; 10009 10010 if (STI.isRegisterReservedByUser(RegLo) || 10011 STI.isRegisterReservedByUser(RegHi)) 10012 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10013 MF.getFunction(), 10014 "Return value register required, but has been reserved."}); 10015 10016 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10017 Glue = Chain.getValue(1); 10018 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10019 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10020 Glue = Chain.getValue(1); 10021 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10022 } else { 10023 // Handle a 'normal' return. 10024 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10025 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10026 10027 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10028 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10029 MF.getFunction(), 10030 "Return value register required, but has been reserved."}); 10031 10032 // Guarantee that all emitted copies are stuck together. 10033 Glue = Chain.getValue(1); 10034 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10035 } 10036 } 10037 10038 RetOps[0] = Chain; // Update chain. 10039 10040 // Add the glue node if we have it. 10041 if (Glue.getNode()) { 10042 RetOps.push_back(Glue); 10043 } 10044 10045 unsigned RetOpc = RISCVISD::RET_FLAG; 10046 // Interrupt service routines use different return instructions. 10047 const Function &Func = DAG.getMachineFunction().getFunction(); 10048 if (Func.hasFnAttribute("interrupt")) { 10049 if (!Func.getReturnType()->isVoidTy()) 10050 report_fatal_error( 10051 "Functions with the interrupt attribute must have void return type!"); 10052 10053 MachineFunction &MF = DAG.getMachineFunction(); 10054 StringRef Kind = 10055 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10056 10057 if (Kind == "user") 10058 RetOpc = RISCVISD::URET_FLAG; 10059 else if (Kind == "supervisor") 10060 RetOpc = RISCVISD::SRET_FLAG; 10061 else 10062 RetOpc = RISCVISD::MRET_FLAG; 10063 } 10064 10065 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10066 } 10067 10068 void RISCVTargetLowering::validateCCReservedRegs( 10069 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10070 MachineFunction &MF) const { 10071 const Function &F = MF.getFunction(); 10072 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10073 10074 if (llvm::any_of(Regs, [&STI](auto Reg) { 10075 return STI.isRegisterReservedByUser(Reg.first); 10076 })) 10077 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10078 F, "Argument register required, but has been reserved."}); 10079 } 10080 10081 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10082 return CI->isTailCall(); 10083 } 10084 10085 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10086 #define NODE_NAME_CASE(NODE) \ 10087 case RISCVISD::NODE: \ 10088 return "RISCVISD::" #NODE; 10089 // clang-format off 10090 switch ((RISCVISD::NodeType)Opcode) { 10091 case RISCVISD::FIRST_NUMBER: 10092 break; 10093 NODE_NAME_CASE(RET_FLAG) 10094 NODE_NAME_CASE(URET_FLAG) 10095 NODE_NAME_CASE(SRET_FLAG) 10096 NODE_NAME_CASE(MRET_FLAG) 10097 NODE_NAME_CASE(CALL) 10098 NODE_NAME_CASE(SELECT_CC) 10099 NODE_NAME_CASE(BR_CC) 10100 NODE_NAME_CASE(BuildPairF64) 10101 NODE_NAME_CASE(SplitF64) 10102 NODE_NAME_CASE(TAIL) 10103 NODE_NAME_CASE(MULHSU) 10104 NODE_NAME_CASE(SLLW) 10105 NODE_NAME_CASE(SRAW) 10106 NODE_NAME_CASE(SRLW) 10107 NODE_NAME_CASE(DIVW) 10108 NODE_NAME_CASE(DIVUW) 10109 NODE_NAME_CASE(REMUW) 10110 NODE_NAME_CASE(ROLW) 10111 NODE_NAME_CASE(RORW) 10112 NODE_NAME_CASE(CLZW) 10113 NODE_NAME_CASE(CTZW) 10114 NODE_NAME_CASE(FSLW) 10115 NODE_NAME_CASE(FSRW) 10116 NODE_NAME_CASE(FSL) 10117 NODE_NAME_CASE(FSR) 10118 NODE_NAME_CASE(FMV_H_X) 10119 NODE_NAME_CASE(FMV_X_ANYEXTH) 10120 NODE_NAME_CASE(FMV_W_X_RV64) 10121 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10122 NODE_NAME_CASE(FCVT_X) 10123 NODE_NAME_CASE(FCVT_XU) 10124 NODE_NAME_CASE(FCVT_W_RV64) 10125 NODE_NAME_CASE(FCVT_WU_RV64) 10126 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10127 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10128 NODE_NAME_CASE(READ_CYCLE_WIDE) 10129 NODE_NAME_CASE(GREV) 10130 NODE_NAME_CASE(GREVW) 10131 NODE_NAME_CASE(GORC) 10132 NODE_NAME_CASE(GORCW) 10133 NODE_NAME_CASE(SHFL) 10134 NODE_NAME_CASE(SHFLW) 10135 NODE_NAME_CASE(UNSHFL) 10136 NODE_NAME_CASE(UNSHFLW) 10137 NODE_NAME_CASE(BFP) 10138 NODE_NAME_CASE(BFPW) 10139 NODE_NAME_CASE(BCOMPRESS) 10140 NODE_NAME_CASE(BCOMPRESSW) 10141 NODE_NAME_CASE(BDECOMPRESS) 10142 NODE_NAME_CASE(BDECOMPRESSW) 10143 NODE_NAME_CASE(VMV_V_X_VL) 10144 NODE_NAME_CASE(VFMV_V_F_VL) 10145 NODE_NAME_CASE(VMV_X_S) 10146 NODE_NAME_CASE(VMV_S_X_VL) 10147 NODE_NAME_CASE(VFMV_S_F_VL) 10148 NODE_NAME_CASE(SPLAT_VECTOR_I64) 10149 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10150 NODE_NAME_CASE(READ_VLENB) 10151 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10152 NODE_NAME_CASE(VSLIDEUP_VL) 10153 NODE_NAME_CASE(VSLIDE1UP_VL) 10154 NODE_NAME_CASE(VSLIDEDOWN_VL) 10155 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10156 NODE_NAME_CASE(VID_VL) 10157 NODE_NAME_CASE(VFNCVT_ROD_VL) 10158 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10159 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10160 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10161 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10162 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10163 NODE_NAME_CASE(VECREDUCE_AND_VL) 10164 NODE_NAME_CASE(VECREDUCE_OR_VL) 10165 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10166 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10167 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10168 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10169 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10170 NODE_NAME_CASE(ADD_VL) 10171 NODE_NAME_CASE(AND_VL) 10172 NODE_NAME_CASE(MUL_VL) 10173 NODE_NAME_CASE(OR_VL) 10174 NODE_NAME_CASE(SDIV_VL) 10175 NODE_NAME_CASE(SHL_VL) 10176 NODE_NAME_CASE(SREM_VL) 10177 NODE_NAME_CASE(SRA_VL) 10178 NODE_NAME_CASE(SRL_VL) 10179 NODE_NAME_CASE(SUB_VL) 10180 NODE_NAME_CASE(UDIV_VL) 10181 NODE_NAME_CASE(UREM_VL) 10182 NODE_NAME_CASE(XOR_VL) 10183 NODE_NAME_CASE(SADDSAT_VL) 10184 NODE_NAME_CASE(UADDSAT_VL) 10185 NODE_NAME_CASE(SSUBSAT_VL) 10186 NODE_NAME_CASE(USUBSAT_VL) 10187 NODE_NAME_CASE(FADD_VL) 10188 NODE_NAME_CASE(FSUB_VL) 10189 NODE_NAME_CASE(FMUL_VL) 10190 NODE_NAME_CASE(FDIV_VL) 10191 NODE_NAME_CASE(FNEG_VL) 10192 NODE_NAME_CASE(FABS_VL) 10193 NODE_NAME_CASE(FSQRT_VL) 10194 NODE_NAME_CASE(FMA_VL) 10195 NODE_NAME_CASE(FCOPYSIGN_VL) 10196 NODE_NAME_CASE(SMIN_VL) 10197 NODE_NAME_CASE(SMAX_VL) 10198 NODE_NAME_CASE(UMIN_VL) 10199 NODE_NAME_CASE(UMAX_VL) 10200 NODE_NAME_CASE(FMINNUM_VL) 10201 NODE_NAME_CASE(FMAXNUM_VL) 10202 NODE_NAME_CASE(MULHS_VL) 10203 NODE_NAME_CASE(MULHU_VL) 10204 NODE_NAME_CASE(FP_TO_SINT_VL) 10205 NODE_NAME_CASE(FP_TO_UINT_VL) 10206 NODE_NAME_CASE(SINT_TO_FP_VL) 10207 NODE_NAME_CASE(UINT_TO_FP_VL) 10208 NODE_NAME_CASE(FP_EXTEND_VL) 10209 NODE_NAME_CASE(FP_ROUND_VL) 10210 NODE_NAME_CASE(VWMUL_VL) 10211 NODE_NAME_CASE(VWMULU_VL) 10212 NODE_NAME_CASE(VWMULSU_VL) 10213 NODE_NAME_CASE(VWADDU_VL) 10214 NODE_NAME_CASE(SETCC_VL) 10215 NODE_NAME_CASE(VSELECT_VL) 10216 NODE_NAME_CASE(VP_MERGE_VL) 10217 NODE_NAME_CASE(VMAND_VL) 10218 NODE_NAME_CASE(VMOR_VL) 10219 NODE_NAME_CASE(VMXOR_VL) 10220 NODE_NAME_CASE(VMCLR_VL) 10221 NODE_NAME_CASE(VMSET_VL) 10222 NODE_NAME_CASE(VRGATHER_VX_VL) 10223 NODE_NAME_CASE(VRGATHER_VV_VL) 10224 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10225 NODE_NAME_CASE(VSEXT_VL) 10226 NODE_NAME_CASE(VZEXT_VL) 10227 NODE_NAME_CASE(VCPOP_VL) 10228 NODE_NAME_CASE(VLE_VL) 10229 NODE_NAME_CASE(VSE_VL) 10230 NODE_NAME_CASE(READ_CSR) 10231 NODE_NAME_CASE(WRITE_CSR) 10232 NODE_NAME_CASE(SWAP_CSR) 10233 } 10234 // clang-format on 10235 return nullptr; 10236 #undef NODE_NAME_CASE 10237 } 10238 10239 /// getConstraintType - Given a constraint letter, return the type of 10240 /// constraint it is for this target. 10241 RISCVTargetLowering::ConstraintType 10242 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 10243 if (Constraint.size() == 1) { 10244 switch (Constraint[0]) { 10245 default: 10246 break; 10247 case 'f': 10248 return C_RegisterClass; 10249 case 'I': 10250 case 'J': 10251 case 'K': 10252 return C_Immediate; 10253 case 'A': 10254 return C_Memory; 10255 case 'S': // A symbolic address 10256 return C_Other; 10257 } 10258 } else { 10259 if (Constraint == "vr" || Constraint == "vm") 10260 return C_RegisterClass; 10261 } 10262 return TargetLowering::getConstraintType(Constraint); 10263 } 10264 10265 std::pair<unsigned, const TargetRegisterClass *> 10266 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10267 StringRef Constraint, 10268 MVT VT) const { 10269 // First, see if this is a constraint that directly corresponds to a 10270 // RISCV register class. 10271 if (Constraint.size() == 1) { 10272 switch (Constraint[0]) { 10273 case 'r': 10274 // TODO: Support fixed vectors up to XLen for P extension? 10275 if (VT.isVector()) 10276 break; 10277 return std::make_pair(0U, &RISCV::GPRRegClass); 10278 case 'f': 10279 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 10280 return std::make_pair(0U, &RISCV::FPR16RegClass); 10281 if (Subtarget.hasStdExtF() && VT == MVT::f32) 10282 return std::make_pair(0U, &RISCV::FPR32RegClass); 10283 if (Subtarget.hasStdExtD() && VT == MVT::f64) 10284 return std::make_pair(0U, &RISCV::FPR64RegClass); 10285 break; 10286 default: 10287 break; 10288 } 10289 } else if (Constraint == "vr") { 10290 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 10291 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10292 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 10293 return std::make_pair(0U, RC); 10294 } 10295 } else if (Constraint == "vm") { 10296 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 10297 return std::make_pair(0U, &RISCV::VMV0RegClass); 10298 } 10299 10300 // Clang will correctly decode the usage of register name aliases into their 10301 // official names. However, other frontends like `rustc` do not. This allows 10302 // users of these frontends to use the ABI names for registers in LLVM-style 10303 // register constraints. 10304 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 10305 .Case("{zero}", RISCV::X0) 10306 .Case("{ra}", RISCV::X1) 10307 .Case("{sp}", RISCV::X2) 10308 .Case("{gp}", RISCV::X3) 10309 .Case("{tp}", RISCV::X4) 10310 .Case("{t0}", RISCV::X5) 10311 .Case("{t1}", RISCV::X6) 10312 .Case("{t2}", RISCV::X7) 10313 .Cases("{s0}", "{fp}", RISCV::X8) 10314 .Case("{s1}", RISCV::X9) 10315 .Case("{a0}", RISCV::X10) 10316 .Case("{a1}", RISCV::X11) 10317 .Case("{a2}", RISCV::X12) 10318 .Case("{a3}", RISCV::X13) 10319 .Case("{a4}", RISCV::X14) 10320 .Case("{a5}", RISCV::X15) 10321 .Case("{a6}", RISCV::X16) 10322 .Case("{a7}", RISCV::X17) 10323 .Case("{s2}", RISCV::X18) 10324 .Case("{s3}", RISCV::X19) 10325 .Case("{s4}", RISCV::X20) 10326 .Case("{s5}", RISCV::X21) 10327 .Case("{s6}", RISCV::X22) 10328 .Case("{s7}", RISCV::X23) 10329 .Case("{s8}", RISCV::X24) 10330 .Case("{s9}", RISCV::X25) 10331 .Case("{s10}", RISCV::X26) 10332 .Case("{s11}", RISCV::X27) 10333 .Case("{t3}", RISCV::X28) 10334 .Case("{t4}", RISCV::X29) 10335 .Case("{t5}", RISCV::X30) 10336 .Case("{t6}", RISCV::X31) 10337 .Default(RISCV::NoRegister); 10338 if (XRegFromAlias != RISCV::NoRegister) 10339 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 10340 10341 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 10342 // TableGen record rather than the AsmName to choose registers for InlineAsm 10343 // constraints, plus we want to match those names to the widest floating point 10344 // register type available, manually select floating point registers here. 10345 // 10346 // The second case is the ABI name of the register, so that frontends can also 10347 // use the ABI names in register constraint lists. 10348 if (Subtarget.hasStdExtF()) { 10349 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 10350 .Cases("{f0}", "{ft0}", RISCV::F0_F) 10351 .Cases("{f1}", "{ft1}", RISCV::F1_F) 10352 .Cases("{f2}", "{ft2}", RISCV::F2_F) 10353 .Cases("{f3}", "{ft3}", RISCV::F3_F) 10354 .Cases("{f4}", "{ft4}", RISCV::F4_F) 10355 .Cases("{f5}", "{ft5}", RISCV::F5_F) 10356 .Cases("{f6}", "{ft6}", RISCV::F6_F) 10357 .Cases("{f7}", "{ft7}", RISCV::F7_F) 10358 .Cases("{f8}", "{fs0}", RISCV::F8_F) 10359 .Cases("{f9}", "{fs1}", RISCV::F9_F) 10360 .Cases("{f10}", "{fa0}", RISCV::F10_F) 10361 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10362 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10363 .Cases("{f13}", "{fa3}", RISCV::F13_F) 10364 .Cases("{f14}", "{fa4}", RISCV::F14_F) 10365 .Cases("{f15}", "{fa5}", RISCV::F15_F) 10366 .Cases("{f16}", "{fa6}", RISCV::F16_F) 10367 .Cases("{f17}", "{fa7}", RISCV::F17_F) 10368 .Cases("{f18}", "{fs2}", RISCV::F18_F) 10369 .Cases("{f19}", "{fs3}", RISCV::F19_F) 10370 .Cases("{f20}", "{fs4}", RISCV::F20_F) 10371 .Cases("{f21}", "{fs5}", RISCV::F21_F) 10372 .Cases("{f22}", "{fs6}", RISCV::F22_F) 10373 .Cases("{f23}", "{fs7}", RISCV::F23_F) 10374 .Cases("{f24}", "{fs8}", RISCV::F24_F) 10375 .Cases("{f25}", "{fs9}", RISCV::F25_F) 10376 .Cases("{f26}", "{fs10}", RISCV::F26_F) 10377 .Cases("{f27}", "{fs11}", RISCV::F27_F) 10378 .Cases("{f28}", "{ft8}", RISCV::F28_F) 10379 .Cases("{f29}", "{ft9}", RISCV::F29_F) 10380 .Cases("{f30}", "{ft10}", RISCV::F30_F) 10381 .Cases("{f31}", "{ft11}", RISCV::F31_F) 10382 .Default(RISCV::NoRegister); 10383 if (FReg != RISCV::NoRegister) { 10384 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 10385 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 10386 unsigned RegNo = FReg - RISCV::F0_F; 10387 unsigned DReg = RISCV::F0_D + RegNo; 10388 return std::make_pair(DReg, &RISCV::FPR64RegClass); 10389 } 10390 if (VT == MVT::f32 || VT == MVT::Other) 10391 return std::make_pair(FReg, &RISCV::FPR32RegClass); 10392 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 10393 unsigned RegNo = FReg - RISCV::F0_F; 10394 unsigned HReg = RISCV::F0_H + RegNo; 10395 return std::make_pair(HReg, &RISCV::FPR16RegClass); 10396 } 10397 } 10398 } 10399 10400 if (Subtarget.hasVInstructions()) { 10401 Register VReg = StringSwitch<Register>(Constraint.lower()) 10402 .Case("{v0}", RISCV::V0) 10403 .Case("{v1}", RISCV::V1) 10404 .Case("{v2}", RISCV::V2) 10405 .Case("{v3}", RISCV::V3) 10406 .Case("{v4}", RISCV::V4) 10407 .Case("{v5}", RISCV::V5) 10408 .Case("{v6}", RISCV::V6) 10409 .Case("{v7}", RISCV::V7) 10410 .Case("{v8}", RISCV::V8) 10411 .Case("{v9}", RISCV::V9) 10412 .Case("{v10}", RISCV::V10) 10413 .Case("{v11}", RISCV::V11) 10414 .Case("{v12}", RISCV::V12) 10415 .Case("{v13}", RISCV::V13) 10416 .Case("{v14}", RISCV::V14) 10417 .Case("{v15}", RISCV::V15) 10418 .Case("{v16}", RISCV::V16) 10419 .Case("{v17}", RISCV::V17) 10420 .Case("{v18}", RISCV::V18) 10421 .Case("{v19}", RISCV::V19) 10422 .Case("{v20}", RISCV::V20) 10423 .Case("{v21}", RISCV::V21) 10424 .Case("{v22}", RISCV::V22) 10425 .Case("{v23}", RISCV::V23) 10426 .Case("{v24}", RISCV::V24) 10427 .Case("{v25}", RISCV::V25) 10428 .Case("{v26}", RISCV::V26) 10429 .Case("{v27}", RISCV::V27) 10430 .Case("{v28}", RISCV::V28) 10431 .Case("{v29}", RISCV::V29) 10432 .Case("{v30}", RISCV::V30) 10433 .Case("{v31}", RISCV::V31) 10434 .Default(RISCV::NoRegister); 10435 if (VReg != RISCV::NoRegister) { 10436 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 10437 return std::make_pair(VReg, &RISCV::VMRegClass); 10438 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 10439 return std::make_pair(VReg, &RISCV::VRRegClass); 10440 for (const auto *RC : 10441 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10442 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 10443 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 10444 return std::make_pair(VReg, RC); 10445 } 10446 } 10447 } 10448 } 10449 10450 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10451 } 10452 10453 unsigned 10454 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 10455 // Currently only support length 1 constraints. 10456 if (ConstraintCode.size() == 1) { 10457 switch (ConstraintCode[0]) { 10458 case 'A': 10459 return InlineAsm::Constraint_A; 10460 default: 10461 break; 10462 } 10463 } 10464 10465 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 10466 } 10467 10468 void RISCVTargetLowering::LowerAsmOperandForConstraint( 10469 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 10470 SelectionDAG &DAG) const { 10471 // Currently only support length 1 constraints. 10472 if (Constraint.length() == 1) { 10473 switch (Constraint[0]) { 10474 case 'I': 10475 // Validate & create a 12-bit signed immediate operand. 10476 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10477 uint64_t CVal = C->getSExtValue(); 10478 if (isInt<12>(CVal)) 10479 Ops.push_back( 10480 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10481 } 10482 return; 10483 case 'J': 10484 // Validate & create an integer zero operand. 10485 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 10486 if (C->getZExtValue() == 0) 10487 Ops.push_back( 10488 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 10489 return; 10490 case 'K': 10491 // Validate & create a 5-bit unsigned immediate operand. 10492 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10493 uint64_t CVal = C->getZExtValue(); 10494 if (isUInt<5>(CVal)) 10495 Ops.push_back( 10496 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10497 } 10498 return; 10499 case 'S': 10500 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 10501 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 10502 GA->getValueType(0))); 10503 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 10504 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 10505 BA->getValueType(0))); 10506 } 10507 return; 10508 default: 10509 break; 10510 } 10511 } 10512 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 10513 } 10514 10515 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 10516 Instruction *Inst, 10517 AtomicOrdering Ord) const { 10518 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 10519 return Builder.CreateFence(Ord); 10520 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 10521 return Builder.CreateFence(AtomicOrdering::Release); 10522 return nullptr; 10523 } 10524 10525 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 10526 Instruction *Inst, 10527 AtomicOrdering Ord) const { 10528 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 10529 return Builder.CreateFence(AtomicOrdering::Acquire); 10530 return nullptr; 10531 } 10532 10533 TargetLowering::AtomicExpansionKind 10534 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10535 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 10536 // point operations can't be used in an lr/sc sequence without breaking the 10537 // forward-progress guarantee. 10538 if (AI->isFloatingPointOperation()) 10539 return AtomicExpansionKind::CmpXChg; 10540 10541 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10542 if (Size == 8 || Size == 16) 10543 return AtomicExpansionKind::MaskedIntrinsic; 10544 return AtomicExpansionKind::None; 10545 } 10546 10547 static Intrinsic::ID 10548 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 10549 if (XLen == 32) { 10550 switch (BinOp) { 10551 default: 10552 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10553 case AtomicRMWInst::Xchg: 10554 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 10555 case AtomicRMWInst::Add: 10556 return Intrinsic::riscv_masked_atomicrmw_add_i32; 10557 case AtomicRMWInst::Sub: 10558 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 10559 case AtomicRMWInst::Nand: 10560 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 10561 case AtomicRMWInst::Max: 10562 return Intrinsic::riscv_masked_atomicrmw_max_i32; 10563 case AtomicRMWInst::Min: 10564 return Intrinsic::riscv_masked_atomicrmw_min_i32; 10565 case AtomicRMWInst::UMax: 10566 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 10567 case AtomicRMWInst::UMin: 10568 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 10569 } 10570 } 10571 10572 if (XLen == 64) { 10573 switch (BinOp) { 10574 default: 10575 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10576 case AtomicRMWInst::Xchg: 10577 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 10578 case AtomicRMWInst::Add: 10579 return Intrinsic::riscv_masked_atomicrmw_add_i64; 10580 case AtomicRMWInst::Sub: 10581 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 10582 case AtomicRMWInst::Nand: 10583 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 10584 case AtomicRMWInst::Max: 10585 return Intrinsic::riscv_masked_atomicrmw_max_i64; 10586 case AtomicRMWInst::Min: 10587 return Intrinsic::riscv_masked_atomicrmw_min_i64; 10588 case AtomicRMWInst::UMax: 10589 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 10590 case AtomicRMWInst::UMin: 10591 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 10592 } 10593 } 10594 10595 llvm_unreachable("Unexpected XLen\n"); 10596 } 10597 10598 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 10599 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 10600 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 10601 unsigned XLen = Subtarget.getXLen(); 10602 Value *Ordering = 10603 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 10604 Type *Tys[] = {AlignedAddr->getType()}; 10605 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 10606 AI->getModule(), 10607 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 10608 10609 if (XLen == 64) { 10610 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 10611 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10612 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 10613 } 10614 10615 Value *Result; 10616 10617 // Must pass the shift amount needed to sign extend the loaded value prior 10618 // to performing a signed comparison for min/max. ShiftAmt is the number of 10619 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 10620 // is the number of bits to left+right shift the value in order to 10621 // sign-extend. 10622 if (AI->getOperation() == AtomicRMWInst::Min || 10623 AI->getOperation() == AtomicRMWInst::Max) { 10624 const DataLayout &DL = AI->getModule()->getDataLayout(); 10625 unsigned ValWidth = 10626 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 10627 Value *SextShamt = 10628 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 10629 Result = Builder.CreateCall(LrwOpScwLoop, 10630 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 10631 } else { 10632 Result = 10633 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 10634 } 10635 10636 if (XLen == 64) 10637 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10638 return Result; 10639 } 10640 10641 TargetLowering::AtomicExpansionKind 10642 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 10643 AtomicCmpXchgInst *CI) const { 10644 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 10645 if (Size == 8 || Size == 16) 10646 return AtomicExpansionKind::MaskedIntrinsic; 10647 return AtomicExpansionKind::None; 10648 } 10649 10650 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 10651 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 10652 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 10653 unsigned XLen = Subtarget.getXLen(); 10654 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 10655 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 10656 if (XLen == 64) { 10657 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 10658 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 10659 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10660 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 10661 } 10662 Type *Tys[] = {AlignedAddr->getType()}; 10663 Function *MaskedCmpXchg = 10664 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 10665 Value *Result = Builder.CreateCall( 10666 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 10667 if (XLen == 64) 10668 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10669 return Result; 10670 } 10671 10672 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 10673 return false; 10674 } 10675 10676 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 10677 EVT VT) const { 10678 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 10679 return false; 10680 10681 switch (FPVT.getSimpleVT().SimpleTy) { 10682 case MVT::f16: 10683 return Subtarget.hasStdExtZfh(); 10684 case MVT::f32: 10685 return Subtarget.hasStdExtF(); 10686 case MVT::f64: 10687 return Subtarget.hasStdExtD(); 10688 default: 10689 return false; 10690 } 10691 } 10692 10693 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 10694 // If we are using the small code model, we can reduce size of jump table 10695 // entry to 4 bytes. 10696 if (Subtarget.is64Bit() && !isPositionIndependent() && 10697 getTargetMachine().getCodeModel() == CodeModel::Small) { 10698 return MachineJumpTableInfo::EK_Custom32; 10699 } 10700 return TargetLowering::getJumpTableEncoding(); 10701 } 10702 10703 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 10704 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 10705 unsigned uid, MCContext &Ctx) const { 10706 assert(Subtarget.is64Bit() && !isPositionIndependent() && 10707 getTargetMachine().getCodeModel() == CodeModel::Small); 10708 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 10709 } 10710 10711 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 10712 EVT VT) const { 10713 VT = VT.getScalarType(); 10714 10715 if (!VT.isSimple()) 10716 return false; 10717 10718 switch (VT.getSimpleVT().SimpleTy) { 10719 case MVT::f16: 10720 return Subtarget.hasStdExtZfh(); 10721 case MVT::f32: 10722 return Subtarget.hasStdExtF(); 10723 case MVT::f64: 10724 return Subtarget.hasStdExtD(); 10725 default: 10726 break; 10727 } 10728 10729 return false; 10730 } 10731 10732 Register RISCVTargetLowering::getExceptionPointerRegister( 10733 const Constant *PersonalityFn) const { 10734 return RISCV::X10; 10735 } 10736 10737 Register RISCVTargetLowering::getExceptionSelectorRegister( 10738 const Constant *PersonalityFn) const { 10739 return RISCV::X11; 10740 } 10741 10742 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 10743 // Return false to suppress the unnecessary extensions if the LibCall 10744 // arguments or return value is f32 type for LP64 ABI. 10745 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 10746 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 10747 return false; 10748 10749 return true; 10750 } 10751 10752 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 10753 if (Subtarget.is64Bit() && Type == MVT::i32) 10754 return true; 10755 10756 return IsSigned; 10757 } 10758 10759 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 10760 SDValue C) const { 10761 // Check integral scalar types. 10762 if (VT.isScalarInteger()) { 10763 // Omit the optimization if the sub target has the M extension and the data 10764 // size exceeds XLen. 10765 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 10766 return false; 10767 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 10768 // Break the MUL to a SLLI and an ADD/SUB. 10769 const APInt &Imm = ConstNode->getAPIntValue(); 10770 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 10771 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 10772 return true; 10773 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 10774 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 10775 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 10776 (Imm - 8).isPowerOf2())) 10777 return true; 10778 // Omit the following optimization if the sub target has the M extension 10779 // and the data size >= XLen. 10780 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 10781 return false; 10782 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 10783 // a pair of LUI/ADDI. 10784 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 10785 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 10786 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 10787 (1 - ImmS).isPowerOf2()) 10788 return true; 10789 } 10790 } 10791 } 10792 10793 return false; 10794 } 10795 10796 bool RISCVTargetLowering::isMulAddWithConstProfitable( 10797 const SDValue &AddNode, const SDValue &ConstNode) const { 10798 // Let the DAGCombiner decide for vectors. 10799 EVT VT = AddNode.getValueType(); 10800 if (VT.isVector()) 10801 return true; 10802 10803 // Let the DAGCombiner decide for larger types. 10804 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 10805 return true; 10806 10807 // It is worse if c1 is simm12 while c1*c2 is not. 10808 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 10809 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 10810 const APInt &C1 = C1Node->getAPIntValue(); 10811 const APInt &C2 = C2Node->getAPIntValue(); 10812 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 10813 return false; 10814 10815 // Default to true and let the DAGCombiner decide. 10816 return true; 10817 } 10818 10819 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 10820 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 10821 bool *Fast) const { 10822 if (!VT.isVector()) 10823 return false; 10824 10825 EVT ElemVT = VT.getVectorElementType(); 10826 if (Alignment >= ElemVT.getStoreSize()) { 10827 if (Fast) 10828 *Fast = true; 10829 return true; 10830 } 10831 10832 return false; 10833 } 10834 10835 bool RISCVTargetLowering::splitValueIntoRegisterParts( 10836 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 10837 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 10838 bool IsABIRegCopy = CC.hasValue(); 10839 EVT ValueVT = Val.getValueType(); 10840 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10841 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 10842 // and cast to f32. 10843 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 10844 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 10845 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 10846 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 10847 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 10848 Parts[0] = Val; 10849 return true; 10850 } 10851 10852 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10853 LLVMContext &Context = *DAG.getContext(); 10854 EVT ValueEltVT = ValueVT.getVectorElementType(); 10855 EVT PartEltVT = PartVT.getVectorElementType(); 10856 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10857 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10858 if (PartVTBitSize % ValueVTBitSize == 0) { 10859 assert(PartVTBitSize >= ValueVTBitSize); 10860 // If the element types are different, bitcast to the same element type of 10861 // PartVT first. 10862 // Give an example here, we want copy a <vscale x 1 x i8> value to 10863 // <vscale x 4 x i16>. 10864 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 10865 // subvector, then we can bitcast to <vscale x 4 x i16>. 10866 if (ValueEltVT != PartEltVT) { 10867 if (PartVTBitSize > ValueVTBitSize) { 10868 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 10869 assert(Count != 0 && "The number of element should not be zero."); 10870 EVT SameEltTypeVT = 10871 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 10872 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 10873 DAG.getUNDEF(SameEltTypeVT), Val, 10874 DAG.getVectorIdxConstant(0, DL)); 10875 } 10876 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 10877 } else { 10878 Val = 10879 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 10880 Val, DAG.getVectorIdxConstant(0, DL)); 10881 } 10882 Parts[0] = Val; 10883 return true; 10884 } 10885 } 10886 return false; 10887 } 10888 10889 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 10890 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 10891 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 10892 bool IsABIRegCopy = CC.hasValue(); 10893 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10894 SDValue Val = Parts[0]; 10895 10896 // Cast the f32 to i32, truncate to i16, and cast back to f16. 10897 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 10898 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 10899 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 10900 return Val; 10901 } 10902 10903 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10904 LLVMContext &Context = *DAG.getContext(); 10905 SDValue Val = Parts[0]; 10906 EVT ValueEltVT = ValueVT.getVectorElementType(); 10907 EVT PartEltVT = PartVT.getVectorElementType(); 10908 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10909 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10910 if (PartVTBitSize % ValueVTBitSize == 0) { 10911 assert(PartVTBitSize >= ValueVTBitSize); 10912 EVT SameEltTypeVT = ValueVT; 10913 // If the element types are different, convert it to the same element type 10914 // of PartVT. 10915 // Give an example here, we want copy a <vscale x 1 x i8> value from 10916 // <vscale x 4 x i16>. 10917 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 10918 // then we can extract <vscale x 1 x i8>. 10919 if (ValueEltVT != PartEltVT) { 10920 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 10921 assert(Count != 0 && "The number of element should not be zero."); 10922 SameEltTypeVT = 10923 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 10924 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 10925 } 10926 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 10927 DAG.getVectorIdxConstant(0, DL)); 10928 return Val; 10929 } 10930 } 10931 return SDValue(); 10932 } 10933 10934 SDValue 10935 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 10936 SelectionDAG &DAG, 10937 SmallVectorImpl<SDNode *> &Created) const { 10938 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 10939 if (isIntDivCheap(N->getValueType(0), Attr)) 10940 return SDValue(N, 0); // Lower SDIV as SDIV 10941 10942 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 10943 "Unexpected divisor!"); 10944 10945 // Conditional move is needed, so do the transformation iff Zbt is enabled. 10946 if (!Subtarget.hasStdExtZbt()) 10947 return SDValue(); 10948 10949 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 10950 // Besides, more critical path instructions will be generated when dividing 10951 // by 2. So we keep using the original DAGs for these cases. 10952 unsigned Lg2 = Divisor.countTrailingZeros(); 10953 if (Lg2 == 1 || Lg2 >= 12) 10954 return SDValue(); 10955 10956 // fold (sdiv X, pow2) 10957 EVT VT = N->getValueType(0); 10958 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 10959 return SDValue(); 10960 10961 SDLoc DL(N); 10962 SDValue N0 = N->getOperand(0); 10963 SDValue Zero = DAG.getConstant(0, DL, VT); 10964 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 10965 10966 // Add (N0 < 0) ? Pow2 - 1 : 0; 10967 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 10968 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 10969 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 10970 10971 Created.push_back(Cmp.getNode()); 10972 Created.push_back(Add.getNode()); 10973 Created.push_back(Sel.getNode()); 10974 10975 // Divide by pow2. 10976 SDValue SRA = 10977 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 10978 10979 // If we're dividing by a positive value, we're done. Otherwise, we must 10980 // negate the result. 10981 if (Divisor.isNonNegative()) 10982 return SRA; 10983 10984 Created.push_back(SRA.getNode()); 10985 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 10986 } 10987 10988 #define GET_REGISTER_MATCHER 10989 #include "RISCVGenAsmMatcher.inc" 10990 10991 Register 10992 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 10993 const MachineFunction &MF) const { 10994 Register Reg = MatchRegisterAltName(RegName); 10995 if (Reg == RISCV::NoRegister) 10996 Reg = MatchRegisterName(RegName); 10997 if (Reg == RISCV::NoRegister) 10998 report_fatal_error( 10999 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11000 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11001 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11002 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11003 StringRef(RegName) + "\".")); 11004 return Reg; 11005 } 11006 11007 namespace llvm { 11008 namespace RISCVVIntrinsicsTable { 11009 11010 #define GET_RISCVVIntrinsicsTable_IMPL 11011 #include "RISCVGenSearchableTables.inc" 11012 11013 } // namespace RISCVVIntrinsicsTable 11014 11015 } // namespace llvm 11016