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 NumViaIntegerBits = std::min(NumViaIntegerBits, 1933 Subtarget.getMaxELENForFixedLengthVectors()); 1934 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1935 // If we have to use more than one INSERT_VECTOR_ELT then this 1936 // optimization is likely to increase code size; avoid peforming it in 1937 // such a case. We can use a load from a constant pool in this case. 1938 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1939 return SDValue(); 1940 // Now we can create our integer vector type. Note that it may be larger 1941 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1942 MVT IntegerViaVecVT = 1943 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1944 divideCeil(NumElts, NumViaIntegerBits)); 1945 1946 uint64_t Bits = 0; 1947 unsigned BitPos = 0, IntegerEltIdx = 0; 1948 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1949 1950 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1951 // Once we accumulate enough bits to fill our scalar type, insert into 1952 // our vector and clear our accumulated data. 1953 if (I != 0 && I % NumViaIntegerBits == 0) { 1954 if (NumViaIntegerBits <= 32) 1955 Bits = SignExtend64(Bits, 32); 1956 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1957 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1958 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1959 Bits = 0; 1960 BitPos = 0; 1961 IntegerEltIdx++; 1962 } 1963 SDValue V = Op.getOperand(I); 1964 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1965 Bits |= ((uint64_t)BitValue << BitPos); 1966 } 1967 1968 // Insert the (remaining) scalar value into position in our integer 1969 // vector type. 1970 if (NumViaIntegerBits <= 32) 1971 Bits = SignExtend64(Bits, 32); 1972 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1973 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1974 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1975 1976 if (NumElts < NumViaIntegerBits) { 1977 // If we're producing a smaller vector than our minimum legal integer 1978 // type, bitcast to the equivalent (known-legal) mask type, and extract 1979 // our final mask. 1980 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1981 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1982 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1983 DAG.getConstant(0, DL, XLenVT)); 1984 } else { 1985 // Else we must have produced an integer type with the same size as the 1986 // mask type; bitcast for the final result. 1987 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1988 Vec = DAG.getBitcast(VT, Vec); 1989 } 1990 1991 return Vec; 1992 } 1993 1994 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 1995 // vector type, we have a legal equivalently-sized i8 type, so we can use 1996 // that. 1997 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 1998 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 1999 2000 SDValue WideVec; 2001 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2002 // For a splat, perform a scalar truncate before creating the wider 2003 // vector. 2004 assert(Splat.getValueType() == XLenVT && 2005 "Unexpected type for i1 splat value"); 2006 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2007 DAG.getConstant(1, DL, XLenVT)); 2008 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2009 } else { 2010 SmallVector<SDValue, 8> Ops(Op->op_values()); 2011 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2012 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2013 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2014 } 2015 2016 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2017 } 2018 2019 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2020 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2021 : RISCVISD::VMV_V_X_VL; 2022 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 2023 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2024 } 2025 2026 // Try and match index sequences, which we can lower to the vid instruction 2027 // with optional modifications. An all-undef vector is matched by 2028 // getSplatValue, above. 2029 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2030 int64_t StepNumerator = SimpleVID->StepNumerator; 2031 unsigned StepDenominator = SimpleVID->StepDenominator; 2032 int64_t Addend = SimpleVID->Addend; 2033 2034 assert(StepNumerator != 0 && "Invalid step"); 2035 bool Negate = false; 2036 int64_t SplatStepVal = StepNumerator; 2037 unsigned StepOpcode = ISD::MUL; 2038 if (StepNumerator != 1) { 2039 if (isPowerOf2_64(std::abs(StepNumerator))) { 2040 Negate = StepNumerator < 0; 2041 StepOpcode = ISD::SHL; 2042 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2043 } 2044 } 2045 2046 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2047 // threshold since it's the immediate value many RVV instructions accept. 2048 // There is no vmul.vi instruction so ensure multiply constant can fit in 2049 // a single addi instruction. 2050 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2051 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2052 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2053 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2054 // Convert right out of the scalable type so we can use standard ISD 2055 // nodes for the rest of the computation. If we used scalable types with 2056 // these, we'd lose the fixed-length vector info and generate worse 2057 // vsetvli code. 2058 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2059 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2060 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2061 SDValue SplatStep = DAG.getSplatVector( 2062 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2063 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2064 } 2065 if (StepDenominator != 1) { 2066 SDValue SplatStep = DAG.getSplatVector( 2067 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2068 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2069 } 2070 if (Addend != 0 || Negate) { 2071 SDValue SplatAddend = 2072 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2073 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2074 } 2075 return VID; 2076 } 2077 } 2078 2079 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2080 // when re-interpreted as a vector with a larger element type. For example, 2081 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2082 // could be instead splat as 2083 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2084 // TODO: This optimization could also work on non-constant splats, but it 2085 // would require bit-manipulation instructions to construct the splat value. 2086 SmallVector<SDValue> Sequence; 2087 unsigned EltBitSize = VT.getScalarSizeInBits(); 2088 const auto *BV = cast<BuildVectorSDNode>(Op); 2089 if (VT.isInteger() && EltBitSize < 64 && 2090 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2091 BV->getRepeatedSequence(Sequence) && 2092 (Sequence.size() * EltBitSize) <= 64) { 2093 unsigned SeqLen = Sequence.size(); 2094 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2095 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2096 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2097 ViaIntVT == MVT::i64) && 2098 "Unexpected sequence type"); 2099 2100 unsigned EltIdx = 0; 2101 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2102 uint64_t SplatValue = 0; 2103 // Construct the amalgamated value which can be splatted as this larger 2104 // vector type. 2105 for (const auto &SeqV : Sequence) { 2106 if (!SeqV.isUndef()) 2107 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2108 << (EltIdx * EltBitSize)); 2109 EltIdx++; 2110 } 2111 2112 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2113 // achieve better constant materializion. 2114 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2115 SplatValue = SignExtend64(SplatValue, 32); 2116 2117 // Since we can't introduce illegal i64 types at this stage, we can only 2118 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2119 // way we can use RVV instructions to splat. 2120 assert((ViaIntVT.bitsLE(XLenVT) || 2121 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2122 "Unexpected bitcast sequence"); 2123 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2124 SDValue ViaVL = 2125 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2126 MVT ViaContainerVT = 2127 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2128 SDValue Splat = 2129 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2130 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2131 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2132 return DAG.getBitcast(VT, Splat); 2133 } 2134 } 2135 2136 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2137 // which constitute a large proportion of the elements. In such cases we can 2138 // splat a vector with the dominant element and make up the shortfall with 2139 // INSERT_VECTOR_ELTs. 2140 // Note that this includes vectors of 2 elements by association. The 2141 // upper-most element is the "dominant" one, allowing us to use a splat to 2142 // "insert" the upper element, and an insert of the lower element at position 2143 // 0, which improves codegen. 2144 SDValue DominantValue; 2145 unsigned MostCommonCount = 0; 2146 DenseMap<SDValue, unsigned> ValueCounts; 2147 unsigned NumUndefElts = 2148 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2149 2150 // Track the number of scalar loads we know we'd be inserting, estimated as 2151 // any non-zero floating-point constant. Other kinds of element are either 2152 // already in registers or are materialized on demand. The threshold at which 2153 // a vector load is more desirable than several scalar materializion and 2154 // vector-insertion instructions is not known. 2155 unsigned NumScalarLoads = 0; 2156 2157 for (SDValue V : Op->op_values()) { 2158 if (V.isUndef()) 2159 continue; 2160 2161 ValueCounts.insert(std::make_pair(V, 0)); 2162 unsigned &Count = ValueCounts[V]; 2163 2164 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2165 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2166 2167 // Is this value dominant? In case of a tie, prefer the highest element as 2168 // it's cheaper to insert near the beginning of a vector than it is at the 2169 // end. 2170 if (++Count >= MostCommonCount) { 2171 DominantValue = V; 2172 MostCommonCount = Count; 2173 } 2174 } 2175 2176 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2177 unsigned NumDefElts = NumElts - NumUndefElts; 2178 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2179 2180 // Don't perform this optimization when optimizing for size, since 2181 // materializing elements and inserting them tends to cause code bloat. 2182 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2183 ((MostCommonCount > DominantValueCountThreshold) || 2184 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2185 // Start by splatting the most common element. 2186 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2187 2188 DenseSet<SDValue> Processed{DominantValue}; 2189 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2190 for (const auto &OpIdx : enumerate(Op->ops())) { 2191 const SDValue &V = OpIdx.value(); 2192 if (V.isUndef() || !Processed.insert(V).second) 2193 continue; 2194 if (ValueCounts[V] == 1) { 2195 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2196 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2197 } else { 2198 // Blend in all instances of this value using a VSELECT, using a 2199 // mask where each bit signals whether that element is the one 2200 // we're after. 2201 SmallVector<SDValue> Ops; 2202 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2203 return DAG.getConstant(V == V1, DL, XLenVT); 2204 }); 2205 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2206 DAG.getBuildVector(SelMaskTy, DL, Ops), 2207 DAG.getSplatBuildVector(VT, DL, V), Vec); 2208 } 2209 } 2210 2211 return Vec; 2212 } 2213 2214 return SDValue(); 2215 } 2216 2217 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 2218 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 2219 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2220 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2221 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2222 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2223 // node in order to try and match RVV vector/scalar instructions. 2224 if ((LoC >> 31) == HiC) 2225 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2226 2227 // If vl is equal to VLMax and Hi constant is equal to Lo, we could use 2228 // vmv.v.x whose EEW = 32 to lower it. 2229 auto *Const = dyn_cast<ConstantSDNode>(VL); 2230 if (LoC == HiC && Const && Const->getSExtValue() == RISCV::VLMaxSentinel) { 2231 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2232 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2233 // access the subtarget here now. 2234 auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT, Lo, VL); 2235 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2236 } 2237 } 2238 2239 // Fall back to a stack store and stride x0 vector load. 2240 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2241 } 2242 2243 // Called by type legalization to handle splat of i64 on RV32. 2244 // FIXME: We can optimize this when the type has sign or zero bits in one 2245 // of the halves. 2246 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2247 SDValue VL, SelectionDAG &DAG) { 2248 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2249 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2250 DAG.getConstant(0, DL, MVT::i32)); 2251 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2252 DAG.getConstant(1, DL, MVT::i32)); 2253 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2254 } 2255 2256 // This function lowers a splat of a scalar operand Splat with the vector 2257 // length VL. It ensures the final sequence is type legal, which is useful when 2258 // lowering a splat after type legalization. 2259 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2260 SelectionDAG &DAG, 2261 const RISCVSubtarget &Subtarget) { 2262 if (VT.isFloatingPoint()) { 2263 // If VL is 1, we could use vfmv.s.f. 2264 if (isOneConstant(VL)) 2265 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT), 2266 Scalar, VL); 2267 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2268 } 2269 2270 MVT XLenVT = Subtarget.getXLenVT(); 2271 2272 // Simplest case is that the operand needs to be promoted to XLenVT. 2273 if (Scalar.getValueType().bitsLE(XLenVT)) { 2274 // If the operand is a constant, sign extend to increase our chances 2275 // of being able to use a .vi instruction. ANY_EXTEND would become a 2276 // a zero extend and the simm5 check in isel would fail. 2277 // FIXME: Should we ignore the upper bits in isel instead? 2278 unsigned ExtOpc = 2279 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2280 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2281 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2282 // If VL is 1 and the scalar value won't benefit from immediate, we could 2283 // use vmv.s.x. 2284 if (isOneConstant(VL) && 2285 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2286 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar, 2287 VL); 2288 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2289 } 2290 2291 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2292 "Unexpected scalar for splat lowering!"); 2293 2294 if (isOneConstant(VL) && isNullConstant(Scalar)) 2295 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), 2296 DAG.getConstant(0, DL, XLenVT), VL); 2297 2298 // Otherwise use the more complicated splatting algorithm. 2299 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2300 } 2301 2302 // Is the mask a slidedown that shifts in undefs. 2303 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) { 2304 int Size = Mask.size(); 2305 2306 // Elements shifted in should be undef. 2307 auto CheckUndefs = [&](int Shift) { 2308 for (int i = Size - Shift; i != Size; ++i) 2309 if (Mask[i] >= 0) 2310 return false; 2311 return true; 2312 }; 2313 2314 // Elements should be shifted or undef. 2315 auto MatchShift = [&](int Shift) { 2316 for (int i = 0; i != Size - Shift; ++i) 2317 if (Mask[i] >= 0 && Mask[i] != Shift + i) 2318 return false; 2319 return true; 2320 }; 2321 2322 // Try all possible shifts. 2323 for (int Shift = 1; Shift != Size; ++Shift) 2324 if (CheckUndefs(Shift) && MatchShift(Shift)) 2325 return Shift; 2326 2327 // No match. 2328 return -1; 2329 } 2330 2331 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2332 const RISCVSubtarget &Subtarget) { 2333 SDValue V1 = Op.getOperand(0); 2334 SDValue V2 = Op.getOperand(1); 2335 SDLoc DL(Op); 2336 MVT XLenVT = Subtarget.getXLenVT(); 2337 MVT VT = Op.getSimpleValueType(); 2338 unsigned NumElts = VT.getVectorNumElements(); 2339 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2340 2341 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2342 2343 SDValue TrueMask, VL; 2344 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2345 2346 if (SVN->isSplat()) { 2347 const int Lane = SVN->getSplatIndex(); 2348 if (Lane >= 0) { 2349 MVT SVT = VT.getVectorElementType(); 2350 2351 // Turn splatted vector load into a strided load with an X0 stride. 2352 SDValue V = V1; 2353 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2354 // with undef. 2355 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2356 int Offset = Lane; 2357 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2358 int OpElements = 2359 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2360 V = V.getOperand(Offset / OpElements); 2361 Offset %= OpElements; 2362 } 2363 2364 // We need to ensure the load isn't atomic or volatile. 2365 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2366 auto *Ld = cast<LoadSDNode>(V); 2367 Offset *= SVT.getStoreSize(); 2368 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2369 TypeSize::Fixed(Offset), DL); 2370 2371 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2372 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2373 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2374 SDValue IntID = 2375 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2376 SDValue Ops[] = {Ld->getChain(), IntID, NewAddr, 2377 DAG.getRegister(RISCV::X0, XLenVT), VL}; 2378 SDValue NewLoad = DAG.getMemIntrinsicNode( 2379 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2380 DAG.getMachineFunction().getMachineMemOperand( 2381 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2382 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2383 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2384 } 2385 2386 // Otherwise use a scalar load and splat. This will give the best 2387 // opportunity to fold a splat into the operation. ISel can turn it into 2388 // the x0 strided load if we aren't able to fold away the select. 2389 if (SVT.isFloatingPoint()) 2390 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2391 Ld->getPointerInfo().getWithOffset(Offset), 2392 Ld->getOriginalAlign(), 2393 Ld->getMemOperand()->getFlags()); 2394 else 2395 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2396 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2397 Ld->getOriginalAlign(), 2398 Ld->getMemOperand()->getFlags()); 2399 DAG.makeEquivalentMemoryOrdering(Ld, V); 2400 2401 unsigned Opc = 2402 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2403 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2404 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2405 } 2406 2407 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2408 assert(Lane < (int)NumElts && "Unexpected lane!"); 2409 SDValue Gather = 2410 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2411 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2412 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2413 } 2414 } 2415 2416 // Try to match as a slidedown. 2417 int SlideAmt = matchShuffleAsSlideDown(SVN->getMask()); 2418 if (SlideAmt >= 0) { 2419 // TODO: Should we reduce the VL to account for the upper undef elements? 2420 // Requires additional vsetvlis, but might be faster to execute. 2421 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2422 SDValue SlideDown = 2423 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 2424 DAG.getUNDEF(ContainerVT), V1, 2425 DAG.getConstant(SlideAmt, DL, XLenVT), 2426 TrueMask, VL); 2427 return convertFromScalableVector(VT, SlideDown, DAG, Subtarget); 2428 } 2429 2430 // Detect shuffles which can be re-expressed as vector selects; these are 2431 // shuffles in which each element in the destination is taken from an element 2432 // at the corresponding index in either source vectors. 2433 bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) { 2434 int MaskIndex = MaskIdx.value(); 2435 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2436 }); 2437 2438 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2439 2440 SmallVector<SDValue> MaskVals; 2441 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2442 // merged with a second vrgather. 2443 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2444 2445 // By default we preserve the original operand order, and use a mask to 2446 // select LHS as true and RHS as false. However, since RVV vector selects may 2447 // feature splats but only on the LHS, we may choose to invert our mask and 2448 // instead select between RHS and LHS. 2449 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2450 bool InvertMask = IsSelect == SwapOps; 2451 2452 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2453 // half. 2454 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2455 2456 // Now construct the mask that will be used by the vselect or blended 2457 // vrgather operation. For vrgathers, construct the appropriate indices into 2458 // each vector. 2459 for (int MaskIndex : SVN->getMask()) { 2460 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2461 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2462 if (!IsSelect) { 2463 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2464 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2465 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2466 : DAG.getUNDEF(XLenVT)); 2467 GatherIndicesRHS.push_back( 2468 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2469 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2470 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2471 ++LHSIndexCounts[MaskIndex]; 2472 if (!IsLHSOrUndefIndex) 2473 ++RHSIndexCounts[MaskIndex - NumElts]; 2474 } 2475 } 2476 2477 if (SwapOps) { 2478 std::swap(V1, V2); 2479 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2480 } 2481 2482 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2483 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2484 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2485 2486 if (IsSelect) 2487 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2488 2489 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2490 // On such a large vector we're unable to use i8 as the index type. 2491 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2492 // may involve vector splitting if we're already at LMUL=8, or our 2493 // user-supplied maximum fixed-length LMUL. 2494 return SDValue(); 2495 } 2496 2497 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2498 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2499 MVT IndexVT = VT.changeTypeToInteger(); 2500 // Since we can't introduce illegal index types at this stage, use i16 and 2501 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2502 // than XLenVT. 2503 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2504 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2505 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2506 } 2507 2508 MVT IndexContainerVT = 2509 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2510 2511 SDValue Gather; 2512 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2513 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2514 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2515 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2516 } else { 2517 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2518 // If only one index is used, we can use a "splat" vrgather. 2519 // TODO: We can splat the most-common index and fix-up any stragglers, if 2520 // that's beneficial. 2521 if (LHSIndexCounts.size() == 1) { 2522 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2523 Gather = 2524 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2525 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2526 } else { 2527 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2528 LHSIndices = 2529 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2530 2531 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2532 TrueMask, VL); 2533 } 2534 } 2535 2536 // If a second vector operand is used by this shuffle, blend it in with an 2537 // additional vrgather. 2538 if (!V2.isUndef()) { 2539 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2540 // If only one index is used, we can use a "splat" vrgather. 2541 // TODO: We can splat the most-common index and fix-up any stragglers, if 2542 // that's beneficial. 2543 if (RHSIndexCounts.size() == 1) { 2544 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2545 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2546 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2547 } else { 2548 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2549 RHSIndices = 2550 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2551 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2552 VL); 2553 } 2554 2555 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2556 SelectMask = 2557 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2558 2559 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2560 Gather, VL); 2561 } 2562 2563 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2564 } 2565 2566 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2567 SDLoc DL, SelectionDAG &DAG, 2568 const RISCVSubtarget &Subtarget) { 2569 if (VT.isScalableVector()) 2570 return DAG.getFPExtendOrRound(Op, DL, VT); 2571 assert(VT.isFixedLengthVector() && 2572 "Unexpected value type for RVV FP extend/round lowering"); 2573 SDValue Mask, VL; 2574 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2575 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2576 ? RISCVISD::FP_EXTEND_VL 2577 : RISCVISD::FP_ROUND_VL; 2578 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2579 } 2580 2581 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2582 // the exponent. 2583 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2584 MVT VT = Op.getSimpleValueType(); 2585 unsigned EltSize = VT.getScalarSizeInBits(); 2586 SDValue Src = Op.getOperand(0); 2587 SDLoc DL(Op); 2588 2589 // We need a FP type that can represent the value. 2590 // TODO: Use f16 for i8 when possible? 2591 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2592 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2593 2594 // Legal types should have been checked in the RISCVTargetLowering 2595 // constructor. 2596 // TODO: Splitting may make sense in some cases. 2597 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2598 "Expected legal float type!"); 2599 2600 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2601 // The trailing zero count is equal to log2 of this single bit value. 2602 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2603 SDValue Neg = 2604 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2605 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2606 } 2607 2608 // We have a legal FP type, convert to it. 2609 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2610 // Bitcast to integer and shift the exponent to the LSB. 2611 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2612 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2613 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2614 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2615 DAG.getConstant(ShiftAmt, DL, IntVT)); 2616 // Truncate back to original type to allow vnsrl. 2617 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2618 // The exponent contains log2 of the value in biased form. 2619 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2620 2621 // For trailing zeros, we just need to subtract the bias. 2622 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2623 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2624 DAG.getConstant(ExponentBias, DL, VT)); 2625 2626 // For leading zeros, we need to remove the bias and convert from log2 to 2627 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2628 unsigned Adjust = ExponentBias + (EltSize - 1); 2629 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2630 } 2631 2632 // While RVV has alignment restrictions, we should always be able to load as a 2633 // legal equivalently-sized byte-typed vector instead. This method is 2634 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2635 // the load is already correctly-aligned, it returns SDValue(). 2636 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2637 SelectionDAG &DAG) const { 2638 auto *Load = cast<LoadSDNode>(Op); 2639 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2640 2641 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2642 Load->getMemoryVT(), 2643 *Load->getMemOperand())) 2644 return SDValue(); 2645 2646 SDLoc DL(Op); 2647 MVT VT = Op.getSimpleValueType(); 2648 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2649 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2650 "Unexpected unaligned RVV load type"); 2651 MVT NewVT = 2652 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2653 assert(NewVT.isValid() && 2654 "Expecting equally-sized RVV vector types to be legal"); 2655 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2656 Load->getPointerInfo(), Load->getOriginalAlign(), 2657 Load->getMemOperand()->getFlags()); 2658 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2659 } 2660 2661 // While RVV has alignment restrictions, we should always be able to store as a 2662 // legal equivalently-sized byte-typed vector instead. This method is 2663 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2664 // returns SDValue() if the store is already correctly aligned. 2665 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2666 SelectionDAG &DAG) const { 2667 auto *Store = cast<StoreSDNode>(Op); 2668 assert(Store && Store->getValue().getValueType().isVector() && 2669 "Expected vector store"); 2670 2671 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2672 Store->getMemoryVT(), 2673 *Store->getMemOperand())) 2674 return SDValue(); 2675 2676 SDLoc DL(Op); 2677 SDValue StoredVal = Store->getValue(); 2678 MVT VT = StoredVal.getSimpleValueType(); 2679 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2680 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2681 "Unexpected unaligned RVV store type"); 2682 MVT NewVT = 2683 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2684 assert(NewVT.isValid() && 2685 "Expecting equally-sized RVV vector types to be legal"); 2686 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2687 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2688 Store->getPointerInfo(), Store->getOriginalAlign(), 2689 Store->getMemOperand()->getFlags()); 2690 } 2691 2692 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2693 SelectionDAG &DAG) const { 2694 switch (Op.getOpcode()) { 2695 default: 2696 report_fatal_error("unimplemented operand"); 2697 case ISD::GlobalAddress: 2698 return lowerGlobalAddress(Op, DAG); 2699 case ISD::BlockAddress: 2700 return lowerBlockAddress(Op, DAG); 2701 case ISD::ConstantPool: 2702 return lowerConstantPool(Op, DAG); 2703 case ISD::JumpTable: 2704 return lowerJumpTable(Op, DAG); 2705 case ISD::GlobalTLSAddress: 2706 return lowerGlobalTLSAddress(Op, DAG); 2707 case ISD::SELECT: 2708 return lowerSELECT(Op, DAG); 2709 case ISD::BRCOND: 2710 return lowerBRCOND(Op, DAG); 2711 case ISD::VASTART: 2712 return lowerVASTART(Op, DAG); 2713 case ISD::FRAMEADDR: 2714 return lowerFRAMEADDR(Op, DAG); 2715 case ISD::RETURNADDR: 2716 return lowerRETURNADDR(Op, DAG); 2717 case ISD::SHL_PARTS: 2718 return lowerShiftLeftParts(Op, DAG); 2719 case ISD::SRA_PARTS: 2720 return lowerShiftRightParts(Op, DAG, true); 2721 case ISD::SRL_PARTS: 2722 return lowerShiftRightParts(Op, DAG, false); 2723 case ISD::BITCAST: { 2724 SDLoc DL(Op); 2725 EVT VT = Op.getValueType(); 2726 SDValue Op0 = Op.getOperand(0); 2727 EVT Op0VT = Op0.getValueType(); 2728 MVT XLenVT = Subtarget.getXLenVT(); 2729 if (VT.isFixedLengthVector()) { 2730 // We can handle fixed length vector bitcasts with a simple replacement 2731 // in isel. 2732 if (Op0VT.isFixedLengthVector()) 2733 return Op; 2734 // When bitcasting from scalar to fixed-length vector, insert the scalar 2735 // into a one-element vector of the result type, and perform a vector 2736 // bitcast. 2737 if (!Op0VT.isVector()) { 2738 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2739 if (!isTypeLegal(BVT)) 2740 return SDValue(); 2741 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2742 DAG.getUNDEF(BVT), Op0, 2743 DAG.getConstant(0, DL, XLenVT))); 2744 } 2745 return SDValue(); 2746 } 2747 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2748 // thus: bitcast the vector to a one-element vector type whose element type 2749 // is the same as the result type, and extract the first element. 2750 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2751 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2752 if (!isTypeLegal(BVT)) 2753 return SDValue(); 2754 SDValue BVec = DAG.getBitcast(BVT, Op0); 2755 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2756 DAG.getConstant(0, DL, XLenVT)); 2757 } 2758 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2759 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2760 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2761 return FPConv; 2762 } 2763 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2764 Subtarget.hasStdExtF()) { 2765 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2766 SDValue FPConv = 2767 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2768 return FPConv; 2769 } 2770 return SDValue(); 2771 } 2772 case ISD::INTRINSIC_WO_CHAIN: 2773 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2774 case ISD::INTRINSIC_W_CHAIN: 2775 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2776 case ISD::INTRINSIC_VOID: 2777 return LowerINTRINSIC_VOID(Op, DAG); 2778 case ISD::BSWAP: 2779 case ISD::BITREVERSE: { 2780 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2781 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 2782 MVT VT = Op.getSimpleValueType(); 2783 SDLoc DL(Op); 2784 // Start with the maximum immediate value which is the bitwidth - 1. 2785 unsigned Imm = VT.getSizeInBits() - 1; 2786 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2787 if (Op.getOpcode() == ISD::BSWAP) 2788 Imm &= ~0x7U; 2789 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2790 DAG.getConstant(Imm, DL, VT)); 2791 } 2792 case ISD::FSHL: 2793 case ISD::FSHR: { 2794 MVT VT = Op.getSimpleValueType(); 2795 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2796 SDLoc DL(Op); 2797 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2798 // use log(XLen) bits. Mask the shift amount accordingly to prevent 2799 // accidentally setting the extra bit. 2800 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2801 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2802 DAG.getConstant(ShAmtWidth, DL, VT)); 2803 // fshl and fshr concatenate their operands in the same order. fsr and fsl 2804 // instruction use different orders. fshl will return its first operand for 2805 // shift of zero, fshr will return its second operand. fsl and fsr both 2806 // return rs1 so the ISD nodes need to have different operand orders. 2807 // Shift amount is in rs2. 2808 SDValue Op0 = Op.getOperand(0); 2809 SDValue Op1 = Op.getOperand(1); 2810 unsigned Opc = RISCVISD::FSL; 2811 if (Op.getOpcode() == ISD::FSHR) { 2812 std::swap(Op0, Op1); 2813 Opc = RISCVISD::FSR; 2814 } 2815 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 2816 } 2817 case ISD::TRUNCATE: { 2818 SDLoc DL(Op); 2819 MVT VT = Op.getSimpleValueType(); 2820 // Only custom-lower vector truncates 2821 if (!VT.isVector()) 2822 return Op; 2823 2824 // Truncates to mask types are handled differently 2825 if (VT.getVectorElementType() == MVT::i1) 2826 return lowerVectorMaskTrunc(Op, DAG); 2827 2828 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 2829 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 2830 // truncate by one power of two at a time. 2831 MVT DstEltVT = VT.getVectorElementType(); 2832 2833 SDValue Src = Op.getOperand(0); 2834 MVT SrcVT = Src.getSimpleValueType(); 2835 MVT SrcEltVT = SrcVT.getVectorElementType(); 2836 2837 assert(DstEltVT.bitsLT(SrcEltVT) && 2838 isPowerOf2_64(DstEltVT.getSizeInBits()) && 2839 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 2840 "Unexpected vector truncate lowering"); 2841 2842 MVT ContainerVT = SrcVT; 2843 if (SrcVT.isFixedLengthVector()) { 2844 ContainerVT = getContainerForFixedLengthVector(SrcVT); 2845 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 2846 } 2847 2848 SDValue Result = Src; 2849 SDValue Mask, VL; 2850 std::tie(Mask, VL) = 2851 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 2852 LLVMContext &Context = *DAG.getContext(); 2853 const ElementCount Count = ContainerVT.getVectorElementCount(); 2854 do { 2855 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 2856 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 2857 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 2858 Mask, VL); 2859 } while (SrcEltVT != DstEltVT); 2860 2861 if (SrcVT.isFixedLengthVector()) 2862 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 2863 2864 return Result; 2865 } 2866 case ISD::ANY_EXTEND: 2867 case ISD::ZERO_EXTEND: 2868 if (Op.getOperand(0).getValueType().isVector() && 2869 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2870 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 2871 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 2872 case ISD::SIGN_EXTEND: 2873 if (Op.getOperand(0).getValueType().isVector() && 2874 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2875 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 2876 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 2877 case ISD::SPLAT_VECTOR_PARTS: 2878 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 2879 case ISD::INSERT_VECTOR_ELT: 2880 return lowerINSERT_VECTOR_ELT(Op, DAG); 2881 case ISD::EXTRACT_VECTOR_ELT: 2882 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 2883 case ISD::VSCALE: { 2884 MVT VT = Op.getSimpleValueType(); 2885 SDLoc DL(Op); 2886 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 2887 // We define our scalable vector types for lmul=1 to use a 64 bit known 2888 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 2889 // vscale as VLENB / 8. 2890 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 2891 if (isa<ConstantSDNode>(Op.getOperand(0))) { 2892 // We assume VLENB is a multiple of 8. We manually choose the best shift 2893 // here because SimplifyDemandedBits isn't always able to simplify it. 2894 uint64_t Val = Op.getConstantOperandVal(0); 2895 if (isPowerOf2_64(Val)) { 2896 uint64_t Log2 = Log2_64(Val); 2897 if (Log2 < 3) 2898 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 2899 DAG.getConstant(3 - Log2, DL, VT)); 2900 if (Log2 > 3) 2901 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 2902 DAG.getConstant(Log2 - 3, DL, VT)); 2903 return VLENB; 2904 } 2905 // If the multiplier is a multiple of 8, scale it down to avoid needing 2906 // to shift the VLENB value. 2907 if ((Val % 8) == 0) 2908 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 2909 DAG.getConstant(Val / 8, DL, VT)); 2910 } 2911 2912 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 2913 DAG.getConstant(3, DL, VT)); 2914 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 2915 } 2916 case ISD::FPOWI: { 2917 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 2918 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 2919 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 2920 Op.getOperand(1).getValueType() == MVT::i32) { 2921 SDLoc DL(Op); 2922 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 2923 SDValue Powi = 2924 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 2925 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 2926 DAG.getIntPtrConstant(0, DL)); 2927 } 2928 return SDValue(); 2929 } 2930 case ISD::FP_EXTEND: { 2931 // RVV can only do fp_extend to types double the size as the source. We 2932 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 2933 // via f32. 2934 SDLoc DL(Op); 2935 MVT VT = Op.getSimpleValueType(); 2936 SDValue Src = Op.getOperand(0); 2937 MVT SrcVT = Src.getSimpleValueType(); 2938 2939 // Prepare any fixed-length vector operands. 2940 MVT ContainerVT = VT; 2941 if (SrcVT.isFixedLengthVector()) { 2942 ContainerVT = getContainerForFixedLengthVector(VT); 2943 MVT SrcContainerVT = 2944 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 2945 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2946 } 2947 2948 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 2949 SrcVT.getVectorElementType() != MVT::f16) { 2950 // For scalable vectors, we only need to close the gap between 2951 // vXf16->vXf64. 2952 if (!VT.isFixedLengthVector()) 2953 return Op; 2954 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 2955 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2956 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2957 } 2958 2959 MVT InterVT = VT.changeVectorElementType(MVT::f32); 2960 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 2961 SDValue IntermediateExtend = getRVVFPExtendOrRound( 2962 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 2963 2964 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 2965 DL, DAG, Subtarget); 2966 if (VT.isFixedLengthVector()) 2967 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 2968 return Extend; 2969 } 2970 case ISD::FP_ROUND: { 2971 // RVV can only do fp_round to types half the size as the source. We 2972 // custom-lower f64->f16 rounds via RVV's round-to-odd float 2973 // conversion instruction. 2974 SDLoc DL(Op); 2975 MVT VT = Op.getSimpleValueType(); 2976 SDValue Src = Op.getOperand(0); 2977 MVT SrcVT = Src.getSimpleValueType(); 2978 2979 // Prepare any fixed-length vector operands. 2980 MVT ContainerVT = VT; 2981 if (VT.isFixedLengthVector()) { 2982 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2983 ContainerVT = 2984 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2985 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2986 } 2987 2988 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 2989 SrcVT.getVectorElementType() != MVT::f64) { 2990 // For scalable vectors, we only need to close the gap between 2991 // vXf64<->vXf16. 2992 if (!VT.isFixedLengthVector()) 2993 return Op; 2994 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 2995 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2996 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2997 } 2998 2999 SDValue Mask, VL; 3000 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3001 3002 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3003 SDValue IntermediateRound = 3004 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3005 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3006 DL, DAG, Subtarget); 3007 3008 if (VT.isFixedLengthVector()) 3009 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3010 return Round; 3011 } 3012 case ISD::FP_TO_SINT: 3013 case ISD::FP_TO_UINT: 3014 case ISD::SINT_TO_FP: 3015 case ISD::UINT_TO_FP: { 3016 // RVV can only do fp<->int conversions to types half/double the size as 3017 // the source. We custom-lower any conversions that do two hops into 3018 // sequences. 3019 MVT VT = Op.getSimpleValueType(); 3020 if (!VT.isVector()) 3021 return Op; 3022 SDLoc DL(Op); 3023 SDValue Src = Op.getOperand(0); 3024 MVT EltVT = VT.getVectorElementType(); 3025 MVT SrcVT = Src.getSimpleValueType(); 3026 MVT SrcEltVT = SrcVT.getVectorElementType(); 3027 unsigned EltSize = EltVT.getSizeInBits(); 3028 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3029 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3030 "Unexpected vector element types"); 3031 3032 bool IsInt2FP = SrcEltVT.isInteger(); 3033 // Widening conversions 3034 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 3035 if (IsInt2FP) { 3036 // Do a regular integer sign/zero extension then convert to float. 3037 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 3038 VT.getVectorElementCount()); 3039 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3040 ? ISD::ZERO_EXTEND 3041 : ISD::SIGN_EXTEND; 3042 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3043 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3044 } 3045 // FP2Int 3046 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3047 // Do one doubling fp_extend then complete the operation by converting 3048 // to int. 3049 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3050 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3051 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3052 } 3053 3054 // Narrowing conversions 3055 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 3056 if (IsInt2FP) { 3057 // One narrowing int_to_fp, then an fp_round. 3058 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3059 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3060 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3061 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3062 } 3063 // FP2Int 3064 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3065 // representable by the integer, the result is poison. 3066 MVT IVecVT = 3067 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3068 VT.getVectorElementCount()); 3069 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3070 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3071 } 3072 3073 // Scalable vectors can exit here. Patterns will handle equally-sized 3074 // conversions halving/doubling ones. 3075 if (!VT.isFixedLengthVector()) 3076 return Op; 3077 3078 // For fixed-length vectors we lower to a custom "VL" node. 3079 unsigned RVVOpc = 0; 3080 switch (Op.getOpcode()) { 3081 default: 3082 llvm_unreachable("Impossible opcode"); 3083 case ISD::FP_TO_SINT: 3084 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3085 break; 3086 case ISD::FP_TO_UINT: 3087 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3088 break; 3089 case ISD::SINT_TO_FP: 3090 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3091 break; 3092 case ISD::UINT_TO_FP: 3093 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3094 break; 3095 } 3096 3097 MVT ContainerVT, SrcContainerVT; 3098 // Derive the reference container type from the larger vector type. 3099 if (SrcEltSize > EltSize) { 3100 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3101 ContainerVT = 3102 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3103 } else { 3104 ContainerVT = getContainerForFixedLengthVector(VT); 3105 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3106 } 3107 3108 SDValue Mask, VL; 3109 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3110 3111 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3112 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3113 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3114 } 3115 case ISD::FP_TO_SINT_SAT: 3116 case ISD::FP_TO_UINT_SAT: 3117 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3118 case ISD::FTRUNC: 3119 case ISD::FCEIL: 3120 case ISD::FFLOOR: 3121 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3122 case ISD::VECREDUCE_ADD: 3123 case ISD::VECREDUCE_UMAX: 3124 case ISD::VECREDUCE_SMAX: 3125 case ISD::VECREDUCE_UMIN: 3126 case ISD::VECREDUCE_SMIN: 3127 return lowerVECREDUCE(Op, DAG); 3128 case ISD::VECREDUCE_AND: 3129 case ISD::VECREDUCE_OR: 3130 case ISD::VECREDUCE_XOR: 3131 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3132 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3133 return lowerVECREDUCE(Op, DAG); 3134 case ISD::VECREDUCE_FADD: 3135 case ISD::VECREDUCE_SEQ_FADD: 3136 case ISD::VECREDUCE_FMIN: 3137 case ISD::VECREDUCE_FMAX: 3138 return lowerFPVECREDUCE(Op, DAG); 3139 case ISD::VP_REDUCE_ADD: 3140 case ISD::VP_REDUCE_UMAX: 3141 case ISD::VP_REDUCE_SMAX: 3142 case ISD::VP_REDUCE_UMIN: 3143 case ISD::VP_REDUCE_SMIN: 3144 case ISD::VP_REDUCE_FADD: 3145 case ISD::VP_REDUCE_SEQ_FADD: 3146 case ISD::VP_REDUCE_FMIN: 3147 case ISD::VP_REDUCE_FMAX: 3148 return lowerVPREDUCE(Op, DAG); 3149 case ISD::VP_REDUCE_AND: 3150 case ISD::VP_REDUCE_OR: 3151 case ISD::VP_REDUCE_XOR: 3152 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3153 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3154 return lowerVPREDUCE(Op, DAG); 3155 case ISD::INSERT_SUBVECTOR: 3156 return lowerINSERT_SUBVECTOR(Op, DAG); 3157 case ISD::EXTRACT_SUBVECTOR: 3158 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3159 case ISD::STEP_VECTOR: 3160 return lowerSTEP_VECTOR(Op, DAG); 3161 case ISD::VECTOR_REVERSE: 3162 return lowerVECTOR_REVERSE(Op, DAG); 3163 case ISD::BUILD_VECTOR: 3164 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3165 case ISD::SPLAT_VECTOR: 3166 if (Op.getValueType().getVectorElementType() == MVT::i1) 3167 return lowerVectorMaskSplat(Op, DAG); 3168 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3169 case ISD::VECTOR_SHUFFLE: 3170 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3171 case ISD::CONCAT_VECTORS: { 3172 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3173 // better than going through the stack, as the default expansion does. 3174 SDLoc DL(Op); 3175 MVT VT = Op.getSimpleValueType(); 3176 unsigned NumOpElts = 3177 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3178 SDValue Vec = DAG.getUNDEF(VT); 3179 for (const auto &OpIdx : enumerate(Op->ops())) { 3180 SDValue SubVec = OpIdx.value(); 3181 // Don't insert undef subvectors. 3182 if (SubVec.isUndef()) 3183 continue; 3184 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3185 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3186 } 3187 return Vec; 3188 } 3189 case ISD::LOAD: 3190 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3191 return V; 3192 if (Op.getValueType().isFixedLengthVector()) 3193 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3194 return Op; 3195 case ISD::STORE: 3196 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3197 return V; 3198 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3199 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3200 return Op; 3201 case ISD::MLOAD: 3202 case ISD::VP_LOAD: 3203 return lowerMaskedLoad(Op, DAG); 3204 case ISD::MSTORE: 3205 case ISD::VP_STORE: 3206 return lowerMaskedStore(Op, DAG); 3207 case ISD::SETCC: 3208 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3209 case ISD::ADD: 3210 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3211 case ISD::SUB: 3212 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3213 case ISD::MUL: 3214 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3215 case ISD::MULHS: 3216 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3217 case ISD::MULHU: 3218 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3219 case ISD::AND: 3220 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3221 RISCVISD::AND_VL); 3222 case ISD::OR: 3223 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3224 RISCVISD::OR_VL); 3225 case ISD::XOR: 3226 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3227 RISCVISD::XOR_VL); 3228 case ISD::SDIV: 3229 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3230 case ISD::SREM: 3231 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3232 case ISD::UDIV: 3233 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3234 case ISD::UREM: 3235 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3236 case ISD::SHL: 3237 case ISD::SRA: 3238 case ISD::SRL: 3239 if (Op.getSimpleValueType().isFixedLengthVector()) 3240 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3241 // This can be called for an i32 shift amount that needs to be promoted. 3242 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3243 "Unexpected custom legalisation"); 3244 return SDValue(); 3245 case ISD::SADDSAT: 3246 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3247 case ISD::UADDSAT: 3248 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3249 case ISD::SSUBSAT: 3250 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3251 case ISD::USUBSAT: 3252 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3253 case ISD::FADD: 3254 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3255 case ISD::FSUB: 3256 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3257 case ISD::FMUL: 3258 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3259 case ISD::FDIV: 3260 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3261 case ISD::FNEG: 3262 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3263 case ISD::FABS: 3264 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3265 case ISD::FSQRT: 3266 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3267 case ISD::FMA: 3268 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3269 case ISD::SMIN: 3270 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3271 case ISD::SMAX: 3272 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3273 case ISD::UMIN: 3274 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3275 case ISD::UMAX: 3276 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3277 case ISD::FMINNUM: 3278 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3279 case ISD::FMAXNUM: 3280 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3281 case ISD::ABS: 3282 return lowerABS(Op, DAG); 3283 case ISD::CTLZ_ZERO_UNDEF: 3284 case ISD::CTTZ_ZERO_UNDEF: 3285 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3286 case ISD::VSELECT: 3287 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3288 case ISD::FCOPYSIGN: 3289 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3290 case ISD::MGATHER: 3291 case ISD::VP_GATHER: 3292 return lowerMaskedGather(Op, DAG); 3293 case ISD::MSCATTER: 3294 case ISD::VP_SCATTER: 3295 return lowerMaskedScatter(Op, DAG); 3296 case ISD::FLT_ROUNDS_: 3297 return lowerGET_ROUNDING(Op, DAG); 3298 case ISD::SET_ROUNDING: 3299 return lowerSET_ROUNDING(Op, DAG); 3300 case ISD::VP_SELECT: 3301 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3302 case ISD::VP_ADD: 3303 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3304 case ISD::VP_SUB: 3305 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3306 case ISD::VP_MUL: 3307 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3308 case ISD::VP_SDIV: 3309 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3310 case ISD::VP_UDIV: 3311 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3312 case ISD::VP_SREM: 3313 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3314 case ISD::VP_UREM: 3315 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3316 case ISD::VP_AND: 3317 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3318 case ISD::VP_OR: 3319 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3320 case ISD::VP_XOR: 3321 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3322 case ISD::VP_ASHR: 3323 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3324 case ISD::VP_LSHR: 3325 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3326 case ISD::VP_SHL: 3327 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3328 case ISD::VP_FADD: 3329 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3330 case ISD::VP_FSUB: 3331 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3332 case ISD::VP_FMUL: 3333 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3334 case ISD::VP_FDIV: 3335 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3336 } 3337 } 3338 3339 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3340 SelectionDAG &DAG, unsigned Flags) { 3341 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3342 } 3343 3344 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3345 SelectionDAG &DAG, unsigned Flags) { 3346 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3347 Flags); 3348 } 3349 3350 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3351 SelectionDAG &DAG, unsigned Flags) { 3352 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3353 N->getOffset(), Flags); 3354 } 3355 3356 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3357 SelectionDAG &DAG, unsigned Flags) { 3358 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3359 } 3360 3361 template <class NodeTy> 3362 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3363 bool IsLocal) const { 3364 SDLoc DL(N); 3365 EVT Ty = getPointerTy(DAG.getDataLayout()); 3366 3367 if (isPositionIndependent()) { 3368 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3369 if (IsLocal) 3370 // Use PC-relative addressing to access the symbol. This generates the 3371 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3372 // %pcrel_lo(auipc)). 3373 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3374 3375 // Use PC-relative addressing to access the GOT for this symbol, then load 3376 // the address from the GOT. This generates the pattern (PseudoLA sym), 3377 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3378 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3379 } 3380 3381 switch (getTargetMachine().getCodeModel()) { 3382 default: 3383 report_fatal_error("Unsupported code model for lowering"); 3384 case CodeModel::Small: { 3385 // Generate a sequence for accessing addresses within the first 2 GiB of 3386 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3387 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3388 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3389 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3390 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3391 } 3392 case CodeModel::Medium: { 3393 // Generate a sequence for accessing addresses within any 2GiB range within 3394 // the address space. This generates the pattern (PseudoLLA sym), which 3395 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3396 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3397 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3398 } 3399 } 3400 } 3401 3402 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3403 SelectionDAG &DAG) const { 3404 SDLoc DL(Op); 3405 EVT Ty = Op.getValueType(); 3406 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3407 int64_t Offset = N->getOffset(); 3408 MVT XLenVT = Subtarget.getXLenVT(); 3409 3410 const GlobalValue *GV = N->getGlobal(); 3411 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3412 SDValue Addr = getAddr(N, DAG, IsLocal); 3413 3414 // In order to maximise the opportunity for common subexpression elimination, 3415 // emit a separate ADD node for the global address offset instead of folding 3416 // it in the global address node. Later peephole optimisations may choose to 3417 // fold it back in when profitable. 3418 if (Offset != 0) 3419 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3420 DAG.getConstant(Offset, DL, XLenVT)); 3421 return Addr; 3422 } 3423 3424 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3425 SelectionDAG &DAG) const { 3426 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3427 3428 return getAddr(N, DAG); 3429 } 3430 3431 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3432 SelectionDAG &DAG) const { 3433 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3434 3435 return getAddr(N, DAG); 3436 } 3437 3438 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3439 SelectionDAG &DAG) const { 3440 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3441 3442 return getAddr(N, DAG); 3443 } 3444 3445 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3446 SelectionDAG &DAG, 3447 bool UseGOT) const { 3448 SDLoc DL(N); 3449 EVT Ty = getPointerTy(DAG.getDataLayout()); 3450 const GlobalValue *GV = N->getGlobal(); 3451 MVT XLenVT = Subtarget.getXLenVT(); 3452 3453 if (UseGOT) { 3454 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3455 // load the address from the GOT and add the thread pointer. This generates 3456 // the pattern (PseudoLA_TLS_IE sym), which expands to 3457 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3458 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3459 SDValue Load = 3460 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3461 3462 // Add the thread pointer. 3463 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3464 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3465 } 3466 3467 // Generate a sequence for accessing the address relative to the thread 3468 // pointer, with the appropriate adjustment for the thread pointer offset. 3469 // This generates the pattern 3470 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3471 SDValue AddrHi = 3472 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3473 SDValue AddrAdd = 3474 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3475 SDValue AddrLo = 3476 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3477 3478 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3479 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3480 SDValue MNAdd = SDValue( 3481 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3482 0); 3483 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3484 } 3485 3486 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3487 SelectionDAG &DAG) const { 3488 SDLoc DL(N); 3489 EVT Ty = getPointerTy(DAG.getDataLayout()); 3490 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3491 const GlobalValue *GV = N->getGlobal(); 3492 3493 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3494 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3495 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3496 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3497 SDValue Load = 3498 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3499 3500 // Prepare argument list to generate call. 3501 ArgListTy Args; 3502 ArgListEntry Entry; 3503 Entry.Node = Load; 3504 Entry.Ty = CallTy; 3505 Args.push_back(Entry); 3506 3507 // Setup call to __tls_get_addr. 3508 TargetLowering::CallLoweringInfo CLI(DAG); 3509 CLI.setDebugLoc(DL) 3510 .setChain(DAG.getEntryNode()) 3511 .setLibCallee(CallingConv::C, CallTy, 3512 DAG.getExternalSymbol("__tls_get_addr", Ty), 3513 std::move(Args)); 3514 3515 return LowerCallTo(CLI).first; 3516 } 3517 3518 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3519 SelectionDAG &DAG) const { 3520 SDLoc DL(Op); 3521 EVT Ty = Op.getValueType(); 3522 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3523 int64_t Offset = N->getOffset(); 3524 MVT XLenVT = Subtarget.getXLenVT(); 3525 3526 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3527 3528 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3529 CallingConv::GHC) 3530 report_fatal_error("In GHC calling convention TLS is not supported"); 3531 3532 SDValue Addr; 3533 switch (Model) { 3534 case TLSModel::LocalExec: 3535 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3536 break; 3537 case TLSModel::InitialExec: 3538 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3539 break; 3540 case TLSModel::LocalDynamic: 3541 case TLSModel::GeneralDynamic: 3542 Addr = getDynamicTLSAddr(N, DAG); 3543 break; 3544 } 3545 3546 // In order to maximise the opportunity for common subexpression elimination, 3547 // emit a separate ADD node for the global address offset instead of folding 3548 // it in the global address node. Later peephole optimisations may choose to 3549 // fold it back in when profitable. 3550 if (Offset != 0) 3551 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3552 DAG.getConstant(Offset, DL, XLenVT)); 3553 return Addr; 3554 } 3555 3556 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3557 SDValue CondV = Op.getOperand(0); 3558 SDValue TrueV = Op.getOperand(1); 3559 SDValue FalseV = Op.getOperand(2); 3560 SDLoc DL(Op); 3561 MVT VT = Op.getSimpleValueType(); 3562 MVT XLenVT = Subtarget.getXLenVT(); 3563 3564 // Lower vector SELECTs to VSELECTs by splatting the condition. 3565 if (VT.isVector()) { 3566 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3567 SDValue CondSplat = VT.isScalableVector() 3568 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3569 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3570 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3571 } 3572 3573 // If the result type is XLenVT and CondV is the output of a SETCC node 3574 // which also operated on XLenVT inputs, then merge the SETCC node into the 3575 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3576 // compare+branch instructions. i.e.: 3577 // (select (setcc lhs, rhs, cc), truev, falsev) 3578 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3579 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3580 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3581 SDValue LHS = CondV.getOperand(0); 3582 SDValue RHS = CondV.getOperand(1); 3583 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3584 ISD::CondCode CCVal = CC->get(); 3585 3586 // Special case for a select of 2 constants that have a diffence of 1. 3587 // Normally this is done by DAGCombine, but if the select is introduced by 3588 // type legalization or op legalization, we miss it. Restricting to SETLT 3589 // case for now because that is what signed saturating add/sub need. 3590 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3591 // but we would probably want to swap the true/false values if the condition 3592 // is SETGE/SETLE to avoid an XORI. 3593 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3594 CCVal == ISD::SETLT) { 3595 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3596 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3597 if (TrueVal - 1 == FalseVal) 3598 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3599 if (TrueVal + 1 == FalseVal) 3600 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3601 } 3602 3603 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3604 3605 SDValue TargetCC = DAG.getCondCode(CCVal); 3606 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3607 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3608 } 3609 3610 // Otherwise: 3611 // (select condv, truev, falsev) 3612 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3613 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3614 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3615 3616 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3617 3618 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3619 } 3620 3621 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3622 SDValue CondV = Op.getOperand(1); 3623 SDLoc DL(Op); 3624 MVT XLenVT = Subtarget.getXLenVT(); 3625 3626 if (CondV.getOpcode() == ISD::SETCC && 3627 CondV.getOperand(0).getValueType() == XLenVT) { 3628 SDValue LHS = CondV.getOperand(0); 3629 SDValue RHS = CondV.getOperand(1); 3630 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3631 3632 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3633 3634 SDValue TargetCC = DAG.getCondCode(CCVal); 3635 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3636 LHS, RHS, TargetCC, Op.getOperand(2)); 3637 } 3638 3639 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3640 CondV, DAG.getConstant(0, DL, XLenVT), 3641 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3642 } 3643 3644 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3645 MachineFunction &MF = DAG.getMachineFunction(); 3646 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3647 3648 SDLoc DL(Op); 3649 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3650 getPointerTy(MF.getDataLayout())); 3651 3652 // vastart just stores the address of the VarArgsFrameIndex slot into the 3653 // memory location argument. 3654 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3655 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3656 MachinePointerInfo(SV)); 3657 } 3658 3659 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3660 SelectionDAG &DAG) const { 3661 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3662 MachineFunction &MF = DAG.getMachineFunction(); 3663 MachineFrameInfo &MFI = MF.getFrameInfo(); 3664 MFI.setFrameAddressIsTaken(true); 3665 Register FrameReg = RI.getFrameRegister(MF); 3666 int XLenInBytes = Subtarget.getXLen() / 8; 3667 3668 EVT VT = Op.getValueType(); 3669 SDLoc DL(Op); 3670 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3671 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3672 while (Depth--) { 3673 int Offset = -(XLenInBytes * 2); 3674 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3675 DAG.getIntPtrConstant(Offset, DL)); 3676 FrameAddr = 3677 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3678 } 3679 return FrameAddr; 3680 } 3681 3682 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3683 SelectionDAG &DAG) const { 3684 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3685 MachineFunction &MF = DAG.getMachineFunction(); 3686 MachineFrameInfo &MFI = MF.getFrameInfo(); 3687 MFI.setReturnAddressIsTaken(true); 3688 MVT XLenVT = Subtarget.getXLenVT(); 3689 int XLenInBytes = Subtarget.getXLen() / 8; 3690 3691 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3692 return SDValue(); 3693 3694 EVT VT = Op.getValueType(); 3695 SDLoc DL(Op); 3696 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3697 if (Depth) { 3698 int Off = -XLenInBytes; 3699 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3700 SDValue Offset = DAG.getConstant(Off, DL, VT); 3701 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3702 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3703 MachinePointerInfo()); 3704 } 3705 3706 // Return the value of the return address register, marking it an implicit 3707 // live-in. 3708 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3709 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3710 } 3711 3712 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3713 SelectionDAG &DAG) const { 3714 SDLoc DL(Op); 3715 SDValue Lo = Op.getOperand(0); 3716 SDValue Hi = Op.getOperand(1); 3717 SDValue Shamt = Op.getOperand(2); 3718 EVT VT = Lo.getValueType(); 3719 3720 // if Shamt-XLEN < 0: // Shamt < XLEN 3721 // Lo = Lo << Shamt 3722 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3723 // else: 3724 // Lo = 0 3725 // Hi = Lo << (Shamt-XLEN) 3726 3727 SDValue Zero = DAG.getConstant(0, DL, VT); 3728 SDValue One = DAG.getConstant(1, DL, VT); 3729 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3730 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3731 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3732 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3733 3734 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3735 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3736 SDValue ShiftRightLo = 3737 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3738 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3739 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3740 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3741 3742 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3743 3744 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3745 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3746 3747 SDValue Parts[2] = {Lo, Hi}; 3748 return DAG.getMergeValues(Parts, DL); 3749 } 3750 3751 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3752 bool IsSRA) const { 3753 SDLoc DL(Op); 3754 SDValue Lo = Op.getOperand(0); 3755 SDValue Hi = Op.getOperand(1); 3756 SDValue Shamt = Op.getOperand(2); 3757 EVT VT = Lo.getValueType(); 3758 3759 // SRA expansion: 3760 // if Shamt-XLEN < 0: // Shamt < XLEN 3761 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3762 // Hi = Hi >>s Shamt 3763 // else: 3764 // Lo = Hi >>s (Shamt-XLEN); 3765 // Hi = Hi >>s (XLEN-1) 3766 // 3767 // SRL expansion: 3768 // if Shamt-XLEN < 0: // Shamt < XLEN 3769 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3770 // Hi = Hi >>u Shamt 3771 // else: 3772 // Lo = Hi >>u (Shamt-XLEN); 3773 // Hi = 0; 3774 3775 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3776 3777 SDValue Zero = DAG.getConstant(0, DL, VT); 3778 SDValue One = DAG.getConstant(1, DL, VT); 3779 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3780 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3781 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3782 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3783 3784 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3785 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3786 SDValue ShiftLeftHi = 3787 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3788 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3789 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3790 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3791 SDValue HiFalse = 3792 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3793 3794 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3795 3796 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3797 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3798 3799 SDValue Parts[2] = {Lo, Hi}; 3800 return DAG.getMergeValues(Parts, DL); 3801 } 3802 3803 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3804 // legal equivalently-sized i8 type, so we can use that as a go-between. 3805 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3806 SelectionDAG &DAG) const { 3807 SDLoc DL(Op); 3808 MVT VT = Op.getSimpleValueType(); 3809 SDValue SplatVal = Op.getOperand(0); 3810 // All-zeros or all-ones splats are handled specially. 3811 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3812 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3813 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3814 } 3815 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3816 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3817 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3818 } 3819 MVT XLenVT = Subtarget.getXLenVT(); 3820 assert(SplatVal.getValueType() == XLenVT && 3821 "Unexpected type for i1 splat value"); 3822 MVT InterVT = VT.changeVectorElementType(MVT::i8); 3823 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 3824 DAG.getConstant(1, DL, XLenVT)); 3825 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 3826 SDValue Zero = DAG.getConstant(0, DL, InterVT); 3827 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 3828 } 3829 3830 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 3831 // illegal (currently only vXi64 RV32). 3832 // FIXME: We could also catch non-constant sign-extended i32 values and lower 3833 // them to SPLAT_VECTOR_I64 3834 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 3835 SelectionDAG &DAG) const { 3836 SDLoc DL(Op); 3837 MVT VecVT = Op.getSimpleValueType(); 3838 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 3839 "Unexpected SPLAT_VECTOR_PARTS lowering"); 3840 3841 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 3842 SDValue Lo = Op.getOperand(0); 3843 SDValue Hi = Op.getOperand(1); 3844 3845 if (VecVT.isFixedLengthVector()) { 3846 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3847 SDLoc DL(Op); 3848 SDValue Mask, VL; 3849 std::tie(Mask, VL) = 3850 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3851 3852 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 3853 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 3854 } 3855 3856 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 3857 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 3858 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 3859 // If Hi constant is all the same sign bit as Lo, lower this as a custom 3860 // node in order to try and match RVV vector/scalar instructions. 3861 if ((LoC >> 31) == HiC) 3862 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3863 } 3864 3865 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 3866 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 3867 isa<ConstantSDNode>(Hi.getOperand(1)) && 3868 Hi.getConstantOperandVal(1) == 31) 3869 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3870 3871 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 3872 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 3873 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64)); 3874 } 3875 3876 // Custom-lower extensions from mask vectors by using a vselect either with 1 3877 // for zero/any-extension or -1 for sign-extension: 3878 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 3879 // Note that any-extension is lowered identically to zero-extension. 3880 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 3881 int64_t ExtTrueVal) const { 3882 SDLoc DL(Op); 3883 MVT VecVT = Op.getSimpleValueType(); 3884 SDValue Src = Op.getOperand(0); 3885 // Only custom-lower extensions from mask types 3886 assert(Src.getValueType().isVector() && 3887 Src.getValueType().getVectorElementType() == MVT::i1); 3888 3889 MVT XLenVT = Subtarget.getXLenVT(); 3890 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 3891 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 3892 3893 if (VecVT.isScalableVector()) { 3894 // Be careful not to introduce illegal scalar types at this stage, and be 3895 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 3896 // illegal and must be expanded. Since we know that the constants are 3897 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 3898 bool IsRV32E64 = 3899 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 3900 3901 if (!IsRV32E64) { 3902 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 3903 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 3904 } else { 3905 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 3906 SplatTrueVal = 3907 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 3908 } 3909 3910 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 3911 } 3912 3913 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3914 MVT I1ContainerVT = 3915 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3916 3917 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 3918 3919 SDValue Mask, VL; 3920 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3921 3922 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 3923 SplatTrueVal = 3924 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 3925 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 3926 SplatTrueVal, SplatZero, VL); 3927 3928 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 3929 } 3930 3931 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 3932 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 3933 MVT ExtVT = Op.getSimpleValueType(); 3934 // Only custom-lower extensions from fixed-length vector types. 3935 if (!ExtVT.isFixedLengthVector()) 3936 return Op; 3937 MVT VT = Op.getOperand(0).getSimpleValueType(); 3938 // Grab the canonical container type for the extended type. Infer the smaller 3939 // type from that to ensure the same number of vector elements, as we know 3940 // the LMUL will be sufficient to hold the smaller type. 3941 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 3942 // Get the extended container type manually to ensure the same number of 3943 // vector elements between source and dest. 3944 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 3945 ContainerExtVT.getVectorElementCount()); 3946 3947 SDValue Op1 = 3948 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 3949 3950 SDLoc DL(Op); 3951 SDValue Mask, VL; 3952 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3953 3954 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 3955 3956 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 3957 } 3958 3959 // Custom-lower truncations from vectors to mask vectors by using a mask and a 3960 // setcc operation: 3961 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 3962 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 3963 SelectionDAG &DAG) const { 3964 SDLoc DL(Op); 3965 EVT MaskVT = Op.getValueType(); 3966 // Only expect to custom-lower truncations to mask types 3967 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 3968 "Unexpected type for vector mask lowering"); 3969 SDValue Src = Op.getOperand(0); 3970 MVT VecVT = Src.getSimpleValueType(); 3971 3972 // If this is a fixed vector, we need to convert it to a scalable vector. 3973 MVT ContainerVT = VecVT; 3974 if (VecVT.isFixedLengthVector()) { 3975 ContainerVT = getContainerForFixedLengthVector(VecVT); 3976 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3977 } 3978 3979 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 3980 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 3981 3982 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 3983 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 3984 3985 if (VecVT.isScalableVector()) { 3986 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 3987 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 3988 } 3989 3990 SDValue Mask, VL; 3991 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3992 3993 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 3994 SDValue Trunc = 3995 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 3996 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 3997 DAG.getCondCode(ISD::SETNE), Mask, VL); 3998 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 3999 } 4000 4001 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4002 // first position of a vector, and that vector is slid up to the insert index. 4003 // By limiting the active vector length to index+1 and merging with the 4004 // original vector (with an undisturbed tail policy for elements >= VL), we 4005 // achieve the desired result of leaving all elements untouched except the one 4006 // at VL-1, which is replaced with the desired value. 4007 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4008 SelectionDAG &DAG) const { 4009 SDLoc DL(Op); 4010 MVT VecVT = Op.getSimpleValueType(); 4011 SDValue Vec = Op.getOperand(0); 4012 SDValue Val = Op.getOperand(1); 4013 SDValue Idx = Op.getOperand(2); 4014 4015 if (VecVT.getVectorElementType() == MVT::i1) { 4016 // FIXME: For now we just promote to an i8 vector and insert into that, 4017 // but this is probably not optimal. 4018 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4019 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4020 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4021 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4022 } 4023 4024 MVT ContainerVT = VecVT; 4025 // If the operand is a fixed-length vector, convert to a scalable one. 4026 if (VecVT.isFixedLengthVector()) { 4027 ContainerVT = getContainerForFixedLengthVector(VecVT); 4028 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4029 } 4030 4031 MVT XLenVT = Subtarget.getXLenVT(); 4032 4033 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4034 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4035 // Even i64-element vectors on RV32 can be lowered without scalar 4036 // legalization if the most-significant 32 bits of the value are not affected 4037 // by the sign-extension of the lower 32 bits. 4038 // TODO: We could also catch sign extensions of a 32-bit value. 4039 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4040 const auto *CVal = cast<ConstantSDNode>(Val); 4041 if (isInt<32>(CVal->getSExtValue())) { 4042 IsLegalInsert = true; 4043 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4044 } 4045 } 4046 4047 SDValue Mask, VL; 4048 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4049 4050 SDValue ValInVec; 4051 4052 if (IsLegalInsert) { 4053 unsigned Opc = 4054 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4055 if (isNullConstant(Idx)) { 4056 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4057 if (!VecVT.isFixedLengthVector()) 4058 return Vec; 4059 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4060 } 4061 ValInVec = 4062 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4063 } else { 4064 // On RV32, i64-element vectors must be specially handled to place the 4065 // value at element 0, by using two vslide1up instructions in sequence on 4066 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4067 // this. 4068 SDValue One = DAG.getConstant(1, DL, XLenVT); 4069 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4070 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4071 MVT I32ContainerVT = 4072 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4073 SDValue I32Mask = 4074 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4075 // Limit the active VL to two. 4076 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4077 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4078 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4079 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 4080 InsertI64VL); 4081 // First slide in the hi value, then the lo in underneath it. 4082 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 4083 ValHi, I32Mask, InsertI64VL); 4084 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 4085 ValLo, I32Mask, InsertI64VL); 4086 // Bitcast back to the right container type. 4087 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4088 } 4089 4090 // Now that the value is in a vector, slide it into position. 4091 SDValue InsertVL = 4092 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4093 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4094 ValInVec, Idx, Mask, InsertVL); 4095 if (!VecVT.isFixedLengthVector()) 4096 return Slideup; 4097 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4098 } 4099 4100 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4101 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4102 // types this is done using VMV_X_S to allow us to glean information about the 4103 // sign bits of the result. 4104 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4105 SelectionDAG &DAG) const { 4106 SDLoc DL(Op); 4107 SDValue Idx = Op.getOperand(1); 4108 SDValue Vec = Op.getOperand(0); 4109 EVT EltVT = Op.getValueType(); 4110 MVT VecVT = Vec.getSimpleValueType(); 4111 MVT XLenVT = Subtarget.getXLenVT(); 4112 4113 if (VecVT.getVectorElementType() == MVT::i1) { 4114 // FIXME: For now we just promote to an i8 vector and extract from that, 4115 // but this is probably not optimal. 4116 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4117 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4118 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4119 } 4120 4121 // If this is a fixed vector, we need to convert it to a scalable vector. 4122 MVT ContainerVT = VecVT; 4123 if (VecVT.isFixedLengthVector()) { 4124 ContainerVT = getContainerForFixedLengthVector(VecVT); 4125 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4126 } 4127 4128 // If the index is 0, the vector is already in the right position. 4129 if (!isNullConstant(Idx)) { 4130 // Use a VL of 1 to avoid processing more elements than we need. 4131 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4132 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4133 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4134 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4135 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4136 } 4137 4138 if (!EltVT.isInteger()) { 4139 // Floating-point extracts are handled in TableGen. 4140 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4141 DAG.getConstant(0, DL, XLenVT)); 4142 } 4143 4144 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4145 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4146 } 4147 4148 // Some RVV intrinsics may claim that they want an integer operand to be 4149 // promoted or expanded. 4150 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 4151 const RISCVSubtarget &Subtarget) { 4152 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4153 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4154 "Unexpected opcode"); 4155 4156 if (!Subtarget.hasVInstructions()) 4157 return SDValue(); 4158 4159 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4160 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4161 SDLoc DL(Op); 4162 4163 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4164 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4165 if (!II || !II->hasSplatOperand()) 4166 return SDValue(); 4167 4168 unsigned SplatOp = II->SplatOperand + 1 + HasChain; 4169 assert(SplatOp < Op.getNumOperands()); 4170 4171 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4172 SDValue &ScalarOp = Operands[SplatOp]; 4173 MVT OpVT = ScalarOp.getSimpleValueType(); 4174 MVT XLenVT = Subtarget.getXLenVT(); 4175 4176 // If this isn't a scalar, or its type is XLenVT we're done. 4177 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4178 return SDValue(); 4179 4180 // Simplest case is that the operand needs to be promoted to XLenVT. 4181 if (OpVT.bitsLT(XLenVT)) { 4182 // If the operand is a constant, sign extend to increase our chances 4183 // of being able to use a .vi instruction. ANY_EXTEND would become a 4184 // a zero extend and the simm5 check in isel would fail. 4185 // FIXME: Should we ignore the upper bits in isel instead? 4186 unsigned ExtOpc = 4187 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4188 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4189 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4190 } 4191 4192 // Use the previous operand to get the vXi64 VT. The result might be a mask 4193 // VT for compares. Using the previous operand assumes that the previous 4194 // operand will never have a smaller element size than a scalar operand and 4195 // that a widening operation never uses SEW=64. 4196 // NOTE: If this fails the below assert, we can probably just find the 4197 // element count from any operand or result and use it to construct the VT. 4198 assert(II->SplatOperand > 0 && "Unexpected splat operand!"); 4199 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4200 4201 // The more complex case is when the scalar is larger than XLenVT. 4202 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4203 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4204 4205 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4206 // on the instruction to sign-extend since SEW>XLEN. 4207 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4208 if (isInt<32>(CVal->getSExtValue())) { 4209 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4210 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4211 } 4212 } 4213 4214 // We need to convert the scalar to a splat vector. 4215 // FIXME: Can we implicitly truncate the scalar if it is known to 4216 // be sign extended? 4217 SDValue VL = Op.getOperand(II->VLOperand + 1 + HasChain); 4218 assert(VL.getValueType() == XLenVT); 4219 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 4220 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4221 } 4222 4223 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4224 SelectionDAG &DAG) const { 4225 unsigned IntNo = Op.getConstantOperandVal(0); 4226 SDLoc DL(Op); 4227 MVT XLenVT = Subtarget.getXLenVT(); 4228 4229 switch (IntNo) { 4230 default: 4231 break; // Don't custom lower most intrinsics. 4232 case Intrinsic::thread_pointer: { 4233 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4234 return DAG.getRegister(RISCV::X4, PtrVT); 4235 } 4236 case Intrinsic::riscv_orc_b: 4237 // Lower to the GORCI encoding for orc.b. 4238 return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1), 4239 DAG.getConstant(7, DL, XLenVT)); 4240 case Intrinsic::riscv_grev: 4241 case Intrinsic::riscv_gorc: { 4242 unsigned Opc = 4243 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4244 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4245 } 4246 case Intrinsic::riscv_shfl: 4247 case Intrinsic::riscv_unshfl: { 4248 unsigned Opc = 4249 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4250 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4251 } 4252 case Intrinsic::riscv_bcompress: 4253 case Intrinsic::riscv_bdecompress: { 4254 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4255 : RISCVISD::BDECOMPRESS; 4256 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4257 } 4258 case Intrinsic::riscv_bfp: 4259 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4260 Op.getOperand(2)); 4261 case Intrinsic::riscv_vmv_x_s: 4262 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4263 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4264 Op.getOperand(1)); 4265 case Intrinsic::riscv_vmv_v_x: 4266 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4267 Op.getSimpleValueType(), DL, DAG, Subtarget); 4268 case Intrinsic::riscv_vfmv_v_f: 4269 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4270 Op.getOperand(1), Op.getOperand(2)); 4271 case Intrinsic::riscv_vmv_s_x: { 4272 SDValue Scalar = Op.getOperand(2); 4273 4274 if (Scalar.getValueType().bitsLE(XLenVT)) { 4275 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4276 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4277 Op.getOperand(1), Scalar, Op.getOperand(3)); 4278 } 4279 4280 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4281 4282 // This is an i64 value that lives in two scalar registers. We have to 4283 // insert this in a convoluted way. First we build vXi64 splat containing 4284 // the/ two values that we assemble using some bit math. Next we'll use 4285 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4286 // to merge element 0 from our splat into the source vector. 4287 // FIXME: This is probably not the best way to do this, but it is 4288 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4289 // point. 4290 // sw lo, (a0) 4291 // sw hi, 4(a0) 4292 // vlse vX, (a0) 4293 // 4294 // vid.v vVid 4295 // vmseq.vx mMask, vVid, 0 4296 // vmerge.vvm vDest, vSrc, vVal, mMask 4297 MVT VT = Op.getSimpleValueType(); 4298 SDValue Vec = Op.getOperand(1); 4299 SDValue VL = Op.getOperand(3); 4300 4301 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 4302 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4303 DAG.getConstant(0, DL, MVT::i32), VL); 4304 4305 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4306 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4307 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4308 SDValue SelectCond = 4309 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4310 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4311 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4312 Vec, VL); 4313 } 4314 case Intrinsic::riscv_vslide1up: 4315 case Intrinsic::riscv_vslide1down: 4316 case Intrinsic::riscv_vslide1up_mask: 4317 case Intrinsic::riscv_vslide1down_mask: { 4318 // We need to special case these when the scalar is larger than XLen. 4319 unsigned NumOps = Op.getNumOperands(); 4320 bool IsMasked = NumOps == 7; 4321 unsigned OpOffset = IsMasked ? 1 : 0; 4322 SDValue Scalar = Op.getOperand(2 + OpOffset); 4323 if (Scalar.getValueType().bitsLE(XLenVT)) 4324 break; 4325 4326 // Splatting a sign extended constant is fine. 4327 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4328 if (isInt<32>(CVal->getSExtValue())) 4329 break; 4330 4331 MVT VT = Op.getSimpleValueType(); 4332 assert(VT.getVectorElementType() == MVT::i64 && 4333 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4334 4335 // Convert the vector source to the equivalent nxvXi32 vector. 4336 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4337 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 4338 4339 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4340 DAG.getConstant(0, DL, XLenVT)); 4341 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4342 DAG.getConstant(1, DL, XLenVT)); 4343 4344 // Double the VL since we halved SEW. 4345 SDValue VL = Op.getOperand(NumOps - (1 + OpOffset)); 4346 SDValue I32VL = 4347 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4348 4349 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4350 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4351 4352 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4353 // instructions. 4354 if (IntNo == Intrinsic::riscv_vslide1up || 4355 IntNo == Intrinsic::riscv_vslide1up_mask) { 4356 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 4357 I32Mask, I32VL); 4358 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 4359 I32Mask, I32VL); 4360 } else { 4361 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 4362 I32Mask, I32VL); 4363 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 4364 I32Mask, I32VL); 4365 } 4366 4367 // Convert back to nxvXi64. 4368 Vec = DAG.getBitcast(VT, Vec); 4369 4370 if (!IsMasked) 4371 return Vec; 4372 4373 // Apply mask after the operation. 4374 SDValue Mask = Op.getOperand(NumOps - 3); 4375 SDValue MaskedOff = Op.getOperand(1); 4376 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4377 } 4378 } 4379 4380 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4381 } 4382 4383 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4384 SelectionDAG &DAG) const { 4385 unsigned IntNo = Op.getConstantOperandVal(1); 4386 switch (IntNo) { 4387 default: 4388 break; 4389 case Intrinsic::riscv_masked_strided_load: { 4390 SDLoc DL(Op); 4391 MVT XLenVT = Subtarget.getXLenVT(); 4392 4393 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4394 // the selection of the masked intrinsics doesn't do this for us. 4395 SDValue Mask = Op.getOperand(5); 4396 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4397 4398 MVT VT = Op->getSimpleValueType(0); 4399 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4400 4401 SDValue PassThru = Op.getOperand(2); 4402 if (!IsUnmasked) { 4403 MVT MaskVT = 4404 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4405 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4406 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4407 } 4408 4409 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4410 4411 SDValue IntID = DAG.getTargetConstant( 4412 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4413 XLenVT); 4414 4415 auto *Load = cast<MemIntrinsicSDNode>(Op); 4416 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4417 if (!IsUnmasked) 4418 Ops.push_back(PassThru); 4419 Ops.push_back(Op.getOperand(3)); // Ptr 4420 Ops.push_back(Op.getOperand(4)); // Stride 4421 if (!IsUnmasked) 4422 Ops.push_back(Mask); 4423 Ops.push_back(VL); 4424 if (!IsUnmasked) { 4425 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4426 Ops.push_back(Policy); 4427 } 4428 4429 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4430 SDValue Result = 4431 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4432 Load->getMemoryVT(), Load->getMemOperand()); 4433 SDValue Chain = Result.getValue(1); 4434 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4435 return DAG.getMergeValues({Result, Chain}, DL); 4436 } 4437 } 4438 4439 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4440 } 4441 4442 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4443 SelectionDAG &DAG) const { 4444 unsigned IntNo = Op.getConstantOperandVal(1); 4445 switch (IntNo) { 4446 default: 4447 break; 4448 case Intrinsic::riscv_masked_strided_store: { 4449 SDLoc DL(Op); 4450 MVT XLenVT = Subtarget.getXLenVT(); 4451 4452 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4453 // the selection of the masked intrinsics doesn't do this for us. 4454 SDValue Mask = Op.getOperand(5); 4455 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4456 4457 SDValue Val = Op.getOperand(2); 4458 MVT VT = Val.getSimpleValueType(); 4459 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4460 4461 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4462 if (!IsUnmasked) { 4463 MVT MaskVT = 4464 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4465 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4466 } 4467 4468 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4469 4470 SDValue IntID = DAG.getTargetConstant( 4471 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4472 XLenVT); 4473 4474 auto *Store = cast<MemIntrinsicSDNode>(Op); 4475 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4476 Ops.push_back(Val); 4477 Ops.push_back(Op.getOperand(3)); // Ptr 4478 Ops.push_back(Op.getOperand(4)); // Stride 4479 if (!IsUnmasked) 4480 Ops.push_back(Mask); 4481 Ops.push_back(VL); 4482 4483 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4484 Ops, Store->getMemoryVT(), 4485 Store->getMemOperand()); 4486 } 4487 } 4488 4489 return SDValue(); 4490 } 4491 4492 static MVT getLMUL1VT(MVT VT) { 4493 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4494 "Unexpected vector MVT"); 4495 return MVT::getScalableVectorVT( 4496 VT.getVectorElementType(), 4497 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4498 } 4499 4500 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4501 switch (ISDOpcode) { 4502 default: 4503 llvm_unreachable("Unhandled reduction"); 4504 case ISD::VECREDUCE_ADD: 4505 return RISCVISD::VECREDUCE_ADD_VL; 4506 case ISD::VECREDUCE_UMAX: 4507 return RISCVISD::VECREDUCE_UMAX_VL; 4508 case ISD::VECREDUCE_SMAX: 4509 return RISCVISD::VECREDUCE_SMAX_VL; 4510 case ISD::VECREDUCE_UMIN: 4511 return RISCVISD::VECREDUCE_UMIN_VL; 4512 case ISD::VECREDUCE_SMIN: 4513 return RISCVISD::VECREDUCE_SMIN_VL; 4514 case ISD::VECREDUCE_AND: 4515 return RISCVISD::VECREDUCE_AND_VL; 4516 case ISD::VECREDUCE_OR: 4517 return RISCVISD::VECREDUCE_OR_VL; 4518 case ISD::VECREDUCE_XOR: 4519 return RISCVISD::VECREDUCE_XOR_VL; 4520 } 4521 } 4522 4523 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4524 SelectionDAG &DAG, 4525 bool IsVP) const { 4526 SDLoc DL(Op); 4527 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4528 MVT VecVT = Vec.getSimpleValueType(); 4529 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4530 Op.getOpcode() == ISD::VECREDUCE_OR || 4531 Op.getOpcode() == ISD::VECREDUCE_XOR || 4532 Op.getOpcode() == ISD::VP_REDUCE_AND || 4533 Op.getOpcode() == ISD::VP_REDUCE_OR || 4534 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4535 "Unexpected reduction lowering"); 4536 4537 MVT XLenVT = Subtarget.getXLenVT(); 4538 assert(Op.getValueType() == XLenVT && 4539 "Expected reduction output to be legalized to XLenVT"); 4540 4541 MVT ContainerVT = VecVT; 4542 if (VecVT.isFixedLengthVector()) { 4543 ContainerVT = getContainerForFixedLengthVector(VecVT); 4544 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4545 } 4546 4547 SDValue Mask, VL; 4548 if (IsVP) { 4549 Mask = Op.getOperand(2); 4550 VL = Op.getOperand(3); 4551 } else { 4552 std::tie(Mask, VL) = 4553 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4554 } 4555 4556 unsigned BaseOpc; 4557 ISD::CondCode CC; 4558 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4559 4560 switch (Op.getOpcode()) { 4561 default: 4562 llvm_unreachable("Unhandled reduction"); 4563 case ISD::VECREDUCE_AND: 4564 case ISD::VP_REDUCE_AND: { 4565 // vcpop ~x == 0 4566 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4567 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4568 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4569 CC = ISD::SETEQ; 4570 BaseOpc = ISD::AND; 4571 break; 4572 } 4573 case ISD::VECREDUCE_OR: 4574 case ISD::VP_REDUCE_OR: 4575 // vcpop x != 0 4576 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4577 CC = ISD::SETNE; 4578 BaseOpc = ISD::OR; 4579 break; 4580 case ISD::VECREDUCE_XOR: 4581 case ISD::VP_REDUCE_XOR: { 4582 // ((vcpop x) & 1) != 0 4583 SDValue One = DAG.getConstant(1, DL, XLenVT); 4584 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4585 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4586 CC = ISD::SETNE; 4587 BaseOpc = ISD::XOR; 4588 break; 4589 } 4590 } 4591 4592 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4593 4594 if (!IsVP) 4595 return SetCC; 4596 4597 // Now include the start value in the operation. 4598 // Note that we must return the start value when no elements are operated 4599 // upon. The vcpop instructions we've emitted in each case above will return 4600 // 0 for an inactive vector, and so we've already received the neutral value: 4601 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4602 // can simply include the start value. 4603 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4604 } 4605 4606 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4607 SelectionDAG &DAG) const { 4608 SDLoc DL(Op); 4609 SDValue Vec = Op.getOperand(0); 4610 EVT VecEVT = Vec.getValueType(); 4611 4612 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4613 4614 // Due to ordering in legalize types we may have a vector type that needs to 4615 // be split. Do that manually so we can get down to a legal type. 4616 while (getTypeAction(*DAG.getContext(), VecEVT) == 4617 TargetLowering::TypeSplitVector) { 4618 SDValue Lo, Hi; 4619 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4620 VecEVT = Lo.getValueType(); 4621 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4622 } 4623 4624 // TODO: The type may need to be widened rather than split. Or widened before 4625 // it can be split. 4626 if (!isTypeLegal(VecEVT)) 4627 return SDValue(); 4628 4629 MVT VecVT = VecEVT.getSimpleVT(); 4630 MVT VecEltVT = VecVT.getVectorElementType(); 4631 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4632 4633 MVT ContainerVT = VecVT; 4634 if (VecVT.isFixedLengthVector()) { 4635 ContainerVT = getContainerForFixedLengthVector(VecVT); 4636 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4637 } 4638 4639 MVT M1VT = getLMUL1VT(ContainerVT); 4640 MVT XLenVT = Subtarget.getXLenVT(); 4641 4642 SDValue Mask, VL; 4643 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4644 4645 SDValue NeutralElem = 4646 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4647 SDValue IdentitySplat = lowerScalarSplat( 4648 NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4649 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4650 IdentitySplat, Mask, VL); 4651 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4652 DAG.getConstant(0, DL, XLenVT)); 4653 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4654 } 4655 4656 // Given a reduction op, this function returns the matching reduction opcode, 4657 // the vector SDValue and the scalar SDValue required to lower this to a 4658 // RISCVISD node. 4659 static std::tuple<unsigned, SDValue, SDValue> 4660 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4661 SDLoc DL(Op); 4662 auto Flags = Op->getFlags(); 4663 unsigned Opcode = Op.getOpcode(); 4664 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4665 switch (Opcode) { 4666 default: 4667 llvm_unreachable("Unhandled reduction"); 4668 case ISD::VECREDUCE_FADD: { 4669 // Use positive zero if we can. It is cheaper to materialize. 4670 SDValue Zero = 4671 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 4672 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 4673 } 4674 case ISD::VECREDUCE_SEQ_FADD: 4675 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4676 Op.getOperand(0)); 4677 case ISD::VECREDUCE_FMIN: 4678 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4679 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4680 case ISD::VECREDUCE_FMAX: 4681 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4682 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4683 } 4684 } 4685 4686 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4687 SelectionDAG &DAG) const { 4688 SDLoc DL(Op); 4689 MVT VecEltVT = Op.getSimpleValueType(); 4690 4691 unsigned RVVOpcode; 4692 SDValue VectorVal, ScalarVal; 4693 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4694 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4695 MVT VecVT = VectorVal.getSimpleValueType(); 4696 4697 MVT ContainerVT = VecVT; 4698 if (VecVT.isFixedLengthVector()) { 4699 ContainerVT = getContainerForFixedLengthVector(VecVT); 4700 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4701 } 4702 4703 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4704 MVT XLenVT = Subtarget.getXLenVT(); 4705 4706 SDValue Mask, VL; 4707 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4708 4709 SDValue ScalarSplat = lowerScalarSplat( 4710 ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4711 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4712 VectorVal, ScalarSplat, Mask, VL); 4713 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4714 DAG.getConstant(0, DL, XLenVT)); 4715 } 4716 4717 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4718 switch (ISDOpcode) { 4719 default: 4720 llvm_unreachable("Unhandled reduction"); 4721 case ISD::VP_REDUCE_ADD: 4722 return RISCVISD::VECREDUCE_ADD_VL; 4723 case ISD::VP_REDUCE_UMAX: 4724 return RISCVISD::VECREDUCE_UMAX_VL; 4725 case ISD::VP_REDUCE_SMAX: 4726 return RISCVISD::VECREDUCE_SMAX_VL; 4727 case ISD::VP_REDUCE_UMIN: 4728 return RISCVISD::VECREDUCE_UMIN_VL; 4729 case ISD::VP_REDUCE_SMIN: 4730 return RISCVISD::VECREDUCE_SMIN_VL; 4731 case ISD::VP_REDUCE_AND: 4732 return RISCVISD::VECREDUCE_AND_VL; 4733 case ISD::VP_REDUCE_OR: 4734 return RISCVISD::VECREDUCE_OR_VL; 4735 case ISD::VP_REDUCE_XOR: 4736 return RISCVISD::VECREDUCE_XOR_VL; 4737 case ISD::VP_REDUCE_FADD: 4738 return RISCVISD::VECREDUCE_FADD_VL; 4739 case ISD::VP_REDUCE_SEQ_FADD: 4740 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 4741 case ISD::VP_REDUCE_FMAX: 4742 return RISCVISD::VECREDUCE_FMAX_VL; 4743 case ISD::VP_REDUCE_FMIN: 4744 return RISCVISD::VECREDUCE_FMIN_VL; 4745 } 4746 } 4747 4748 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 4749 SelectionDAG &DAG) const { 4750 SDLoc DL(Op); 4751 SDValue Vec = Op.getOperand(1); 4752 EVT VecEVT = Vec.getValueType(); 4753 4754 // TODO: The type may need to be widened rather than split. Or widened before 4755 // it can be split. 4756 if (!isTypeLegal(VecEVT)) 4757 return SDValue(); 4758 4759 MVT VecVT = VecEVT.getSimpleVT(); 4760 MVT VecEltVT = VecVT.getVectorElementType(); 4761 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 4762 4763 MVT ContainerVT = VecVT; 4764 if (VecVT.isFixedLengthVector()) { 4765 ContainerVT = getContainerForFixedLengthVector(VecVT); 4766 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4767 } 4768 4769 SDValue VL = Op.getOperand(3); 4770 SDValue Mask = Op.getOperand(2); 4771 4772 MVT M1VT = getLMUL1VT(ContainerVT); 4773 MVT XLenVT = Subtarget.getXLenVT(); 4774 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 4775 4776 SDValue StartSplat = 4777 lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT, 4778 DL, DAG, Subtarget); 4779 SDValue Reduction = 4780 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 4781 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 4782 DAG.getConstant(0, DL, XLenVT)); 4783 if (!VecVT.isInteger()) 4784 return Elt0; 4785 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4786 } 4787 4788 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4789 SelectionDAG &DAG) const { 4790 SDValue Vec = Op.getOperand(0); 4791 SDValue SubVec = Op.getOperand(1); 4792 MVT VecVT = Vec.getSimpleValueType(); 4793 MVT SubVecVT = SubVec.getSimpleValueType(); 4794 4795 SDLoc DL(Op); 4796 MVT XLenVT = Subtarget.getXLenVT(); 4797 unsigned OrigIdx = Op.getConstantOperandVal(2); 4798 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4799 4800 // We don't have the ability to slide mask vectors up indexed by their i1 4801 // elements; the smallest we can do is i8. Often we are able to bitcast to 4802 // equivalent i8 vectors. Note that when inserting a fixed-length vector 4803 // into a scalable one, we might not necessarily have enough scalable 4804 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 4805 if (SubVecVT.getVectorElementType() == MVT::i1 && 4806 (OrigIdx != 0 || !Vec.isUndef())) { 4807 if (VecVT.getVectorMinNumElements() >= 8 && 4808 SubVecVT.getVectorMinNumElements() >= 8) { 4809 assert(OrigIdx % 8 == 0 && "Invalid index"); 4810 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4811 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4812 "Unexpected mask vector lowering"); 4813 OrigIdx /= 8; 4814 SubVecVT = 4815 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4816 SubVecVT.isScalableVector()); 4817 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4818 VecVT.isScalableVector()); 4819 Vec = DAG.getBitcast(VecVT, Vec); 4820 SubVec = DAG.getBitcast(SubVecVT, SubVec); 4821 } else { 4822 // We can't slide this mask vector up indexed by its i1 elements. 4823 // This poses a problem when we wish to insert a scalable vector which 4824 // can't be re-expressed as a larger type. Just choose the slow path and 4825 // extend to a larger type, then truncate back down. 4826 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4827 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4828 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4829 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 4830 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 4831 Op.getOperand(2)); 4832 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 4833 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 4834 } 4835 } 4836 4837 // If the subvector vector is a fixed-length type, we cannot use subregister 4838 // manipulation to simplify the codegen; we don't know which register of a 4839 // LMUL group contains the specific subvector as we only know the minimum 4840 // register size. Therefore we must slide the vector group up the full 4841 // amount. 4842 if (SubVecVT.isFixedLengthVector()) { 4843 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 4844 return Op; 4845 MVT ContainerVT = VecVT; 4846 if (VecVT.isFixedLengthVector()) { 4847 ContainerVT = getContainerForFixedLengthVector(VecVT); 4848 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4849 } 4850 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 4851 DAG.getUNDEF(ContainerVT), SubVec, 4852 DAG.getConstant(0, DL, XLenVT)); 4853 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 4854 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 4855 return DAG.getBitcast(Op.getValueType(), SubVec); 4856 } 4857 SDValue Mask = 4858 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4859 // Set the vector length to only the number of elements we care about. Note 4860 // that for slideup this includes the offset. 4861 SDValue VL = 4862 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 4863 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4864 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4865 SubVec, SlideupAmt, Mask, VL); 4866 if (VecVT.isFixedLengthVector()) 4867 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4868 return DAG.getBitcast(Op.getValueType(), Slideup); 4869 } 4870 4871 unsigned SubRegIdx, RemIdx; 4872 std::tie(SubRegIdx, RemIdx) = 4873 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4874 VecVT, SubVecVT, OrigIdx, TRI); 4875 4876 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 4877 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 4878 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 4879 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 4880 4881 // 1. If the Idx has been completely eliminated and this subvector's size is 4882 // a vector register or a multiple thereof, or the surrounding elements are 4883 // undef, then this is a subvector insert which naturally aligns to a vector 4884 // register. These can easily be handled using subregister manipulation. 4885 // 2. If the subvector is smaller than a vector register, then the insertion 4886 // must preserve the undisturbed elements of the register. We do this by 4887 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 4888 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 4889 // subvector within the vector register, and an INSERT_SUBVECTOR of that 4890 // LMUL=1 type back into the larger vector (resolving to another subregister 4891 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 4892 // to avoid allocating a large register group to hold our subvector. 4893 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 4894 return Op; 4895 4896 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 4897 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 4898 // (in our case undisturbed). This means we can set up a subvector insertion 4899 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 4900 // size of the subvector. 4901 MVT InterSubVT = VecVT; 4902 SDValue AlignedExtract = Vec; 4903 unsigned AlignedIdx = OrigIdx - RemIdx; 4904 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4905 InterSubVT = getLMUL1VT(VecVT); 4906 // Extract a subvector equal to the nearest full vector register type. This 4907 // should resolve to a EXTRACT_SUBREG instruction. 4908 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4909 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4910 } 4911 4912 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4913 // For scalable vectors this must be further multiplied by vscale. 4914 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 4915 4916 SDValue Mask, VL; 4917 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4918 4919 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 4920 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 4921 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 4922 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 4923 4924 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 4925 DAG.getUNDEF(InterSubVT), SubVec, 4926 DAG.getConstant(0, DL, XLenVT)); 4927 4928 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 4929 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 4930 4931 // If required, insert this subvector back into the correct vector register. 4932 // This should resolve to an INSERT_SUBREG instruction. 4933 if (VecVT.bitsGT(InterSubVT)) 4934 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 4935 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4936 4937 // We might have bitcast from a mask type: cast back to the original type if 4938 // required. 4939 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 4940 } 4941 4942 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 4943 SelectionDAG &DAG) const { 4944 SDValue Vec = Op.getOperand(0); 4945 MVT SubVecVT = Op.getSimpleValueType(); 4946 MVT VecVT = Vec.getSimpleValueType(); 4947 4948 SDLoc DL(Op); 4949 MVT XLenVT = Subtarget.getXLenVT(); 4950 unsigned OrigIdx = Op.getConstantOperandVal(1); 4951 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4952 4953 // We don't have the ability to slide mask vectors down indexed by their i1 4954 // elements; the smallest we can do is i8. Often we are able to bitcast to 4955 // equivalent i8 vectors. Note that when extracting a fixed-length vector 4956 // from a scalable one, we might not necessarily have enough scalable 4957 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 4958 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 4959 if (VecVT.getVectorMinNumElements() >= 8 && 4960 SubVecVT.getVectorMinNumElements() >= 8) { 4961 assert(OrigIdx % 8 == 0 && "Invalid index"); 4962 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4963 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4964 "Unexpected mask vector lowering"); 4965 OrigIdx /= 8; 4966 SubVecVT = 4967 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4968 SubVecVT.isScalableVector()); 4969 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4970 VecVT.isScalableVector()); 4971 Vec = DAG.getBitcast(VecVT, Vec); 4972 } else { 4973 // We can't slide this mask vector down, indexed by its i1 elements. 4974 // This poses a problem when we wish to extract a scalable vector which 4975 // can't be re-expressed as a larger type. Just choose the slow path and 4976 // extend to a larger type, then truncate back down. 4977 // TODO: We could probably improve this when extracting certain fixed 4978 // from fixed, where we can extract as i8 and shift the correct element 4979 // right to reach the desired subvector? 4980 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4981 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4982 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4983 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 4984 Op.getOperand(1)); 4985 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 4986 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 4987 } 4988 } 4989 4990 // If the subvector vector is a fixed-length type, we cannot use subregister 4991 // manipulation to simplify the codegen; we don't know which register of a 4992 // LMUL group contains the specific subvector as we only know the minimum 4993 // register size. Therefore we must slide the vector group down the full 4994 // amount. 4995 if (SubVecVT.isFixedLengthVector()) { 4996 // With an index of 0 this is a cast-like subvector, which can be performed 4997 // with subregister operations. 4998 if (OrigIdx == 0) 4999 return Op; 5000 MVT ContainerVT = VecVT; 5001 if (VecVT.isFixedLengthVector()) { 5002 ContainerVT = getContainerForFixedLengthVector(VecVT); 5003 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5004 } 5005 SDValue Mask = 5006 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5007 // Set the vector length to only the number of elements we care about. This 5008 // avoids sliding down elements we're going to discard straight away. 5009 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5010 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5011 SDValue Slidedown = 5012 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5013 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5014 // Now we can use a cast-like subvector extract to get the result. 5015 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5016 DAG.getConstant(0, DL, XLenVT)); 5017 return DAG.getBitcast(Op.getValueType(), Slidedown); 5018 } 5019 5020 unsigned SubRegIdx, RemIdx; 5021 std::tie(SubRegIdx, RemIdx) = 5022 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5023 VecVT, SubVecVT, OrigIdx, TRI); 5024 5025 // If the Idx has been completely eliminated then this is a subvector extract 5026 // which naturally aligns to a vector register. These can easily be handled 5027 // using subregister manipulation. 5028 if (RemIdx == 0) 5029 return Op; 5030 5031 // Else we must shift our vector register directly to extract the subvector. 5032 // Do this using VSLIDEDOWN. 5033 5034 // If the vector type is an LMUL-group type, extract a subvector equal to the 5035 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5036 // instruction. 5037 MVT InterSubVT = VecVT; 5038 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5039 InterSubVT = getLMUL1VT(VecVT); 5040 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5041 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5042 } 5043 5044 // Slide this vector register down by the desired number of elements in order 5045 // to place the desired subvector starting at element 0. 5046 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5047 // For scalable vectors this must be further multiplied by vscale. 5048 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5049 5050 SDValue Mask, VL; 5051 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5052 SDValue Slidedown = 5053 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5054 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5055 5056 // Now the vector is in the right position, extract our final subvector. This 5057 // should resolve to a COPY. 5058 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5059 DAG.getConstant(0, DL, XLenVT)); 5060 5061 // We might have bitcast from a mask type: cast back to the original type if 5062 // required. 5063 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5064 } 5065 5066 // Lower step_vector to the vid instruction. Any non-identity step value must 5067 // be accounted for my manual expansion. 5068 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5069 SelectionDAG &DAG) const { 5070 SDLoc DL(Op); 5071 MVT VT = Op.getSimpleValueType(); 5072 MVT XLenVT = Subtarget.getXLenVT(); 5073 SDValue Mask, VL; 5074 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5075 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5076 uint64_t StepValImm = Op.getConstantOperandVal(0); 5077 if (StepValImm != 1) { 5078 if (isPowerOf2_64(StepValImm)) { 5079 SDValue StepVal = 5080 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 5081 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5082 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5083 } else { 5084 SDValue StepVal = lowerScalarSplat( 5085 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 5086 DL, DAG, Subtarget); 5087 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5088 } 5089 } 5090 return StepVec; 5091 } 5092 5093 // Implement vector_reverse using vrgather.vv with indices determined by 5094 // subtracting the id of each element from (VLMAX-1). This will convert 5095 // the indices like so: 5096 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5097 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5098 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5099 SelectionDAG &DAG) const { 5100 SDLoc DL(Op); 5101 MVT VecVT = Op.getSimpleValueType(); 5102 unsigned EltSize = VecVT.getScalarSizeInBits(); 5103 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5104 5105 unsigned MaxVLMAX = 0; 5106 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5107 if (VectorBitsMax != 0) 5108 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5109 5110 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5111 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5112 5113 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5114 // to use vrgatherei16.vv. 5115 // TODO: It's also possible to use vrgatherei16.vv for other types to 5116 // decrease register width for the index calculation. 5117 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5118 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5119 // Reverse each half, then reassemble them in reverse order. 5120 // NOTE: It's also possible that after splitting that VLMAX no longer 5121 // requires vrgatherei16.vv. 5122 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5123 SDValue Lo, Hi; 5124 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5125 EVT LoVT, HiVT; 5126 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5127 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5128 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5129 // Reassemble the low and high pieces reversed. 5130 // FIXME: This is a CONCAT_VECTORS. 5131 SDValue Res = 5132 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5133 DAG.getIntPtrConstant(0, DL)); 5134 return DAG.getNode( 5135 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5136 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5137 } 5138 5139 // Just promote the int type to i16 which will double the LMUL. 5140 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5141 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5142 } 5143 5144 MVT XLenVT = Subtarget.getXLenVT(); 5145 SDValue Mask, VL; 5146 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5147 5148 // Calculate VLMAX-1 for the desired SEW. 5149 unsigned MinElts = VecVT.getVectorMinNumElements(); 5150 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5151 DAG.getConstant(MinElts, DL, XLenVT)); 5152 SDValue VLMinus1 = 5153 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5154 5155 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5156 bool IsRV32E64 = 5157 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5158 SDValue SplatVL; 5159 if (!IsRV32E64) 5160 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5161 else 5162 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 5163 5164 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5165 SDValue Indices = 5166 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5167 5168 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5169 } 5170 5171 SDValue 5172 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5173 SelectionDAG &DAG) const { 5174 SDLoc DL(Op); 5175 auto *Load = cast<LoadSDNode>(Op); 5176 5177 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5178 Load->getMemoryVT(), 5179 *Load->getMemOperand()) && 5180 "Expecting a correctly-aligned load"); 5181 5182 MVT VT = Op.getSimpleValueType(); 5183 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5184 5185 SDValue VL = 5186 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5187 5188 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5189 SDValue NewLoad = DAG.getMemIntrinsicNode( 5190 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5191 Load->getMemoryVT(), Load->getMemOperand()); 5192 5193 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5194 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5195 } 5196 5197 SDValue 5198 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5199 SelectionDAG &DAG) const { 5200 SDLoc DL(Op); 5201 auto *Store = cast<StoreSDNode>(Op); 5202 5203 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5204 Store->getMemoryVT(), 5205 *Store->getMemOperand()) && 5206 "Expecting a correctly-aligned store"); 5207 5208 SDValue StoreVal = Store->getValue(); 5209 MVT VT = StoreVal.getSimpleValueType(); 5210 5211 // If the size less than a byte, we need to pad with zeros to make a byte. 5212 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5213 VT = MVT::v8i1; 5214 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5215 DAG.getConstant(0, DL, VT), StoreVal, 5216 DAG.getIntPtrConstant(0, DL)); 5217 } 5218 5219 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5220 5221 SDValue VL = 5222 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5223 5224 SDValue NewValue = 5225 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5226 return DAG.getMemIntrinsicNode( 5227 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5228 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5229 Store->getMemoryVT(), Store->getMemOperand()); 5230 } 5231 5232 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5233 SelectionDAG &DAG) const { 5234 SDLoc DL(Op); 5235 MVT VT = Op.getSimpleValueType(); 5236 5237 const auto *MemSD = cast<MemSDNode>(Op); 5238 EVT MemVT = MemSD->getMemoryVT(); 5239 MachineMemOperand *MMO = MemSD->getMemOperand(); 5240 SDValue Chain = MemSD->getChain(); 5241 SDValue BasePtr = MemSD->getBasePtr(); 5242 5243 SDValue Mask, PassThru, VL; 5244 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5245 Mask = VPLoad->getMask(); 5246 PassThru = DAG.getUNDEF(VT); 5247 VL = VPLoad->getVectorLength(); 5248 } else { 5249 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5250 Mask = MLoad->getMask(); 5251 PassThru = MLoad->getPassThru(); 5252 } 5253 5254 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5255 5256 MVT XLenVT = Subtarget.getXLenVT(); 5257 5258 MVT ContainerVT = VT; 5259 if (VT.isFixedLengthVector()) { 5260 ContainerVT = getContainerForFixedLengthVector(VT); 5261 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5262 if (!IsUnmasked) { 5263 MVT MaskVT = 5264 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5265 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5266 } 5267 } 5268 5269 if (!VL) 5270 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5271 5272 unsigned IntID = 5273 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5274 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5275 if (!IsUnmasked) 5276 Ops.push_back(PassThru); 5277 Ops.push_back(BasePtr); 5278 if (!IsUnmasked) 5279 Ops.push_back(Mask); 5280 Ops.push_back(VL); 5281 if (!IsUnmasked) 5282 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5283 5284 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5285 5286 SDValue Result = 5287 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5288 Chain = Result.getValue(1); 5289 5290 if (VT.isFixedLengthVector()) 5291 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5292 5293 return DAG.getMergeValues({Result, Chain}, DL); 5294 } 5295 5296 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5297 SelectionDAG &DAG) const { 5298 SDLoc DL(Op); 5299 5300 const auto *MemSD = cast<MemSDNode>(Op); 5301 EVT MemVT = MemSD->getMemoryVT(); 5302 MachineMemOperand *MMO = MemSD->getMemOperand(); 5303 SDValue Chain = MemSD->getChain(); 5304 SDValue BasePtr = MemSD->getBasePtr(); 5305 SDValue Val, Mask, VL; 5306 5307 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5308 Val = VPStore->getValue(); 5309 Mask = VPStore->getMask(); 5310 VL = VPStore->getVectorLength(); 5311 } else { 5312 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5313 Val = MStore->getValue(); 5314 Mask = MStore->getMask(); 5315 } 5316 5317 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5318 5319 MVT VT = Val.getSimpleValueType(); 5320 MVT XLenVT = Subtarget.getXLenVT(); 5321 5322 MVT ContainerVT = VT; 5323 if (VT.isFixedLengthVector()) { 5324 ContainerVT = getContainerForFixedLengthVector(VT); 5325 5326 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5327 if (!IsUnmasked) { 5328 MVT MaskVT = 5329 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5330 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5331 } 5332 } 5333 5334 if (!VL) 5335 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5336 5337 unsigned IntID = 5338 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5339 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5340 Ops.push_back(Val); 5341 Ops.push_back(BasePtr); 5342 if (!IsUnmasked) 5343 Ops.push_back(Mask); 5344 Ops.push_back(VL); 5345 5346 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5347 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5348 } 5349 5350 SDValue 5351 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5352 SelectionDAG &DAG) const { 5353 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5354 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5355 5356 MVT VT = Op.getSimpleValueType(); 5357 5358 SDValue Op1 = 5359 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5360 SDValue Op2 = 5361 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5362 5363 SDLoc DL(Op); 5364 SDValue VL = 5365 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5366 5367 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5368 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5369 5370 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5371 Op.getOperand(2), Mask, VL); 5372 5373 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5374 } 5375 5376 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5377 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5378 MVT VT = Op.getSimpleValueType(); 5379 5380 if (VT.getVectorElementType() == MVT::i1) 5381 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5382 5383 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5384 } 5385 5386 SDValue 5387 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5388 SelectionDAG &DAG) const { 5389 unsigned Opc; 5390 switch (Op.getOpcode()) { 5391 default: llvm_unreachable("Unexpected opcode!"); 5392 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5393 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5394 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5395 } 5396 5397 return lowerToScalableOp(Op, DAG, Opc); 5398 } 5399 5400 // Lower vector ABS to smax(X, sub(0, X)). 5401 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5402 SDLoc DL(Op); 5403 MVT VT = Op.getSimpleValueType(); 5404 SDValue X = Op.getOperand(0); 5405 5406 assert(VT.isFixedLengthVector() && "Unexpected type"); 5407 5408 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5409 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5410 5411 SDValue Mask, VL; 5412 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5413 5414 SDValue SplatZero = 5415 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5416 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5417 SDValue NegX = 5418 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5419 SDValue Max = 5420 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5421 5422 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5423 } 5424 5425 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5426 SDValue Op, SelectionDAG &DAG) const { 5427 SDLoc DL(Op); 5428 MVT VT = Op.getSimpleValueType(); 5429 SDValue Mag = Op.getOperand(0); 5430 SDValue Sign = Op.getOperand(1); 5431 assert(Mag.getValueType() == Sign.getValueType() && 5432 "Can only handle COPYSIGN with matching types."); 5433 5434 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5435 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5436 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5437 5438 SDValue Mask, VL; 5439 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5440 5441 SDValue CopySign = 5442 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5443 5444 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5445 } 5446 5447 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5448 SDValue Op, SelectionDAG &DAG) const { 5449 MVT VT = Op.getSimpleValueType(); 5450 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5451 5452 MVT I1ContainerVT = 5453 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5454 5455 SDValue CC = 5456 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5457 SDValue Op1 = 5458 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5459 SDValue Op2 = 5460 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5461 5462 SDLoc DL(Op); 5463 SDValue Mask, VL; 5464 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5465 5466 SDValue Select = 5467 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5468 5469 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5470 } 5471 5472 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5473 unsigned NewOpc, 5474 bool HasMask) const { 5475 MVT VT = Op.getSimpleValueType(); 5476 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5477 5478 // Create list of operands by converting existing ones to scalable types. 5479 SmallVector<SDValue, 6> Ops; 5480 for (const SDValue &V : Op->op_values()) { 5481 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5482 5483 // Pass through non-vector operands. 5484 if (!V.getValueType().isVector()) { 5485 Ops.push_back(V); 5486 continue; 5487 } 5488 5489 // "cast" fixed length vector to a scalable vector. 5490 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5491 "Only fixed length vectors are supported!"); 5492 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5493 } 5494 5495 SDLoc DL(Op); 5496 SDValue Mask, VL; 5497 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5498 if (HasMask) 5499 Ops.push_back(Mask); 5500 Ops.push_back(VL); 5501 5502 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5503 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5504 } 5505 5506 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5507 // * Operands of each node are assumed to be in the same order. 5508 // * The EVL operand is promoted from i32 to i64 on RV64. 5509 // * Fixed-length vectors are converted to their scalable-vector container 5510 // types. 5511 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5512 unsigned RISCVISDOpc) const { 5513 SDLoc DL(Op); 5514 MVT VT = Op.getSimpleValueType(); 5515 SmallVector<SDValue, 4> Ops; 5516 5517 for (const auto &OpIdx : enumerate(Op->ops())) { 5518 SDValue V = OpIdx.value(); 5519 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5520 // Pass through operands which aren't fixed-length vectors. 5521 if (!V.getValueType().isFixedLengthVector()) { 5522 Ops.push_back(V); 5523 continue; 5524 } 5525 // "cast" fixed length vector to a scalable vector. 5526 MVT OpVT = V.getSimpleValueType(); 5527 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5528 assert(useRVVForFixedLengthVectorVT(OpVT) && 5529 "Only fixed length vectors are supported!"); 5530 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5531 } 5532 5533 if (!VT.isFixedLengthVector()) 5534 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5535 5536 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5537 5538 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5539 5540 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5541 } 5542 5543 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 5544 unsigned MaskOpc, 5545 unsigned VecOpc) const { 5546 MVT VT = Op.getSimpleValueType(); 5547 if (VT.getVectorElementType() != MVT::i1) 5548 return lowerVPOp(Op, DAG, VecOpc); 5549 5550 // It is safe to drop mask parameter as masked-off elements are undef. 5551 SDValue Op1 = Op->getOperand(0); 5552 SDValue Op2 = Op->getOperand(1); 5553 SDValue VL = Op->getOperand(3); 5554 5555 MVT ContainerVT = VT; 5556 const bool IsFixed = VT.isFixedLengthVector(); 5557 if (IsFixed) { 5558 ContainerVT = getContainerForFixedLengthVector(VT); 5559 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 5560 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 5561 } 5562 5563 SDLoc DL(Op); 5564 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 5565 if (!IsFixed) 5566 return Val; 5567 return convertFromScalableVector(VT, Val, DAG, Subtarget); 5568 } 5569 5570 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5571 // matched to a RVV indexed load. The RVV indexed load instructions only 5572 // support the "unsigned unscaled" addressing mode; indices are implicitly 5573 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5574 // signed or scaled indexing is extended to the XLEN value type and scaled 5575 // accordingly. 5576 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5577 SelectionDAG &DAG) const { 5578 SDLoc DL(Op); 5579 MVT VT = Op.getSimpleValueType(); 5580 5581 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5582 EVT MemVT = MemSD->getMemoryVT(); 5583 MachineMemOperand *MMO = MemSD->getMemOperand(); 5584 SDValue Chain = MemSD->getChain(); 5585 SDValue BasePtr = MemSD->getBasePtr(); 5586 5587 ISD::LoadExtType LoadExtType; 5588 SDValue Index, Mask, PassThru, VL; 5589 5590 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5591 Index = VPGN->getIndex(); 5592 Mask = VPGN->getMask(); 5593 PassThru = DAG.getUNDEF(VT); 5594 VL = VPGN->getVectorLength(); 5595 // VP doesn't support extending loads. 5596 LoadExtType = ISD::NON_EXTLOAD; 5597 } else { 5598 // Else it must be a MGATHER. 5599 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5600 Index = MGN->getIndex(); 5601 Mask = MGN->getMask(); 5602 PassThru = MGN->getPassThru(); 5603 LoadExtType = MGN->getExtensionType(); 5604 } 5605 5606 MVT IndexVT = Index.getSimpleValueType(); 5607 MVT XLenVT = Subtarget.getXLenVT(); 5608 5609 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5610 "Unexpected VTs!"); 5611 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5612 // Targets have to explicitly opt-in for extending vector loads. 5613 assert(LoadExtType == ISD::NON_EXTLOAD && 5614 "Unexpected extending MGATHER/VP_GATHER"); 5615 (void)LoadExtType; 5616 5617 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5618 // the selection of the masked intrinsics doesn't do this for us. 5619 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5620 5621 MVT ContainerVT = VT; 5622 if (VT.isFixedLengthVector()) { 5623 // We need to use the larger of the result and index type to determine the 5624 // scalable type to use so we don't increase LMUL for any operand/result. 5625 if (VT.bitsGE(IndexVT)) { 5626 ContainerVT = getContainerForFixedLengthVector(VT); 5627 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5628 ContainerVT.getVectorElementCount()); 5629 } else { 5630 IndexVT = getContainerForFixedLengthVector(IndexVT); 5631 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5632 IndexVT.getVectorElementCount()); 5633 } 5634 5635 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5636 5637 if (!IsUnmasked) { 5638 MVT MaskVT = 5639 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5640 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5641 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5642 } 5643 } 5644 5645 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 5646 IndexVT = IndexVT.changeVectorElementType(XLenVT); 5647 Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index); 5648 } 5649 5650 if (!VL) 5651 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5652 5653 unsigned IntID = 5654 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5655 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5656 if (!IsUnmasked) 5657 Ops.push_back(PassThru); 5658 Ops.push_back(BasePtr); 5659 Ops.push_back(Index); 5660 if (!IsUnmasked) 5661 Ops.push_back(Mask); 5662 Ops.push_back(VL); 5663 if (!IsUnmasked) 5664 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5665 5666 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5667 SDValue Result = 5668 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5669 Chain = Result.getValue(1); 5670 5671 if (VT.isFixedLengthVector()) 5672 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5673 5674 return DAG.getMergeValues({Result, Chain}, DL); 5675 } 5676 5677 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5678 // matched to a RVV indexed store. The RVV indexed store instructions only 5679 // support the "unsigned unscaled" addressing mode; indices are implicitly 5680 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5681 // signed or scaled indexing is extended to the XLEN value type and scaled 5682 // accordingly. 5683 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5684 SelectionDAG &DAG) const { 5685 SDLoc DL(Op); 5686 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5687 EVT MemVT = MemSD->getMemoryVT(); 5688 MachineMemOperand *MMO = MemSD->getMemOperand(); 5689 SDValue Chain = MemSD->getChain(); 5690 SDValue BasePtr = MemSD->getBasePtr(); 5691 5692 bool IsTruncatingStore = false; 5693 SDValue Index, Mask, Val, VL; 5694 5695 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5696 Index = VPSN->getIndex(); 5697 Mask = VPSN->getMask(); 5698 Val = VPSN->getValue(); 5699 VL = VPSN->getVectorLength(); 5700 // VP doesn't support truncating stores. 5701 IsTruncatingStore = false; 5702 } else { 5703 // Else it must be a MSCATTER. 5704 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5705 Index = MSN->getIndex(); 5706 Mask = MSN->getMask(); 5707 Val = MSN->getValue(); 5708 IsTruncatingStore = MSN->isTruncatingStore(); 5709 } 5710 5711 MVT VT = Val.getSimpleValueType(); 5712 MVT IndexVT = Index.getSimpleValueType(); 5713 MVT XLenVT = Subtarget.getXLenVT(); 5714 5715 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5716 "Unexpected VTs!"); 5717 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5718 // Targets have to explicitly opt-in for extending vector loads and 5719 // truncating vector stores. 5720 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5721 (void)IsTruncatingStore; 5722 5723 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5724 // the selection of the masked intrinsics doesn't do this for us. 5725 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5726 5727 MVT ContainerVT = VT; 5728 if (VT.isFixedLengthVector()) { 5729 // We need to use the larger of the value and index type to determine the 5730 // scalable type to use so we don't increase LMUL for any operand/result. 5731 if (VT.bitsGE(IndexVT)) { 5732 ContainerVT = getContainerForFixedLengthVector(VT); 5733 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5734 ContainerVT.getVectorElementCount()); 5735 } else { 5736 IndexVT = getContainerForFixedLengthVector(IndexVT); 5737 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 5738 IndexVT.getVectorElementCount()); 5739 } 5740 5741 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5742 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5743 5744 if (!IsUnmasked) { 5745 MVT MaskVT = 5746 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5747 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5748 } 5749 } 5750 5751 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 5752 IndexVT = IndexVT.changeVectorElementType(XLenVT); 5753 Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index); 5754 } 5755 5756 if (!VL) 5757 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5758 5759 unsigned IntID = 5760 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 5761 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5762 Ops.push_back(Val); 5763 Ops.push_back(BasePtr); 5764 Ops.push_back(Index); 5765 if (!IsUnmasked) 5766 Ops.push_back(Mask); 5767 Ops.push_back(VL); 5768 5769 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5770 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5771 } 5772 5773 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 5774 SelectionDAG &DAG) const { 5775 const MVT XLenVT = Subtarget.getXLenVT(); 5776 SDLoc DL(Op); 5777 SDValue Chain = Op->getOperand(0); 5778 SDValue SysRegNo = DAG.getTargetConstant( 5779 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5780 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 5781 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 5782 5783 // Encoding used for rounding mode in RISCV differs from that used in 5784 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 5785 // table, which consists of a sequence of 4-bit fields, each representing 5786 // corresponding FLT_ROUNDS mode. 5787 static const int Table = 5788 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 5789 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 5790 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 5791 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 5792 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 5793 5794 SDValue Shift = 5795 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 5796 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5797 DAG.getConstant(Table, DL, XLenVT), Shift); 5798 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5799 DAG.getConstant(7, DL, XLenVT)); 5800 5801 return DAG.getMergeValues({Masked, Chain}, DL); 5802 } 5803 5804 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 5805 SelectionDAG &DAG) const { 5806 const MVT XLenVT = Subtarget.getXLenVT(); 5807 SDLoc DL(Op); 5808 SDValue Chain = Op->getOperand(0); 5809 SDValue RMValue = Op->getOperand(1); 5810 SDValue SysRegNo = DAG.getTargetConstant( 5811 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5812 5813 // Encoding used for rounding mode in RISCV differs from that used in 5814 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 5815 // a table, which consists of a sequence of 4-bit fields, each representing 5816 // corresponding RISCV mode. 5817 static const unsigned Table = 5818 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 5819 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 5820 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 5821 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 5822 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 5823 5824 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 5825 DAG.getConstant(2, DL, XLenVT)); 5826 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5827 DAG.getConstant(Table, DL, XLenVT), Shift); 5828 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5829 DAG.getConstant(0x7, DL, XLenVT)); 5830 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 5831 RMValue); 5832 } 5833 5834 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 5835 switch (IntNo) { 5836 default: 5837 llvm_unreachable("Unexpected Intrinsic"); 5838 case Intrinsic::riscv_grev: 5839 return RISCVISD::GREVW; 5840 case Intrinsic::riscv_gorc: 5841 return RISCVISD::GORCW; 5842 case Intrinsic::riscv_bcompress: 5843 return RISCVISD::BCOMPRESSW; 5844 case Intrinsic::riscv_bdecompress: 5845 return RISCVISD::BDECOMPRESSW; 5846 case Intrinsic::riscv_bfp: 5847 return RISCVISD::BFPW; 5848 } 5849 } 5850 5851 // Converts the given intrinsic to a i64 operation with any extension. 5852 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 5853 unsigned IntNo) { 5854 SDLoc DL(N); 5855 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 5856 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5857 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5858 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 5859 // ReplaceNodeResults requires we maintain the same type for the return value. 5860 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 5861 } 5862 5863 // Returns the opcode of the target-specific SDNode that implements the 32-bit 5864 // form of the given Opcode. 5865 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 5866 switch (Opcode) { 5867 default: 5868 llvm_unreachable("Unexpected opcode"); 5869 case ISD::SHL: 5870 return RISCVISD::SLLW; 5871 case ISD::SRA: 5872 return RISCVISD::SRAW; 5873 case ISD::SRL: 5874 return RISCVISD::SRLW; 5875 case ISD::SDIV: 5876 return RISCVISD::DIVW; 5877 case ISD::UDIV: 5878 return RISCVISD::DIVUW; 5879 case ISD::UREM: 5880 return RISCVISD::REMUW; 5881 case ISD::ROTL: 5882 return RISCVISD::ROLW; 5883 case ISD::ROTR: 5884 return RISCVISD::RORW; 5885 case RISCVISD::GREV: 5886 return RISCVISD::GREVW; 5887 case RISCVISD::GORC: 5888 return RISCVISD::GORCW; 5889 } 5890 } 5891 5892 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 5893 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 5894 // otherwise be promoted to i64, making it difficult to select the 5895 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 5896 // type i8/i16/i32 is lost. 5897 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 5898 unsigned ExtOpc = ISD::ANY_EXTEND) { 5899 SDLoc DL(N); 5900 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5901 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 5902 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 5903 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5904 // ReplaceNodeResults requires we maintain the same type for the return value. 5905 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 5906 } 5907 5908 // Converts the given 32-bit operation to a i64 operation with signed extension 5909 // semantic to reduce the signed extension instructions. 5910 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 5911 SDLoc DL(N); 5912 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5913 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5914 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 5915 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5916 DAG.getValueType(MVT::i32)); 5917 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 5918 } 5919 5920 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 5921 SmallVectorImpl<SDValue> &Results, 5922 SelectionDAG &DAG) const { 5923 SDLoc DL(N); 5924 switch (N->getOpcode()) { 5925 default: 5926 llvm_unreachable("Don't know how to custom type legalize this operation!"); 5927 case ISD::STRICT_FP_TO_SINT: 5928 case ISD::STRICT_FP_TO_UINT: 5929 case ISD::FP_TO_SINT: 5930 case ISD::FP_TO_UINT: { 5931 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5932 "Unexpected custom legalisation"); 5933 bool IsStrict = N->isStrictFPOpcode(); 5934 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 5935 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 5936 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 5937 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 5938 TargetLowering::TypeSoftenFloat) { 5939 if (!isTypeLegal(Op0.getValueType())) 5940 return; 5941 if (IsStrict) { 5942 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 5943 : RISCVISD::STRICT_FCVT_WU_RV64; 5944 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 5945 SDValue Res = DAG.getNode( 5946 Opc, DL, VTs, N->getOperand(0), Op0, 5947 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 5948 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5949 Results.push_back(Res.getValue(1)); 5950 return; 5951 } 5952 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 5953 SDValue Res = 5954 DAG.getNode(Opc, DL, MVT::i64, Op0, 5955 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 5956 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5957 return; 5958 } 5959 // If the FP type needs to be softened, emit a library call using the 'si' 5960 // version. If we left it to default legalization we'd end up with 'di'. If 5961 // the FP type doesn't need to be softened just let generic type 5962 // legalization promote the result type. 5963 RTLIB::Libcall LC; 5964 if (IsSigned) 5965 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 5966 else 5967 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 5968 MakeLibCallOptions CallOptions; 5969 EVT OpVT = Op0.getValueType(); 5970 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 5971 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 5972 SDValue Result; 5973 std::tie(Result, Chain) = 5974 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 5975 Results.push_back(Result); 5976 if (IsStrict) 5977 Results.push_back(Chain); 5978 break; 5979 } 5980 case ISD::READCYCLECOUNTER: { 5981 assert(!Subtarget.is64Bit() && 5982 "READCYCLECOUNTER only has custom type legalization on riscv32"); 5983 5984 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 5985 SDValue RCW = 5986 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 5987 5988 Results.push_back( 5989 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 5990 Results.push_back(RCW.getValue(2)); 5991 break; 5992 } 5993 case ISD::MUL: { 5994 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 5995 unsigned XLen = Subtarget.getXLen(); 5996 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 5997 if (Size > XLen) { 5998 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 5999 SDValue LHS = N->getOperand(0); 6000 SDValue RHS = N->getOperand(1); 6001 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6002 6003 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6004 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6005 // We need exactly one side to be unsigned. 6006 if (LHSIsU == RHSIsU) 6007 return; 6008 6009 auto MakeMULPair = [&](SDValue S, SDValue U) { 6010 MVT XLenVT = Subtarget.getXLenVT(); 6011 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6012 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6013 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6014 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6015 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6016 }; 6017 6018 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6019 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6020 6021 // The other operand should be signed, but still prefer MULH when 6022 // possible. 6023 if (RHSIsU && LHSIsS && !RHSIsS) 6024 Results.push_back(MakeMULPair(LHS, RHS)); 6025 else if (LHSIsU && RHSIsS && !LHSIsS) 6026 Results.push_back(MakeMULPair(RHS, LHS)); 6027 6028 return; 6029 } 6030 LLVM_FALLTHROUGH; 6031 } 6032 case ISD::ADD: 6033 case ISD::SUB: 6034 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6035 "Unexpected custom legalisation"); 6036 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6037 break; 6038 case ISD::SHL: 6039 case ISD::SRA: 6040 case ISD::SRL: 6041 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6042 "Unexpected custom legalisation"); 6043 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6044 Results.push_back(customLegalizeToWOp(N, DAG)); 6045 break; 6046 } 6047 6048 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6049 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6050 // shift amount. 6051 if (N->getOpcode() == ISD::SHL) { 6052 SDLoc DL(N); 6053 SDValue NewOp0 = 6054 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6055 SDValue NewOp1 = 6056 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6057 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6058 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6059 DAG.getValueType(MVT::i32)); 6060 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6061 } 6062 6063 break; 6064 case ISD::ROTL: 6065 case ISD::ROTR: 6066 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6067 "Unexpected custom legalisation"); 6068 Results.push_back(customLegalizeToWOp(N, DAG)); 6069 break; 6070 case ISD::CTTZ: 6071 case ISD::CTTZ_ZERO_UNDEF: 6072 case ISD::CTLZ: 6073 case ISD::CTLZ_ZERO_UNDEF: { 6074 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6075 "Unexpected custom legalisation"); 6076 6077 SDValue NewOp0 = 6078 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6079 bool IsCTZ = 6080 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6081 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6082 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6083 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6084 return; 6085 } 6086 case ISD::SDIV: 6087 case ISD::UDIV: 6088 case ISD::UREM: { 6089 MVT VT = N->getSimpleValueType(0); 6090 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6091 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6092 "Unexpected custom legalisation"); 6093 // Don't promote division/remainder by constant since we should expand those 6094 // to multiply by magic constant. 6095 // FIXME: What if the expansion is disabled for minsize. 6096 if (N->getOperand(1).getOpcode() == ISD::Constant) 6097 return; 6098 6099 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6100 // the upper 32 bits. For other types we need to sign or zero extend 6101 // based on the opcode. 6102 unsigned ExtOpc = ISD::ANY_EXTEND; 6103 if (VT != MVT::i32) 6104 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6105 : ISD::ZERO_EXTEND; 6106 6107 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6108 break; 6109 } 6110 case ISD::UADDO: 6111 case ISD::USUBO: { 6112 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6113 "Unexpected custom legalisation"); 6114 bool IsAdd = N->getOpcode() == ISD::UADDO; 6115 // Create an ADDW or SUBW. 6116 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6117 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6118 SDValue Res = 6119 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6120 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6121 DAG.getValueType(MVT::i32)); 6122 6123 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6124 // Since the inputs are sign extended from i32, this is equivalent to 6125 // comparing the lower 32 bits. 6126 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6127 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6128 IsAdd ? ISD::SETULT : ISD::SETUGT); 6129 6130 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6131 Results.push_back(Overflow); 6132 return; 6133 } 6134 case ISD::UADDSAT: 6135 case ISD::USUBSAT: { 6136 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6137 "Unexpected custom legalisation"); 6138 if (Subtarget.hasStdExtZbb()) { 6139 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6140 // sign extend allows overflow of the lower 32 bits to be detected on 6141 // the promoted size. 6142 SDValue LHS = 6143 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6144 SDValue RHS = 6145 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6146 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6147 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6148 return; 6149 } 6150 6151 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6152 // promotion for UADDO/USUBO. 6153 Results.push_back(expandAddSubSat(N, DAG)); 6154 return; 6155 } 6156 case ISD::BITCAST: { 6157 EVT VT = N->getValueType(0); 6158 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6159 SDValue Op0 = N->getOperand(0); 6160 EVT Op0VT = Op0.getValueType(); 6161 MVT XLenVT = Subtarget.getXLenVT(); 6162 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6163 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6164 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6165 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6166 Subtarget.hasStdExtF()) { 6167 SDValue FPConv = 6168 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6169 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6170 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6171 isTypeLegal(Op0VT)) { 6172 // Custom-legalize bitcasts from fixed-length vector types to illegal 6173 // scalar types in order to improve codegen. Bitcast the vector to a 6174 // one-element vector type whose element type is the same as the result 6175 // type, and extract the first element. 6176 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6177 if (isTypeLegal(BVT)) { 6178 SDValue BVec = DAG.getBitcast(BVT, Op0); 6179 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6180 DAG.getConstant(0, DL, XLenVT))); 6181 } 6182 } 6183 break; 6184 } 6185 case RISCVISD::GREV: 6186 case RISCVISD::GORC: { 6187 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6188 "Unexpected custom legalisation"); 6189 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6190 // This is similar to customLegalizeToWOp, except that we pass the second 6191 // operand (a TargetConstant) straight through: it is already of type 6192 // XLenVT. 6193 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6194 SDValue NewOp0 = 6195 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6196 SDValue NewOp1 = 6197 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6198 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6199 // ReplaceNodeResults requires we maintain the same type for the return 6200 // value. 6201 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6202 break; 6203 } 6204 case RISCVISD::SHFL: { 6205 // There is no SHFLIW instruction, but we can just promote the operation. 6206 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6207 "Unexpected custom legalisation"); 6208 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6209 SDValue NewOp0 = 6210 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6211 SDValue NewOp1 = 6212 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6213 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6214 // ReplaceNodeResults requires we maintain the same type for the return 6215 // value. 6216 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6217 break; 6218 } 6219 case ISD::BSWAP: 6220 case ISD::BITREVERSE: { 6221 MVT VT = N->getSimpleValueType(0); 6222 MVT XLenVT = Subtarget.getXLenVT(); 6223 assert((VT == MVT::i8 || VT == MVT::i16 || 6224 (VT == MVT::i32 && Subtarget.is64Bit())) && 6225 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6226 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6227 unsigned Imm = VT.getSizeInBits() - 1; 6228 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6229 if (N->getOpcode() == ISD::BSWAP) 6230 Imm &= ~0x7U; 6231 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6232 SDValue GREVI = 6233 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6234 // ReplaceNodeResults requires we maintain the same type for the return 6235 // value. 6236 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6237 break; 6238 } 6239 case ISD::FSHL: 6240 case ISD::FSHR: { 6241 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6242 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6243 SDValue NewOp0 = 6244 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6245 SDValue NewOp1 = 6246 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6247 SDValue NewShAmt = 6248 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6249 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6250 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6251 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6252 DAG.getConstant(0x1f, DL, MVT::i64)); 6253 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6254 // instruction use different orders. fshl will return its first operand for 6255 // shift of zero, fshr will return its second operand. fsl and fsr both 6256 // return rs1 so the ISD nodes need to have different operand orders. 6257 // Shift amount is in rs2. 6258 unsigned Opc = RISCVISD::FSLW; 6259 if (N->getOpcode() == ISD::FSHR) { 6260 std::swap(NewOp0, NewOp1); 6261 Opc = RISCVISD::FSRW; 6262 } 6263 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6264 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6265 break; 6266 } 6267 case ISD::EXTRACT_VECTOR_ELT: { 6268 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6269 // type is illegal (currently only vXi64 RV32). 6270 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6271 // transferred to the destination register. We issue two of these from the 6272 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6273 // first element. 6274 SDValue Vec = N->getOperand(0); 6275 SDValue Idx = N->getOperand(1); 6276 6277 // The vector type hasn't been legalized yet so we can't issue target 6278 // specific nodes if it needs legalization. 6279 // FIXME: We would manually legalize if it's important. 6280 if (!isTypeLegal(Vec.getValueType())) 6281 return; 6282 6283 MVT VecVT = Vec.getSimpleValueType(); 6284 6285 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6286 VecVT.getVectorElementType() == MVT::i64 && 6287 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6288 6289 // If this is a fixed vector, we need to convert it to a scalable vector. 6290 MVT ContainerVT = VecVT; 6291 if (VecVT.isFixedLengthVector()) { 6292 ContainerVT = getContainerForFixedLengthVector(VecVT); 6293 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6294 } 6295 6296 MVT XLenVT = Subtarget.getXLenVT(); 6297 6298 // Use a VL of 1 to avoid processing more elements than we need. 6299 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6300 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6301 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6302 6303 // Unless the index is known to be 0, we must slide the vector down to get 6304 // the desired element into index 0. 6305 if (!isNullConstant(Idx)) { 6306 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6307 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6308 } 6309 6310 // Extract the lower XLEN bits of the correct vector element. 6311 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6312 6313 // To extract the upper XLEN bits of the vector element, shift the first 6314 // element right by 32 bits and re-extract the lower XLEN bits. 6315 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6316 DAG.getConstant(32, DL, XLenVT), VL); 6317 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6318 ThirtyTwoV, Mask, VL); 6319 6320 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6321 6322 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6323 break; 6324 } 6325 case ISD::INTRINSIC_WO_CHAIN: { 6326 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6327 switch (IntNo) { 6328 default: 6329 llvm_unreachable( 6330 "Don't know how to custom type legalize this intrinsic!"); 6331 case Intrinsic::riscv_grev: 6332 case Intrinsic::riscv_gorc: 6333 case Intrinsic::riscv_bcompress: 6334 case Intrinsic::riscv_bdecompress: 6335 case Intrinsic::riscv_bfp: { 6336 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6337 "Unexpected custom legalisation"); 6338 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6339 break; 6340 } 6341 case Intrinsic::riscv_orc_b: { 6342 // Lower to the GORCI encoding for orc.b with the operand extended. 6343 SDValue NewOp = 6344 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6345 // If Zbp is enabled, use GORCIW which will sign extend the result. 6346 unsigned Opc = 6347 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6348 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6349 DAG.getConstant(7, DL, MVT::i64)); 6350 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6351 return; 6352 } 6353 case Intrinsic::riscv_shfl: 6354 case Intrinsic::riscv_unshfl: { 6355 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6356 "Unexpected custom legalisation"); 6357 SDValue NewOp1 = 6358 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6359 SDValue NewOp2 = 6360 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6361 unsigned Opc = 6362 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6363 if (isa<ConstantSDNode>(N->getOperand(2))) { 6364 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6365 DAG.getConstant(0xf, DL, MVT::i64)); 6366 Opc = 6367 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6368 } 6369 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6370 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6371 break; 6372 } 6373 case Intrinsic::riscv_vmv_x_s: { 6374 EVT VT = N->getValueType(0); 6375 MVT XLenVT = Subtarget.getXLenVT(); 6376 if (VT.bitsLT(XLenVT)) { 6377 // Simple case just extract using vmv.x.s and truncate. 6378 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6379 Subtarget.getXLenVT(), N->getOperand(1)); 6380 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6381 return; 6382 } 6383 6384 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6385 "Unexpected custom legalization"); 6386 6387 // We need to do the move in two steps. 6388 SDValue Vec = N->getOperand(1); 6389 MVT VecVT = Vec.getSimpleValueType(); 6390 6391 // First extract the lower XLEN bits of the element. 6392 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6393 6394 // To extract the upper XLEN bits of the vector element, shift the first 6395 // element right by 32 bits and re-extract the lower XLEN bits. 6396 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6397 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6398 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6399 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 6400 DAG.getConstant(32, DL, XLenVT), VL); 6401 SDValue LShr32 = 6402 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6403 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6404 6405 Results.push_back( 6406 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6407 break; 6408 } 6409 } 6410 break; 6411 } 6412 case ISD::VECREDUCE_ADD: 6413 case ISD::VECREDUCE_AND: 6414 case ISD::VECREDUCE_OR: 6415 case ISD::VECREDUCE_XOR: 6416 case ISD::VECREDUCE_SMAX: 6417 case ISD::VECREDUCE_UMAX: 6418 case ISD::VECREDUCE_SMIN: 6419 case ISD::VECREDUCE_UMIN: 6420 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6421 Results.push_back(V); 6422 break; 6423 case ISD::VP_REDUCE_ADD: 6424 case ISD::VP_REDUCE_AND: 6425 case ISD::VP_REDUCE_OR: 6426 case ISD::VP_REDUCE_XOR: 6427 case ISD::VP_REDUCE_SMAX: 6428 case ISD::VP_REDUCE_UMAX: 6429 case ISD::VP_REDUCE_SMIN: 6430 case ISD::VP_REDUCE_UMIN: 6431 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6432 Results.push_back(V); 6433 break; 6434 case ISD::FLT_ROUNDS_: { 6435 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6436 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6437 Results.push_back(Res.getValue(0)); 6438 Results.push_back(Res.getValue(1)); 6439 break; 6440 } 6441 } 6442 } 6443 6444 // A structure to hold one of the bit-manipulation patterns below. Together, a 6445 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6446 // (or (and (shl x, 1), 0xAAAAAAAA), 6447 // (and (srl x, 1), 0x55555555)) 6448 struct RISCVBitmanipPat { 6449 SDValue Op; 6450 unsigned ShAmt; 6451 bool IsSHL; 6452 6453 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6454 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6455 } 6456 }; 6457 6458 // Matches patterns of the form 6459 // (and (shl x, C2), (C1 << C2)) 6460 // (and (srl x, C2), C1) 6461 // (shl (and x, C1), C2) 6462 // (srl (and x, (C1 << C2)), C2) 6463 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6464 // The expected masks for each shift amount are specified in BitmanipMasks where 6465 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6466 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6467 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6468 // XLen is 64. 6469 static Optional<RISCVBitmanipPat> 6470 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6471 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6472 "Unexpected number of masks"); 6473 Optional<uint64_t> Mask; 6474 // Optionally consume a mask around the shift operation. 6475 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6476 Mask = Op.getConstantOperandVal(1); 6477 Op = Op.getOperand(0); 6478 } 6479 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6480 return None; 6481 bool IsSHL = Op.getOpcode() == ISD::SHL; 6482 6483 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6484 return None; 6485 uint64_t ShAmt = Op.getConstantOperandVal(1); 6486 6487 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6488 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6489 return None; 6490 // If we don't have enough masks for 64 bit, then we must be trying to 6491 // match SHFL so we're only allowed to shift 1/4 of the width. 6492 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6493 return None; 6494 6495 SDValue Src = Op.getOperand(0); 6496 6497 // The expected mask is shifted left when the AND is found around SHL 6498 // patterns. 6499 // ((x >> 1) & 0x55555555) 6500 // ((x << 1) & 0xAAAAAAAA) 6501 bool SHLExpMask = IsSHL; 6502 6503 if (!Mask) { 6504 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6505 // the mask is all ones: consume that now. 6506 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6507 Mask = Src.getConstantOperandVal(1); 6508 Src = Src.getOperand(0); 6509 // The expected mask is now in fact shifted left for SRL, so reverse the 6510 // decision. 6511 // ((x & 0xAAAAAAAA) >> 1) 6512 // ((x & 0x55555555) << 1) 6513 SHLExpMask = !SHLExpMask; 6514 } else { 6515 // Use a default shifted mask of all-ones if there's no AND, truncated 6516 // down to the expected width. This simplifies the logic later on. 6517 Mask = maskTrailingOnes<uint64_t>(Width); 6518 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6519 } 6520 } 6521 6522 unsigned MaskIdx = Log2_32(ShAmt); 6523 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6524 6525 if (SHLExpMask) 6526 ExpMask <<= ShAmt; 6527 6528 if (Mask != ExpMask) 6529 return None; 6530 6531 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6532 } 6533 6534 // Matches any of the following bit-manipulation patterns: 6535 // (and (shl x, 1), (0x55555555 << 1)) 6536 // (and (srl x, 1), 0x55555555) 6537 // (shl (and x, 0x55555555), 1) 6538 // (srl (and x, (0x55555555 << 1)), 1) 6539 // where the shift amount and mask may vary thus: 6540 // [1] = 0x55555555 / 0xAAAAAAAA 6541 // [2] = 0x33333333 / 0xCCCCCCCC 6542 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6543 // [8] = 0x00FF00FF / 0xFF00FF00 6544 // [16] = 0x0000FFFF / 0xFFFFFFFF 6545 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6546 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6547 // These are the unshifted masks which we use to match bit-manipulation 6548 // patterns. They may be shifted left in certain circumstances. 6549 static const uint64_t BitmanipMasks[] = { 6550 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6551 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6552 6553 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6554 } 6555 6556 // Match the following pattern as a GREVI(W) operation 6557 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6558 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6559 const RISCVSubtarget &Subtarget) { 6560 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6561 EVT VT = Op.getValueType(); 6562 6563 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6564 auto LHS = matchGREVIPat(Op.getOperand(0)); 6565 auto RHS = matchGREVIPat(Op.getOperand(1)); 6566 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6567 SDLoc DL(Op); 6568 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6569 DAG.getConstant(LHS->ShAmt, DL, VT)); 6570 } 6571 } 6572 return SDValue(); 6573 } 6574 6575 // Matches any the following pattern as a GORCI(W) operation 6576 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6577 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6578 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6579 // Note that with the variant of 3., 6580 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6581 // the inner pattern will first be matched as GREVI and then the outer 6582 // pattern will be matched to GORC via the first rule above. 6583 // 4. (or (rotl/rotr x, bitwidth/2), x) 6584 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6585 const RISCVSubtarget &Subtarget) { 6586 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6587 EVT VT = Op.getValueType(); 6588 6589 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6590 SDLoc DL(Op); 6591 SDValue Op0 = Op.getOperand(0); 6592 SDValue Op1 = Op.getOperand(1); 6593 6594 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6595 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6596 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6597 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6598 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6599 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6600 if ((Reverse.getOpcode() == ISD::ROTL || 6601 Reverse.getOpcode() == ISD::ROTR) && 6602 Reverse.getOperand(0) == X && 6603 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6604 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6605 if (RotAmt == (VT.getSizeInBits() / 2)) 6606 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6607 DAG.getConstant(RotAmt, DL, VT)); 6608 } 6609 return SDValue(); 6610 }; 6611 6612 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6613 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6614 return V; 6615 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6616 return V; 6617 6618 // OR is commutable so canonicalize its OR operand to the left 6619 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6620 std::swap(Op0, Op1); 6621 if (Op0.getOpcode() != ISD::OR) 6622 return SDValue(); 6623 SDValue OrOp0 = Op0.getOperand(0); 6624 SDValue OrOp1 = Op0.getOperand(1); 6625 auto LHS = matchGREVIPat(OrOp0); 6626 // OR is commutable so swap the operands and try again: x might have been 6627 // on the left 6628 if (!LHS) { 6629 std::swap(OrOp0, OrOp1); 6630 LHS = matchGREVIPat(OrOp0); 6631 } 6632 auto RHS = matchGREVIPat(Op1); 6633 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6634 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6635 DAG.getConstant(LHS->ShAmt, DL, VT)); 6636 } 6637 } 6638 return SDValue(); 6639 } 6640 6641 // Matches any of the following bit-manipulation patterns: 6642 // (and (shl x, 1), (0x22222222 << 1)) 6643 // (and (srl x, 1), 0x22222222) 6644 // (shl (and x, 0x22222222), 1) 6645 // (srl (and x, (0x22222222 << 1)), 1) 6646 // where the shift amount and mask may vary thus: 6647 // [1] = 0x22222222 / 0x44444444 6648 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6649 // [4] = 0x00F000F0 / 0x0F000F00 6650 // [8] = 0x0000FF00 / 0x00FF0000 6651 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6652 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6653 // These are the unshifted masks which we use to match bit-manipulation 6654 // patterns. They may be shifted left in certain circumstances. 6655 static const uint64_t BitmanipMasks[] = { 6656 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6657 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6658 6659 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6660 } 6661 6662 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6663 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6664 const RISCVSubtarget &Subtarget) { 6665 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6666 EVT VT = Op.getValueType(); 6667 6668 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6669 return SDValue(); 6670 6671 SDValue Op0 = Op.getOperand(0); 6672 SDValue Op1 = Op.getOperand(1); 6673 6674 // Or is commutable so canonicalize the second OR to the LHS. 6675 if (Op0.getOpcode() != ISD::OR) 6676 std::swap(Op0, Op1); 6677 if (Op0.getOpcode() != ISD::OR) 6678 return SDValue(); 6679 6680 // We found an inner OR, so our operands are the operands of the inner OR 6681 // and the other operand of the outer OR. 6682 SDValue A = Op0.getOperand(0); 6683 SDValue B = Op0.getOperand(1); 6684 SDValue C = Op1; 6685 6686 auto Match1 = matchSHFLPat(A); 6687 auto Match2 = matchSHFLPat(B); 6688 6689 // If neither matched, we failed. 6690 if (!Match1 && !Match2) 6691 return SDValue(); 6692 6693 // We had at least one match. if one failed, try the remaining C operand. 6694 if (!Match1) { 6695 std::swap(A, C); 6696 Match1 = matchSHFLPat(A); 6697 if (!Match1) 6698 return SDValue(); 6699 } else if (!Match2) { 6700 std::swap(B, C); 6701 Match2 = matchSHFLPat(B); 6702 if (!Match2) 6703 return SDValue(); 6704 } 6705 assert(Match1 && Match2); 6706 6707 // Make sure our matches pair up. 6708 if (!Match1->formsPairWith(*Match2)) 6709 return SDValue(); 6710 6711 // All the remains is to make sure C is an AND with the same input, that masks 6712 // out the bits that are being shuffled. 6713 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 6714 C.getOperand(0) != Match1->Op) 6715 return SDValue(); 6716 6717 uint64_t Mask = C.getConstantOperandVal(1); 6718 6719 static const uint64_t BitmanipMasks[] = { 6720 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 6721 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 6722 }; 6723 6724 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6725 unsigned MaskIdx = Log2_32(Match1->ShAmt); 6726 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6727 6728 if (Mask != ExpMask) 6729 return SDValue(); 6730 6731 SDLoc DL(Op); 6732 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 6733 DAG.getConstant(Match1->ShAmt, DL, VT)); 6734 } 6735 6736 // Optimize (add (shl x, c0), (shl y, c1)) -> 6737 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 6738 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 6739 const RISCVSubtarget &Subtarget) { 6740 // Perform this optimization only in the zba extension. 6741 if (!Subtarget.hasStdExtZba()) 6742 return SDValue(); 6743 6744 // Skip for vector types and larger types. 6745 EVT VT = N->getValueType(0); 6746 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6747 return SDValue(); 6748 6749 // The two operand nodes must be SHL and have no other use. 6750 SDValue N0 = N->getOperand(0); 6751 SDValue N1 = N->getOperand(1); 6752 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 6753 !N0->hasOneUse() || !N1->hasOneUse()) 6754 return SDValue(); 6755 6756 // Check c0 and c1. 6757 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6758 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 6759 if (!N0C || !N1C) 6760 return SDValue(); 6761 int64_t C0 = N0C->getSExtValue(); 6762 int64_t C1 = N1C->getSExtValue(); 6763 if (C0 <= 0 || C1 <= 0) 6764 return SDValue(); 6765 6766 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 6767 int64_t Bits = std::min(C0, C1); 6768 int64_t Diff = std::abs(C0 - C1); 6769 if (Diff != 1 && Diff != 2 && Diff != 3) 6770 return SDValue(); 6771 6772 // Build nodes. 6773 SDLoc DL(N); 6774 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 6775 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 6776 SDValue NA0 = 6777 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 6778 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 6779 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 6780 } 6781 6782 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 6783 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 6784 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 6785 // not undo itself, but they are redundant. 6786 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 6787 SDValue Src = N->getOperand(0); 6788 6789 if (Src.getOpcode() != N->getOpcode()) 6790 return SDValue(); 6791 6792 if (!isa<ConstantSDNode>(N->getOperand(1)) || 6793 !isa<ConstantSDNode>(Src.getOperand(1))) 6794 return SDValue(); 6795 6796 unsigned ShAmt1 = N->getConstantOperandVal(1); 6797 unsigned ShAmt2 = Src.getConstantOperandVal(1); 6798 Src = Src.getOperand(0); 6799 6800 unsigned CombinedShAmt; 6801 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 6802 CombinedShAmt = ShAmt1 | ShAmt2; 6803 else 6804 CombinedShAmt = ShAmt1 ^ ShAmt2; 6805 6806 if (CombinedShAmt == 0) 6807 return Src; 6808 6809 SDLoc DL(N); 6810 return DAG.getNode( 6811 N->getOpcode(), DL, N->getValueType(0), Src, 6812 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 6813 } 6814 6815 // Combine a constant select operand into its use: 6816 // 6817 // (and (select cond, -1, c), x) 6818 // -> (select cond, x, (and x, c)) [AllOnes=1] 6819 // (or (select cond, 0, c), x) 6820 // -> (select cond, x, (or x, c)) [AllOnes=0] 6821 // (xor (select cond, 0, c), x) 6822 // -> (select cond, x, (xor x, c)) [AllOnes=0] 6823 // (add (select cond, 0, c), x) 6824 // -> (select cond, x, (add x, c)) [AllOnes=0] 6825 // (sub x, (select cond, 0, c)) 6826 // -> (select cond, x, (sub x, c)) [AllOnes=0] 6827 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 6828 SelectionDAG &DAG, bool AllOnes) { 6829 EVT VT = N->getValueType(0); 6830 6831 // Skip vectors. 6832 if (VT.isVector()) 6833 return SDValue(); 6834 6835 if ((Slct.getOpcode() != ISD::SELECT && 6836 Slct.getOpcode() != RISCVISD::SELECT_CC) || 6837 !Slct.hasOneUse()) 6838 return SDValue(); 6839 6840 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 6841 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 6842 }; 6843 6844 bool SwapSelectOps; 6845 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 6846 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 6847 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 6848 SDValue NonConstantVal; 6849 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 6850 SwapSelectOps = false; 6851 NonConstantVal = FalseVal; 6852 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 6853 SwapSelectOps = true; 6854 NonConstantVal = TrueVal; 6855 } else 6856 return SDValue(); 6857 6858 // Slct is now know to be the desired identity constant when CC is true. 6859 TrueVal = OtherOp; 6860 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 6861 // Unless SwapSelectOps says the condition should be false. 6862 if (SwapSelectOps) 6863 std::swap(TrueVal, FalseVal); 6864 6865 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 6866 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 6867 {Slct.getOperand(0), Slct.getOperand(1), 6868 Slct.getOperand(2), TrueVal, FalseVal}); 6869 6870 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 6871 {Slct.getOperand(0), TrueVal, FalseVal}); 6872 } 6873 6874 // Attempt combineSelectAndUse on each operand of a commutative operator N. 6875 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 6876 bool AllOnes) { 6877 SDValue N0 = N->getOperand(0); 6878 SDValue N1 = N->getOperand(1); 6879 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 6880 return Result; 6881 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 6882 return Result; 6883 return SDValue(); 6884 } 6885 6886 // Transform (add (mul x, c0), c1) -> 6887 // (add (mul (add x, c1/c0), c0), c1%c0). 6888 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 6889 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 6890 // to an infinite loop in DAGCombine if transformed. 6891 // Or transform (add (mul x, c0), c1) -> 6892 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 6893 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 6894 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 6895 // lead to an infinite loop in DAGCombine if transformed. 6896 // Or transform (add (mul x, c0), c1) -> 6897 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 6898 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 6899 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 6900 // lead to an infinite loop in DAGCombine if transformed. 6901 // Or transform (add (mul x, c0), c1) -> 6902 // (mul (add x, c1/c0), c0). 6903 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 6904 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 6905 const RISCVSubtarget &Subtarget) { 6906 // Skip for vector types and larger types. 6907 EVT VT = N->getValueType(0); 6908 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6909 return SDValue(); 6910 // The first operand node must be a MUL and has no other use. 6911 SDValue N0 = N->getOperand(0); 6912 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 6913 return SDValue(); 6914 // Check if c0 and c1 match above conditions. 6915 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6916 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6917 if (!N0C || !N1C) 6918 return SDValue(); 6919 int64_t C0 = N0C->getSExtValue(); 6920 int64_t C1 = N1C->getSExtValue(); 6921 int64_t CA, CB; 6922 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 6923 return SDValue(); 6924 // Search for proper CA (non-zero) and CB that both are simm12. 6925 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 6926 !isInt<12>(C0 * (C1 / C0))) { 6927 CA = C1 / C0; 6928 CB = C1 % C0; 6929 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 6930 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 6931 CA = C1 / C0 + 1; 6932 CB = C1 % C0 - C0; 6933 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 6934 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 6935 CA = C1 / C0 - 1; 6936 CB = C1 % C0 + C0; 6937 } else 6938 return SDValue(); 6939 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 6940 SDLoc DL(N); 6941 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 6942 DAG.getConstant(CA, DL, VT)); 6943 SDValue New1 = 6944 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 6945 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 6946 } 6947 6948 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 6949 const RISCVSubtarget &Subtarget) { 6950 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 6951 return V; 6952 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 6953 return V; 6954 // fold (add (select lhs, rhs, cc, 0, y), x) -> 6955 // (select lhs, rhs, cc, x, (add x, y)) 6956 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6957 } 6958 6959 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 6960 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 6961 // (select lhs, rhs, cc, x, (sub x, y)) 6962 SDValue N0 = N->getOperand(0); 6963 SDValue N1 = N->getOperand(1); 6964 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 6965 } 6966 6967 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 6968 // fold (and (select lhs, rhs, cc, -1, y), x) -> 6969 // (select lhs, rhs, cc, x, (and x, y)) 6970 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 6971 } 6972 6973 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 6974 const RISCVSubtarget &Subtarget) { 6975 if (Subtarget.hasStdExtZbp()) { 6976 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 6977 return GREV; 6978 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 6979 return GORC; 6980 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 6981 return SHFL; 6982 } 6983 6984 // fold (or (select cond, 0, y), x) -> 6985 // (select cond, x, (or x, y)) 6986 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6987 } 6988 6989 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 6990 // fold (xor (select cond, 0, y), x) -> 6991 // (select cond, x, (xor x, y)) 6992 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6993 } 6994 6995 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 6996 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 6997 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 6998 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 6999 // ADDW/SUBW/MULW. 7000 static SDValue performANY_EXTENDCombine(SDNode *N, 7001 TargetLowering::DAGCombinerInfo &DCI, 7002 const RISCVSubtarget &Subtarget) { 7003 if (!Subtarget.is64Bit()) 7004 return SDValue(); 7005 7006 SelectionDAG &DAG = DCI.DAG; 7007 7008 SDValue Src = N->getOperand(0); 7009 EVT VT = N->getValueType(0); 7010 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 7011 return SDValue(); 7012 7013 // The opcode must be one that can implicitly sign_extend. 7014 // FIXME: Additional opcodes. 7015 switch (Src.getOpcode()) { 7016 default: 7017 return SDValue(); 7018 case ISD::MUL: 7019 if (!Subtarget.hasStdExtM()) 7020 return SDValue(); 7021 LLVM_FALLTHROUGH; 7022 case ISD::ADD: 7023 case ISD::SUB: 7024 break; 7025 } 7026 7027 // Only handle cases where the result is used by a CopyToReg. That likely 7028 // means the value is a liveout of the basic block. This helps prevent 7029 // infinite combine loops like PR51206. 7030 if (none_of(N->uses(), 7031 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 7032 return SDValue(); 7033 7034 SmallVector<SDNode *, 4> SetCCs; 7035 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 7036 UE = Src.getNode()->use_end(); 7037 UI != UE; ++UI) { 7038 SDNode *User = *UI; 7039 if (User == N) 7040 continue; 7041 if (UI.getUse().getResNo() != Src.getResNo()) 7042 continue; 7043 // All i32 setccs are legalized by sign extending operands. 7044 if (User->getOpcode() == ISD::SETCC) { 7045 SetCCs.push_back(User); 7046 continue; 7047 } 7048 // We don't know if we can extend this user. 7049 break; 7050 } 7051 7052 // If we don't have any SetCCs, this isn't worthwhile. 7053 if (SetCCs.empty()) 7054 return SDValue(); 7055 7056 SDLoc DL(N); 7057 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 7058 DCI.CombineTo(N, SExt); 7059 7060 // Promote all the setccs. 7061 for (SDNode *SetCC : SetCCs) { 7062 SmallVector<SDValue, 4> Ops; 7063 7064 for (unsigned j = 0; j != 2; ++j) { 7065 SDValue SOp = SetCC->getOperand(j); 7066 if (SOp == Src) 7067 Ops.push_back(SExt); 7068 else 7069 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 7070 } 7071 7072 Ops.push_back(SetCC->getOperand(2)); 7073 DCI.CombineTo(SetCC, 7074 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7075 } 7076 return SDValue(N, 0); 7077 } 7078 7079 // Try to form VWMUL or VWMULU. 7080 // FIXME: Support VWMULSU. 7081 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1, 7082 SelectionDAG &DAG) { 7083 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7084 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7085 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7086 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7087 return SDValue(); 7088 7089 SDValue Mask = N->getOperand(2); 7090 SDValue VL = N->getOperand(3); 7091 7092 // Make sure the mask and VL match. 7093 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7094 return SDValue(); 7095 7096 MVT VT = N->getSimpleValueType(0); 7097 7098 // Determine the narrow size for a widening multiply. 7099 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7100 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7101 VT.getVectorElementCount()); 7102 7103 SDLoc DL(N); 7104 7105 // See if the other operand is the same opcode. 7106 if (Op0.getOpcode() == Op1.getOpcode()) { 7107 if (!Op1.hasOneUse()) 7108 return SDValue(); 7109 7110 // Make sure the mask and VL match. 7111 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7112 return SDValue(); 7113 7114 Op1 = Op1.getOperand(0); 7115 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7116 // The operand is a splat of a scalar. 7117 7118 // The VL must be the same. 7119 if (Op1.getOperand(1) != VL) 7120 return SDValue(); 7121 7122 // Get the scalar value. 7123 Op1 = Op1.getOperand(0); 7124 7125 // See if have enough sign bits or zero bits in the scalar to use a 7126 // widening multiply by splatting to smaller element size. 7127 unsigned EltBits = VT.getScalarSizeInBits(); 7128 unsigned ScalarBits = Op1.getValueSizeInBits(); 7129 // Make sure we're getting all element bits from the scalar register. 7130 // FIXME: Support implicit sign extension of vmv.v.x? 7131 if (ScalarBits < EltBits) 7132 return SDValue(); 7133 7134 if (IsSignExt) { 7135 if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize)) 7136 return SDValue(); 7137 } else { 7138 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7139 if (!DAG.MaskedValueIsZero(Op1, Mask)) 7140 return SDValue(); 7141 } 7142 7143 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 7144 } else 7145 return SDValue(); 7146 7147 Op0 = Op0.getOperand(0); 7148 7149 // Re-introduce narrower extends if needed. 7150 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7151 if (Op0.getValueType() != NarrowVT) 7152 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7153 if (Op1.getValueType() != NarrowVT) 7154 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7155 7156 unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7157 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7158 } 7159 7160 // Fold 7161 // (fp_to_int (froundeven X)) -> fcvt X, rne 7162 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7163 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7164 // (fp_to_int (fceil X)) -> fcvt X, rup 7165 // (fp_to_int (fround X)) -> fcvt X, rmm 7166 // FIXME: We should also do this for fp_to_int_sat. 7167 static SDValue performFP_TO_INTCombine(SDNode *N, 7168 TargetLowering::DAGCombinerInfo &DCI, 7169 const RISCVSubtarget &Subtarget) { 7170 SelectionDAG &DAG = DCI.DAG; 7171 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7172 MVT XLenVT = Subtarget.getXLenVT(); 7173 7174 // Only handle XLen or i32 types. Other types narrower than XLen will 7175 // eventually be legalized to XLenVT. 7176 EVT VT = N->getValueType(0); 7177 if (VT != MVT::i32 && VT != XLenVT) 7178 return SDValue(); 7179 7180 SDValue Src = N->getOperand(0); 7181 7182 // Ensure the FP type is also legal. 7183 if (!TLI.isTypeLegal(Src.getValueType())) 7184 return SDValue(); 7185 7186 // Don't do this for f16 with Zfhmin and not Zfh. 7187 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7188 return SDValue(); 7189 7190 RISCVFPRndMode::RoundingMode FRM; 7191 switch (Src->getOpcode()) { 7192 default: 7193 return SDValue(); 7194 case ISD::FROUNDEVEN: FRM = RISCVFPRndMode::RNE; break; 7195 case ISD::FTRUNC: FRM = RISCVFPRndMode::RTZ; break; 7196 case ISD::FFLOOR: FRM = RISCVFPRndMode::RDN; break; 7197 case ISD::FCEIL: FRM = RISCVFPRndMode::RUP; break; 7198 case ISD::FROUND: FRM = RISCVFPRndMode::RMM; break; 7199 } 7200 7201 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7202 7203 unsigned Opc; 7204 if (VT == XLenVT) 7205 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7206 else 7207 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7208 7209 SDLoc DL(N); 7210 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 7211 DAG.getTargetConstant(FRM, DL, XLenVT)); 7212 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 7213 } 7214 7215 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 7216 DAGCombinerInfo &DCI) const { 7217 SelectionDAG &DAG = DCI.DAG; 7218 7219 // Helper to call SimplifyDemandedBits on an operand of N where only some low 7220 // bits are demanded. N will be added to the Worklist if it was not deleted. 7221 // Caller should return SDValue(N, 0) if this returns true. 7222 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 7223 SDValue Op = N->getOperand(OpNo); 7224 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 7225 if (!SimplifyDemandedBits(Op, Mask, DCI)) 7226 return false; 7227 7228 if (N->getOpcode() != ISD::DELETED_NODE) 7229 DCI.AddToWorklist(N); 7230 return true; 7231 }; 7232 7233 switch (N->getOpcode()) { 7234 default: 7235 break; 7236 case RISCVISD::SplitF64: { 7237 SDValue Op0 = N->getOperand(0); 7238 // If the input to SplitF64 is just BuildPairF64 then the operation is 7239 // redundant. Instead, use BuildPairF64's operands directly. 7240 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 7241 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 7242 7243 SDLoc DL(N); 7244 7245 // It's cheaper to materialise two 32-bit integers than to load a double 7246 // from the constant pool and transfer it to integer registers through the 7247 // stack. 7248 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 7249 APInt V = C->getValueAPF().bitcastToAPInt(); 7250 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 7251 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 7252 return DCI.CombineTo(N, Lo, Hi); 7253 } 7254 7255 // This is a target-specific version of a DAGCombine performed in 7256 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7257 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7258 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7259 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7260 !Op0.getNode()->hasOneUse()) 7261 break; 7262 SDValue NewSplitF64 = 7263 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 7264 Op0.getOperand(0)); 7265 SDValue Lo = NewSplitF64.getValue(0); 7266 SDValue Hi = NewSplitF64.getValue(1); 7267 APInt SignBit = APInt::getSignMask(32); 7268 if (Op0.getOpcode() == ISD::FNEG) { 7269 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 7270 DAG.getConstant(SignBit, DL, MVT::i32)); 7271 return DCI.CombineTo(N, Lo, NewHi); 7272 } 7273 assert(Op0.getOpcode() == ISD::FABS); 7274 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 7275 DAG.getConstant(~SignBit, DL, MVT::i32)); 7276 return DCI.CombineTo(N, Lo, NewHi); 7277 } 7278 case RISCVISD::SLLW: 7279 case RISCVISD::SRAW: 7280 case RISCVISD::SRLW: 7281 case RISCVISD::ROLW: 7282 case RISCVISD::RORW: { 7283 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7284 if (SimplifyDemandedLowBitsHelper(0, 32) || 7285 SimplifyDemandedLowBitsHelper(1, 5)) 7286 return SDValue(N, 0); 7287 break; 7288 } 7289 case RISCVISD::CLZW: 7290 case RISCVISD::CTZW: { 7291 // Only the lower 32 bits of the first operand are read 7292 if (SimplifyDemandedLowBitsHelper(0, 32)) 7293 return SDValue(N, 0); 7294 break; 7295 } 7296 case RISCVISD::GREV: 7297 case RISCVISD::GORC: { 7298 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 7299 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7300 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7301 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 7302 return SDValue(N, 0); 7303 7304 return combineGREVI_GORCI(N, DAG); 7305 } 7306 case RISCVISD::GREVW: 7307 case RISCVISD::GORCW: { 7308 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7309 if (SimplifyDemandedLowBitsHelper(0, 32) || 7310 SimplifyDemandedLowBitsHelper(1, 5)) 7311 return SDValue(N, 0); 7312 7313 return combineGREVI_GORCI(N, DAG); 7314 } 7315 case RISCVISD::SHFL: 7316 case RISCVISD::UNSHFL: { 7317 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 7318 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7319 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7320 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 7321 return SDValue(N, 0); 7322 7323 break; 7324 } 7325 case RISCVISD::SHFLW: 7326 case RISCVISD::UNSHFLW: { 7327 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 7328 SDValue LHS = N->getOperand(0); 7329 SDValue RHS = N->getOperand(1); 7330 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 7331 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4); 7332 if (SimplifyDemandedLowBitsHelper(0, 32) || 7333 SimplifyDemandedLowBitsHelper(1, 4)) 7334 return SDValue(N, 0); 7335 7336 break; 7337 } 7338 case RISCVISD::BCOMPRESSW: 7339 case RISCVISD::BDECOMPRESSW: { 7340 // Only the lower 32 bits of LHS and RHS are read. 7341 if (SimplifyDemandedLowBitsHelper(0, 32) || 7342 SimplifyDemandedLowBitsHelper(1, 32)) 7343 return SDValue(N, 0); 7344 7345 break; 7346 } 7347 case RISCVISD::FMV_X_ANYEXTH: 7348 case RISCVISD::FMV_X_ANYEXTW_RV64: { 7349 SDLoc DL(N); 7350 SDValue Op0 = N->getOperand(0); 7351 MVT VT = N->getSimpleValueType(0); 7352 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 7353 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 7354 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 7355 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 7356 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 7357 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7358 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 7359 assert(Op0.getOperand(0).getValueType() == VT && 7360 "Unexpected value type!"); 7361 return Op0.getOperand(0); 7362 } 7363 7364 // This is a target-specific version of a DAGCombine performed in 7365 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7366 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7367 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7368 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7369 !Op0.getNode()->hasOneUse()) 7370 break; 7371 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 7372 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 7373 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 7374 if (Op0.getOpcode() == ISD::FNEG) 7375 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 7376 DAG.getConstant(SignBit, DL, VT)); 7377 7378 assert(Op0.getOpcode() == ISD::FABS); 7379 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 7380 DAG.getConstant(~SignBit, DL, VT)); 7381 } 7382 case ISD::ADD: 7383 return performADDCombine(N, DAG, Subtarget); 7384 case ISD::SUB: 7385 return performSUBCombine(N, DAG); 7386 case ISD::AND: 7387 return performANDCombine(N, DAG); 7388 case ISD::OR: 7389 return performORCombine(N, DAG, Subtarget); 7390 case ISD::XOR: 7391 return performXORCombine(N, DAG); 7392 case ISD::ANY_EXTEND: 7393 return performANY_EXTENDCombine(N, DCI, Subtarget); 7394 case ISD::ZERO_EXTEND: 7395 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 7396 // type legalization. This is safe because fp_to_uint produces poison if 7397 // it overflows. 7398 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 7399 SDValue Src = N->getOperand(0); 7400 if (Src.getOpcode() == ISD::FP_TO_UINT && 7401 isTypeLegal(Src.getOperand(0).getValueType())) 7402 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 7403 Src.getOperand(0)); 7404 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 7405 isTypeLegal(Src.getOperand(1).getValueType())) { 7406 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 7407 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 7408 Src.getOperand(0), Src.getOperand(1)); 7409 DCI.CombineTo(N, Res); 7410 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 7411 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 7412 return SDValue(N, 0); // Return N so it doesn't get rechecked. 7413 } 7414 } 7415 return SDValue(); 7416 case RISCVISD::SELECT_CC: { 7417 // Transform 7418 SDValue LHS = N->getOperand(0); 7419 SDValue RHS = N->getOperand(1); 7420 SDValue TrueV = N->getOperand(3); 7421 SDValue FalseV = N->getOperand(4); 7422 7423 // If the True and False values are the same, we don't need a select_cc. 7424 if (TrueV == FalseV) 7425 return TrueV; 7426 7427 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 7428 if (!ISD::isIntEqualitySetCC(CCVal)) 7429 break; 7430 7431 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 7432 // (select_cc X, Y, lt, trueV, falseV) 7433 // Sometimes the setcc is introduced after select_cc has been formed. 7434 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7435 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7436 // If we're looking for eq 0 instead of ne 0, we need to invert the 7437 // condition. 7438 bool Invert = CCVal == ISD::SETEQ; 7439 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7440 if (Invert) 7441 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7442 7443 SDLoc DL(N); 7444 RHS = LHS.getOperand(1); 7445 LHS = LHS.getOperand(0); 7446 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7447 7448 SDValue TargetCC = DAG.getCondCode(CCVal); 7449 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7450 {LHS, RHS, TargetCC, TrueV, FalseV}); 7451 } 7452 7453 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 7454 // (select_cc X, Y, eq/ne, trueV, falseV) 7455 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7456 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 7457 {LHS.getOperand(0), LHS.getOperand(1), 7458 N->getOperand(2), TrueV, FalseV}); 7459 // (select_cc X, 1, setne, trueV, falseV) -> 7460 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 7461 // This can occur when legalizing some floating point comparisons. 7462 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7463 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7464 SDLoc DL(N); 7465 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7466 SDValue TargetCC = DAG.getCondCode(CCVal); 7467 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7468 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7469 {LHS, RHS, TargetCC, TrueV, FalseV}); 7470 } 7471 7472 break; 7473 } 7474 case RISCVISD::BR_CC: { 7475 SDValue LHS = N->getOperand(1); 7476 SDValue RHS = N->getOperand(2); 7477 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 7478 if (!ISD::isIntEqualitySetCC(CCVal)) 7479 break; 7480 7481 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 7482 // (br_cc X, Y, lt, dest) 7483 // Sometimes the setcc is introduced after br_cc has been formed. 7484 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7485 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7486 // If we're looking for eq 0 instead of ne 0, we need to invert the 7487 // condition. 7488 bool Invert = CCVal == ISD::SETEQ; 7489 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7490 if (Invert) 7491 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7492 7493 SDLoc DL(N); 7494 RHS = LHS.getOperand(1); 7495 LHS = LHS.getOperand(0); 7496 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7497 7498 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7499 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 7500 N->getOperand(4)); 7501 } 7502 7503 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 7504 // (br_cc X, Y, eq/ne, trueV, falseV) 7505 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7506 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 7507 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 7508 N->getOperand(3), N->getOperand(4)); 7509 7510 // (br_cc X, 1, setne, br_cc) -> 7511 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 7512 // This can occur when legalizing some floating point comparisons. 7513 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7514 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7515 SDLoc DL(N); 7516 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7517 SDValue TargetCC = DAG.getCondCode(CCVal); 7518 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7519 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7520 N->getOperand(0), LHS, RHS, TargetCC, 7521 N->getOperand(4)); 7522 } 7523 break; 7524 } 7525 case ISD::FP_TO_SINT: 7526 case ISD::FP_TO_UINT: 7527 return performFP_TO_INTCombine(N, DCI, Subtarget); 7528 case ISD::FCOPYSIGN: { 7529 EVT VT = N->getValueType(0); 7530 if (!VT.isVector()) 7531 break; 7532 // There is a form of VFSGNJ which injects the negated sign of its second 7533 // operand. Try and bubble any FNEG up after the extend/round to produce 7534 // this optimized pattern. Avoid modifying cases where FP_ROUND and 7535 // TRUNC=1. 7536 SDValue In2 = N->getOperand(1); 7537 // Avoid cases where the extend/round has multiple uses, as duplicating 7538 // those is typically more expensive than removing a fneg. 7539 if (!In2.hasOneUse()) 7540 break; 7541 if (In2.getOpcode() != ISD::FP_EXTEND && 7542 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 7543 break; 7544 In2 = In2.getOperand(0); 7545 if (In2.getOpcode() != ISD::FNEG) 7546 break; 7547 SDLoc DL(N); 7548 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 7549 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 7550 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 7551 } 7552 case ISD::MGATHER: 7553 case ISD::MSCATTER: 7554 case ISD::VP_GATHER: 7555 case ISD::VP_SCATTER: { 7556 if (!DCI.isBeforeLegalize()) 7557 break; 7558 SDValue Index, ScaleOp; 7559 bool IsIndexScaled = false; 7560 bool IsIndexSigned = false; 7561 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 7562 Index = VPGSN->getIndex(); 7563 ScaleOp = VPGSN->getScale(); 7564 IsIndexScaled = VPGSN->isIndexScaled(); 7565 IsIndexSigned = VPGSN->isIndexSigned(); 7566 } else { 7567 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 7568 Index = MGSN->getIndex(); 7569 ScaleOp = MGSN->getScale(); 7570 IsIndexScaled = MGSN->isIndexScaled(); 7571 IsIndexSigned = MGSN->isIndexSigned(); 7572 } 7573 EVT IndexVT = Index.getValueType(); 7574 MVT XLenVT = Subtarget.getXLenVT(); 7575 // RISCV indexed loads only support the "unsigned unscaled" addressing 7576 // mode, so anything else must be manually legalized. 7577 bool NeedsIdxLegalization = 7578 IsIndexScaled || 7579 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 7580 if (!NeedsIdxLegalization) 7581 break; 7582 7583 SDLoc DL(N); 7584 7585 // Any index legalization should first promote to XLenVT, so we don't lose 7586 // bits when scaling. This may create an illegal index type so we let 7587 // LLVM's legalization take care of the splitting. 7588 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 7589 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 7590 IndexVT = IndexVT.changeVectorElementType(XLenVT); 7591 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 7592 DL, IndexVT, Index); 7593 } 7594 7595 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 7596 if (IsIndexScaled && Scale != 1) { 7597 // Manually scale the indices by the element size. 7598 // TODO: Sanitize the scale operand here? 7599 // TODO: For VP nodes, should we use VP_SHL here? 7600 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 7601 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 7602 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 7603 } 7604 7605 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 7606 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 7607 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 7608 {VPGN->getChain(), VPGN->getBasePtr(), Index, 7609 VPGN->getScale(), VPGN->getMask(), 7610 VPGN->getVectorLength()}, 7611 VPGN->getMemOperand(), NewIndexTy); 7612 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 7613 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 7614 {VPSN->getChain(), VPSN->getValue(), 7615 VPSN->getBasePtr(), Index, VPSN->getScale(), 7616 VPSN->getMask(), VPSN->getVectorLength()}, 7617 VPSN->getMemOperand(), NewIndexTy); 7618 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 7619 return DAG.getMaskedGather( 7620 N->getVTList(), MGN->getMemoryVT(), DL, 7621 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 7622 MGN->getBasePtr(), Index, MGN->getScale()}, 7623 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 7624 const auto *MSN = cast<MaskedScatterSDNode>(N); 7625 return DAG.getMaskedScatter( 7626 N->getVTList(), MSN->getMemoryVT(), DL, 7627 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 7628 Index, MSN->getScale()}, 7629 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 7630 } 7631 case RISCVISD::SRA_VL: 7632 case RISCVISD::SRL_VL: 7633 case RISCVISD::SHL_VL: { 7634 SDValue ShAmt = N->getOperand(1); 7635 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7636 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7637 SDLoc DL(N); 7638 SDValue VL = N->getOperand(3); 7639 EVT VT = N->getValueType(0); 7640 ShAmt = 7641 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 7642 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 7643 N->getOperand(2), N->getOperand(3)); 7644 } 7645 break; 7646 } 7647 case ISD::SRA: 7648 case ISD::SRL: 7649 case ISD::SHL: { 7650 SDValue ShAmt = N->getOperand(1); 7651 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7652 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7653 SDLoc DL(N); 7654 EVT VT = N->getValueType(0); 7655 ShAmt = 7656 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 7657 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 7658 } 7659 break; 7660 } 7661 case RISCVISD::MUL_VL: { 7662 SDValue Op0 = N->getOperand(0); 7663 SDValue Op1 = N->getOperand(1); 7664 if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG)) 7665 return V; 7666 if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG)) 7667 return V; 7668 return SDValue(); 7669 } 7670 case ISD::STORE: { 7671 auto *Store = cast<StoreSDNode>(N); 7672 SDValue Val = Store->getValue(); 7673 // Combine store of vmv.x.s to vse with VL of 1. 7674 // FIXME: Support FP. 7675 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 7676 SDValue Src = Val.getOperand(0); 7677 EVT VecVT = Src.getValueType(); 7678 EVT MemVT = Store->getMemoryVT(); 7679 // The memory VT and the element type must match. 7680 if (VecVT.getVectorElementType() == MemVT) { 7681 SDLoc DL(N); 7682 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7683 return DAG.getStoreVP( 7684 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 7685 DAG.getConstant(1, DL, MaskVT), 7686 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 7687 Store->getMemOperand(), Store->getAddressingMode(), 7688 Store->isTruncatingStore(), /*IsCompress*/ false); 7689 } 7690 } 7691 7692 break; 7693 } 7694 } 7695 7696 return SDValue(); 7697 } 7698 7699 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 7700 const SDNode *N, CombineLevel Level) const { 7701 // The following folds are only desirable if `(OP _, c1 << c2)` can be 7702 // materialised in fewer instructions than `(OP _, c1)`: 7703 // 7704 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 7705 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 7706 SDValue N0 = N->getOperand(0); 7707 EVT Ty = N0.getValueType(); 7708 if (Ty.isScalarInteger() && 7709 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 7710 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7711 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7712 if (C1 && C2) { 7713 const APInt &C1Int = C1->getAPIntValue(); 7714 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 7715 7716 // We can materialise `c1 << c2` into an add immediate, so it's "free", 7717 // and the combine should happen, to potentially allow further combines 7718 // later. 7719 if (ShiftedC1Int.getMinSignedBits() <= 64 && 7720 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 7721 return true; 7722 7723 // We can materialise `c1` in an add immediate, so it's "free", and the 7724 // combine should be prevented. 7725 if (C1Int.getMinSignedBits() <= 64 && 7726 isLegalAddImmediate(C1Int.getSExtValue())) 7727 return false; 7728 7729 // Neither constant will fit into an immediate, so find materialisation 7730 // costs. 7731 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 7732 Subtarget.getFeatureBits(), 7733 /*CompressionCost*/true); 7734 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 7735 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 7736 /*CompressionCost*/true); 7737 7738 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 7739 // combine should be prevented. 7740 if (C1Cost < ShiftedC1Cost) 7741 return false; 7742 } 7743 } 7744 return true; 7745 } 7746 7747 bool RISCVTargetLowering::targetShrinkDemandedConstant( 7748 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 7749 TargetLoweringOpt &TLO) const { 7750 // Delay this optimization as late as possible. 7751 if (!TLO.LegalOps) 7752 return false; 7753 7754 EVT VT = Op.getValueType(); 7755 if (VT.isVector()) 7756 return false; 7757 7758 // Only handle AND for now. 7759 if (Op.getOpcode() != ISD::AND) 7760 return false; 7761 7762 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7763 if (!C) 7764 return false; 7765 7766 const APInt &Mask = C->getAPIntValue(); 7767 7768 // Clear all non-demanded bits initially. 7769 APInt ShrunkMask = Mask & DemandedBits; 7770 7771 // Try to make a smaller immediate by setting undemanded bits. 7772 7773 APInt ExpandedMask = Mask | ~DemandedBits; 7774 7775 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 7776 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 7777 }; 7778 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 7779 if (NewMask == Mask) 7780 return true; 7781 SDLoc DL(Op); 7782 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 7783 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 7784 return TLO.CombineTo(Op, NewOp); 7785 }; 7786 7787 // If the shrunk mask fits in sign extended 12 bits, let the target 7788 // independent code apply it. 7789 if (ShrunkMask.isSignedIntN(12)) 7790 return false; 7791 7792 // Preserve (and X, 0xffff) when zext.h is supported. 7793 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 7794 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 7795 if (IsLegalMask(NewMask)) 7796 return UseMask(NewMask); 7797 } 7798 7799 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 7800 if (VT == MVT::i64) { 7801 APInt NewMask = APInt(64, 0xffffffff); 7802 if (IsLegalMask(NewMask)) 7803 return UseMask(NewMask); 7804 } 7805 7806 // For the remaining optimizations, we need to be able to make a negative 7807 // number through a combination of mask and undemanded bits. 7808 if (!ExpandedMask.isNegative()) 7809 return false; 7810 7811 // What is the fewest number of bits we need to represent the negative number. 7812 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 7813 7814 // Try to make a 12 bit negative immediate. If that fails try to make a 32 7815 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 7816 APInt NewMask = ShrunkMask; 7817 if (MinSignedBits <= 12) 7818 NewMask.setBitsFrom(11); 7819 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 7820 NewMask.setBitsFrom(31); 7821 else 7822 return false; 7823 7824 // Check that our new mask is a subset of the demanded mask. 7825 assert(IsLegalMask(NewMask)); 7826 return UseMask(NewMask); 7827 } 7828 7829 static void computeGREV(APInt &Src, unsigned ShAmt) { 7830 ShAmt &= Src.getBitWidth() - 1; 7831 uint64_t x = Src.getZExtValue(); 7832 if (ShAmt & 1) 7833 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 7834 if (ShAmt & 2) 7835 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 7836 if (ShAmt & 4) 7837 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 7838 if (ShAmt & 8) 7839 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 7840 if (ShAmt & 16) 7841 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 7842 if (ShAmt & 32) 7843 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 7844 Src = x; 7845 } 7846 7847 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 7848 KnownBits &Known, 7849 const APInt &DemandedElts, 7850 const SelectionDAG &DAG, 7851 unsigned Depth) const { 7852 unsigned BitWidth = Known.getBitWidth(); 7853 unsigned Opc = Op.getOpcode(); 7854 assert((Opc >= ISD::BUILTIN_OP_END || 7855 Opc == ISD::INTRINSIC_WO_CHAIN || 7856 Opc == ISD::INTRINSIC_W_CHAIN || 7857 Opc == ISD::INTRINSIC_VOID) && 7858 "Should use MaskedValueIsZero if you don't know whether Op" 7859 " is a target node!"); 7860 7861 Known.resetAll(); 7862 switch (Opc) { 7863 default: break; 7864 case RISCVISD::SELECT_CC: { 7865 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 7866 // If we don't know any bits, early out. 7867 if (Known.isUnknown()) 7868 break; 7869 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 7870 7871 // Only known if known in both the LHS and RHS. 7872 Known = KnownBits::commonBits(Known, Known2); 7873 break; 7874 } 7875 case RISCVISD::REMUW: { 7876 KnownBits Known2; 7877 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7878 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7879 // We only care about the lower 32 bits. 7880 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 7881 // Restore the original width by sign extending. 7882 Known = Known.sext(BitWidth); 7883 break; 7884 } 7885 case RISCVISD::DIVUW: { 7886 KnownBits Known2; 7887 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7888 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7889 // We only care about the lower 32 bits. 7890 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 7891 // Restore the original width by sign extending. 7892 Known = Known.sext(BitWidth); 7893 break; 7894 } 7895 case RISCVISD::CTZW: { 7896 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7897 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 7898 unsigned LowBits = Log2_32(PossibleTZ) + 1; 7899 Known.Zero.setBitsFrom(LowBits); 7900 break; 7901 } 7902 case RISCVISD::CLZW: { 7903 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7904 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 7905 unsigned LowBits = Log2_32(PossibleLZ) + 1; 7906 Known.Zero.setBitsFrom(LowBits); 7907 break; 7908 } 7909 case RISCVISD::GREV: 7910 case RISCVISD::GREVW: { 7911 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7912 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7913 if (Opc == RISCVISD::GREVW) 7914 Known = Known.trunc(32); 7915 unsigned ShAmt = C->getZExtValue(); 7916 computeGREV(Known.Zero, ShAmt); 7917 computeGREV(Known.One, ShAmt); 7918 if (Opc == RISCVISD::GREVW) 7919 Known = Known.sext(BitWidth); 7920 } 7921 break; 7922 } 7923 case RISCVISD::READ_VLENB: 7924 // We assume VLENB is at least 16 bytes. 7925 Known.Zero.setLowBits(4); 7926 // We assume VLENB is no more than 65536 / 8 bytes. 7927 Known.Zero.setBitsFrom(14); 7928 break; 7929 case ISD::INTRINSIC_W_CHAIN: { 7930 unsigned IntNo = Op.getConstantOperandVal(1); 7931 switch (IntNo) { 7932 default: 7933 // We can't do anything for most intrinsics. 7934 break; 7935 case Intrinsic::riscv_vsetvli: 7936 case Intrinsic::riscv_vsetvlimax: 7937 // Assume that VL output is positive and would fit in an int32_t. 7938 // TODO: VLEN might be capped at 16 bits in a future V spec update. 7939 if (BitWidth >= 32) 7940 Known.Zero.setBitsFrom(31); 7941 break; 7942 } 7943 break; 7944 } 7945 } 7946 } 7947 7948 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 7949 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 7950 unsigned Depth) const { 7951 switch (Op.getOpcode()) { 7952 default: 7953 break; 7954 case RISCVISD::SELECT_CC: { 7955 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 7956 if (Tmp == 1) return 1; // Early out. 7957 unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 7958 return std::min(Tmp, Tmp2); 7959 } 7960 case RISCVISD::SLLW: 7961 case RISCVISD::SRAW: 7962 case RISCVISD::SRLW: 7963 case RISCVISD::DIVW: 7964 case RISCVISD::DIVUW: 7965 case RISCVISD::REMUW: 7966 case RISCVISD::ROLW: 7967 case RISCVISD::RORW: 7968 case RISCVISD::GREVW: 7969 case RISCVISD::GORCW: 7970 case RISCVISD::FSLW: 7971 case RISCVISD::FSRW: 7972 case RISCVISD::SHFLW: 7973 case RISCVISD::UNSHFLW: 7974 case RISCVISD::BCOMPRESSW: 7975 case RISCVISD::BDECOMPRESSW: 7976 case RISCVISD::BFPW: 7977 case RISCVISD::FCVT_W_RV64: 7978 case RISCVISD::FCVT_WU_RV64: 7979 case RISCVISD::STRICT_FCVT_W_RV64: 7980 case RISCVISD::STRICT_FCVT_WU_RV64: 7981 // TODO: As the result is sign-extended, this is conservatively correct. A 7982 // more precise answer could be calculated for SRAW depending on known 7983 // bits in the shift amount. 7984 return 33; 7985 case RISCVISD::SHFL: 7986 case RISCVISD::UNSHFL: { 7987 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 7988 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 7989 // will stay within the upper 32 bits. If there were more than 32 sign bits 7990 // before there will be at least 33 sign bits after. 7991 if (Op.getValueType() == MVT::i64 && 7992 isa<ConstantSDNode>(Op.getOperand(1)) && 7993 (Op.getConstantOperandVal(1) & 0x10) == 0) { 7994 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 7995 if (Tmp > 32) 7996 return 33; 7997 } 7998 break; 7999 } 8000 case RISCVISD::VMV_X_S: 8001 // The number of sign bits of the scalar result is computed by obtaining the 8002 // element type of the input vector operand, subtracting its width from the 8003 // XLEN, and then adding one (sign bit within the element type). If the 8004 // element type is wider than XLen, the least-significant XLEN bits are 8005 // taken. 8006 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 8007 return 1; 8008 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 8009 } 8010 8011 return 1; 8012 } 8013 8014 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 8015 MachineBasicBlock *BB) { 8016 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 8017 8018 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 8019 // Should the count have wrapped while it was being read, we need to try 8020 // again. 8021 // ... 8022 // read: 8023 // rdcycleh x3 # load high word of cycle 8024 // rdcycle x2 # load low word of cycle 8025 // rdcycleh x4 # load high word of cycle 8026 // bne x3, x4, read # check if high word reads match, otherwise try again 8027 // ... 8028 8029 MachineFunction &MF = *BB->getParent(); 8030 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8031 MachineFunction::iterator It = ++BB->getIterator(); 8032 8033 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8034 MF.insert(It, LoopMBB); 8035 8036 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8037 MF.insert(It, DoneMBB); 8038 8039 // Transfer the remainder of BB and its successor edges to DoneMBB. 8040 DoneMBB->splice(DoneMBB->begin(), BB, 8041 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8042 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 8043 8044 BB->addSuccessor(LoopMBB); 8045 8046 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8047 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8048 Register LoReg = MI.getOperand(0).getReg(); 8049 Register HiReg = MI.getOperand(1).getReg(); 8050 DebugLoc DL = MI.getDebugLoc(); 8051 8052 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 8053 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 8054 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8055 .addReg(RISCV::X0); 8056 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 8057 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 8058 .addReg(RISCV::X0); 8059 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 8060 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8061 .addReg(RISCV::X0); 8062 8063 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 8064 .addReg(HiReg) 8065 .addReg(ReadAgainReg) 8066 .addMBB(LoopMBB); 8067 8068 LoopMBB->addSuccessor(LoopMBB); 8069 LoopMBB->addSuccessor(DoneMBB); 8070 8071 MI.eraseFromParent(); 8072 8073 return DoneMBB; 8074 } 8075 8076 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 8077 MachineBasicBlock *BB) { 8078 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 8079 8080 MachineFunction &MF = *BB->getParent(); 8081 DebugLoc DL = MI.getDebugLoc(); 8082 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8083 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8084 Register LoReg = MI.getOperand(0).getReg(); 8085 Register HiReg = MI.getOperand(1).getReg(); 8086 Register SrcReg = MI.getOperand(2).getReg(); 8087 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 8088 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8089 8090 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 8091 RI); 8092 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8093 MachineMemOperand *MMOLo = 8094 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 8095 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8096 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 8097 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 8098 .addFrameIndex(FI) 8099 .addImm(0) 8100 .addMemOperand(MMOLo); 8101 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 8102 .addFrameIndex(FI) 8103 .addImm(4) 8104 .addMemOperand(MMOHi); 8105 MI.eraseFromParent(); // The pseudo instruction is gone now. 8106 return BB; 8107 } 8108 8109 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 8110 MachineBasicBlock *BB) { 8111 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 8112 "Unexpected instruction"); 8113 8114 MachineFunction &MF = *BB->getParent(); 8115 DebugLoc DL = MI.getDebugLoc(); 8116 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8117 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8118 Register DstReg = MI.getOperand(0).getReg(); 8119 Register LoReg = MI.getOperand(1).getReg(); 8120 Register HiReg = MI.getOperand(2).getReg(); 8121 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 8122 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8123 8124 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8125 MachineMemOperand *MMOLo = 8126 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 8127 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8128 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 8129 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8130 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 8131 .addFrameIndex(FI) 8132 .addImm(0) 8133 .addMemOperand(MMOLo); 8134 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8135 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 8136 .addFrameIndex(FI) 8137 .addImm(4) 8138 .addMemOperand(MMOHi); 8139 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 8140 MI.eraseFromParent(); // The pseudo instruction is gone now. 8141 return BB; 8142 } 8143 8144 static bool isSelectPseudo(MachineInstr &MI) { 8145 switch (MI.getOpcode()) { 8146 default: 8147 return false; 8148 case RISCV::Select_GPR_Using_CC_GPR: 8149 case RISCV::Select_FPR16_Using_CC_GPR: 8150 case RISCV::Select_FPR32_Using_CC_GPR: 8151 case RISCV::Select_FPR64_Using_CC_GPR: 8152 return true; 8153 } 8154 } 8155 8156 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 8157 unsigned RelOpcode, unsigned EqOpcode, 8158 const RISCVSubtarget &Subtarget) { 8159 DebugLoc DL = MI.getDebugLoc(); 8160 Register DstReg = MI.getOperand(0).getReg(); 8161 Register Src1Reg = MI.getOperand(1).getReg(); 8162 Register Src2Reg = MI.getOperand(2).getReg(); 8163 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 8164 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 8165 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 8166 8167 // Save the current FFLAGS. 8168 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 8169 8170 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 8171 .addReg(Src1Reg) 8172 .addReg(Src2Reg); 8173 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8174 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 8175 8176 // Restore the FFLAGS. 8177 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 8178 .addReg(SavedFFlags, RegState::Kill); 8179 8180 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 8181 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 8182 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 8183 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 8184 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8185 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 8186 8187 // Erase the pseudoinstruction. 8188 MI.eraseFromParent(); 8189 return BB; 8190 } 8191 8192 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 8193 MachineBasicBlock *BB, 8194 const RISCVSubtarget &Subtarget) { 8195 // To "insert" Select_* instructions, we actually have to insert the triangle 8196 // control-flow pattern. The incoming instructions know the destination vreg 8197 // to set, the condition code register to branch on, the true/false values to 8198 // select between, and the condcode to use to select the appropriate branch. 8199 // 8200 // We produce the following control flow: 8201 // HeadMBB 8202 // | \ 8203 // | IfFalseMBB 8204 // | / 8205 // TailMBB 8206 // 8207 // When we find a sequence of selects we attempt to optimize their emission 8208 // by sharing the control flow. Currently we only handle cases where we have 8209 // multiple selects with the exact same condition (same LHS, RHS and CC). 8210 // The selects may be interleaved with other instructions if the other 8211 // instructions meet some requirements we deem safe: 8212 // - They are debug instructions. Otherwise, 8213 // - They do not have side-effects, do not access memory and their inputs do 8214 // not depend on the results of the select pseudo-instructions. 8215 // The TrueV/FalseV operands of the selects cannot depend on the result of 8216 // previous selects in the sequence. 8217 // These conditions could be further relaxed. See the X86 target for a 8218 // related approach and more information. 8219 Register LHS = MI.getOperand(1).getReg(); 8220 Register RHS = MI.getOperand(2).getReg(); 8221 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 8222 8223 SmallVector<MachineInstr *, 4> SelectDebugValues; 8224 SmallSet<Register, 4> SelectDests; 8225 SelectDests.insert(MI.getOperand(0).getReg()); 8226 8227 MachineInstr *LastSelectPseudo = &MI; 8228 8229 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 8230 SequenceMBBI != E; ++SequenceMBBI) { 8231 if (SequenceMBBI->isDebugInstr()) 8232 continue; 8233 else if (isSelectPseudo(*SequenceMBBI)) { 8234 if (SequenceMBBI->getOperand(1).getReg() != LHS || 8235 SequenceMBBI->getOperand(2).getReg() != RHS || 8236 SequenceMBBI->getOperand(3).getImm() != CC || 8237 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 8238 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 8239 break; 8240 LastSelectPseudo = &*SequenceMBBI; 8241 SequenceMBBI->collectDebugValues(SelectDebugValues); 8242 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 8243 } else { 8244 if (SequenceMBBI->hasUnmodeledSideEffects() || 8245 SequenceMBBI->mayLoadOrStore()) 8246 break; 8247 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 8248 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 8249 })) 8250 break; 8251 } 8252 } 8253 8254 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 8255 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8256 DebugLoc DL = MI.getDebugLoc(); 8257 MachineFunction::iterator I = ++BB->getIterator(); 8258 8259 MachineBasicBlock *HeadMBB = BB; 8260 MachineFunction *F = BB->getParent(); 8261 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 8262 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 8263 8264 F->insert(I, IfFalseMBB); 8265 F->insert(I, TailMBB); 8266 8267 // Transfer debug instructions associated with the selects to TailMBB. 8268 for (MachineInstr *DebugInstr : SelectDebugValues) { 8269 TailMBB->push_back(DebugInstr->removeFromParent()); 8270 } 8271 8272 // Move all instructions after the sequence to TailMBB. 8273 TailMBB->splice(TailMBB->end(), HeadMBB, 8274 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 8275 // Update machine-CFG edges by transferring all successors of the current 8276 // block to the new block which will contain the Phi nodes for the selects. 8277 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 8278 // Set the successors for HeadMBB. 8279 HeadMBB->addSuccessor(IfFalseMBB); 8280 HeadMBB->addSuccessor(TailMBB); 8281 8282 // Insert appropriate branch. 8283 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 8284 .addReg(LHS) 8285 .addReg(RHS) 8286 .addMBB(TailMBB); 8287 8288 // IfFalseMBB just falls through to TailMBB. 8289 IfFalseMBB->addSuccessor(TailMBB); 8290 8291 // Create PHIs for all of the select pseudo-instructions. 8292 auto SelectMBBI = MI.getIterator(); 8293 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 8294 auto InsertionPoint = TailMBB->begin(); 8295 while (SelectMBBI != SelectEnd) { 8296 auto Next = std::next(SelectMBBI); 8297 if (isSelectPseudo(*SelectMBBI)) { 8298 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 8299 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 8300 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 8301 .addReg(SelectMBBI->getOperand(4).getReg()) 8302 .addMBB(HeadMBB) 8303 .addReg(SelectMBBI->getOperand(5).getReg()) 8304 .addMBB(IfFalseMBB); 8305 SelectMBBI->eraseFromParent(); 8306 } 8307 SelectMBBI = Next; 8308 } 8309 8310 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 8311 return TailMBB; 8312 } 8313 8314 MachineBasicBlock * 8315 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8316 MachineBasicBlock *BB) const { 8317 switch (MI.getOpcode()) { 8318 default: 8319 llvm_unreachable("Unexpected instr type to insert"); 8320 case RISCV::ReadCycleWide: 8321 assert(!Subtarget.is64Bit() && 8322 "ReadCycleWrite is only to be used on riscv32"); 8323 return emitReadCycleWidePseudo(MI, BB); 8324 case RISCV::Select_GPR_Using_CC_GPR: 8325 case RISCV::Select_FPR16_Using_CC_GPR: 8326 case RISCV::Select_FPR32_Using_CC_GPR: 8327 case RISCV::Select_FPR64_Using_CC_GPR: 8328 return emitSelectPseudo(MI, BB, Subtarget); 8329 case RISCV::BuildPairF64Pseudo: 8330 return emitBuildPairF64Pseudo(MI, BB); 8331 case RISCV::SplitF64Pseudo: 8332 return emitSplitF64Pseudo(MI, BB); 8333 case RISCV::PseudoQuietFLE_H: 8334 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 8335 case RISCV::PseudoQuietFLT_H: 8336 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 8337 case RISCV::PseudoQuietFLE_S: 8338 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 8339 case RISCV::PseudoQuietFLT_S: 8340 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 8341 case RISCV::PseudoQuietFLE_D: 8342 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 8343 case RISCV::PseudoQuietFLT_D: 8344 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 8345 } 8346 } 8347 8348 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 8349 SDNode *Node) const { 8350 // Add FRM dependency to any instructions with dynamic rounding mode. 8351 unsigned Opc = MI.getOpcode(); 8352 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 8353 if (Idx < 0) 8354 return; 8355 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 8356 return; 8357 // If the instruction already reads FRM, don't add another read. 8358 if (MI.readsRegister(RISCV::FRM)) 8359 return; 8360 MI.addOperand( 8361 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 8362 } 8363 8364 // Calling Convention Implementation. 8365 // The expectations for frontend ABI lowering vary from target to target. 8366 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 8367 // details, but this is a longer term goal. For now, we simply try to keep the 8368 // role of the frontend as simple and well-defined as possible. The rules can 8369 // be summarised as: 8370 // * Never split up large scalar arguments. We handle them here. 8371 // * If a hardfloat calling convention is being used, and the struct may be 8372 // passed in a pair of registers (fp+fp, int+fp), and both registers are 8373 // available, then pass as two separate arguments. If either the GPRs or FPRs 8374 // are exhausted, then pass according to the rule below. 8375 // * If a struct could never be passed in registers or directly in a stack 8376 // slot (as it is larger than 2*XLEN and the floating point rules don't 8377 // apply), then pass it using a pointer with the byval attribute. 8378 // * If a struct is less than 2*XLEN, then coerce to either a two-element 8379 // word-sized array or a 2*XLEN scalar (depending on alignment). 8380 // * The frontend can determine whether a struct is returned by reference or 8381 // not based on its size and fields. If it will be returned by reference, the 8382 // frontend must modify the prototype so a pointer with the sret annotation is 8383 // passed as the first argument. This is not necessary for large scalar 8384 // returns. 8385 // * Struct return values and varargs should be coerced to structs containing 8386 // register-size fields in the same situations they would be for fixed 8387 // arguments. 8388 8389 static const MCPhysReg ArgGPRs[] = { 8390 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 8391 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 8392 }; 8393 static const MCPhysReg ArgFPR16s[] = { 8394 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 8395 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 8396 }; 8397 static const MCPhysReg ArgFPR32s[] = { 8398 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 8399 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 8400 }; 8401 static const MCPhysReg ArgFPR64s[] = { 8402 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 8403 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 8404 }; 8405 // This is an interim calling convention and it may be changed in the future. 8406 static const MCPhysReg ArgVRs[] = { 8407 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 8408 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 8409 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 8410 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 8411 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 8412 RISCV::V20M2, RISCV::V22M2}; 8413 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 8414 RISCV::V20M4}; 8415 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 8416 8417 // Pass a 2*XLEN argument that has been split into two XLEN values through 8418 // registers or the stack as necessary. 8419 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 8420 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 8421 MVT ValVT2, MVT LocVT2, 8422 ISD::ArgFlagsTy ArgFlags2) { 8423 unsigned XLenInBytes = XLen / 8; 8424 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8425 // At least one half can be passed via register. 8426 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 8427 VA1.getLocVT(), CCValAssign::Full)); 8428 } else { 8429 // Both halves must be passed on the stack, with proper alignment. 8430 Align StackAlign = 8431 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 8432 State.addLoc( 8433 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 8434 State.AllocateStack(XLenInBytes, StackAlign), 8435 VA1.getLocVT(), CCValAssign::Full)); 8436 State.addLoc(CCValAssign::getMem( 8437 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8438 LocVT2, CCValAssign::Full)); 8439 return false; 8440 } 8441 8442 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8443 // The second half can also be passed via register. 8444 State.addLoc( 8445 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 8446 } else { 8447 // The second half is passed via the stack, without additional alignment. 8448 State.addLoc(CCValAssign::getMem( 8449 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8450 LocVT2, CCValAssign::Full)); 8451 } 8452 8453 return false; 8454 } 8455 8456 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 8457 Optional<unsigned> FirstMaskArgument, 8458 CCState &State, const RISCVTargetLowering &TLI) { 8459 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 8460 if (RC == &RISCV::VRRegClass) { 8461 // Assign the first mask argument to V0. 8462 // This is an interim calling convention and it may be changed in the 8463 // future. 8464 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 8465 return State.AllocateReg(RISCV::V0); 8466 return State.AllocateReg(ArgVRs); 8467 } 8468 if (RC == &RISCV::VRM2RegClass) 8469 return State.AllocateReg(ArgVRM2s); 8470 if (RC == &RISCV::VRM4RegClass) 8471 return State.AllocateReg(ArgVRM4s); 8472 if (RC == &RISCV::VRM8RegClass) 8473 return State.AllocateReg(ArgVRM8s); 8474 llvm_unreachable("Unhandled register class for ValueType"); 8475 } 8476 8477 // Implements the RISC-V calling convention. Returns true upon failure. 8478 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 8479 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 8480 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 8481 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 8482 Optional<unsigned> FirstMaskArgument) { 8483 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 8484 assert(XLen == 32 || XLen == 64); 8485 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 8486 8487 // Any return value split in to more than two values can't be returned 8488 // directly. Vectors are returned via the available vector registers. 8489 if (!LocVT.isVector() && IsRet && ValNo > 1) 8490 return true; 8491 8492 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 8493 // variadic argument, or if no F16/F32 argument registers are available. 8494 bool UseGPRForF16_F32 = true; 8495 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 8496 // variadic argument, or if no F64 argument registers are available. 8497 bool UseGPRForF64 = true; 8498 8499 switch (ABI) { 8500 default: 8501 llvm_unreachable("Unexpected ABI"); 8502 case RISCVABI::ABI_ILP32: 8503 case RISCVABI::ABI_LP64: 8504 break; 8505 case RISCVABI::ABI_ILP32F: 8506 case RISCVABI::ABI_LP64F: 8507 UseGPRForF16_F32 = !IsFixed; 8508 break; 8509 case RISCVABI::ABI_ILP32D: 8510 case RISCVABI::ABI_LP64D: 8511 UseGPRForF16_F32 = !IsFixed; 8512 UseGPRForF64 = !IsFixed; 8513 break; 8514 } 8515 8516 // FPR16, FPR32, and FPR64 alias each other. 8517 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 8518 UseGPRForF16_F32 = true; 8519 UseGPRForF64 = true; 8520 } 8521 8522 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 8523 // similar local variables rather than directly checking against the target 8524 // ABI. 8525 8526 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 8527 LocVT = XLenVT; 8528 LocInfo = CCValAssign::BCvt; 8529 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 8530 LocVT = MVT::i64; 8531 LocInfo = CCValAssign::BCvt; 8532 } 8533 8534 // If this is a variadic argument, the RISC-V calling convention requires 8535 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 8536 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 8537 // be used regardless of whether the original argument was split during 8538 // legalisation or not. The argument will not be passed by registers if the 8539 // original type is larger than 2*XLEN, so the register alignment rule does 8540 // not apply. 8541 unsigned TwoXLenInBytes = (2 * XLen) / 8; 8542 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 8543 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 8544 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 8545 // Skip 'odd' register if necessary. 8546 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 8547 State.AllocateReg(ArgGPRs); 8548 } 8549 8550 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 8551 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 8552 State.getPendingArgFlags(); 8553 8554 assert(PendingLocs.size() == PendingArgFlags.size() && 8555 "PendingLocs and PendingArgFlags out of sync"); 8556 8557 // Handle passing f64 on RV32D with a soft float ABI or when floating point 8558 // registers are exhausted. 8559 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 8560 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 8561 "Can't lower f64 if it is split"); 8562 // Depending on available argument GPRS, f64 may be passed in a pair of 8563 // GPRs, split between a GPR and the stack, or passed completely on the 8564 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 8565 // cases. 8566 Register Reg = State.AllocateReg(ArgGPRs); 8567 LocVT = MVT::i32; 8568 if (!Reg) { 8569 unsigned StackOffset = State.AllocateStack(8, Align(8)); 8570 State.addLoc( 8571 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8572 return false; 8573 } 8574 if (!State.AllocateReg(ArgGPRs)) 8575 State.AllocateStack(4, Align(4)); 8576 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8577 return false; 8578 } 8579 8580 // Fixed-length vectors are located in the corresponding scalable-vector 8581 // container types. 8582 if (ValVT.isFixedLengthVector()) 8583 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8584 8585 // Split arguments might be passed indirectly, so keep track of the pending 8586 // values. Split vectors are passed via a mix of registers and indirectly, so 8587 // treat them as we would any other argument. 8588 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 8589 LocVT = XLenVT; 8590 LocInfo = CCValAssign::Indirect; 8591 PendingLocs.push_back( 8592 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 8593 PendingArgFlags.push_back(ArgFlags); 8594 if (!ArgFlags.isSplitEnd()) { 8595 return false; 8596 } 8597 } 8598 8599 // If the split argument only had two elements, it should be passed directly 8600 // in registers or on the stack. 8601 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 8602 PendingLocs.size() <= 2) { 8603 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 8604 // Apply the normal calling convention rules to the first half of the 8605 // split argument. 8606 CCValAssign VA = PendingLocs[0]; 8607 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 8608 PendingLocs.clear(); 8609 PendingArgFlags.clear(); 8610 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 8611 ArgFlags); 8612 } 8613 8614 // Allocate to a register if possible, or else a stack slot. 8615 Register Reg; 8616 unsigned StoreSizeBytes = XLen / 8; 8617 Align StackAlign = Align(XLen / 8); 8618 8619 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 8620 Reg = State.AllocateReg(ArgFPR16s); 8621 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 8622 Reg = State.AllocateReg(ArgFPR32s); 8623 else if (ValVT == MVT::f64 && !UseGPRForF64) 8624 Reg = State.AllocateReg(ArgFPR64s); 8625 else if (ValVT.isVector()) { 8626 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 8627 if (!Reg) { 8628 // For return values, the vector must be passed fully via registers or 8629 // via the stack. 8630 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 8631 // but we're using all of them. 8632 if (IsRet) 8633 return true; 8634 // Try using a GPR to pass the address 8635 if ((Reg = State.AllocateReg(ArgGPRs))) { 8636 LocVT = XLenVT; 8637 LocInfo = CCValAssign::Indirect; 8638 } else if (ValVT.isScalableVector()) { 8639 LocVT = XLenVT; 8640 LocInfo = CCValAssign::Indirect; 8641 } else { 8642 // Pass fixed-length vectors on the stack. 8643 LocVT = ValVT; 8644 StoreSizeBytes = ValVT.getStoreSize(); 8645 // Align vectors to their element sizes, being careful for vXi1 8646 // vectors. 8647 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8648 } 8649 } 8650 } else { 8651 Reg = State.AllocateReg(ArgGPRs); 8652 } 8653 8654 unsigned StackOffset = 8655 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 8656 8657 // If we reach this point and PendingLocs is non-empty, we must be at the 8658 // end of a split argument that must be passed indirectly. 8659 if (!PendingLocs.empty()) { 8660 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 8661 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 8662 8663 for (auto &It : PendingLocs) { 8664 if (Reg) 8665 It.convertToReg(Reg); 8666 else 8667 It.convertToMem(StackOffset); 8668 State.addLoc(It); 8669 } 8670 PendingLocs.clear(); 8671 PendingArgFlags.clear(); 8672 return false; 8673 } 8674 8675 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 8676 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 8677 "Expected an XLenVT or vector types at this stage"); 8678 8679 if (Reg) { 8680 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8681 return false; 8682 } 8683 8684 // When a floating-point value is passed on the stack, no bit-conversion is 8685 // needed. 8686 if (ValVT.isFloatingPoint()) { 8687 LocVT = ValVT; 8688 LocInfo = CCValAssign::Full; 8689 } 8690 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8691 return false; 8692 } 8693 8694 template <typename ArgTy> 8695 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 8696 for (const auto &ArgIdx : enumerate(Args)) { 8697 MVT ArgVT = ArgIdx.value().VT; 8698 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 8699 return ArgIdx.index(); 8700 } 8701 return None; 8702 } 8703 8704 void RISCVTargetLowering::analyzeInputArgs( 8705 MachineFunction &MF, CCState &CCInfo, 8706 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 8707 RISCVCCAssignFn Fn) const { 8708 unsigned NumArgs = Ins.size(); 8709 FunctionType *FType = MF.getFunction().getFunctionType(); 8710 8711 Optional<unsigned> FirstMaskArgument; 8712 if (Subtarget.hasVInstructions()) 8713 FirstMaskArgument = preAssignMask(Ins); 8714 8715 for (unsigned i = 0; i != NumArgs; ++i) { 8716 MVT ArgVT = Ins[i].VT; 8717 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 8718 8719 Type *ArgTy = nullptr; 8720 if (IsRet) 8721 ArgTy = FType->getReturnType(); 8722 else if (Ins[i].isOrigArg()) 8723 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 8724 8725 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8726 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8727 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 8728 FirstMaskArgument)) { 8729 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 8730 << EVT(ArgVT).getEVTString() << '\n'); 8731 llvm_unreachable(nullptr); 8732 } 8733 } 8734 } 8735 8736 void RISCVTargetLowering::analyzeOutputArgs( 8737 MachineFunction &MF, CCState &CCInfo, 8738 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 8739 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 8740 unsigned NumArgs = Outs.size(); 8741 8742 Optional<unsigned> FirstMaskArgument; 8743 if (Subtarget.hasVInstructions()) 8744 FirstMaskArgument = preAssignMask(Outs); 8745 8746 for (unsigned i = 0; i != NumArgs; i++) { 8747 MVT ArgVT = Outs[i].VT; 8748 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 8749 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 8750 8751 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8752 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8753 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 8754 FirstMaskArgument)) { 8755 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 8756 << EVT(ArgVT).getEVTString() << "\n"); 8757 llvm_unreachable(nullptr); 8758 } 8759 } 8760 } 8761 8762 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 8763 // values. 8764 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 8765 const CCValAssign &VA, const SDLoc &DL, 8766 const RISCVSubtarget &Subtarget) { 8767 switch (VA.getLocInfo()) { 8768 default: 8769 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8770 case CCValAssign::Full: 8771 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 8772 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 8773 break; 8774 case CCValAssign::BCvt: 8775 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8776 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 8777 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8778 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 8779 else 8780 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 8781 break; 8782 } 8783 return Val; 8784 } 8785 8786 // The caller is responsible for loading the full value if the argument is 8787 // passed with CCValAssign::Indirect. 8788 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 8789 const CCValAssign &VA, const SDLoc &DL, 8790 const RISCVTargetLowering &TLI) { 8791 MachineFunction &MF = DAG.getMachineFunction(); 8792 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8793 EVT LocVT = VA.getLocVT(); 8794 SDValue Val; 8795 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 8796 Register VReg = RegInfo.createVirtualRegister(RC); 8797 RegInfo.addLiveIn(VA.getLocReg(), VReg); 8798 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 8799 8800 if (VA.getLocInfo() == CCValAssign::Indirect) 8801 return Val; 8802 8803 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 8804 } 8805 8806 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 8807 const CCValAssign &VA, const SDLoc &DL, 8808 const RISCVSubtarget &Subtarget) { 8809 EVT LocVT = VA.getLocVT(); 8810 8811 switch (VA.getLocInfo()) { 8812 default: 8813 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8814 case CCValAssign::Full: 8815 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 8816 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 8817 break; 8818 case CCValAssign::BCvt: 8819 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8820 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 8821 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8822 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 8823 else 8824 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 8825 break; 8826 } 8827 return Val; 8828 } 8829 8830 // The caller is responsible for loading the full value if the argument is 8831 // passed with CCValAssign::Indirect. 8832 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 8833 const CCValAssign &VA, const SDLoc &DL) { 8834 MachineFunction &MF = DAG.getMachineFunction(); 8835 MachineFrameInfo &MFI = MF.getFrameInfo(); 8836 EVT LocVT = VA.getLocVT(); 8837 EVT ValVT = VA.getValVT(); 8838 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 8839 if (ValVT.isScalableVector()) { 8840 // When the value is a scalable vector, we save the pointer which points to 8841 // the scalable vector value in the stack. The ValVT will be the pointer 8842 // type, instead of the scalable vector type. 8843 ValVT = LocVT; 8844 } 8845 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 8846 /*IsImmutable=*/true); 8847 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 8848 SDValue Val; 8849 8850 ISD::LoadExtType ExtType; 8851 switch (VA.getLocInfo()) { 8852 default: 8853 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8854 case CCValAssign::Full: 8855 case CCValAssign::Indirect: 8856 case CCValAssign::BCvt: 8857 ExtType = ISD::NON_EXTLOAD; 8858 break; 8859 } 8860 Val = DAG.getExtLoad( 8861 ExtType, DL, LocVT, Chain, FIN, 8862 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 8863 return Val; 8864 } 8865 8866 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 8867 const CCValAssign &VA, const SDLoc &DL) { 8868 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 8869 "Unexpected VA"); 8870 MachineFunction &MF = DAG.getMachineFunction(); 8871 MachineFrameInfo &MFI = MF.getFrameInfo(); 8872 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8873 8874 if (VA.isMemLoc()) { 8875 // f64 is passed on the stack. 8876 int FI = 8877 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 8878 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8879 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 8880 MachinePointerInfo::getFixedStack(MF, FI)); 8881 } 8882 8883 assert(VA.isRegLoc() && "Expected register VA assignment"); 8884 8885 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8886 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 8887 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 8888 SDValue Hi; 8889 if (VA.getLocReg() == RISCV::X17) { 8890 // Second half of f64 is passed on the stack. 8891 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 8892 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8893 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 8894 MachinePointerInfo::getFixedStack(MF, FI)); 8895 } else { 8896 // Second half of f64 is passed in another GPR. 8897 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8898 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 8899 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 8900 } 8901 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 8902 } 8903 8904 // FastCC has less than 1% performance improvement for some particular 8905 // benchmark. But theoretically, it may has benenfit for some cases. 8906 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 8907 unsigned ValNo, MVT ValVT, MVT LocVT, 8908 CCValAssign::LocInfo LocInfo, 8909 ISD::ArgFlagsTy ArgFlags, CCState &State, 8910 bool IsFixed, bool IsRet, Type *OrigTy, 8911 const RISCVTargetLowering &TLI, 8912 Optional<unsigned> FirstMaskArgument) { 8913 8914 // X5 and X6 might be used for save-restore libcall. 8915 static const MCPhysReg GPRList[] = { 8916 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 8917 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 8918 RISCV::X29, RISCV::X30, RISCV::X31}; 8919 8920 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8921 if (unsigned Reg = State.AllocateReg(GPRList)) { 8922 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8923 return false; 8924 } 8925 } 8926 8927 if (LocVT == MVT::f16) { 8928 static const MCPhysReg FPR16List[] = { 8929 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 8930 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 8931 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 8932 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 8933 if (unsigned Reg = State.AllocateReg(FPR16List)) { 8934 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8935 return false; 8936 } 8937 } 8938 8939 if (LocVT == MVT::f32) { 8940 static const MCPhysReg FPR32List[] = { 8941 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 8942 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 8943 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 8944 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 8945 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8946 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8947 return false; 8948 } 8949 } 8950 8951 if (LocVT == MVT::f64) { 8952 static const MCPhysReg FPR64List[] = { 8953 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 8954 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 8955 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 8956 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 8957 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8958 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8959 return false; 8960 } 8961 } 8962 8963 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 8964 unsigned Offset4 = State.AllocateStack(4, Align(4)); 8965 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 8966 return false; 8967 } 8968 8969 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 8970 unsigned Offset5 = State.AllocateStack(8, Align(8)); 8971 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 8972 return false; 8973 } 8974 8975 if (LocVT.isVector()) { 8976 if (unsigned Reg = 8977 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 8978 // Fixed-length vectors are located in the corresponding scalable-vector 8979 // container types. 8980 if (ValVT.isFixedLengthVector()) 8981 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8982 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8983 } else { 8984 // Try and pass the address via a "fast" GPR. 8985 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 8986 LocInfo = CCValAssign::Indirect; 8987 LocVT = TLI.getSubtarget().getXLenVT(); 8988 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 8989 } else if (ValVT.isFixedLengthVector()) { 8990 auto StackAlign = 8991 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8992 unsigned StackOffset = 8993 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 8994 State.addLoc( 8995 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8996 } else { 8997 // Can't pass scalable vectors on the stack. 8998 return true; 8999 } 9000 } 9001 9002 return false; 9003 } 9004 9005 return true; // CC didn't match. 9006 } 9007 9008 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9009 CCValAssign::LocInfo LocInfo, 9010 ISD::ArgFlagsTy ArgFlags, CCState &State) { 9011 9012 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9013 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 9014 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 9015 static const MCPhysReg GPRList[] = { 9016 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 9017 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 9018 if (unsigned Reg = State.AllocateReg(GPRList)) { 9019 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9020 return false; 9021 } 9022 } 9023 9024 if (LocVT == MVT::f32) { 9025 // Pass in STG registers: F1, ..., F6 9026 // fs0 ... fs5 9027 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 9028 RISCV::F18_F, RISCV::F19_F, 9029 RISCV::F20_F, RISCV::F21_F}; 9030 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9031 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9032 return false; 9033 } 9034 } 9035 9036 if (LocVT == MVT::f64) { 9037 // Pass in STG registers: D1, ..., D6 9038 // fs6 ... fs11 9039 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 9040 RISCV::F24_D, RISCV::F25_D, 9041 RISCV::F26_D, RISCV::F27_D}; 9042 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9043 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9044 return false; 9045 } 9046 } 9047 9048 report_fatal_error("No registers left in GHC calling convention"); 9049 return true; 9050 } 9051 9052 // Transform physical registers into virtual registers. 9053 SDValue RISCVTargetLowering::LowerFormalArguments( 9054 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 9055 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 9056 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 9057 9058 MachineFunction &MF = DAG.getMachineFunction(); 9059 9060 switch (CallConv) { 9061 default: 9062 report_fatal_error("Unsupported calling convention"); 9063 case CallingConv::C: 9064 case CallingConv::Fast: 9065 break; 9066 case CallingConv::GHC: 9067 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 9068 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 9069 report_fatal_error( 9070 "GHC calling convention requires the F and D instruction set extensions"); 9071 } 9072 9073 const Function &Func = MF.getFunction(); 9074 if (Func.hasFnAttribute("interrupt")) { 9075 if (!Func.arg_empty()) 9076 report_fatal_error( 9077 "Functions with the interrupt attribute cannot have arguments!"); 9078 9079 StringRef Kind = 9080 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9081 9082 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 9083 report_fatal_error( 9084 "Function interrupt attribute argument not supported!"); 9085 } 9086 9087 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9088 MVT XLenVT = Subtarget.getXLenVT(); 9089 unsigned XLenInBytes = Subtarget.getXLen() / 8; 9090 // Used with vargs to acumulate store chains. 9091 std::vector<SDValue> OutChains; 9092 9093 // Assign locations to all of the incoming arguments. 9094 SmallVector<CCValAssign, 16> ArgLocs; 9095 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9096 9097 if (CallConv == CallingConv::GHC) 9098 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 9099 else 9100 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 9101 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9102 : CC_RISCV); 9103 9104 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 9105 CCValAssign &VA = ArgLocs[i]; 9106 SDValue ArgValue; 9107 // Passing f64 on RV32D with a soft float ABI must be handled as a special 9108 // case. 9109 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 9110 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 9111 else if (VA.isRegLoc()) 9112 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 9113 else 9114 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 9115 9116 if (VA.getLocInfo() == CCValAssign::Indirect) { 9117 // If the original argument was split and passed by reference (e.g. i128 9118 // on RV32), we need to load all parts of it here (using the same 9119 // address). Vectors may be partly split to registers and partly to the 9120 // stack, in which case the base address is partly offset and subsequent 9121 // stores are relative to that. 9122 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 9123 MachinePointerInfo())); 9124 unsigned ArgIndex = Ins[i].OrigArgIndex; 9125 unsigned ArgPartOffset = Ins[i].PartOffset; 9126 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9127 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 9128 CCValAssign &PartVA = ArgLocs[i + 1]; 9129 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 9130 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9131 if (PartVA.getValVT().isScalableVector()) 9132 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9133 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 9134 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 9135 MachinePointerInfo())); 9136 ++i; 9137 } 9138 continue; 9139 } 9140 InVals.push_back(ArgValue); 9141 } 9142 9143 if (IsVarArg) { 9144 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 9145 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 9146 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 9147 MachineFrameInfo &MFI = MF.getFrameInfo(); 9148 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9149 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 9150 9151 // Offset of the first variable argument from stack pointer, and size of 9152 // the vararg save area. For now, the varargs save area is either zero or 9153 // large enough to hold a0-a7. 9154 int VaArgOffset, VarArgsSaveSize; 9155 9156 // If all registers are allocated, then all varargs must be passed on the 9157 // stack and we don't need to save any argregs. 9158 if (ArgRegs.size() == Idx) { 9159 VaArgOffset = CCInfo.getNextStackOffset(); 9160 VarArgsSaveSize = 0; 9161 } else { 9162 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 9163 VaArgOffset = -VarArgsSaveSize; 9164 } 9165 9166 // Record the frame index of the first variable argument 9167 // which is a value necessary to VASTART. 9168 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9169 RVFI->setVarArgsFrameIndex(FI); 9170 9171 // If saving an odd number of registers then create an extra stack slot to 9172 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 9173 // offsets to even-numbered registered remain 2*XLEN-aligned. 9174 if (Idx % 2) { 9175 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 9176 VarArgsSaveSize += XLenInBytes; 9177 } 9178 9179 // Copy the integer registers that may have been used for passing varargs 9180 // to the vararg save area. 9181 for (unsigned I = Idx; I < ArgRegs.size(); 9182 ++I, VaArgOffset += XLenInBytes) { 9183 const Register Reg = RegInfo.createVirtualRegister(RC); 9184 RegInfo.addLiveIn(ArgRegs[I], Reg); 9185 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 9186 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9187 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9188 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 9189 MachinePointerInfo::getFixedStack(MF, FI)); 9190 cast<StoreSDNode>(Store.getNode()) 9191 ->getMemOperand() 9192 ->setValue((Value *)nullptr); 9193 OutChains.push_back(Store); 9194 } 9195 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 9196 } 9197 9198 // All stores are grouped in one node to allow the matching between 9199 // the size of Ins and InVals. This only happens for vararg functions. 9200 if (!OutChains.empty()) { 9201 OutChains.push_back(Chain); 9202 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 9203 } 9204 9205 return Chain; 9206 } 9207 9208 /// isEligibleForTailCallOptimization - Check whether the call is eligible 9209 /// for tail call optimization. 9210 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 9211 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 9212 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 9213 const SmallVector<CCValAssign, 16> &ArgLocs) const { 9214 9215 auto &Callee = CLI.Callee; 9216 auto CalleeCC = CLI.CallConv; 9217 auto &Outs = CLI.Outs; 9218 auto &Caller = MF.getFunction(); 9219 auto CallerCC = Caller.getCallingConv(); 9220 9221 // Exception-handling functions need a special set of instructions to 9222 // indicate a return to the hardware. Tail-calling another function would 9223 // probably break this. 9224 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 9225 // should be expanded as new function attributes are introduced. 9226 if (Caller.hasFnAttribute("interrupt")) 9227 return false; 9228 9229 // Do not tail call opt if the stack is used to pass parameters. 9230 if (CCInfo.getNextStackOffset() != 0) 9231 return false; 9232 9233 // Do not tail call opt if any parameters need to be passed indirectly. 9234 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 9235 // passed indirectly. So the address of the value will be passed in a 9236 // register, or if not available, then the address is put on the stack. In 9237 // order to pass indirectly, space on the stack often needs to be allocated 9238 // in order to store the value. In this case the CCInfo.getNextStackOffset() 9239 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 9240 // are passed CCValAssign::Indirect. 9241 for (auto &VA : ArgLocs) 9242 if (VA.getLocInfo() == CCValAssign::Indirect) 9243 return false; 9244 9245 // Do not tail call opt if either caller or callee uses struct return 9246 // semantics. 9247 auto IsCallerStructRet = Caller.hasStructRetAttr(); 9248 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 9249 if (IsCallerStructRet || IsCalleeStructRet) 9250 return false; 9251 9252 // Externally-defined functions with weak linkage should not be 9253 // tail-called. The behaviour of branch instructions in this situation (as 9254 // used for tail calls) is implementation-defined, so we cannot rely on the 9255 // linker replacing the tail call with a return. 9256 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 9257 const GlobalValue *GV = G->getGlobal(); 9258 if (GV->hasExternalWeakLinkage()) 9259 return false; 9260 } 9261 9262 // The callee has to preserve all registers the caller needs to preserve. 9263 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9264 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 9265 if (CalleeCC != CallerCC) { 9266 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 9267 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 9268 return false; 9269 } 9270 9271 // Byval parameters hand the function a pointer directly into the stack area 9272 // we want to reuse during a tail call. Working around this *is* possible 9273 // but less efficient and uglier in LowerCall. 9274 for (auto &Arg : Outs) 9275 if (Arg.Flags.isByVal()) 9276 return false; 9277 9278 return true; 9279 } 9280 9281 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 9282 return DAG.getDataLayout().getPrefTypeAlign( 9283 VT.getTypeForEVT(*DAG.getContext())); 9284 } 9285 9286 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 9287 // and output parameter nodes. 9288 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 9289 SmallVectorImpl<SDValue> &InVals) const { 9290 SelectionDAG &DAG = CLI.DAG; 9291 SDLoc &DL = CLI.DL; 9292 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 9293 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 9294 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 9295 SDValue Chain = CLI.Chain; 9296 SDValue Callee = CLI.Callee; 9297 bool &IsTailCall = CLI.IsTailCall; 9298 CallingConv::ID CallConv = CLI.CallConv; 9299 bool IsVarArg = CLI.IsVarArg; 9300 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9301 MVT XLenVT = Subtarget.getXLenVT(); 9302 9303 MachineFunction &MF = DAG.getMachineFunction(); 9304 9305 // Analyze the operands of the call, assigning locations to each operand. 9306 SmallVector<CCValAssign, 16> ArgLocs; 9307 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9308 9309 if (CallConv == CallingConv::GHC) 9310 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 9311 else 9312 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 9313 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9314 : CC_RISCV); 9315 9316 // Check if it's really possible to do a tail call. 9317 if (IsTailCall) 9318 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 9319 9320 if (IsTailCall) 9321 ++NumTailCalls; 9322 else if (CLI.CB && CLI.CB->isMustTailCall()) 9323 report_fatal_error("failed to perform tail call elimination on a call " 9324 "site marked musttail"); 9325 9326 // Get a count of how many bytes are to be pushed on the stack. 9327 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 9328 9329 // Create local copies for byval args 9330 SmallVector<SDValue, 8> ByValArgs; 9331 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9332 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9333 if (!Flags.isByVal()) 9334 continue; 9335 9336 SDValue Arg = OutVals[i]; 9337 unsigned Size = Flags.getByValSize(); 9338 Align Alignment = Flags.getNonZeroByValAlign(); 9339 9340 int FI = 9341 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 9342 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9343 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 9344 9345 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 9346 /*IsVolatile=*/false, 9347 /*AlwaysInline=*/false, IsTailCall, 9348 MachinePointerInfo(), MachinePointerInfo()); 9349 ByValArgs.push_back(FIPtr); 9350 } 9351 9352 if (!IsTailCall) 9353 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 9354 9355 // Copy argument values to their designated locations. 9356 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 9357 SmallVector<SDValue, 8> MemOpChains; 9358 SDValue StackPtr; 9359 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 9360 CCValAssign &VA = ArgLocs[i]; 9361 SDValue ArgValue = OutVals[i]; 9362 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9363 9364 // Handle passing f64 on RV32D with a soft float ABI as a special case. 9365 bool IsF64OnRV32DSoftABI = 9366 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 9367 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 9368 SDValue SplitF64 = DAG.getNode( 9369 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 9370 SDValue Lo = SplitF64.getValue(0); 9371 SDValue Hi = SplitF64.getValue(1); 9372 9373 Register RegLo = VA.getLocReg(); 9374 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 9375 9376 if (RegLo == RISCV::X17) { 9377 // Second half of f64 is passed on the stack. 9378 // Work out the address of the stack slot. 9379 if (!StackPtr.getNode()) 9380 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9381 // Emit the store. 9382 MemOpChains.push_back( 9383 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 9384 } else { 9385 // Second half of f64 is passed in another GPR. 9386 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9387 Register RegHigh = RegLo + 1; 9388 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 9389 } 9390 continue; 9391 } 9392 9393 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 9394 // as any other MemLoc. 9395 9396 // Promote the value if needed. 9397 // For now, only handle fully promoted and indirect arguments. 9398 if (VA.getLocInfo() == CCValAssign::Indirect) { 9399 // Store the argument in a stack slot and pass its address. 9400 Align StackAlign = 9401 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 9402 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 9403 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 9404 // If the original argument was split (e.g. i128), we need 9405 // to store the required parts of it here (and pass just one address). 9406 // Vectors may be partly split to registers and partly to the stack, in 9407 // which case the base address is partly offset and subsequent stores are 9408 // relative to that. 9409 unsigned ArgIndex = Outs[i].OrigArgIndex; 9410 unsigned ArgPartOffset = Outs[i].PartOffset; 9411 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9412 // Calculate the total size to store. We don't have access to what we're 9413 // actually storing other than performing the loop and collecting the 9414 // info. 9415 SmallVector<std::pair<SDValue, SDValue>> Parts; 9416 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 9417 SDValue PartValue = OutVals[i + 1]; 9418 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 9419 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9420 EVT PartVT = PartValue.getValueType(); 9421 if (PartVT.isScalableVector()) 9422 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9423 StoredSize += PartVT.getStoreSize(); 9424 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 9425 Parts.push_back(std::make_pair(PartValue, Offset)); 9426 ++i; 9427 } 9428 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 9429 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 9430 MemOpChains.push_back( 9431 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 9432 MachinePointerInfo::getFixedStack(MF, FI))); 9433 for (const auto &Part : Parts) { 9434 SDValue PartValue = Part.first; 9435 SDValue PartOffset = Part.second; 9436 SDValue Address = 9437 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 9438 MemOpChains.push_back( 9439 DAG.getStore(Chain, DL, PartValue, Address, 9440 MachinePointerInfo::getFixedStack(MF, FI))); 9441 } 9442 ArgValue = SpillSlot; 9443 } else { 9444 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 9445 } 9446 9447 // Use local copy if it is a byval arg. 9448 if (Flags.isByVal()) 9449 ArgValue = ByValArgs[j++]; 9450 9451 if (VA.isRegLoc()) { 9452 // Queue up the argument copies and emit them at the end. 9453 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 9454 } else { 9455 assert(VA.isMemLoc() && "Argument not register or memory"); 9456 assert(!IsTailCall && "Tail call not allowed if stack is used " 9457 "for passing parameters"); 9458 9459 // Work out the address of the stack slot. 9460 if (!StackPtr.getNode()) 9461 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9462 SDValue Address = 9463 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 9464 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 9465 9466 // Emit the store. 9467 MemOpChains.push_back( 9468 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 9469 } 9470 } 9471 9472 // Join the stores, which are independent of one another. 9473 if (!MemOpChains.empty()) 9474 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 9475 9476 SDValue Glue; 9477 9478 // Build a sequence of copy-to-reg nodes, chained and glued together. 9479 for (auto &Reg : RegsToPass) { 9480 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 9481 Glue = Chain.getValue(1); 9482 } 9483 9484 // Validate that none of the argument registers have been marked as 9485 // reserved, if so report an error. Do the same for the return address if this 9486 // is not a tailcall. 9487 validateCCReservedRegs(RegsToPass, MF); 9488 if (!IsTailCall && 9489 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 9490 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9491 MF.getFunction(), 9492 "Return address register required, but has been reserved."}); 9493 9494 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 9495 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 9496 // split it and then direct call can be matched by PseudoCALL. 9497 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 9498 const GlobalValue *GV = S->getGlobal(); 9499 9500 unsigned OpFlags = RISCVII::MO_CALL; 9501 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 9502 OpFlags = RISCVII::MO_PLT; 9503 9504 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 9505 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 9506 unsigned OpFlags = RISCVII::MO_CALL; 9507 9508 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 9509 nullptr)) 9510 OpFlags = RISCVII::MO_PLT; 9511 9512 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 9513 } 9514 9515 // The first call operand is the chain and the second is the target address. 9516 SmallVector<SDValue, 8> Ops; 9517 Ops.push_back(Chain); 9518 Ops.push_back(Callee); 9519 9520 // Add argument registers to the end of the list so that they are 9521 // known live into the call. 9522 for (auto &Reg : RegsToPass) 9523 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 9524 9525 if (!IsTailCall) { 9526 // Add a register mask operand representing the call-preserved registers. 9527 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9528 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 9529 assert(Mask && "Missing call preserved mask for calling convention"); 9530 Ops.push_back(DAG.getRegisterMask(Mask)); 9531 } 9532 9533 // Glue the call to the argument copies, if any. 9534 if (Glue.getNode()) 9535 Ops.push_back(Glue); 9536 9537 // Emit the call. 9538 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9539 9540 if (IsTailCall) { 9541 MF.getFrameInfo().setHasTailCall(); 9542 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 9543 } 9544 9545 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 9546 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 9547 Glue = Chain.getValue(1); 9548 9549 // Mark the end of the call, which is glued to the call itself. 9550 Chain = DAG.getCALLSEQ_END(Chain, 9551 DAG.getConstant(NumBytes, DL, PtrVT, true), 9552 DAG.getConstant(0, DL, PtrVT, true), 9553 Glue, DL); 9554 Glue = Chain.getValue(1); 9555 9556 // Assign locations to each value returned by this call. 9557 SmallVector<CCValAssign, 16> RVLocs; 9558 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 9559 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 9560 9561 // Copy all of the result registers out of their specified physreg. 9562 for (auto &VA : RVLocs) { 9563 // Copy the value out 9564 SDValue RetValue = 9565 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 9566 // Glue the RetValue to the end of the call sequence 9567 Chain = RetValue.getValue(1); 9568 Glue = RetValue.getValue(2); 9569 9570 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9571 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 9572 SDValue RetValue2 = 9573 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 9574 Chain = RetValue2.getValue(1); 9575 Glue = RetValue2.getValue(2); 9576 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 9577 RetValue2); 9578 } 9579 9580 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 9581 9582 InVals.push_back(RetValue); 9583 } 9584 9585 return Chain; 9586 } 9587 9588 bool RISCVTargetLowering::CanLowerReturn( 9589 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 9590 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 9591 SmallVector<CCValAssign, 16> RVLocs; 9592 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 9593 9594 Optional<unsigned> FirstMaskArgument; 9595 if (Subtarget.hasVInstructions()) 9596 FirstMaskArgument = preAssignMask(Outs); 9597 9598 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9599 MVT VT = Outs[i].VT; 9600 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9601 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9602 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 9603 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 9604 *this, FirstMaskArgument)) 9605 return false; 9606 } 9607 return true; 9608 } 9609 9610 SDValue 9611 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 9612 bool IsVarArg, 9613 const SmallVectorImpl<ISD::OutputArg> &Outs, 9614 const SmallVectorImpl<SDValue> &OutVals, 9615 const SDLoc &DL, SelectionDAG &DAG) const { 9616 const MachineFunction &MF = DAG.getMachineFunction(); 9617 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9618 9619 // Stores the assignment of the return value to a location. 9620 SmallVector<CCValAssign, 16> RVLocs; 9621 9622 // Info about the registers and stack slot. 9623 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 9624 *DAG.getContext()); 9625 9626 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 9627 nullptr, CC_RISCV); 9628 9629 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 9630 report_fatal_error("GHC functions return void only"); 9631 9632 SDValue Glue; 9633 SmallVector<SDValue, 4> RetOps(1, Chain); 9634 9635 // Copy the result values into the output registers. 9636 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 9637 SDValue Val = OutVals[i]; 9638 CCValAssign &VA = RVLocs[i]; 9639 assert(VA.isRegLoc() && "Can only return in registers!"); 9640 9641 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9642 // Handle returning f64 on RV32D with a soft float ABI. 9643 assert(VA.isRegLoc() && "Expected return via registers"); 9644 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 9645 DAG.getVTList(MVT::i32, MVT::i32), Val); 9646 SDValue Lo = SplitF64.getValue(0); 9647 SDValue Hi = SplitF64.getValue(1); 9648 Register RegLo = VA.getLocReg(); 9649 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9650 Register RegHi = RegLo + 1; 9651 9652 if (STI.isRegisterReservedByUser(RegLo) || 9653 STI.isRegisterReservedByUser(RegHi)) 9654 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9655 MF.getFunction(), 9656 "Return value register required, but has been reserved."}); 9657 9658 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 9659 Glue = Chain.getValue(1); 9660 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 9661 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 9662 Glue = Chain.getValue(1); 9663 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 9664 } else { 9665 // Handle a 'normal' return. 9666 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 9667 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 9668 9669 if (STI.isRegisterReservedByUser(VA.getLocReg())) 9670 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9671 MF.getFunction(), 9672 "Return value register required, but has been reserved."}); 9673 9674 // Guarantee that all emitted copies are stuck together. 9675 Glue = Chain.getValue(1); 9676 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 9677 } 9678 } 9679 9680 RetOps[0] = Chain; // Update chain. 9681 9682 // Add the glue node if we have it. 9683 if (Glue.getNode()) { 9684 RetOps.push_back(Glue); 9685 } 9686 9687 unsigned RetOpc = RISCVISD::RET_FLAG; 9688 // Interrupt service routines use different return instructions. 9689 const Function &Func = DAG.getMachineFunction().getFunction(); 9690 if (Func.hasFnAttribute("interrupt")) { 9691 if (!Func.getReturnType()->isVoidTy()) 9692 report_fatal_error( 9693 "Functions with the interrupt attribute must have void return type!"); 9694 9695 MachineFunction &MF = DAG.getMachineFunction(); 9696 StringRef Kind = 9697 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9698 9699 if (Kind == "user") 9700 RetOpc = RISCVISD::URET_FLAG; 9701 else if (Kind == "supervisor") 9702 RetOpc = RISCVISD::SRET_FLAG; 9703 else 9704 RetOpc = RISCVISD::MRET_FLAG; 9705 } 9706 9707 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 9708 } 9709 9710 void RISCVTargetLowering::validateCCReservedRegs( 9711 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 9712 MachineFunction &MF) const { 9713 const Function &F = MF.getFunction(); 9714 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9715 9716 if (llvm::any_of(Regs, [&STI](auto Reg) { 9717 return STI.isRegisterReservedByUser(Reg.first); 9718 })) 9719 F.getContext().diagnose(DiagnosticInfoUnsupported{ 9720 F, "Argument register required, but has been reserved."}); 9721 } 9722 9723 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 9724 return CI->isTailCall(); 9725 } 9726 9727 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 9728 #define NODE_NAME_CASE(NODE) \ 9729 case RISCVISD::NODE: \ 9730 return "RISCVISD::" #NODE; 9731 // clang-format off 9732 switch ((RISCVISD::NodeType)Opcode) { 9733 case RISCVISD::FIRST_NUMBER: 9734 break; 9735 NODE_NAME_CASE(RET_FLAG) 9736 NODE_NAME_CASE(URET_FLAG) 9737 NODE_NAME_CASE(SRET_FLAG) 9738 NODE_NAME_CASE(MRET_FLAG) 9739 NODE_NAME_CASE(CALL) 9740 NODE_NAME_CASE(SELECT_CC) 9741 NODE_NAME_CASE(BR_CC) 9742 NODE_NAME_CASE(BuildPairF64) 9743 NODE_NAME_CASE(SplitF64) 9744 NODE_NAME_CASE(TAIL) 9745 NODE_NAME_CASE(MULHSU) 9746 NODE_NAME_CASE(SLLW) 9747 NODE_NAME_CASE(SRAW) 9748 NODE_NAME_CASE(SRLW) 9749 NODE_NAME_CASE(DIVW) 9750 NODE_NAME_CASE(DIVUW) 9751 NODE_NAME_CASE(REMUW) 9752 NODE_NAME_CASE(ROLW) 9753 NODE_NAME_CASE(RORW) 9754 NODE_NAME_CASE(CLZW) 9755 NODE_NAME_CASE(CTZW) 9756 NODE_NAME_CASE(FSLW) 9757 NODE_NAME_CASE(FSRW) 9758 NODE_NAME_CASE(FSL) 9759 NODE_NAME_CASE(FSR) 9760 NODE_NAME_CASE(FMV_H_X) 9761 NODE_NAME_CASE(FMV_X_ANYEXTH) 9762 NODE_NAME_CASE(FMV_W_X_RV64) 9763 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 9764 NODE_NAME_CASE(FCVT_X) 9765 NODE_NAME_CASE(FCVT_XU) 9766 NODE_NAME_CASE(FCVT_W_RV64) 9767 NODE_NAME_CASE(FCVT_WU_RV64) 9768 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 9769 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 9770 NODE_NAME_CASE(READ_CYCLE_WIDE) 9771 NODE_NAME_CASE(GREV) 9772 NODE_NAME_CASE(GREVW) 9773 NODE_NAME_CASE(GORC) 9774 NODE_NAME_CASE(GORCW) 9775 NODE_NAME_CASE(SHFL) 9776 NODE_NAME_CASE(SHFLW) 9777 NODE_NAME_CASE(UNSHFL) 9778 NODE_NAME_CASE(UNSHFLW) 9779 NODE_NAME_CASE(BFP) 9780 NODE_NAME_CASE(BFPW) 9781 NODE_NAME_CASE(BCOMPRESS) 9782 NODE_NAME_CASE(BCOMPRESSW) 9783 NODE_NAME_CASE(BDECOMPRESS) 9784 NODE_NAME_CASE(BDECOMPRESSW) 9785 NODE_NAME_CASE(VMV_V_X_VL) 9786 NODE_NAME_CASE(VFMV_V_F_VL) 9787 NODE_NAME_CASE(VMV_X_S) 9788 NODE_NAME_CASE(VMV_S_X_VL) 9789 NODE_NAME_CASE(VFMV_S_F_VL) 9790 NODE_NAME_CASE(SPLAT_VECTOR_I64) 9791 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 9792 NODE_NAME_CASE(READ_VLENB) 9793 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 9794 NODE_NAME_CASE(VSLIDEUP_VL) 9795 NODE_NAME_CASE(VSLIDE1UP_VL) 9796 NODE_NAME_CASE(VSLIDEDOWN_VL) 9797 NODE_NAME_CASE(VSLIDE1DOWN_VL) 9798 NODE_NAME_CASE(VID_VL) 9799 NODE_NAME_CASE(VFNCVT_ROD_VL) 9800 NODE_NAME_CASE(VECREDUCE_ADD_VL) 9801 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 9802 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 9803 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 9804 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 9805 NODE_NAME_CASE(VECREDUCE_AND_VL) 9806 NODE_NAME_CASE(VECREDUCE_OR_VL) 9807 NODE_NAME_CASE(VECREDUCE_XOR_VL) 9808 NODE_NAME_CASE(VECREDUCE_FADD_VL) 9809 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 9810 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 9811 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 9812 NODE_NAME_CASE(ADD_VL) 9813 NODE_NAME_CASE(AND_VL) 9814 NODE_NAME_CASE(MUL_VL) 9815 NODE_NAME_CASE(OR_VL) 9816 NODE_NAME_CASE(SDIV_VL) 9817 NODE_NAME_CASE(SHL_VL) 9818 NODE_NAME_CASE(SREM_VL) 9819 NODE_NAME_CASE(SRA_VL) 9820 NODE_NAME_CASE(SRL_VL) 9821 NODE_NAME_CASE(SUB_VL) 9822 NODE_NAME_CASE(UDIV_VL) 9823 NODE_NAME_CASE(UREM_VL) 9824 NODE_NAME_CASE(XOR_VL) 9825 NODE_NAME_CASE(SADDSAT_VL) 9826 NODE_NAME_CASE(UADDSAT_VL) 9827 NODE_NAME_CASE(SSUBSAT_VL) 9828 NODE_NAME_CASE(USUBSAT_VL) 9829 NODE_NAME_CASE(FADD_VL) 9830 NODE_NAME_CASE(FSUB_VL) 9831 NODE_NAME_CASE(FMUL_VL) 9832 NODE_NAME_CASE(FDIV_VL) 9833 NODE_NAME_CASE(FNEG_VL) 9834 NODE_NAME_CASE(FABS_VL) 9835 NODE_NAME_CASE(FSQRT_VL) 9836 NODE_NAME_CASE(FMA_VL) 9837 NODE_NAME_CASE(FCOPYSIGN_VL) 9838 NODE_NAME_CASE(SMIN_VL) 9839 NODE_NAME_CASE(SMAX_VL) 9840 NODE_NAME_CASE(UMIN_VL) 9841 NODE_NAME_CASE(UMAX_VL) 9842 NODE_NAME_CASE(FMINNUM_VL) 9843 NODE_NAME_CASE(FMAXNUM_VL) 9844 NODE_NAME_CASE(MULHS_VL) 9845 NODE_NAME_CASE(MULHU_VL) 9846 NODE_NAME_CASE(FP_TO_SINT_VL) 9847 NODE_NAME_CASE(FP_TO_UINT_VL) 9848 NODE_NAME_CASE(SINT_TO_FP_VL) 9849 NODE_NAME_CASE(UINT_TO_FP_VL) 9850 NODE_NAME_CASE(FP_EXTEND_VL) 9851 NODE_NAME_CASE(FP_ROUND_VL) 9852 NODE_NAME_CASE(VWMUL_VL) 9853 NODE_NAME_CASE(VWMULU_VL) 9854 NODE_NAME_CASE(SETCC_VL) 9855 NODE_NAME_CASE(VSELECT_VL) 9856 NODE_NAME_CASE(VMAND_VL) 9857 NODE_NAME_CASE(VMOR_VL) 9858 NODE_NAME_CASE(VMXOR_VL) 9859 NODE_NAME_CASE(VMCLR_VL) 9860 NODE_NAME_CASE(VMSET_VL) 9861 NODE_NAME_CASE(VRGATHER_VX_VL) 9862 NODE_NAME_CASE(VRGATHER_VV_VL) 9863 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 9864 NODE_NAME_CASE(VSEXT_VL) 9865 NODE_NAME_CASE(VZEXT_VL) 9866 NODE_NAME_CASE(VCPOP_VL) 9867 NODE_NAME_CASE(VLE_VL) 9868 NODE_NAME_CASE(VSE_VL) 9869 NODE_NAME_CASE(READ_CSR) 9870 NODE_NAME_CASE(WRITE_CSR) 9871 NODE_NAME_CASE(SWAP_CSR) 9872 } 9873 // clang-format on 9874 return nullptr; 9875 #undef NODE_NAME_CASE 9876 } 9877 9878 /// getConstraintType - Given a constraint letter, return the type of 9879 /// constraint it is for this target. 9880 RISCVTargetLowering::ConstraintType 9881 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 9882 if (Constraint.size() == 1) { 9883 switch (Constraint[0]) { 9884 default: 9885 break; 9886 case 'f': 9887 return C_RegisterClass; 9888 case 'I': 9889 case 'J': 9890 case 'K': 9891 return C_Immediate; 9892 case 'A': 9893 return C_Memory; 9894 case 'S': // A symbolic address 9895 return C_Other; 9896 } 9897 } else { 9898 if (Constraint == "vr" || Constraint == "vm") 9899 return C_RegisterClass; 9900 } 9901 return TargetLowering::getConstraintType(Constraint); 9902 } 9903 9904 std::pair<unsigned, const TargetRegisterClass *> 9905 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 9906 StringRef Constraint, 9907 MVT VT) const { 9908 // First, see if this is a constraint that directly corresponds to a 9909 // RISCV register class. 9910 if (Constraint.size() == 1) { 9911 switch (Constraint[0]) { 9912 case 'r': 9913 // TODO: Support fixed vectors up to XLen for P extension? 9914 if (VT.isVector()) 9915 break; 9916 return std::make_pair(0U, &RISCV::GPRRegClass); 9917 case 'f': 9918 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 9919 return std::make_pair(0U, &RISCV::FPR16RegClass); 9920 if (Subtarget.hasStdExtF() && VT == MVT::f32) 9921 return std::make_pair(0U, &RISCV::FPR32RegClass); 9922 if (Subtarget.hasStdExtD() && VT == MVT::f64) 9923 return std::make_pair(0U, &RISCV::FPR64RegClass); 9924 break; 9925 default: 9926 break; 9927 } 9928 } else if (Constraint == "vr") { 9929 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 9930 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9931 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 9932 return std::make_pair(0U, RC); 9933 } 9934 } else if (Constraint == "vm") { 9935 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 9936 return std::make_pair(0U, &RISCV::VMV0RegClass); 9937 } 9938 9939 // Clang will correctly decode the usage of register name aliases into their 9940 // official names. However, other frontends like `rustc` do not. This allows 9941 // users of these frontends to use the ABI names for registers in LLVM-style 9942 // register constraints. 9943 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 9944 .Case("{zero}", RISCV::X0) 9945 .Case("{ra}", RISCV::X1) 9946 .Case("{sp}", RISCV::X2) 9947 .Case("{gp}", RISCV::X3) 9948 .Case("{tp}", RISCV::X4) 9949 .Case("{t0}", RISCV::X5) 9950 .Case("{t1}", RISCV::X6) 9951 .Case("{t2}", RISCV::X7) 9952 .Cases("{s0}", "{fp}", RISCV::X8) 9953 .Case("{s1}", RISCV::X9) 9954 .Case("{a0}", RISCV::X10) 9955 .Case("{a1}", RISCV::X11) 9956 .Case("{a2}", RISCV::X12) 9957 .Case("{a3}", RISCV::X13) 9958 .Case("{a4}", RISCV::X14) 9959 .Case("{a5}", RISCV::X15) 9960 .Case("{a6}", RISCV::X16) 9961 .Case("{a7}", RISCV::X17) 9962 .Case("{s2}", RISCV::X18) 9963 .Case("{s3}", RISCV::X19) 9964 .Case("{s4}", RISCV::X20) 9965 .Case("{s5}", RISCV::X21) 9966 .Case("{s6}", RISCV::X22) 9967 .Case("{s7}", RISCV::X23) 9968 .Case("{s8}", RISCV::X24) 9969 .Case("{s9}", RISCV::X25) 9970 .Case("{s10}", RISCV::X26) 9971 .Case("{s11}", RISCV::X27) 9972 .Case("{t3}", RISCV::X28) 9973 .Case("{t4}", RISCV::X29) 9974 .Case("{t5}", RISCV::X30) 9975 .Case("{t6}", RISCV::X31) 9976 .Default(RISCV::NoRegister); 9977 if (XRegFromAlias != RISCV::NoRegister) 9978 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 9979 9980 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 9981 // TableGen record rather than the AsmName to choose registers for InlineAsm 9982 // constraints, plus we want to match those names to the widest floating point 9983 // register type available, manually select floating point registers here. 9984 // 9985 // The second case is the ABI name of the register, so that frontends can also 9986 // use the ABI names in register constraint lists. 9987 if (Subtarget.hasStdExtF()) { 9988 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 9989 .Cases("{f0}", "{ft0}", RISCV::F0_F) 9990 .Cases("{f1}", "{ft1}", RISCV::F1_F) 9991 .Cases("{f2}", "{ft2}", RISCV::F2_F) 9992 .Cases("{f3}", "{ft3}", RISCV::F3_F) 9993 .Cases("{f4}", "{ft4}", RISCV::F4_F) 9994 .Cases("{f5}", "{ft5}", RISCV::F5_F) 9995 .Cases("{f6}", "{ft6}", RISCV::F6_F) 9996 .Cases("{f7}", "{ft7}", RISCV::F7_F) 9997 .Cases("{f8}", "{fs0}", RISCV::F8_F) 9998 .Cases("{f9}", "{fs1}", RISCV::F9_F) 9999 .Cases("{f10}", "{fa0}", RISCV::F10_F) 10000 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10001 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10002 .Cases("{f13}", "{fa3}", RISCV::F13_F) 10003 .Cases("{f14}", "{fa4}", RISCV::F14_F) 10004 .Cases("{f15}", "{fa5}", RISCV::F15_F) 10005 .Cases("{f16}", "{fa6}", RISCV::F16_F) 10006 .Cases("{f17}", "{fa7}", RISCV::F17_F) 10007 .Cases("{f18}", "{fs2}", RISCV::F18_F) 10008 .Cases("{f19}", "{fs3}", RISCV::F19_F) 10009 .Cases("{f20}", "{fs4}", RISCV::F20_F) 10010 .Cases("{f21}", "{fs5}", RISCV::F21_F) 10011 .Cases("{f22}", "{fs6}", RISCV::F22_F) 10012 .Cases("{f23}", "{fs7}", RISCV::F23_F) 10013 .Cases("{f24}", "{fs8}", RISCV::F24_F) 10014 .Cases("{f25}", "{fs9}", RISCV::F25_F) 10015 .Cases("{f26}", "{fs10}", RISCV::F26_F) 10016 .Cases("{f27}", "{fs11}", RISCV::F27_F) 10017 .Cases("{f28}", "{ft8}", RISCV::F28_F) 10018 .Cases("{f29}", "{ft9}", RISCV::F29_F) 10019 .Cases("{f30}", "{ft10}", RISCV::F30_F) 10020 .Cases("{f31}", "{ft11}", RISCV::F31_F) 10021 .Default(RISCV::NoRegister); 10022 if (FReg != RISCV::NoRegister) { 10023 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 10024 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 10025 unsigned RegNo = FReg - RISCV::F0_F; 10026 unsigned DReg = RISCV::F0_D + RegNo; 10027 return std::make_pair(DReg, &RISCV::FPR64RegClass); 10028 } 10029 if (VT == MVT::f32 || VT == MVT::Other) 10030 return std::make_pair(FReg, &RISCV::FPR32RegClass); 10031 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 10032 unsigned RegNo = FReg - RISCV::F0_F; 10033 unsigned HReg = RISCV::F0_H + RegNo; 10034 return std::make_pair(HReg, &RISCV::FPR16RegClass); 10035 } 10036 } 10037 } 10038 10039 if (Subtarget.hasVInstructions()) { 10040 Register VReg = StringSwitch<Register>(Constraint.lower()) 10041 .Case("{v0}", RISCV::V0) 10042 .Case("{v1}", RISCV::V1) 10043 .Case("{v2}", RISCV::V2) 10044 .Case("{v3}", RISCV::V3) 10045 .Case("{v4}", RISCV::V4) 10046 .Case("{v5}", RISCV::V5) 10047 .Case("{v6}", RISCV::V6) 10048 .Case("{v7}", RISCV::V7) 10049 .Case("{v8}", RISCV::V8) 10050 .Case("{v9}", RISCV::V9) 10051 .Case("{v10}", RISCV::V10) 10052 .Case("{v11}", RISCV::V11) 10053 .Case("{v12}", RISCV::V12) 10054 .Case("{v13}", RISCV::V13) 10055 .Case("{v14}", RISCV::V14) 10056 .Case("{v15}", RISCV::V15) 10057 .Case("{v16}", RISCV::V16) 10058 .Case("{v17}", RISCV::V17) 10059 .Case("{v18}", RISCV::V18) 10060 .Case("{v19}", RISCV::V19) 10061 .Case("{v20}", RISCV::V20) 10062 .Case("{v21}", RISCV::V21) 10063 .Case("{v22}", RISCV::V22) 10064 .Case("{v23}", RISCV::V23) 10065 .Case("{v24}", RISCV::V24) 10066 .Case("{v25}", RISCV::V25) 10067 .Case("{v26}", RISCV::V26) 10068 .Case("{v27}", RISCV::V27) 10069 .Case("{v28}", RISCV::V28) 10070 .Case("{v29}", RISCV::V29) 10071 .Case("{v30}", RISCV::V30) 10072 .Case("{v31}", RISCV::V31) 10073 .Default(RISCV::NoRegister); 10074 if (VReg != RISCV::NoRegister) { 10075 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 10076 return std::make_pair(VReg, &RISCV::VMRegClass); 10077 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 10078 return std::make_pair(VReg, &RISCV::VRRegClass); 10079 for (const auto *RC : 10080 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10081 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 10082 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 10083 return std::make_pair(VReg, RC); 10084 } 10085 } 10086 } 10087 } 10088 10089 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10090 } 10091 10092 unsigned 10093 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 10094 // Currently only support length 1 constraints. 10095 if (ConstraintCode.size() == 1) { 10096 switch (ConstraintCode[0]) { 10097 case 'A': 10098 return InlineAsm::Constraint_A; 10099 default: 10100 break; 10101 } 10102 } 10103 10104 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 10105 } 10106 10107 void RISCVTargetLowering::LowerAsmOperandForConstraint( 10108 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 10109 SelectionDAG &DAG) const { 10110 // Currently only support length 1 constraints. 10111 if (Constraint.length() == 1) { 10112 switch (Constraint[0]) { 10113 case 'I': 10114 // Validate & create a 12-bit signed immediate operand. 10115 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10116 uint64_t CVal = C->getSExtValue(); 10117 if (isInt<12>(CVal)) 10118 Ops.push_back( 10119 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10120 } 10121 return; 10122 case 'J': 10123 // Validate & create an integer zero operand. 10124 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 10125 if (C->getZExtValue() == 0) 10126 Ops.push_back( 10127 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 10128 return; 10129 case 'K': 10130 // Validate & create a 5-bit unsigned immediate operand. 10131 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10132 uint64_t CVal = C->getZExtValue(); 10133 if (isUInt<5>(CVal)) 10134 Ops.push_back( 10135 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10136 } 10137 return; 10138 case 'S': 10139 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 10140 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 10141 GA->getValueType(0))); 10142 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 10143 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 10144 BA->getValueType(0))); 10145 } 10146 return; 10147 default: 10148 break; 10149 } 10150 } 10151 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 10152 } 10153 10154 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 10155 Instruction *Inst, 10156 AtomicOrdering Ord) const { 10157 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 10158 return Builder.CreateFence(Ord); 10159 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 10160 return Builder.CreateFence(AtomicOrdering::Release); 10161 return nullptr; 10162 } 10163 10164 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 10165 Instruction *Inst, 10166 AtomicOrdering Ord) const { 10167 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 10168 return Builder.CreateFence(AtomicOrdering::Acquire); 10169 return nullptr; 10170 } 10171 10172 TargetLowering::AtomicExpansionKind 10173 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10174 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 10175 // point operations can't be used in an lr/sc sequence without breaking the 10176 // forward-progress guarantee. 10177 if (AI->isFloatingPointOperation()) 10178 return AtomicExpansionKind::CmpXChg; 10179 10180 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10181 if (Size == 8 || Size == 16) 10182 return AtomicExpansionKind::MaskedIntrinsic; 10183 return AtomicExpansionKind::None; 10184 } 10185 10186 static Intrinsic::ID 10187 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 10188 if (XLen == 32) { 10189 switch (BinOp) { 10190 default: 10191 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10192 case AtomicRMWInst::Xchg: 10193 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 10194 case AtomicRMWInst::Add: 10195 return Intrinsic::riscv_masked_atomicrmw_add_i32; 10196 case AtomicRMWInst::Sub: 10197 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 10198 case AtomicRMWInst::Nand: 10199 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 10200 case AtomicRMWInst::Max: 10201 return Intrinsic::riscv_masked_atomicrmw_max_i32; 10202 case AtomicRMWInst::Min: 10203 return Intrinsic::riscv_masked_atomicrmw_min_i32; 10204 case AtomicRMWInst::UMax: 10205 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 10206 case AtomicRMWInst::UMin: 10207 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 10208 } 10209 } 10210 10211 if (XLen == 64) { 10212 switch (BinOp) { 10213 default: 10214 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10215 case AtomicRMWInst::Xchg: 10216 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 10217 case AtomicRMWInst::Add: 10218 return Intrinsic::riscv_masked_atomicrmw_add_i64; 10219 case AtomicRMWInst::Sub: 10220 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 10221 case AtomicRMWInst::Nand: 10222 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 10223 case AtomicRMWInst::Max: 10224 return Intrinsic::riscv_masked_atomicrmw_max_i64; 10225 case AtomicRMWInst::Min: 10226 return Intrinsic::riscv_masked_atomicrmw_min_i64; 10227 case AtomicRMWInst::UMax: 10228 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 10229 case AtomicRMWInst::UMin: 10230 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 10231 } 10232 } 10233 10234 llvm_unreachable("Unexpected XLen\n"); 10235 } 10236 10237 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 10238 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 10239 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 10240 unsigned XLen = Subtarget.getXLen(); 10241 Value *Ordering = 10242 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 10243 Type *Tys[] = {AlignedAddr->getType()}; 10244 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 10245 AI->getModule(), 10246 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 10247 10248 if (XLen == 64) { 10249 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 10250 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10251 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 10252 } 10253 10254 Value *Result; 10255 10256 // Must pass the shift amount needed to sign extend the loaded value prior 10257 // to performing a signed comparison for min/max. ShiftAmt is the number of 10258 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 10259 // is the number of bits to left+right shift the value in order to 10260 // sign-extend. 10261 if (AI->getOperation() == AtomicRMWInst::Min || 10262 AI->getOperation() == AtomicRMWInst::Max) { 10263 const DataLayout &DL = AI->getModule()->getDataLayout(); 10264 unsigned ValWidth = 10265 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 10266 Value *SextShamt = 10267 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 10268 Result = Builder.CreateCall(LrwOpScwLoop, 10269 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 10270 } else { 10271 Result = 10272 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 10273 } 10274 10275 if (XLen == 64) 10276 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10277 return Result; 10278 } 10279 10280 TargetLowering::AtomicExpansionKind 10281 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 10282 AtomicCmpXchgInst *CI) const { 10283 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 10284 if (Size == 8 || Size == 16) 10285 return AtomicExpansionKind::MaskedIntrinsic; 10286 return AtomicExpansionKind::None; 10287 } 10288 10289 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 10290 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 10291 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 10292 unsigned XLen = Subtarget.getXLen(); 10293 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 10294 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 10295 if (XLen == 64) { 10296 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 10297 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 10298 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10299 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 10300 } 10301 Type *Tys[] = {AlignedAddr->getType()}; 10302 Function *MaskedCmpXchg = 10303 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 10304 Value *Result = Builder.CreateCall( 10305 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 10306 if (XLen == 64) 10307 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10308 return Result; 10309 } 10310 10311 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 10312 return false; 10313 } 10314 10315 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 10316 EVT VT) const { 10317 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 10318 return false; 10319 10320 switch (FPVT.getSimpleVT().SimpleTy) { 10321 case MVT::f16: 10322 return Subtarget.hasStdExtZfh(); 10323 case MVT::f32: 10324 return Subtarget.hasStdExtF(); 10325 case MVT::f64: 10326 return Subtarget.hasStdExtD(); 10327 default: 10328 return false; 10329 } 10330 } 10331 10332 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 10333 // If we are using the small code model, we can reduce size of jump table 10334 // entry to 4 bytes. 10335 if (Subtarget.is64Bit() && !isPositionIndependent() && 10336 getTargetMachine().getCodeModel() == CodeModel::Small) { 10337 return MachineJumpTableInfo::EK_Custom32; 10338 } 10339 return TargetLowering::getJumpTableEncoding(); 10340 } 10341 10342 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 10343 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 10344 unsigned uid, MCContext &Ctx) const { 10345 assert(Subtarget.is64Bit() && !isPositionIndependent() && 10346 getTargetMachine().getCodeModel() == CodeModel::Small); 10347 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 10348 } 10349 10350 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 10351 EVT VT) const { 10352 VT = VT.getScalarType(); 10353 10354 if (!VT.isSimple()) 10355 return false; 10356 10357 switch (VT.getSimpleVT().SimpleTy) { 10358 case MVT::f16: 10359 return Subtarget.hasStdExtZfh(); 10360 case MVT::f32: 10361 return Subtarget.hasStdExtF(); 10362 case MVT::f64: 10363 return Subtarget.hasStdExtD(); 10364 default: 10365 break; 10366 } 10367 10368 return false; 10369 } 10370 10371 Register RISCVTargetLowering::getExceptionPointerRegister( 10372 const Constant *PersonalityFn) const { 10373 return RISCV::X10; 10374 } 10375 10376 Register RISCVTargetLowering::getExceptionSelectorRegister( 10377 const Constant *PersonalityFn) const { 10378 return RISCV::X11; 10379 } 10380 10381 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 10382 // Return false to suppress the unnecessary extensions if the LibCall 10383 // arguments or return value is f32 type for LP64 ABI. 10384 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 10385 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 10386 return false; 10387 10388 return true; 10389 } 10390 10391 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 10392 if (Subtarget.is64Bit() && Type == MVT::i32) 10393 return true; 10394 10395 return IsSigned; 10396 } 10397 10398 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 10399 SDValue C) const { 10400 // Check integral scalar types. 10401 if (VT.isScalarInteger()) { 10402 // Omit the optimization if the sub target has the M extension and the data 10403 // size exceeds XLen. 10404 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 10405 return false; 10406 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 10407 // Break the MUL to a SLLI and an ADD/SUB. 10408 const APInt &Imm = ConstNode->getAPIntValue(); 10409 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 10410 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 10411 return true; 10412 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 10413 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 10414 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 10415 (Imm - 8).isPowerOf2())) 10416 return true; 10417 // Omit the following optimization if the sub target has the M extension 10418 // and the data size >= XLen. 10419 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 10420 return false; 10421 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 10422 // a pair of LUI/ADDI. 10423 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 10424 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 10425 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 10426 (1 - ImmS).isPowerOf2()) 10427 return true; 10428 } 10429 } 10430 } 10431 10432 return false; 10433 } 10434 10435 bool RISCVTargetLowering::isMulAddWithConstProfitable( 10436 const SDValue &AddNode, const SDValue &ConstNode) const { 10437 // Let the DAGCombiner decide for vectors. 10438 EVT VT = AddNode.getValueType(); 10439 if (VT.isVector()) 10440 return true; 10441 10442 // Let the DAGCombiner decide for larger types. 10443 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 10444 return true; 10445 10446 // It is worse if c1 is simm12 while c1*c2 is not. 10447 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 10448 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 10449 const APInt &C1 = C1Node->getAPIntValue(); 10450 const APInt &C2 = C2Node->getAPIntValue(); 10451 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 10452 return false; 10453 10454 // Default to true and let the DAGCombiner decide. 10455 return true; 10456 } 10457 10458 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 10459 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 10460 bool *Fast) const { 10461 if (!VT.isVector()) 10462 return false; 10463 10464 EVT ElemVT = VT.getVectorElementType(); 10465 if (Alignment >= ElemVT.getStoreSize()) { 10466 if (Fast) 10467 *Fast = true; 10468 return true; 10469 } 10470 10471 return false; 10472 } 10473 10474 bool RISCVTargetLowering::splitValueIntoRegisterParts( 10475 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 10476 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 10477 bool IsABIRegCopy = CC.hasValue(); 10478 EVT ValueVT = Val.getValueType(); 10479 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10480 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 10481 // and cast to f32. 10482 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 10483 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 10484 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 10485 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 10486 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 10487 Parts[0] = Val; 10488 return true; 10489 } 10490 10491 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10492 LLVMContext &Context = *DAG.getContext(); 10493 EVT ValueEltVT = ValueVT.getVectorElementType(); 10494 EVT PartEltVT = PartVT.getVectorElementType(); 10495 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10496 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10497 if (PartVTBitSize % ValueVTBitSize == 0) { 10498 assert(PartVTBitSize >= ValueVTBitSize); 10499 // If the element types are different, bitcast to the same element type of 10500 // PartVT first. 10501 // Give an example here, we want copy a <vscale x 1 x i8> value to 10502 // <vscale x 4 x i16>. 10503 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 10504 // subvector, then we can bitcast to <vscale x 4 x i16>. 10505 if (ValueEltVT != PartEltVT) { 10506 if (PartVTBitSize > ValueVTBitSize) { 10507 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 10508 assert(Count != 0 && "The number of element should not be zero."); 10509 EVT SameEltTypeVT = 10510 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 10511 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 10512 DAG.getUNDEF(SameEltTypeVT), Val, 10513 DAG.getVectorIdxConstant(0, DL)); 10514 } 10515 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 10516 } else { 10517 Val = 10518 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 10519 Val, DAG.getVectorIdxConstant(0, DL)); 10520 } 10521 Parts[0] = Val; 10522 return true; 10523 } 10524 } 10525 return false; 10526 } 10527 10528 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 10529 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 10530 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 10531 bool IsABIRegCopy = CC.hasValue(); 10532 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10533 SDValue Val = Parts[0]; 10534 10535 // Cast the f32 to i32, truncate to i16, and cast back to f16. 10536 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 10537 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 10538 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 10539 return Val; 10540 } 10541 10542 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10543 LLVMContext &Context = *DAG.getContext(); 10544 SDValue Val = Parts[0]; 10545 EVT ValueEltVT = ValueVT.getVectorElementType(); 10546 EVT PartEltVT = PartVT.getVectorElementType(); 10547 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10548 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10549 if (PartVTBitSize % ValueVTBitSize == 0) { 10550 assert(PartVTBitSize >= ValueVTBitSize); 10551 EVT SameEltTypeVT = ValueVT; 10552 // If the element types are different, convert it to the same element type 10553 // of PartVT. 10554 // Give an example here, we want copy a <vscale x 1 x i8> value from 10555 // <vscale x 4 x i16>. 10556 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 10557 // then we can extract <vscale x 1 x i8>. 10558 if (ValueEltVT != PartEltVT) { 10559 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 10560 assert(Count != 0 && "The number of element should not be zero."); 10561 SameEltTypeVT = 10562 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 10563 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 10564 } 10565 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 10566 DAG.getVectorIdxConstant(0, DL)); 10567 return Val; 10568 } 10569 } 10570 return SDValue(); 10571 } 10572 10573 SDValue 10574 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 10575 SelectionDAG &DAG, 10576 SmallVectorImpl<SDNode *> &Created) const { 10577 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 10578 if (isIntDivCheap(N->getValueType(0), Attr)) 10579 return SDValue(N, 0); // Lower SDIV as SDIV 10580 10581 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 10582 "Unexpected divisor!"); 10583 10584 // Conditional move is needed, so do the transformation iff Zbt is enabled. 10585 if (!Subtarget.hasStdExtZbt()) 10586 return SDValue(); 10587 10588 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 10589 // Besides, more critical path instructions will be generated when dividing 10590 // by 2. So we keep using the original DAGs for these cases. 10591 unsigned Lg2 = Divisor.countTrailingZeros(); 10592 if (Lg2 == 1 || Lg2 >= 12) 10593 return SDValue(); 10594 10595 // fold (sdiv X, pow2) 10596 EVT VT = N->getValueType(0); 10597 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 10598 return SDValue(); 10599 10600 SDLoc DL(N); 10601 SDValue N0 = N->getOperand(0); 10602 SDValue Zero = DAG.getConstant(0, DL, VT); 10603 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 10604 10605 // Add (N0 < 0) ? Pow2 - 1 : 0; 10606 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 10607 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 10608 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 10609 10610 Created.push_back(Cmp.getNode()); 10611 Created.push_back(Add.getNode()); 10612 Created.push_back(Sel.getNode()); 10613 10614 // Divide by pow2. 10615 SDValue SRA = 10616 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 10617 10618 // If we're dividing by a positive value, we're done. Otherwise, we must 10619 // negate the result. 10620 if (Divisor.isNonNegative()) 10621 return SRA; 10622 10623 Created.push_back(SRA.getNode()); 10624 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 10625 } 10626 10627 #define GET_REGISTER_MATCHER 10628 #include "RISCVGenAsmMatcher.inc" 10629 10630 Register 10631 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 10632 const MachineFunction &MF) const { 10633 Register Reg = MatchRegisterAltName(RegName); 10634 if (Reg == RISCV::NoRegister) 10635 Reg = MatchRegisterName(RegName); 10636 if (Reg == RISCV::NoRegister) 10637 report_fatal_error( 10638 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 10639 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 10640 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 10641 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 10642 StringRef(RegName) + "\".")); 10643 return Reg; 10644 } 10645 10646 namespace llvm { 10647 namespace RISCVVIntrinsicsTable { 10648 10649 #define GET_RISCVVIntrinsicsTable_IMPL 10650 #include "RISCVGenSearchableTables.inc" 10651 10652 } // namespace RISCVVIntrinsicsTable 10653 10654 } // namespace llvm 10655