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 if (Subtarget.is64Bit()) { 255 setOperationAction(ISD::ROTL, MVT::i32, Custom); 256 setOperationAction(ISD::ROTR, MVT::i32, Custom); 257 } 258 } else { 259 setOperationAction(ISD::ROTL, XLenVT, Expand); 260 setOperationAction(ISD::ROTR, XLenVT, Expand); 261 } 262 263 if (Subtarget.hasStdExtZbp()) { 264 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 265 // more combining. 266 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 267 setOperationAction(ISD::BSWAP, XLenVT, Custom); 268 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 269 // BSWAP i8 doesn't exist. 270 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 271 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 272 273 if (Subtarget.is64Bit()) { 274 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 275 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 276 } 277 } else { 278 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 279 // pattern match it directly in isel. 280 setOperationAction(ISD::BSWAP, XLenVT, 281 Subtarget.hasStdExtZbb() ? Legal : Expand); 282 } 283 284 if (Subtarget.hasStdExtZbb()) { 285 setOperationAction(ISD::SMIN, XLenVT, Legal); 286 setOperationAction(ISD::SMAX, XLenVT, Legal); 287 setOperationAction(ISD::UMIN, XLenVT, Legal); 288 setOperationAction(ISD::UMAX, XLenVT, Legal); 289 290 if (Subtarget.is64Bit()) { 291 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 292 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 293 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 294 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 295 } 296 } else { 297 setOperationAction(ISD::CTTZ, XLenVT, Expand); 298 setOperationAction(ISD::CTLZ, XLenVT, Expand); 299 setOperationAction(ISD::CTPOP, XLenVT, Expand); 300 } 301 302 if (Subtarget.hasStdExtZbt()) { 303 setOperationAction(ISD::FSHL, XLenVT, Custom); 304 setOperationAction(ISD::FSHR, XLenVT, Custom); 305 setOperationAction(ISD::SELECT, XLenVT, Legal); 306 307 if (Subtarget.is64Bit()) { 308 setOperationAction(ISD::FSHL, MVT::i32, Custom); 309 setOperationAction(ISD::FSHR, MVT::i32, Custom); 310 } 311 } else { 312 setOperationAction(ISD::SELECT, XLenVT, Custom); 313 } 314 315 static const ISD::CondCode FPCCToExpand[] = { 316 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 317 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 318 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 319 320 static const ISD::NodeType FPOpToExpand[] = { 321 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 322 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 323 324 if (Subtarget.hasStdExtZfh()) 325 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 326 327 if (Subtarget.hasStdExtZfh()) { 328 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 329 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 330 setOperationAction(ISD::LRINT, MVT::f16, Legal); 331 setOperationAction(ISD::LLRINT, MVT::f16, Legal); 332 setOperationAction(ISD::LROUND, MVT::f16, Legal); 333 setOperationAction(ISD::LLROUND, MVT::f16, Legal); 334 setOperationAction(ISD::STRICT_LRINT, MVT::f16, Legal); 335 setOperationAction(ISD::STRICT_LLRINT, MVT::f16, Legal); 336 setOperationAction(ISD::STRICT_LROUND, MVT::f16, Legal); 337 setOperationAction(ISD::STRICT_LLROUND, MVT::f16, Legal); 338 setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal); 339 setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal); 340 setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal); 341 setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal); 342 setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal); 343 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 344 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 345 setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal); 346 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Legal); 347 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Legal); 348 for (auto CC : FPCCToExpand) 349 setCondCodeAction(CC, MVT::f16, Expand); 350 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 351 setOperationAction(ISD::SELECT, MVT::f16, Custom); 352 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 353 354 setOperationAction(ISD::FREM, MVT::f16, Promote); 355 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 356 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 357 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 358 setOperationAction(ISD::FRINT, MVT::f16, Promote); 359 setOperationAction(ISD::FROUND, MVT::f16, Promote); 360 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 361 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 362 setOperationAction(ISD::FPOW, MVT::f16, Promote); 363 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 364 setOperationAction(ISD::FCOS, MVT::f16, Promote); 365 setOperationAction(ISD::FSIN, MVT::f16, Promote); 366 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 367 setOperationAction(ISD::FEXP, MVT::f16, Promote); 368 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 369 setOperationAction(ISD::FLOG, MVT::f16, Promote); 370 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 371 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 372 373 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 374 // complete support for all operations in LegalizeDAG. 375 376 // We need to custom promote this. 377 if (Subtarget.is64Bit()) 378 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 379 } 380 381 if (Subtarget.hasStdExtF()) { 382 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 383 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 384 setOperationAction(ISD::LRINT, MVT::f32, Legal); 385 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 386 setOperationAction(ISD::LROUND, MVT::f32, Legal); 387 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 388 setOperationAction(ISD::STRICT_LRINT, MVT::f32, Legal); 389 setOperationAction(ISD::STRICT_LLRINT, MVT::f32, Legal); 390 setOperationAction(ISD::STRICT_LROUND, MVT::f32, Legal); 391 setOperationAction(ISD::STRICT_LLROUND, MVT::f32, Legal); 392 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 393 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 394 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 395 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 396 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 397 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 398 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 399 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 400 for (auto CC : FPCCToExpand) 401 setCondCodeAction(CC, MVT::f32, Expand); 402 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 403 setOperationAction(ISD::SELECT, MVT::f32, Custom); 404 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 405 for (auto Op : FPOpToExpand) 406 setOperationAction(Op, MVT::f32, Expand); 407 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 408 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 409 } 410 411 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 412 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 413 414 if (Subtarget.hasStdExtD()) { 415 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 416 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 417 setOperationAction(ISD::LRINT, MVT::f64, Legal); 418 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 419 setOperationAction(ISD::LROUND, MVT::f64, Legal); 420 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 421 setOperationAction(ISD::STRICT_LRINT, MVT::f64, Legal); 422 setOperationAction(ISD::STRICT_LLRINT, MVT::f64, Legal); 423 setOperationAction(ISD::STRICT_LROUND, MVT::f64, Legal); 424 setOperationAction(ISD::STRICT_LLROUND, MVT::f64, Legal); 425 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 426 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 427 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 428 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 429 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 430 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 431 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 432 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 433 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 434 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 435 for (auto CC : FPCCToExpand) 436 setCondCodeAction(CC, MVT::f64, Expand); 437 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 438 setOperationAction(ISD::SELECT, MVT::f64, Custom); 439 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 440 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 441 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 442 for (auto Op : FPOpToExpand) 443 setOperationAction(Op, MVT::f64, Expand); 444 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 445 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 446 } 447 448 if (Subtarget.is64Bit()) { 449 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 450 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 451 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 452 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 453 } 454 455 if (Subtarget.hasStdExtF()) { 456 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 457 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 458 459 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 460 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 461 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 462 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 463 464 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 465 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 466 } 467 468 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 469 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 470 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 471 setOperationAction(ISD::JumpTable, XLenVT, Custom); 472 473 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 474 475 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 476 // Unfortunately this can't be determined just from the ISA naming string. 477 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 478 Subtarget.is64Bit() ? Legal : Custom); 479 480 setOperationAction(ISD::TRAP, MVT::Other, Legal); 481 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 482 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 483 if (Subtarget.is64Bit()) 484 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 485 486 if (Subtarget.hasStdExtA()) { 487 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 488 setMinCmpXchgSizeInBits(32); 489 } else { 490 setMaxAtomicSizeInBitsSupported(0); 491 } 492 493 setBooleanContents(ZeroOrOneBooleanContent); 494 495 if (Subtarget.hasVInstructions()) { 496 setBooleanVectorContents(ZeroOrOneBooleanContent); 497 498 setOperationAction(ISD::VSCALE, XLenVT, Custom); 499 500 // RVV intrinsics may have illegal operands. 501 // We also need to custom legalize vmv.x.s. 502 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 503 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 504 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 505 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 506 if (Subtarget.is64Bit()) { 507 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 508 } else { 509 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 510 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 511 } 512 513 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 514 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 515 516 static const unsigned IntegerVPOps[] = { 517 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 518 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 519 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 520 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 521 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 522 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 523 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 524 ISD::VP_SELECT}; 525 526 static const unsigned FloatingPointVPOps[] = { 527 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 528 ISD::VP_FDIV, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 529 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_SELECT}; 530 531 if (!Subtarget.is64Bit()) { 532 // We must custom-lower certain vXi64 operations on RV32 due to the vector 533 // element type being illegal. 534 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 535 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 536 537 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 538 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 539 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 540 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 541 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 542 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 543 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 544 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 545 546 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 547 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 548 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 549 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 550 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 551 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 552 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 553 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 554 } 555 556 for (MVT VT : BoolVecVTs) { 557 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 558 559 // Mask VTs are custom-expanded into a series of standard nodes 560 setOperationAction(ISD::TRUNCATE, VT, Custom); 561 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 562 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 563 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 564 565 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 566 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 567 568 setOperationAction(ISD::SELECT, VT, Custom); 569 setOperationAction(ISD::SELECT_CC, VT, Expand); 570 setOperationAction(ISD::VSELECT, VT, Expand); 571 setOperationAction(ISD::VP_SELECT, VT, Expand); 572 573 setOperationAction(ISD::VP_AND, VT, Custom); 574 setOperationAction(ISD::VP_OR, VT, Custom); 575 setOperationAction(ISD::VP_XOR, VT, Custom); 576 577 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 578 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 579 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 580 581 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 582 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 583 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 584 585 // RVV has native int->float & float->int conversions where the 586 // element type sizes are within one power-of-two of each other. Any 587 // wider distances between type sizes have to be lowered as sequences 588 // which progressively narrow the gap in stages. 589 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 590 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 591 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 592 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 593 594 // Expand all extending loads to types larger than this, and truncating 595 // stores from types larger than this. 596 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 597 setTruncStoreAction(OtherVT, VT, Expand); 598 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 599 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 600 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 601 } 602 } 603 604 for (MVT VT : IntVecVTs) { 605 if (VT.getVectorElementType() == MVT::i64 && 606 !Subtarget.hasVInstructionsI64()) 607 continue; 608 609 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 610 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 611 612 // Vectors implement MULHS/MULHU. 613 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 614 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 615 616 setOperationAction(ISD::SMIN, VT, Legal); 617 setOperationAction(ISD::SMAX, VT, Legal); 618 setOperationAction(ISD::UMIN, VT, Legal); 619 setOperationAction(ISD::UMAX, VT, Legal); 620 621 setOperationAction(ISD::ROTL, VT, Expand); 622 setOperationAction(ISD::ROTR, VT, Expand); 623 624 setOperationAction(ISD::CTTZ, VT, Expand); 625 setOperationAction(ISD::CTLZ, VT, Expand); 626 setOperationAction(ISD::CTPOP, VT, Expand); 627 628 setOperationAction(ISD::BSWAP, VT, Expand); 629 630 // Custom-lower extensions and truncations from/to mask types. 631 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 632 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 633 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 634 635 // RVV has native int->float & float->int conversions where the 636 // element type sizes are within one power-of-two of each other. Any 637 // wider distances between type sizes have to be lowered as sequences 638 // which progressively narrow the gap in stages. 639 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 640 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 641 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 642 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 643 644 setOperationAction(ISD::SADDSAT, VT, Legal); 645 setOperationAction(ISD::UADDSAT, VT, Legal); 646 setOperationAction(ISD::SSUBSAT, VT, Legal); 647 setOperationAction(ISD::USUBSAT, VT, Legal); 648 649 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 650 // nodes which truncate by one power of two at a time. 651 setOperationAction(ISD::TRUNCATE, VT, Custom); 652 653 // Custom-lower insert/extract operations to simplify patterns. 654 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 655 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 656 657 // Custom-lower reduction operations to set up the corresponding custom 658 // nodes' operands. 659 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 660 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 661 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 662 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 663 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 664 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 665 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 666 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 667 668 for (unsigned VPOpc : IntegerVPOps) 669 setOperationAction(VPOpc, VT, Custom); 670 671 setOperationAction(ISD::LOAD, VT, Custom); 672 setOperationAction(ISD::STORE, VT, Custom); 673 674 setOperationAction(ISD::MLOAD, VT, Custom); 675 setOperationAction(ISD::MSTORE, VT, Custom); 676 setOperationAction(ISD::MGATHER, VT, Custom); 677 setOperationAction(ISD::MSCATTER, VT, Custom); 678 679 setOperationAction(ISD::VP_LOAD, VT, Custom); 680 setOperationAction(ISD::VP_STORE, VT, Custom); 681 setOperationAction(ISD::VP_GATHER, VT, Custom); 682 setOperationAction(ISD::VP_SCATTER, VT, Custom); 683 684 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 685 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 686 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 687 688 setOperationAction(ISD::SELECT, VT, Custom); 689 setOperationAction(ISD::SELECT_CC, VT, Expand); 690 691 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 692 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 693 694 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 695 setTruncStoreAction(VT, OtherVT, Expand); 696 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 697 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 698 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 699 } 700 701 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 702 // type that can represent the value exactly. 703 if (VT.getVectorElementType() != MVT::i64) { 704 MVT FloatEltVT = 705 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 706 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 707 if (isTypeLegal(FloatVT)) { 708 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 709 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 710 } 711 } 712 } 713 714 // Expand various CCs to best match the RVV ISA, which natively supports UNE 715 // but no other unordered comparisons, and supports all ordered comparisons 716 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 717 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 718 // and we pattern-match those back to the "original", swapping operands once 719 // more. This way we catch both operations and both "vf" and "fv" forms with 720 // fewer patterns. 721 static const ISD::CondCode VFPCCToExpand[] = { 722 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 723 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 724 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 725 }; 726 727 // Sets common operation actions on RVV floating-point vector types. 728 const auto SetCommonVFPActions = [&](MVT VT) { 729 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 730 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 731 // sizes are within one power-of-two of each other. Therefore conversions 732 // between vXf16 and vXf64 must be lowered as sequences which convert via 733 // vXf32. 734 setOperationAction(ISD::FP_ROUND, VT, Custom); 735 setOperationAction(ISD::FP_EXTEND, VT, Custom); 736 // Custom-lower insert/extract operations to simplify patterns. 737 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 738 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 739 // Expand various condition codes (explained above). 740 for (auto CC : VFPCCToExpand) 741 setCondCodeAction(CC, VT, Expand); 742 743 setOperationAction(ISD::FMINNUM, VT, Legal); 744 setOperationAction(ISD::FMAXNUM, VT, Legal); 745 746 setOperationAction(ISD::FTRUNC, VT, Custom); 747 setOperationAction(ISD::FCEIL, VT, Custom); 748 setOperationAction(ISD::FFLOOR, VT, Custom); 749 750 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 751 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 752 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 753 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 754 755 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 756 757 setOperationAction(ISD::LOAD, VT, Custom); 758 setOperationAction(ISD::STORE, VT, Custom); 759 760 setOperationAction(ISD::MLOAD, VT, Custom); 761 setOperationAction(ISD::MSTORE, VT, Custom); 762 setOperationAction(ISD::MGATHER, VT, Custom); 763 setOperationAction(ISD::MSCATTER, VT, Custom); 764 765 setOperationAction(ISD::VP_LOAD, VT, Custom); 766 setOperationAction(ISD::VP_STORE, VT, Custom); 767 setOperationAction(ISD::VP_GATHER, VT, Custom); 768 setOperationAction(ISD::VP_SCATTER, VT, Custom); 769 770 setOperationAction(ISD::SELECT, VT, Custom); 771 setOperationAction(ISD::SELECT_CC, VT, Expand); 772 773 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 774 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 775 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 776 777 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 778 779 for (unsigned VPOpc : FloatingPointVPOps) 780 setOperationAction(VPOpc, VT, Custom); 781 }; 782 783 // Sets common extload/truncstore actions on RVV floating-point vector 784 // types. 785 const auto SetCommonVFPExtLoadTruncStoreActions = 786 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 787 for (auto SmallVT : SmallerVTs) { 788 setTruncStoreAction(VT, SmallVT, Expand); 789 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 790 } 791 }; 792 793 if (Subtarget.hasVInstructionsF16()) 794 for (MVT VT : F16VecVTs) 795 SetCommonVFPActions(VT); 796 797 for (MVT VT : F32VecVTs) { 798 if (Subtarget.hasVInstructionsF32()) 799 SetCommonVFPActions(VT); 800 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 801 } 802 803 for (MVT VT : F64VecVTs) { 804 if (Subtarget.hasVInstructionsF64()) 805 SetCommonVFPActions(VT); 806 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 807 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 808 } 809 810 if (Subtarget.useRVVForFixedLengthVectors()) { 811 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 812 if (!useRVVForFixedLengthVectorVT(VT)) 813 continue; 814 815 // By default everything must be expanded. 816 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 817 setOperationAction(Op, VT, Expand); 818 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 819 setTruncStoreAction(VT, OtherVT, Expand); 820 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 821 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 822 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 823 } 824 825 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 826 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 827 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 828 829 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 830 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 831 832 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 833 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 834 835 setOperationAction(ISD::LOAD, VT, Custom); 836 setOperationAction(ISD::STORE, VT, Custom); 837 838 setOperationAction(ISD::SETCC, VT, Custom); 839 840 setOperationAction(ISD::SELECT, VT, Custom); 841 842 setOperationAction(ISD::TRUNCATE, VT, Custom); 843 844 setOperationAction(ISD::BITCAST, VT, Custom); 845 846 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 847 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 848 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 849 850 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 851 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 852 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 853 854 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 855 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 856 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 857 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 858 859 // Operations below are different for between masks and other vectors. 860 if (VT.getVectorElementType() == MVT::i1) { 861 setOperationAction(ISD::VP_AND, VT, Custom); 862 setOperationAction(ISD::VP_OR, VT, Custom); 863 setOperationAction(ISD::VP_XOR, VT, Custom); 864 setOperationAction(ISD::AND, VT, Custom); 865 setOperationAction(ISD::OR, VT, Custom); 866 setOperationAction(ISD::XOR, VT, Custom); 867 continue; 868 } 869 870 // Use SPLAT_VECTOR to prevent type legalization from destroying the 871 // splats when type legalizing i64 scalar on RV32. 872 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 873 // improvements first. 874 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 875 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 876 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 877 } 878 879 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 880 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 881 882 setOperationAction(ISD::MLOAD, VT, Custom); 883 setOperationAction(ISD::MSTORE, VT, Custom); 884 setOperationAction(ISD::MGATHER, VT, Custom); 885 setOperationAction(ISD::MSCATTER, VT, Custom); 886 887 setOperationAction(ISD::VP_LOAD, VT, Custom); 888 setOperationAction(ISD::VP_STORE, VT, Custom); 889 setOperationAction(ISD::VP_GATHER, VT, Custom); 890 setOperationAction(ISD::VP_SCATTER, VT, Custom); 891 892 setOperationAction(ISD::ADD, VT, Custom); 893 setOperationAction(ISD::MUL, VT, Custom); 894 setOperationAction(ISD::SUB, VT, Custom); 895 setOperationAction(ISD::AND, VT, Custom); 896 setOperationAction(ISD::OR, VT, Custom); 897 setOperationAction(ISD::XOR, VT, Custom); 898 setOperationAction(ISD::SDIV, VT, Custom); 899 setOperationAction(ISD::SREM, VT, Custom); 900 setOperationAction(ISD::UDIV, VT, Custom); 901 setOperationAction(ISD::UREM, VT, Custom); 902 setOperationAction(ISD::SHL, VT, Custom); 903 setOperationAction(ISD::SRA, VT, Custom); 904 setOperationAction(ISD::SRL, VT, Custom); 905 906 setOperationAction(ISD::SMIN, VT, Custom); 907 setOperationAction(ISD::SMAX, VT, Custom); 908 setOperationAction(ISD::UMIN, VT, Custom); 909 setOperationAction(ISD::UMAX, VT, Custom); 910 setOperationAction(ISD::ABS, VT, Custom); 911 912 setOperationAction(ISD::MULHS, VT, Custom); 913 setOperationAction(ISD::MULHU, VT, Custom); 914 915 setOperationAction(ISD::SADDSAT, VT, Custom); 916 setOperationAction(ISD::UADDSAT, VT, Custom); 917 setOperationAction(ISD::SSUBSAT, VT, Custom); 918 setOperationAction(ISD::USUBSAT, VT, Custom); 919 920 setOperationAction(ISD::VSELECT, VT, Custom); 921 setOperationAction(ISD::SELECT_CC, VT, Expand); 922 923 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 924 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 925 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 926 927 // Custom-lower reduction operations to set up the corresponding custom 928 // nodes' operands. 929 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 930 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 931 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 932 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 933 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 934 935 for (unsigned VPOpc : IntegerVPOps) 936 setOperationAction(VPOpc, VT, Custom); 937 938 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 939 // type that can represent the value exactly. 940 if (VT.getVectorElementType() != MVT::i64) { 941 MVT FloatEltVT = 942 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 943 EVT FloatVT = 944 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 945 if (isTypeLegal(FloatVT)) { 946 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 947 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 948 } 949 } 950 } 951 952 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 953 if (!useRVVForFixedLengthVectorVT(VT)) 954 continue; 955 956 // By default everything must be expanded. 957 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 958 setOperationAction(Op, VT, Expand); 959 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 960 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 961 setTruncStoreAction(VT, OtherVT, Expand); 962 } 963 964 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 965 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 966 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 967 968 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 969 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 970 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 971 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 972 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 973 974 setOperationAction(ISD::LOAD, VT, Custom); 975 setOperationAction(ISD::STORE, VT, Custom); 976 setOperationAction(ISD::MLOAD, VT, Custom); 977 setOperationAction(ISD::MSTORE, VT, Custom); 978 setOperationAction(ISD::MGATHER, VT, Custom); 979 setOperationAction(ISD::MSCATTER, VT, Custom); 980 981 setOperationAction(ISD::VP_LOAD, VT, Custom); 982 setOperationAction(ISD::VP_STORE, VT, Custom); 983 setOperationAction(ISD::VP_GATHER, VT, Custom); 984 setOperationAction(ISD::VP_SCATTER, VT, Custom); 985 986 setOperationAction(ISD::FADD, VT, Custom); 987 setOperationAction(ISD::FSUB, VT, Custom); 988 setOperationAction(ISD::FMUL, VT, Custom); 989 setOperationAction(ISD::FDIV, VT, Custom); 990 setOperationAction(ISD::FNEG, VT, Custom); 991 setOperationAction(ISD::FABS, VT, Custom); 992 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 993 setOperationAction(ISD::FSQRT, VT, Custom); 994 setOperationAction(ISD::FMA, VT, Custom); 995 setOperationAction(ISD::FMINNUM, VT, Custom); 996 setOperationAction(ISD::FMAXNUM, VT, Custom); 997 998 setOperationAction(ISD::FP_ROUND, VT, Custom); 999 setOperationAction(ISD::FP_EXTEND, VT, Custom); 1000 1001 setOperationAction(ISD::FTRUNC, VT, Custom); 1002 setOperationAction(ISD::FCEIL, VT, Custom); 1003 setOperationAction(ISD::FFLOOR, VT, Custom); 1004 1005 for (auto CC : VFPCCToExpand) 1006 setCondCodeAction(CC, VT, Expand); 1007 1008 setOperationAction(ISD::VSELECT, VT, Custom); 1009 setOperationAction(ISD::SELECT, VT, Custom); 1010 setOperationAction(ISD::SELECT_CC, VT, Expand); 1011 1012 setOperationAction(ISD::BITCAST, VT, Custom); 1013 1014 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1015 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1016 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1017 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1018 1019 for (unsigned VPOpc : FloatingPointVPOps) 1020 setOperationAction(VPOpc, VT, Custom); 1021 } 1022 1023 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1024 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1025 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1026 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1027 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1028 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1029 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1030 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1031 } 1032 } 1033 1034 // Function alignments. 1035 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1036 setMinFunctionAlignment(FunctionAlignment); 1037 setPrefFunctionAlignment(FunctionAlignment); 1038 1039 setMinimumJumpTableEntries(5); 1040 1041 // Jumps are expensive, compared to logic 1042 setJumpIsExpensive(); 1043 1044 setTargetDAGCombine(ISD::ADD); 1045 setTargetDAGCombine(ISD::SUB); 1046 setTargetDAGCombine(ISD::AND); 1047 setTargetDAGCombine(ISD::OR); 1048 setTargetDAGCombine(ISD::XOR); 1049 setTargetDAGCombine(ISD::ANY_EXTEND); 1050 if (Subtarget.hasStdExtF()) { 1051 setTargetDAGCombine(ISD::ZERO_EXTEND); 1052 setTargetDAGCombine(ISD::FP_TO_SINT); 1053 setTargetDAGCombine(ISD::FP_TO_UINT); 1054 } 1055 if (Subtarget.hasVInstructions()) { 1056 setTargetDAGCombine(ISD::FCOPYSIGN); 1057 setTargetDAGCombine(ISD::MGATHER); 1058 setTargetDAGCombine(ISD::MSCATTER); 1059 setTargetDAGCombine(ISD::VP_GATHER); 1060 setTargetDAGCombine(ISD::VP_SCATTER); 1061 setTargetDAGCombine(ISD::SRA); 1062 setTargetDAGCombine(ISD::SRL); 1063 setTargetDAGCombine(ISD::SHL); 1064 setTargetDAGCombine(ISD::STORE); 1065 } 1066 } 1067 1068 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1069 LLVMContext &Context, 1070 EVT VT) const { 1071 if (!VT.isVector()) 1072 return getPointerTy(DL); 1073 if (Subtarget.hasVInstructions() && 1074 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1075 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1076 return VT.changeVectorElementTypeToInteger(); 1077 } 1078 1079 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1080 return Subtarget.getXLenVT(); 1081 } 1082 1083 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1084 const CallInst &I, 1085 MachineFunction &MF, 1086 unsigned Intrinsic) const { 1087 auto &DL = I.getModule()->getDataLayout(); 1088 switch (Intrinsic) { 1089 default: 1090 return false; 1091 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1092 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1093 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1094 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1095 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1096 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1097 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1098 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1099 case Intrinsic::riscv_masked_cmpxchg_i32: { 1100 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 1101 Info.opc = ISD::INTRINSIC_W_CHAIN; 1102 Info.memVT = MVT::getVT(PtrTy->getElementType()); 1103 Info.ptrVal = I.getArgOperand(0); 1104 Info.offset = 0; 1105 Info.align = Align(4); 1106 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1107 MachineMemOperand::MOVolatile; 1108 return true; 1109 } 1110 case Intrinsic::riscv_masked_strided_load: 1111 Info.opc = ISD::INTRINSIC_W_CHAIN; 1112 Info.ptrVal = I.getArgOperand(1); 1113 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1114 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1115 Info.size = MemoryLocation::UnknownSize; 1116 Info.flags |= MachineMemOperand::MOLoad; 1117 return true; 1118 case Intrinsic::riscv_masked_strided_store: 1119 Info.opc = ISD::INTRINSIC_VOID; 1120 Info.ptrVal = I.getArgOperand(1); 1121 Info.memVT = 1122 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1123 Info.align = Align( 1124 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1125 8); 1126 Info.size = MemoryLocation::UnknownSize; 1127 Info.flags |= MachineMemOperand::MOStore; 1128 return true; 1129 } 1130 } 1131 1132 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1133 const AddrMode &AM, Type *Ty, 1134 unsigned AS, 1135 Instruction *I) const { 1136 // No global is ever allowed as a base. 1137 if (AM.BaseGV) 1138 return false; 1139 1140 // Require a 12-bit signed offset. 1141 if (!isInt<12>(AM.BaseOffs)) 1142 return false; 1143 1144 switch (AM.Scale) { 1145 case 0: // "r+i" or just "i", depending on HasBaseReg. 1146 break; 1147 case 1: 1148 if (!AM.HasBaseReg) // allow "r+i". 1149 break; 1150 return false; // disallow "r+r" or "r+r+i". 1151 default: 1152 return false; 1153 } 1154 1155 return true; 1156 } 1157 1158 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1159 return isInt<12>(Imm); 1160 } 1161 1162 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1163 return isInt<12>(Imm); 1164 } 1165 1166 // On RV32, 64-bit integers are split into their high and low parts and held 1167 // in two different registers, so the trunc is free since the low register can 1168 // just be used. 1169 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1170 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1171 return false; 1172 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1173 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1174 return (SrcBits == 64 && DestBits == 32); 1175 } 1176 1177 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1178 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1179 !SrcVT.isInteger() || !DstVT.isInteger()) 1180 return false; 1181 unsigned SrcBits = SrcVT.getSizeInBits(); 1182 unsigned DestBits = DstVT.getSizeInBits(); 1183 return (SrcBits == 64 && DestBits == 32); 1184 } 1185 1186 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1187 // Zexts are free if they can be combined with a load. 1188 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1189 // poorly with type legalization of compares preferring sext. 1190 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1191 EVT MemVT = LD->getMemoryVT(); 1192 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1193 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1194 LD->getExtensionType() == ISD::ZEXTLOAD)) 1195 return true; 1196 } 1197 1198 return TargetLowering::isZExtFree(Val, VT2); 1199 } 1200 1201 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1202 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1203 } 1204 1205 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1206 return Subtarget.hasStdExtZbb(); 1207 } 1208 1209 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1210 return Subtarget.hasStdExtZbb(); 1211 } 1212 1213 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1214 EVT VT = Y.getValueType(); 1215 1216 // FIXME: Support vectors once we have tests. 1217 if (VT.isVector()) 1218 return false; 1219 1220 return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y); 1221 } 1222 1223 /// Check if sinking \p I's operands to I's basic block is profitable, because 1224 /// the operands can be folded into a target instruction, e.g. 1225 /// splats of scalars can fold into vector instructions. 1226 bool RISCVTargetLowering::shouldSinkOperands( 1227 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1228 using namespace llvm::PatternMatch; 1229 1230 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1231 return false; 1232 1233 auto IsSinker = [&](Instruction *I, int Operand) { 1234 switch (I->getOpcode()) { 1235 case Instruction::Add: 1236 case Instruction::Sub: 1237 case Instruction::Mul: 1238 case Instruction::And: 1239 case Instruction::Or: 1240 case Instruction::Xor: 1241 case Instruction::FAdd: 1242 case Instruction::FSub: 1243 case Instruction::FMul: 1244 case Instruction::FDiv: 1245 case Instruction::ICmp: 1246 case Instruction::FCmp: 1247 return true; 1248 case Instruction::Shl: 1249 case Instruction::LShr: 1250 case Instruction::AShr: 1251 case Instruction::UDiv: 1252 case Instruction::SDiv: 1253 case Instruction::URem: 1254 case Instruction::SRem: 1255 return Operand == 1; 1256 case Instruction::Call: 1257 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1258 switch (II->getIntrinsicID()) { 1259 case Intrinsic::fma: 1260 return Operand == 0 || Operand == 1; 1261 default: 1262 return false; 1263 } 1264 } 1265 return false; 1266 default: 1267 return false; 1268 } 1269 }; 1270 1271 for (auto OpIdx : enumerate(I->operands())) { 1272 if (!IsSinker(I, OpIdx.index())) 1273 continue; 1274 1275 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1276 // Make sure we are not already sinking this operand 1277 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1278 continue; 1279 1280 // We are looking for a splat that can be sunk. 1281 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1282 m_Undef(), m_ZeroMask()))) 1283 continue; 1284 1285 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1286 // and vector registers 1287 for (Use &U : Op->uses()) { 1288 Instruction *Insn = cast<Instruction>(U.getUser()); 1289 if (!IsSinker(Insn, U.getOperandNo())) 1290 return false; 1291 } 1292 1293 Ops.push_back(&Op->getOperandUse(0)); 1294 Ops.push_back(&OpIdx.value()); 1295 } 1296 return true; 1297 } 1298 1299 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1300 bool ForCodeSize) const { 1301 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1302 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1303 return false; 1304 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1305 return false; 1306 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1307 return false; 1308 if (Imm.isNegZero()) 1309 return false; 1310 return Imm.isZero(); 1311 } 1312 1313 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1314 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1315 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1316 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1317 } 1318 1319 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1320 CallingConv::ID CC, 1321 EVT VT) const { 1322 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1323 // We might still end up using a GPR but that will be decided based on ABI. 1324 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1325 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1326 return MVT::f32; 1327 1328 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1329 } 1330 1331 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1332 CallingConv::ID CC, 1333 EVT VT) const { 1334 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1335 // We might still end up using a GPR but that will be decided based on ABI. 1336 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1337 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1338 return 1; 1339 1340 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1341 } 1342 1343 // Changes the condition code and swaps operands if necessary, so the SetCC 1344 // operation matches one of the comparisons supported directly by branches 1345 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1346 // with 1/-1. 1347 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1348 ISD::CondCode &CC, SelectionDAG &DAG) { 1349 // Convert X > -1 to X >= 0. 1350 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1351 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1352 CC = ISD::SETGE; 1353 return; 1354 } 1355 // Convert X < 1 to 0 >= X. 1356 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1357 RHS = LHS; 1358 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1359 CC = ISD::SETGE; 1360 return; 1361 } 1362 1363 switch (CC) { 1364 default: 1365 break; 1366 case ISD::SETGT: 1367 case ISD::SETLE: 1368 case ISD::SETUGT: 1369 case ISD::SETULE: 1370 CC = ISD::getSetCCSwappedOperands(CC); 1371 std::swap(LHS, RHS); 1372 break; 1373 } 1374 } 1375 1376 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1377 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1378 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1379 if (VT.getVectorElementType() == MVT::i1) 1380 KnownSize *= 8; 1381 1382 switch (KnownSize) { 1383 default: 1384 llvm_unreachable("Invalid LMUL."); 1385 case 8: 1386 return RISCVII::VLMUL::LMUL_F8; 1387 case 16: 1388 return RISCVII::VLMUL::LMUL_F4; 1389 case 32: 1390 return RISCVII::VLMUL::LMUL_F2; 1391 case 64: 1392 return RISCVII::VLMUL::LMUL_1; 1393 case 128: 1394 return RISCVII::VLMUL::LMUL_2; 1395 case 256: 1396 return RISCVII::VLMUL::LMUL_4; 1397 case 512: 1398 return RISCVII::VLMUL::LMUL_8; 1399 } 1400 } 1401 1402 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1403 switch (LMul) { 1404 default: 1405 llvm_unreachable("Invalid LMUL."); 1406 case RISCVII::VLMUL::LMUL_F8: 1407 case RISCVII::VLMUL::LMUL_F4: 1408 case RISCVII::VLMUL::LMUL_F2: 1409 case RISCVII::VLMUL::LMUL_1: 1410 return RISCV::VRRegClassID; 1411 case RISCVII::VLMUL::LMUL_2: 1412 return RISCV::VRM2RegClassID; 1413 case RISCVII::VLMUL::LMUL_4: 1414 return RISCV::VRM4RegClassID; 1415 case RISCVII::VLMUL::LMUL_8: 1416 return RISCV::VRM8RegClassID; 1417 } 1418 } 1419 1420 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1421 RISCVII::VLMUL LMUL = getLMUL(VT); 1422 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1423 LMUL == RISCVII::VLMUL::LMUL_F4 || 1424 LMUL == RISCVII::VLMUL::LMUL_F2 || 1425 LMUL == RISCVII::VLMUL::LMUL_1) { 1426 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1427 "Unexpected subreg numbering"); 1428 return RISCV::sub_vrm1_0 + Index; 1429 } 1430 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1431 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1432 "Unexpected subreg numbering"); 1433 return RISCV::sub_vrm2_0 + Index; 1434 } 1435 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1436 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1437 "Unexpected subreg numbering"); 1438 return RISCV::sub_vrm4_0 + Index; 1439 } 1440 llvm_unreachable("Invalid vector type."); 1441 } 1442 1443 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1444 if (VT.getVectorElementType() == MVT::i1) 1445 return RISCV::VRRegClassID; 1446 return getRegClassIDForLMUL(getLMUL(VT)); 1447 } 1448 1449 // Attempt to decompose a subvector insert/extract between VecVT and 1450 // SubVecVT via subregister indices. Returns the subregister index that 1451 // can perform the subvector insert/extract with the given element index, as 1452 // well as the index corresponding to any leftover subvectors that must be 1453 // further inserted/extracted within the register class for SubVecVT. 1454 std::pair<unsigned, unsigned> 1455 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1456 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1457 const RISCVRegisterInfo *TRI) { 1458 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1459 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1460 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1461 "Register classes not ordered"); 1462 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1463 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1464 // Try to compose a subregister index that takes us from the incoming 1465 // LMUL>1 register class down to the outgoing one. At each step we half 1466 // the LMUL: 1467 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1468 // Note that this is not guaranteed to find a subregister index, such as 1469 // when we are extracting from one VR type to another. 1470 unsigned SubRegIdx = RISCV::NoSubRegister; 1471 for (const unsigned RCID : 1472 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1473 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1474 VecVT = VecVT.getHalfNumVectorElementsVT(); 1475 bool IsHi = 1476 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1477 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1478 getSubregIndexByMVT(VecVT, IsHi)); 1479 if (IsHi) 1480 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1481 } 1482 return {SubRegIdx, InsertExtractIdx}; 1483 } 1484 1485 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1486 // stores for those types. 1487 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1488 return !Subtarget.useRVVForFixedLengthVectors() || 1489 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1490 } 1491 1492 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1493 if (ScalarTy->isPointerTy()) 1494 return true; 1495 1496 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1497 ScalarTy->isIntegerTy(32)) 1498 return true; 1499 1500 if (ScalarTy->isIntegerTy(64)) 1501 return Subtarget.hasVInstructionsI64(); 1502 1503 if (ScalarTy->isHalfTy()) 1504 return Subtarget.hasVInstructionsF16(); 1505 if (ScalarTy->isFloatTy()) 1506 return Subtarget.hasVInstructionsF32(); 1507 if (ScalarTy->isDoubleTy()) 1508 return Subtarget.hasVInstructionsF64(); 1509 1510 return false; 1511 } 1512 1513 static bool useRVVForFixedLengthVectorVT(MVT VT, 1514 const RISCVSubtarget &Subtarget) { 1515 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1516 if (!Subtarget.useRVVForFixedLengthVectors()) 1517 return false; 1518 1519 // We only support a set of vector types with a consistent maximum fixed size 1520 // across all supported vector element types to avoid legalization issues. 1521 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1522 // fixed-length vector type we support is 1024 bytes. 1523 if (VT.getFixedSizeInBits() > 1024 * 8) 1524 return false; 1525 1526 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1527 1528 MVT EltVT = VT.getVectorElementType(); 1529 1530 // Don't use RVV for vectors we cannot scalarize if required. 1531 switch (EltVT.SimpleTy) { 1532 // i1 is supported but has different rules. 1533 default: 1534 return false; 1535 case MVT::i1: 1536 // Masks can only use a single register. 1537 if (VT.getVectorNumElements() > MinVLen) 1538 return false; 1539 MinVLen /= 8; 1540 break; 1541 case MVT::i8: 1542 case MVT::i16: 1543 case MVT::i32: 1544 break; 1545 case MVT::i64: 1546 if (!Subtarget.hasVInstructionsI64()) 1547 return false; 1548 break; 1549 case MVT::f16: 1550 if (!Subtarget.hasVInstructionsF16()) 1551 return false; 1552 break; 1553 case MVT::f32: 1554 if (!Subtarget.hasVInstructionsF32()) 1555 return false; 1556 break; 1557 case MVT::f64: 1558 if (!Subtarget.hasVInstructionsF64()) 1559 return false; 1560 break; 1561 } 1562 1563 // Reject elements larger than ELEN. 1564 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1565 return false; 1566 1567 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1568 // Don't use RVV for types that don't fit. 1569 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1570 return false; 1571 1572 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1573 // the base fixed length RVV support in place. 1574 if (!VT.isPow2VectorType()) 1575 return false; 1576 1577 return true; 1578 } 1579 1580 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1581 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1582 } 1583 1584 // Return the largest legal scalable vector type that matches VT's element type. 1585 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1586 const RISCVSubtarget &Subtarget) { 1587 // This may be called before legal types are setup. 1588 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1589 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1590 "Expected legal fixed length vector!"); 1591 1592 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1593 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1594 1595 MVT EltVT = VT.getVectorElementType(); 1596 switch (EltVT.SimpleTy) { 1597 default: 1598 llvm_unreachable("unexpected element type for RVV container"); 1599 case MVT::i1: 1600 case MVT::i8: 1601 case MVT::i16: 1602 case MVT::i32: 1603 case MVT::i64: 1604 case MVT::f16: 1605 case MVT::f32: 1606 case MVT::f64: { 1607 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1608 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1609 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1610 unsigned NumElts = 1611 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1612 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1613 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1614 return MVT::getScalableVectorVT(EltVT, NumElts); 1615 } 1616 } 1617 } 1618 1619 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1620 const RISCVSubtarget &Subtarget) { 1621 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1622 Subtarget); 1623 } 1624 1625 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1626 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1627 } 1628 1629 // Grow V to consume an entire RVV register. 1630 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1631 const RISCVSubtarget &Subtarget) { 1632 assert(VT.isScalableVector() && 1633 "Expected to convert into a scalable vector!"); 1634 assert(V.getValueType().isFixedLengthVector() && 1635 "Expected a fixed length vector operand!"); 1636 SDLoc DL(V); 1637 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1638 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1639 } 1640 1641 // Shrink V so it's just big enough to maintain a VT's worth of data. 1642 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1643 const RISCVSubtarget &Subtarget) { 1644 assert(VT.isFixedLengthVector() && 1645 "Expected to convert into a fixed length vector!"); 1646 assert(V.getValueType().isScalableVector() && 1647 "Expected a scalable vector operand!"); 1648 SDLoc DL(V); 1649 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1650 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1651 } 1652 1653 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1654 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1655 // the vector type that it is contained in. 1656 static std::pair<SDValue, SDValue> 1657 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1658 const RISCVSubtarget &Subtarget) { 1659 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1660 MVT XLenVT = Subtarget.getXLenVT(); 1661 SDValue VL = VecVT.isFixedLengthVector() 1662 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1663 : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT); 1664 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1665 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1666 return {Mask, VL}; 1667 } 1668 1669 // As above but assuming the given type is a scalable vector type. 1670 static std::pair<SDValue, SDValue> 1671 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1672 const RISCVSubtarget &Subtarget) { 1673 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1674 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1675 } 1676 1677 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1678 // of either is (currently) supported. This can get us into an infinite loop 1679 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1680 // as a ..., etc. 1681 // Until either (or both) of these can reliably lower any node, reporting that 1682 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1683 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1684 // which is not desirable. 1685 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1686 EVT VT, unsigned DefinedValues) const { 1687 return false; 1688 } 1689 1690 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1691 // Only splats are currently supported. 1692 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1693 return true; 1694 1695 return false; 1696 } 1697 1698 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1699 const RISCVSubtarget &Subtarget) { 1700 // RISCV FP-to-int conversions saturate to the destination register size, but 1701 // don't produce 0 for nan. We can use a conversion instruction and fix the 1702 // nan case with a compare and a select. 1703 SDValue Src = Op.getOperand(0); 1704 1705 EVT DstVT = Op.getValueType(); 1706 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1707 1708 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1709 unsigned Opc; 1710 if (SatVT == DstVT) 1711 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1712 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1713 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1714 else 1715 return SDValue(); 1716 // FIXME: Support other SatVTs by clamping before or after the conversion. 1717 1718 SDLoc DL(Op); 1719 SDValue FpToInt = DAG.getNode( 1720 Opc, DL, DstVT, Src, 1721 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1722 1723 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1724 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1725 } 1726 1727 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1728 // and back. Taking care to avoid converting values that are nan or already 1729 // correct. 1730 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1731 // have FRM dependencies modeled yet. 1732 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1733 MVT VT = Op.getSimpleValueType(); 1734 assert(VT.isVector() && "Unexpected type"); 1735 1736 SDLoc DL(Op); 1737 1738 // Freeze the source since we are increasing the number of uses. 1739 SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0)); 1740 1741 // Truncate to integer and convert back to FP. 1742 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1743 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1744 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1745 1746 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1747 1748 if (Op.getOpcode() == ISD::FCEIL) { 1749 // If the truncated value is the greater than or equal to the original 1750 // value, we've computed the ceil. Otherwise, we went the wrong way and 1751 // need to increase by 1. 1752 // FIXME: This should use a masked operation. Handle here or in isel? 1753 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1754 DAG.getConstantFP(1.0, DL, VT)); 1755 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1756 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1757 } else if (Op.getOpcode() == ISD::FFLOOR) { 1758 // If the truncated value is the less than or equal to the original value, 1759 // we've computed the floor. Otherwise, we went the wrong way and need to 1760 // decrease by 1. 1761 // FIXME: This should use a masked operation. Handle here or in isel? 1762 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1763 DAG.getConstantFP(1.0, DL, VT)); 1764 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1765 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1766 } 1767 1768 // Restore the original sign so that -0.0 is preserved. 1769 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1770 1771 // Determine the largest integer that can be represented exactly. This and 1772 // values larger than it don't have any fractional bits so don't need to 1773 // be converted. 1774 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1775 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1776 APFloat MaxVal = APFloat(FltSem); 1777 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1778 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1779 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1780 1781 // If abs(Src) was larger than MaxVal or nan, keep it. 1782 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1783 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1784 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1785 } 1786 1787 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1788 const RISCVSubtarget &Subtarget) { 1789 MVT VT = Op.getSimpleValueType(); 1790 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1791 1792 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1793 1794 SDLoc DL(Op); 1795 SDValue Mask, VL; 1796 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1797 1798 unsigned Opc = 1799 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1800 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1801 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1802 } 1803 1804 struct VIDSequence { 1805 int64_t StepNumerator; 1806 unsigned StepDenominator; 1807 int64_t Addend; 1808 }; 1809 1810 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1811 // to the (non-zero) step S and start value X. This can be then lowered as the 1812 // RVV sequence (VID * S) + X, for example. 1813 // The step S is represented as an integer numerator divided by a positive 1814 // denominator. Note that the implementation currently only identifies 1815 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1816 // cannot detect 2/3, for example. 1817 // Note that this method will also match potentially unappealing index 1818 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1819 // determine whether this is worth generating code for. 1820 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1821 unsigned NumElts = Op.getNumOperands(); 1822 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1823 if (!Op.getValueType().isInteger()) 1824 return None; 1825 1826 Optional<unsigned> SeqStepDenom; 1827 Optional<int64_t> SeqStepNum, SeqAddend; 1828 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1829 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1830 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1831 // Assume undef elements match the sequence; we just have to be careful 1832 // when interpolating across them. 1833 if (Op.getOperand(Idx).isUndef()) 1834 continue; 1835 // The BUILD_VECTOR must be all constants. 1836 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1837 return None; 1838 1839 uint64_t Val = Op.getConstantOperandVal(Idx) & 1840 maskTrailingOnes<uint64_t>(EltSizeInBits); 1841 1842 if (PrevElt) { 1843 // Calculate the step since the last non-undef element, and ensure 1844 // it's consistent across the entire sequence. 1845 unsigned IdxDiff = Idx - PrevElt->second; 1846 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1847 1848 // A zero-value value difference means that we're somewhere in the middle 1849 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1850 // step change before evaluating the sequence. 1851 if (ValDiff != 0) { 1852 int64_t Remainder = ValDiff % IdxDiff; 1853 // Normalize the step if it's greater than 1. 1854 if (Remainder != ValDiff) { 1855 // The difference must cleanly divide the element span. 1856 if (Remainder != 0) 1857 return None; 1858 ValDiff /= IdxDiff; 1859 IdxDiff = 1; 1860 } 1861 1862 if (!SeqStepNum) 1863 SeqStepNum = ValDiff; 1864 else if (ValDiff != SeqStepNum) 1865 return None; 1866 1867 if (!SeqStepDenom) 1868 SeqStepDenom = IdxDiff; 1869 else if (IdxDiff != *SeqStepDenom) 1870 return None; 1871 } 1872 } 1873 1874 // Record and/or check any addend. 1875 if (SeqStepNum && SeqStepDenom) { 1876 uint64_t ExpectedVal = 1877 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1878 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1879 if (!SeqAddend) 1880 SeqAddend = Addend; 1881 else if (SeqAddend != Addend) 1882 return None; 1883 } 1884 1885 // Record this non-undef element for later. 1886 if (!PrevElt || PrevElt->first != Val) 1887 PrevElt = std::make_pair(Val, Idx); 1888 } 1889 // We need to have logged both a step and an addend for this to count as 1890 // a legal index sequence. 1891 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1892 return None; 1893 1894 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1895 } 1896 1897 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1898 const RISCVSubtarget &Subtarget) { 1899 MVT VT = Op.getSimpleValueType(); 1900 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1901 1902 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1903 1904 SDLoc DL(Op); 1905 SDValue Mask, VL; 1906 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1907 1908 MVT XLenVT = Subtarget.getXLenVT(); 1909 unsigned NumElts = Op.getNumOperands(); 1910 1911 if (VT.getVectorElementType() == MVT::i1) { 1912 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1913 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1914 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1915 } 1916 1917 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1918 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1919 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1920 } 1921 1922 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1923 // scalar integer chunks whose bit-width depends on the number of mask 1924 // bits and XLEN. 1925 // First, determine the most appropriate scalar integer type to use. This 1926 // is at most XLenVT, but may be shrunk to a smaller vector element type 1927 // according to the size of the final vector - use i8 chunks rather than 1928 // XLenVT if we're producing a v8i1. This results in more consistent 1929 // codegen across RV32 and RV64. 1930 unsigned NumViaIntegerBits = 1931 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1932 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1933 // If we have to use more than one INSERT_VECTOR_ELT then this 1934 // optimization is likely to increase code size; avoid peforming it in 1935 // such a case. We can use a load from a constant pool in this case. 1936 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1937 return SDValue(); 1938 // Now we can create our integer vector type. Note that it may be larger 1939 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1940 MVT IntegerViaVecVT = 1941 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1942 divideCeil(NumElts, NumViaIntegerBits)); 1943 1944 uint64_t Bits = 0; 1945 unsigned BitPos = 0, IntegerEltIdx = 0; 1946 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1947 1948 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1949 // Once we accumulate enough bits to fill our scalar type, insert into 1950 // our vector and clear our accumulated data. 1951 if (I != 0 && I % NumViaIntegerBits == 0) { 1952 if (NumViaIntegerBits <= 32) 1953 Bits = SignExtend64(Bits, 32); 1954 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1955 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1956 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1957 Bits = 0; 1958 BitPos = 0; 1959 IntegerEltIdx++; 1960 } 1961 SDValue V = Op.getOperand(I); 1962 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1963 Bits |= ((uint64_t)BitValue << BitPos); 1964 } 1965 1966 // Insert the (remaining) scalar value into position in our integer 1967 // vector type. 1968 if (NumViaIntegerBits <= 32) 1969 Bits = SignExtend64(Bits, 32); 1970 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1971 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1972 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1973 1974 if (NumElts < NumViaIntegerBits) { 1975 // If we're producing a smaller vector than our minimum legal integer 1976 // type, bitcast to the equivalent (known-legal) mask type, and extract 1977 // our final mask. 1978 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1979 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1980 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1981 DAG.getConstant(0, DL, XLenVT)); 1982 } else { 1983 // Else we must have produced an integer type with the same size as the 1984 // mask type; bitcast for the final result. 1985 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1986 Vec = DAG.getBitcast(VT, Vec); 1987 } 1988 1989 return Vec; 1990 } 1991 1992 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 1993 // vector type, we have a legal equivalently-sized i8 type, so we can use 1994 // that. 1995 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 1996 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 1997 1998 SDValue WideVec; 1999 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2000 // For a splat, perform a scalar truncate before creating the wider 2001 // vector. 2002 assert(Splat.getValueType() == XLenVT && 2003 "Unexpected type for i1 splat value"); 2004 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2005 DAG.getConstant(1, DL, XLenVT)); 2006 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2007 } else { 2008 SmallVector<SDValue, 8> Ops(Op->op_values()); 2009 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2010 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2011 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2012 } 2013 2014 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2015 } 2016 2017 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2018 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2019 : RISCVISD::VMV_V_X_VL; 2020 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 2021 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2022 } 2023 2024 // Try and match index sequences, which we can lower to the vid instruction 2025 // with optional modifications. An all-undef vector is matched by 2026 // getSplatValue, above. 2027 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2028 int64_t StepNumerator = SimpleVID->StepNumerator; 2029 unsigned StepDenominator = SimpleVID->StepDenominator; 2030 int64_t Addend = SimpleVID->Addend; 2031 2032 assert(StepNumerator != 0 && "Invalid step"); 2033 bool Negate = false; 2034 int64_t SplatStepVal = StepNumerator; 2035 unsigned StepOpcode = ISD::MUL; 2036 if (StepNumerator != 1) { 2037 if (isPowerOf2_64(std::abs(StepNumerator))) { 2038 Negate = StepNumerator < 0; 2039 StepOpcode = ISD::SHL; 2040 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2041 } 2042 } 2043 2044 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2045 // threshold since it's the immediate value many RVV instructions accept. 2046 // There is no vmul.vi instruction so ensure multiply constant can fit in 2047 // a single addi instruction. 2048 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2049 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2050 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2051 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2052 // Convert right out of the scalable type so we can use standard ISD 2053 // nodes for the rest of the computation. If we used scalable types with 2054 // these, we'd lose the fixed-length vector info and generate worse 2055 // vsetvli code. 2056 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2057 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2058 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2059 SDValue SplatStep = DAG.getSplatVector( 2060 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2061 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2062 } 2063 if (StepDenominator != 1) { 2064 SDValue SplatStep = DAG.getSplatVector( 2065 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2066 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2067 } 2068 if (Addend != 0 || Negate) { 2069 SDValue SplatAddend = 2070 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2071 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2072 } 2073 return VID; 2074 } 2075 } 2076 2077 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2078 // when re-interpreted as a vector with a larger element type. For example, 2079 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2080 // could be instead splat as 2081 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2082 // TODO: This optimization could also work on non-constant splats, but it 2083 // would require bit-manipulation instructions to construct the splat value. 2084 SmallVector<SDValue> Sequence; 2085 unsigned EltBitSize = VT.getScalarSizeInBits(); 2086 const auto *BV = cast<BuildVectorSDNode>(Op); 2087 if (VT.isInteger() && EltBitSize < 64 && 2088 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2089 BV->getRepeatedSequence(Sequence) && 2090 (Sequence.size() * EltBitSize) <= 64) { 2091 unsigned SeqLen = Sequence.size(); 2092 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2093 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2094 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2095 ViaIntVT == MVT::i64) && 2096 "Unexpected sequence type"); 2097 2098 unsigned EltIdx = 0; 2099 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2100 uint64_t SplatValue = 0; 2101 // Construct the amalgamated value which can be splatted as this larger 2102 // vector type. 2103 for (const auto &SeqV : Sequence) { 2104 if (!SeqV.isUndef()) 2105 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2106 << (EltIdx * EltBitSize)); 2107 EltIdx++; 2108 } 2109 2110 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2111 // achieve better constant materializion. 2112 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2113 SplatValue = SignExtend64(SplatValue, 32); 2114 2115 // Since we can't introduce illegal i64 types at this stage, we can only 2116 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2117 // way we can use RVV instructions to splat. 2118 assert((ViaIntVT.bitsLE(XLenVT) || 2119 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2120 "Unexpected bitcast sequence"); 2121 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2122 SDValue ViaVL = 2123 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2124 MVT ViaContainerVT = 2125 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2126 SDValue Splat = 2127 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2128 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2129 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2130 return DAG.getBitcast(VT, Splat); 2131 } 2132 } 2133 2134 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2135 // which constitute a large proportion of the elements. In such cases we can 2136 // splat a vector with the dominant element and make up the shortfall with 2137 // INSERT_VECTOR_ELTs. 2138 // Note that this includes vectors of 2 elements by association. The 2139 // upper-most element is the "dominant" one, allowing us to use a splat to 2140 // "insert" the upper element, and an insert of the lower element at position 2141 // 0, which improves codegen. 2142 SDValue DominantValue; 2143 unsigned MostCommonCount = 0; 2144 DenseMap<SDValue, unsigned> ValueCounts; 2145 unsigned NumUndefElts = 2146 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2147 2148 // Track the number of scalar loads we know we'd be inserting, estimated as 2149 // any non-zero floating-point constant. Other kinds of element are either 2150 // already in registers or are materialized on demand. The threshold at which 2151 // a vector load is more desirable than several scalar materializion and 2152 // vector-insertion instructions is not known. 2153 unsigned NumScalarLoads = 0; 2154 2155 for (SDValue V : Op->op_values()) { 2156 if (V.isUndef()) 2157 continue; 2158 2159 ValueCounts.insert(std::make_pair(V, 0)); 2160 unsigned &Count = ValueCounts[V]; 2161 2162 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2163 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2164 2165 // Is this value dominant? In case of a tie, prefer the highest element as 2166 // it's cheaper to insert near the beginning of a vector than it is at the 2167 // end. 2168 if (++Count >= MostCommonCount) { 2169 DominantValue = V; 2170 MostCommonCount = Count; 2171 } 2172 } 2173 2174 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2175 unsigned NumDefElts = NumElts - NumUndefElts; 2176 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2177 2178 // Don't perform this optimization when optimizing for size, since 2179 // materializing elements and inserting them tends to cause code bloat. 2180 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2181 ((MostCommonCount > DominantValueCountThreshold) || 2182 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2183 // Start by splatting the most common element. 2184 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2185 2186 DenseSet<SDValue> Processed{DominantValue}; 2187 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2188 for (const auto &OpIdx : enumerate(Op->ops())) { 2189 const SDValue &V = OpIdx.value(); 2190 if (V.isUndef() || !Processed.insert(V).second) 2191 continue; 2192 if (ValueCounts[V] == 1) { 2193 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2194 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2195 } else { 2196 // Blend in all instances of this value using a VSELECT, using a 2197 // mask where each bit signals whether that element is the one 2198 // we're after. 2199 SmallVector<SDValue> Ops; 2200 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2201 return DAG.getConstant(V == V1, DL, XLenVT); 2202 }); 2203 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2204 DAG.getBuildVector(SelMaskTy, DL, Ops), 2205 DAG.getSplatBuildVector(VT, DL, V), Vec); 2206 } 2207 } 2208 2209 return Vec; 2210 } 2211 2212 return SDValue(); 2213 } 2214 2215 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 2216 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 2217 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2218 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2219 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2220 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2221 // node in order to try and match RVV vector/scalar instructions. 2222 if ((LoC >> 31) == HiC) 2223 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2224 } 2225 2226 // Fall back to a stack store and stride x0 vector load. 2227 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2228 } 2229 2230 // Called by type legalization to handle splat of i64 on RV32. 2231 // FIXME: We can optimize this when the type has sign or zero bits in one 2232 // of the halves. 2233 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2234 SDValue VL, SelectionDAG &DAG) { 2235 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2236 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2237 DAG.getConstant(0, DL, MVT::i32)); 2238 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2239 DAG.getConstant(1, DL, MVT::i32)); 2240 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2241 } 2242 2243 // This function lowers a splat of a scalar operand Splat with the vector 2244 // length VL. It ensures the final sequence is type legal, which is useful when 2245 // lowering a splat after type legalization. 2246 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2247 SelectionDAG &DAG, 2248 const RISCVSubtarget &Subtarget) { 2249 if (VT.isFloatingPoint()) { 2250 // If VL is 1, we could use vfmv.s.f. 2251 if (isOneConstant(VL)) 2252 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT), 2253 Scalar, VL); 2254 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2255 } 2256 2257 MVT XLenVT = Subtarget.getXLenVT(); 2258 2259 // Simplest case is that the operand needs to be promoted to XLenVT. 2260 if (Scalar.getValueType().bitsLE(XLenVT)) { 2261 // If the operand is a constant, sign extend to increase our chances 2262 // of being able to use a .vi instruction. ANY_EXTEND would become a 2263 // a zero extend and the simm5 check in isel would fail. 2264 // FIXME: Should we ignore the upper bits in isel instead? 2265 unsigned ExtOpc = 2266 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2267 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2268 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2269 // If VL is 1 and the scalar value won't benefit from immediate, we could 2270 // use vmv.s.x. 2271 if (isOneConstant(VL) && 2272 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2273 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar, 2274 VL); 2275 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2276 } 2277 2278 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2279 "Unexpected scalar for splat lowering!"); 2280 2281 if (isOneConstant(VL) && isNullConstant(Scalar)) 2282 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), 2283 DAG.getConstant(0, DL, XLenVT), VL); 2284 2285 // Otherwise use the more complicated splatting algorithm. 2286 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2287 } 2288 2289 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2290 const RISCVSubtarget &Subtarget) { 2291 SDValue V1 = Op.getOperand(0); 2292 SDValue V2 = Op.getOperand(1); 2293 SDLoc DL(Op); 2294 MVT XLenVT = Subtarget.getXLenVT(); 2295 MVT VT = Op.getSimpleValueType(); 2296 unsigned NumElts = VT.getVectorNumElements(); 2297 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2298 2299 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2300 2301 SDValue TrueMask, VL; 2302 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2303 2304 if (SVN->isSplat()) { 2305 const int Lane = SVN->getSplatIndex(); 2306 if (Lane >= 0) { 2307 MVT SVT = VT.getVectorElementType(); 2308 2309 // Turn splatted vector load into a strided load with an X0 stride. 2310 SDValue V = V1; 2311 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2312 // with undef. 2313 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2314 int Offset = Lane; 2315 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2316 int OpElements = 2317 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2318 V = V.getOperand(Offset / OpElements); 2319 Offset %= OpElements; 2320 } 2321 2322 // We need to ensure the load isn't atomic or volatile. 2323 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2324 auto *Ld = cast<LoadSDNode>(V); 2325 Offset *= SVT.getStoreSize(); 2326 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2327 TypeSize::Fixed(Offset), DL); 2328 2329 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2330 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2331 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2332 SDValue IntID = 2333 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2334 SDValue Ops[] = {Ld->getChain(), IntID, NewAddr, 2335 DAG.getRegister(RISCV::X0, XLenVT), VL}; 2336 SDValue NewLoad = DAG.getMemIntrinsicNode( 2337 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2338 DAG.getMachineFunction().getMachineMemOperand( 2339 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2340 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2341 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2342 } 2343 2344 // Otherwise use a scalar load and splat. This will give the best 2345 // opportunity to fold a splat into the operation. ISel can turn it into 2346 // the x0 strided load if we aren't able to fold away the select. 2347 if (SVT.isFloatingPoint()) 2348 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2349 Ld->getPointerInfo().getWithOffset(Offset), 2350 Ld->getOriginalAlign(), 2351 Ld->getMemOperand()->getFlags()); 2352 else 2353 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2354 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2355 Ld->getOriginalAlign(), 2356 Ld->getMemOperand()->getFlags()); 2357 DAG.makeEquivalentMemoryOrdering(Ld, V); 2358 2359 unsigned Opc = 2360 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2361 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2362 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2363 } 2364 2365 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2366 assert(Lane < (int)NumElts && "Unexpected lane!"); 2367 SDValue Gather = 2368 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2369 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2370 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2371 } 2372 } 2373 2374 // Detect shuffles which can be re-expressed as vector selects; these are 2375 // shuffles in which each element in the destination is taken from an element 2376 // at the corresponding index in either source vectors. 2377 bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) { 2378 int MaskIndex = MaskIdx.value(); 2379 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2380 }); 2381 2382 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2383 2384 SmallVector<SDValue> MaskVals; 2385 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2386 // merged with a second vrgather. 2387 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2388 2389 // By default we preserve the original operand order, and use a mask to 2390 // select LHS as true and RHS as false. However, since RVV vector selects may 2391 // feature splats but only on the LHS, we may choose to invert our mask and 2392 // instead select between RHS and LHS. 2393 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2394 bool InvertMask = IsSelect == SwapOps; 2395 2396 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2397 // half. 2398 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2399 2400 // Now construct the mask that will be used by the vselect or blended 2401 // vrgather operation. For vrgathers, construct the appropriate indices into 2402 // each vector. 2403 for (int MaskIndex : SVN->getMask()) { 2404 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2405 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2406 if (!IsSelect) { 2407 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2408 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2409 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2410 : DAG.getUNDEF(XLenVT)); 2411 GatherIndicesRHS.push_back( 2412 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2413 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2414 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2415 ++LHSIndexCounts[MaskIndex]; 2416 if (!IsLHSOrUndefIndex) 2417 ++RHSIndexCounts[MaskIndex - NumElts]; 2418 } 2419 } 2420 2421 if (SwapOps) { 2422 std::swap(V1, V2); 2423 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2424 } 2425 2426 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2427 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2428 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2429 2430 if (IsSelect) 2431 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2432 2433 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2434 // On such a large vector we're unable to use i8 as the index type. 2435 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2436 // may involve vector splitting if we're already at LMUL=8, or our 2437 // user-supplied maximum fixed-length LMUL. 2438 return SDValue(); 2439 } 2440 2441 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2442 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2443 MVT IndexVT = VT.changeTypeToInteger(); 2444 // Since we can't introduce illegal index types at this stage, use i16 and 2445 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2446 // than XLenVT. 2447 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2448 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2449 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2450 } 2451 2452 MVT IndexContainerVT = 2453 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2454 2455 SDValue Gather; 2456 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2457 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2458 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2459 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2460 } else { 2461 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2462 // If only one index is used, we can use a "splat" vrgather. 2463 // TODO: We can splat the most-common index and fix-up any stragglers, if 2464 // that's beneficial. 2465 if (LHSIndexCounts.size() == 1) { 2466 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2467 Gather = 2468 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2469 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2470 } else { 2471 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2472 LHSIndices = 2473 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2474 2475 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2476 TrueMask, VL); 2477 } 2478 } 2479 2480 // If a second vector operand is used by this shuffle, blend it in with an 2481 // additional vrgather. 2482 if (!V2.isUndef()) { 2483 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2484 // If only one index is used, we can use a "splat" vrgather. 2485 // TODO: We can splat the most-common index and fix-up any stragglers, if 2486 // that's beneficial. 2487 if (RHSIndexCounts.size() == 1) { 2488 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2489 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2490 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2491 } else { 2492 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2493 RHSIndices = 2494 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2495 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2496 VL); 2497 } 2498 2499 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2500 SelectMask = 2501 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2502 2503 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2504 Gather, VL); 2505 } 2506 2507 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2508 } 2509 2510 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2511 SDLoc DL, SelectionDAG &DAG, 2512 const RISCVSubtarget &Subtarget) { 2513 if (VT.isScalableVector()) 2514 return DAG.getFPExtendOrRound(Op, DL, VT); 2515 assert(VT.isFixedLengthVector() && 2516 "Unexpected value type for RVV FP extend/round lowering"); 2517 SDValue Mask, VL; 2518 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2519 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2520 ? RISCVISD::FP_EXTEND_VL 2521 : RISCVISD::FP_ROUND_VL; 2522 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2523 } 2524 2525 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2526 // the exponent. 2527 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2528 MVT VT = Op.getSimpleValueType(); 2529 unsigned EltSize = VT.getScalarSizeInBits(); 2530 SDValue Src = Op.getOperand(0); 2531 SDLoc DL(Op); 2532 2533 // We need a FP type that can represent the value. 2534 // TODO: Use f16 for i8 when possible? 2535 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2536 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2537 2538 // Legal types should have been checked in the RISCVTargetLowering 2539 // constructor. 2540 // TODO: Splitting may make sense in some cases. 2541 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2542 "Expected legal float type!"); 2543 2544 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2545 // The trailing zero count is equal to log2 of this single bit value. 2546 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2547 SDValue Neg = 2548 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2549 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2550 } 2551 2552 // We have a legal FP type, convert to it. 2553 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2554 // Bitcast to integer and shift the exponent to the LSB. 2555 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2556 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2557 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2558 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2559 DAG.getConstant(ShiftAmt, DL, IntVT)); 2560 // Truncate back to original type to allow vnsrl. 2561 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2562 // The exponent contains log2 of the value in biased form. 2563 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2564 2565 // For trailing zeros, we just need to subtract the bias. 2566 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2567 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2568 DAG.getConstant(ExponentBias, DL, VT)); 2569 2570 // For leading zeros, we need to remove the bias and convert from log2 to 2571 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2572 unsigned Adjust = ExponentBias + (EltSize - 1); 2573 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2574 } 2575 2576 // While RVV has alignment restrictions, we should always be able to load as a 2577 // legal equivalently-sized byte-typed vector instead. This method is 2578 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2579 // the load is already correctly-aligned, it returns SDValue(). 2580 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2581 SelectionDAG &DAG) const { 2582 auto *Load = cast<LoadSDNode>(Op); 2583 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2584 2585 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2586 Load->getMemoryVT(), 2587 *Load->getMemOperand())) 2588 return SDValue(); 2589 2590 SDLoc DL(Op); 2591 MVT VT = Op.getSimpleValueType(); 2592 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2593 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2594 "Unexpected unaligned RVV load type"); 2595 MVT NewVT = 2596 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2597 assert(NewVT.isValid() && 2598 "Expecting equally-sized RVV vector types to be legal"); 2599 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2600 Load->getPointerInfo(), Load->getOriginalAlign(), 2601 Load->getMemOperand()->getFlags()); 2602 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2603 } 2604 2605 // While RVV has alignment restrictions, we should always be able to store as a 2606 // legal equivalently-sized byte-typed vector instead. This method is 2607 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2608 // returns SDValue() if the store is already correctly aligned. 2609 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2610 SelectionDAG &DAG) const { 2611 auto *Store = cast<StoreSDNode>(Op); 2612 assert(Store && Store->getValue().getValueType().isVector() && 2613 "Expected vector store"); 2614 2615 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2616 Store->getMemoryVT(), 2617 *Store->getMemOperand())) 2618 return SDValue(); 2619 2620 SDLoc DL(Op); 2621 SDValue StoredVal = Store->getValue(); 2622 MVT VT = StoredVal.getSimpleValueType(); 2623 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2624 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2625 "Unexpected unaligned RVV store type"); 2626 MVT NewVT = 2627 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2628 assert(NewVT.isValid() && 2629 "Expecting equally-sized RVV vector types to be legal"); 2630 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2631 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2632 Store->getPointerInfo(), Store->getOriginalAlign(), 2633 Store->getMemOperand()->getFlags()); 2634 } 2635 2636 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2637 SelectionDAG &DAG) const { 2638 switch (Op.getOpcode()) { 2639 default: 2640 report_fatal_error("unimplemented operand"); 2641 case ISD::GlobalAddress: 2642 return lowerGlobalAddress(Op, DAG); 2643 case ISD::BlockAddress: 2644 return lowerBlockAddress(Op, DAG); 2645 case ISD::ConstantPool: 2646 return lowerConstantPool(Op, DAG); 2647 case ISD::JumpTable: 2648 return lowerJumpTable(Op, DAG); 2649 case ISD::GlobalTLSAddress: 2650 return lowerGlobalTLSAddress(Op, DAG); 2651 case ISD::SELECT: 2652 return lowerSELECT(Op, DAG); 2653 case ISD::BRCOND: 2654 return lowerBRCOND(Op, DAG); 2655 case ISD::VASTART: 2656 return lowerVASTART(Op, DAG); 2657 case ISD::FRAMEADDR: 2658 return lowerFRAMEADDR(Op, DAG); 2659 case ISD::RETURNADDR: 2660 return lowerRETURNADDR(Op, DAG); 2661 case ISD::SHL_PARTS: 2662 return lowerShiftLeftParts(Op, DAG); 2663 case ISD::SRA_PARTS: 2664 return lowerShiftRightParts(Op, DAG, true); 2665 case ISD::SRL_PARTS: 2666 return lowerShiftRightParts(Op, DAG, false); 2667 case ISD::BITCAST: { 2668 SDLoc DL(Op); 2669 EVT VT = Op.getValueType(); 2670 SDValue Op0 = Op.getOperand(0); 2671 EVT Op0VT = Op0.getValueType(); 2672 MVT XLenVT = Subtarget.getXLenVT(); 2673 if (VT.isFixedLengthVector()) { 2674 // We can handle fixed length vector bitcasts with a simple replacement 2675 // in isel. 2676 if (Op0VT.isFixedLengthVector()) 2677 return Op; 2678 // When bitcasting from scalar to fixed-length vector, insert the scalar 2679 // into a one-element vector of the result type, and perform a vector 2680 // bitcast. 2681 if (!Op0VT.isVector()) { 2682 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2683 if (!isTypeLegal(BVT)) 2684 return SDValue(); 2685 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2686 DAG.getUNDEF(BVT), Op0, 2687 DAG.getConstant(0, DL, XLenVT))); 2688 } 2689 return SDValue(); 2690 } 2691 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2692 // thus: bitcast the vector to a one-element vector type whose element type 2693 // is the same as the result type, and extract the first element. 2694 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2695 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2696 if (!isTypeLegal(BVT)) 2697 return SDValue(); 2698 SDValue BVec = DAG.getBitcast(BVT, Op0); 2699 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2700 DAG.getConstant(0, DL, XLenVT)); 2701 } 2702 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2703 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2704 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2705 return FPConv; 2706 } 2707 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2708 Subtarget.hasStdExtF()) { 2709 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2710 SDValue FPConv = 2711 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2712 return FPConv; 2713 } 2714 return SDValue(); 2715 } 2716 case ISD::INTRINSIC_WO_CHAIN: 2717 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2718 case ISD::INTRINSIC_W_CHAIN: 2719 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2720 case ISD::INTRINSIC_VOID: 2721 return LowerINTRINSIC_VOID(Op, DAG); 2722 case ISD::BSWAP: 2723 case ISD::BITREVERSE: { 2724 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2725 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 2726 MVT VT = Op.getSimpleValueType(); 2727 SDLoc DL(Op); 2728 // Start with the maximum immediate value which is the bitwidth - 1. 2729 unsigned Imm = VT.getSizeInBits() - 1; 2730 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2731 if (Op.getOpcode() == ISD::BSWAP) 2732 Imm &= ~0x7U; 2733 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2734 DAG.getConstant(Imm, DL, VT)); 2735 } 2736 case ISD::FSHL: 2737 case ISD::FSHR: { 2738 MVT VT = Op.getSimpleValueType(); 2739 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2740 SDLoc DL(Op); 2741 if (Op.getOperand(2).getOpcode() == ISD::Constant) 2742 return Op; 2743 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2744 // use log(XLen) bits. Mask the shift amount accordingly. 2745 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2746 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2747 DAG.getConstant(ShAmtWidth, DL, VT)); 2748 unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR; 2749 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt); 2750 } 2751 case ISD::TRUNCATE: { 2752 SDLoc DL(Op); 2753 MVT VT = Op.getSimpleValueType(); 2754 // Only custom-lower vector truncates 2755 if (!VT.isVector()) 2756 return Op; 2757 2758 // Truncates to mask types are handled differently 2759 if (VT.getVectorElementType() == MVT::i1) 2760 return lowerVectorMaskTrunc(Op, DAG); 2761 2762 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 2763 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 2764 // truncate by one power of two at a time. 2765 MVT DstEltVT = VT.getVectorElementType(); 2766 2767 SDValue Src = Op.getOperand(0); 2768 MVT SrcVT = Src.getSimpleValueType(); 2769 MVT SrcEltVT = SrcVT.getVectorElementType(); 2770 2771 assert(DstEltVT.bitsLT(SrcEltVT) && 2772 isPowerOf2_64(DstEltVT.getSizeInBits()) && 2773 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 2774 "Unexpected vector truncate lowering"); 2775 2776 MVT ContainerVT = SrcVT; 2777 if (SrcVT.isFixedLengthVector()) { 2778 ContainerVT = getContainerForFixedLengthVector(SrcVT); 2779 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 2780 } 2781 2782 SDValue Result = Src; 2783 SDValue Mask, VL; 2784 std::tie(Mask, VL) = 2785 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 2786 LLVMContext &Context = *DAG.getContext(); 2787 const ElementCount Count = ContainerVT.getVectorElementCount(); 2788 do { 2789 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 2790 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 2791 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 2792 Mask, VL); 2793 } while (SrcEltVT != DstEltVT); 2794 2795 if (SrcVT.isFixedLengthVector()) 2796 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 2797 2798 return Result; 2799 } 2800 case ISD::ANY_EXTEND: 2801 case ISD::ZERO_EXTEND: 2802 if (Op.getOperand(0).getValueType().isVector() && 2803 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2804 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 2805 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 2806 case ISD::SIGN_EXTEND: 2807 if (Op.getOperand(0).getValueType().isVector() && 2808 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2809 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 2810 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 2811 case ISD::SPLAT_VECTOR_PARTS: 2812 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 2813 case ISD::INSERT_VECTOR_ELT: 2814 return lowerINSERT_VECTOR_ELT(Op, DAG); 2815 case ISD::EXTRACT_VECTOR_ELT: 2816 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 2817 case ISD::VSCALE: { 2818 MVT VT = Op.getSimpleValueType(); 2819 SDLoc DL(Op); 2820 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 2821 // We define our scalable vector types for lmul=1 to use a 64 bit known 2822 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 2823 // vscale as VLENB / 8. 2824 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 2825 if (isa<ConstantSDNode>(Op.getOperand(0))) { 2826 // We assume VLENB is a multiple of 8. We manually choose the best shift 2827 // here because SimplifyDemandedBits isn't always able to simplify it. 2828 uint64_t Val = Op.getConstantOperandVal(0); 2829 if (isPowerOf2_64(Val)) { 2830 uint64_t Log2 = Log2_64(Val); 2831 if (Log2 < 3) 2832 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 2833 DAG.getConstant(3 - Log2, DL, VT)); 2834 if (Log2 > 3) 2835 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 2836 DAG.getConstant(Log2 - 3, DL, VT)); 2837 return VLENB; 2838 } 2839 // If the multiplier is a multiple of 8, scale it down to avoid needing 2840 // to shift the VLENB value. 2841 if ((Val % 8) == 0) 2842 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 2843 DAG.getConstant(Val / 8, DL, VT)); 2844 } 2845 2846 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 2847 DAG.getConstant(3, DL, VT)); 2848 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 2849 } 2850 case ISD::FPOWI: { 2851 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 2852 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 2853 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 2854 Op.getOperand(1).getValueType() == MVT::i32) { 2855 SDLoc DL(Op); 2856 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 2857 SDValue Powi = 2858 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 2859 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 2860 DAG.getIntPtrConstant(0, DL)); 2861 } 2862 return SDValue(); 2863 } 2864 case ISD::FP_EXTEND: { 2865 // RVV can only do fp_extend to types double the size as the source. We 2866 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 2867 // via f32. 2868 SDLoc DL(Op); 2869 MVT VT = Op.getSimpleValueType(); 2870 SDValue Src = Op.getOperand(0); 2871 MVT SrcVT = Src.getSimpleValueType(); 2872 2873 // Prepare any fixed-length vector operands. 2874 MVT ContainerVT = VT; 2875 if (SrcVT.isFixedLengthVector()) { 2876 ContainerVT = getContainerForFixedLengthVector(VT); 2877 MVT SrcContainerVT = 2878 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 2879 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2880 } 2881 2882 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 2883 SrcVT.getVectorElementType() != MVT::f16) { 2884 // For scalable vectors, we only need to close the gap between 2885 // vXf16->vXf64. 2886 if (!VT.isFixedLengthVector()) 2887 return Op; 2888 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 2889 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2890 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2891 } 2892 2893 MVT InterVT = VT.changeVectorElementType(MVT::f32); 2894 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 2895 SDValue IntermediateExtend = getRVVFPExtendOrRound( 2896 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 2897 2898 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 2899 DL, DAG, Subtarget); 2900 if (VT.isFixedLengthVector()) 2901 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 2902 return Extend; 2903 } 2904 case ISD::FP_ROUND: { 2905 // RVV can only do fp_round to types half the size as the source. We 2906 // custom-lower f64->f16 rounds via RVV's round-to-odd float 2907 // conversion instruction. 2908 SDLoc DL(Op); 2909 MVT VT = Op.getSimpleValueType(); 2910 SDValue Src = Op.getOperand(0); 2911 MVT SrcVT = Src.getSimpleValueType(); 2912 2913 // Prepare any fixed-length vector operands. 2914 MVT ContainerVT = VT; 2915 if (VT.isFixedLengthVector()) { 2916 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2917 ContainerVT = 2918 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2919 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2920 } 2921 2922 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 2923 SrcVT.getVectorElementType() != MVT::f64) { 2924 // For scalable vectors, we only need to close the gap between 2925 // vXf64<->vXf16. 2926 if (!VT.isFixedLengthVector()) 2927 return Op; 2928 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 2929 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2930 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2931 } 2932 2933 SDValue Mask, VL; 2934 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2935 2936 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 2937 SDValue IntermediateRound = 2938 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 2939 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 2940 DL, DAG, Subtarget); 2941 2942 if (VT.isFixedLengthVector()) 2943 return convertFromScalableVector(VT, Round, DAG, Subtarget); 2944 return Round; 2945 } 2946 case ISD::FP_TO_SINT: 2947 case ISD::FP_TO_UINT: 2948 case ISD::SINT_TO_FP: 2949 case ISD::UINT_TO_FP: { 2950 // RVV can only do fp<->int conversions to types half/double the size as 2951 // the source. We custom-lower any conversions that do two hops into 2952 // sequences. 2953 MVT VT = Op.getSimpleValueType(); 2954 if (!VT.isVector()) 2955 return Op; 2956 SDLoc DL(Op); 2957 SDValue Src = Op.getOperand(0); 2958 MVT EltVT = VT.getVectorElementType(); 2959 MVT SrcVT = Src.getSimpleValueType(); 2960 MVT SrcEltVT = SrcVT.getVectorElementType(); 2961 unsigned EltSize = EltVT.getSizeInBits(); 2962 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 2963 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 2964 "Unexpected vector element types"); 2965 2966 bool IsInt2FP = SrcEltVT.isInteger(); 2967 // Widening conversions 2968 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 2969 if (IsInt2FP) { 2970 // Do a regular integer sign/zero extension then convert to float. 2971 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 2972 VT.getVectorElementCount()); 2973 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 2974 ? ISD::ZERO_EXTEND 2975 : ISD::SIGN_EXTEND; 2976 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 2977 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 2978 } 2979 // FP2Int 2980 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 2981 // Do one doubling fp_extend then complete the operation by converting 2982 // to int. 2983 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2984 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 2985 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 2986 } 2987 2988 // Narrowing conversions 2989 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 2990 if (IsInt2FP) { 2991 // One narrowing int_to_fp, then an fp_round. 2992 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 2993 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2994 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 2995 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 2996 } 2997 // FP2Int 2998 // One narrowing fp_to_int, then truncate the integer. If the float isn't 2999 // representable by the integer, the result is poison. 3000 MVT IVecVT = 3001 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3002 VT.getVectorElementCount()); 3003 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3004 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3005 } 3006 3007 // Scalable vectors can exit here. Patterns will handle equally-sized 3008 // conversions halving/doubling ones. 3009 if (!VT.isFixedLengthVector()) 3010 return Op; 3011 3012 // For fixed-length vectors we lower to a custom "VL" node. 3013 unsigned RVVOpc = 0; 3014 switch (Op.getOpcode()) { 3015 default: 3016 llvm_unreachable("Impossible opcode"); 3017 case ISD::FP_TO_SINT: 3018 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3019 break; 3020 case ISD::FP_TO_UINT: 3021 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3022 break; 3023 case ISD::SINT_TO_FP: 3024 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3025 break; 3026 case ISD::UINT_TO_FP: 3027 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3028 break; 3029 } 3030 3031 MVT ContainerVT, SrcContainerVT; 3032 // Derive the reference container type from the larger vector type. 3033 if (SrcEltSize > EltSize) { 3034 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3035 ContainerVT = 3036 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3037 } else { 3038 ContainerVT = getContainerForFixedLengthVector(VT); 3039 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3040 } 3041 3042 SDValue Mask, VL; 3043 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3044 3045 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3046 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3047 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3048 } 3049 case ISD::FP_TO_SINT_SAT: 3050 case ISD::FP_TO_UINT_SAT: 3051 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3052 case ISD::FTRUNC: 3053 case ISD::FCEIL: 3054 case ISD::FFLOOR: 3055 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3056 case ISD::VECREDUCE_ADD: 3057 case ISD::VECREDUCE_UMAX: 3058 case ISD::VECREDUCE_SMAX: 3059 case ISD::VECREDUCE_UMIN: 3060 case ISD::VECREDUCE_SMIN: 3061 return lowerVECREDUCE(Op, DAG); 3062 case ISD::VECREDUCE_AND: 3063 case ISD::VECREDUCE_OR: 3064 case ISD::VECREDUCE_XOR: 3065 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3066 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3067 return lowerVECREDUCE(Op, DAG); 3068 case ISD::VECREDUCE_FADD: 3069 case ISD::VECREDUCE_SEQ_FADD: 3070 case ISD::VECREDUCE_FMIN: 3071 case ISD::VECREDUCE_FMAX: 3072 return lowerFPVECREDUCE(Op, DAG); 3073 case ISD::VP_REDUCE_ADD: 3074 case ISD::VP_REDUCE_UMAX: 3075 case ISD::VP_REDUCE_SMAX: 3076 case ISD::VP_REDUCE_UMIN: 3077 case ISD::VP_REDUCE_SMIN: 3078 case ISD::VP_REDUCE_FADD: 3079 case ISD::VP_REDUCE_SEQ_FADD: 3080 case ISD::VP_REDUCE_FMIN: 3081 case ISD::VP_REDUCE_FMAX: 3082 return lowerVPREDUCE(Op, DAG); 3083 case ISD::VP_REDUCE_AND: 3084 case ISD::VP_REDUCE_OR: 3085 case ISD::VP_REDUCE_XOR: 3086 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3087 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3088 return lowerVPREDUCE(Op, DAG); 3089 case ISD::INSERT_SUBVECTOR: 3090 return lowerINSERT_SUBVECTOR(Op, DAG); 3091 case ISD::EXTRACT_SUBVECTOR: 3092 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3093 case ISD::STEP_VECTOR: 3094 return lowerSTEP_VECTOR(Op, DAG); 3095 case ISD::VECTOR_REVERSE: 3096 return lowerVECTOR_REVERSE(Op, DAG); 3097 case ISD::BUILD_VECTOR: 3098 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3099 case ISD::SPLAT_VECTOR: 3100 if (Op.getValueType().getVectorElementType() == MVT::i1) 3101 return lowerVectorMaskSplat(Op, DAG); 3102 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3103 case ISD::VECTOR_SHUFFLE: 3104 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3105 case ISD::CONCAT_VECTORS: { 3106 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3107 // better than going through the stack, as the default expansion does. 3108 SDLoc DL(Op); 3109 MVT VT = Op.getSimpleValueType(); 3110 unsigned NumOpElts = 3111 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3112 SDValue Vec = DAG.getUNDEF(VT); 3113 for (const auto &OpIdx : enumerate(Op->ops())) 3114 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(), 3115 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3116 return Vec; 3117 } 3118 case ISD::LOAD: 3119 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3120 return V; 3121 if (Op.getValueType().isFixedLengthVector()) 3122 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3123 return Op; 3124 case ISD::STORE: 3125 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3126 return V; 3127 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3128 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3129 return Op; 3130 case ISD::MLOAD: 3131 case ISD::VP_LOAD: 3132 return lowerMaskedLoad(Op, DAG); 3133 case ISD::MSTORE: 3134 case ISD::VP_STORE: 3135 return lowerMaskedStore(Op, DAG); 3136 case ISD::SETCC: 3137 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3138 case ISD::ADD: 3139 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3140 case ISD::SUB: 3141 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3142 case ISD::MUL: 3143 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3144 case ISD::MULHS: 3145 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3146 case ISD::MULHU: 3147 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3148 case ISD::AND: 3149 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3150 RISCVISD::AND_VL); 3151 case ISD::OR: 3152 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3153 RISCVISD::OR_VL); 3154 case ISD::XOR: 3155 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3156 RISCVISD::XOR_VL); 3157 case ISD::SDIV: 3158 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3159 case ISD::SREM: 3160 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3161 case ISD::UDIV: 3162 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3163 case ISD::UREM: 3164 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3165 case ISD::SHL: 3166 case ISD::SRA: 3167 case ISD::SRL: 3168 if (Op.getSimpleValueType().isFixedLengthVector()) 3169 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3170 // This can be called for an i32 shift amount that needs to be promoted. 3171 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3172 "Unexpected custom legalisation"); 3173 return SDValue(); 3174 case ISD::SADDSAT: 3175 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3176 case ISD::UADDSAT: 3177 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3178 case ISD::SSUBSAT: 3179 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3180 case ISD::USUBSAT: 3181 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3182 case ISD::FADD: 3183 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3184 case ISD::FSUB: 3185 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3186 case ISD::FMUL: 3187 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3188 case ISD::FDIV: 3189 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3190 case ISD::FNEG: 3191 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3192 case ISD::FABS: 3193 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3194 case ISD::FSQRT: 3195 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3196 case ISD::FMA: 3197 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3198 case ISD::SMIN: 3199 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3200 case ISD::SMAX: 3201 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3202 case ISD::UMIN: 3203 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3204 case ISD::UMAX: 3205 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3206 case ISD::FMINNUM: 3207 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3208 case ISD::FMAXNUM: 3209 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3210 case ISD::ABS: 3211 return lowerABS(Op, DAG); 3212 case ISD::CTLZ_ZERO_UNDEF: 3213 case ISD::CTTZ_ZERO_UNDEF: 3214 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3215 case ISD::VSELECT: 3216 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3217 case ISD::FCOPYSIGN: 3218 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3219 case ISD::MGATHER: 3220 case ISD::VP_GATHER: 3221 return lowerMaskedGather(Op, DAG); 3222 case ISD::MSCATTER: 3223 case ISD::VP_SCATTER: 3224 return lowerMaskedScatter(Op, DAG); 3225 case ISD::FLT_ROUNDS_: 3226 return lowerGET_ROUNDING(Op, DAG); 3227 case ISD::SET_ROUNDING: 3228 return lowerSET_ROUNDING(Op, DAG); 3229 case ISD::VP_SELECT: 3230 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3231 case ISD::VP_ADD: 3232 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3233 case ISD::VP_SUB: 3234 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3235 case ISD::VP_MUL: 3236 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3237 case ISD::VP_SDIV: 3238 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3239 case ISD::VP_UDIV: 3240 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3241 case ISD::VP_SREM: 3242 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3243 case ISD::VP_UREM: 3244 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3245 case ISD::VP_AND: 3246 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3247 case ISD::VP_OR: 3248 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3249 case ISD::VP_XOR: 3250 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3251 case ISD::VP_ASHR: 3252 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3253 case ISD::VP_LSHR: 3254 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3255 case ISD::VP_SHL: 3256 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3257 case ISD::VP_FADD: 3258 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3259 case ISD::VP_FSUB: 3260 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3261 case ISD::VP_FMUL: 3262 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3263 case ISD::VP_FDIV: 3264 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3265 } 3266 } 3267 3268 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3269 SelectionDAG &DAG, unsigned Flags) { 3270 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3271 } 3272 3273 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3274 SelectionDAG &DAG, unsigned Flags) { 3275 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3276 Flags); 3277 } 3278 3279 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3280 SelectionDAG &DAG, unsigned Flags) { 3281 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3282 N->getOffset(), Flags); 3283 } 3284 3285 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3286 SelectionDAG &DAG, unsigned Flags) { 3287 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3288 } 3289 3290 template <class NodeTy> 3291 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3292 bool IsLocal) const { 3293 SDLoc DL(N); 3294 EVT Ty = getPointerTy(DAG.getDataLayout()); 3295 3296 if (isPositionIndependent()) { 3297 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3298 if (IsLocal) 3299 // Use PC-relative addressing to access the symbol. This generates the 3300 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3301 // %pcrel_lo(auipc)). 3302 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3303 3304 // Use PC-relative addressing to access the GOT for this symbol, then load 3305 // the address from the GOT. This generates the pattern (PseudoLA sym), 3306 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3307 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3308 } 3309 3310 switch (getTargetMachine().getCodeModel()) { 3311 default: 3312 report_fatal_error("Unsupported code model for lowering"); 3313 case CodeModel::Small: { 3314 // Generate a sequence for accessing addresses within the first 2 GiB of 3315 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3316 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3317 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3318 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3319 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3320 } 3321 case CodeModel::Medium: { 3322 // Generate a sequence for accessing addresses within any 2GiB range within 3323 // the address space. This generates the pattern (PseudoLLA sym), which 3324 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3325 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3326 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3327 } 3328 } 3329 } 3330 3331 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3332 SelectionDAG &DAG) const { 3333 SDLoc DL(Op); 3334 EVT Ty = Op.getValueType(); 3335 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3336 int64_t Offset = N->getOffset(); 3337 MVT XLenVT = Subtarget.getXLenVT(); 3338 3339 const GlobalValue *GV = N->getGlobal(); 3340 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3341 SDValue Addr = getAddr(N, DAG, IsLocal); 3342 3343 // In order to maximise the opportunity for common subexpression elimination, 3344 // emit a separate ADD node for the global address offset instead of folding 3345 // it in the global address node. Later peephole optimisations may choose to 3346 // fold it back in when profitable. 3347 if (Offset != 0) 3348 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3349 DAG.getConstant(Offset, DL, XLenVT)); 3350 return Addr; 3351 } 3352 3353 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3354 SelectionDAG &DAG) const { 3355 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3356 3357 return getAddr(N, DAG); 3358 } 3359 3360 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3361 SelectionDAG &DAG) const { 3362 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3363 3364 return getAddr(N, DAG); 3365 } 3366 3367 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3368 SelectionDAG &DAG) const { 3369 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3370 3371 return getAddr(N, DAG); 3372 } 3373 3374 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3375 SelectionDAG &DAG, 3376 bool UseGOT) const { 3377 SDLoc DL(N); 3378 EVT Ty = getPointerTy(DAG.getDataLayout()); 3379 const GlobalValue *GV = N->getGlobal(); 3380 MVT XLenVT = Subtarget.getXLenVT(); 3381 3382 if (UseGOT) { 3383 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3384 // load the address from the GOT and add the thread pointer. This generates 3385 // the pattern (PseudoLA_TLS_IE sym), which expands to 3386 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3387 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3388 SDValue Load = 3389 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3390 3391 // Add the thread pointer. 3392 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3393 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3394 } 3395 3396 // Generate a sequence for accessing the address relative to the thread 3397 // pointer, with the appropriate adjustment for the thread pointer offset. 3398 // This generates the pattern 3399 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3400 SDValue AddrHi = 3401 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3402 SDValue AddrAdd = 3403 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3404 SDValue AddrLo = 3405 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3406 3407 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3408 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3409 SDValue MNAdd = SDValue( 3410 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3411 0); 3412 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3413 } 3414 3415 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3416 SelectionDAG &DAG) const { 3417 SDLoc DL(N); 3418 EVT Ty = getPointerTy(DAG.getDataLayout()); 3419 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3420 const GlobalValue *GV = N->getGlobal(); 3421 3422 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3423 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3424 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3425 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3426 SDValue Load = 3427 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3428 3429 // Prepare argument list to generate call. 3430 ArgListTy Args; 3431 ArgListEntry Entry; 3432 Entry.Node = Load; 3433 Entry.Ty = CallTy; 3434 Args.push_back(Entry); 3435 3436 // Setup call to __tls_get_addr. 3437 TargetLowering::CallLoweringInfo CLI(DAG); 3438 CLI.setDebugLoc(DL) 3439 .setChain(DAG.getEntryNode()) 3440 .setLibCallee(CallingConv::C, CallTy, 3441 DAG.getExternalSymbol("__tls_get_addr", Ty), 3442 std::move(Args)); 3443 3444 return LowerCallTo(CLI).first; 3445 } 3446 3447 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3448 SelectionDAG &DAG) const { 3449 SDLoc DL(Op); 3450 EVT Ty = Op.getValueType(); 3451 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3452 int64_t Offset = N->getOffset(); 3453 MVT XLenVT = Subtarget.getXLenVT(); 3454 3455 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3456 3457 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3458 CallingConv::GHC) 3459 report_fatal_error("In GHC calling convention TLS is not supported"); 3460 3461 SDValue Addr; 3462 switch (Model) { 3463 case TLSModel::LocalExec: 3464 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3465 break; 3466 case TLSModel::InitialExec: 3467 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3468 break; 3469 case TLSModel::LocalDynamic: 3470 case TLSModel::GeneralDynamic: 3471 Addr = getDynamicTLSAddr(N, DAG); 3472 break; 3473 } 3474 3475 // In order to maximise the opportunity for common subexpression elimination, 3476 // emit a separate ADD node for the global address offset instead of folding 3477 // it in the global address node. Later peephole optimisations may choose to 3478 // fold it back in when profitable. 3479 if (Offset != 0) 3480 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3481 DAG.getConstant(Offset, DL, XLenVT)); 3482 return Addr; 3483 } 3484 3485 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3486 SDValue CondV = Op.getOperand(0); 3487 SDValue TrueV = Op.getOperand(1); 3488 SDValue FalseV = Op.getOperand(2); 3489 SDLoc DL(Op); 3490 MVT VT = Op.getSimpleValueType(); 3491 MVT XLenVT = Subtarget.getXLenVT(); 3492 3493 // Lower vector SELECTs to VSELECTs by splatting the condition. 3494 if (VT.isVector()) { 3495 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3496 SDValue CondSplat = VT.isScalableVector() 3497 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3498 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3499 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3500 } 3501 3502 // If the result type is XLenVT and CondV is the output of a SETCC node 3503 // which also operated on XLenVT inputs, then merge the SETCC node into the 3504 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3505 // compare+branch instructions. i.e.: 3506 // (select (setcc lhs, rhs, cc), truev, falsev) 3507 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3508 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3509 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3510 SDValue LHS = CondV.getOperand(0); 3511 SDValue RHS = CondV.getOperand(1); 3512 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3513 ISD::CondCode CCVal = CC->get(); 3514 3515 // Special case for a select of 2 constants that have a diffence of 1. 3516 // Normally this is done by DAGCombine, but if the select is introduced by 3517 // type legalization or op legalization, we miss it. Restricting to SETLT 3518 // case for now because that is what signed saturating add/sub need. 3519 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3520 // but we would probably want to swap the true/false values if the condition 3521 // is SETGE/SETLE to avoid an XORI. 3522 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3523 CCVal == ISD::SETLT) { 3524 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3525 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3526 if (TrueVal - 1 == FalseVal) 3527 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3528 if (TrueVal + 1 == FalseVal) 3529 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3530 } 3531 3532 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3533 3534 SDValue TargetCC = DAG.getCondCode(CCVal); 3535 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3536 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3537 } 3538 3539 // Otherwise: 3540 // (select condv, truev, falsev) 3541 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3542 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3543 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3544 3545 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3546 3547 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3548 } 3549 3550 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3551 SDValue CondV = Op.getOperand(1); 3552 SDLoc DL(Op); 3553 MVT XLenVT = Subtarget.getXLenVT(); 3554 3555 if (CondV.getOpcode() == ISD::SETCC && 3556 CondV.getOperand(0).getValueType() == XLenVT) { 3557 SDValue LHS = CondV.getOperand(0); 3558 SDValue RHS = CondV.getOperand(1); 3559 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3560 3561 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3562 3563 SDValue TargetCC = DAG.getCondCode(CCVal); 3564 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3565 LHS, RHS, TargetCC, Op.getOperand(2)); 3566 } 3567 3568 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3569 CondV, DAG.getConstant(0, DL, XLenVT), 3570 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3571 } 3572 3573 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3574 MachineFunction &MF = DAG.getMachineFunction(); 3575 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3576 3577 SDLoc DL(Op); 3578 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3579 getPointerTy(MF.getDataLayout())); 3580 3581 // vastart just stores the address of the VarArgsFrameIndex slot into the 3582 // memory location argument. 3583 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3584 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3585 MachinePointerInfo(SV)); 3586 } 3587 3588 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3589 SelectionDAG &DAG) const { 3590 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3591 MachineFunction &MF = DAG.getMachineFunction(); 3592 MachineFrameInfo &MFI = MF.getFrameInfo(); 3593 MFI.setFrameAddressIsTaken(true); 3594 Register FrameReg = RI.getFrameRegister(MF); 3595 int XLenInBytes = Subtarget.getXLen() / 8; 3596 3597 EVT VT = Op.getValueType(); 3598 SDLoc DL(Op); 3599 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3600 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3601 while (Depth--) { 3602 int Offset = -(XLenInBytes * 2); 3603 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3604 DAG.getIntPtrConstant(Offset, DL)); 3605 FrameAddr = 3606 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3607 } 3608 return FrameAddr; 3609 } 3610 3611 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3612 SelectionDAG &DAG) const { 3613 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3614 MachineFunction &MF = DAG.getMachineFunction(); 3615 MachineFrameInfo &MFI = MF.getFrameInfo(); 3616 MFI.setReturnAddressIsTaken(true); 3617 MVT XLenVT = Subtarget.getXLenVT(); 3618 int XLenInBytes = Subtarget.getXLen() / 8; 3619 3620 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3621 return SDValue(); 3622 3623 EVT VT = Op.getValueType(); 3624 SDLoc DL(Op); 3625 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3626 if (Depth) { 3627 int Off = -XLenInBytes; 3628 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3629 SDValue Offset = DAG.getConstant(Off, DL, VT); 3630 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3631 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3632 MachinePointerInfo()); 3633 } 3634 3635 // Return the value of the return address register, marking it an implicit 3636 // live-in. 3637 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3638 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3639 } 3640 3641 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3642 SelectionDAG &DAG) const { 3643 SDLoc DL(Op); 3644 SDValue Lo = Op.getOperand(0); 3645 SDValue Hi = Op.getOperand(1); 3646 SDValue Shamt = Op.getOperand(2); 3647 EVT VT = Lo.getValueType(); 3648 3649 // if Shamt-XLEN < 0: // Shamt < XLEN 3650 // Lo = Lo << Shamt 3651 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3652 // else: 3653 // Lo = 0 3654 // Hi = Lo << (Shamt-XLEN) 3655 3656 SDValue Zero = DAG.getConstant(0, DL, VT); 3657 SDValue One = DAG.getConstant(1, DL, VT); 3658 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3659 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3660 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3661 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3662 3663 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3664 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3665 SDValue ShiftRightLo = 3666 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3667 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3668 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3669 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3670 3671 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3672 3673 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3674 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3675 3676 SDValue Parts[2] = {Lo, Hi}; 3677 return DAG.getMergeValues(Parts, DL); 3678 } 3679 3680 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3681 bool IsSRA) const { 3682 SDLoc DL(Op); 3683 SDValue Lo = Op.getOperand(0); 3684 SDValue Hi = Op.getOperand(1); 3685 SDValue Shamt = Op.getOperand(2); 3686 EVT VT = Lo.getValueType(); 3687 3688 // SRA expansion: 3689 // if Shamt-XLEN < 0: // Shamt < XLEN 3690 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3691 // Hi = Hi >>s Shamt 3692 // else: 3693 // Lo = Hi >>s (Shamt-XLEN); 3694 // Hi = Hi >>s (XLEN-1) 3695 // 3696 // SRL expansion: 3697 // if Shamt-XLEN < 0: // Shamt < XLEN 3698 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3699 // Hi = Hi >>u Shamt 3700 // else: 3701 // Lo = Hi >>u (Shamt-XLEN); 3702 // Hi = 0; 3703 3704 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3705 3706 SDValue Zero = DAG.getConstant(0, DL, VT); 3707 SDValue One = DAG.getConstant(1, DL, VT); 3708 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3709 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3710 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3711 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3712 3713 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3714 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3715 SDValue ShiftLeftHi = 3716 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3717 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3718 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3719 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3720 SDValue HiFalse = 3721 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3722 3723 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3724 3725 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3726 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3727 3728 SDValue Parts[2] = {Lo, Hi}; 3729 return DAG.getMergeValues(Parts, DL); 3730 } 3731 3732 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3733 // legal equivalently-sized i8 type, so we can use that as a go-between. 3734 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3735 SelectionDAG &DAG) const { 3736 SDLoc DL(Op); 3737 MVT VT = Op.getSimpleValueType(); 3738 SDValue SplatVal = Op.getOperand(0); 3739 // All-zeros or all-ones splats are handled specially. 3740 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3741 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3742 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3743 } 3744 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3745 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3746 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3747 } 3748 MVT XLenVT = Subtarget.getXLenVT(); 3749 assert(SplatVal.getValueType() == XLenVT && 3750 "Unexpected type for i1 splat value"); 3751 MVT InterVT = VT.changeVectorElementType(MVT::i8); 3752 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 3753 DAG.getConstant(1, DL, XLenVT)); 3754 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 3755 SDValue Zero = DAG.getConstant(0, DL, InterVT); 3756 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 3757 } 3758 3759 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 3760 // illegal (currently only vXi64 RV32). 3761 // FIXME: We could also catch non-constant sign-extended i32 values and lower 3762 // them to SPLAT_VECTOR_I64 3763 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 3764 SelectionDAG &DAG) const { 3765 SDLoc DL(Op); 3766 MVT VecVT = Op.getSimpleValueType(); 3767 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 3768 "Unexpected SPLAT_VECTOR_PARTS lowering"); 3769 3770 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 3771 SDValue Lo = Op.getOperand(0); 3772 SDValue Hi = Op.getOperand(1); 3773 3774 if (VecVT.isFixedLengthVector()) { 3775 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3776 SDLoc DL(Op); 3777 SDValue Mask, VL; 3778 std::tie(Mask, VL) = 3779 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3780 3781 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 3782 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 3783 } 3784 3785 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 3786 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 3787 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 3788 // If Hi constant is all the same sign bit as Lo, lower this as a custom 3789 // node in order to try and match RVV vector/scalar instructions. 3790 if ((LoC >> 31) == HiC) 3791 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3792 } 3793 3794 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 3795 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 3796 isa<ConstantSDNode>(Hi.getOperand(1)) && 3797 Hi.getConstantOperandVal(1) == 31) 3798 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3799 3800 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 3801 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 3802 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64)); 3803 } 3804 3805 // Custom-lower extensions from mask vectors by using a vselect either with 1 3806 // for zero/any-extension or -1 for sign-extension: 3807 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 3808 // Note that any-extension is lowered identically to zero-extension. 3809 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 3810 int64_t ExtTrueVal) const { 3811 SDLoc DL(Op); 3812 MVT VecVT = Op.getSimpleValueType(); 3813 SDValue Src = Op.getOperand(0); 3814 // Only custom-lower extensions from mask types 3815 assert(Src.getValueType().isVector() && 3816 Src.getValueType().getVectorElementType() == MVT::i1); 3817 3818 MVT XLenVT = Subtarget.getXLenVT(); 3819 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 3820 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 3821 3822 if (VecVT.isScalableVector()) { 3823 // Be careful not to introduce illegal scalar types at this stage, and be 3824 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 3825 // illegal and must be expanded. Since we know that the constants are 3826 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 3827 bool IsRV32E64 = 3828 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 3829 3830 if (!IsRV32E64) { 3831 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 3832 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 3833 } else { 3834 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 3835 SplatTrueVal = 3836 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 3837 } 3838 3839 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 3840 } 3841 3842 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3843 MVT I1ContainerVT = 3844 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3845 3846 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 3847 3848 SDValue Mask, VL; 3849 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3850 3851 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 3852 SplatTrueVal = 3853 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 3854 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 3855 SplatTrueVal, SplatZero, VL); 3856 3857 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 3858 } 3859 3860 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 3861 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 3862 MVT ExtVT = Op.getSimpleValueType(); 3863 // Only custom-lower extensions from fixed-length vector types. 3864 if (!ExtVT.isFixedLengthVector()) 3865 return Op; 3866 MVT VT = Op.getOperand(0).getSimpleValueType(); 3867 // Grab the canonical container type for the extended type. Infer the smaller 3868 // type from that to ensure the same number of vector elements, as we know 3869 // the LMUL will be sufficient to hold the smaller type. 3870 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 3871 // Get the extended container type manually to ensure the same number of 3872 // vector elements between source and dest. 3873 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 3874 ContainerExtVT.getVectorElementCount()); 3875 3876 SDValue Op1 = 3877 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 3878 3879 SDLoc DL(Op); 3880 SDValue Mask, VL; 3881 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3882 3883 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 3884 3885 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 3886 } 3887 3888 // Custom-lower truncations from vectors to mask vectors by using a mask and a 3889 // setcc operation: 3890 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 3891 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 3892 SelectionDAG &DAG) const { 3893 SDLoc DL(Op); 3894 EVT MaskVT = Op.getValueType(); 3895 // Only expect to custom-lower truncations to mask types 3896 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 3897 "Unexpected type for vector mask lowering"); 3898 SDValue Src = Op.getOperand(0); 3899 MVT VecVT = Src.getSimpleValueType(); 3900 3901 // If this is a fixed vector, we need to convert it to a scalable vector. 3902 MVT ContainerVT = VecVT; 3903 if (VecVT.isFixedLengthVector()) { 3904 ContainerVT = getContainerForFixedLengthVector(VecVT); 3905 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3906 } 3907 3908 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 3909 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 3910 3911 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 3912 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 3913 3914 if (VecVT.isScalableVector()) { 3915 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 3916 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 3917 } 3918 3919 SDValue Mask, VL; 3920 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3921 3922 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 3923 SDValue Trunc = 3924 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 3925 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 3926 DAG.getCondCode(ISD::SETNE), Mask, VL); 3927 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 3928 } 3929 3930 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 3931 // first position of a vector, and that vector is slid up to the insert index. 3932 // By limiting the active vector length to index+1 and merging with the 3933 // original vector (with an undisturbed tail policy for elements >= VL), we 3934 // achieve the desired result of leaving all elements untouched except the one 3935 // at VL-1, which is replaced with the desired value. 3936 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3937 SelectionDAG &DAG) const { 3938 SDLoc DL(Op); 3939 MVT VecVT = Op.getSimpleValueType(); 3940 SDValue Vec = Op.getOperand(0); 3941 SDValue Val = Op.getOperand(1); 3942 SDValue Idx = Op.getOperand(2); 3943 3944 if (VecVT.getVectorElementType() == MVT::i1) { 3945 // FIXME: For now we just promote to an i8 vector and insert into that, 3946 // but this is probably not optimal. 3947 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3948 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3949 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 3950 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 3951 } 3952 3953 MVT ContainerVT = VecVT; 3954 // If the operand is a fixed-length vector, convert to a scalable one. 3955 if (VecVT.isFixedLengthVector()) { 3956 ContainerVT = getContainerForFixedLengthVector(VecVT); 3957 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3958 } 3959 3960 MVT XLenVT = Subtarget.getXLenVT(); 3961 3962 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3963 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 3964 // Even i64-element vectors on RV32 can be lowered without scalar 3965 // legalization if the most-significant 32 bits of the value are not affected 3966 // by the sign-extension of the lower 32 bits. 3967 // TODO: We could also catch sign extensions of a 32-bit value. 3968 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 3969 const auto *CVal = cast<ConstantSDNode>(Val); 3970 if (isInt<32>(CVal->getSExtValue())) { 3971 IsLegalInsert = true; 3972 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3973 } 3974 } 3975 3976 SDValue Mask, VL; 3977 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3978 3979 SDValue ValInVec; 3980 3981 if (IsLegalInsert) { 3982 unsigned Opc = 3983 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 3984 if (isNullConstant(Idx)) { 3985 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 3986 if (!VecVT.isFixedLengthVector()) 3987 return Vec; 3988 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 3989 } 3990 ValInVec = 3991 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 3992 } else { 3993 // On RV32, i64-element vectors must be specially handled to place the 3994 // value at element 0, by using two vslide1up instructions in sequence on 3995 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 3996 // this. 3997 SDValue One = DAG.getConstant(1, DL, XLenVT); 3998 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 3999 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4000 MVT I32ContainerVT = 4001 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4002 SDValue I32Mask = 4003 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4004 // Limit the active VL to two. 4005 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4006 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4007 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4008 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 4009 InsertI64VL); 4010 // First slide in the hi value, then the lo in underneath it. 4011 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 4012 ValHi, I32Mask, InsertI64VL); 4013 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 4014 ValLo, I32Mask, InsertI64VL); 4015 // Bitcast back to the right container type. 4016 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4017 } 4018 4019 // Now that the value is in a vector, slide it into position. 4020 SDValue InsertVL = 4021 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4022 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4023 ValInVec, Idx, Mask, InsertVL); 4024 if (!VecVT.isFixedLengthVector()) 4025 return Slideup; 4026 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4027 } 4028 4029 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4030 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4031 // types this is done using VMV_X_S to allow us to glean information about the 4032 // sign bits of the result. 4033 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4034 SelectionDAG &DAG) const { 4035 SDLoc DL(Op); 4036 SDValue Idx = Op.getOperand(1); 4037 SDValue Vec = Op.getOperand(0); 4038 EVT EltVT = Op.getValueType(); 4039 MVT VecVT = Vec.getSimpleValueType(); 4040 MVT XLenVT = Subtarget.getXLenVT(); 4041 4042 if (VecVT.getVectorElementType() == MVT::i1) { 4043 // FIXME: For now we just promote to an i8 vector and extract from that, 4044 // but this is probably not optimal. 4045 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4046 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4047 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4048 } 4049 4050 // If this is a fixed vector, we need to convert it to a scalable vector. 4051 MVT ContainerVT = VecVT; 4052 if (VecVT.isFixedLengthVector()) { 4053 ContainerVT = getContainerForFixedLengthVector(VecVT); 4054 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4055 } 4056 4057 // If the index is 0, the vector is already in the right position. 4058 if (!isNullConstant(Idx)) { 4059 // Use a VL of 1 to avoid processing more elements than we need. 4060 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4061 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4062 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4063 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4064 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4065 } 4066 4067 if (!EltVT.isInteger()) { 4068 // Floating-point extracts are handled in TableGen. 4069 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4070 DAG.getConstant(0, DL, XLenVT)); 4071 } 4072 4073 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4074 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4075 } 4076 4077 // Some RVV intrinsics may claim that they want an integer operand to be 4078 // promoted or expanded. 4079 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 4080 const RISCVSubtarget &Subtarget) { 4081 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4082 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4083 "Unexpected opcode"); 4084 4085 if (!Subtarget.hasVInstructions()) 4086 return SDValue(); 4087 4088 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4089 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4090 SDLoc DL(Op); 4091 4092 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4093 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4094 if (!II || !II->SplatOperand) 4095 return SDValue(); 4096 4097 unsigned SplatOp = II->SplatOperand + HasChain; 4098 assert(SplatOp < Op.getNumOperands()); 4099 4100 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4101 SDValue &ScalarOp = Operands[SplatOp]; 4102 MVT OpVT = ScalarOp.getSimpleValueType(); 4103 MVT XLenVT = Subtarget.getXLenVT(); 4104 4105 // If this isn't a scalar, or its type is XLenVT we're done. 4106 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4107 return SDValue(); 4108 4109 // Simplest case is that the operand needs to be promoted to XLenVT. 4110 if (OpVT.bitsLT(XLenVT)) { 4111 // If the operand is a constant, sign extend to increase our chances 4112 // of being able to use a .vi instruction. ANY_EXTEND would become a 4113 // a zero extend and the simm5 check in isel would fail. 4114 // FIXME: Should we ignore the upper bits in isel instead? 4115 unsigned ExtOpc = 4116 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4117 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4118 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4119 } 4120 4121 // Use the previous operand to get the vXi64 VT. The result might be a mask 4122 // VT for compares. Using the previous operand assumes that the previous 4123 // operand will never have a smaller element size than a scalar operand and 4124 // that a widening operation never uses SEW=64. 4125 // NOTE: If this fails the below assert, we can probably just find the 4126 // element count from any operand or result and use it to construct the VT. 4127 assert(II->SplatOperand > 1 && "Unexpected splat operand!"); 4128 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4129 4130 // The more complex case is when the scalar is larger than XLenVT. 4131 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4132 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4133 4134 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4135 // on the instruction to sign-extend since SEW>XLEN. 4136 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4137 if (isInt<32>(CVal->getSExtValue())) { 4138 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4139 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4140 } 4141 } 4142 4143 // We need to convert the scalar to a splat vector. 4144 // FIXME: Can we implicitly truncate the scalar if it is known to 4145 // be sign extended? 4146 // VL should be the last operand. 4147 SDValue VL = Op.getOperand(Op.getNumOperands() - 1); 4148 assert(VL.getValueType() == XLenVT); 4149 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 4150 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4151 } 4152 4153 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4154 SelectionDAG &DAG) const { 4155 unsigned IntNo = Op.getConstantOperandVal(0); 4156 SDLoc DL(Op); 4157 MVT XLenVT = Subtarget.getXLenVT(); 4158 4159 switch (IntNo) { 4160 default: 4161 break; // Don't custom lower most intrinsics. 4162 case Intrinsic::thread_pointer: { 4163 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4164 return DAG.getRegister(RISCV::X4, PtrVT); 4165 } 4166 case Intrinsic::riscv_orc_b: 4167 // Lower to the GORCI encoding for orc.b. 4168 return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1), 4169 DAG.getConstant(7, DL, XLenVT)); 4170 case Intrinsic::riscv_grev: 4171 case Intrinsic::riscv_gorc: { 4172 unsigned Opc = 4173 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4174 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4175 } 4176 case Intrinsic::riscv_shfl: 4177 case Intrinsic::riscv_unshfl: { 4178 unsigned Opc = 4179 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4180 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4181 } 4182 case Intrinsic::riscv_bcompress: 4183 case Intrinsic::riscv_bdecompress: { 4184 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4185 : RISCVISD::BDECOMPRESS; 4186 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4187 } 4188 case Intrinsic::riscv_vmv_x_s: 4189 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4190 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4191 Op.getOperand(1)); 4192 case Intrinsic::riscv_vmv_v_x: 4193 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4194 Op.getSimpleValueType(), DL, DAG, Subtarget); 4195 case Intrinsic::riscv_vfmv_v_f: 4196 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4197 Op.getOperand(1), Op.getOperand(2)); 4198 case Intrinsic::riscv_vmv_s_x: { 4199 SDValue Scalar = Op.getOperand(2); 4200 4201 if (Scalar.getValueType().bitsLE(XLenVT)) { 4202 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4203 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4204 Op.getOperand(1), Scalar, Op.getOperand(3)); 4205 } 4206 4207 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4208 4209 // This is an i64 value that lives in two scalar registers. We have to 4210 // insert this in a convoluted way. First we build vXi64 splat containing 4211 // the/ two values that we assemble using some bit math. Next we'll use 4212 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4213 // to merge element 0 from our splat into the source vector. 4214 // FIXME: This is probably not the best way to do this, but it is 4215 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4216 // point. 4217 // sw lo, (a0) 4218 // sw hi, 4(a0) 4219 // vlse vX, (a0) 4220 // 4221 // vid.v vVid 4222 // vmseq.vx mMask, vVid, 0 4223 // vmerge.vvm vDest, vSrc, vVal, mMask 4224 MVT VT = Op.getSimpleValueType(); 4225 SDValue Vec = Op.getOperand(1); 4226 SDValue VL = Op.getOperand(3); 4227 4228 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 4229 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4230 DAG.getConstant(0, DL, MVT::i32), VL); 4231 4232 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4233 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4234 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4235 SDValue SelectCond = 4236 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4237 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4238 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4239 Vec, VL); 4240 } 4241 case Intrinsic::riscv_vslide1up: 4242 case Intrinsic::riscv_vslide1down: 4243 case Intrinsic::riscv_vslide1up_mask: 4244 case Intrinsic::riscv_vslide1down_mask: { 4245 // We need to special case these when the scalar is larger than XLen. 4246 unsigned NumOps = Op.getNumOperands(); 4247 bool IsMasked = NumOps == 7; 4248 unsigned OpOffset = IsMasked ? 1 : 0; 4249 SDValue Scalar = Op.getOperand(2 + OpOffset); 4250 if (Scalar.getValueType().bitsLE(XLenVT)) 4251 break; 4252 4253 // Splatting a sign extended constant is fine. 4254 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4255 if (isInt<32>(CVal->getSExtValue())) 4256 break; 4257 4258 MVT VT = Op.getSimpleValueType(); 4259 assert(VT.getVectorElementType() == MVT::i64 && 4260 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4261 4262 // Convert the vector source to the equivalent nxvXi32 vector. 4263 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4264 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 4265 4266 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4267 DAG.getConstant(0, DL, XLenVT)); 4268 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4269 DAG.getConstant(1, DL, XLenVT)); 4270 4271 // Double the VL since we halved SEW. 4272 SDValue VL = Op.getOperand(NumOps - (1 + OpOffset)); 4273 SDValue I32VL = 4274 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4275 4276 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4277 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4278 4279 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4280 // instructions. 4281 if (IntNo == Intrinsic::riscv_vslide1up || 4282 IntNo == Intrinsic::riscv_vslide1up_mask) { 4283 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 4284 I32Mask, I32VL); 4285 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 4286 I32Mask, I32VL); 4287 } else { 4288 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 4289 I32Mask, I32VL); 4290 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 4291 I32Mask, I32VL); 4292 } 4293 4294 // Convert back to nxvXi64. 4295 Vec = DAG.getBitcast(VT, Vec); 4296 4297 if (!IsMasked) 4298 return Vec; 4299 4300 // Apply mask after the operation. 4301 SDValue Mask = Op.getOperand(NumOps - 3); 4302 SDValue MaskedOff = Op.getOperand(1); 4303 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4304 } 4305 } 4306 4307 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4308 } 4309 4310 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4311 SelectionDAG &DAG) const { 4312 unsigned IntNo = Op.getConstantOperandVal(1); 4313 switch (IntNo) { 4314 default: 4315 break; 4316 case Intrinsic::riscv_masked_strided_load: { 4317 SDLoc DL(Op); 4318 MVT XLenVT = Subtarget.getXLenVT(); 4319 4320 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4321 // the selection of the masked intrinsics doesn't do this for us. 4322 SDValue Mask = Op.getOperand(5); 4323 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4324 4325 MVT VT = Op->getSimpleValueType(0); 4326 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4327 4328 SDValue PassThru = Op.getOperand(2); 4329 if (!IsUnmasked) { 4330 MVT MaskVT = 4331 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4332 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4333 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4334 } 4335 4336 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4337 4338 SDValue IntID = DAG.getTargetConstant( 4339 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4340 XLenVT); 4341 4342 auto *Load = cast<MemIntrinsicSDNode>(Op); 4343 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4344 if (!IsUnmasked) 4345 Ops.push_back(PassThru); 4346 Ops.push_back(Op.getOperand(3)); // Ptr 4347 Ops.push_back(Op.getOperand(4)); // Stride 4348 if (!IsUnmasked) 4349 Ops.push_back(Mask); 4350 Ops.push_back(VL); 4351 if (!IsUnmasked) { 4352 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4353 Ops.push_back(Policy); 4354 } 4355 4356 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4357 SDValue Result = 4358 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4359 Load->getMemoryVT(), Load->getMemOperand()); 4360 SDValue Chain = Result.getValue(1); 4361 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4362 return DAG.getMergeValues({Result, Chain}, DL); 4363 } 4364 } 4365 4366 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4367 } 4368 4369 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4370 SelectionDAG &DAG) const { 4371 unsigned IntNo = Op.getConstantOperandVal(1); 4372 switch (IntNo) { 4373 default: 4374 break; 4375 case Intrinsic::riscv_masked_strided_store: { 4376 SDLoc DL(Op); 4377 MVT XLenVT = Subtarget.getXLenVT(); 4378 4379 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4380 // the selection of the masked intrinsics doesn't do this for us. 4381 SDValue Mask = Op.getOperand(5); 4382 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4383 4384 SDValue Val = Op.getOperand(2); 4385 MVT VT = Val.getSimpleValueType(); 4386 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4387 4388 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4389 if (!IsUnmasked) { 4390 MVT MaskVT = 4391 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4392 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4393 } 4394 4395 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4396 4397 SDValue IntID = DAG.getTargetConstant( 4398 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4399 XLenVT); 4400 4401 auto *Store = cast<MemIntrinsicSDNode>(Op); 4402 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4403 Ops.push_back(Val); 4404 Ops.push_back(Op.getOperand(3)); // Ptr 4405 Ops.push_back(Op.getOperand(4)); // Stride 4406 if (!IsUnmasked) 4407 Ops.push_back(Mask); 4408 Ops.push_back(VL); 4409 4410 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4411 Ops, Store->getMemoryVT(), 4412 Store->getMemOperand()); 4413 } 4414 } 4415 4416 return SDValue(); 4417 } 4418 4419 static MVT getLMUL1VT(MVT VT) { 4420 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4421 "Unexpected vector MVT"); 4422 return MVT::getScalableVectorVT( 4423 VT.getVectorElementType(), 4424 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4425 } 4426 4427 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4428 switch (ISDOpcode) { 4429 default: 4430 llvm_unreachable("Unhandled reduction"); 4431 case ISD::VECREDUCE_ADD: 4432 return RISCVISD::VECREDUCE_ADD_VL; 4433 case ISD::VECREDUCE_UMAX: 4434 return RISCVISD::VECREDUCE_UMAX_VL; 4435 case ISD::VECREDUCE_SMAX: 4436 return RISCVISD::VECREDUCE_SMAX_VL; 4437 case ISD::VECREDUCE_UMIN: 4438 return RISCVISD::VECREDUCE_UMIN_VL; 4439 case ISD::VECREDUCE_SMIN: 4440 return RISCVISD::VECREDUCE_SMIN_VL; 4441 case ISD::VECREDUCE_AND: 4442 return RISCVISD::VECREDUCE_AND_VL; 4443 case ISD::VECREDUCE_OR: 4444 return RISCVISD::VECREDUCE_OR_VL; 4445 case ISD::VECREDUCE_XOR: 4446 return RISCVISD::VECREDUCE_XOR_VL; 4447 } 4448 } 4449 4450 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4451 SelectionDAG &DAG, 4452 bool IsVP) const { 4453 SDLoc DL(Op); 4454 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4455 MVT VecVT = Vec.getSimpleValueType(); 4456 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4457 Op.getOpcode() == ISD::VECREDUCE_OR || 4458 Op.getOpcode() == ISD::VECREDUCE_XOR || 4459 Op.getOpcode() == ISD::VP_REDUCE_AND || 4460 Op.getOpcode() == ISD::VP_REDUCE_OR || 4461 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4462 "Unexpected reduction lowering"); 4463 4464 MVT XLenVT = Subtarget.getXLenVT(); 4465 assert(Op.getValueType() == XLenVT && 4466 "Expected reduction output to be legalized to XLenVT"); 4467 4468 MVT ContainerVT = VecVT; 4469 if (VecVT.isFixedLengthVector()) { 4470 ContainerVT = getContainerForFixedLengthVector(VecVT); 4471 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4472 } 4473 4474 SDValue Mask, VL; 4475 if (IsVP) { 4476 Mask = Op.getOperand(2); 4477 VL = Op.getOperand(3); 4478 } else { 4479 std::tie(Mask, VL) = 4480 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4481 } 4482 4483 unsigned BaseOpc; 4484 ISD::CondCode CC; 4485 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4486 4487 switch (Op.getOpcode()) { 4488 default: 4489 llvm_unreachable("Unhandled reduction"); 4490 case ISD::VECREDUCE_AND: 4491 case ISD::VP_REDUCE_AND: { 4492 // vcpop ~x == 0 4493 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4494 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4495 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4496 CC = ISD::SETEQ; 4497 BaseOpc = ISD::AND; 4498 break; 4499 } 4500 case ISD::VECREDUCE_OR: 4501 case ISD::VP_REDUCE_OR: 4502 // vcpop x != 0 4503 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4504 CC = ISD::SETNE; 4505 BaseOpc = ISD::OR; 4506 break; 4507 case ISD::VECREDUCE_XOR: 4508 case ISD::VP_REDUCE_XOR: { 4509 // ((vcpop x) & 1) != 0 4510 SDValue One = DAG.getConstant(1, DL, XLenVT); 4511 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4512 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4513 CC = ISD::SETNE; 4514 BaseOpc = ISD::XOR; 4515 break; 4516 } 4517 } 4518 4519 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4520 4521 if (!IsVP) 4522 return SetCC; 4523 4524 // Now include the start value in the operation. 4525 // Note that we must return the start value when no elements are operated 4526 // upon. The vcpop instructions we've emitted in each case above will return 4527 // 0 for an inactive vector, and so we've already received the neutral value: 4528 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4529 // can simply include the start value. 4530 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4531 } 4532 4533 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4534 SelectionDAG &DAG) const { 4535 SDLoc DL(Op); 4536 SDValue Vec = Op.getOperand(0); 4537 EVT VecEVT = Vec.getValueType(); 4538 4539 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4540 4541 // Due to ordering in legalize types we may have a vector type that needs to 4542 // be split. Do that manually so we can get down to a legal type. 4543 while (getTypeAction(*DAG.getContext(), VecEVT) == 4544 TargetLowering::TypeSplitVector) { 4545 SDValue Lo, Hi; 4546 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4547 VecEVT = Lo.getValueType(); 4548 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4549 } 4550 4551 // TODO: The type may need to be widened rather than split. Or widened before 4552 // it can be split. 4553 if (!isTypeLegal(VecEVT)) 4554 return SDValue(); 4555 4556 MVT VecVT = VecEVT.getSimpleVT(); 4557 MVT VecEltVT = VecVT.getVectorElementType(); 4558 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4559 4560 MVT ContainerVT = VecVT; 4561 if (VecVT.isFixedLengthVector()) { 4562 ContainerVT = getContainerForFixedLengthVector(VecVT); 4563 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4564 } 4565 4566 MVT M1VT = getLMUL1VT(ContainerVT); 4567 MVT XLenVT = Subtarget.getXLenVT(); 4568 4569 SDValue Mask, VL; 4570 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4571 4572 SDValue NeutralElem = 4573 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4574 SDValue IdentitySplat = lowerScalarSplat( 4575 NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4576 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4577 IdentitySplat, Mask, VL); 4578 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4579 DAG.getConstant(0, DL, XLenVT)); 4580 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4581 } 4582 4583 // Given a reduction op, this function returns the matching reduction opcode, 4584 // the vector SDValue and the scalar SDValue required to lower this to a 4585 // RISCVISD node. 4586 static std::tuple<unsigned, SDValue, SDValue> 4587 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4588 SDLoc DL(Op); 4589 auto Flags = Op->getFlags(); 4590 unsigned Opcode = Op.getOpcode(); 4591 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4592 switch (Opcode) { 4593 default: 4594 llvm_unreachable("Unhandled reduction"); 4595 case ISD::VECREDUCE_FADD: { 4596 // Use positive zero if we can. It is cheaper to materialize. 4597 SDValue Zero = 4598 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 4599 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 4600 } 4601 case ISD::VECREDUCE_SEQ_FADD: 4602 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4603 Op.getOperand(0)); 4604 case ISD::VECREDUCE_FMIN: 4605 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4606 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4607 case ISD::VECREDUCE_FMAX: 4608 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4609 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4610 } 4611 } 4612 4613 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4614 SelectionDAG &DAG) const { 4615 SDLoc DL(Op); 4616 MVT VecEltVT = Op.getSimpleValueType(); 4617 4618 unsigned RVVOpcode; 4619 SDValue VectorVal, ScalarVal; 4620 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4621 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4622 MVT VecVT = VectorVal.getSimpleValueType(); 4623 4624 MVT ContainerVT = VecVT; 4625 if (VecVT.isFixedLengthVector()) { 4626 ContainerVT = getContainerForFixedLengthVector(VecVT); 4627 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4628 } 4629 4630 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4631 MVT XLenVT = Subtarget.getXLenVT(); 4632 4633 SDValue Mask, VL; 4634 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4635 4636 SDValue ScalarSplat = lowerScalarSplat( 4637 ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4638 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4639 VectorVal, ScalarSplat, Mask, VL); 4640 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4641 DAG.getConstant(0, DL, XLenVT)); 4642 } 4643 4644 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4645 switch (ISDOpcode) { 4646 default: 4647 llvm_unreachable("Unhandled reduction"); 4648 case ISD::VP_REDUCE_ADD: 4649 return RISCVISD::VECREDUCE_ADD_VL; 4650 case ISD::VP_REDUCE_UMAX: 4651 return RISCVISD::VECREDUCE_UMAX_VL; 4652 case ISD::VP_REDUCE_SMAX: 4653 return RISCVISD::VECREDUCE_SMAX_VL; 4654 case ISD::VP_REDUCE_UMIN: 4655 return RISCVISD::VECREDUCE_UMIN_VL; 4656 case ISD::VP_REDUCE_SMIN: 4657 return RISCVISD::VECREDUCE_SMIN_VL; 4658 case ISD::VP_REDUCE_AND: 4659 return RISCVISD::VECREDUCE_AND_VL; 4660 case ISD::VP_REDUCE_OR: 4661 return RISCVISD::VECREDUCE_OR_VL; 4662 case ISD::VP_REDUCE_XOR: 4663 return RISCVISD::VECREDUCE_XOR_VL; 4664 case ISD::VP_REDUCE_FADD: 4665 return RISCVISD::VECREDUCE_FADD_VL; 4666 case ISD::VP_REDUCE_SEQ_FADD: 4667 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 4668 case ISD::VP_REDUCE_FMAX: 4669 return RISCVISD::VECREDUCE_FMAX_VL; 4670 case ISD::VP_REDUCE_FMIN: 4671 return RISCVISD::VECREDUCE_FMIN_VL; 4672 } 4673 } 4674 4675 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 4676 SelectionDAG &DAG) const { 4677 SDLoc DL(Op); 4678 SDValue Vec = Op.getOperand(1); 4679 EVT VecEVT = Vec.getValueType(); 4680 4681 // TODO: The type may need to be widened rather than split. Or widened before 4682 // it can be split. 4683 if (!isTypeLegal(VecEVT)) 4684 return SDValue(); 4685 4686 MVT VecVT = VecEVT.getSimpleVT(); 4687 MVT VecEltVT = VecVT.getVectorElementType(); 4688 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 4689 4690 MVT ContainerVT = VecVT; 4691 if (VecVT.isFixedLengthVector()) { 4692 ContainerVT = getContainerForFixedLengthVector(VecVT); 4693 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4694 } 4695 4696 SDValue VL = Op.getOperand(3); 4697 SDValue Mask = Op.getOperand(2); 4698 4699 MVT M1VT = getLMUL1VT(ContainerVT); 4700 MVT XLenVT = Subtarget.getXLenVT(); 4701 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 4702 4703 SDValue StartSplat = 4704 lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT, 4705 DL, DAG, Subtarget); 4706 SDValue Reduction = 4707 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 4708 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 4709 DAG.getConstant(0, DL, XLenVT)); 4710 if (!VecVT.isInteger()) 4711 return Elt0; 4712 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4713 } 4714 4715 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4716 SelectionDAG &DAG) const { 4717 SDValue Vec = Op.getOperand(0); 4718 SDValue SubVec = Op.getOperand(1); 4719 MVT VecVT = Vec.getSimpleValueType(); 4720 MVT SubVecVT = SubVec.getSimpleValueType(); 4721 4722 SDLoc DL(Op); 4723 MVT XLenVT = Subtarget.getXLenVT(); 4724 unsigned OrigIdx = Op.getConstantOperandVal(2); 4725 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4726 4727 // We don't have the ability to slide mask vectors up indexed by their i1 4728 // elements; the smallest we can do is i8. Often we are able to bitcast to 4729 // equivalent i8 vectors. Note that when inserting a fixed-length vector 4730 // into a scalable one, we might not necessarily have enough scalable 4731 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 4732 if (SubVecVT.getVectorElementType() == MVT::i1 && 4733 (OrigIdx != 0 || !Vec.isUndef())) { 4734 if (VecVT.getVectorMinNumElements() >= 8 && 4735 SubVecVT.getVectorMinNumElements() >= 8) { 4736 assert(OrigIdx % 8 == 0 && "Invalid index"); 4737 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4738 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4739 "Unexpected mask vector lowering"); 4740 OrigIdx /= 8; 4741 SubVecVT = 4742 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4743 SubVecVT.isScalableVector()); 4744 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4745 VecVT.isScalableVector()); 4746 Vec = DAG.getBitcast(VecVT, Vec); 4747 SubVec = DAG.getBitcast(SubVecVT, SubVec); 4748 } else { 4749 // We can't slide this mask vector up indexed by its i1 elements. 4750 // This poses a problem when we wish to insert a scalable vector which 4751 // can't be re-expressed as a larger type. Just choose the slow path and 4752 // extend to a larger type, then truncate back down. 4753 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4754 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4755 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4756 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 4757 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 4758 Op.getOperand(2)); 4759 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 4760 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 4761 } 4762 } 4763 4764 // If the subvector vector is a fixed-length type, we cannot use subregister 4765 // manipulation to simplify the codegen; we don't know which register of a 4766 // LMUL group contains the specific subvector as we only know the minimum 4767 // register size. Therefore we must slide the vector group up the full 4768 // amount. 4769 if (SubVecVT.isFixedLengthVector()) { 4770 if (OrigIdx == 0 && Vec.isUndef()) 4771 return Op; 4772 MVT ContainerVT = VecVT; 4773 if (VecVT.isFixedLengthVector()) { 4774 ContainerVT = getContainerForFixedLengthVector(VecVT); 4775 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4776 } 4777 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 4778 DAG.getUNDEF(ContainerVT), SubVec, 4779 DAG.getConstant(0, DL, XLenVT)); 4780 SDValue Mask = 4781 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4782 // Set the vector length to only the number of elements we care about. Note 4783 // that for slideup this includes the offset. 4784 SDValue VL = 4785 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 4786 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4787 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4788 SubVec, SlideupAmt, Mask, VL); 4789 if (VecVT.isFixedLengthVector()) 4790 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4791 return DAG.getBitcast(Op.getValueType(), Slideup); 4792 } 4793 4794 unsigned SubRegIdx, RemIdx; 4795 std::tie(SubRegIdx, RemIdx) = 4796 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4797 VecVT, SubVecVT, OrigIdx, TRI); 4798 4799 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 4800 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 4801 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 4802 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 4803 4804 // 1. If the Idx has been completely eliminated and this subvector's size is 4805 // a vector register or a multiple thereof, or the surrounding elements are 4806 // undef, then this is a subvector insert which naturally aligns to a vector 4807 // register. These can easily be handled using subregister manipulation. 4808 // 2. If the subvector is smaller than a vector register, then the insertion 4809 // must preserve the undisturbed elements of the register. We do this by 4810 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 4811 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 4812 // subvector within the vector register, and an INSERT_SUBVECTOR of that 4813 // LMUL=1 type back into the larger vector (resolving to another subregister 4814 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 4815 // to avoid allocating a large register group to hold our subvector. 4816 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 4817 return Op; 4818 4819 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 4820 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 4821 // (in our case undisturbed). This means we can set up a subvector insertion 4822 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 4823 // size of the subvector. 4824 MVT InterSubVT = VecVT; 4825 SDValue AlignedExtract = Vec; 4826 unsigned AlignedIdx = OrigIdx - RemIdx; 4827 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4828 InterSubVT = getLMUL1VT(VecVT); 4829 // Extract a subvector equal to the nearest full vector register type. This 4830 // should resolve to a EXTRACT_SUBREG instruction. 4831 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4832 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4833 } 4834 4835 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4836 // For scalable vectors this must be further multiplied by vscale. 4837 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 4838 4839 SDValue Mask, VL; 4840 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4841 4842 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 4843 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 4844 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 4845 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 4846 4847 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 4848 DAG.getUNDEF(InterSubVT), SubVec, 4849 DAG.getConstant(0, DL, XLenVT)); 4850 4851 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 4852 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 4853 4854 // If required, insert this subvector back into the correct vector register. 4855 // This should resolve to an INSERT_SUBREG instruction. 4856 if (VecVT.bitsGT(InterSubVT)) 4857 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 4858 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4859 4860 // We might have bitcast from a mask type: cast back to the original type if 4861 // required. 4862 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 4863 } 4864 4865 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 4866 SelectionDAG &DAG) const { 4867 SDValue Vec = Op.getOperand(0); 4868 MVT SubVecVT = Op.getSimpleValueType(); 4869 MVT VecVT = Vec.getSimpleValueType(); 4870 4871 SDLoc DL(Op); 4872 MVT XLenVT = Subtarget.getXLenVT(); 4873 unsigned OrigIdx = Op.getConstantOperandVal(1); 4874 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4875 4876 // We don't have the ability to slide mask vectors down indexed by their i1 4877 // elements; the smallest we can do is i8. Often we are able to bitcast to 4878 // equivalent i8 vectors. Note that when extracting a fixed-length vector 4879 // from a scalable one, we might not necessarily have enough scalable 4880 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 4881 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 4882 if (VecVT.getVectorMinNumElements() >= 8 && 4883 SubVecVT.getVectorMinNumElements() >= 8) { 4884 assert(OrigIdx % 8 == 0 && "Invalid index"); 4885 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4886 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4887 "Unexpected mask vector lowering"); 4888 OrigIdx /= 8; 4889 SubVecVT = 4890 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4891 SubVecVT.isScalableVector()); 4892 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4893 VecVT.isScalableVector()); 4894 Vec = DAG.getBitcast(VecVT, Vec); 4895 } else { 4896 // We can't slide this mask vector down, indexed by its i1 elements. 4897 // This poses a problem when we wish to extract a scalable vector which 4898 // can't be re-expressed as a larger type. Just choose the slow path and 4899 // extend to a larger type, then truncate back down. 4900 // TODO: We could probably improve this when extracting certain fixed 4901 // from fixed, where we can extract as i8 and shift the correct element 4902 // right to reach the desired subvector? 4903 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4904 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4905 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4906 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 4907 Op.getOperand(1)); 4908 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 4909 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 4910 } 4911 } 4912 4913 // If the subvector vector is a fixed-length type, we cannot use subregister 4914 // manipulation to simplify the codegen; we don't know which register of a 4915 // LMUL group contains the specific subvector as we only know the minimum 4916 // register size. Therefore we must slide the vector group down the full 4917 // amount. 4918 if (SubVecVT.isFixedLengthVector()) { 4919 // With an index of 0 this is a cast-like subvector, which can be performed 4920 // with subregister operations. 4921 if (OrigIdx == 0) 4922 return Op; 4923 MVT ContainerVT = VecVT; 4924 if (VecVT.isFixedLengthVector()) { 4925 ContainerVT = getContainerForFixedLengthVector(VecVT); 4926 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4927 } 4928 SDValue Mask = 4929 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4930 // Set the vector length to only the number of elements we care about. This 4931 // avoids sliding down elements we're going to discard straight away. 4932 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 4933 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4934 SDValue Slidedown = 4935 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4936 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 4937 // Now we can use a cast-like subvector extract to get the result. 4938 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4939 DAG.getConstant(0, DL, XLenVT)); 4940 return DAG.getBitcast(Op.getValueType(), Slidedown); 4941 } 4942 4943 unsigned SubRegIdx, RemIdx; 4944 std::tie(SubRegIdx, RemIdx) = 4945 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4946 VecVT, SubVecVT, OrigIdx, TRI); 4947 4948 // If the Idx has been completely eliminated then this is a subvector extract 4949 // which naturally aligns to a vector register. These can easily be handled 4950 // using subregister manipulation. 4951 if (RemIdx == 0) 4952 return Op; 4953 4954 // Else we must shift our vector register directly to extract the subvector. 4955 // Do this using VSLIDEDOWN. 4956 4957 // If the vector type is an LMUL-group type, extract a subvector equal to the 4958 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 4959 // instruction. 4960 MVT InterSubVT = VecVT; 4961 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4962 InterSubVT = getLMUL1VT(VecVT); 4963 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4964 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 4965 } 4966 4967 // Slide this vector register down by the desired number of elements in order 4968 // to place the desired subvector starting at element 0. 4969 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4970 // For scalable vectors this must be further multiplied by vscale. 4971 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 4972 4973 SDValue Mask, VL; 4974 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 4975 SDValue Slidedown = 4976 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 4977 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 4978 4979 // Now the vector is in the right position, extract our final subvector. This 4980 // should resolve to a COPY. 4981 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4982 DAG.getConstant(0, DL, XLenVT)); 4983 4984 // We might have bitcast from a mask type: cast back to the original type if 4985 // required. 4986 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 4987 } 4988 4989 // Lower step_vector to the vid instruction. Any non-identity step value must 4990 // be accounted for my manual expansion. 4991 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 4992 SelectionDAG &DAG) const { 4993 SDLoc DL(Op); 4994 MVT VT = Op.getSimpleValueType(); 4995 MVT XLenVT = Subtarget.getXLenVT(); 4996 SDValue Mask, VL; 4997 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 4998 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4999 uint64_t StepValImm = Op.getConstantOperandVal(0); 5000 if (StepValImm != 1) { 5001 if (isPowerOf2_64(StepValImm)) { 5002 SDValue StepVal = 5003 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 5004 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5005 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5006 } else { 5007 SDValue StepVal = lowerScalarSplat( 5008 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 5009 DL, DAG, Subtarget); 5010 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5011 } 5012 } 5013 return StepVec; 5014 } 5015 5016 // Implement vector_reverse using vrgather.vv with indices determined by 5017 // subtracting the id of each element from (VLMAX-1). This will convert 5018 // the indices like so: 5019 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5020 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5021 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5022 SelectionDAG &DAG) const { 5023 SDLoc DL(Op); 5024 MVT VecVT = Op.getSimpleValueType(); 5025 unsigned EltSize = VecVT.getScalarSizeInBits(); 5026 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5027 5028 unsigned MaxVLMAX = 0; 5029 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5030 if (VectorBitsMax != 0) 5031 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5032 5033 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5034 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5035 5036 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5037 // to use vrgatherei16.vv. 5038 // TODO: It's also possible to use vrgatherei16.vv for other types to 5039 // decrease register width for the index calculation. 5040 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5041 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5042 // Reverse each half, then reassemble them in reverse order. 5043 // NOTE: It's also possible that after splitting that VLMAX no longer 5044 // requires vrgatherei16.vv. 5045 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5046 SDValue Lo, Hi; 5047 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5048 EVT LoVT, HiVT; 5049 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5050 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5051 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5052 // Reassemble the low and high pieces reversed. 5053 // FIXME: This is a CONCAT_VECTORS. 5054 SDValue Res = 5055 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5056 DAG.getIntPtrConstant(0, DL)); 5057 return DAG.getNode( 5058 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5059 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5060 } 5061 5062 // Just promote the int type to i16 which will double the LMUL. 5063 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5064 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5065 } 5066 5067 MVT XLenVT = Subtarget.getXLenVT(); 5068 SDValue Mask, VL; 5069 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5070 5071 // Calculate VLMAX-1 for the desired SEW. 5072 unsigned MinElts = VecVT.getVectorMinNumElements(); 5073 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5074 DAG.getConstant(MinElts, DL, XLenVT)); 5075 SDValue VLMinus1 = 5076 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5077 5078 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5079 bool IsRV32E64 = 5080 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5081 SDValue SplatVL; 5082 if (!IsRV32E64) 5083 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5084 else 5085 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 5086 5087 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5088 SDValue Indices = 5089 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5090 5091 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5092 } 5093 5094 SDValue 5095 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5096 SelectionDAG &DAG) const { 5097 SDLoc DL(Op); 5098 auto *Load = cast<LoadSDNode>(Op); 5099 5100 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5101 Load->getMemoryVT(), 5102 *Load->getMemOperand()) && 5103 "Expecting a correctly-aligned load"); 5104 5105 MVT VT = Op.getSimpleValueType(); 5106 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5107 5108 SDValue VL = 5109 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5110 5111 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5112 SDValue NewLoad = DAG.getMemIntrinsicNode( 5113 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5114 Load->getMemoryVT(), Load->getMemOperand()); 5115 5116 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5117 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5118 } 5119 5120 SDValue 5121 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5122 SelectionDAG &DAG) const { 5123 SDLoc DL(Op); 5124 auto *Store = cast<StoreSDNode>(Op); 5125 5126 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5127 Store->getMemoryVT(), 5128 *Store->getMemOperand()) && 5129 "Expecting a correctly-aligned store"); 5130 5131 SDValue StoreVal = Store->getValue(); 5132 MVT VT = StoreVal.getSimpleValueType(); 5133 5134 // If the size less than a byte, we need to pad with zeros to make a byte. 5135 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5136 VT = MVT::v8i1; 5137 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5138 DAG.getConstant(0, DL, VT), StoreVal, 5139 DAG.getIntPtrConstant(0, DL)); 5140 } 5141 5142 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5143 5144 SDValue VL = 5145 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5146 5147 SDValue NewValue = 5148 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5149 return DAG.getMemIntrinsicNode( 5150 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5151 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5152 Store->getMemoryVT(), Store->getMemOperand()); 5153 } 5154 5155 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5156 SelectionDAG &DAG) const { 5157 SDLoc DL(Op); 5158 MVT VT = Op.getSimpleValueType(); 5159 5160 const auto *MemSD = cast<MemSDNode>(Op); 5161 EVT MemVT = MemSD->getMemoryVT(); 5162 MachineMemOperand *MMO = MemSD->getMemOperand(); 5163 SDValue Chain = MemSD->getChain(); 5164 SDValue BasePtr = MemSD->getBasePtr(); 5165 5166 SDValue Mask, PassThru, VL; 5167 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5168 Mask = VPLoad->getMask(); 5169 PassThru = DAG.getUNDEF(VT); 5170 VL = VPLoad->getVectorLength(); 5171 } else { 5172 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5173 Mask = MLoad->getMask(); 5174 PassThru = MLoad->getPassThru(); 5175 } 5176 5177 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5178 5179 MVT XLenVT = Subtarget.getXLenVT(); 5180 5181 MVT ContainerVT = VT; 5182 if (VT.isFixedLengthVector()) { 5183 ContainerVT = getContainerForFixedLengthVector(VT); 5184 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5185 if (!IsUnmasked) { 5186 MVT MaskVT = 5187 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5188 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5189 } 5190 } 5191 5192 if (!VL) 5193 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5194 5195 unsigned IntID = 5196 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5197 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5198 if (!IsUnmasked) 5199 Ops.push_back(PassThru); 5200 Ops.push_back(BasePtr); 5201 if (!IsUnmasked) 5202 Ops.push_back(Mask); 5203 Ops.push_back(VL); 5204 if (!IsUnmasked) 5205 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5206 5207 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5208 5209 SDValue Result = 5210 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5211 Chain = Result.getValue(1); 5212 5213 if (VT.isFixedLengthVector()) 5214 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5215 5216 return DAG.getMergeValues({Result, Chain}, DL); 5217 } 5218 5219 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5220 SelectionDAG &DAG) const { 5221 SDLoc DL(Op); 5222 5223 const auto *MemSD = cast<MemSDNode>(Op); 5224 EVT MemVT = MemSD->getMemoryVT(); 5225 MachineMemOperand *MMO = MemSD->getMemOperand(); 5226 SDValue Chain = MemSD->getChain(); 5227 SDValue BasePtr = MemSD->getBasePtr(); 5228 SDValue Val, Mask, VL; 5229 5230 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5231 Val = VPStore->getValue(); 5232 Mask = VPStore->getMask(); 5233 VL = VPStore->getVectorLength(); 5234 } else { 5235 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5236 Val = MStore->getValue(); 5237 Mask = MStore->getMask(); 5238 } 5239 5240 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5241 5242 MVT VT = Val.getSimpleValueType(); 5243 MVT XLenVT = Subtarget.getXLenVT(); 5244 5245 MVT ContainerVT = VT; 5246 if (VT.isFixedLengthVector()) { 5247 ContainerVT = getContainerForFixedLengthVector(VT); 5248 5249 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5250 if (!IsUnmasked) { 5251 MVT MaskVT = 5252 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5253 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5254 } 5255 } 5256 5257 if (!VL) 5258 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5259 5260 unsigned IntID = 5261 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5262 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5263 Ops.push_back(Val); 5264 Ops.push_back(BasePtr); 5265 if (!IsUnmasked) 5266 Ops.push_back(Mask); 5267 Ops.push_back(VL); 5268 5269 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5270 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5271 } 5272 5273 SDValue 5274 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5275 SelectionDAG &DAG) const { 5276 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5277 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5278 5279 MVT VT = Op.getSimpleValueType(); 5280 5281 SDValue Op1 = 5282 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5283 SDValue Op2 = 5284 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5285 5286 SDLoc DL(Op); 5287 SDValue VL = 5288 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5289 5290 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5291 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5292 5293 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5294 Op.getOperand(2), Mask, VL); 5295 5296 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5297 } 5298 5299 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5300 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5301 MVT VT = Op.getSimpleValueType(); 5302 5303 if (VT.getVectorElementType() == MVT::i1) 5304 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5305 5306 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5307 } 5308 5309 SDValue 5310 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5311 SelectionDAG &DAG) const { 5312 unsigned Opc; 5313 switch (Op.getOpcode()) { 5314 default: llvm_unreachable("Unexpected opcode!"); 5315 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5316 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5317 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5318 } 5319 5320 return lowerToScalableOp(Op, DAG, Opc); 5321 } 5322 5323 // Lower vector ABS to smax(X, sub(0, X)). 5324 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5325 SDLoc DL(Op); 5326 MVT VT = Op.getSimpleValueType(); 5327 SDValue X = Op.getOperand(0); 5328 5329 assert(VT.isFixedLengthVector() && "Unexpected type"); 5330 5331 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5332 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5333 5334 SDValue Mask, VL; 5335 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5336 5337 SDValue SplatZero = 5338 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5339 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5340 SDValue NegX = 5341 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5342 SDValue Max = 5343 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5344 5345 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5346 } 5347 5348 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5349 SDValue Op, SelectionDAG &DAG) const { 5350 SDLoc DL(Op); 5351 MVT VT = Op.getSimpleValueType(); 5352 SDValue Mag = Op.getOperand(0); 5353 SDValue Sign = Op.getOperand(1); 5354 assert(Mag.getValueType() == Sign.getValueType() && 5355 "Can only handle COPYSIGN with matching types."); 5356 5357 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5358 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5359 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5360 5361 SDValue Mask, VL; 5362 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5363 5364 SDValue CopySign = 5365 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5366 5367 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5368 } 5369 5370 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5371 SDValue Op, SelectionDAG &DAG) const { 5372 MVT VT = Op.getSimpleValueType(); 5373 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5374 5375 MVT I1ContainerVT = 5376 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5377 5378 SDValue CC = 5379 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5380 SDValue Op1 = 5381 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5382 SDValue Op2 = 5383 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5384 5385 SDLoc DL(Op); 5386 SDValue Mask, VL; 5387 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5388 5389 SDValue Select = 5390 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5391 5392 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5393 } 5394 5395 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5396 unsigned NewOpc, 5397 bool HasMask) const { 5398 MVT VT = Op.getSimpleValueType(); 5399 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5400 5401 // Create list of operands by converting existing ones to scalable types. 5402 SmallVector<SDValue, 6> Ops; 5403 for (const SDValue &V : Op->op_values()) { 5404 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5405 5406 // Pass through non-vector operands. 5407 if (!V.getValueType().isVector()) { 5408 Ops.push_back(V); 5409 continue; 5410 } 5411 5412 // "cast" fixed length vector to a scalable vector. 5413 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5414 "Only fixed length vectors are supported!"); 5415 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5416 } 5417 5418 SDLoc DL(Op); 5419 SDValue Mask, VL; 5420 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5421 if (HasMask) 5422 Ops.push_back(Mask); 5423 Ops.push_back(VL); 5424 5425 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5426 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5427 } 5428 5429 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5430 // * Operands of each node are assumed to be in the same order. 5431 // * The EVL operand is promoted from i32 to i64 on RV64. 5432 // * Fixed-length vectors are converted to their scalable-vector container 5433 // types. 5434 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5435 unsigned RISCVISDOpc) const { 5436 SDLoc DL(Op); 5437 MVT VT = Op.getSimpleValueType(); 5438 SmallVector<SDValue, 4> Ops; 5439 5440 for (const auto &OpIdx : enumerate(Op->ops())) { 5441 SDValue V = OpIdx.value(); 5442 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5443 // Pass through operands which aren't fixed-length vectors. 5444 if (!V.getValueType().isFixedLengthVector()) { 5445 Ops.push_back(V); 5446 continue; 5447 } 5448 // "cast" fixed length vector to a scalable vector. 5449 MVT OpVT = V.getSimpleValueType(); 5450 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5451 assert(useRVVForFixedLengthVectorVT(OpVT) && 5452 "Only fixed length vectors are supported!"); 5453 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5454 } 5455 5456 if (!VT.isFixedLengthVector()) 5457 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5458 5459 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5460 5461 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5462 5463 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5464 } 5465 5466 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 5467 unsigned MaskOpc, 5468 unsigned VecOpc) const { 5469 MVT VT = Op.getSimpleValueType(); 5470 if (VT.getVectorElementType() != MVT::i1) 5471 return lowerVPOp(Op, DAG, VecOpc); 5472 5473 // It is safe to drop mask parameter as masked-off elements are undef. 5474 SDValue Op1 = Op->getOperand(0); 5475 SDValue Op2 = Op->getOperand(1); 5476 SDValue VL = Op->getOperand(3); 5477 5478 MVT ContainerVT = VT; 5479 const bool IsFixed = VT.isFixedLengthVector(); 5480 if (IsFixed) { 5481 ContainerVT = getContainerForFixedLengthVector(VT); 5482 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 5483 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 5484 } 5485 5486 SDLoc DL(Op); 5487 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 5488 if (!IsFixed) 5489 return Val; 5490 return convertFromScalableVector(VT, Val, DAG, Subtarget); 5491 } 5492 5493 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5494 // matched to a RVV indexed load. The RVV indexed load instructions only 5495 // support the "unsigned unscaled" addressing mode; indices are implicitly 5496 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5497 // signed or scaled indexing is extended to the XLEN value type and scaled 5498 // accordingly. 5499 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5500 SelectionDAG &DAG) const { 5501 SDLoc DL(Op); 5502 MVT VT = Op.getSimpleValueType(); 5503 5504 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5505 EVT MemVT = MemSD->getMemoryVT(); 5506 MachineMemOperand *MMO = MemSD->getMemOperand(); 5507 SDValue Chain = MemSD->getChain(); 5508 SDValue BasePtr = MemSD->getBasePtr(); 5509 5510 ISD::LoadExtType LoadExtType; 5511 SDValue Index, Mask, PassThru, VL; 5512 5513 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5514 Index = VPGN->getIndex(); 5515 Mask = VPGN->getMask(); 5516 PassThru = DAG.getUNDEF(VT); 5517 VL = VPGN->getVectorLength(); 5518 // VP doesn't support extending loads. 5519 LoadExtType = ISD::NON_EXTLOAD; 5520 } else { 5521 // Else it must be a MGATHER. 5522 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5523 Index = MGN->getIndex(); 5524 Mask = MGN->getMask(); 5525 PassThru = MGN->getPassThru(); 5526 LoadExtType = MGN->getExtensionType(); 5527 } 5528 5529 MVT IndexVT = Index.getSimpleValueType(); 5530 MVT XLenVT = Subtarget.getXLenVT(); 5531 5532 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5533 "Unexpected VTs!"); 5534 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5535 // Targets have to explicitly opt-in for extending vector loads. 5536 assert(LoadExtType == ISD::NON_EXTLOAD && 5537 "Unexpected extending MGATHER/VP_GATHER"); 5538 (void)LoadExtType; 5539 5540 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5541 // the selection of the masked intrinsics doesn't do this for us. 5542 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5543 5544 MVT ContainerVT = VT; 5545 if (VT.isFixedLengthVector()) { 5546 // We need to use the larger of the result and index type to determine the 5547 // scalable type to use so we don't increase LMUL for any operand/result. 5548 if (VT.bitsGE(IndexVT)) { 5549 ContainerVT = getContainerForFixedLengthVector(VT); 5550 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5551 ContainerVT.getVectorElementCount()); 5552 } else { 5553 IndexVT = getContainerForFixedLengthVector(IndexVT); 5554 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5555 IndexVT.getVectorElementCount()); 5556 } 5557 5558 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5559 5560 if (!IsUnmasked) { 5561 MVT MaskVT = 5562 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5563 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5564 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5565 } 5566 } 5567 5568 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 5569 IndexVT = IndexVT.changeVectorElementType(XLenVT); 5570 Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index); 5571 } 5572 5573 if (!VL) 5574 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5575 5576 unsigned IntID = 5577 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5578 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5579 if (!IsUnmasked) 5580 Ops.push_back(PassThru); 5581 Ops.push_back(BasePtr); 5582 Ops.push_back(Index); 5583 if (!IsUnmasked) 5584 Ops.push_back(Mask); 5585 Ops.push_back(VL); 5586 if (!IsUnmasked) 5587 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5588 5589 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5590 SDValue Result = 5591 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5592 Chain = Result.getValue(1); 5593 5594 if (VT.isFixedLengthVector()) 5595 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5596 5597 return DAG.getMergeValues({Result, Chain}, DL); 5598 } 5599 5600 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5601 // matched to a RVV indexed store. The RVV indexed store instructions only 5602 // support the "unsigned unscaled" addressing mode; indices are implicitly 5603 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5604 // signed or scaled indexing is extended to the XLEN value type and scaled 5605 // accordingly. 5606 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5607 SelectionDAG &DAG) const { 5608 SDLoc DL(Op); 5609 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5610 EVT MemVT = MemSD->getMemoryVT(); 5611 MachineMemOperand *MMO = MemSD->getMemOperand(); 5612 SDValue Chain = MemSD->getChain(); 5613 SDValue BasePtr = MemSD->getBasePtr(); 5614 5615 bool IsTruncatingStore = false; 5616 SDValue Index, Mask, Val, VL; 5617 5618 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5619 Index = VPSN->getIndex(); 5620 Mask = VPSN->getMask(); 5621 Val = VPSN->getValue(); 5622 VL = VPSN->getVectorLength(); 5623 // VP doesn't support truncating stores. 5624 IsTruncatingStore = false; 5625 } else { 5626 // Else it must be a MSCATTER. 5627 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5628 Index = MSN->getIndex(); 5629 Mask = MSN->getMask(); 5630 Val = MSN->getValue(); 5631 IsTruncatingStore = MSN->isTruncatingStore(); 5632 } 5633 5634 MVT VT = Val.getSimpleValueType(); 5635 MVT IndexVT = Index.getSimpleValueType(); 5636 MVT XLenVT = Subtarget.getXLenVT(); 5637 5638 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5639 "Unexpected VTs!"); 5640 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5641 // Targets have to explicitly opt-in for extending vector loads and 5642 // truncating vector stores. 5643 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5644 (void)IsTruncatingStore; 5645 5646 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5647 // the selection of the masked intrinsics doesn't do this for us. 5648 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5649 5650 MVT ContainerVT = VT; 5651 if (VT.isFixedLengthVector()) { 5652 // We need to use the larger of the value and index type to determine the 5653 // scalable type to use so we don't increase LMUL for any operand/result. 5654 if (VT.bitsGE(IndexVT)) { 5655 ContainerVT = getContainerForFixedLengthVector(VT); 5656 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5657 ContainerVT.getVectorElementCount()); 5658 } else { 5659 IndexVT = getContainerForFixedLengthVector(IndexVT); 5660 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 5661 IndexVT.getVectorElementCount()); 5662 } 5663 5664 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5665 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5666 5667 if (!IsUnmasked) { 5668 MVT MaskVT = 5669 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5670 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5671 } 5672 } 5673 5674 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 5675 IndexVT = IndexVT.changeVectorElementType(XLenVT); 5676 Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index); 5677 } 5678 5679 if (!VL) 5680 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5681 5682 unsigned IntID = 5683 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 5684 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5685 Ops.push_back(Val); 5686 Ops.push_back(BasePtr); 5687 Ops.push_back(Index); 5688 if (!IsUnmasked) 5689 Ops.push_back(Mask); 5690 Ops.push_back(VL); 5691 5692 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5693 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5694 } 5695 5696 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 5697 SelectionDAG &DAG) const { 5698 const MVT XLenVT = Subtarget.getXLenVT(); 5699 SDLoc DL(Op); 5700 SDValue Chain = Op->getOperand(0); 5701 SDValue SysRegNo = DAG.getTargetConstant( 5702 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5703 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 5704 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 5705 5706 // Encoding used for rounding mode in RISCV differs from that used in 5707 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 5708 // table, which consists of a sequence of 4-bit fields, each representing 5709 // corresponding FLT_ROUNDS mode. 5710 static const int Table = 5711 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 5712 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 5713 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 5714 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 5715 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 5716 5717 SDValue Shift = 5718 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 5719 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5720 DAG.getConstant(Table, DL, XLenVT), Shift); 5721 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5722 DAG.getConstant(7, DL, XLenVT)); 5723 5724 return DAG.getMergeValues({Masked, Chain}, DL); 5725 } 5726 5727 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 5728 SelectionDAG &DAG) const { 5729 const MVT XLenVT = Subtarget.getXLenVT(); 5730 SDLoc DL(Op); 5731 SDValue Chain = Op->getOperand(0); 5732 SDValue RMValue = Op->getOperand(1); 5733 SDValue SysRegNo = DAG.getTargetConstant( 5734 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5735 5736 // Encoding used for rounding mode in RISCV differs from that used in 5737 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 5738 // a table, which consists of a sequence of 4-bit fields, each representing 5739 // corresponding RISCV mode. 5740 static const unsigned Table = 5741 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 5742 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 5743 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 5744 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 5745 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 5746 5747 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 5748 DAG.getConstant(2, DL, XLenVT)); 5749 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5750 DAG.getConstant(Table, DL, XLenVT), Shift); 5751 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5752 DAG.getConstant(0x7, DL, XLenVT)); 5753 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 5754 RMValue); 5755 } 5756 5757 // Returns the opcode of the target-specific SDNode that implements the 32-bit 5758 // form of the given Opcode. 5759 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 5760 switch (Opcode) { 5761 default: 5762 llvm_unreachable("Unexpected opcode"); 5763 case ISD::SHL: 5764 return RISCVISD::SLLW; 5765 case ISD::SRA: 5766 return RISCVISD::SRAW; 5767 case ISD::SRL: 5768 return RISCVISD::SRLW; 5769 case ISD::SDIV: 5770 return RISCVISD::DIVW; 5771 case ISD::UDIV: 5772 return RISCVISD::DIVUW; 5773 case ISD::UREM: 5774 return RISCVISD::REMUW; 5775 case ISD::ROTL: 5776 return RISCVISD::ROLW; 5777 case ISD::ROTR: 5778 return RISCVISD::RORW; 5779 case RISCVISD::GREV: 5780 return RISCVISD::GREVW; 5781 case RISCVISD::GORC: 5782 return RISCVISD::GORCW; 5783 } 5784 } 5785 5786 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 5787 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 5788 // otherwise be promoted to i64, making it difficult to select the 5789 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 5790 // type i8/i16/i32 is lost. 5791 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 5792 unsigned ExtOpc = ISD::ANY_EXTEND) { 5793 SDLoc DL(N); 5794 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5795 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 5796 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 5797 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5798 // ReplaceNodeResults requires we maintain the same type for the return value. 5799 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 5800 } 5801 5802 // Converts the given 32-bit operation to a i64 operation with signed extension 5803 // semantic to reduce the signed extension instructions. 5804 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 5805 SDLoc DL(N); 5806 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5807 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5808 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 5809 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5810 DAG.getValueType(MVT::i32)); 5811 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 5812 } 5813 5814 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 5815 SmallVectorImpl<SDValue> &Results, 5816 SelectionDAG &DAG) const { 5817 SDLoc DL(N); 5818 switch (N->getOpcode()) { 5819 default: 5820 llvm_unreachable("Don't know how to custom type legalize this operation!"); 5821 case ISD::STRICT_FP_TO_SINT: 5822 case ISD::STRICT_FP_TO_UINT: 5823 case ISD::FP_TO_SINT: 5824 case ISD::FP_TO_UINT: { 5825 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5826 "Unexpected custom legalisation"); 5827 bool IsStrict = N->isStrictFPOpcode(); 5828 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 5829 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 5830 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 5831 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 5832 TargetLowering::TypeSoftenFloat) { 5833 if (!isTypeLegal(Op0.getValueType())) 5834 return; 5835 if (IsStrict) { 5836 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 5837 : RISCVISD::STRICT_FCVT_WU_RV64; 5838 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 5839 SDValue Res = DAG.getNode( 5840 Opc, DL, VTs, N->getOperand(0), Op0, 5841 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 5842 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5843 Results.push_back(Res.getValue(1)); 5844 return; 5845 } 5846 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 5847 SDValue Res = 5848 DAG.getNode(Opc, DL, MVT::i64, Op0, 5849 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 5850 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5851 return; 5852 } 5853 // If the FP type needs to be softened, emit a library call using the 'si' 5854 // version. If we left it to default legalization we'd end up with 'di'. If 5855 // the FP type doesn't need to be softened just let generic type 5856 // legalization promote the result type. 5857 RTLIB::Libcall LC; 5858 if (IsSigned) 5859 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 5860 else 5861 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 5862 MakeLibCallOptions CallOptions; 5863 EVT OpVT = Op0.getValueType(); 5864 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 5865 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 5866 SDValue Result; 5867 std::tie(Result, Chain) = 5868 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 5869 Results.push_back(Result); 5870 if (IsStrict) 5871 Results.push_back(Chain); 5872 break; 5873 } 5874 case ISD::READCYCLECOUNTER: { 5875 assert(!Subtarget.is64Bit() && 5876 "READCYCLECOUNTER only has custom type legalization on riscv32"); 5877 5878 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 5879 SDValue RCW = 5880 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 5881 5882 Results.push_back( 5883 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 5884 Results.push_back(RCW.getValue(2)); 5885 break; 5886 } 5887 case ISD::MUL: { 5888 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 5889 unsigned XLen = Subtarget.getXLen(); 5890 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 5891 if (Size > XLen) { 5892 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 5893 SDValue LHS = N->getOperand(0); 5894 SDValue RHS = N->getOperand(1); 5895 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 5896 5897 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 5898 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 5899 // We need exactly one side to be unsigned. 5900 if (LHSIsU == RHSIsU) 5901 return; 5902 5903 auto MakeMULPair = [&](SDValue S, SDValue U) { 5904 MVT XLenVT = Subtarget.getXLenVT(); 5905 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 5906 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 5907 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 5908 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 5909 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 5910 }; 5911 5912 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 5913 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 5914 5915 // The other operand should be signed, but still prefer MULH when 5916 // possible. 5917 if (RHSIsU && LHSIsS && !RHSIsS) 5918 Results.push_back(MakeMULPair(LHS, RHS)); 5919 else if (LHSIsU && RHSIsS && !LHSIsS) 5920 Results.push_back(MakeMULPair(RHS, LHS)); 5921 5922 return; 5923 } 5924 LLVM_FALLTHROUGH; 5925 } 5926 case ISD::ADD: 5927 case ISD::SUB: 5928 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5929 "Unexpected custom legalisation"); 5930 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 5931 break; 5932 case ISD::SHL: 5933 case ISD::SRA: 5934 case ISD::SRL: 5935 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5936 "Unexpected custom legalisation"); 5937 if (N->getOperand(1).getOpcode() != ISD::Constant) { 5938 Results.push_back(customLegalizeToWOp(N, DAG)); 5939 break; 5940 } 5941 5942 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 5943 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 5944 // shift amount. 5945 if (N->getOpcode() == ISD::SHL) { 5946 SDLoc DL(N); 5947 SDValue NewOp0 = 5948 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5949 SDValue NewOp1 = 5950 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 5951 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 5952 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5953 DAG.getValueType(MVT::i32)); 5954 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5955 } 5956 5957 break; 5958 case ISD::ROTL: 5959 case ISD::ROTR: 5960 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5961 "Unexpected custom legalisation"); 5962 Results.push_back(customLegalizeToWOp(N, DAG)); 5963 break; 5964 case ISD::CTTZ: 5965 case ISD::CTTZ_ZERO_UNDEF: 5966 case ISD::CTLZ: 5967 case ISD::CTLZ_ZERO_UNDEF: { 5968 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5969 "Unexpected custom legalisation"); 5970 5971 SDValue NewOp0 = 5972 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5973 bool IsCTZ = 5974 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 5975 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 5976 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 5977 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5978 return; 5979 } 5980 case ISD::SDIV: 5981 case ISD::UDIV: 5982 case ISD::UREM: { 5983 MVT VT = N->getSimpleValueType(0); 5984 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 5985 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 5986 "Unexpected custom legalisation"); 5987 // Don't promote division/remainder by constant since we should expand those 5988 // to multiply by magic constant. 5989 // FIXME: What if the expansion is disabled for minsize. 5990 if (N->getOperand(1).getOpcode() == ISD::Constant) 5991 return; 5992 5993 // If the input is i32, use ANY_EXTEND since the W instructions don't read 5994 // the upper 32 bits. For other types we need to sign or zero extend 5995 // based on the opcode. 5996 unsigned ExtOpc = ISD::ANY_EXTEND; 5997 if (VT != MVT::i32) 5998 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 5999 : ISD::ZERO_EXTEND; 6000 6001 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6002 break; 6003 } 6004 case ISD::UADDO: 6005 case ISD::USUBO: { 6006 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6007 "Unexpected custom legalisation"); 6008 bool IsAdd = N->getOpcode() == ISD::UADDO; 6009 // Create an ADDW or SUBW. 6010 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6011 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6012 SDValue Res = 6013 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6014 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6015 DAG.getValueType(MVT::i32)); 6016 6017 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6018 // Since the inputs are sign extended from i32, this is equivalent to 6019 // comparing the lower 32 bits. 6020 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6021 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6022 IsAdd ? ISD::SETULT : ISD::SETUGT); 6023 6024 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6025 Results.push_back(Overflow); 6026 return; 6027 } 6028 case ISD::UADDSAT: 6029 case ISD::USUBSAT: { 6030 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6031 "Unexpected custom legalisation"); 6032 if (Subtarget.hasStdExtZbb()) { 6033 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6034 // sign extend allows overflow of the lower 32 bits to be detected on 6035 // the promoted size. 6036 SDValue LHS = 6037 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6038 SDValue RHS = 6039 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6040 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6041 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6042 return; 6043 } 6044 6045 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6046 // promotion for UADDO/USUBO. 6047 Results.push_back(expandAddSubSat(N, DAG)); 6048 return; 6049 } 6050 case ISD::BITCAST: { 6051 EVT VT = N->getValueType(0); 6052 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6053 SDValue Op0 = N->getOperand(0); 6054 EVT Op0VT = Op0.getValueType(); 6055 MVT XLenVT = Subtarget.getXLenVT(); 6056 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6057 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6058 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6059 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6060 Subtarget.hasStdExtF()) { 6061 SDValue FPConv = 6062 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6063 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6064 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6065 isTypeLegal(Op0VT)) { 6066 // Custom-legalize bitcasts from fixed-length vector types to illegal 6067 // scalar types in order to improve codegen. Bitcast the vector to a 6068 // one-element vector type whose element type is the same as the result 6069 // type, and extract the first element. 6070 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6071 if (isTypeLegal(BVT)) { 6072 SDValue BVec = DAG.getBitcast(BVT, Op0); 6073 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6074 DAG.getConstant(0, DL, XLenVT))); 6075 } 6076 } 6077 break; 6078 } 6079 case RISCVISD::GREV: 6080 case RISCVISD::GORC: { 6081 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6082 "Unexpected custom legalisation"); 6083 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6084 // This is similar to customLegalizeToWOp, except that we pass the second 6085 // operand (a TargetConstant) straight through: it is already of type 6086 // XLenVT. 6087 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6088 SDValue NewOp0 = 6089 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6090 SDValue NewOp1 = 6091 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6092 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6093 // ReplaceNodeResults requires we maintain the same type for the return 6094 // value. 6095 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6096 break; 6097 } 6098 case RISCVISD::SHFL: { 6099 // There is no SHFLIW instruction, but we can just promote the operation. 6100 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6101 "Unexpected custom legalisation"); 6102 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6103 SDValue NewOp0 = 6104 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6105 SDValue NewOp1 = 6106 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6107 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6108 // ReplaceNodeResults requires we maintain the same type for the return 6109 // value. 6110 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6111 break; 6112 } 6113 case ISD::BSWAP: 6114 case ISD::BITREVERSE: { 6115 MVT VT = N->getSimpleValueType(0); 6116 MVT XLenVT = Subtarget.getXLenVT(); 6117 assert((VT == MVT::i8 || VT == MVT::i16 || 6118 (VT == MVT::i32 && Subtarget.is64Bit())) && 6119 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6120 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6121 unsigned Imm = VT.getSizeInBits() - 1; 6122 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6123 if (N->getOpcode() == ISD::BSWAP) 6124 Imm &= ~0x7U; 6125 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6126 SDValue GREVI = 6127 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6128 // ReplaceNodeResults requires we maintain the same type for the return 6129 // value. 6130 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6131 break; 6132 } 6133 case ISD::FSHL: 6134 case ISD::FSHR: { 6135 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6136 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6137 SDValue NewOp0 = 6138 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6139 SDValue NewOp1 = 6140 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6141 SDValue NewOp2 = 6142 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6143 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6144 // Mask the shift amount to 5 bits. 6145 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6146 DAG.getConstant(0x1f, DL, MVT::i64)); 6147 unsigned Opc = 6148 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 6149 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 6150 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6151 break; 6152 } 6153 case ISD::EXTRACT_VECTOR_ELT: { 6154 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6155 // type is illegal (currently only vXi64 RV32). 6156 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6157 // transferred to the destination register. We issue two of these from the 6158 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6159 // first element. 6160 SDValue Vec = N->getOperand(0); 6161 SDValue Idx = N->getOperand(1); 6162 6163 // The vector type hasn't been legalized yet so we can't issue target 6164 // specific nodes if it needs legalization. 6165 // FIXME: We would manually legalize if it's important. 6166 if (!isTypeLegal(Vec.getValueType())) 6167 return; 6168 6169 MVT VecVT = Vec.getSimpleValueType(); 6170 6171 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6172 VecVT.getVectorElementType() == MVT::i64 && 6173 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6174 6175 // If this is a fixed vector, we need to convert it to a scalable vector. 6176 MVT ContainerVT = VecVT; 6177 if (VecVT.isFixedLengthVector()) { 6178 ContainerVT = getContainerForFixedLengthVector(VecVT); 6179 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6180 } 6181 6182 MVT XLenVT = Subtarget.getXLenVT(); 6183 6184 // Use a VL of 1 to avoid processing more elements than we need. 6185 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6186 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6187 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6188 6189 // Unless the index is known to be 0, we must slide the vector down to get 6190 // the desired element into index 0. 6191 if (!isNullConstant(Idx)) { 6192 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6193 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6194 } 6195 6196 // Extract the lower XLEN bits of the correct vector element. 6197 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6198 6199 // To extract the upper XLEN bits of the vector element, shift the first 6200 // element right by 32 bits and re-extract the lower XLEN bits. 6201 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6202 DAG.getConstant(32, DL, XLenVT), VL); 6203 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6204 ThirtyTwoV, Mask, VL); 6205 6206 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6207 6208 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6209 break; 6210 } 6211 case ISD::INTRINSIC_WO_CHAIN: { 6212 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6213 switch (IntNo) { 6214 default: 6215 llvm_unreachable( 6216 "Don't know how to custom type legalize this intrinsic!"); 6217 case Intrinsic::riscv_orc_b: { 6218 // Lower to the GORCI encoding for orc.b with the operand extended. 6219 SDValue NewOp = 6220 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6221 // If Zbp is enabled, use GORCIW which will sign extend the result. 6222 unsigned Opc = 6223 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6224 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6225 DAG.getConstant(7, DL, MVT::i64)); 6226 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6227 return; 6228 } 6229 case Intrinsic::riscv_grev: 6230 case Intrinsic::riscv_gorc: { 6231 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6232 "Unexpected custom legalisation"); 6233 SDValue NewOp1 = 6234 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6235 SDValue NewOp2 = 6236 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6237 unsigned Opc = 6238 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 6239 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6240 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6241 break; 6242 } 6243 case Intrinsic::riscv_shfl: 6244 case Intrinsic::riscv_unshfl: { 6245 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6246 "Unexpected custom legalisation"); 6247 SDValue NewOp1 = 6248 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6249 SDValue NewOp2 = 6250 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6251 unsigned Opc = 6252 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6253 if (isa<ConstantSDNode>(N->getOperand(2))) { 6254 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6255 DAG.getConstant(0xf, DL, MVT::i64)); 6256 Opc = 6257 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6258 } 6259 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6260 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6261 break; 6262 } 6263 case Intrinsic::riscv_bcompress: 6264 case Intrinsic::riscv_bdecompress: { 6265 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6266 "Unexpected custom legalisation"); 6267 SDValue NewOp1 = 6268 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6269 SDValue NewOp2 = 6270 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6271 unsigned Opc = IntNo == Intrinsic::riscv_bcompress 6272 ? RISCVISD::BCOMPRESSW 6273 : RISCVISD::BDECOMPRESSW; 6274 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6275 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6276 break; 6277 } 6278 case Intrinsic::riscv_vmv_x_s: { 6279 EVT VT = N->getValueType(0); 6280 MVT XLenVT = Subtarget.getXLenVT(); 6281 if (VT.bitsLT(XLenVT)) { 6282 // Simple case just extract using vmv.x.s and truncate. 6283 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6284 Subtarget.getXLenVT(), N->getOperand(1)); 6285 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6286 return; 6287 } 6288 6289 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6290 "Unexpected custom legalization"); 6291 6292 // We need to do the move in two steps. 6293 SDValue Vec = N->getOperand(1); 6294 MVT VecVT = Vec.getSimpleValueType(); 6295 6296 // First extract the lower XLEN bits of the element. 6297 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6298 6299 // To extract the upper XLEN bits of the vector element, shift the first 6300 // element right by 32 bits and re-extract the lower XLEN bits. 6301 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6302 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6303 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6304 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 6305 DAG.getConstant(32, DL, XLenVT), VL); 6306 SDValue LShr32 = 6307 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6308 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6309 6310 Results.push_back( 6311 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6312 break; 6313 } 6314 } 6315 break; 6316 } 6317 case ISD::VECREDUCE_ADD: 6318 case ISD::VECREDUCE_AND: 6319 case ISD::VECREDUCE_OR: 6320 case ISD::VECREDUCE_XOR: 6321 case ISD::VECREDUCE_SMAX: 6322 case ISD::VECREDUCE_UMAX: 6323 case ISD::VECREDUCE_SMIN: 6324 case ISD::VECREDUCE_UMIN: 6325 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6326 Results.push_back(V); 6327 break; 6328 case ISD::VP_REDUCE_ADD: 6329 case ISD::VP_REDUCE_AND: 6330 case ISD::VP_REDUCE_OR: 6331 case ISD::VP_REDUCE_XOR: 6332 case ISD::VP_REDUCE_SMAX: 6333 case ISD::VP_REDUCE_UMAX: 6334 case ISD::VP_REDUCE_SMIN: 6335 case ISD::VP_REDUCE_UMIN: 6336 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6337 Results.push_back(V); 6338 break; 6339 case ISD::FLT_ROUNDS_: { 6340 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6341 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6342 Results.push_back(Res.getValue(0)); 6343 Results.push_back(Res.getValue(1)); 6344 break; 6345 } 6346 } 6347 } 6348 6349 // A structure to hold one of the bit-manipulation patterns below. Together, a 6350 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6351 // (or (and (shl x, 1), 0xAAAAAAAA), 6352 // (and (srl x, 1), 0x55555555)) 6353 struct RISCVBitmanipPat { 6354 SDValue Op; 6355 unsigned ShAmt; 6356 bool IsSHL; 6357 6358 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6359 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6360 } 6361 }; 6362 6363 // Matches patterns of the form 6364 // (and (shl x, C2), (C1 << C2)) 6365 // (and (srl x, C2), C1) 6366 // (shl (and x, C1), C2) 6367 // (srl (and x, (C1 << C2)), C2) 6368 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6369 // The expected masks for each shift amount are specified in BitmanipMasks where 6370 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6371 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6372 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6373 // XLen is 64. 6374 static Optional<RISCVBitmanipPat> 6375 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6376 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6377 "Unexpected number of masks"); 6378 Optional<uint64_t> Mask; 6379 // Optionally consume a mask around the shift operation. 6380 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6381 Mask = Op.getConstantOperandVal(1); 6382 Op = Op.getOperand(0); 6383 } 6384 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6385 return None; 6386 bool IsSHL = Op.getOpcode() == ISD::SHL; 6387 6388 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6389 return None; 6390 uint64_t ShAmt = Op.getConstantOperandVal(1); 6391 6392 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6393 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6394 return None; 6395 // If we don't have enough masks for 64 bit, then we must be trying to 6396 // match SHFL so we're only allowed to shift 1/4 of the width. 6397 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6398 return None; 6399 6400 SDValue Src = Op.getOperand(0); 6401 6402 // The expected mask is shifted left when the AND is found around SHL 6403 // patterns. 6404 // ((x >> 1) & 0x55555555) 6405 // ((x << 1) & 0xAAAAAAAA) 6406 bool SHLExpMask = IsSHL; 6407 6408 if (!Mask) { 6409 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6410 // the mask is all ones: consume that now. 6411 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6412 Mask = Src.getConstantOperandVal(1); 6413 Src = Src.getOperand(0); 6414 // The expected mask is now in fact shifted left for SRL, so reverse the 6415 // decision. 6416 // ((x & 0xAAAAAAAA) >> 1) 6417 // ((x & 0x55555555) << 1) 6418 SHLExpMask = !SHLExpMask; 6419 } else { 6420 // Use a default shifted mask of all-ones if there's no AND, truncated 6421 // down to the expected width. This simplifies the logic later on. 6422 Mask = maskTrailingOnes<uint64_t>(Width); 6423 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6424 } 6425 } 6426 6427 unsigned MaskIdx = Log2_32(ShAmt); 6428 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6429 6430 if (SHLExpMask) 6431 ExpMask <<= ShAmt; 6432 6433 if (Mask != ExpMask) 6434 return None; 6435 6436 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6437 } 6438 6439 // Matches any of the following bit-manipulation patterns: 6440 // (and (shl x, 1), (0x55555555 << 1)) 6441 // (and (srl x, 1), 0x55555555) 6442 // (shl (and x, 0x55555555), 1) 6443 // (srl (and x, (0x55555555 << 1)), 1) 6444 // where the shift amount and mask may vary thus: 6445 // [1] = 0x55555555 / 0xAAAAAAAA 6446 // [2] = 0x33333333 / 0xCCCCCCCC 6447 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6448 // [8] = 0x00FF00FF / 0xFF00FF00 6449 // [16] = 0x0000FFFF / 0xFFFFFFFF 6450 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6451 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6452 // These are the unshifted masks which we use to match bit-manipulation 6453 // patterns. They may be shifted left in certain circumstances. 6454 static const uint64_t BitmanipMasks[] = { 6455 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6456 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6457 6458 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6459 } 6460 6461 // Match the following pattern as a GREVI(W) operation 6462 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6463 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6464 const RISCVSubtarget &Subtarget) { 6465 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6466 EVT VT = Op.getValueType(); 6467 6468 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6469 auto LHS = matchGREVIPat(Op.getOperand(0)); 6470 auto RHS = matchGREVIPat(Op.getOperand(1)); 6471 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6472 SDLoc DL(Op); 6473 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6474 DAG.getConstant(LHS->ShAmt, DL, VT)); 6475 } 6476 } 6477 return SDValue(); 6478 } 6479 6480 // Matches any the following pattern as a GORCI(W) operation 6481 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6482 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6483 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6484 // Note that with the variant of 3., 6485 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6486 // the inner pattern will first be matched as GREVI and then the outer 6487 // pattern will be matched to GORC via the first rule above. 6488 // 4. (or (rotl/rotr x, bitwidth/2), x) 6489 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6490 const RISCVSubtarget &Subtarget) { 6491 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6492 EVT VT = Op.getValueType(); 6493 6494 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6495 SDLoc DL(Op); 6496 SDValue Op0 = Op.getOperand(0); 6497 SDValue Op1 = Op.getOperand(1); 6498 6499 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6500 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6501 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6502 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6503 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6504 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6505 if ((Reverse.getOpcode() == ISD::ROTL || 6506 Reverse.getOpcode() == ISD::ROTR) && 6507 Reverse.getOperand(0) == X && 6508 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6509 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6510 if (RotAmt == (VT.getSizeInBits() / 2)) 6511 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6512 DAG.getConstant(RotAmt, DL, VT)); 6513 } 6514 return SDValue(); 6515 }; 6516 6517 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6518 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6519 return V; 6520 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6521 return V; 6522 6523 // OR is commutable so canonicalize its OR operand to the left 6524 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6525 std::swap(Op0, Op1); 6526 if (Op0.getOpcode() != ISD::OR) 6527 return SDValue(); 6528 SDValue OrOp0 = Op0.getOperand(0); 6529 SDValue OrOp1 = Op0.getOperand(1); 6530 auto LHS = matchGREVIPat(OrOp0); 6531 // OR is commutable so swap the operands and try again: x might have been 6532 // on the left 6533 if (!LHS) { 6534 std::swap(OrOp0, OrOp1); 6535 LHS = matchGREVIPat(OrOp0); 6536 } 6537 auto RHS = matchGREVIPat(Op1); 6538 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6539 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6540 DAG.getConstant(LHS->ShAmt, DL, VT)); 6541 } 6542 } 6543 return SDValue(); 6544 } 6545 6546 // Matches any of the following bit-manipulation patterns: 6547 // (and (shl x, 1), (0x22222222 << 1)) 6548 // (and (srl x, 1), 0x22222222) 6549 // (shl (and x, 0x22222222), 1) 6550 // (srl (and x, (0x22222222 << 1)), 1) 6551 // where the shift amount and mask may vary thus: 6552 // [1] = 0x22222222 / 0x44444444 6553 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6554 // [4] = 0x00F000F0 / 0x0F000F00 6555 // [8] = 0x0000FF00 / 0x00FF0000 6556 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6557 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6558 // These are the unshifted masks which we use to match bit-manipulation 6559 // patterns. They may be shifted left in certain circumstances. 6560 static const uint64_t BitmanipMasks[] = { 6561 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6562 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6563 6564 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6565 } 6566 6567 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6568 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6569 const RISCVSubtarget &Subtarget) { 6570 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6571 EVT VT = Op.getValueType(); 6572 6573 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6574 return SDValue(); 6575 6576 SDValue Op0 = Op.getOperand(0); 6577 SDValue Op1 = Op.getOperand(1); 6578 6579 // Or is commutable so canonicalize the second OR to the LHS. 6580 if (Op0.getOpcode() != ISD::OR) 6581 std::swap(Op0, Op1); 6582 if (Op0.getOpcode() != ISD::OR) 6583 return SDValue(); 6584 6585 // We found an inner OR, so our operands are the operands of the inner OR 6586 // and the other operand of the outer OR. 6587 SDValue A = Op0.getOperand(0); 6588 SDValue B = Op0.getOperand(1); 6589 SDValue C = Op1; 6590 6591 auto Match1 = matchSHFLPat(A); 6592 auto Match2 = matchSHFLPat(B); 6593 6594 // If neither matched, we failed. 6595 if (!Match1 && !Match2) 6596 return SDValue(); 6597 6598 // We had at least one match. if one failed, try the remaining C operand. 6599 if (!Match1) { 6600 std::swap(A, C); 6601 Match1 = matchSHFLPat(A); 6602 if (!Match1) 6603 return SDValue(); 6604 } else if (!Match2) { 6605 std::swap(B, C); 6606 Match2 = matchSHFLPat(B); 6607 if (!Match2) 6608 return SDValue(); 6609 } 6610 assert(Match1 && Match2); 6611 6612 // Make sure our matches pair up. 6613 if (!Match1->formsPairWith(*Match2)) 6614 return SDValue(); 6615 6616 // All the remains is to make sure C is an AND with the same input, that masks 6617 // out the bits that are being shuffled. 6618 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 6619 C.getOperand(0) != Match1->Op) 6620 return SDValue(); 6621 6622 uint64_t Mask = C.getConstantOperandVal(1); 6623 6624 static const uint64_t BitmanipMasks[] = { 6625 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 6626 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 6627 }; 6628 6629 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6630 unsigned MaskIdx = Log2_32(Match1->ShAmt); 6631 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6632 6633 if (Mask != ExpMask) 6634 return SDValue(); 6635 6636 SDLoc DL(Op); 6637 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 6638 DAG.getConstant(Match1->ShAmt, DL, VT)); 6639 } 6640 6641 // Optimize (add (shl x, c0), (shl y, c1)) -> 6642 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 6643 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 6644 const RISCVSubtarget &Subtarget) { 6645 // Perform this optimization only in the zba extension. 6646 if (!Subtarget.hasStdExtZba()) 6647 return SDValue(); 6648 6649 // Skip for vector types and larger types. 6650 EVT VT = N->getValueType(0); 6651 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6652 return SDValue(); 6653 6654 // The two operand nodes must be SHL and have no other use. 6655 SDValue N0 = N->getOperand(0); 6656 SDValue N1 = N->getOperand(1); 6657 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 6658 !N0->hasOneUse() || !N1->hasOneUse()) 6659 return SDValue(); 6660 6661 // Check c0 and c1. 6662 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6663 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 6664 if (!N0C || !N1C) 6665 return SDValue(); 6666 int64_t C0 = N0C->getSExtValue(); 6667 int64_t C1 = N1C->getSExtValue(); 6668 if (C0 <= 0 || C1 <= 0) 6669 return SDValue(); 6670 6671 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 6672 int64_t Bits = std::min(C0, C1); 6673 int64_t Diff = std::abs(C0 - C1); 6674 if (Diff != 1 && Diff != 2 && Diff != 3) 6675 return SDValue(); 6676 6677 // Build nodes. 6678 SDLoc DL(N); 6679 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 6680 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 6681 SDValue NA0 = 6682 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 6683 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 6684 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 6685 } 6686 6687 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 6688 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 6689 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 6690 // not undo itself, but they are redundant. 6691 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 6692 SDValue Src = N->getOperand(0); 6693 6694 if (Src.getOpcode() != N->getOpcode()) 6695 return SDValue(); 6696 6697 if (!isa<ConstantSDNode>(N->getOperand(1)) || 6698 !isa<ConstantSDNode>(Src.getOperand(1))) 6699 return SDValue(); 6700 6701 unsigned ShAmt1 = N->getConstantOperandVal(1); 6702 unsigned ShAmt2 = Src.getConstantOperandVal(1); 6703 Src = Src.getOperand(0); 6704 6705 unsigned CombinedShAmt; 6706 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 6707 CombinedShAmt = ShAmt1 | ShAmt2; 6708 else 6709 CombinedShAmt = ShAmt1 ^ ShAmt2; 6710 6711 if (CombinedShAmt == 0) 6712 return Src; 6713 6714 SDLoc DL(N); 6715 return DAG.getNode( 6716 N->getOpcode(), DL, N->getValueType(0), Src, 6717 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 6718 } 6719 6720 // Combine a constant select operand into its use: 6721 // 6722 // (and (select cond, -1, c), x) 6723 // -> (select cond, x, (and x, c)) [AllOnes=1] 6724 // (or (select cond, 0, c), x) 6725 // -> (select cond, x, (or x, c)) [AllOnes=0] 6726 // (xor (select cond, 0, c), x) 6727 // -> (select cond, x, (xor x, c)) [AllOnes=0] 6728 // (add (select cond, 0, c), x) 6729 // -> (select cond, x, (add x, c)) [AllOnes=0] 6730 // (sub x, (select cond, 0, c)) 6731 // -> (select cond, x, (sub x, c)) [AllOnes=0] 6732 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 6733 SelectionDAG &DAG, bool AllOnes) { 6734 EVT VT = N->getValueType(0); 6735 6736 // Skip vectors. 6737 if (VT.isVector()) 6738 return SDValue(); 6739 6740 if ((Slct.getOpcode() != ISD::SELECT && 6741 Slct.getOpcode() != RISCVISD::SELECT_CC) || 6742 !Slct.hasOneUse()) 6743 return SDValue(); 6744 6745 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 6746 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 6747 }; 6748 6749 bool SwapSelectOps; 6750 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 6751 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 6752 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 6753 SDValue NonConstantVal; 6754 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 6755 SwapSelectOps = false; 6756 NonConstantVal = FalseVal; 6757 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 6758 SwapSelectOps = true; 6759 NonConstantVal = TrueVal; 6760 } else 6761 return SDValue(); 6762 6763 // Slct is now know to be the desired identity constant when CC is true. 6764 TrueVal = OtherOp; 6765 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 6766 // Unless SwapSelectOps says the condition should be false. 6767 if (SwapSelectOps) 6768 std::swap(TrueVal, FalseVal); 6769 6770 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 6771 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 6772 {Slct.getOperand(0), Slct.getOperand(1), 6773 Slct.getOperand(2), TrueVal, FalseVal}); 6774 6775 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 6776 {Slct.getOperand(0), TrueVal, FalseVal}); 6777 } 6778 6779 // Attempt combineSelectAndUse on each operand of a commutative operator N. 6780 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 6781 bool AllOnes) { 6782 SDValue N0 = N->getOperand(0); 6783 SDValue N1 = N->getOperand(1); 6784 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 6785 return Result; 6786 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 6787 return Result; 6788 return SDValue(); 6789 } 6790 6791 // Transform (add (mul x, c0), c1) -> 6792 // (add (mul (add x, c1/c0), c0), c1%c0). 6793 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 6794 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 6795 // to an infinite loop in DAGCombine if transformed. 6796 // Or transform (add (mul x, c0), c1) -> 6797 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 6798 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 6799 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 6800 // lead to an infinite loop in DAGCombine if transformed. 6801 // Or transform (add (mul x, c0), c1) -> 6802 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 6803 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 6804 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 6805 // lead to an infinite loop in DAGCombine if transformed. 6806 // Or transform (add (mul x, c0), c1) -> 6807 // (mul (add x, c1/c0), c0). 6808 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 6809 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 6810 const RISCVSubtarget &Subtarget) { 6811 // Skip for vector types and larger types. 6812 EVT VT = N->getValueType(0); 6813 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6814 return SDValue(); 6815 // The first operand node must be a MUL and has no other use. 6816 SDValue N0 = N->getOperand(0); 6817 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 6818 return SDValue(); 6819 // Check if c0 and c1 match above conditions. 6820 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6821 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6822 if (!N0C || !N1C) 6823 return SDValue(); 6824 int64_t C0 = N0C->getSExtValue(); 6825 int64_t C1 = N1C->getSExtValue(); 6826 int64_t CA, CB; 6827 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 6828 return SDValue(); 6829 // Search for proper CA (non-zero) and CB that both are simm12. 6830 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 6831 !isInt<12>(C0 * (C1 / C0))) { 6832 CA = C1 / C0; 6833 CB = C1 % C0; 6834 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 6835 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 6836 CA = C1 / C0 + 1; 6837 CB = C1 % C0 - C0; 6838 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 6839 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 6840 CA = C1 / C0 - 1; 6841 CB = C1 % C0 + C0; 6842 } else 6843 return SDValue(); 6844 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 6845 SDLoc DL(N); 6846 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 6847 DAG.getConstant(CA, DL, VT)); 6848 SDValue New1 = 6849 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 6850 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 6851 } 6852 6853 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 6854 const RISCVSubtarget &Subtarget) { 6855 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 6856 return V; 6857 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 6858 return V; 6859 // fold (add (select lhs, rhs, cc, 0, y), x) -> 6860 // (select lhs, rhs, cc, x, (add x, y)) 6861 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6862 } 6863 6864 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 6865 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 6866 // (select lhs, rhs, cc, x, (sub x, y)) 6867 SDValue N0 = N->getOperand(0); 6868 SDValue N1 = N->getOperand(1); 6869 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 6870 } 6871 6872 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 6873 // fold (and (select lhs, rhs, cc, -1, y), x) -> 6874 // (select lhs, rhs, cc, x, (and x, y)) 6875 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 6876 } 6877 6878 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 6879 const RISCVSubtarget &Subtarget) { 6880 if (Subtarget.hasStdExtZbp()) { 6881 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 6882 return GREV; 6883 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 6884 return GORC; 6885 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 6886 return SHFL; 6887 } 6888 6889 // fold (or (select cond, 0, y), x) -> 6890 // (select cond, x, (or x, y)) 6891 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6892 } 6893 6894 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 6895 // fold (xor (select cond, 0, y), x) -> 6896 // (select cond, x, (xor x, y)) 6897 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6898 } 6899 6900 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 6901 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 6902 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 6903 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 6904 // ADDW/SUBW/MULW. 6905 static SDValue performANY_EXTENDCombine(SDNode *N, 6906 TargetLowering::DAGCombinerInfo &DCI, 6907 const RISCVSubtarget &Subtarget) { 6908 if (!Subtarget.is64Bit()) 6909 return SDValue(); 6910 6911 SelectionDAG &DAG = DCI.DAG; 6912 6913 SDValue Src = N->getOperand(0); 6914 EVT VT = N->getValueType(0); 6915 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 6916 return SDValue(); 6917 6918 // The opcode must be one that can implicitly sign_extend. 6919 // FIXME: Additional opcodes. 6920 switch (Src.getOpcode()) { 6921 default: 6922 return SDValue(); 6923 case ISD::MUL: 6924 if (!Subtarget.hasStdExtM()) 6925 return SDValue(); 6926 LLVM_FALLTHROUGH; 6927 case ISD::ADD: 6928 case ISD::SUB: 6929 break; 6930 } 6931 6932 // Only handle cases where the result is used by a CopyToReg. That likely 6933 // means the value is a liveout of the basic block. This helps prevent 6934 // infinite combine loops like PR51206. 6935 if (none_of(N->uses(), 6936 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 6937 return SDValue(); 6938 6939 SmallVector<SDNode *, 4> SetCCs; 6940 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 6941 UE = Src.getNode()->use_end(); 6942 UI != UE; ++UI) { 6943 SDNode *User = *UI; 6944 if (User == N) 6945 continue; 6946 if (UI.getUse().getResNo() != Src.getResNo()) 6947 continue; 6948 // All i32 setccs are legalized by sign extending operands. 6949 if (User->getOpcode() == ISD::SETCC) { 6950 SetCCs.push_back(User); 6951 continue; 6952 } 6953 // We don't know if we can extend this user. 6954 break; 6955 } 6956 6957 // If we don't have any SetCCs, this isn't worthwhile. 6958 if (SetCCs.empty()) 6959 return SDValue(); 6960 6961 SDLoc DL(N); 6962 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 6963 DCI.CombineTo(N, SExt); 6964 6965 // Promote all the setccs. 6966 for (SDNode *SetCC : SetCCs) { 6967 SmallVector<SDValue, 4> Ops; 6968 6969 for (unsigned j = 0; j != 2; ++j) { 6970 SDValue SOp = SetCC->getOperand(j); 6971 if (SOp == Src) 6972 Ops.push_back(SExt); 6973 else 6974 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 6975 } 6976 6977 Ops.push_back(SetCC->getOperand(2)); 6978 DCI.CombineTo(SetCC, 6979 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6980 } 6981 return SDValue(N, 0); 6982 } 6983 6984 // Try to form VWMUL or VWMULU. 6985 // FIXME: Support VWMULSU. 6986 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1, 6987 SelectionDAG &DAG) { 6988 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 6989 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 6990 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 6991 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 6992 return SDValue(); 6993 6994 SDValue Mask = N->getOperand(2); 6995 SDValue VL = N->getOperand(3); 6996 6997 // Make sure the mask and VL match. 6998 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 6999 return SDValue(); 7000 7001 MVT VT = N->getSimpleValueType(0); 7002 7003 // Determine the narrow size for a widening multiply. 7004 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7005 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7006 VT.getVectorElementCount()); 7007 7008 SDLoc DL(N); 7009 7010 // See if the other operand is the same opcode. 7011 if (Op0.getOpcode() == Op1.getOpcode()) { 7012 if (!Op1.hasOneUse()) 7013 return SDValue(); 7014 7015 // Make sure the mask and VL match. 7016 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7017 return SDValue(); 7018 7019 Op1 = Op1.getOperand(0); 7020 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7021 // The operand is a splat of a scalar. 7022 7023 // The VL must be the same. 7024 if (Op1.getOperand(1) != VL) 7025 return SDValue(); 7026 7027 // Get the scalar value. 7028 Op1 = Op1.getOperand(0); 7029 7030 // See if have enough sign bits or zero bits in the scalar to use a 7031 // widening multiply by splatting to smaller element size. 7032 unsigned EltBits = VT.getScalarSizeInBits(); 7033 unsigned ScalarBits = Op1.getValueSizeInBits(); 7034 // Make sure we're getting all element bits from the scalar register. 7035 // FIXME: Support implicit sign extension of vmv.v.x? 7036 if (ScalarBits < EltBits) 7037 return SDValue(); 7038 7039 if (IsSignExt) { 7040 if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize)) 7041 return SDValue(); 7042 } else { 7043 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7044 if (!DAG.MaskedValueIsZero(Op1, Mask)) 7045 return SDValue(); 7046 } 7047 7048 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 7049 } else 7050 return SDValue(); 7051 7052 Op0 = Op0.getOperand(0); 7053 7054 // Re-introduce narrower extends if needed. 7055 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7056 if (Op0.getValueType() != NarrowVT) 7057 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7058 if (Op1.getValueType() != NarrowVT) 7059 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7060 7061 unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7062 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7063 } 7064 7065 // Fold 7066 // (fp_to_int (froundeven X)) -> fcvt X, rne 7067 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7068 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7069 // (fp_to_int (fceil X)) -> fcvt X, rup 7070 // (fp_to_int (fround X)) -> fcvt X, rmm 7071 // FIXME: We should also do this for fp_to_int_sat. 7072 static SDValue performFP_TO_INTCombine(SDNode *N, 7073 TargetLowering::DAGCombinerInfo &DCI, 7074 const RISCVSubtarget &Subtarget) { 7075 SelectionDAG &DAG = DCI.DAG; 7076 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7077 MVT XLenVT = Subtarget.getXLenVT(); 7078 7079 // Only handle XLen or i32 types. Other types narrower than XLen will 7080 // eventually be legalized to XLenVT. 7081 EVT VT = N->getValueType(0); 7082 if (VT != MVT::i32 && VT != XLenVT) 7083 return SDValue(); 7084 7085 SDValue Src = N->getOperand(0); 7086 7087 // Ensure the FP type is also legal. 7088 if (!TLI.isTypeLegal(Src.getValueType())) 7089 return SDValue(); 7090 7091 // Don't do this for f16 with Zfhmin and not Zfh. 7092 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7093 return SDValue(); 7094 7095 RISCVFPRndMode::RoundingMode FRM; 7096 switch (Src->getOpcode()) { 7097 default: 7098 return SDValue(); 7099 case ISD::FROUNDEVEN: FRM = RISCVFPRndMode::RNE; break; 7100 case ISD::FTRUNC: FRM = RISCVFPRndMode::RTZ; break; 7101 case ISD::FFLOOR: FRM = RISCVFPRndMode::RDN; break; 7102 case ISD::FCEIL: FRM = RISCVFPRndMode::RUP; break; 7103 case ISD::FROUND: FRM = RISCVFPRndMode::RMM; break; 7104 } 7105 7106 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7107 7108 unsigned Opc; 7109 if (VT == XLenVT) 7110 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7111 else 7112 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7113 7114 SDLoc DL(N); 7115 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 7116 DAG.getTargetConstant(FRM, DL, XLenVT)); 7117 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 7118 } 7119 7120 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 7121 DAGCombinerInfo &DCI) const { 7122 SelectionDAG &DAG = DCI.DAG; 7123 7124 // Helper to call SimplifyDemandedBits on an operand of N where only some low 7125 // bits are demanded. N will be added to the Worklist if it was not deleted. 7126 // Caller should return SDValue(N, 0) if this returns true. 7127 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 7128 SDValue Op = N->getOperand(OpNo); 7129 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 7130 if (!SimplifyDemandedBits(Op, Mask, DCI)) 7131 return false; 7132 7133 if (N->getOpcode() != ISD::DELETED_NODE) 7134 DCI.AddToWorklist(N); 7135 return true; 7136 }; 7137 7138 switch (N->getOpcode()) { 7139 default: 7140 break; 7141 case RISCVISD::SplitF64: { 7142 SDValue Op0 = N->getOperand(0); 7143 // If the input to SplitF64 is just BuildPairF64 then the operation is 7144 // redundant. Instead, use BuildPairF64's operands directly. 7145 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 7146 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 7147 7148 SDLoc DL(N); 7149 7150 // It's cheaper to materialise two 32-bit integers than to load a double 7151 // from the constant pool and transfer it to integer registers through the 7152 // stack. 7153 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 7154 APInt V = C->getValueAPF().bitcastToAPInt(); 7155 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 7156 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 7157 return DCI.CombineTo(N, Lo, Hi); 7158 } 7159 7160 // This is a target-specific version of a DAGCombine performed in 7161 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7162 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7163 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7164 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7165 !Op0.getNode()->hasOneUse()) 7166 break; 7167 SDValue NewSplitF64 = 7168 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 7169 Op0.getOperand(0)); 7170 SDValue Lo = NewSplitF64.getValue(0); 7171 SDValue Hi = NewSplitF64.getValue(1); 7172 APInt SignBit = APInt::getSignMask(32); 7173 if (Op0.getOpcode() == ISD::FNEG) { 7174 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 7175 DAG.getConstant(SignBit, DL, MVT::i32)); 7176 return DCI.CombineTo(N, Lo, NewHi); 7177 } 7178 assert(Op0.getOpcode() == ISD::FABS); 7179 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 7180 DAG.getConstant(~SignBit, DL, MVT::i32)); 7181 return DCI.CombineTo(N, Lo, NewHi); 7182 } 7183 case RISCVISD::SLLW: 7184 case RISCVISD::SRAW: 7185 case RISCVISD::SRLW: 7186 case RISCVISD::ROLW: 7187 case RISCVISD::RORW: { 7188 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7189 if (SimplifyDemandedLowBitsHelper(0, 32) || 7190 SimplifyDemandedLowBitsHelper(1, 5)) 7191 return SDValue(N, 0); 7192 break; 7193 } 7194 case RISCVISD::CLZW: 7195 case RISCVISD::CTZW: { 7196 // Only the lower 32 bits of the first operand are read 7197 if (SimplifyDemandedLowBitsHelper(0, 32)) 7198 return SDValue(N, 0); 7199 break; 7200 } 7201 case RISCVISD::FSL: 7202 case RISCVISD::FSR: { 7203 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 7204 unsigned BitWidth = N->getOperand(2).getValueSizeInBits(); 7205 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7206 if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1)) 7207 return SDValue(N, 0); 7208 break; 7209 } 7210 case RISCVISD::FSLW: 7211 case RISCVISD::FSRW: { 7212 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 7213 // read. 7214 if (SimplifyDemandedLowBitsHelper(0, 32) || 7215 SimplifyDemandedLowBitsHelper(1, 32) || 7216 SimplifyDemandedLowBitsHelper(2, 6)) 7217 return SDValue(N, 0); 7218 break; 7219 } 7220 case RISCVISD::GREV: 7221 case RISCVISD::GORC: { 7222 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 7223 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7224 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7225 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 7226 return SDValue(N, 0); 7227 7228 return combineGREVI_GORCI(N, DAG); 7229 } 7230 case RISCVISD::GREVW: 7231 case RISCVISD::GORCW: { 7232 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7233 if (SimplifyDemandedLowBitsHelper(0, 32) || 7234 SimplifyDemandedLowBitsHelper(1, 5)) 7235 return SDValue(N, 0); 7236 7237 return combineGREVI_GORCI(N, DAG); 7238 } 7239 case RISCVISD::SHFL: 7240 case RISCVISD::UNSHFL: { 7241 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 7242 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7243 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7244 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 7245 return SDValue(N, 0); 7246 7247 break; 7248 } 7249 case RISCVISD::SHFLW: 7250 case RISCVISD::UNSHFLW: { 7251 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 7252 SDValue LHS = N->getOperand(0); 7253 SDValue RHS = N->getOperand(1); 7254 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 7255 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4); 7256 if (SimplifyDemandedLowBitsHelper(0, 32) || 7257 SimplifyDemandedLowBitsHelper(1, 4)) 7258 return SDValue(N, 0); 7259 7260 break; 7261 } 7262 case RISCVISD::BCOMPRESSW: 7263 case RISCVISD::BDECOMPRESSW: { 7264 // Only the lower 32 bits of LHS and RHS are read. 7265 if (SimplifyDemandedLowBitsHelper(0, 32) || 7266 SimplifyDemandedLowBitsHelper(1, 32)) 7267 return SDValue(N, 0); 7268 7269 break; 7270 } 7271 case RISCVISD::FMV_X_ANYEXTH: 7272 case RISCVISD::FMV_X_ANYEXTW_RV64: { 7273 SDLoc DL(N); 7274 SDValue Op0 = N->getOperand(0); 7275 MVT VT = N->getSimpleValueType(0); 7276 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 7277 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 7278 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 7279 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 7280 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 7281 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7282 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 7283 assert(Op0.getOperand(0).getValueType() == VT && 7284 "Unexpected value type!"); 7285 return Op0.getOperand(0); 7286 } 7287 7288 // This is a target-specific version of a DAGCombine performed in 7289 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7290 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7291 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7292 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7293 !Op0.getNode()->hasOneUse()) 7294 break; 7295 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 7296 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 7297 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 7298 if (Op0.getOpcode() == ISD::FNEG) 7299 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 7300 DAG.getConstant(SignBit, DL, VT)); 7301 7302 assert(Op0.getOpcode() == ISD::FABS); 7303 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 7304 DAG.getConstant(~SignBit, DL, VT)); 7305 } 7306 case ISD::ADD: 7307 return performADDCombine(N, DAG, Subtarget); 7308 case ISD::SUB: 7309 return performSUBCombine(N, DAG); 7310 case ISD::AND: 7311 return performANDCombine(N, DAG); 7312 case ISD::OR: 7313 return performORCombine(N, DAG, Subtarget); 7314 case ISD::XOR: 7315 return performXORCombine(N, DAG); 7316 case ISD::ANY_EXTEND: 7317 return performANY_EXTENDCombine(N, DCI, Subtarget); 7318 case ISD::ZERO_EXTEND: 7319 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 7320 // type legalization. This is safe because fp_to_uint produces poison if 7321 // it overflows. 7322 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 7323 SDValue Src = N->getOperand(0); 7324 if (Src.getOpcode() == ISD::FP_TO_UINT && 7325 isTypeLegal(Src.getOperand(0).getValueType())) 7326 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 7327 Src.getOperand(0)); 7328 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 7329 isTypeLegal(Src.getOperand(1).getValueType())) { 7330 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 7331 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 7332 Src.getOperand(0), Src.getOperand(1)); 7333 DCI.CombineTo(N, Res); 7334 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 7335 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 7336 return SDValue(N, 0); // Return N so it doesn't get rechecked. 7337 } 7338 } 7339 return SDValue(); 7340 case RISCVISD::SELECT_CC: { 7341 // Transform 7342 SDValue LHS = N->getOperand(0); 7343 SDValue RHS = N->getOperand(1); 7344 SDValue TrueV = N->getOperand(3); 7345 SDValue FalseV = N->getOperand(4); 7346 7347 // If the True and False values are the same, we don't need a select_cc. 7348 if (TrueV == FalseV) 7349 return TrueV; 7350 7351 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 7352 if (!ISD::isIntEqualitySetCC(CCVal)) 7353 break; 7354 7355 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 7356 // (select_cc X, Y, lt, trueV, falseV) 7357 // Sometimes the setcc is introduced after select_cc has been formed. 7358 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7359 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7360 // If we're looking for eq 0 instead of ne 0, we need to invert the 7361 // condition. 7362 bool Invert = CCVal == ISD::SETEQ; 7363 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7364 if (Invert) 7365 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7366 7367 SDLoc DL(N); 7368 RHS = LHS.getOperand(1); 7369 LHS = LHS.getOperand(0); 7370 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7371 7372 SDValue TargetCC = DAG.getCondCode(CCVal); 7373 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7374 {LHS, RHS, TargetCC, TrueV, FalseV}); 7375 } 7376 7377 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 7378 // (select_cc X, Y, eq/ne, trueV, falseV) 7379 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7380 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 7381 {LHS.getOperand(0), LHS.getOperand(1), 7382 N->getOperand(2), TrueV, FalseV}); 7383 // (select_cc X, 1, setne, trueV, falseV) -> 7384 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 7385 // This can occur when legalizing some floating point comparisons. 7386 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7387 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7388 SDLoc DL(N); 7389 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7390 SDValue TargetCC = DAG.getCondCode(CCVal); 7391 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7392 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7393 {LHS, RHS, TargetCC, TrueV, FalseV}); 7394 } 7395 7396 break; 7397 } 7398 case RISCVISD::BR_CC: { 7399 SDValue LHS = N->getOperand(1); 7400 SDValue RHS = N->getOperand(2); 7401 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 7402 if (!ISD::isIntEqualitySetCC(CCVal)) 7403 break; 7404 7405 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 7406 // (br_cc X, Y, lt, dest) 7407 // Sometimes the setcc is introduced after br_cc has been formed. 7408 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7409 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7410 // If we're looking for eq 0 instead of ne 0, we need to invert the 7411 // condition. 7412 bool Invert = CCVal == ISD::SETEQ; 7413 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7414 if (Invert) 7415 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7416 7417 SDLoc DL(N); 7418 RHS = LHS.getOperand(1); 7419 LHS = LHS.getOperand(0); 7420 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7421 7422 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7423 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 7424 N->getOperand(4)); 7425 } 7426 7427 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 7428 // (br_cc X, Y, eq/ne, trueV, falseV) 7429 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7430 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 7431 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 7432 N->getOperand(3), N->getOperand(4)); 7433 7434 // (br_cc X, 1, setne, br_cc) -> 7435 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 7436 // This can occur when legalizing some floating point comparisons. 7437 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7438 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7439 SDLoc DL(N); 7440 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7441 SDValue TargetCC = DAG.getCondCode(CCVal); 7442 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7443 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7444 N->getOperand(0), LHS, RHS, TargetCC, 7445 N->getOperand(4)); 7446 } 7447 break; 7448 } 7449 case ISD::FP_TO_SINT: 7450 case ISD::FP_TO_UINT: 7451 return performFP_TO_INTCombine(N, DCI, Subtarget); 7452 case ISD::FCOPYSIGN: { 7453 EVT VT = N->getValueType(0); 7454 if (!VT.isVector()) 7455 break; 7456 // There is a form of VFSGNJ which injects the negated sign of its second 7457 // operand. Try and bubble any FNEG up after the extend/round to produce 7458 // this optimized pattern. Avoid modifying cases where FP_ROUND and 7459 // TRUNC=1. 7460 SDValue In2 = N->getOperand(1); 7461 // Avoid cases where the extend/round has multiple uses, as duplicating 7462 // those is typically more expensive than removing a fneg. 7463 if (!In2.hasOneUse()) 7464 break; 7465 if (In2.getOpcode() != ISD::FP_EXTEND && 7466 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 7467 break; 7468 In2 = In2.getOperand(0); 7469 if (In2.getOpcode() != ISD::FNEG) 7470 break; 7471 SDLoc DL(N); 7472 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 7473 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 7474 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 7475 } 7476 case ISD::MGATHER: 7477 case ISD::MSCATTER: 7478 case ISD::VP_GATHER: 7479 case ISD::VP_SCATTER: { 7480 if (!DCI.isBeforeLegalize()) 7481 break; 7482 SDValue Index, ScaleOp; 7483 bool IsIndexScaled = false; 7484 bool IsIndexSigned = false; 7485 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 7486 Index = VPGSN->getIndex(); 7487 ScaleOp = VPGSN->getScale(); 7488 IsIndexScaled = VPGSN->isIndexScaled(); 7489 IsIndexSigned = VPGSN->isIndexSigned(); 7490 } else { 7491 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 7492 Index = MGSN->getIndex(); 7493 ScaleOp = MGSN->getScale(); 7494 IsIndexScaled = MGSN->isIndexScaled(); 7495 IsIndexSigned = MGSN->isIndexSigned(); 7496 } 7497 EVT IndexVT = Index.getValueType(); 7498 MVT XLenVT = Subtarget.getXLenVT(); 7499 // RISCV indexed loads only support the "unsigned unscaled" addressing 7500 // mode, so anything else must be manually legalized. 7501 bool NeedsIdxLegalization = 7502 IsIndexScaled || 7503 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 7504 if (!NeedsIdxLegalization) 7505 break; 7506 7507 SDLoc DL(N); 7508 7509 // Any index legalization should first promote to XLenVT, so we don't lose 7510 // bits when scaling. This may create an illegal index type so we let 7511 // LLVM's legalization take care of the splitting. 7512 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 7513 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 7514 IndexVT = IndexVT.changeVectorElementType(XLenVT); 7515 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 7516 DL, IndexVT, Index); 7517 } 7518 7519 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 7520 if (IsIndexScaled && Scale != 1) { 7521 // Manually scale the indices by the element size. 7522 // TODO: Sanitize the scale operand here? 7523 // TODO: For VP nodes, should we use VP_SHL here? 7524 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 7525 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 7526 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 7527 } 7528 7529 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 7530 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 7531 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 7532 {VPGN->getChain(), VPGN->getBasePtr(), Index, 7533 VPGN->getScale(), VPGN->getMask(), 7534 VPGN->getVectorLength()}, 7535 VPGN->getMemOperand(), NewIndexTy); 7536 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 7537 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 7538 {VPSN->getChain(), VPSN->getValue(), 7539 VPSN->getBasePtr(), Index, VPSN->getScale(), 7540 VPSN->getMask(), VPSN->getVectorLength()}, 7541 VPSN->getMemOperand(), NewIndexTy); 7542 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 7543 return DAG.getMaskedGather( 7544 N->getVTList(), MGN->getMemoryVT(), DL, 7545 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 7546 MGN->getBasePtr(), Index, MGN->getScale()}, 7547 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 7548 const auto *MSN = cast<MaskedScatterSDNode>(N); 7549 return DAG.getMaskedScatter( 7550 N->getVTList(), MSN->getMemoryVT(), DL, 7551 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 7552 Index, MSN->getScale()}, 7553 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 7554 } 7555 case RISCVISD::SRA_VL: 7556 case RISCVISD::SRL_VL: 7557 case RISCVISD::SHL_VL: { 7558 SDValue ShAmt = N->getOperand(1); 7559 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7560 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7561 SDLoc DL(N); 7562 SDValue VL = N->getOperand(3); 7563 EVT VT = N->getValueType(0); 7564 ShAmt = 7565 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 7566 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 7567 N->getOperand(2), N->getOperand(3)); 7568 } 7569 break; 7570 } 7571 case ISD::SRA: 7572 case ISD::SRL: 7573 case ISD::SHL: { 7574 SDValue ShAmt = N->getOperand(1); 7575 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7576 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7577 SDLoc DL(N); 7578 EVT VT = N->getValueType(0); 7579 ShAmt = 7580 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 7581 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 7582 } 7583 break; 7584 } 7585 case RISCVISD::MUL_VL: { 7586 SDValue Op0 = N->getOperand(0); 7587 SDValue Op1 = N->getOperand(1); 7588 if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG)) 7589 return V; 7590 if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG)) 7591 return V; 7592 return SDValue(); 7593 } 7594 case ISD::STORE: { 7595 auto *Store = cast<StoreSDNode>(N); 7596 SDValue Val = Store->getValue(); 7597 // Combine store of vmv.x.s to vse with VL of 1. 7598 // FIXME: Support FP. 7599 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 7600 SDValue Src = Val.getOperand(0); 7601 EVT VecVT = Src.getValueType(); 7602 EVT MemVT = Store->getMemoryVT(); 7603 // The memory VT and the element type must match. 7604 if (VecVT.getVectorElementType() == MemVT) { 7605 SDLoc DL(N); 7606 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7607 return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(), 7608 DAG.getConstant(1, DL, MaskVT), 7609 DAG.getConstant(1, DL, Subtarget.getXLenVT()), 7610 Store->getPointerInfo(), 7611 Store->getOriginalAlign(), 7612 Store->getMemOperand()->getFlags()); 7613 } 7614 } 7615 7616 break; 7617 } 7618 } 7619 7620 return SDValue(); 7621 } 7622 7623 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 7624 const SDNode *N, CombineLevel Level) const { 7625 // The following folds are only desirable if `(OP _, c1 << c2)` can be 7626 // materialised in fewer instructions than `(OP _, c1)`: 7627 // 7628 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 7629 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 7630 SDValue N0 = N->getOperand(0); 7631 EVT Ty = N0.getValueType(); 7632 if (Ty.isScalarInteger() && 7633 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 7634 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7635 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7636 if (C1 && C2) { 7637 const APInt &C1Int = C1->getAPIntValue(); 7638 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 7639 7640 // We can materialise `c1 << c2` into an add immediate, so it's "free", 7641 // and the combine should happen, to potentially allow further combines 7642 // later. 7643 if (ShiftedC1Int.getMinSignedBits() <= 64 && 7644 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 7645 return true; 7646 7647 // We can materialise `c1` in an add immediate, so it's "free", and the 7648 // combine should be prevented. 7649 if (C1Int.getMinSignedBits() <= 64 && 7650 isLegalAddImmediate(C1Int.getSExtValue())) 7651 return false; 7652 7653 // Neither constant will fit into an immediate, so find materialisation 7654 // costs. 7655 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 7656 Subtarget.getFeatureBits(), 7657 /*CompressionCost*/true); 7658 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 7659 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 7660 /*CompressionCost*/true); 7661 7662 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 7663 // combine should be prevented. 7664 if (C1Cost < ShiftedC1Cost) 7665 return false; 7666 } 7667 } 7668 return true; 7669 } 7670 7671 bool RISCVTargetLowering::targetShrinkDemandedConstant( 7672 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 7673 TargetLoweringOpt &TLO) const { 7674 // Delay this optimization as late as possible. 7675 if (!TLO.LegalOps) 7676 return false; 7677 7678 EVT VT = Op.getValueType(); 7679 if (VT.isVector()) 7680 return false; 7681 7682 // Only handle AND for now. 7683 if (Op.getOpcode() != ISD::AND) 7684 return false; 7685 7686 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7687 if (!C) 7688 return false; 7689 7690 const APInt &Mask = C->getAPIntValue(); 7691 7692 // Clear all non-demanded bits initially. 7693 APInt ShrunkMask = Mask & DemandedBits; 7694 7695 // Try to make a smaller immediate by setting undemanded bits. 7696 7697 APInt ExpandedMask = Mask | ~DemandedBits; 7698 7699 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 7700 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 7701 }; 7702 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 7703 if (NewMask == Mask) 7704 return true; 7705 SDLoc DL(Op); 7706 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 7707 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 7708 return TLO.CombineTo(Op, NewOp); 7709 }; 7710 7711 // If the shrunk mask fits in sign extended 12 bits, let the target 7712 // independent code apply it. 7713 if (ShrunkMask.isSignedIntN(12)) 7714 return false; 7715 7716 // Preserve (and X, 0xffff) when zext.h is supported. 7717 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 7718 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 7719 if (IsLegalMask(NewMask)) 7720 return UseMask(NewMask); 7721 } 7722 7723 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 7724 if (VT == MVT::i64) { 7725 APInt NewMask = APInt(64, 0xffffffff); 7726 if (IsLegalMask(NewMask)) 7727 return UseMask(NewMask); 7728 } 7729 7730 // For the remaining optimizations, we need to be able to make a negative 7731 // number through a combination of mask and undemanded bits. 7732 if (!ExpandedMask.isNegative()) 7733 return false; 7734 7735 // What is the fewest number of bits we need to represent the negative number. 7736 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 7737 7738 // Try to make a 12 bit negative immediate. If that fails try to make a 32 7739 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 7740 APInt NewMask = ShrunkMask; 7741 if (MinSignedBits <= 12) 7742 NewMask.setBitsFrom(11); 7743 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 7744 NewMask.setBitsFrom(31); 7745 else 7746 return false; 7747 7748 // Check that our new mask is a subset of the demanded mask. 7749 assert(IsLegalMask(NewMask)); 7750 return UseMask(NewMask); 7751 } 7752 7753 static void computeGREV(APInt &Src, unsigned ShAmt) { 7754 ShAmt &= Src.getBitWidth() - 1; 7755 uint64_t x = Src.getZExtValue(); 7756 if (ShAmt & 1) 7757 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 7758 if (ShAmt & 2) 7759 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 7760 if (ShAmt & 4) 7761 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 7762 if (ShAmt & 8) 7763 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 7764 if (ShAmt & 16) 7765 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 7766 if (ShAmt & 32) 7767 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 7768 Src = x; 7769 } 7770 7771 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 7772 KnownBits &Known, 7773 const APInt &DemandedElts, 7774 const SelectionDAG &DAG, 7775 unsigned Depth) const { 7776 unsigned BitWidth = Known.getBitWidth(); 7777 unsigned Opc = Op.getOpcode(); 7778 assert((Opc >= ISD::BUILTIN_OP_END || 7779 Opc == ISD::INTRINSIC_WO_CHAIN || 7780 Opc == ISD::INTRINSIC_W_CHAIN || 7781 Opc == ISD::INTRINSIC_VOID) && 7782 "Should use MaskedValueIsZero if you don't know whether Op" 7783 " is a target node!"); 7784 7785 Known.resetAll(); 7786 switch (Opc) { 7787 default: break; 7788 case RISCVISD::SELECT_CC: { 7789 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 7790 // If we don't know any bits, early out. 7791 if (Known.isUnknown()) 7792 break; 7793 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 7794 7795 // Only known if known in both the LHS and RHS. 7796 Known = KnownBits::commonBits(Known, Known2); 7797 break; 7798 } 7799 case RISCVISD::REMUW: { 7800 KnownBits Known2; 7801 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7802 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7803 // We only care about the lower 32 bits. 7804 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 7805 // Restore the original width by sign extending. 7806 Known = Known.sext(BitWidth); 7807 break; 7808 } 7809 case RISCVISD::DIVUW: { 7810 KnownBits Known2; 7811 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7812 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7813 // We only care about the lower 32 bits. 7814 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 7815 // Restore the original width by sign extending. 7816 Known = Known.sext(BitWidth); 7817 break; 7818 } 7819 case RISCVISD::CTZW: { 7820 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7821 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 7822 unsigned LowBits = Log2_32(PossibleTZ) + 1; 7823 Known.Zero.setBitsFrom(LowBits); 7824 break; 7825 } 7826 case RISCVISD::CLZW: { 7827 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7828 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 7829 unsigned LowBits = Log2_32(PossibleLZ) + 1; 7830 Known.Zero.setBitsFrom(LowBits); 7831 break; 7832 } 7833 case RISCVISD::GREV: 7834 case RISCVISD::GREVW: { 7835 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7836 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7837 if (Opc == RISCVISD::GREVW) 7838 Known = Known.trunc(32); 7839 unsigned ShAmt = C->getZExtValue(); 7840 computeGREV(Known.Zero, ShAmt); 7841 computeGREV(Known.One, ShAmt); 7842 if (Opc == RISCVISD::GREVW) 7843 Known = Known.sext(BitWidth); 7844 } 7845 break; 7846 } 7847 case RISCVISD::READ_VLENB: 7848 // We assume VLENB is at least 16 bytes. 7849 Known.Zero.setLowBits(4); 7850 // We assume VLENB is no more than 65536 / 8 bytes. 7851 Known.Zero.setBitsFrom(14); 7852 break; 7853 case ISD::INTRINSIC_W_CHAIN: { 7854 unsigned IntNo = Op.getConstantOperandVal(1); 7855 switch (IntNo) { 7856 default: 7857 // We can't do anything for most intrinsics. 7858 break; 7859 case Intrinsic::riscv_vsetvli: 7860 case Intrinsic::riscv_vsetvlimax: 7861 // Assume that VL output is positive and would fit in an int32_t. 7862 // TODO: VLEN might be capped at 16 bits in a future V spec update. 7863 if (BitWidth >= 32) 7864 Known.Zero.setBitsFrom(31); 7865 break; 7866 } 7867 break; 7868 } 7869 } 7870 } 7871 7872 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 7873 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 7874 unsigned Depth) const { 7875 switch (Op.getOpcode()) { 7876 default: 7877 break; 7878 case RISCVISD::SELECT_CC: { 7879 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 7880 if (Tmp == 1) return 1; // Early out. 7881 unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 7882 return std::min(Tmp, Tmp2); 7883 } 7884 case RISCVISD::SLLW: 7885 case RISCVISD::SRAW: 7886 case RISCVISD::SRLW: 7887 case RISCVISD::DIVW: 7888 case RISCVISD::DIVUW: 7889 case RISCVISD::REMUW: 7890 case RISCVISD::ROLW: 7891 case RISCVISD::RORW: 7892 case RISCVISD::GREVW: 7893 case RISCVISD::GORCW: 7894 case RISCVISD::FSLW: 7895 case RISCVISD::FSRW: 7896 case RISCVISD::SHFLW: 7897 case RISCVISD::UNSHFLW: 7898 case RISCVISD::BCOMPRESSW: 7899 case RISCVISD::BDECOMPRESSW: 7900 case RISCVISD::FCVT_W_RV64: 7901 case RISCVISD::FCVT_WU_RV64: 7902 case RISCVISD::STRICT_FCVT_W_RV64: 7903 case RISCVISD::STRICT_FCVT_WU_RV64: 7904 // TODO: As the result is sign-extended, this is conservatively correct. A 7905 // more precise answer could be calculated for SRAW depending on known 7906 // bits in the shift amount. 7907 return 33; 7908 case RISCVISD::SHFL: 7909 case RISCVISD::UNSHFL: { 7910 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 7911 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 7912 // will stay within the upper 32 bits. If there were more than 32 sign bits 7913 // before there will be at least 33 sign bits after. 7914 if (Op.getValueType() == MVT::i64 && 7915 isa<ConstantSDNode>(Op.getOperand(1)) && 7916 (Op.getConstantOperandVal(1) & 0x10) == 0) { 7917 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 7918 if (Tmp > 32) 7919 return 33; 7920 } 7921 break; 7922 } 7923 case RISCVISD::VMV_X_S: 7924 // The number of sign bits of the scalar result is computed by obtaining the 7925 // element type of the input vector operand, subtracting its width from the 7926 // XLEN, and then adding one (sign bit within the element type). If the 7927 // element type is wider than XLen, the least-significant XLEN bits are 7928 // taken. 7929 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 7930 return 1; 7931 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 7932 } 7933 7934 return 1; 7935 } 7936 7937 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 7938 MachineBasicBlock *BB) { 7939 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 7940 7941 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 7942 // Should the count have wrapped while it was being read, we need to try 7943 // again. 7944 // ... 7945 // read: 7946 // rdcycleh x3 # load high word of cycle 7947 // rdcycle x2 # load low word of cycle 7948 // rdcycleh x4 # load high word of cycle 7949 // bne x3, x4, read # check if high word reads match, otherwise try again 7950 // ... 7951 7952 MachineFunction &MF = *BB->getParent(); 7953 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7954 MachineFunction::iterator It = ++BB->getIterator(); 7955 7956 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7957 MF.insert(It, LoopMBB); 7958 7959 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7960 MF.insert(It, DoneMBB); 7961 7962 // Transfer the remainder of BB and its successor edges to DoneMBB. 7963 DoneMBB->splice(DoneMBB->begin(), BB, 7964 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7965 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 7966 7967 BB->addSuccessor(LoopMBB); 7968 7969 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7970 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 7971 Register LoReg = MI.getOperand(0).getReg(); 7972 Register HiReg = MI.getOperand(1).getReg(); 7973 DebugLoc DL = MI.getDebugLoc(); 7974 7975 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 7976 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 7977 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7978 .addReg(RISCV::X0); 7979 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 7980 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 7981 .addReg(RISCV::X0); 7982 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 7983 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7984 .addReg(RISCV::X0); 7985 7986 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 7987 .addReg(HiReg) 7988 .addReg(ReadAgainReg) 7989 .addMBB(LoopMBB); 7990 7991 LoopMBB->addSuccessor(LoopMBB); 7992 LoopMBB->addSuccessor(DoneMBB); 7993 7994 MI.eraseFromParent(); 7995 7996 return DoneMBB; 7997 } 7998 7999 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 8000 MachineBasicBlock *BB) { 8001 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 8002 8003 MachineFunction &MF = *BB->getParent(); 8004 DebugLoc DL = MI.getDebugLoc(); 8005 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8006 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8007 Register LoReg = MI.getOperand(0).getReg(); 8008 Register HiReg = MI.getOperand(1).getReg(); 8009 Register SrcReg = MI.getOperand(2).getReg(); 8010 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 8011 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8012 8013 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 8014 RI); 8015 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8016 MachineMemOperand *MMOLo = 8017 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 8018 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8019 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 8020 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 8021 .addFrameIndex(FI) 8022 .addImm(0) 8023 .addMemOperand(MMOLo); 8024 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 8025 .addFrameIndex(FI) 8026 .addImm(4) 8027 .addMemOperand(MMOHi); 8028 MI.eraseFromParent(); // The pseudo instruction is gone now. 8029 return BB; 8030 } 8031 8032 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 8033 MachineBasicBlock *BB) { 8034 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 8035 "Unexpected instruction"); 8036 8037 MachineFunction &MF = *BB->getParent(); 8038 DebugLoc DL = MI.getDebugLoc(); 8039 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8040 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8041 Register DstReg = MI.getOperand(0).getReg(); 8042 Register LoReg = MI.getOperand(1).getReg(); 8043 Register HiReg = MI.getOperand(2).getReg(); 8044 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 8045 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8046 8047 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8048 MachineMemOperand *MMOLo = 8049 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 8050 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8051 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 8052 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8053 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 8054 .addFrameIndex(FI) 8055 .addImm(0) 8056 .addMemOperand(MMOLo); 8057 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8058 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 8059 .addFrameIndex(FI) 8060 .addImm(4) 8061 .addMemOperand(MMOHi); 8062 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 8063 MI.eraseFromParent(); // The pseudo instruction is gone now. 8064 return BB; 8065 } 8066 8067 static bool isSelectPseudo(MachineInstr &MI) { 8068 switch (MI.getOpcode()) { 8069 default: 8070 return false; 8071 case RISCV::Select_GPR_Using_CC_GPR: 8072 case RISCV::Select_FPR16_Using_CC_GPR: 8073 case RISCV::Select_FPR32_Using_CC_GPR: 8074 case RISCV::Select_FPR64_Using_CC_GPR: 8075 return true; 8076 } 8077 } 8078 8079 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 8080 unsigned RelOpcode, unsigned EqOpcode, 8081 const RISCVSubtarget &Subtarget) { 8082 DebugLoc DL = MI.getDebugLoc(); 8083 Register DstReg = MI.getOperand(0).getReg(); 8084 Register Src1Reg = MI.getOperand(1).getReg(); 8085 Register Src2Reg = MI.getOperand(2).getReg(); 8086 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 8087 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 8088 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 8089 8090 // Save the current FFLAGS. 8091 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 8092 8093 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 8094 .addReg(Src1Reg) 8095 .addReg(Src2Reg); 8096 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8097 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 8098 8099 // Restore the FFLAGS. 8100 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 8101 .addReg(SavedFFlags, RegState::Kill); 8102 8103 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 8104 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 8105 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 8106 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 8107 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8108 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 8109 8110 // Erase the pseudoinstruction. 8111 MI.eraseFromParent(); 8112 return BB; 8113 } 8114 8115 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 8116 MachineBasicBlock *BB, 8117 const RISCVSubtarget &Subtarget) { 8118 // To "insert" Select_* instructions, we actually have to insert the triangle 8119 // control-flow pattern. The incoming instructions know the destination vreg 8120 // to set, the condition code register to branch on, the true/false values to 8121 // select between, and the condcode to use to select the appropriate branch. 8122 // 8123 // We produce the following control flow: 8124 // HeadMBB 8125 // | \ 8126 // | IfFalseMBB 8127 // | / 8128 // TailMBB 8129 // 8130 // When we find a sequence of selects we attempt to optimize their emission 8131 // by sharing the control flow. Currently we only handle cases where we have 8132 // multiple selects with the exact same condition (same LHS, RHS and CC). 8133 // The selects may be interleaved with other instructions if the other 8134 // instructions meet some requirements we deem safe: 8135 // - They are debug instructions. Otherwise, 8136 // - They do not have side-effects, do not access memory and their inputs do 8137 // not depend on the results of the select pseudo-instructions. 8138 // The TrueV/FalseV operands of the selects cannot depend on the result of 8139 // previous selects in the sequence. 8140 // These conditions could be further relaxed. See the X86 target for a 8141 // related approach and more information. 8142 Register LHS = MI.getOperand(1).getReg(); 8143 Register RHS = MI.getOperand(2).getReg(); 8144 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 8145 8146 SmallVector<MachineInstr *, 4> SelectDebugValues; 8147 SmallSet<Register, 4> SelectDests; 8148 SelectDests.insert(MI.getOperand(0).getReg()); 8149 8150 MachineInstr *LastSelectPseudo = &MI; 8151 8152 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 8153 SequenceMBBI != E; ++SequenceMBBI) { 8154 if (SequenceMBBI->isDebugInstr()) 8155 continue; 8156 else if (isSelectPseudo(*SequenceMBBI)) { 8157 if (SequenceMBBI->getOperand(1).getReg() != LHS || 8158 SequenceMBBI->getOperand(2).getReg() != RHS || 8159 SequenceMBBI->getOperand(3).getImm() != CC || 8160 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 8161 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 8162 break; 8163 LastSelectPseudo = &*SequenceMBBI; 8164 SequenceMBBI->collectDebugValues(SelectDebugValues); 8165 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 8166 } else { 8167 if (SequenceMBBI->hasUnmodeledSideEffects() || 8168 SequenceMBBI->mayLoadOrStore()) 8169 break; 8170 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 8171 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 8172 })) 8173 break; 8174 } 8175 } 8176 8177 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 8178 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8179 DebugLoc DL = MI.getDebugLoc(); 8180 MachineFunction::iterator I = ++BB->getIterator(); 8181 8182 MachineBasicBlock *HeadMBB = BB; 8183 MachineFunction *F = BB->getParent(); 8184 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 8185 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 8186 8187 F->insert(I, IfFalseMBB); 8188 F->insert(I, TailMBB); 8189 8190 // Transfer debug instructions associated with the selects to TailMBB. 8191 for (MachineInstr *DebugInstr : SelectDebugValues) { 8192 TailMBB->push_back(DebugInstr->removeFromParent()); 8193 } 8194 8195 // Move all instructions after the sequence to TailMBB. 8196 TailMBB->splice(TailMBB->end(), HeadMBB, 8197 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 8198 // Update machine-CFG edges by transferring all successors of the current 8199 // block to the new block which will contain the Phi nodes for the selects. 8200 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 8201 // Set the successors for HeadMBB. 8202 HeadMBB->addSuccessor(IfFalseMBB); 8203 HeadMBB->addSuccessor(TailMBB); 8204 8205 // Insert appropriate branch. 8206 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 8207 .addReg(LHS) 8208 .addReg(RHS) 8209 .addMBB(TailMBB); 8210 8211 // IfFalseMBB just falls through to TailMBB. 8212 IfFalseMBB->addSuccessor(TailMBB); 8213 8214 // Create PHIs for all of the select pseudo-instructions. 8215 auto SelectMBBI = MI.getIterator(); 8216 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 8217 auto InsertionPoint = TailMBB->begin(); 8218 while (SelectMBBI != SelectEnd) { 8219 auto Next = std::next(SelectMBBI); 8220 if (isSelectPseudo(*SelectMBBI)) { 8221 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 8222 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 8223 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 8224 .addReg(SelectMBBI->getOperand(4).getReg()) 8225 .addMBB(HeadMBB) 8226 .addReg(SelectMBBI->getOperand(5).getReg()) 8227 .addMBB(IfFalseMBB); 8228 SelectMBBI->eraseFromParent(); 8229 } 8230 SelectMBBI = Next; 8231 } 8232 8233 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 8234 return TailMBB; 8235 } 8236 8237 MachineBasicBlock * 8238 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8239 MachineBasicBlock *BB) const { 8240 switch (MI.getOpcode()) { 8241 default: 8242 llvm_unreachable("Unexpected instr type to insert"); 8243 case RISCV::ReadCycleWide: 8244 assert(!Subtarget.is64Bit() && 8245 "ReadCycleWrite is only to be used on riscv32"); 8246 return emitReadCycleWidePseudo(MI, BB); 8247 case RISCV::Select_GPR_Using_CC_GPR: 8248 case RISCV::Select_FPR16_Using_CC_GPR: 8249 case RISCV::Select_FPR32_Using_CC_GPR: 8250 case RISCV::Select_FPR64_Using_CC_GPR: 8251 return emitSelectPseudo(MI, BB, Subtarget); 8252 case RISCV::BuildPairF64Pseudo: 8253 return emitBuildPairF64Pseudo(MI, BB); 8254 case RISCV::SplitF64Pseudo: 8255 return emitSplitF64Pseudo(MI, BB); 8256 case RISCV::PseudoQuietFLE_H: 8257 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 8258 case RISCV::PseudoQuietFLT_H: 8259 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 8260 case RISCV::PseudoQuietFLE_S: 8261 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 8262 case RISCV::PseudoQuietFLT_S: 8263 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 8264 case RISCV::PseudoQuietFLE_D: 8265 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 8266 case RISCV::PseudoQuietFLT_D: 8267 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 8268 } 8269 } 8270 8271 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 8272 SDNode *Node) const { 8273 // Add FRM dependency to any instructions with dynamic rounding mode. 8274 unsigned Opc = MI.getOpcode(); 8275 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 8276 if (Idx < 0) 8277 return; 8278 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 8279 return; 8280 // If the instruction already reads FRM, don't add another read. 8281 if (MI.readsRegister(RISCV::FRM)) 8282 return; 8283 MI.addOperand( 8284 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 8285 } 8286 8287 // Calling Convention Implementation. 8288 // The expectations for frontend ABI lowering vary from target to target. 8289 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 8290 // details, but this is a longer term goal. For now, we simply try to keep the 8291 // role of the frontend as simple and well-defined as possible. The rules can 8292 // be summarised as: 8293 // * Never split up large scalar arguments. We handle them here. 8294 // * If a hardfloat calling convention is being used, and the struct may be 8295 // passed in a pair of registers (fp+fp, int+fp), and both registers are 8296 // available, then pass as two separate arguments. If either the GPRs or FPRs 8297 // are exhausted, then pass according to the rule below. 8298 // * If a struct could never be passed in registers or directly in a stack 8299 // slot (as it is larger than 2*XLEN and the floating point rules don't 8300 // apply), then pass it using a pointer with the byval attribute. 8301 // * If a struct is less than 2*XLEN, then coerce to either a two-element 8302 // word-sized array or a 2*XLEN scalar (depending on alignment). 8303 // * The frontend can determine whether a struct is returned by reference or 8304 // not based on its size and fields. If it will be returned by reference, the 8305 // frontend must modify the prototype so a pointer with the sret annotation is 8306 // passed as the first argument. This is not necessary for large scalar 8307 // returns. 8308 // * Struct return values and varargs should be coerced to structs containing 8309 // register-size fields in the same situations they would be for fixed 8310 // arguments. 8311 8312 static const MCPhysReg ArgGPRs[] = { 8313 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 8314 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 8315 }; 8316 static const MCPhysReg ArgFPR16s[] = { 8317 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 8318 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 8319 }; 8320 static const MCPhysReg ArgFPR32s[] = { 8321 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 8322 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 8323 }; 8324 static const MCPhysReg ArgFPR64s[] = { 8325 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 8326 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 8327 }; 8328 // This is an interim calling convention and it may be changed in the future. 8329 static const MCPhysReg ArgVRs[] = { 8330 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 8331 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 8332 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 8333 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 8334 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 8335 RISCV::V20M2, RISCV::V22M2}; 8336 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 8337 RISCV::V20M4}; 8338 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 8339 8340 // Pass a 2*XLEN argument that has been split into two XLEN values through 8341 // registers or the stack as necessary. 8342 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 8343 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 8344 MVT ValVT2, MVT LocVT2, 8345 ISD::ArgFlagsTy ArgFlags2) { 8346 unsigned XLenInBytes = XLen / 8; 8347 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8348 // At least one half can be passed via register. 8349 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 8350 VA1.getLocVT(), CCValAssign::Full)); 8351 } else { 8352 // Both halves must be passed on the stack, with proper alignment. 8353 Align StackAlign = 8354 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 8355 State.addLoc( 8356 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 8357 State.AllocateStack(XLenInBytes, StackAlign), 8358 VA1.getLocVT(), CCValAssign::Full)); 8359 State.addLoc(CCValAssign::getMem( 8360 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8361 LocVT2, CCValAssign::Full)); 8362 return false; 8363 } 8364 8365 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8366 // The second half can also be passed via register. 8367 State.addLoc( 8368 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 8369 } else { 8370 // The second half is passed via the stack, without additional alignment. 8371 State.addLoc(CCValAssign::getMem( 8372 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8373 LocVT2, CCValAssign::Full)); 8374 } 8375 8376 return false; 8377 } 8378 8379 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 8380 Optional<unsigned> FirstMaskArgument, 8381 CCState &State, const RISCVTargetLowering &TLI) { 8382 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 8383 if (RC == &RISCV::VRRegClass) { 8384 // Assign the first mask argument to V0. 8385 // This is an interim calling convention and it may be changed in the 8386 // future. 8387 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 8388 return State.AllocateReg(RISCV::V0); 8389 return State.AllocateReg(ArgVRs); 8390 } 8391 if (RC == &RISCV::VRM2RegClass) 8392 return State.AllocateReg(ArgVRM2s); 8393 if (RC == &RISCV::VRM4RegClass) 8394 return State.AllocateReg(ArgVRM4s); 8395 if (RC == &RISCV::VRM8RegClass) 8396 return State.AllocateReg(ArgVRM8s); 8397 llvm_unreachable("Unhandled register class for ValueType"); 8398 } 8399 8400 // Implements the RISC-V calling convention. Returns true upon failure. 8401 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 8402 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 8403 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 8404 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 8405 Optional<unsigned> FirstMaskArgument) { 8406 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 8407 assert(XLen == 32 || XLen == 64); 8408 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 8409 8410 // Any return value split in to more than two values can't be returned 8411 // directly. Vectors are returned via the available vector registers. 8412 if (!LocVT.isVector() && IsRet && ValNo > 1) 8413 return true; 8414 8415 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 8416 // variadic argument, or if no F16/F32 argument registers are available. 8417 bool UseGPRForF16_F32 = true; 8418 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 8419 // variadic argument, or if no F64 argument registers are available. 8420 bool UseGPRForF64 = true; 8421 8422 switch (ABI) { 8423 default: 8424 llvm_unreachable("Unexpected ABI"); 8425 case RISCVABI::ABI_ILP32: 8426 case RISCVABI::ABI_LP64: 8427 break; 8428 case RISCVABI::ABI_ILP32F: 8429 case RISCVABI::ABI_LP64F: 8430 UseGPRForF16_F32 = !IsFixed; 8431 break; 8432 case RISCVABI::ABI_ILP32D: 8433 case RISCVABI::ABI_LP64D: 8434 UseGPRForF16_F32 = !IsFixed; 8435 UseGPRForF64 = !IsFixed; 8436 break; 8437 } 8438 8439 // FPR16, FPR32, and FPR64 alias each other. 8440 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 8441 UseGPRForF16_F32 = true; 8442 UseGPRForF64 = true; 8443 } 8444 8445 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 8446 // similar local variables rather than directly checking against the target 8447 // ABI. 8448 8449 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 8450 LocVT = XLenVT; 8451 LocInfo = CCValAssign::BCvt; 8452 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 8453 LocVT = MVT::i64; 8454 LocInfo = CCValAssign::BCvt; 8455 } 8456 8457 // If this is a variadic argument, the RISC-V calling convention requires 8458 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 8459 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 8460 // be used regardless of whether the original argument was split during 8461 // legalisation or not. The argument will not be passed by registers if the 8462 // original type is larger than 2*XLEN, so the register alignment rule does 8463 // not apply. 8464 unsigned TwoXLenInBytes = (2 * XLen) / 8; 8465 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 8466 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 8467 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 8468 // Skip 'odd' register if necessary. 8469 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 8470 State.AllocateReg(ArgGPRs); 8471 } 8472 8473 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 8474 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 8475 State.getPendingArgFlags(); 8476 8477 assert(PendingLocs.size() == PendingArgFlags.size() && 8478 "PendingLocs and PendingArgFlags out of sync"); 8479 8480 // Handle passing f64 on RV32D with a soft float ABI or when floating point 8481 // registers are exhausted. 8482 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 8483 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 8484 "Can't lower f64 if it is split"); 8485 // Depending on available argument GPRS, f64 may be passed in a pair of 8486 // GPRs, split between a GPR and the stack, or passed completely on the 8487 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 8488 // cases. 8489 Register Reg = State.AllocateReg(ArgGPRs); 8490 LocVT = MVT::i32; 8491 if (!Reg) { 8492 unsigned StackOffset = State.AllocateStack(8, Align(8)); 8493 State.addLoc( 8494 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8495 return false; 8496 } 8497 if (!State.AllocateReg(ArgGPRs)) 8498 State.AllocateStack(4, Align(4)); 8499 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8500 return false; 8501 } 8502 8503 // Fixed-length vectors are located in the corresponding scalable-vector 8504 // container types. 8505 if (ValVT.isFixedLengthVector()) 8506 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8507 8508 // Split arguments might be passed indirectly, so keep track of the pending 8509 // values. Split vectors are passed via a mix of registers and indirectly, so 8510 // treat them as we would any other argument. 8511 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 8512 LocVT = XLenVT; 8513 LocInfo = CCValAssign::Indirect; 8514 PendingLocs.push_back( 8515 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 8516 PendingArgFlags.push_back(ArgFlags); 8517 if (!ArgFlags.isSplitEnd()) { 8518 return false; 8519 } 8520 } 8521 8522 // If the split argument only had two elements, it should be passed directly 8523 // in registers or on the stack. 8524 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 8525 PendingLocs.size() <= 2) { 8526 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 8527 // Apply the normal calling convention rules to the first half of the 8528 // split argument. 8529 CCValAssign VA = PendingLocs[0]; 8530 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 8531 PendingLocs.clear(); 8532 PendingArgFlags.clear(); 8533 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 8534 ArgFlags); 8535 } 8536 8537 // Allocate to a register if possible, or else a stack slot. 8538 Register Reg; 8539 unsigned StoreSizeBytes = XLen / 8; 8540 Align StackAlign = Align(XLen / 8); 8541 8542 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 8543 Reg = State.AllocateReg(ArgFPR16s); 8544 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 8545 Reg = State.AllocateReg(ArgFPR32s); 8546 else if (ValVT == MVT::f64 && !UseGPRForF64) 8547 Reg = State.AllocateReg(ArgFPR64s); 8548 else if (ValVT.isVector()) { 8549 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 8550 if (!Reg) { 8551 // For return values, the vector must be passed fully via registers or 8552 // via the stack. 8553 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 8554 // but we're using all of them. 8555 if (IsRet) 8556 return true; 8557 // Try using a GPR to pass the address 8558 if ((Reg = State.AllocateReg(ArgGPRs))) { 8559 LocVT = XLenVT; 8560 LocInfo = CCValAssign::Indirect; 8561 } else if (ValVT.isScalableVector()) { 8562 LocVT = XLenVT; 8563 LocInfo = CCValAssign::Indirect; 8564 } else { 8565 // Pass fixed-length vectors on the stack. 8566 LocVT = ValVT; 8567 StoreSizeBytes = ValVT.getStoreSize(); 8568 // Align vectors to their element sizes, being careful for vXi1 8569 // vectors. 8570 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8571 } 8572 } 8573 } else { 8574 Reg = State.AllocateReg(ArgGPRs); 8575 } 8576 8577 unsigned StackOffset = 8578 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 8579 8580 // If we reach this point and PendingLocs is non-empty, we must be at the 8581 // end of a split argument that must be passed indirectly. 8582 if (!PendingLocs.empty()) { 8583 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 8584 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 8585 8586 for (auto &It : PendingLocs) { 8587 if (Reg) 8588 It.convertToReg(Reg); 8589 else 8590 It.convertToMem(StackOffset); 8591 State.addLoc(It); 8592 } 8593 PendingLocs.clear(); 8594 PendingArgFlags.clear(); 8595 return false; 8596 } 8597 8598 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 8599 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 8600 "Expected an XLenVT or vector types at this stage"); 8601 8602 if (Reg) { 8603 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8604 return false; 8605 } 8606 8607 // When a floating-point value is passed on the stack, no bit-conversion is 8608 // needed. 8609 if (ValVT.isFloatingPoint()) { 8610 LocVT = ValVT; 8611 LocInfo = CCValAssign::Full; 8612 } 8613 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8614 return false; 8615 } 8616 8617 template <typename ArgTy> 8618 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 8619 for (const auto &ArgIdx : enumerate(Args)) { 8620 MVT ArgVT = ArgIdx.value().VT; 8621 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 8622 return ArgIdx.index(); 8623 } 8624 return None; 8625 } 8626 8627 void RISCVTargetLowering::analyzeInputArgs( 8628 MachineFunction &MF, CCState &CCInfo, 8629 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 8630 RISCVCCAssignFn Fn) const { 8631 unsigned NumArgs = Ins.size(); 8632 FunctionType *FType = MF.getFunction().getFunctionType(); 8633 8634 Optional<unsigned> FirstMaskArgument; 8635 if (Subtarget.hasVInstructions()) 8636 FirstMaskArgument = preAssignMask(Ins); 8637 8638 for (unsigned i = 0; i != NumArgs; ++i) { 8639 MVT ArgVT = Ins[i].VT; 8640 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 8641 8642 Type *ArgTy = nullptr; 8643 if (IsRet) 8644 ArgTy = FType->getReturnType(); 8645 else if (Ins[i].isOrigArg()) 8646 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 8647 8648 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8649 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8650 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 8651 FirstMaskArgument)) { 8652 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 8653 << EVT(ArgVT).getEVTString() << '\n'); 8654 llvm_unreachable(nullptr); 8655 } 8656 } 8657 } 8658 8659 void RISCVTargetLowering::analyzeOutputArgs( 8660 MachineFunction &MF, CCState &CCInfo, 8661 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 8662 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 8663 unsigned NumArgs = Outs.size(); 8664 8665 Optional<unsigned> FirstMaskArgument; 8666 if (Subtarget.hasVInstructions()) 8667 FirstMaskArgument = preAssignMask(Outs); 8668 8669 for (unsigned i = 0; i != NumArgs; i++) { 8670 MVT ArgVT = Outs[i].VT; 8671 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 8672 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 8673 8674 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8675 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8676 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 8677 FirstMaskArgument)) { 8678 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 8679 << EVT(ArgVT).getEVTString() << "\n"); 8680 llvm_unreachable(nullptr); 8681 } 8682 } 8683 } 8684 8685 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 8686 // values. 8687 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 8688 const CCValAssign &VA, const SDLoc &DL, 8689 const RISCVSubtarget &Subtarget) { 8690 switch (VA.getLocInfo()) { 8691 default: 8692 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8693 case CCValAssign::Full: 8694 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 8695 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 8696 break; 8697 case CCValAssign::BCvt: 8698 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8699 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 8700 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8701 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 8702 else 8703 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 8704 break; 8705 } 8706 return Val; 8707 } 8708 8709 // The caller is responsible for loading the full value if the argument is 8710 // passed with CCValAssign::Indirect. 8711 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 8712 const CCValAssign &VA, const SDLoc &DL, 8713 const RISCVTargetLowering &TLI) { 8714 MachineFunction &MF = DAG.getMachineFunction(); 8715 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8716 EVT LocVT = VA.getLocVT(); 8717 SDValue Val; 8718 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 8719 Register VReg = RegInfo.createVirtualRegister(RC); 8720 RegInfo.addLiveIn(VA.getLocReg(), VReg); 8721 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 8722 8723 if (VA.getLocInfo() == CCValAssign::Indirect) 8724 return Val; 8725 8726 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 8727 } 8728 8729 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 8730 const CCValAssign &VA, const SDLoc &DL, 8731 const RISCVSubtarget &Subtarget) { 8732 EVT LocVT = VA.getLocVT(); 8733 8734 switch (VA.getLocInfo()) { 8735 default: 8736 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8737 case CCValAssign::Full: 8738 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 8739 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 8740 break; 8741 case CCValAssign::BCvt: 8742 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8743 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 8744 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8745 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 8746 else 8747 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 8748 break; 8749 } 8750 return Val; 8751 } 8752 8753 // The caller is responsible for loading the full value if the argument is 8754 // passed with CCValAssign::Indirect. 8755 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 8756 const CCValAssign &VA, const SDLoc &DL) { 8757 MachineFunction &MF = DAG.getMachineFunction(); 8758 MachineFrameInfo &MFI = MF.getFrameInfo(); 8759 EVT LocVT = VA.getLocVT(); 8760 EVT ValVT = VA.getValVT(); 8761 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 8762 if (ValVT.isScalableVector()) { 8763 // When the value is a scalable vector, we save the pointer which points to 8764 // the scalable vector value in the stack. The ValVT will be the pointer 8765 // type, instead of the scalable vector type. 8766 ValVT = LocVT; 8767 } 8768 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 8769 /*IsImmutable=*/true); 8770 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 8771 SDValue Val; 8772 8773 ISD::LoadExtType ExtType; 8774 switch (VA.getLocInfo()) { 8775 default: 8776 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8777 case CCValAssign::Full: 8778 case CCValAssign::Indirect: 8779 case CCValAssign::BCvt: 8780 ExtType = ISD::NON_EXTLOAD; 8781 break; 8782 } 8783 Val = DAG.getExtLoad( 8784 ExtType, DL, LocVT, Chain, FIN, 8785 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 8786 return Val; 8787 } 8788 8789 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 8790 const CCValAssign &VA, const SDLoc &DL) { 8791 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 8792 "Unexpected VA"); 8793 MachineFunction &MF = DAG.getMachineFunction(); 8794 MachineFrameInfo &MFI = MF.getFrameInfo(); 8795 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8796 8797 if (VA.isMemLoc()) { 8798 // f64 is passed on the stack. 8799 int FI = 8800 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 8801 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8802 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 8803 MachinePointerInfo::getFixedStack(MF, FI)); 8804 } 8805 8806 assert(VA.isRegLoc() && "Expected register VA assignment"); 8807 8808 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8809 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 8810 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 8811 SDValue Hi; 8812 if (VA.getLocReg() == RISCV::X17) { 8813 // Second half of f64 is passed on the stack. 8814 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 8815 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8816 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 8817 MachinePointerInfo::getFixedStack(MF, FI)); 8818 } else { 8819 // Second half of f64 is passed in another GPR. 8820 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8821 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 8822 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 8823 } 8824 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 8825 } 8826 8827 // FastCC has less than 1% performance improvement for some particular 8828 // benchmark. But theoretically, it may has benenfit for some cases. 8829 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 8830 unsigned ValNo, MVT ValVT, MVT LocVT, 8831 CCValAssign::LocInfo LocInfo, 8832 ISD::ArgFlagsTy ArgFlags, CCState &State, 8833 bool IsFixed, bool IsRet, Type *OrigTy, 8834 const RISCVTargetLowering &TLI, 8835 Optional<unsigned> FirstMaskArgument) { 8836 8837 // X5 and X6 might be used for save-restore libcall. 8838 static const MCPhysReg GPRList[] = { 8839 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 8840 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 8841 RISCV::X29, RISCV::X30, RISCV::X31}; 8842 8843 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8844 if (unsigned Reg = State.AllocateReg(GPRList)) { 8845 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8846 return false; 8847 } 8848 } 8849 8850 if (LocVT == MVT::f16) { 8851 static const MCPhysReg FPR16List[] = { 8852 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 8853 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 8854 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 8855 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 8856 if (unsigned Reg = State.AllocateReg(FPR16List)) { 8857 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8858 return false; 8859 } 8860 } 8861 8862 if (LocVT == MVT::f32) { 8863 static const MCPhysReg FPR32List[] = { 8864 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 8865 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 8866 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 8867 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 8868 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8869 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8870 return false; 8871 } 8872 } 8873 8874 if (LocVT == MVT::f64) { 8875 static const MCPhysReg FPR64List[] = { 8876 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 8877 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 8878 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 8879 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 8880 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8881 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8882 return false; 8883 } 8884 } 8885 8886 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 8887 unsigned Offset4 = State.AllocateStack(4, Align(4)); 8888 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 8889 return false; 8890 } 8891 8892 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 8893 unsigned Offset5 = State.AllocateStack(8, Align(8)); 8894 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 8895 return false; 8896 } 8897 8898 if (LocVT.isVector()) { 8899 if (unsigned Reg = 8900 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 8901 // Fixed-length vectors are located in the corresponding scalable-vector 8902 // container types. 8903 if (ValVT.isFixedLengthVector()) 8904 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8905 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8906 } else { 8907 // Try and pass the address via a "fast" GPR. 8908 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 8909 LocInfo = CCValAssign::Indirect; 8910 LocVT = TLI.getSubtarget().getXLenVT(); 8911 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 8912 } else if (ValVT.isFixedLengthVector()) { 8913 auto StackAlign = 8914 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8915 unsigned StackOffset = 8916 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 8917 State.addLoc( 8918 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8919 } else { 8920 // Can't pass scalable vectors on the stack. 8921 return true; 8922 } 8923 } 8924 8925 return false; 8926 } 8927 8928 return true; // CC didn't match. 8929 } 8930 8931 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 8932 CCValAssign::LocInfo LocInfo, 8933 ISD::ArgFlagsTy ArgFlags, CCState &State) { 8934 8935 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8936 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 8937 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 8938 static const MCPhysReg GPRList[] = { 8939 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 8940 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 8941 if (unsigned Reg = State.AllocateReg(GPRList)) { 8942 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8943 return false; 8944 } 8945 } 8946 8947 if (LocVT == MVT::f32) { 8948 // Pass in STG registers: F1, ..., F6 8949 // fs0 ... fs5 8950 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 8951 RISCV::F18_F, RISCV::F19_F, 8952 RISCV::F20_F, RISCV::F21_F}; 8953 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8954 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8955 return false; 8956 } 8957 } 8958 8959 if (LocVT == MVT::f64) { 8960 // Pass in STG registers: D1, ..., D6 8961 // fs6 ... fs11 8962 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 8963 RISCV::F24_D, RISCV::F25_D, 8964 RISCV::F26_D, RISCV::F27_D}; 8965 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8966 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8967 return false; 8968 } 8969 } 8970 8971 report_fatal_error("No registers left in GHC calling convention"); 8972 return true; 8973 } 8974 8975 // Transform physical registers into virtual registers. 8976 SDValue RISCVTargetLowering::LowerFormalArguments( 8977 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 8978 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 8979 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 8980 8981 MachineFunction &MF = DAG.getMachineFunction(); 8982 8983 switch (CallConv) { 8984 default: 8985 report_fatal_error("Unsupported calling convention"); 8986 case CallingConv::C: 8987 case CallingConv::Fast: 8988 break; 8989 case CallingConv::GHC: 8990 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 8991 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 8992 report_fatal_error( 8993 "GHC calling convention requires the F and D instruction set extensions"); 8994 } 8995 8996 const Function &Func = MF.getFunction(); 8997 if (Func.hasFnAttribute("interrupt")) { 8998 if (!Func.arg_empty()) 8999 report_fatal_error( 9000 "Functions with the interrupt attribute cannot have arguments!"); 9001 9002 StringRef Kind = 9003 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9004 9005 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 9006 report_fatal_error( 9007 "Function interrupt attribute argument not supported!"); 9008 } 9009 9010 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9011 MVT XLenVT = Subtarget.getXLenVT(); 9012 unsigned XLenInBytes = Subtarget.getXLen() / 8; 9013 // Used with vargs to acumulate store chains. 9014 std::vector<SDValue> OutChains; 9015 9016 // Assign locations to all of the incoming arguments. 9017 SmallVector<CCValAssign, 16> ArgLocs; 9018 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9019 9020 if (CallConv == CallingConv::GHC) 9021 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 9022 else 9023 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 9024 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9025 : CC_RISCV); 9026 9027 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 9028 CCValAssign &VA = ArgLocs[i]; 9029 SDValue ArgValue; 9030 // Passing f64 on RV32D with a soft float ABI must be handled as a special 9031 // case. 9032 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 9033 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 9034 else if (VA.isRegLoc()) 9035 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 9036 else 9037 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 9038 9039 if (VA.getLocInfo() == CCValAssign::Indirect) { 9040 // If the original argument was split and passed by reference (e.g. i128 9041 // on RV32), we need to load all parts of it here (using the same 9042 // address). Vectors may be partly split to registers and partly to the 9043 // stack, in which case the base address is partly offset and subsequent 9044 // stores are relative to that. 9045 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 9046 MachinePointerInfo())); 9047 unsigned ArgIndex = Ins[i].OrigArgIndex; 9048 unsigned ArgPartOffset = Ins[i].PartOffset; 9049 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9050 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 9051 CCValAssign &PartVA = ArgLocs[i + 1]; 9052 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 9053 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9054 if (PartVA.getValVT().isScalableVector()) 9055 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9056 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 9057 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 9058 MachinePointerInfo())); 9059 ++i; 9060 } 9061 continue; 9062 } 9063 InVals.push_back(ArgValue); 9064 } 9065 9066 if (IsVarArg) { 9067 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 9068 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 9069 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 9070 MachineFrameInfo &MFI = MF.getFrameInfo(); 9071 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9072 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 9073 9074 // Offset of the first variable argument from stack pointer, and size of 9075 // the vararg save area. For now, the varargs save area is either zero or 9076 // large enough to hold a0-a7. 9077 int VaArgOffset, VarArgsSaveSize; 9078 9079 // If all registers are allocated, then all varargs must be passed on the 9080 // stack and we don't need to save any argregs. 9081 if (ArgRegs.size() == Idx) { 9082 VaArgOffset = CCInfo.getNextStackOffset(); 9083 VarArgsSaveSize = 0; 9084 } else { 9085 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 9086 VaArgOffset = -VarArgsSaveSize; 9087 } 9088 9089 // Record the frame index of the first variable argument 9090 // which is a value necessary to VASTART. 9091 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9092 RVFI->setVarArgsFrameIndex(FI); 9093 9094 // If saving an odd number of registers then create an extra stack slot to 9095 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 9096 // offsets to even-numbered registered remain 2*XLEN-aligned. 9097 if (Idx % 2) { 9098 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 9099 VarArgsSaveSize += XLenInBytes; 9100 } 9101 9102 // Copy the integer registers that may have been used for passing varargs 9103 // to the vararg save area. 9104 for (unsigned I = Idx; I < ArgRegs.size(); 9105 ++I, VaArgOffset += XLenInBytes) { 9106 const Register Reg = RegInfo.createVirtualRegister(RC); 9107 RegInfo.addLiveIn(ArgRegs[I], Reg); 9108 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 9109 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9110 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9111 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 9112 MachinePointerInfo::getFixedStack(MF, FI)); 9113 cast<StoreSDNode>(Store.getNode()) 9114 ->getMemOperand() 9115 ->setValue((Value *)nullptr); 9116 OutChains.push_back(Store); 9117 } 9118 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 9119 } 9120 9121 // All stores are grouped in one node to allow the matching between 9122 // the size of Ins and InVals. This only happens for vararg functions. 9123 if (!OutChains.empty()) { 9124 OutChains.push_back(Chain); 9125 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 9126 } 9127 9128 return Chain; 9129 } 9130 9131 /// isEligibleForTailCallOptimization - Check whether the call is eligible 9132 /// for tail call optimization. 9133 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 9134 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 9135 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 9136 const SmallVector<CCValAssign, 16> &ArgLocs) const { 9137 9138 auto &Callee = CLI.Callee; 9139 auto CalleeCC = CLI.CallConv; 9140 auto &Outs = CLI.Outs; 9141 auto &Caller = MF.getFunction(); 9142 auto CallerCC = Caller.getCallingConv(); 9143 9144 // Exception-handling functions need a special set of instructions to 9145 // indicate a return to the hardware. Tail-calling another function would 9146 // probably break this. 9147 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 9148 // should be expanded as new function attributes are introduced. 9149 if (Caller.hasFnAttribute("interrupt")) 9150 return false; 9151 9152 // Do not tail call opt if the stack is used to pass parameters. 9153 if (CCInfo.getNextStackOffset() != 0) 9154 return false; 9155 9156 // Do not tail call opt if any parameters need to be passed indirectly. 9157 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 9158 // passed indirectly. So the address of the value will be passed in a 9159 // register, or if not available, then the address is put on the stack. In 9160 // order to pass indirectly, space on the stack often needs to be allocated 9161 // in order to store the value. In this case the CCInfo.getNextStackOffset() 9162 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 9163 // are passed CCValAssign::Indirect. 9164 for (auto &VA : ArgLocs) 9165 if (VA.getLocInfo() == CCValAssign::Indirect) 9166 return false; 9167 9168 // Do not tail call opt if either caller or callee uses struct return 9169 // semantics. 9170 auto IsCallerStructRet = Caller.hasStructRetAttr(); 9171 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 9172 if (IsCallerStructRet || IsCalleeStructRet) 9173 return false; 9174 9175 // Externally-defined functions with weak linkage should not be 9176 // tail-called. The behaviour of branch instructions in this situation (as 9177 // used for tail calls) is implementation-defined, so we cannot rely on the 9178 // linker replacing the tail call with a return. 9179 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 9180 const GlobalValue *GV = G->getGlobal(); 9181 if (GV->hasExternalWeakLinkage()) 9182 return false; 9183 } 9184 9185 // The callee has to preserve all registers the caller needs to preserve. 9186 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9187 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 9188 if (CalleeCC != CallerCC) { 9189 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 9190 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 9191 return false; 9192 } 9193 9194 // Byval parameters hand the function a pointer directly into the stack area 9195 // we want to reuse during a tail call. Working around this *is* possible 9196 // but less efficient and uglier in LowerCall. 9197 for (auto &Arg : Outs) 9198 if (Arg.Flags.isByVal()) 9199 return false; 9200 9201 return true; 9202 } 9203 9204 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 9205 return DAG.getDataLayout().getPrefTypeAlign( 9206 VT.getTypeForEVT(*DAG.getContext())); 9207 } 9208 9209 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 9210 // and output parameter nodes. 9211 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 9212 SmallVectorImpl<SDValue> &InVals) const { 9213 SelectionDAG &DAG = CLI.DAG; 9214 SDLoc &DL = CLI.DL; 9215 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 9216 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 9217 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 9218 SDValue Chain = CLI.Chain; 9219 SDValue Callee = CLI.Callee; 9220 bool &IsTailCall = CLI.IsTailCall; 9221 CallingConv::ID CallConv = CLI.CallConv; 9222 bool IsVarArg = CLI.IsVarArg; 9223 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9224 MVT XLenVT = Subtarget.getXLenVT(); 9225 9226 MachineFunction &MF = DAG.getMachineFunction(); 9227 9228 // Analyze the operands of the call, assigning locations to each operand. 9229 SmallVector<CCValAssign, 16> ArgLocs; 9230 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9231 9232 if (CallConv == CallingConv::GHC) 9233 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 9234 else 9235 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 9236 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9237 : CC_RISCV); 9238 9239 // Check if it's really possible to do a tail call. 9240 if (IsTailCall) 9241 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 9242 9243 if (IsTailCall) 9244 ++NumTailCalls; 9245 else if (CLI.CB && CLI.CB->isMustTailCall()) 9246 report_fatal_error("failed to perform tail call elimination on a call " 9247 "site marked musttail"); 9248 9249 // Get a count of how many bytes are to be pushed on the stack. 9250 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 9251 9252 // Create local copies for byval args 9253 SmallVector<SDValue, 8> ByValArgs; 9254 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9255 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9256 if (!Flags.isByVal()) 9257 continue; 9258 9259 SDValue Arg = OutVals[i]; 9260 unsigned Size = Flags.getByValSize(); 9261 Align Alignment = Flags.getNonZeroByValAlign(); 9262 9263 int FI = 9264 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 9265 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9266 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 9267 9268 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 9269 /*IsVolatile=*/false, 9270 /*AlwaysInline=*/false, IsTailCall, 9271 MachinePointerInfo(), MachinePointerInfo()); 9272 ByValArgs.push_back(FIPtr); 9273 } 9274 9275 if (!IsTailCall) 9276 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 9277 9278 // Copy argument values to their designated locations. 9279 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 9280 SmallVector<SDValue, 8> MemOpChains; 9281 SDValue StackPtr; 9282 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 9283 CCValAssign &VA = ArgLocs[i]; 9284 SDValue ArgValue = OutVals[i]; 9285 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9286 9287 // Handle passing f64 on RV32D with a soft float ABI as a special case. 9288 bool IsF64OnRV32DSoftABI = 9289 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 9290 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 9291 SDValue SplitF64 = DAG.getNode( 9292 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 9293 SDValue Lo = SplitF64.getValue(0); 9294 SDValue Hi = SplitF64.getValue(1); 9295 9296 Register RegLo = VA.getLocReg(); 9297 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 9298 9299 if (RegLo == RISCV::X17) { 9300 // Second half of f64 is passed on the stack. 9301 // Work out the address of the stack slot. 9302 if (!StackPtr.getNode()) 9303 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9304 // Emit the store. 9305 MemOpChains.push_back( 9306 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 9307 } else { 9308 // Second half of f64 is passed in another GPR. 9309 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9310 Register RegHigh = RegLo + 1; 9311 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 9312 } 9313 continue; 9314 } 9315 9316 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 9317 // as any other MemLoc. 9318 9319 // Promote the value if needed. 9320 // For now, only handle fully promoted and indirect arguments. 9321 if (VA.getLocInfo() == CCValAssign::Indirect) { 9322 // Store the argument in a stack slot and pass its address. 9323 Align StackAlign = 9324 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 9325 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 9326 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 9327 // If the original argument was split (e.g. i128), we need 9328 // to store the required parts of it here (and pass just one address). 9329 // Vectors may be partly split to registers and partly to the stack, in 9330 // which case the base address is partly offset and subsequent stores are 9331 // relative to that. 9332 unsigned ArgIndex = Outs[i].OrigArgIndex; 9333 unsigned ArgPartOffset = Outs[i].PartOffset; 9334 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9335 // Calculate the total size to store. We don't have access to what we're 9336 // actually storing other than performing the loop and collecting the 9337 // info. 9338 SmallVector<std::pair<SDValue, SDValue>> Parts; 9339 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 9340 SDValue PartValue = OutVals[i + 1]; 9341 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 9342 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9343 EVT PartVT = PartValue.getValueType(); 9344 if (PartVT.isScalableVector()) 9345 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9346 StoredSize += PartVT.getStoreSize(); 9347 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 9348 Parts.push_back(std::make_pair(PartValue, Offset)); 9349 ++i; 9350 } 9351 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 9352 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 9353 MemOpChains.push_back( 9354 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 9355 MachinePointerInfo::getFixedStack(MF, FI))); 9356 for (const auto &Part : Parts) { 9357 SDValue PartValue = Part.first; 9358 SDValue PartOffset = Part.second; 9359 SDValue Address = 9360 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 9361 MemOpChains.push_back( 9362 DAG.getStore(Chain, DL, PartValue, Address, 9363 MachinePointerInfo::getFixedStack(MF, FI))); 9364 } 9365 ArgValue = SpillSlot; 9366 } else { 9367 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 9368 } 9369 9370 // Use local copy if it is a byval arg. 9371 if (Flags.isByVal()) 9372 ArgValue = ByValArgs[j++]; 9373 9374 if (VA.isRegLoc()) { 9375 // Queue up the argument copies and emit them at the end. 9376 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 9377 } else { 9378 assert(VA.isMemLoc() && "Argument not register or memory"); 9379 assert(!IsTailCall && "Tail call not allowed if stack is used " 9380 "for passing parameters"); 9381 9382 // Work out the address of the stack slot. 9383 if (!StackPtr.getNode()) 9384 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9385 SDValue Address = 9386 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 9387 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 9388 9389 // Emit the store. 9390 MemOpChains.push_back( 9391 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 9392 } 9393 } 9394 9395 // Join the stores, which are independent of one another. 9396 if (!MemOpChains.empty()) 9397 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 9398 9399 SDValue Glue; 9400 9401 // Build a sequence of copy-to-reg nodes, chained and glued together. 9402 for (auto &Reg : RegsToPass) { 9403 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 9404 Glue = Chain.getValue(1); 9405 } 9406 9407 // Validate that none of the argument registers have been marked as 9408 // reserved, if so report an error. Do the same for the return address if this 9409 // is not a tailcall. 9410 validateCCReservedRegs(RegsToPass, MF); 9411 if (!IsTailCall && 9412 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 9413 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9414 MF.getFunction(), 9415 "Return address register required, but has been reserved."}); 9416 9417 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 9418 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 9419 // split it and then direct call can be matched by PseudoCALL. 9420 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 9421 const GlobalValue *GV = S->getGlobal(); 9422 9423 unsigned OpFlags = RISCVII::MO_CALL; 9424 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 9425 OpFlags = RISCVII::MO_PLT; 9426 9427 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 9428 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 9429 unsigned OpFlags = RISCVII::MO_CALL; 9430 9431 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 9432 nullptr)) 9433 OpFlags = RISCVII::MO_PLT; 9434 9435 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 9436 } 9437 9438 // The first call operand is the chain and the second is the target address. 9439 SmallVector<SDValue, 8> Ops; 9440 Ops.push_back(Chain); 9441 Ops.push_back(Callee); 9442 9443 // Add argument registers to the end of the list so that they are 9444 // known live into the call. 9445 for (auto &Reg : RegsToPass) 9446 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 9447 9448 if (!IsTailCall) { 9449 // Add a register mask operand representing the call-preserved registers. 9450 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9451 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 9452 assert(Mask && "Missing call preserved mask for calling convention"); 9453 Ops.push_back(DAG.getRegisterMask(Mask)); 9454 } 9455 9456 // Glue the call to the argument copies, if any. 9457 if (Glue.getNode()) 9458 Ops.push_back(Glue); 9459 9460 // Emit the call. 9461 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9462 9463 if (IsTailCall) { 9464 MF.getFrameInfo().setHasTailCall(); 9465 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 9466 } 9467 9468 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 9469 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 9470 Glue = Chain.getValue(1); 9471 9472 // Mark the end of the call, which is glued to the call itself. 9473 Chain = DAG.getCALLSEQ_END(Chain, 9474 DAG.getConstant(NumBytes, DL, PtrVT, true), 9475 DAG.getConstant(0, DL, PtrVT, true), 9476 Glue, DL); 9477 Glue = Chain.getValue(1); 9478 9479 // Assign locations to each value returned by this call. 9480 SmallVector<CCValAssign, 16> RVLocs; 9481 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 9482 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 9483 9484 // Copy all of the result registers out of their specified physreg. 9485 for (auto &VA : RVLocs) { 9486 // Copy the value out 9487 SDValue RetValue = 9488 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 9489 // Glue the RetValue to the end of the call sequence 9490 Chain = RetValue.getValue(1); 9491 Glue = RetValue.getValue(2); 9492 9493 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9494 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 9495 SDValue RetValue2 = 9496 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 9497 Chain = RetValue2.getValue(1); 9498 Glue = RetValue2.getValue(2); 9499 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 9500 RetValue2); 9501 } 9502 9503 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 9504 9505 InVals.push_back(RetValue); 9506 } 9507 9508 return Chain; 9509 } 9510 9511 bool RISCVTargetLowering::CanLowerReturn( 9512 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 9513 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 9514 SmallVector<CCValAssign, 16> RVLocs; 9515 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 9516 9517 Optional<unsigned> FirstMaskArgument; 9518 if (Subtarget.hasVInstructions()) 9519 FirstMaskArgument = preAssignMask(Outs); 9520 9521 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9522 MVT VT = Outs[i].VT; 9523 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9524 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9525 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 9526 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 9527 *this, FirstMaskArgument)) 9528 return false; 9529 } 9530 return true; 9531 } 9532 9533 SDValue 9534 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 9535 bool IsVarArg, 9536 const SmallVectorImpl<ISD::OutputArg> &Outs, 9537 const SmallVectorImpl<SDValue> &OutVals, 9538 const SDLoc &DL, SelectionDAG &DAG) const { 9539 const MachineFunction &MF = DAG.getMachineFunction(); 9540 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9541 9542 // Stores the assignment of the return value to a location. 9543 SmallVector<CCValAssign, 16> RVLocs; 9544 9545 // Info about the registers and stack slot. 9546 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 9547 *DAG.getContext()); 9548 9549 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 9550 nullptr, CC_RISCV); 9551 9552 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 9553 report_fatal_error("GHC functions return void only"); 9554 9555 SDValue Glue; 9556 SmallVector<SDValue, 4> RetOps(1, Chain); 9557 9558 // Copy the result values into the output registers. 9559 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 9560 SDValue Val = OutVals[i]; 9561 CCValAssign &VA = RVLocs[i]; 9562 assert(VA.isRegLoc() && "Can only return in registers!"); 9563 9564 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9565 // Handle returning f64 on RV32D with a soft float ABI. 9566 assert(VA.isRegLoc() && "Expected return via registers"); 9567 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 9568 DAG.getVTList(MVT::i32, MVT::i32), Val); 9569 SDValue Lo = SplitF64.getValue(0); 9570 SDValue Hi = SplitF64.getValue(1); 9571 Register RegLo = VA.getLocReg(); 9572 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9573 Register RegHi = RegLo + 1; 9574 9575 if (STI.isRegisterReservedByUser(RegLo) || 9576 STI.isRegisterReservedByUser(RegHi)) 9577 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9578 MF.getFunction(), 9579 "Return value register required, but has been reserved."}); 9580 9581 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 9582 Glue = Chain.getValue(1); 9583 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 9584 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 9585 Glue = Chain.getValue(1); 9586 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 9587 } else { 9588 // Handle a 'normal' return. 9589 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 9590 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 9591 9592 if (STI.isRegisterReservedByUser(VA.getLocReg())) 9593 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9594 MF.getFunction(), 9595 "Return value register required, but has been reserved."}); 9596 9597 // Guarantee that all emitted copies are stuck together. 9598 Glue = Chain.getValue(1); 9599 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 9600 } 9601 } 9602 9603 RetOps[0] = Chain; // Update chain. 9604 9605 // Add the glue node if we have it. 9606 if (Glue.getNode()) { 9607 RetOps.push_back(Glue); 9608 } 9609 9610 unsigned RetOpc = RISCVISD::RET_FLAG; 9611 // Interrupt service routines use different return instructions. 9612 const Function &Func = DAG.getMachineFunction().getFunction(); 9613 if (Func.hasFnAttribute("interrupt")) { 9614 if (!Func.getReturnType()->isVoidTy()) 9615 report_fatal_error( 9616 "Functions with the interrupt attribute must have void return type!"); 9617 9618 MachineFunction &MF = DAG.getMachineFunction(); 9619 StringRef Kind = 9620 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9621 9622 if (Kind == "user") 9623 RetOpc = RISCVISD::URET_FLAG; 9624 else if (Kind == "supervisor") 9625 RetOpc = RISCVISD::SRET_FLAG; 9626 else 9627 RetOpc = RISCVISD::MRET_FLAG; 9628 } 9629 9630 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 9631 } 9632 9633 void RISCVTargetLowering::validateCCReservedRegs( 9634 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 9635 MachineFunction &MF) const { 9636 const Function &F = MF.getFunction(); 9637 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9638 9639 if (llvm::any_of(Regs, [&STI](auto Reg) { 9640 return STI.isRegisterReservedByUser(Reg.first); 9641 })) 9642 F.getContext().diagnose(DiagnosticInfoUnsupported{ 9643 F, "Argument register required, but has been reserved."}); 9644 } 9645 9646 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 9647 return CI->isTailCall(); 9648 } 9649 9650 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 9651 #define NODE_NAME_CASE(NODE) \ 9652 case RISCVISD::NODE: \ 9653 return "RISCVISD::" #NODE; 9654 // clang-format off 9655 switch ((RISCVISD::NodeType)Opcode) { 9656 case RISCVISD::FIRST_NUMBER: 9657 break; 9658 NODE_NAME_CASE(RET_FLAG) 9659 NODE_NAME_CASE(URET_FLAG) 9660 NODE_NAME_CASE(SRET_FLAG) 9661 NODE_NAME_CASE(MRET_FLAG) 9662 NODE_NAME_CASE(CALL) 9663 NODE_NAME_CASE(SELECT_CC) 9664 NODE_NAME_CASE(BR_CC) 9665 NODE_NAME_CASE(BuildPairF64) 9666 NODE_NAME_CASE(SplitF64) 9667 NODE_NAME_CASE(TAIL) 9668 NODE_NAME_CASE(MULHSU) 9669 NODE_NAME_CASE(SLLW) 9670 NODE_NAME_CASE(SRAW) 9671 NODE_NAME_CASE(SRLW) 9672 NODE_NAME_CASE(DIVW) 9673 NODE_NAME_CASE(DIVUW) 9674 NODE_NAME_CASE(REMUW) 9675 NODE_NAME_CASE(ROLW) 9676 NODE_NAME_CASE(RORW) 9677 NODE_NAME_CASE(CLZW) 9678 NODE_NAME_CASE(CTZW) 9679 NODE_NAME_CASE(FSLW) 9680 NODE_NAME_CASE(FSRW) 9681 NODE_NAME_CASE(FSL) 9682 NODE_NAME_CASE(FSR) 9683 NODE_NAME_CASE(FMV_H_X) 9684 NODE_NAME_CASE(FMV_X_ANYEXTH) 9685 NODE_NAME_CASE(FMV_W_X_RV64) 9686 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 9687 NODE_NAME_CASE(FCVT_X) 9688 NODE_NAME_CASE(FCVT_XU) 9689 NODE_NAME_CASE(FCVT_W_RV64) 9690 NODE_NAME_CASE(FCVT_WU_RV64) 9691 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 9692 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 9693 NODE_NAME_CASE(READ_CYCLE_WIDE) 9694 NODE_NAME_CASE(GREV) 9695 NODE_NAME_CASE(GREVW) 9696 NODE_NAME_CASE(GORC) 9697 NODE_NAME_CASE(GORCW) 9698 NODE_NAME_CASE(SHFL) 9699 NODE_NAME_CASE(SHFLW) 9700 NODE_NAME_CASE(UNSHFL) 9701 NODE_NAME_CASE(UNSHFLW) 9702 NODE_NAME_CASE(BCOMPRESS) 9703 NODE_NAME_CASE(BCOMPRESSW) 9704 NODE_NAME_CASE(BDECOMPRESS) 9705 NODE_NAME_CASE(BDECOMPRESSW) 9706 NODE_NAME_CASE(VMV_V_X_VL) 9707 NODE_NAME_CASE(VFMV_V_F_VL) 9708 NODE_NAME_CASE(VMV_X_S) 9709 NODE_NAME_CASE(VMV_S_X_VL) 9710 NODE_NAME_CASE(VFMV_S_F_VL) 9711 NODE_NAME_CASE(SPLAT_VECTOR_I64) 9712 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 9713 NODE_NAME_CASE(READ_VLENB) 9714 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 9715 NODE_NAME_CASE(VSLIDEUP_VL) 9716 NODE_NAME_CASE(VSLIDE1UP_VL) 9717 NODE_NAME_CASE(VSLIDEDOWN_VL) 9718 NODE_NAME_CASE(VSLIDE1DOWN_VL) 9719 NODE_NAME_CASE(VID_VL) 9720 NODE_NAME_CASE(VFNCVT_ROD_VL) 9721 NODE_NAME_CASE(VECREDUCE_ADD_VL) 9722 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 9723 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 9724 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 9725 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 9726 NODE_NAME_CASE(VECREDUCE_AND_VL) 9727 NODE_NAME_CASE(VECREDUCE_OR_VL) 9728 NODE_NAME_CASE(VECREDUCE_XOR_VL) 9729 NODE_NAME_CASE(VECREDUCE_FADD_VL) 9730 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 9731 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 9732 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 9733 NODE_NAME_CASE(ADD_VL) 9734 NODE_NAME_CASE(AND_VL) 9735 NODE_NAME_CASE(MUL_VL) 9736 NODE_NAME_CASE(OR_VL) 9737 NODE_NAME_CASE(SDIV_VL) 9738 NODE_NAME_CASE(SHL_VL) 9739 NODE_NAME_CASE(SREM_VL) 9740 NODE_NAME_CASE(SRA_VL) 9741 NODE_NAME_CASE(SRL_VL) 9742 NODE_NAME_CASE(SUB_VL) 9743 NODE_NAME_CASE(UDIV_VL) 9744 NODE_NAME_CASE(UREM_VL) 9745 NODE_NAME_CASE(XOR_VL) 9746 NODE_NAME_CASE(SADDSAT_VL) 9747 NODE_NAME_CASE(UADDSAT_VL) 9748 NODE_NAME_CASE(SSUBSAT_VL) 9749 NODE_NAME_CASE(USUBSAT_VL) 9750 NODE_NAME_CASE(FADD_VL) 9751 NODE_NAME_CASE(FSUB_VL) 9752 NODE_NAME_CASE(FMUL_VL) 9753 NODE_NAME_CASE(FDIV_VL) 9754 NODE_NAME_CASE(FNEG_VL) 9755 NODE_NAME_CASE(FABS_VL) 9756 NODE_NAME_CASE(FSQRT_VL) 9757 NODE_NAME_CASE(FMA_VL) 9758 NODE_NAME_CASE(FCOPYSIGN_VL) 9759 NODE_NAME_CASE(SMIN_VL) 9760 NODE_NAME_CASE(SMAX_VL) 9761 NODE_NAME_CASE(UMIN_VL) 9762 NODE_NAME_CASE(UMAX_VL) 9763 NODE_NAME_CASE(FMINNUM_VL) 9764 NODE_NAME_CASE(FMAXNUM_VL) 9765 NODE_NAME_CASE(MULHS_VL) 9766 NODE_NAME_CASE(MULHU_VL) 9767 NODE_NAME_CASE(FP_TO_SINT_VL) 9768 NODE_NAME_CASE(FP_TO_UINT_VL) 9769 NODE_NAME_CASE(SINT_TO_FP_VL) 9770 NODE_NAME_CASE(UINT_TO_FP_VL) 9771 NODE_NAME_CASE(FP_EXTEND_VL) 9772 NODE_NAME_CASE(FP_ROUND_VL) 9773 NODE_NAME_CASE(VWMUL_VL) 9774 NODE_NAME_CASE(VWMULU_VL) 9775 NODE_NAME_CASE(SETCC_VL) 9776 NODE_NAME_CASE(VSELECT_VL) 9777 NODE_NAME_CASE(VMAND_VL) 9778 NODE_NAME_CASE(VMOR_VL) 9779 NODE_NAME_CASE(VMXOR_VL) 9780 NODE_NAME_CASE(VMCLR_VL) 9781 NODE_NAME_CASE(VMSET_VL) 9782 NODE_NAME_CASE(VRGATHER_VX_VL) 9783 NODE_NAME_CASE(VRGATHER_VV_VL) 9784 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 9785 NODE_NAME_CASE(VSEXT_VL) 9786 NODE_NAME_CASE(VZEXT_VL) 9787 NODE_NAME_CASE(VCPOP_VL) 9788 NODE_NAME_CASE(VLE_VL) 9789 NODE_NAME_CASE(VSE_VL) 9790 NODE_NAME_CASE(READ_CSR) 9791 NODE_NAME_CASE(WRITE_CSR) 9792 NODE_NAME_CASE(SWAP_CSR) 9793 } 9794 // clang-format on 9795 return nullptr; 9796 #undef NODE_NAME_CASE 9797 } 9798 9799 /// getConstraintType - Given a constraint letter, return the type of 9800 /// constraint it is for this target. 9801 RISCVTargetLowering::ConstraintType 9802 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 9803 if (Constraint.size() == 1) { 9804 switch (Constraint[0]) { 9805 default: 9806 break; 9807 case 'f': 9808 return C_RegisterClass; 9809 case 'I': 9810 case 'J': 9811 case 'K': 9812 return C_Immediate; 9813 case 'A': 9814 return C_Memory; 9815 case 'S': // A symbolic address 9816 return C_Other; 9817 } 9818 } else { 9819 if (Constraint == "vr" || Constraint == "vm") 9820 return C_RegisterClass; 9821 } 9822 return TargetLowering::getConstraintType(Constraint); 9823 } 9824 9825 std::pair<unsigned, const TargetRegisterClass *> 9826 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 9827 StringRef Constraint, 9828 MVT VT) const { 9829 // First, see if this is a constraint that directly corresponds to a 9830 // RISCV register class. 9831 if (Constraint.size() == 1) { 9832 switch (Constraint[0]) { 9833 case 'r': 9834 // TODO: Support fixed vectors up to XLen for P extension? 9835 if (VT.isVector()) 9836 break; 9837 return std::make_pair(0U, &RISCV::GPRRegClass); 9838 case 'f': 9839 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 9840 return std::make_pair(0U, &RISCV::FPR16RegClass); 9841 if (Subtarget.hasStdExtF() && VT == MVT::f32) 9842 return std::make_pair(0U, &RISCV::FPR32RegClass); 9843 if (Subtarget.hasStdExtD() && VT == MVT::f64) 9844 return std::make_pair(0U, &RISCV::FPR64RegClass); 9845 break; 9846 default: 9847 break; 9848 } 9849 } else if (Constraint == "vr") { 9850 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 9851 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9852 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 9853 return std::make_pair(0U, RC); 9854 } 9855 } else if (Constraint == "vm") { 9856 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 9857 return std::make_pair(0U, &RISCV::VMV0RegClass); 9858 } 9859 9860 // Clang will correctly decode the usage of register name aliases into their 9861 // official names. However, other frontends like `rustc` do not. This allows 9862 // users of these frontends to use the ABI names for registers in LLVM-style 9863 // register constraints. 9864 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 9865 .Case("{zero}", RISCV::X0) 9866 .Case("{ra}", RISCV::X1) 9867 .Case("{sp}", RISCV::X2) 9868 .Case("{gp}", RISCV::X3) 9869 .Case("{tp}", RISCV::X4) 9870 .Case("{t0}", RISCV::X5) 9871 .Case("{t1}", RISCV::X6) 9872 .Case("{t2}", RISCV::X7) 9873 .Cases("{s0}", "{fp}", RISCV::X8) 9874 .Case("{s1}", RISCV::X9) 9875 .Case("{a0}", RISCV::X10) 9876 .Case("{a1}", RISCV::X11) 9877 .Case("{a2}", RISCV::X12) 9878 .Case("{a3}", RISCV::X13) 9879 .Case("{a4}", RISCV::X14) 9880 .Case("{a5}", RISCV::X15) 9881 .Case("{a6}", RISCV::X16) 9882 .Case("{a7}", RISCV::X17) 9883 .Case("{s2}", RISCV::X18) 9884 .Case("{s3}", RISCV::X19) 9885 .Case("{s4}", RISCV::X20) 9886 .Case("{s5}", RISCV::X21) 9887 .Case("{s6}", RISCV::X22) 9888 .Case("{s7}", RISCV::X23) 9889 .Case("{s8}", RISCV::X24) 9890 .Case("{s9}", RISCV::X25) 9891 .Case("{s10}", RISCV::X26) 9892 .Case("{s11}", RISCV::X27) 9893 .Case("{t3}", RISCV::X28) 9894 .Case("{t4}", RISCV::X29) 9895 .Case("{t5}", RISCV::X30) 9896 .Case("{t6}", RISCV::X31) 9897 .Default(RISCV::NoRegister); 9898 if (XRegFromAlias != RISCV::NoRegister) 9899 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 9900 9901 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 9902 // TableGen record rather than the AsmName to choose registers for InlineAsm 9903 // constraints, plus we want to match those names to the widest floating point 9904 // register type available, manually select floating point registers here. 9905 // 9906 // The second case is the ABI name of the register, so that frontends can also 9907 // use the ABI names in register constraint lists. 9908 if (Subtarget.hasStdExtF()) { 9909 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 9910 .Cases("{f0}", "{ft0}", RISCV::F0_F) 9911 .Cases("{f1}", "{ft1}", RISCV::F1_F) 9912 .Cases("{f2}", "{ft2}", RISCV::F2_F) 9913 .Cases("{f3}", "{ft3}", RISCV::F3_F) 9914 .Cases("{f4}", "{ft4}", RISCV::F4_F) 9915 .Cases("{f5}", "{ft5}", RISCV::F5_F) 9916 .Cases("{f6}", "{ft6}", RISCV::F6_F) 9917 .Cases("{f7}", "{ft7}", RISCV::F7_F) 9918 .Cases("{f8}", "{fs0}", RISCV::F8_F) 9919 .Cases("{f9}", "{fs1}", RISCV::F9_F) 9920 .Cases("{f10}", "{fa0}", RISCV::F10_F) 9921 .Cases("{f11}", "{fa1}", RISCV::F11_F) 9922 .Cases("{f12}", "{fa2}", RISCV::F12_F) 9923 .Cases("{f13}", "{fa3}", RISCV::F13_F) 9924 .Cases("{f14}", "{fa4}", RISCV::F14_F) 9925 .Cases("{f15}", "{fa5}", RISCV::F15_F) 9926 .Cases("{f16}", "{fa6}", RISCV::F16_F) 9927 .Cases("{f17}", "{fa7}", RISCV::F17_F) 9928 .Cases("{f18}", "{fs2}", RISCV::F18_F) 9929 .Cases("{f19}", "{fs3}", RISCV::F19_F) 9930 .Cases("{f20}", "{fs4}", RISCV::F20_F) 9931 .Cases("{f21}", "{fs5}", RISCV::F21_F) 9932 .Cases("{f22}", "{fs6}", RISCV::F22_F) 9933 .Cases("{f23}", "{fs7}", RISCV::F23_F) 9934 .Cases("{f24}", "{fs8}", RISCV::F24_F) 9935 .Cases("{f25}", "{fs9}", RISCV::F25_F) 9936 .Cases("{f26}", "{fs10}", RISCV::F26_F) 9937 .Cases("{f27}", "{fs11}", RISCV::F27_F) 9938 .Cases("{f28}", "{ft8}", RISCV::F28_F) 9939 .Cases("{f29}", "{ft9}", RISCV::F29_F) 9940 .Cases("{f30}", "{ft10}", RISCV::F30_F) 9941 .Cases("{f31}", "{ft11}", RISCV::F31_F) 9942 .Default(RISCV::NoRegister); 9943 if (FReg != RISCV::NoRegister) { 9944 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 9945 if (Subtarget.hasStdExtD()) { 9946 unsigned RegNo = FReg - RISCV::F0_F; 9947 unsigned DReg = RISCV::F0_D + RegNo; 9948 return std::make_pair(DReg, &RISCV::FPR64RegClass); 9949 } 9950 return std::make_pair(FReg, &RISCV::FPR32RegClass); 9951 } 9952 } 9953 9954 if (Subtarget.hasVInstructions()) { 9955 Register VReg = StringSwitch<Register>(Constraint.lower()) 9956 .Case("{v0}", RISCV::V0) 9957 .Case("{v1}", RISCV::V1) 9958 .Case("{v2}", RISCV::V2) 9959 .Case("{v3}", RISCV::V3) 9960 .Case("{v4}", RISCV::V4) 9961 .Case("{v5}", RISCV::V5) 9962 .Case("{v6}", RISCV::V6) 9963 .Case("{v7}", RISCV::V7) 9964 .Case("{v8}", RISCV::V8) 9965 .Case("{v9}", RISCV::V9) 9966 .Case("{v10}", RISCV::V10) 9967 .Case("{v11}", RISCV::V11) 9968 .Case("{v12}", RISCV::V12) 9969 .Case("{v13}", RISCV::V13) 9970 .Case("{v14}", RISCV::V14) 9971 .Case("{v15}", RISCV::V15) 9972 .Case("{v16}", RISCV::V16) 9973 .Case("{v17}", RISCV::V17) 9974 .Case("{v18}", RISCV::V18) 9975 .Case("{v19}", RISCV::V19) 9976 .Case("{v20}", RISCV::V20) 9977 .Case("{v21}", RISCV::V21) 9978 .Case("{v22}", RISCV::V22) 9979 .Case("{v23}", RISCV::V23) 9980 .Case("{v24}", RISCV::V24) 9981 .Case("{v25}", RISCV::V25) 9982 .Case("{v26}", RISCV::V26) 9983 .Case("{v27}", RISCV::V27) 9984 .Case("{v28}", RISCV::V28) 9985 .Case("{v29}", RISCV::V29) 9986 .Case("{v30}", RISCV::V30) 9987 .Case("{v31}", RISCV::V31) 9988 .Default(RISCV::NoRegister); 9989 if (VReg != RISCV::NoRegister) { 9990 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9991 return std::make_pair(VReg, &RISCV::VMRegClass); 9992 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 9993 return std::make_pair(VReg, &RISCV::VRRegClass); 9994 for (const auto *RC : 9995 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9996 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 9997 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 9998 return std::make_pair(VReg, RC); 9999 } 10000 } 10001 } 10002 } 10003 10004 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10005 } 10006 10007 unsigned 10008 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 10009 // Currently only support length 1 constraints. 10010 if (ConstraintCode.size() == 1) { 10011 switch (ConstraintCode[0]) { 10012 case 'A': 10013 return InlineAsm::Constraint_A; 10014 default: 10015 break; 10016 } 10017 } 10018 10019 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 10020 } 10021 10022 void RISCVTargetLowering::LowerAsmOperandForConstraint( 10023 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 10024 SelectionDAG &DAG) const { 10025 // Currently only support length 1 constraints. 10026 if (Constraint.length() == 1) { 10027 switch (Constraint[0]) { 10028 case 'I': 10029 // Validate & create a 12-bit signed immediate operand. 10030 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10031 uint64_t CVal = C->getSExtValue(); 10032 if (isInt<12>(CVal)) 10033 Ops.push_back( 10034 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10035 } 10036 return; 10037 case 'J': 10038 // Validate & create an integer zero operand. 10039 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 10040 if (C->getZExtValue() == 0) 10041 Ops.push_back( 10042 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 10043 return; 10044 case 'K': 10045 // Validate & create a 5-bit unsigned immediate operand. 10046 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10047 uint64_t CVal = C->getZExtValue(); 10048 if (isUInt<5>(CVal)) 10049 Ops.push_back( 10050 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10051 } 10052 return; 10053 case 'S': 10054 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 10055 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 10056 GA->getValueType(0))); 10057 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 10058 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 10059 BA->getValueType(0))); 10060 } 10061 return; 10062 default: 10063 break; 10064 } 10065 } 10066 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 10067 } 10068 10069 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 10070 Instruction *Inst, 10071 AtomicOrdering Ord) const { 10072 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 10073 return Builder.CreateFence(Ord); 10074 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 10075 return Builder.CreateFence(AtomicOrdering::Release); 10076 return nullptr; 10077 } 10078 10079 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 10080 Instruction *Inst, 10081 AtomicOrdering Ord) const { 10082 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 10083 return Builder.CreateFence(AtomicOrdering::Acquire); 10084 return nullptr; 10085 } 10086 10087 TargetLowering::AtomicExpansionKind 10088 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10089 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 10090 // point operations can't be used in an lr/sc sequence without breaking the 10091 // forward-progress guarantee. 10092 if (AI->isFloatingPointOperation()) 10093 return AtomicExpansionKind::CmpXChg; 10094 10095 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10096 if (Size == 8 || Size == 16) 10097 return AtomicExpansionKind::MaskedIntrinsic; 10098 return AtomicExpansionKind::None; 10099 } 10100 10101 static Intrinsic::ID 10102 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 10103 if (XLen == 32) { 10104 switch (BinOp) { 10105 default: 10106 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10107 case AtomicRMWInst::Xchg: 10108 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 10109 case AtomicRMWInst::Add: 10110 return Intrinsic::riscv_masked_atomicrmw_add_i32; 10111 case AtomicRMWInst::Sub: 10112 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 10113 case AtomicRMWInst::Nand: 10114 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 10115 case AtomicRMWInst::Max: 10116 return Intrinsic::riscv_masked_atomicrmw_max_i32; 10117 case AtomicRMWInst::Min: 10118 return Intrinsic::riscv_masked_atomicrmw_min_i32; 10119 case AtomicRMWInst::UMax: 10120 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 10121 case AtomicRMWInst::UMin: 10122 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 10123 } 10124 } 10125 10126 if (XLen == 64) { 10127 switch (BinOp) { 10128 default: 10129 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10130 case AtomicRMWInst::Xchg: 10131 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 10132 case AtomicRMWInst::Add: 10133 return Intrinsic::riscv_masked_atomicrmw_add_i64; 10134 case AtomicRMWInst::Sub: 10135 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 10136 case AtomicRMWInst::Nand: 10137 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 10138 case AtomicRMWInst::Max: 10139 return Intrinsic::riscv_masked_atomicrmw_max_i64; 10140 case AtomicRMWInst::Min: 10141 return Intrinsic::riscv_masked_atomicrmw_min_i64; 10142 case AtomicRMWInst::UMax: 10143 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 10144 case AtomicRMWInst::UMin: 10145 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 10146 } 10147 } 10148 10149 llvm_unreachable("Unexpected XLen\n"); 10150 } 10151 10152 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 10153 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 10154 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 10155 unsigned XLen = Subtarget.getXLen(); 10156 Value *Ordering = 10157 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 10158 Type *Tys[] = {AlignedAddr->getType()}; 10159 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 10160 AI->getModule(), 10161 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 10162 10163 if (XLen == 64) { 10164 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 10165 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10166 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 10167 } 10168 10169 Value *Result; 10170 10171 // Must pass the shift amount needed to sign extend the loaded value prior 10172 // to performing a signed comparison for min/max. ShiftAmt is the number of 10173 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 10174 // is the number of bits to left+right shift the value in order to 10175 // sign-extend. 10176 if (AI->getOperation() == AtomicRMWInst::Min || 10177 AI->getOperation() == AtomicRMWInst::Max) { 10178 const DataLayout &DL = AI->getModule()->getDataLayout(); 10179 unsigned ValWidth = 10180 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 10181 Value *SextShamt = 10182 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 10183 Result = Builder.CreateCall(LrwOpScwLoop, 10184 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 10185 } else { 10186 Result = 10187 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 10188 } 10189 10190 if (XLen == 64) 10191 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10192 return Result; 10193 } 10194 10195 TargetLowering::AtomicExpansionKind 10196 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 10197 AtomicCmpXchgInst *CI) const { 10198 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 10199 if (Size == 8 || Size == 16) 10200 return AtomicExpansionKind::MaskedIntrinsic; 10201 return AtomicExpansionKind::None; 10202 } 10203 10204 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 10205 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 10206 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 10207 unsigned XLen = Subtarget.getXLen(); 10208 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 10209 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 10210 if (XLen == 64) { 10211 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 10212 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 10213 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10214 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 10215 } 10216 Type *Tys[] = {AlignedAddr->getType()}; 10217 Function *MaskedCmpXchg = 10218 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 10219 Value *Result = Builder.CreateCall( 10220 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 10221 if (XLen == 64) 10222 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10223 return Result; 10224 } 10225 10226 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 10227 return false; 10228 } 10229 10230 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 10231 EVT VT) const { 10232 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 10233 return false; 10234 10235 switch (FPVT.getSimpleVT().SimpleTy) { 10236 case MVT::f16: 10237 return Subtarget.hasStdExtZfh(); 10238 case MVT::f32: 10239 return Subtarget.hasStdExtF(); 10240 case MVT::f64: 10241 return Subtarget.hasStdExtD(); 10242 default: 10243 return false; 10244 } 10245 } 10246 10247 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 10248 // If we are using the small code model, we can reduce size of jump table 10249 // entry to 4 bytes. 10250 if (Subtarget.is64Bit() && !isPositionIndependent() && 10251 getTargetMachine().getCodeModel() == CodeModel::Small) { 10252 return MachineJumpTableInfo::EK_Custom32; 10253 } 10254 return TargetLowering::getJumpTableEncoding(); 10255 } 10256 10257 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 10258 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 10259 unsigned uid, MCContext &Ctx) const { 10260 assert(Subtarget.is64Bit() && !isPositionIndependent() && 10261 getTargetMachine().getCodeModel() == CodeModel::Small); 10262 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 10263 } 10264 10265 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 10266 EVT VT) const { 10267 VT = VT.getScalarType(); 10268 10269 if (!VT.isSimple()) 10270 return false; 10271 10272 switch (VT.getSimpleVT().SimpleTy) { 10273 case MVT::f16: 10274 return Subtarget.hasStdExtZfh(); 10275 case MVT::f32: 10276 return Subtarget.hasStdExtF(); 10277 case MVT::f64: 10278 return Subtarget.hasStdExtD(); 10279 default: 10280 break; 10281 } 10282 10283 return false; 10284 } 10285 10286 Register RISCVTargetLowering::getExceptionPointerRegister( 10287 const Constant *PersonalityFn) const { 10288 return RISCV::X10; 10289 } 10290 10291 Register RISCVTargetLowering::getExceptionSelectorRegister( 10292 const Constant *PersonalityFn) const { 10293 return RISCV::X11; 10294 } 10295 10296 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 10297 // Return false to suppress the unnecessary extensions if the LibCall 10298 // arguments or return value is f32 type for LP64 ABI. 10299 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 10300 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 10301 return false; 10302 10303 return true; 10304 } 10305 10306 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 10307 if (Subtarget.is64Bit() && Type == MVT::i32) 10308 return true; 10309 10310 return IsSigned; 10311 } 10312 10313 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 10314 SDValue C) const { 10315 // Check integral scalar types. 10316 if (VT.isScalarInteger()) { 10317 // Omit the optimization if the sub target has the M extension and the data 10318 // size exceeds XLen. 10319 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 10320 return false; 10321 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 10322 // Break the MUL to a SLLI and an ADD/SUB. 10323 const APInt &Imm = ConstNode->getAPIntValue(); 10324 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 10325 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 10326 return true; 10327 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 10328 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 10329 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 10330 (Imm - 8).isPowerOf2())) 10331 return true; 10332 // Omit the following optimization if the sub target has the M extension 10333 // and the data size >= XLen. 10334 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 10335 return false; 10336 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 10337 // a pair of LUI/ADDI. 10338 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 10339 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 10340 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 10341 (1 - ImmS).isPowerOf2()) 10342 return true; 10343 } 10344 } 10345 } 10346 10347 return false; 10348 } 10349 10350 bool RISCVTargetLowering::isMulAddWithConstProfitable( 10351 const SDValue &AddNode, const SDValue &ConstNode) const { 10352 // Let the DAGCombiner decide for vectors. 10353 EVT VT = AddNode.getValueType(); 10354 if (VT.isVector()) 10355 return true; 10356 10357 // Let the DAGCombiner decide for larger types. 10358 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 10359 return true; 10360 10361 // It is worse if c1 is simm12 while c1*c2 is not. 10362 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 10363 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 10364 const APInt &C1 = C1Node->getAPIntValue(); 10365 const APInt &C2 = C2Node->getAPIntValue(); 10366 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 10367 return false; 10368 10369 // Default to true and let the DAGCombiner decide. 10370 return true; 10371 } 10372 10373 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 10374 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 10375 bool *Fast) const { 10376 if (!VT.isVector()) 10377 return false; 10378 10379 EVT ElemVT = VT.getVectorElementType(); 10380 if (Alignment >= ElemVT.getStoreSize()) { 10381 if (Fast) 10382 *Fast = true; 10383 return true; 10384 } 10385 10386 return false; 10387 } 10388 10389 bool RISCVTargetLowering::splitValueIntoRegisterParts( 10390 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 10391 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 10392 bool IsABIRegCopy = CC.hasValue(); 10393 EVT ValueVT = Val.getValueType(); 10394 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10395 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 10396 // and cast to f32. 10397 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 10398 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 10399 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 10400 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 10401 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 10402 Parts[0] = Val; 10403 return true; 10404 } 10405 10406 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10407 LLVMContext &Context = *DAG.getContext(); 10408 EVT ValueEltVT = ValueVT.getVectorElementType(); 10409 EVT PartEltVT = PartVT.getVectorElementType(); 10410 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10411 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10412 if (PartVTBitSize % ValueVTBitSize == 0) { 10413 assert(PartVTBitSize >= ValueVTBitSize); 10414 // If the element types are different, bitcast to the same element type of 10415 // PartVT first. 10416 // Give an example here, we want copy a <vscale x 1 x i8> value to 10417 // <vscale x 4 x i16>. 10418 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 10419 // subvector, then we can bitcast to <vscale x 4 x i16>. 10420 if (ValueEltVT != PartEltVT) { 10421 if (PartVTBitSize > ValueVTBitSize) { 10422 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 10423 assert(Count != 0 && "The number of element should not be zero."); 10424 EVT SameEltTypeVT = 10425 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 10426 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 10427 DAG.getUNDEF(SameEltTypeVT), Val, 10428 DAG.getVectorIdxConstant(0, DL)); 10429 } 10430 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 10431 } else { 10432 Val = 10433 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 10434 Val, DAG.getVectorIdxConstant(0, DL)); 10435 } 10436 Parts[0] = Val; 10437 return true; 10438 } 10439 } 10440 return false; 10441 } 10442 10443 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 10444 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 10445 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 10446 bool IsABIRegCopy = CC.hasValue(); 10447 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10448 SDValue Val = Parts[0]; 10449 10450 // Cast the f32 to i32, truncate to i16, and cast back to f16. 10451 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 10452 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 10453 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 10454 return Val; 10455 } 10456 10457 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10458 LLVMContext &Context = *DAG.getContext(); 10459 SDValue Val = Parts[0]; 10460 EVT ValueEltVT = ValueVT.getVectorElementType(); 10461 EVT PartEltVT = PartVT.getVectorElementType(); 10462 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10463 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10464 if (PartVTBitSize % ValueVTBitSize == 0) { 10465 assert(PartVTBitSize >= ValueVTBitSize); 10466 EVT SameEltTypeVT = ValueVT; 10467 // If the element types are different, convert it to the same element type 10468 // of PartVT. 10469 // Give an example here, we want copy a <vscale x 1 x i8> value from 10470 // <vscale x 4 x i16>. 10471 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 10472 // then we can extract <vscale x 1 x i8>. 10473 if (ValueEltVT != PartEltVT) { 10474 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 10475 assert(Count != 0 && "The number of element should not be zero."); 10476 SameEltTypeVT = 10477 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 10478 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 10479 } 10480 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 10481 DAG.getVectorIdxConstant(0, DL)); 10482 return Val; 10483 } 10484 } 10485 return SDValue(); 10486 } 10487 10488 SDValue 10489 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 10490 SelectionDAG &DAG, 10491 SmallVectorImpl<SDNode *> &Created) const { 10492 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 10493 if (isIntDivCheap(N->getValueType(0), Attr)) 10494 return SDValue(N, 0); // Lower SDIV as SDIV 10495 10496 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 10497 "Unexpected divisor!"); 10498 10499 // Conditional move is needed, so do the transformation iff Zbt is enabled. 10500 if (!Subtarget.hasStdExtZbt()) 10501 return SDValue(); 10502 10503 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 10504 // Besides, more critical path instructions will be generated when dividing 10505 // by 2. So we keep using the original DAGs for these cases. 10506 unsigned Lg2 = Divisor.countTrailingZeros(); 10507 if (Lg2 == 1 || Lg2 >= 12) 10508 return SDValue(); 10509 10510 // fold (sdiv X, pow2) 10511 EVT VT = N->getValueType(0); 10512 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 10513 return SDValue(); 10514 10515 SDLoc DL(N); 10516 SDValue N0 = N->getOperand(0); 10517 SDValue Zero = DAG.getConstant(0, DL, VT); 10518 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 10519 10520 // Add (N0 < 0) ? Pow2 - 1 : 0; 10521 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 10522 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 10523 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 10524 10525 Created.push_back(Cmp.getNode()); 10526 Created.push_back(Add.getNode()); 10527 Created.push_back(Sel.getNode()); 10528 10529 // Divide by pow2. 10530 SDValue SRA = 10531 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 10532 10533 // If we're dividing by a positive value, we're done. Otherwise, we must 10534 // negate the result. 10535 if (Divisor.isNonNegative()) 10536 return SRA; 10537 10538 Created.push_back(SRA.getNode()); 10539 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 10540 } 10541 10542 #define GET_REGISTER_MATCHER 10543 #include "RISCVGenAsmMatcher.inc" 10544 10545 Register 10546 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 10547 const MachineFunction &MF) const { 10548 Register Reg = MatchRegisterAltName(RegName); 10549 if (Reg == RISCV::NoRegister) 10550 Reg = MatchRegisterName(RegName); 10551 if (Reg == RISCV::NoRegister) 10552 report_fatal_error( 10553 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 10554 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 10555 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 10556 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 10557 StringRef(RegName) + "\".")); 10558 return Reg; 10559 } 10560 10561 namespace llvm { 10562 namespace RISCVVIntrinsicsTable { 10563 10564 #define GET_RISCVVIntrinsicsTable_IMPL 10565 #include "RISCVGenSearchableTables.inc" 10566 10567 } // namespace RISCVVIntrinsicsTable 10568 10569 } // namespace llvm 10570