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 "RISCV.h" 16 #include "RISCVMachineFunctionInfo.h" 17 #include "RISCVRegisterInfo.h" 18 #include "RISCVSubtarget.h" 19 #include "RISCVTargetMachine.h" 20 #include "Utils/RISCVMatInt.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/CodeGen/CallingConvLower.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineRegisterInfo.h" 28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 29 #include "llvm/CodeGen/ValueTypes.h" 30 #include "llvm/IR/DiagnosticInfo.h" 31 #include "llvm/IR/DiagnosticPrinter.h" 32 #include "llvm/IR/IntrinsicsRISCV.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/MathExtras.h" 36 #include "llvm/Support/raw_ostream.h" 37 38 using namespace llvm; 39 40 #define DEBUG_TYPE "riscv-lower" 41 42 STATISTIC(NumTailCalls, "Number of tail calls"); 43 44 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 45 const RISCVSubtarget &STI) 46 : TargetLowering(TM), Subtarget(STI) { 47 48 if (Subtarget.isRV32E()) 49 report_fatal_error("Codegen not yet implemented for RV32E"); 50 51 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 52 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 53 54 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 55 !Subtarget.hasStdExtF()) { 56 errs() << "Hard-float 'f' ABI can't be used for a target that " 57 "doesn't support the F instruction set extension (ignoring " 58 "target-abi)\n"; 59 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 60 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 61 !Subtarget.hasStdExtD()) { 62 errs() << "Hard-float 'd' ABI can't be used for a target that " 63 "doesn't support the D instruction set extension (ignoring " 64 "target-abi)\n"; 65 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 66 } 67 68 switch (ABI) { 69 default: 70 report_fatal_error("Don't know how to lower this ABI"); 71 case RISCVABI::ABI_ILP32: 72 case RISCVABI::ABI_ILP32F: 73 case RISCVABI::ABI_ILP32D: 74 case RISCVABI::ABI_LP64: 75 case RISCVABI::ABI_LP64F: 76 case RISCVABI::ABI_LP64D: 77 break; 78 } 79 80 MVT XLenVT = Subtarget.getXLenVT(); 81 82 // Set up the register classes. 83 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 84 85 if (Subtarget.hasStdExtZfh()) 86 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 87 if (Subtarget.hasStdExtF()) 88 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 89 if (Subtarget.hasStdExtD()) 90 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 91 92 if (Subtarget.hasStdExtV()) { 93 addRegisterClass(RISCVVMVTs::vbool64_t, &RISCV::VRRegClass); 94 addRegisterClass(RISCVVMVTs::vbool32_t, &RISCV::VRRegClass); 95 addRegisterClass(RISCVVMVTs::vbool16_t, &RISCV::VRRegClass); 96 addRegisterClass(RISCVVMVTs::vbool8_t, &RISCV::VRRegClass); 97 addRegisterClass(RISCVVMVTs::vbool4_t, &RISCV::VRRegClass); 98 addRegisterClass(RISCVVMVTs::vbool2_t, &RISCV::VRRegClass); 99 addRegisterClass(RISCVVMVTs::vbool1_t, &RISCV::VRRegClass); 100 101 addRegisterClass(RISCVVMVTs::vint8mf8_t, &RISCV::VRRegClass); 102 addRegisterClass(RISCVVMVTs::vint8mf4_t, &RISCV::VRRegClass); 103 addRegisterClass(RISCVVMVTs::vint8mf2_t, &RISCV::VRRegClass); 104 addRegisterClass(RISCVVMVTs::vint8m1_t, &RISCV::VRRegClass); 105 addRegisterClass(RISCVVMVTs::vint8m2_t, &RISCV::VRM2RegClass); 106 addRegisterClass(RISCVVMVTs::vint8m4_t, &RISCV::VRM4RegClass); 107 addRegisterClass(RISCVVMVTs::vint8m8_t, &RISCV::VRM8RegClass); 108 109 addRegisterClass(RISCVVMVTs::vint16mf4_t, &RISCV::VRRegClass); 110 addRegisterClass(RISCVVMVTs::vint16mf2_t, &RISCV::VRRegClass); 111 addRegisterClass(RISCVVMVTs::vint16m1_t, &RISCV::VRRegClass); 112 addRegisterClass(RISCVVMVTs::vint16m2_t, &RISCV::VRM2RegClass); 113 addRegisterClass(RISCVVMVTs::vint16m4_t, &RISCV::VRM4RegClass); 114 addRegisterClass(RISCVVMVTs::vint16m8_t, &RISCV::VRM8RegClass); 115 116 addRegisterClass(RISCVVMVTs::vint32mf2_t, &RISCV::VRRegClass); 117 addRegisterClass(RISCVVMVTs::vint32m1_t, &RISCV::VRRegClass); 118 addRegisterClass(RISCVVMVTs::vint32m2_t, &RISCV::VRM2RegClass); 119 addRegisterClass(RISCVVMVTs::vint32m4_t, &RISCV::VRM4RegClass); 120 addRegisterClass(RISCVVMVTs::vint32m8_t, &RISCV::VRM8RegClass); 121 122 addRegisterClass(RISCVVMVTs::vint64m1_t, &RISCV::VRRegClass); 123 addRegisterClass(RISCVVMVTs::vint64m2_t, &RISCV::VRM2RegClass); 124 addRegisterClass(RISCVVMVTs::vint64m4_t, &RISCV::VRM4RegClass); 125 addRegisterClass(RISCVVMVTs::vint64m8_t, &RISCV::VRM8RegClass); 126 127 if (Subtarget.hasStdExtZfh()) { 128 addRegisterClass(RISCVVMVTs::vfloat16mf4_t, &RISCV::VRRegClass); 129 addRegisterClass(RISCVVMVTs::vfloat16mf2_t, &RISCV::VRRegClass); 130 addRegisterClass(RISCVVMVTs::vfloat16m1_t, &RISCV::VRRegClass); 131 addRegisterClass(RISCVVMVTs::vfloat16m2_t, &RISCV::VRM2RegClass); 132 addRegisterClass(RISCVVMVTs::vfloat16m4_t, &RISCV::VRM4RegClass); 133 addRegisterClass(RISCVVMVTs::vfloat16m8_t, &RISCV::VRM8RegClass); 134 } 135 136 if (Subtarget.hasStdExtF()) { 137 addRegisterClass(RISCVVMVTs::vfloat32mf2_t, &RISCV::VRRegClass); 138 addRegisterClass(RISCVVMVTs::vfloat32m1_t, &RISCV::VRRegClass); 139 addRegisterClass(RISCVVMVTs::vfloat32m2_t, &RISCV::VRM2RegClass); 140 addRegisterClass(RISCVVMVTs::vfloat32m4_t, &RISCV::VRM4RegClass); 141 addRegisterClass(RISCVVMVTs::vfloat32m8_t, &RISCV::VRM8RegClass); 142 } 143 144 if (Subtarget.hasStdExtD()) { 145 addRegisterClass(RISCVVMVTs::vfloat64m1_t, &RISCV::VRRegClass); 146 addRegisterClass(RISCVVMVTs::vfloat64m2_t, &RISCV::VRM2RegClass); 147 addRegisterClass(RISCVVMVTs::vfloat64m4_t, &RISCV::VRM4RegClass); 148 addRegisterClass(RISCVVMVTs::vfloat64m8_t, &RISCV::VRM8RegClass); 149 } 150 } 151 152 // Compute derived properties from the register classes. 153 computeRegisterProperties(STI.getRegisterInfo()); 154 155 setStackPointerRegisterToSaveRestore(RISCV::X2); 156 157 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 158 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 159 160 // TODO: add all necessary setOperationAction calls. 161 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 162 163 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 164 setOperationAction(ISD::BR_CC, XLenVT, Expand); 165 setOperationAction(ISD::SELECT, XLenVT, Custom); 166 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 167 168 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 169 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 170 171 setOperationAction(ISD::VASTART, MVT::Other, Custom); 172 setOperationAction(ISD::VAARG, MVT::Other, Expand); 173 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 174 setOperationAction(ISD::VAEND, MVT::Other, Expand); 175 176 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 177 if (!Subtarget.hasStdExtZbb()) { 178 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 179 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 180 } 181 182 if (Subtarget.is64Bit()) { 183 setOperationAction(ISD::ADD, MVT::i32, Custom); 184 setOperationAction(ISD::SUB, MVT::i32, Custom); 185 setOperationAction(ISD::SHL, MVT::i32, Custom); 186 setOperationAction(ISD::SRA, MVT::i32, Custom); 187 setOperationAction(ISD::SRL, MVT::i32, Custom); 188 } 189 190 if (!Subtarget.hasStdExtM()) { 191 setOperationAction(ISD::MUL, XLenVT, Expand); 192 setOperationAction(ISD::MULHS, XLenVT, Expand); 193 setOperationAction(ISD::MULHU, XLenVT, Expand); 194 setOperationAction(ISD::SDIV, XLenVT, Expand); 195 setOperationAction(ISD::UDIV, XLenVT, Expand); 196 setOperationAction(ISD::SREM, XLenVT, Expand); 197 setOperationAction(ISD::UREM, XLenVT, Expand); 198 } 199 200 if (Subtarget.is64Bit() && Subtarget.hasStdExtM()) { 201 setOperationAction(ISD::MUL, MVT::i32, Custom); 202 setOperationAction(ISD::SDIV, MVT::i32, Custom); 203 setOperationAction(ISD::UDIV, MVT::i32, Custom); 204 setOperationAction(ISD::UREM, MVT::i32, Custom); 205 } 206 207 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 208 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 209 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 210 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 211 212 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 213 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 214 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 215 216 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 217 if (Subtarget.is64Bit()) { 218 setOperationAction(ISD::ROTL, MVT::i32, Custom); 219 setOperationAction(ISD::ROTR, MVT::i32, Custom); 220 } 221 } else { 222 setOperationAction(ISD::ROTL, XLenVT, Expand); 223 setOperationAction(ISD::ROTR, XLenVT, Expand); 224 } 225 226 if (Subtarget.hasStdExtZbp()) { 227 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 228 setOperationAction(ISD::BSWAP, XLenVT, Custom); 229 230 if (Subtarget.is64Bit()) { 231 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 232 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 233 } 234 } else { 235 setOperationAction(ISD::BSWAP, XLenVT, Expand); 236 } 237 238 if (Subtarget.hasStdExtZbb()) { 239 setOperationAction(ISD::SMIN, XLenVT, Legal); 240 setOperationAction(ISD::SMAX, XLenVT, Legal); 241 setOperationAction(ISD::UMIN, XLenVT, Legal); 242 setOperationAction(ISD::UMAX, XLenVT, Legal); 243 } else { 244 setOperationAction(ISD::CTTZ, XLenVT, Expand); 245 setOperationAction(ISD::CTLZ, XLenVT, Expand); 246 setOperationAction(ISD::CTPOP, XLenVT, Expand); 247 } 248 249 if (Subtarget.hasStdExtZbt()) { 250 setOperationAction(ISD::FSHL, XLenVT, Legal); 251 setOperationAction(ISD::FSHR, XLenVT, Legal); 252 253 if (Subtarget.is64Bit()) { 254 setOperationAction(ISD::FSHL, MVT::i32, Custom); 255 setOperationAction(ISD::FSHR, MVT::i32, Custom); 256 } 257 } 258 259 ISD::CondCode FPCCToExpand[] = { 260 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 261 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 262 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 263 264 ISD::NodeType FPOpToExpand[] = { 265 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP, 266 ISD::FP_TO_FP16}; 267 268 if (Subtarget.hasStdExtZfh()) 269 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 270 271 if (Subtarget.hasStdExtZfh()) { 272 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 273 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 274 for (auto CC : FPCCToExpand) 275 setCondCodeAction(CC, MVT::f16, Expand); 276 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 277 setOperationAction(ISD::SELECT, MVT::f16, Custom); 278 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 279 for (auto Op : FPOpToExpand) 280 setOperationAction(Op, MVT::f16, Expand); 281 } 282 283 if (Subtarget.hasStdExtF()) { 284 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 285 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 286 for (auto CC : FPCCToExpand) 287 setCondCodeAction(CC, MVT::f32, Expand); 288 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 289 setOperationAction(ISD::SELECT, MVT::f32, Custom); 290 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 291 for (auto Op : FPOpToExpand) 292 setOperationAction(Op, MVT::f32, Expand); 293 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 294 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 295 } 296 297 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 298 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 299 300 if (Subtarget.hasStdExtD()) { 301 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 302 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 303 for (auto CC : FPCCToExpand) 304 setCondCodeAction(CC, MVT::f64, Expand); 305 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 306 setOperationAction(ISD::SELECT, MVT::f64, Custom); 307 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 308 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 309 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 310 for (auto Op : FPOpToExpand) 311 setOperationAction(Op, MVT::f64, Expand); 312 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 313 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 314 } 315 316 if (Subtarget.is64Bit()) { 317 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 318 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 319 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 320 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 321 } 322 323 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 324 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 325 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 326 setOperationAction(ISD::JumpTable, XLenVT, Custom); 327 328 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 329 330 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 331 // Unfortunately this can't be determined just from the ISA naming string. 332 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 333 Subtarget.is64Bit() ? Legal : Custom); 334 335 setOperationAction(ISD::TRAP, MVT::Other, Legal); 336 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 337 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 338 339 if (Subtarget.hasStdExtA()) { 340 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 341 setMinCmpXchgSizeInBits(32); 342 } else { 343 setMaxAtomicSizeInBitsSupported(0); 344 } 345 346 setBooleanContents(ZeroOrOneBooleanContent); 347 348 if (Subtarget.hasStdExtV()) { 349 setBooleanVectorContents(ZeroOrOneBooleanContent); 350 351 // RVV intrinsics may have illegal operands. 352 // We also need to custom legalize vmv.x.s. 353 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 354 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 355 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 356 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 357 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 358 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 359 360 if (Subtarget.is64Bit()) { 361 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 362 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 363 } 364 365 for (auto VT : MVT::integer_scalable_vector_valuetypes()) { 366 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 367 368 setOperationAction(ISD::SMIN, VT, Legal); 369 setOperationAction(ISD::SMAX, VT, Legal); 370 setOperationAction(ISD::UMIN, VT, Legal); 371 setOperationAction(ISD::UMAX, VT, Legal); 372 } 373 374 // We must custom-lower SPLAT_VECTOR vXi64 on RV32 375 if (!Subtarget.is64Bit()) 376 setOperationAction(ISD::SPLAT_VECTOR, MVT::i64, Custom); 377 } 378 379 // Function alignments. 380 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 381 setMinFunctionAlignment(FunctionAlignment); 382 setPrefFunctionAlignment(FunctionAlignment); 383 384 setMinimumJumpTableEntries(5); 385 386 // Jumps are expensive, compared to logic 387 setJumpIsExpensive(); 388 389 // We can use any register for comparisons 390 setHasMultipleConditionRegisters(); 391 392 if (Subtarget.hasStdExtZbp()) { 393 setTargetDAGCombine(ISD::OR); 394 } 395 } 396 397 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 398 EVT VT) const { 399 if (!VT.isVector()) 400 return getPointerTy(DL); 401 if (Subtarget.hasStdExtV()) 402 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 403 return VT.changeVectorElementTypeToInteger(); 404 } 405 406 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 407 const CallInst &I, 408 MachineFunction &MF, 409 unsigned Intrinsic) const { 410 switch (Intrinsic) { 411 default: 412 return false; 413 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 414 case Intrinsic::riscv_masked_atomicrmw_add_i32: 415 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 416 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 417 case Intrinsic::riscv_masked_atomicrmw_max_i32: 418 case Intrinsic::riscv_masked_atomicrmw_min_i32: 419 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 420 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 421 case Intrinsic::riscv_masked_cmpxchg_i32: 422 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 423 Info.opc = ISD::INTRINSIC_W_CHAIN; 424 Info.memVT = MVT::getVT(PtrTy->getElementType()); 425 Info.ptrVal = I.getArgOperand(0); 426 Info.offset = 0; 427 Info.align = Align(4); 428 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 429 MachineMemOperand::MOVolatile; 430 return true; 431 } 432 } 433 434 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 435 const AddrMode &AM, Type *Ty, 436 unsigned AS, 437 Instruction *I) const { 438 // No global is ever allowed as a base. 439 if (AM.BaseGV) 440 return false; 441 442 // Require a 12-bit signed offset. 443 if (!isInt<12>(AM.BaseOffs)) 444 return false; 445 446 switch (AM.Scale) { 447 case 0: // "r+i" or just "i", depending on HasBaseReg. 448 break; 449 case 1: 450 if (!AM.HasBaseReg) // allow "r+i". 451 break; 452 return false; // disallow "r+r" or "r+r+i". 453 default: 454 return false; 455 } 456 457 return true; 458 } 459 460 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 461 return isInt<12>(Imm); 462 } 463 464 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 465 return isInt<12>(Imm); 466 } 467 468 // On RV32, 64-bit integers are split into their high and low parts and held 469 // in two different registers, so the trunc is free since the low register can 470 // just be used. 471 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 472 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 473 return false; 474 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 475 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 476 return (SrcBits == 64 && DestBits == 32); 477 } 478 479 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 480 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 481 !SrcVT.isInteger() || !DstVT.isInteger()) 482 return false; 483 unsigned SrcBits = SrcVT.getSizeInBits(); 484 unsigned DestBits = DstVT.getSizeInBits(); 485 return (SrcBits == 64 && DestBits == 32); 486 } 487 488 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 489 // Zexts are free if they can be combined with a load. 490 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 491 EVT MemVT = LD->getMemoryVT(); 492 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 493 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 494 (LD->getExtensionType() == ISD::NON_EXTLOAD || 495 LD->getExtensionType() == ISD::ZEXTLOAD)) 496 return true; 497 } 498 499 return TargetLowering::isZExtFree(Val, VT2); 500 } 501 502 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 503 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 504 } 505 506 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 507 return Subtarget.hasStdExtZbb(); 508 } 509 510 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 511 return Subtarget.hasStdExtZbb(); 512 } 513 514 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 515 bool ForCodeSize) const { 516 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 517 return false; 518 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 519 return false; 520 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 521 return false; 522 if (Imm.isNegZero()) 523 return false; 524 return Imm.isZero(); 525 } 526 527 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 528 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 529 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 530 (VT == MVT::f64 && Subtarget.hasStdExtD()); 531 } 532 533 // Changes the condition code and swaps operands if necessary, so the SetCC 534 // operation matches one of the comparisons supported directly in the RISC-V 535 // ISA. 536 static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) { 537 switch (CC) { 538 default: 539 break; 540 case ISD::SETGT: 541 case ISD::SETLE: 542 case ISD::SETUGT: 543 case ISD::SETULE: 544 CC = ISD::getSetCCSwappedOperands(CC); 545 std::swap(LHS, RHS); 546 break; 547 } 548 } 549 550 // Return the RISC-V branch opcode that matches the given DAG integer 551 // condition code. The CondCode must be one of those supported by the RISC-V 552 // ISA (see normaliseSetCC). 553 static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) { 554 switch (CC) { 555 default: 556 llvm_unreachable("Unsupported CondCode"); 557 case ISD::SETEQ: 558 return RISCV::BEQ; 559 case ISD::SETNE: 560 return RISCV::BNE; 561 case ISD::SETLT: 562 return RISCV::BLT; 563 case ISD::SETGE: 564 return RISCV::BGE; 565 case ISD::SETULT: 566 return RISCV::BLTU; 567 case ISD::SETUGE: 568 return RISCV::BGEU; 569 } 570 } 571 572 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 573 SelectionDAG &DAG) const { 574 switch (Op.getOpcode()) { 575 default: 576 report_fatal_error("unimplemented operand"); 577 case ISD::GlobalAddress: 578 return lowerGlobalAddress(Op, DAG); 579 case ISD::BlockAddress: 580 return lowerBlockAddress(Op, DAG); 581 case ISD::ConstantPool: 582 return lowerConstantPool(Op, DAG); 583 case ISD::JumpTable: 584 return lowerJumpTable(Op, DAG); 585 case ISD::GlobalTLSAddress: 586 return lowerGlobalTLSAddress(Op, DAG); 587 case ISD::SELECT: 588 return lowerSELECT(Op, DAG); 589 case ISD::VASTART: 590 return lowerVASTART(Op, DAG); 591 case ISD::FRAMEADDR: 592 return lowerFRAMEADDR(Op, DAG); 593 case ISD::RETURNADDR: 594 return lowerRETURNADDR(Op, DAG); 595 case ISD::SHL_PARTS: 596 return lowerShiftLeftParts(Op, DAG); 597 case ISD::SRA_PARTS: 598 return lowerShiftRightParts(Op, DAG, true); 599 case ISD::SRL_PARTS: 600 return lowerShiftRightParts(Op, DAG, false); 601 case ISD::BITCAST: { 602 assert(((Subtarget.is64Bit() && Subtarget.hasStdExtF()) || 603 Subtarget.hasStdExtZfh()) && 604 "Unexpected custom legalisation"); 605 SDLoc DL(Op); 606 SDValue Op0 = Op.getOperand(0); 607 if (Op.getValueType() == MVT::f16 && Subtarget.hasStdExtZfh()) { 608 if (Op0.getValueType() != MVT::i16) 609 return SDValue(); 610 SDValue NewOp0 = 611 DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getXLenVT(), Op0); 612 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 613 return FPConv; 614 } else if (Op.getValueType() == MVT::f32 && Subtarget.is64Bit() && 615 Subtarget.hasStdExtF()) { 616 if (Op0.getValueType() != MVT::i32) 617 return SDValue(); 618 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 619 SDValue FPConv = 620 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 621 return FPConv; 622 } 623 return SDValue(); 624 } 625 case ISD::INTRINSIC_WO_CHAIN: 626 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 627 case ISD::INTRINSIC_W_CHAIN: 628 return LowerINTRINSIC_W_CHAIN(Op, DAG); 629 case ISD::BSWAP: 630 case ISD::BITREVERSE: { 631 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 632 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 633 MVT VT = Op.getSimpleValueType(); 634 SDLoc DL(Op); 635 // Start with the maximum immediate value which is the bitwidth - 1. 636 unsigned Imm = VT.getSizeInBits() - 1; 637 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 638 if (Op.getOpcode() == ISD::BSWAP) 639 Imm &= ~0x7U; 640 return DAG.getNode(RISCVISD::GREVI, DL, VT, Op.getOperand(0), 641 DAG.getTargetConstant(Imm, DL, Subtarget.getXLenVT())); 642 } 643 case ISD::SPLAT_VECTOR: 644 return lowerSPLATVECTOR(Op, DAG); 645 } 646 } 647 648 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 649 SelectionDAG &DAG, unsigned Flags) { 650 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 651 } 652 653 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 654 SelectionDAG &DAG, unsigned Flags) { 655 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 656 Flags); 657 } 658 659 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 660 SelectionDAG &DAG, unsigned Flags) { 661 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 662 N->getOffset(), Flags); 663 } 664 665 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 666 SelectionDAG &DAG, unsigned Flags) { 667 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 668 } 669 670 template <class NodeTy> 671 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 672 bool IsLocal) const { 673 SDLoc DL(N); 674 EVT Ty = getPointerTy(DAG.getDataLayout()); 675 676 if (isPositionIndependent()) { 677 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 678 if (IsLocal) 679 // Use PC-relative addressing to access the symbol. This generates the 680 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 681 // %pcrel_lo(auipc)). 682 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 683 684 // Use PC-relative addressing to access the GOT for this symbol, then load 685 // the address from the GOT. This generates the pattern (PseudoLA sym), 686 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 687 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 688 } 689 690 switch (getTargetMachine().getCodeModel()) { 691 default: 692 report_fatal_error("Unsupported code model for lowering"); 693 case CodeModel::Small: { 694 // Generate a sequence for accessing addresses within the first 2 GiB of 695 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 696 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 697 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 698 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 699 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 700 } 701 case CodeModel::Medium: { 702 // Generate a sequence for accessing addresses within any 2GiB range within 703 // the address space. This generates the pattern (PseudoLLA sym), which 704 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 705 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 706 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 707 } 708 } 709 } 710 711 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 712 SelectionDAG &DAG) const { 713 SDLoc DL(Op); 714 EVT Ty = Op.getValueType(); 715 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 716 int64_t Offset = N->getOffset(); 717 MVT XLenVT = Subtarget.getXLenVT(); 718 719 const GlobalValue *GV = N->getGlobal(); 720 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 721 SDValue Addr = getAddr(N, DAG, IsLocal); 722 723 // In order to maximise the opportunity for common subexpression elimination, 724 // emit a separate ADD node for the global address offset instead of folding 725 // it in the global address node. Later peephole optimisations may choose to 726 // fold it back in when profitable. 727 if (Offset != 0) 728 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 729 DAG.getConstant(Offset, DL, XLenVT)); 730 return Addr; 731 } 732 733 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 734 SelectionDAG &DAG) const { 735 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 736 737 return getAddr(N, DAG); 738 } 739 740 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 741 SelectionDAG &DAG) const { 742 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 743 744 return getAddr(N, DAG); 745 } 746 747 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 748 SelectionDAG &DAG) const { 749 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 750 751 return getAddr(N, DAG); 752 } 753 754 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 755 SelectionDAG &DAG, 756 bool UseGOT) const { 757 SDLoc DL(N); 758 EVT Ty = getPointerTy(DAG.getDataLayout()); 759 const GlobalValue *GV = N->getGlobal(); 760 MVT XLenVT = Subtarget.getXLenVT(); 761 762 if (UseGOT) { 763 // Use PC-relative addressing to access the GOT for this TLS symbol, then 764 // load the address from the GOT and add the thread pointer. This generates 765 // the pattern (PseudoLA_TLS_IE sym), which expands to 766 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 767 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 768 SDValue Load = 769 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 770 771 // Add the thread pointer. 772 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 773 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 774 } 775 776 // Generate a sequence for accessing the address relative to the thread 777 // pointer, with the appropriate adjustment for the thread pointer offset. 778 // This generates the pattern 779 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 780 SDValue AddrHi = 781 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 782 SDValue AddrAdd = 783 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 784 SDValue AddrLo = 785 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 786 787 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 788 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 789 SDValue MNAdd = SDValue( 790 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 791 0); 792 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 793 } 794 795 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 796 SelectionDAG &DAG) const { 797 SDLoc DL(N); 798 EVT Ty = getPointerTy(DAG.getDataLayout()); 799 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 800 const GlobalValue *GV = N->getGlobal(); 801 802 // Use a PC-relative addressing mode to access the global dynamic GOT address. 803 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 804 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 805 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 806 SDValue Load = 807 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 808 809 // Prepare argument list to generate call. 810 ArgListTy Args; 811 ArgListEntry Entry; 812 Entry.Node = Load; 813 Entry.Ty = CallTy; 814 Args.push_back(Entry); 815 816 // Setup call to __tls_get_addr. 817 TargetLowering::CallLoweringInfo CLI(DAG); 818 CLI.setDebugLoc(DL) 819 .setChain(DAG.getEntryNode()) 820 .setLibCallee(CallingConv::C, CallTy, 821 DAG.getExternalSymbol("__tls_get_addr", Ty), 822 std::move(Args)); 823 824 return LowerCallTo(CLI).first; 825 } 826 827 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 828 SelectionDAG &DAG) const { 829 SDLoc DL(Op); 830 EVT Ty = Op.getValueType(); 831 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 832 int64_t Offset = N->getOffset(); 833 MVT XLenVT = Subtarget.getXLenVT(); 834 835 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 836 837 if (DAG.getMachineFunction().getFunction().getCallingConv() == 838 CallingConv::GHC) 839 report_fatal_error("In GHC calling convention TLS is not supported"); 840 841 SDValue Addr; 842 switch (Model) { 843 case TLSModel::LocalExec: 844 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 845 break; 846 case TLSModel::InitialExec: 847 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 848 break; 849 case TLSModel::LocalDynamic: 850 case TLSModel::GeneralDynamic: 851 Addr = getDynamicTLSAddr(N, DAG); 852 break; 853 } 854 855 // In order to maximise the opportunity for common subexpression elimination, 856 // emit a separate ADD node for the global address offset instead of folding 857 // it in the global address node. Later peephole optimisations may choose to 858 // fold it back in when profitable. 859 if (Offset != 0) 860 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 861 DAG.getConstant(Offset, DL, XLenVT)); 862 return Addr; 863 } 864 865 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 866 SDValue CondV = Op.getOperand(0); 867 SDValue TrueV = Op.getOperand(1); 868 SDValue FalseV = Op.getOperand(2); 869 SDLoc DL(Op); 870 MVT XLenVT = Subtarget.getXLenVT(); 871 872 // If the result type is XLenVT and CondV is the output of a SETCC node 873 // which also operated on XLenVT inputs, then merge the SETCC node into the 874 // lowered RISCVISD::SELECT_CC to take advantage of the integer 875 // compare+branch instructions. i.e.: 876 // (select (setcc lhs, rhs, cc), truev, falsev) 877 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 878 if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC && 879 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 880 SDValue LHS = CondV.getOperand(0); 881 SDValue RHS = CondV.getOperand(1); 882 auto CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 883 ISD::CondCode CCVal = CC->get(); 884 885 normaliseSetCC(LHS, RHS, CCVal); 886 887 SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT); 888 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 889 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 890 } 891 892 // Otherwise: 893 // (select condv, truev, falsev) 894 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 895 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 896 SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT); 897 898 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 899 900 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 901 } 902 903 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 904 MachineFunction &MF = DAG.getMachineFunction(); 905 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 906 907 SDLoc DL(Op); 908 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 909 getPointerTy(MF.getDataLayout())); 910 911 // vastart just stores the address of the VarArgsFrameIndex slot into the 912 // memory location argument. 913 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 914 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 915 MachinePointerInfo(SV)); 916 } 917 918 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 919 SelectionDAG &DAG) const { 920 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 921 MachineFunction &MF = DAG.getMachineFunction(); 922 MachineFrameInfo &MFI = MF.getFrameInfo(); 923 MFI.setFrameAddressIsTaken(true); 924 Register FrameReg = RI.getFrameRegister(MF); 925 int XLenInBytes = Subtarget.getXLen() / 8; 926 927 EVT VT = Op.getValueType(); 928 SDLoc DL(Op); 929 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 930 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 931 while (Depth--) { 932 int Offset = -(XLenInBytes * 2); 933 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 934 DAG.getIntPtrConstant(Offset, DL)); 935 FrameAddr = 936 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 937 } 938 return FrameAddr; 939 } 940 941 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 942 SelectionDAG &DAG) const { 943 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 944 MachineFunction &MF = DAG.getMachineFunction(); 945 MachineFrameInfo &MFI = MF.getFrameInfo(); 946 MFI.setReturnAddressIsTaken(true); 947 MVT XLenVT = Subtarget.getXLenVT(); 948 int XLenInBytes = Subtarget.getXLen() / 8; 949 950 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 951 return SDValue(); 952 953 EVT VT = Op.getValueType(); 954 SDLoc DL(Op); 955 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 956 if (Depth) { 957 int Off = -XLenInBytes; 958 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 959 SDValue Offset = DAG.getConstant(Off, DL, VT); 960 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 961 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 962 MachinePointerInfo()); 963 } 964 965 // Return the value of the return address register, marking it an implicit 966 // live-in. 967 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 968 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 969 } 970 971 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 972 SelectionDAG &DAG) const { 973 SDLoc DL(Op); 974 SDValue Lo = Op.getOperand(0); 975 SDValue Hi = Op.getOperand(1); 976 SDValue Shamt = Op.getOperand(2); 977 EVT VT = Lo.getValueType(); 978 979 // if Shamt-XLEN < 0: // Shamt < XLEN 980 // Lo = Lo << Shamt 981 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 982 // else: 983 // Lo = 0 984 // Hi = Lo << (Shamt-XLEN) 985 986 SDValue Zero = DAG.getConstant(0, DL, VT); 987 SDValue One = DAG.getConstant(1, DL, VT); 988 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 989 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 990 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 991 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 992 993 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 994 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 995 SDValue ShiftRightLo = 996 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 997 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 998 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 999 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 1000 1001 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 1002 1003 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 1004 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 1005 1006 SDValue Parts[2] = {Lo, Hi}; 1007 return DAG.getMergeValues(Parts, DL); 1008 } 1009 1010 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 1011 bool IsSRA) const { 1012 SDLoc DL(Op); 1013 SDValue Lo = Op.getOperand(0); 1014 SDValue Hi = Op.getOperand(1); 1015 SDValue Shamt = Op.getOperand(2); 1016 EVT VT = Lo.getValueType(); 1017 1018 // SRA expansion: 1019 // if Shamt-XLEN < 0: // Shamt < XLEN 1020 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 1021 // Hi = Hi >>s Shamt 1022 // else: 1023 // Lo = Hi >>s (Shamt-XLEN); 1024 // Hi = Hi >>s (XLEN-1) 1025 // 1026 // SRL expansion: 1027 // if Shamt-XLEN < 0: // Shamt < XLEN 1028 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 1029 // Hi = Hi >>u Shamt 1030 // else: 1031 // Lo = Hi >>u (Shamt-XLEN); 1032 // Hi = 0; 1033 1034 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 1035 1036 SDValue Zero = DAG.getConstant(0, DL, VT); 1037 SDValue One = DAG.getConstant(1, DL, VT); 1038 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 1039 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 1040 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 1041 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 1042 1043 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 1044 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 1045 SDValue ShiftLeftHi = 1046 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 1047 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 1048 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 1049 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 1050 SDValue HiFalse = 1051 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 1052 1053 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 1054 1055 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 1056 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 1057 1058 SDValue Parts[2] = {Lo, Hi}; 1059 return DAG.getMergeValues(Parts, DL); 1060 } 1061 1062 // Custom-lower a SPLAT_VECTOR where XLEN<SEW, as the SEW element type is 1063 // illegal (currently only vXi64 RV32). 1064 // FIXME: We could also catch non-constant sign-extended i32 values and lower 1065 // them to SPLAT_VECTOR_I64 1066 SDValue RISCVTargetLowering::lowerSPLATVECTOR(SDValue Op, 1067 SelectionDAG &DAG) const { 1068 SDLoc DL(Op); 1069 EVT VecVT = Op.getValueType(); 1070 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 1071 "Unexpected SPLAT_VECTOR lowering"); 1072 SDValue SplatVal = Op.getOperand(0); 1073 1074 // If we can prove that the value is a sign-extended 32-bit value, lower this 1075 // as a custom node in order to try and match RVV vector/scalar instructions. 1076 if (auto *CVal = dyn_cast<ConstantSDNode>(SplatVal)) { 1077 if (isInt<32>(CVal->getSExtValue())) 1078 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, 1079 DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32)); 1080 } 1081 1082 // Else, on RV32 we lower an i64-element SPLAT_VECTOR thus, being careful not 1083 // to accidentally sign-extend the 32-bit halves to the e64 SEW: 1084 // vmv.v.x vX, hi 1085 // vsll.vx vX, vX, /*32*/ 1086 // vmv.v.x vY, lo 1087 // vsll.vx vY, vY, /*32*/ 1088 // vsrl.vx vY, vY, /*32*/ 1089 // vor.vv vX, vX, vY 1090 SDValue One = DAG.getConstant(1, DL, MVT::i32); 1091 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 1092 SDValue ThirtyTwoV = DAG.getConstant(32, DL, VecVT); 1093 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, SplatVal, Zero); 1094 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, SplatVal, One); 1095 1096 Lo = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 1097 Lo = DAG.getNode(ISD::SHL, DL, VecVT, Lo, ThirtyTwoV); 1098 Lo = DAG.getNode(ISD::SRL, DL, VecVT, Lo, ThirtyTwoV); 1099 1100 if (isNullConstant(Hi)) 1101 return Lo; 1102 1103 Hi = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Hi); 1104 Hi = DAG.getNode(ISD::SHL, DL, VecVT, Hi, ThirtyTwoV); 1105 1106 return DAG.getNode(ISD::OR, DL, VecVT, Lo, Hi); 1107 } 1108 1109 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 1110 SelectionDAG &DAG) const { 1111 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1112 SDLoc DL(Op); 1113 1114 if (Subtarget.hasStdExtV()) { 1115 // Some RVV intrinsics may claim that they want an integer operand to be 1116 // extended. 1117 if (const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1118 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo)) { 1119 if (II->ExtendedOperand) { 1120 assert(II->ExtendedOperand < Op.getNumOperands()); 1121 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 1122 SDValue &ScalarOp = Operands[II->ExtendedOperand]; 1123 EVT OpVT = ScalarOp.getValueType(); 1124 if (OpVT == MVT::i8 || OpVT == MVT::i16 || 1125 (OpVT == MVT::i32 && Subtarget.is64Bit())) { 1126 // If the operand is a constant, sign extend to increase our chances 1127 // of being able to use a .vi instruction. ANY_EXTEND would become a 1128 // a zero extend and the simm5 check in isel would fail. 1129 // FIXME: Should we ignore the upper bits in isel instead? 1130 unsigned ExtOpc = isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND 1131 : ISD::ANY_EXTEND; 1132 ScalarOp = DAG.getNode(ExtOpc, DL, Subtarget.getXLenVT(), ScalarOp); 1133 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 1134 Operands); 1135 } 1136 } 1137 } 1138 } 1139 1140 switch (IntNo) { 1141 default: 1142 return SDValue(); // Don't custom lower most intrinsics. 1143 case Intrinsic::thread_pointer: { 1144 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 1145 return DAG.getRegister(RISCV::X4, PtrVT); 1146 } 1147 case Intrinsic::riscv_vmv_x_s: 1148 assert(Op.getValueType() == Subtarget.getXLenVT() && "Unexpected VT!"); 1149 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 1150 Op.getOperand(1)); 1151 } 1152 } 1153 1154 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 1155 SelectionDAG &DAG) const { 1156 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 1157 SDLoc DL(Op); 1158 1159 if (Subtarget.hasStdExtV()) { 1160 // Some RVV intrinsics may claim that they want an integer operand to be 1161 // extended. 1162 if (const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1163 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo)) { 1164 if (II->ExtendedOperand) { 1165 // The operands start from the second argument in INTRINSIC_W_CHAIN. 1166 unsigned ExtendOp = II->ExtendedOperand + 1; 1167 assert(ExtendOp < Op.getNumOperands()); 1168 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 1169 SDValue &ScalarOp = Operands[ExtendOp]; 1170 EVT OpVT = ScalarOp.getValueType(); 1171 if (OpVT == MVT::i8 || OpVT == MVT::i16 || 1172 (OpVT == MVT::i32 && Subtarget.is64Bit())) { 1173 // If the operand is a constant, sign extend to increase our chances 1174 // of being able to use a .vi instruction. ANY_EXTEND would become a 1175 // a zero extend and the simm5 check in isel would fail. 1176 // FIXME: Should we ignore the upper bits in isel instead? 1177 unsigned ExtOpc = isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND 1178 : ISD::ANY_EXTEND; 1179 ScalarOp = DAG.getNode(ExtOpc, DL, Subtarget.getXLenVT(), ScalarOp); 1180 return DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, Op->getVTList(), 1181 Operands); 1182 } 1183 } 1184 } 1185 } 1186 1187 return SDValue(); 1188 } 1189 1190 // Returns the opcode of the target-specific SDNode that implements the 32-bit 1191 // form of the given Opcode. 1192 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 1193 switch (Opcode) { 1194 default: 1195 llvm_unreachable("Unexpected opcode"); 1196 case ISD::SHL: 1197 return RISCVISD::SLLW; 1198 case ISD::SRA: 1199 return RISCVISD::SRAW; 1200 case ISD::SRL: 1201 return RISCVISD::SRLW; 1202 case ISD::SDIV: 1203 return RISCVISD::DIVW; 1204 case ISD::UDIV: 1205 return RISCVISD::DIVUW; 1206 case ISD::UREM: 1207 return RISCVISD::REMUW; 1208 case ISD::ROTL: 1209 return RISCVISD::ROLW; 1210 case ISD::ROTR: 1211 return RISCVISD::RORW; 1212 case RISCVISD::GREVI: 1213 return RISCVISD::GREVIW; 1214 case RISCVISD::GORCI: 1215 return RISCVISD::GORCIW; 1216 } 1217 } 1218 1219 // Converts the given 32-bit operation to a target-specific SelectionDAG node. 1220 // Because i32 isn't a legal type for RV64, these operations would otherwise 1221 // be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W 1222 // later one because the fact the operation was originally of type i32 is 1223 // lost. 1224 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG) { 1225 SDLoc DL(N); 1226 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 1227 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 1228 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 1229 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 1230 // ReplaceNodeResults requires we maintain the same type for the return value. 1231 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 1232 } 1233 1234 // Converts the given 32-bit operation to a i64 operation with signed extension 1235 // semantic to reduce the signed extension instructions. 1236 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 1237 SDLoc DL(N); 1238 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 1239 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 1240 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 1241 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 1242 DAG.getValueType(MVT::i32)); 1243 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 1244 } 1245 1246 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 1247 SmallVectorImpl<SDValue> &Results, 1248 SelectionDAG &DAG) const { 1249 SDLoc DL(N); 1250 switch (N->getOpcode()) { 1251 default: 1252 llvm_unreachable("Don't know how to custom type legalize this operation!"); 1253 case ISD::STRICT_FP_TO_SINT: 1254 case ISD::STRICT_FP_TO_UINT: 1255 case ISD::FP_TO_SINT: 1256 case ISD::FP_TO_UINT: { 1257 bool IsStrict = N->isStrictFPOpcode(); 1258 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1259 "Unexpected custom legalisation"); 1260 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 1261 // If the FP type needs to be softened, emit a library call using the 'si' 1262 // version. If we left it to default legalization we'd end up with 'di'. If 1263 // the FP type doesn't need to be softened just let generic type 1264 // legalization promote the result type. 1265 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 1266 TargetLowering::TypeSoftenFloat) 1267 return; 1268 RTLIB::Libcall LC; 1269 if (N->getOpcode() == ISD::FP_TO_SINT || 1270 N->getOpcode() == ISD::STRICT_FP_TO_SINT) 1271 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 1272 else 1273 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 1274 MakeLibCallOptions CallOptions; 1275 EVT OpVT = Op0.getValueType(); 1276 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 1277 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 1278 SDValue Result; 1279 std::tie(Result, Chain) = 1280 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 1281 Results.push_back(Result); 1282 if (IsStrict) 1283 Results.push_back(Chain); 1284 break; 1285 } 1286 case ISD::READCYCLECOUNTER: { 1287 assert(!Subtarget.is64Bit() && 1288 "READCYCLECOUNTER only has custom type legalization on riscv32"); 1289 1290 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 1291 SDValue RCW = 1292 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 1293 1294 Results.push_back( 1295 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 1296 Results.push_back(RCW.getValue(2)); 1297 break; 1298 } 1299 case ISD::ADD: 1300 case ISD::SUB: 1301 case ISD::MUL: 1302 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1303 "Unexpected custom legalisation"); 1304 if (N->getOperand(1).getOpcode() == ISD::Constant) 1305 return; 1306 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 1307 break; 1308 case ISD::SHL: 1309 case ISD::SRA: 1310 case ISD::SRL: 1311 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1312 "Unexpected custom legalisation"); 1313 if (N->getOperand(1).getOpcode() == ISD::Constant) 1314 return; 1315 Results.push_back(customLegalizeToWOp(N, DAG)); 1316 break; 1317 case ISD::ROTL: 1318 case ISD::ROTR: 1319 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1320 "Unexpected custom legalisation"); 1321 Results.push_back(customLegalizeToWOp(N, DAG)); 1322 break; 1323 case ISD::SDIV: 1324 case ISD::UDIV: 1325 case ISD::UREM: 1326 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1327 Subtarget.hasStdExtM() && "Unexpected custom legalisation"); 1328 if (N->getOperand(0).getOpcode() == ISD::Constant || 1329 N->getOperand(1).getOpcode() == ISD::Constant) 1330 return; 1331 Results.push_back(customLegalizeToWOp(N, DAG)); 1332 break; 1333 case ISD::BITCAST: { 1334 assert(((N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1335 Subtarget.hasStdExtF()) || 1336 (N->getValueType(0) == MVT::i16 && Subtarget.hasStdExtZfh())) && 1337 "Unexpected custom legalisation"); 1338 SDValue Op0 = N->getOperand(0); 1339 if (N->getValueType(0) == MVT::i16 && Subtarget.hasStdExtZfh()) { 1340 if (Op0.getValueType() != MVT::f16) 1341 return; 1342 SDValue FPConv = 1343 DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, Subtarget.getXLenVT(), Op0); 1344 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 1345 } else if (N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1346 Subtarget.hasStdExtF()) { 1347 if (Op0.getValueType() != MVT::f32) 1348 return; 1349 SDValue FPConv = 1350 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 1351 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 1352 } 1353 break; 1354 } 1355 case RISCVISD::GREVI: 1356 case RISCVISD::GORCI: { 1357 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1358 "Unexpected custom legalisation"); 1359 // This is similar to customLegalizeToWOp, except that we pass the second 1360 // operand (a TargetConstant) straight through: it is already of type 1361 // XLenVT. 1362 SDLoc DL(N); 1363 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 1364 SDValue NewOp0 = 1365 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 1366 SDValue NewRes = 1367 DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, N->getOperand(1)); 1368 // ReplaceNodeResults requires we maintain the same type for the return 1369 // value. 1370 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 1371 break; 1372 } 1373 case ISD::BSWAP: 1374 case ISD::BITREVERSE: { 1375 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1376 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 1377 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 1378 N->getOperand(0)); 1379 unsigned Imm = N->getOpcode() == ISD::BITREVERSE ? 31 : 24; 1380 SDValue GREVIW = DAG.getNode(RISCVISD::GREVIW, DL, MVT::i64, NewOp0, 1381 DAG.getTargetConstant(Imm, DL, 1382 Subtarget.getXLenVT())); 1383 // ReplaceNodeResults requires we maintain the same type for the return 1384 // value. 1385 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, GREVIW)); 1386 break; 1387 } 1388 case ISD::FSHL: 1389 case ISD::FSHR: { 1390 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1391 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 1392 SDValue NewOp0 = 1393 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 1394 SDValue NewOp1 = 1395 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 1396 SDValue NewOp2 = 1397 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 1398 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 1399 // Mask the shift amount to 5 bits. 1400 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 1401 DAG.getConstant(0x1f, DL, MVT::i64)); 1402 unsigned Opc = 1403 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 1404 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 1405 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 1406 break; 1407 } 1408 case ISD::INTRINSIC_WO_CHAIN: { 1409 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 1410 switch (IntNo) { 1411 default: 1412 llvm_unreachable( 1413 "Don't know how to custom type legalize this intrinsic!"); 1414 case Intrinsic::riscv_vmv_x_s: { 1415 EVT VT = N->getValueType(0); 1416 assert((VT == MVT::i8 || VT == MVT::i16 || 1417 (Subtarget.is64Bit() && VT == MVT::i32)) && 1418 "Unexpected custom legalisation!"); 1419 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 1420 Subtarget.getXLenVT(), N->getOperand(1)); 1421 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 1422 break; 1423 } 1424 } 1425 break; 1426 } 1427 } 1428 } 1429 1430 // A structure to hold one of the bit-manipulation patterns below. Together, a 1431 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 1432 // (or (and (shl x, 1), 0xAAAAAAAA), 1433 // (and (srl x, 1), 0x55555555)) 1434 struct RISCVBitmanipPat { 1435 SDValue Op; 1436 unsigned ShAmt; 1437 bool IsSHL; 1438 1439 bool formsPairWith(const RISCVBitmanipPat &Other) const { 1440 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 1441 } 1442 }; 1443 1444 // Matches any of the following bit-manipulation patterns: 1445 // (and (shl x, 1), (0x55555555 << 1)) 1446 // (and (srl x, 1), 0x55555555) 1447 // (shl (and x, 0x55555555), 1) 1448 // (srl (and x, (0x55555555 << 1)), 1) 1449 // where the shift amount and mask may vary thus: 1450 // [1] = 0x55555555 / 0xAAAAAAAA 1451 // [2] = 0x33333333 / 0xCCCCCCCC 1452 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 1453 // [8] = 0x00FF00FF / 0xFF00FF00 1454 // [16] = 0x0000FFFF / 0xFFFFFFFF 1455 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 1456 static Optional<RISCVBitmanipPat> matchRISCVBitmanipPat(SDValue Op) { 1457 Optional<uint64_t> Mask; 1458 // Optionally consume a mask around the shift operation. 1459 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 1460 Mask = Op.getConstantOperandVal(1); 1461 Op = Op.getOperand(0); 1462 } 1463 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 1464 return None; 1465 bool IsSHL = Op.getOpcode() == ISD::SHL; 1466 1467 if (!isa<ConstantSDNode>(Op.getOperand(1))) 1468 return None; 1469 auto ShAmt = Op.getConstantOperandVal(1); 1470 1471 if (!isPowerOf2_64(ShAmt)) 1472 return None; 1473 1474 // These are the unshifted masks which we use to match bit-manipulation 1475 // patterns. They may be shifted left in certain circumstances. 1476 static const uint64_t BitmanipMasks[] = { 1477 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 1478 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL, 1479 }; 1480 1481 unsigned MaskIdx = Log2_64(ShAmt); 1482 if (MaskIdx >= array_lengthof(BitmanipMasks)) 1483 return None; 1484 1485 auto Src = Op.getOperand(0); 1486 1487 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 1488 auto ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 1489 1490 // The expected mask is shifted left when the AND is found around SHL 1491 // patterns. 1492 // ((x >> 1) & 0x55555555) 1493 // ((x << 1) & 0xAAAAAAAA) 1494 bool SHLExpMask = IsSHL; 1495 1496 if (!Mask) { 1497 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 1498 // the mask is all ones: consume that now. 1499 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 1500 Mask = Src.getConstantOperandVal(1); 1501 Src = Src.getOperand(0); 1502 // The expected mask is now in fact shifted left for SRL, so reverse the 1503 // decision. 1504 // ((x & 0xAAAAAAAA) >> 1) 1505 // ((x & 0x55555555) << 1) 1506 SHLExpMask = !SHLExpMask; 1507 } else { 1508 // Use a default shifted mask of all-ones if there's no AND, truncated 1509 // down to the expected width. This simplifies the logic later on. 1510 Mask = maskTrailingOnes<uint64_t>(Width); 1511 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 1512 } 1513 } 1514 1515 if (SHLExpMask) 1516 ExpMask <<= ShAmt; 1517 1518 if (Mask != ExpMask) 1519 return None; 1520 1521 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 1522 } 1523 1524 // Match the following pattern as a GREVI(W) operation 1525 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 1526 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 1527 const RISCVSubtarget &Subtarget) { 1528 EVT VT = Op.getValueType(); 1529 1530 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 1531 auto LHS = matchRISCVBitmanipPat(Op.getOperand(0)); 1532 auto RHS = matchRISCVBitmanipPat(Op.getOperand(1)); 1533 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 1534 SDLoc DL(Op); 1535 return DAG.getNode( 1536 RISCVISD::GREVI, DL, VT, LHS->Op, 1537 DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT())); 1538 } 1539 } 1540 return SDValue(); 1541 } 1542 1543 // Matches any the following pattern as a GORCI(W) operation 1544 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 1545 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 1546 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 1547 // Note that with the variant of 3., 1548 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 1549 // the inner pattern will first be matched as GREVI and then the outer 1550 // pattern will be matched to GORC via the first rule above. 1551 // 4. (or (rotl/rotr x, bitwidth/2), x) 1552 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 1553 const RISCVSubtarget &Subtarget) { 1554 EVT VT = Op.getValueType(); 1555 1556 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 1557 SDLoc DL(Op); 1558 SDValue Op0 = Op.getOperand(0); 1559 SDValue Op1 = Op.getOperand(1); 1560 1561 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 1562 if (Reverse.getOpcode() == RISCVISD::GREVI && Reverse.getOperand(0) == X && 1563 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 1564 return DAG.getNode(RISCVISD::GORCI, DL, VT, X, Reverse.getOperand(1)); 1565 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 1566 if ((Reverse.getOpcode() == ISD::ROTL || 1567 Reverse.getOpcode() == ISD::ROTR) && 1568 Reverse.getOperand(0) == X && 1569 isa<ConstantSDNode>(Reverse.getOperand(1))) { 1570 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 1571 if (RotAmt == (VT.getSizeInBits() / 2)) 1572 return DAG.getNode( 1573 RISCVISD::GORCI, DL, VT, X, 1574 DAG.getTargetConstant(RotAmt, DL, Subtarget.getXLenVT())); 1575 } 1576 return SDValue(); 1577 }; 1578 1579 // Check for either commutable permutation of (or (GREVI x, shamt), x) 1580 if (SDValue V = MatchOROfReverse(Op0, Op1)) 1581 return V; 1582 if (SDValue V = MatchOROfReverse(Op1, Op0)) 1583 return V; 1584 1585 // OR is commutable so canonicalize its OR operand to the left 1586 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 1587 std::swap(Op0, Op1); 1588 if (Op0.getOpcode() != ISD::OR) 1589 return SDValue(); 1590 SDValue OrOp0 = Op0.getOperand(0); 1591 SDValue OrOp1 = Op0.getOperand(1); 1592 auto LHS = matchRISCVBitmanipPat(OrOp0); 1593 // OR is commutable so swap the operands and try again: x might have been 1594 // on the left 1595 if (!LHS) { 1596 std::swap(OrOp0, OrOp1); 1597 LHS = matchRISCVBitmanipPat(OrOp0); 1598 } 1599 auto RHS = matchRISCVBitmanipPat(Op1); 1600 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 1601 return DAG.getNode( 1602 RISCVISD::GORCI, DL, VT, LHS->Op, 1603 DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT())); 1604 } 1605 } 1606 return SDValue(); 1607 } 1608 1609 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 1610 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 1611 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 1612 // not undo itself, but they are redundant. 1613 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 1614 unsigned ShAmt1 = N->getConstantOperandVal(1); 1615 SDValue Src = N->getOperand(0); 1616 1617 if (Src.getOpcode() != N->getOpcode()) 1618 return SDValue(); 1619 1620 unsigned ShAmt2 = Src.getConstantOperandVal(1); 1621 Src = Src.getOperand(0); 1622 1623 unsigned CombinedShAmt; 1624 if (N->getOpcode() == RISCVISD::GORCI || N->getOpcode() == RISCVISD::GORCIW) 1625 CombinedShAmt = ShAmt1 | ShAmt2; 1626 else 1627 CombinedShAmt = ShAmt1 ^ ShAmt2; 1628 1629 if (CombinedShAmt == 0) 1630 return Src; 1631 1632 SDLoc DL(N); 1633 return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), Src, 1634 DAG.getTargetConstant(CombinedShAmt, DL, 1635 N->getOperand(1).getValueType())); 1636 } 1637 1638 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 1639 DAGCombinerInfo &DCI) const { 1640 SelectionDAG &DAG = DCI.DAG; 1641 1642 switch (N->getOpcode()) { 1643 default: 1644 break; 1645 case RISCVISD::SplitF64: { 1646 SDValue Op0 = N->getOperand(0); 1647 // If the input to SplitF64 is just BuildPairF64 then the operation is 1648 // redundant. Instead, use BuildPairF64's operands directly. 1649 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 1650 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 1651 1652 SDLoc DL(N); 1653 1654 // It's cheaper to materialise two 32-bit integers than to load a double 1655 // from the constant pool and transfer it to integer registers through the 1656 // stack. 1657 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 1658 APInt V = C->getValueAPF().bitcastToAPInt(); 1659 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 1660 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 1661 return DCI.CombineTo(N, Lo, Hi); 1662 } 1663 1664 // This is a target-specific version of a DAGCombine performed in 1665 // DAGCombiner::visitBITCAST. It performs the equivalent of: 1666 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 1667 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 1668 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 1669 !Op0.getNode()->hasOneUse()) 1670 break; 1671 SDValue NewSplitF64 = 1672 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 1673 Op0.getOperand(0)); 1674 SDValue Lo = NewSplitF64.getValue(0); 1675 SDValue Hi = NewSplitF64.getValue(1); 1676 APInt SignBit = APInt::getSignMask(32); 1677 if (Op0.getOpcode() == ISD::FNEG) { 1678 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 1679 DAG.getConstant(SignBit, DL, MVT::i32)); 1680 return DCI.CombineTo(N, Lo, NewHi); 1681 } 1682 assert(Op0.getOpcode() == ISD::FABS); 1683 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 1684 DAG.getConstant(~SignBit, DL, MVT::i32)); 1685 return DCI.CombineTo(N, Lo, NewHi); 1686 } 1687 case RISCVISD::SLLW: 1688 case RISCVISD::SRAW: 1689 case RISCVISD::SRLW: 1690 case RISCVISD::ROLW: 1691 case RISCVISD::RORW: { 1692 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 1693 SDValue LHS = N->getOperand(0); 1694 SDValue RHS = N->getOperand(1); 1695 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 1696 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5); 1697 if (SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI) || 1698 SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI)) { 1699 if (N->getOpcode() != ISD::DELETED_NODE) 1700 DCI.AddToWorklist(N); 1701 return SDValue(N, 0); 1702 } 1703 break; 1704 } 1705 case RISCVISD::FSLW: 1706 case RISCVISD::FSRW: { 1707 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 1708 // read. 1709 SDValue Op0 = N->getOperand(0); 1710 SDValue Op1 = N->getOperand(1); 1711 SDValue ShAmt = N->getOperand(2); 1712 APInt OpMask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32); 1713 APInt ShAmtMask = APInt::getLowBitsSet(ShAmt.getValueSizeInBits(), 6); 1714 if (SimplifyDemandedBits(Op0, OpMask, DCI) || 1715 SimplifyDemandedBits(Op1, OpMask, DCI) || 1716 SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) { 1717 if (N->getOpcode() != ISD::DELETED_NODE) 1718 DCI.AddToWorklist(N); 1719 return SDValue(N, 0); 1720 } 1721 break; 1722 } 1723 case RISCVISD::GREVIW: 1724 case RISCVISD::GORCIW: { 1725 // Only the lower 32 bits of the first operand are read 1726 SDValue Op0 = N->getOperand(0); 1727 APInt Mask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32); 1728 if (SimplifyDemandedBits(Op0, Mask, DCI)) { 1729 if (N->getOpcode() != ISD::DELETED_NODE) 1730 DCI.AddToWorklist(N); 1731 return SDValue(N, 0); 1732 } 1733 1734 return combineGREVI_GORCI(N, DCI.DAG); 1735 } 1736 case RISCVISD::FMV_X_ANYEXTW_RV64: { 1737 SDLoc DL(N); 1738 SDValue Op0 = N->getOperand(0); 1739 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 1740 // conversion is unnecessary and can be replaced with an ANY_EXTEND 1741 // of the FMV_W_X_RV64 operand. 1742 if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) { 1743 assert(Op0.getOperand(0).getValueType() == MVT::i64 && 1744 "Unexpected value type!"); 1745 return Op0.getOperand(0); 1746 } 1747 1748 // This is a target-specific version of a DAGCombine performed in 1749 // DAGCombiner::visitBITCAST. It performs the equivalent of: 1750 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 1751 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 1752 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 1753 !Op0.getNode()->hasOneUse()) 1754 break; 1755 SDValue NewFMV = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, 1756 Op0.getOperand(0)); 1757 APInt SignBit = APInt::getSignMask(32).sext(64); 1758 if (Op0.getOpcode() == ISD::FNEG) 1759 return DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV, 1760 DAG.getConstant(SignBit, DL, MVT::i64)); 1761 1762 assert(Op0.getOpcode() == ISD::FABS); 1763 return DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV, 1764 DAG.getConstant(~SignBit, DL, MVT::i64)); 1765 } 1766 case RISCVISD::GREVI: 1767 case RISCVISD::GORCI: 1768 return combineGREVI_GORCI(N, DCI.DAG); 1769 case ISD::OR: 1770 if (auto GREV = combineORToGREV(SDValue(N, 0), DCI.DAG, Subtarget)) 1771 return GREV; 1772 if (auto GORC = combineORToGORC(SDValue(N, 0), DCI.DAG, Subtarget)) 1773 return GORC; 1774 break; 1775 } 1776 1777 return SDValue(); 1778 } 1779 1780 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 1781 const SDNode *N, CombineLevel Level) const { 1782 // The following folds are only desirable if `(OP _, c1 << c2)` can be 1783 // materialised in fewer instructions than `(OP _, c1)`: 1784 // 1785 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 1786 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 1787 SDValue N0 = N->getOperand(0); 1788 EVT Ty = N0.getValueType(); 1789 if (Ty.isScalarInteger() && 1790 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 1791 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 1792 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 1793 if (C1 && C2) { 1794 APInt C1Int = C1->getAPIntValue(); 1795 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 1796 1797 // We can materialise `c1 << c2` into an add immediate, so it's "free", 1798 // and the combine should happen, to potentially allow further combines 1799 // later. 1800 if (ShiftedC1Int.getMinSignedBits() <= 64 && 1801 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 1802 return true; 1803 1804 // We can materialise `c1` in an add immediate, so it's "free", and the 1805 // combine should be prevented. 1806 if (C1Int.getMinSignedBits() <= 64 && 1807 isLegalAddImmediate(C1Int.getSExtValue())) 1808 return false; 1809 1810 // Neither constant will fit into an immediate, so find materialisation 1811 // costs. 1812 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 1813 Subtarget.is64Bit()); 1814 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 1815 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.is64Bit()); 1816 1817 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 1818 // combine should be prevented. 1819 if (C1Cost < ShiftedC1Cost) 1820 return false; 1821 } 1822 } 1823 return true; 1824 } 1825 1826 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 1827 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 1828 unsigned Depth) const { 1829 switch (Op.getOpcode()) { 1830 default: 1831 break; 1832 case RISCVISD::SLLW: 1833 case RISCVISD::SRAW: 1834 case RISCVISD::SRLW: 1835 case RISCVISD::DIVW: 1836 case RISCVISD::DIVUW: 1837 case RISCVISD::REMUW: 1838 case RISCVISD::ROLW: 1839 case RISCVISD::RORW: 1840 case RISCVISD::GREVIW: 1841 case RISCVISD::GORCIW: 1842 case RISCVISD::FSLW: 1843 case RISCVISD::FSRW: 1844 // TODO: As the result is sign-extended, this is conservatively correct. A 1845 // more precise answer could be calculated for SRAW depending on known 1846 // bits in the shift amount. 1847 return 33; 1848 case RISCVISD::VMV_X_S: 1849 // The number of sign bits of the scalar result is computed by obtaining the 1850 // element type of the input vector operand, substracting its width from the 1851 // XLEN, and then adding one (sign bit within the element type). 1852 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 1853 } 1854 1855 return 1; 1856 } 1857 1858 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 1859 MachineBasicBlock *BB) { 1860 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 1861 1862 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 1863 // Should the count have wrapped while it was being read, we need to try 1864 // again. 1865 // ... 1866 // read: 1867 // rdcycleh x3 # load high word of cycle 1868 // rdcycle x2 # load low word of cycle 1869 // rdcycleh x4 # load high word of cycle 1870 // bne x3, x4, read # check if high word reads match, otherwise try again 1871 // ... 1872 1873 MachineFunction &MF = *BB->getParent(); 1874 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 1875 MachineFunction::iterator It = ++BB->getIterator(); 1876 1877 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 1878 MF.insert(It, LoopMBB); 1879 1880 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 1881 MF.insert(It, DoneMBB); 1882 1883 // Transfer the remainder of BB and its successor edges to DoneMBB. 1884 DoneMBB->splice(DoneMBB->begin(), BB, 1885 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 1886 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 1887 1888 BB->addSuccessor(LoopMBB); 1889 1890 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 1891 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 1892 Register LoReg = MI.getOperand(0).getReg(); 1893 Register HiReg = MI.getOperand(1).getReg(); 1894 DebugLoc DL = MI.getDebugLoc(); 1895 1896 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 1897 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 1898 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 1899 .addReg(RISCV::X0); 1900 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 1901 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 1902 .addReg(RISCV::X0); 1903 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 1904 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 1905 .addReg(RISCV::X0); 1906 1907 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 1908 .addReg(HiReg) 1909 .addReg(ReadAgainReg) 1910 .addMBB(LoopMBB); 1911 1912 LoopMBB->addSuccessor(LoopMBB); 1913 LoopMBB->addSuccessor(DoneMBB); 1914 1915 MI.eraseFromParent(); 1916 1917 return DoneMBB; 1918 } 1919 1920 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 1921 MachineBasicBlock *BB) { 1922 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 1923 1924 MachineFunction &MF = *BB->getParent(); 1925 DebugLoc DL = MI.getDebugLoc(); 1926 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1927 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 1928 Register LoReg = MI.getOperand(0).getReg(); 1929 Register HiReg = MI.getOperand(1).getReg(); 1930 Register SrcReg = MI.getOperand(2).getReg(); 1931 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 1932 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 1933 1934 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 1935 RI); 1936 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 1937 MachineMemOperand *MMOLo = 1938 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 1939 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 1940 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 1941 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 1942 .addFrameIndex(FI) 1943 .addImm(0) 1944 .addMemOperand(MMOLo); 1945 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 1946 .addFrameIndex(FI) 1947 .addImm(4) 1948 .addMemOperand(MMOHi); 1949 MI.eraseFromParent(); // The pseudo instruction is gone now. 1950 return BB; 1951 } 1952 1953 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 1954 MachineBasicBlock *BB) { 1955 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 1956 "Unexpected instruction"); 1957 1958 MachineFunction &MF = *BB->getParent(); 1959 DebugLoc DL = MI.getDebugLoc(); 1960 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1961 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 1962 Register DstReg = MI.getOperand(0).getReg(); 1963 Register LoReg = MI.getOperand(1).getReg(); 1964 Register HiReg = MI.getOperand(2).getReg(); 1965 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 1966 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 1967 1968 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 1969 MachineMemOperand *MMOLo = 1970 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 1971 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 1972 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 1973 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 1974 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 1975 .addFrameIndex(FI) 1976 .addImm(0) 1977 .addMemOperand(MMOLo); 1978 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 1979 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 1980 .addFrameIndex(FI) 1981 .addImm(4) 1982 .addMemOperand(MMOHi); 1983 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 1984 MI.eraseFromParent(); // The pseudo instruction is gone now. 1985 return BB; 1986 } 1987 1988 static bool isSelectPseudo(MachineInstr &MI) { 1989 switch (MI.getOpcode()) { 1990 default: 1991 return false; 1992 case RISCV::Select_GPR_Using_CC_GPR: 1993 case RISCV::Select_FPR16_Using_CC_GPR: 1994 case RISCV::Select_FPR32_Using_CC_GPR: 1995 case RISCV::Select_FPR64_Using_CC_GPR: 1996 return true; 1997 } 1998 } 1999 2000 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 2001 MachineBasicBlock *BB) { 2002 // To "insert" Select_* instructions, we actually have to insert the triangle 2003 // control-flow pattern. The incoming instructions know the destination vreg 2004 // to set, the condition code register to branch on, the true/false values to 2005 // select between, and the condcode to use to select the appropriate branch. 2006 // 2007 // We produce the following control flow: 2008 // HeadMBB 2009 // | \ 2010 // | IfFalseMBB 2011 // | / 2012 // TailMBB 2013 // 2014 // When we find a sequence of selects we attempt to optimize their emission 2015 // by sharing the control flow. Currently we only handle cases where we have 2016 // multiple selects with the exact same condition (same LHS, RHS and CC). 2017 // The selects may be interleaved with other instructions if the other 2018 // instructions meet some requirements we deem safe: 2019 // - They are debug instructions. Otherwise, 2020 // - They do not have side-effects, do not access memory and their inputs do 2021 // not depend on the results of the select pseudo-instructions. 2022 // The TrueV/FalseV operands of the selects cannot depend on the result of 2023 // previous selects in the sequence. 2024 // These conditions could be further relaxed. See the X86 target for a 2025 // related approach and more information. 2026 Register LHS = MI.getOperand(1).getReg(); 2027 Register RHS = MI.getOperand(2).getReg(); 2028 auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm()); 2029 2030 SmallVector<MachineInstr *, 4> SelectDebugValues; 2031 SmallSet<Register, 4> SelectDests; 2032 SelectDests.insert(MI.getOperand(0).getReg()); 2033 2034 MachineInstr *LastSelectPseudo = &MI; 2035 2036 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 2037 SequenceMBBI != E; ++SequenceMBBI) { 2038 if (SequenceMBBI->isDebugInstr()) 2039 continue; 2040 else if (isSelectPseudo(*SequenceMBBI)) { 2041 if (SequenceMBBI->getOperand(1).getReg() != LHS || 2042 SequenceMBBI->getOperand(2).getReg() != RHS || 2043 SequenceMBBI->getOperand(3).getImm() != CC || 2044 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 2045 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 2046 break; 2047 LastSelectPseudo = &*SequenceMBBI; 2048 SequenceMBBI->collectDebugValues(SelectDebugValues); 2049 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 2050 } else { 2051 if (SequenceMBBI->hasUnmodeledSideEffects() || 2052 SequenceMBBI->mayLoadOrStore()) 2053 break; 2054 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 2055 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 2056 })) 2057 break; 2058 } 2059 } 2060 2061 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 2062 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 2063 DebugLoc DL = MI.getDebugLoc(); 2064 MachineFunction::iterator I = ++BB->getIterator(); 2065 2066 MachineBasicBlock *HeadMBB = BB; 2067 MachineFunction *F = BB->getParent(); 2068 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 2069 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 2070 2071 F->insert(I, IfFalseMBB); 2072 F->insert(I, TailMBB); 2073 2074 // Transfer debug instructions associated with the selects to TailMBB. 2075 for (MachineInstr *DebugInstr : SelectDebugValues) { 2076 TailMBB->push_back(DebugInstr->removeFromParent()); 2077 } 2078 2079 // Move all instructions after the sequence to TailMBB. 2080 TailMBB->splice(TailMBB->end(), HeadMBB, 2081 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 2082 // Update machine-CFG edges by transferring all successors of the current 2083 // block to the new block which will contain the Phi nodes for the selects. 2084 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 2085 // Set the successors for HeadMBB. 2086 HeadMBB->addSuccessor(IfFalseMBB); 2087 HeadMBB->addSuccessor(TailMBB); 2088 2089 // Insert appropriate branch. 2090 unsigned Opcode = getBranchOpcodeForIntCondCode(CC); 2091 2092 BuildMI(HeadMBB, DL, TII.get(Opcode)) 2093 .addReg(LHS) 2094 .addReg(RHS) 2095 .addMBB(TailMBB); 2096 2097 // IfFalseMBB just falls through to TailMBB. 2098 IfFalseMBB->addSuccessor(TailMBB); 2099 2100 // Create PHIs for all of the select pseudo-instructions. 2101 auto SelectMBBI = MI.getIterator(); 2102 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 2103 auto InsertionPoint = TailMBB->begin(); 2104 while (SelectMBBI != SelectEnd) { 2105 auto Next = std::next(SelectMBBI); 2106 if (isSelectPseudo(*SelectMBBI)) { 2107 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 2108 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 2109 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 2110 .addReg(SelectMBBI->getOperand(4).getReg()) 2111 .addMBB(HeadMBB) 2112 .addReg(SelectMBBI->getOperand(5).getReg()) 2113 .addMBB(IfFalseMBB); 2114 SelectMBBI->eraseFromParent(); 2115 } 2116 SelectMBBI = Next; 2117 } 2118 2119 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 2120 return TailMBB; 2121 } 2122 2123 static MachineBasicBlock *addVSetVL(MachineInstr &MI, MachineBasicBlock *BB, 2124 int VLIndex, unsigned SEWIndex, 2125 RISCVVLMUL VLMul, bool WritesElement0) { 2126 MachineFunction &MF = *BB->getParent(); 2127 DebugLoc DL = MI.getDebugLoc(); 2128 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 2129 2130 unsigned SEW = MI.getOperand(SEWIndex).getImm(); 2131 assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW"); 2132 RISCVVSEW ElementWidth = static_cast<RISCVVSEW>(Log2_32(SEW / 8)); 2133 2134 MachineRegisterInfo &MRI = MF.getRegInfo(); 2135 2136 // VL and VTYPE are alive here. 2137 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII.get(RISCV::PseudoVSETVLI)); 2138 2139 if (VLIndex >= 0) { 2140 // Set VL (rs1 != X0). 2141 Register DestReg = MRI.createVirtualRegister(&RISCV::GPRRegClass); 2142 MIB.addReg(DestReg, RegState::Define | RegState::Dead) 2143 .addReg(MI.getOperand(VLIndex).getReg()); 2144 } else 2145 // With no VL operator in the pseudo, do not modify VL (rd = X0, rs1 = X0). 2146 MIB.addReg(RISCV::X0, RegState::Define | RegState::Dead) 2147 .addReg(RISCV::X0, RegState::Kill); 2148 2149 // Default to tail agnostic unless the destination is tied to a source. In 2150 // that case the user would have some control over the tail values. The tail 2151 // policy is also ignored on instructions that only update element 0 like 2152 // vmv.s.x or reductions so use agnostic there to match the common case. 2153 // FIXME: This is conservatively correct, but we might want to detect that 2154 // the input is undefined. 2155 bool TailAgnostic = true; 2156 if (MI.isRegTiedToUseOperand(0) && !WritesElement0) 2157 TailAgnostic = false; 2158 2159 // For simplicity we reuse the vtype representation here. 2160 MIB.addImm(RISCVVType::encodeVTYPE(VLMul, ElementWidth, 2161 /*TailAgnostic*/ TailAgnostic, 2162 /*MaskAgnostic*/ false)); 2163 2164 // Remove (now) redundant operands from pseudo 2165 MI.getOperand(SEWIndex).setImm(-1); 2166 if (VLIndex >= 0) { 2167 MI.getOperand(VLIndex).setReg(RISCV::NoRegister); 2168 MI.getOperand(VLIndex).setIsKill(false); 2169 } 2170 2171 return BB; 2172 } 2173 2174 MachineBasicBlock * 2175 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 2176 MachineBasicBlock *BB) const { 2177 uint64_t TSFlags = MI.getDesc().TSFlags; 2178 2179 if (TSFlags & RISCVII::HasSEWOpMask) { 2180 unsigned NumOperands = MI.getNumExplicitOperands(); 2181 int VLIndex = (TSFlags & RISCVII::HasVLOpMask) ? NumOperands - 2 : -1; 2182 unsigned SEWIndex = NumOperands - 1; 2183 bool WritesElement0 = TSFlags & RISCVII::WritesElement0Mask; 2184 2185 RISCVVLMUL VLMul = static_cast<RISCVVLMUL>((TSFlags & RISCVII::VLMulMask) >> 2186 RISCVII::VLMulShift); 2187 return addVSetVL(MI, BB, VLIndex, SEWIndex, VLMul, WritesElement0); 2188 } 2189 2190 switch (MI.getOpcode()) { 2191 default: 2192 llvm_unreachable("Unexpected instr type to insert"); 2193 case RISCV::ReadCycleWide: 2194 assert(!Subtarget.is64Bit() && 2195 "ReadCycleWrite is only to be used on riscv32"); 2196 return emitReadCycleWidePseudo(MI, BB); 2197 case RISCV::Select_GPR_Using_CC_GPR: 2198 case RISCV::Select_FPR16_Using_CC_GPR: 2199 case RISCV::Select_FPR32_Using_CC_GPR: 2200 case RISCV::Select_FPR64_Using_CC_GPR: 2201 return emitSelectPseudo(MI, BB); 2202 case RISCV::BuildPairF64Pseudo: 2203 return emitBuildPairF64Pseudo(MI, BB); 2204 case RISCV::SplitF64Pseudo: 2205 return emitSplitF64Pseudo(MI, BB); 2206 } 2207 } 2208 2209 // Calling Convention Implementation. 2210 // The expectations for frontend ABI lowering vary from target to target. 2211 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 2212 // details, but this is a longer term goal. For now, we simply try to keep the 2213 // role of the frontend as simple and well-defined as possible. The rules can 2214 // be summarised as: 2215 // * Never split up large scalar arguments. We handle them here. 2216 // * If a hardfloat calling convention is being used, and the struct may be 2217 // passed in a pair of registers (fp+fp, int+fp), and both registers are 2218 // available, then pass as two separate arguments. If either the GPRs or FPRs 2219 // are exhausted, then pass according to the rule below. 2220 // * If a struct could never be passed in registers or directly in a stack 2221 // slot (as it is larger than 2*XLEN and the floating point rules don't 2222 // apply), then pass it using a pointer with the byval attribute. 2223 // * If a struct is less than 2*XLEN, then coerce to either a two-element 2224 // word-sized array or a 2*XLEN scalar (depending on alignment). 2225 // * The frontend can determine whether a struct is returned by reference or 2226 // not based on its size and fields. If it will be returned by reference, the 2227 // frontend must modify the prototype so a pointer with the sret annotation is 2228 // passed as the first argument. This is not necessary for large scalar 2229 // returns. 2230 // * Struct return values and varargs should be coerced to structs containing 2231 // register-size fields in the same situations they would be for fixed 2232 // arguments. 2233 2234 static const MCPhysReg ArgGPRs[] = { 2235 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 2236 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 2237 }; 2238 static const MCPhysReg ArgFPR16s[] = { 2239 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 2240 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 2241 }; 2242 static const MCPhysReg ArgFPR32s[] = { 2243 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 2244 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 2245 }; 2246 static const MCPhysReg ArgFPR64s[] = { 2247 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 2248 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 2249 }; 2250 // This is an interim calling convention and it may be changed in the future. 2251 static const MCPhysReg ArgVRs[] = { 2252 RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, RISCV::V20, 2253 RISCV::V21, RISCV::V22, RISCV::V23 2254 }; 2255 static const MCPhysReg ArgVRM2s[] = { 2256 RISCV::V16M2, RISCV::V18M2, RISCV::V20M2, RISCV::V22M2 2257 }; 2258 static const MCPhysReg ArgVRM4s[] = {RISCV::V16M4, RISCV::V20M4}; 2259 static const MCPhysReg ArgVRM8s[] = {RISCV::V16M8}; 2260 2261 // Pass a 2*XLEN argument that has been split into two XLEN values through 2262 // registers or the stack as necessary. 2263 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 2264 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 2265 MVT ValVT2, MVT LocVT2, 2266 ISD::ArgFlagsTy ArgFlags2) { 2267 unsigned XLenInBytes = XLen / 8; 2268 if (Register Reg = State.AllocateReg(ArgGPRs)) { 2269 // At least one half can be passed via register. 2270 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 2271 VA1.getLocVT(), CCValAssign::Full)); 2272 } else { 2273 // Both halves must be passed on the stack, with proper alignment. 2274 Align StackAlign = 2275 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 2276 State.addLoc( 2277 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 2278 State.AllocateStack(XLenInBytes, StackAlign), 2279 VA1.getLocVT(), CCValAssign::Full)); 2280 State.addLoc(CCValAssign::getMem( 2281 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 2282 LocVT2, CCValAssign::Full)); 2283 return false; 2284 } 2285 2286 if (Register Reg = State.AllocateReg(ArgGPRs)) { 2287 // The second half can also be passed via register. 2288 State.addLoc( 2289 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 2290 } else { 2291 // The second half is passed via the stack, without additional alignment. 2292 State.addLoc(CCValAssign::getMem( 2293 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 2294 LocVT2, CCValAssign::Full)); 2295 } 2296 2297 return false; 2298 } 2299 2300 // Implements the RISC-V calling convention. Returns true upon failure. 2301 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 2302 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 2303 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 2304 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 2305 Optional<unsigned> FirstMaskArgument) { 2306 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 2307 assert(XLen == 32 || XLen == 64); 2308 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 2309 2310 // Any return value split in to more than two values can't be returned 2311 // directly. 2312 if (IsRet && ValNo > 1) 2313 return true; 2314 2315 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 2316 // variadic argument, or if no F16/F32 argument registers are available. 2317 bool UseGPRForF16_F32 = true; 2318 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 2319 // variadic argument, or if no F64 argument registers are available. 2320 bool UseGPRForF64 = true; 2321 2322 switch (ABI) { 2323 default: 2324 llvm_unreachable("Unexpected ABI"); 2325 case RISCVABI::ABI_ILP32: 2326 case RISCVABI::ABI_LP64: 2327 break; 2328 case RISCVABI::ABI_ILP32F: 2329 case RISCVABI::ABI_LP64F: 2330 UseGPRForF16_F32 = !IsFixed; 2331 break; 2332 case RISCVABI::ABI_ILP32D: 2333 case RISCVABI::ABI_LP64D: 2334 UseGPRForF16_F32 = !IsFixed; 2335 UseGPRForF64 = !IsFixed; 2336 break; 2337 } 2338 2339 // FPR16, FPR32, and FPR64 alias each other. 2340 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 2341 UseGPRForF16_F32 = true; 2342 UseGPRForF64 = true; 2343 } 2344 2345 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 2346 // similar local variables rather than directly checking against the target 2347 // ABI. 2348 2349 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 2350 LocVT = XLenVT; 2351 LocInfo = CCValAssign::BCvt; 2352 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 2353 LocVT = MVT::i64; 2354 LocInfo = CCValAssign::BCvt; 2355 } 2356 2357 // If this is a variadic argument, the RISC-V calling convention requires 2358 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 2359 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 2360 // be used regardless of whether the original argument was split during 2361 // legalisation or not. The argument will not be passed by registers if the 2362 // original type is larger than 2*XLEN, so the register alignment rule does 2363 // not apply. 2364 unsigned TwoXLenInBytes = (2 * XLen) / 8; 2365 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 2366 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 2367 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 2368 // Skip 'odd' register if necessary. 2369 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 2370 State.AllocateReg(ArgGPRs); 2371 } 2372 2373 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 2374 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 2375 State.getPendingArgFlags(); 2376 2377 assert(PendingLocs.size() == PendingArgFlags.size() && 2378 "PendingLocs and PendingArgFlags out of sync"); 2379 2380 // Handle passing f64 on RV32D with a soft float ABI or when floating point 2381 // registers are exhausted. 2382 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 2383 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 2384 "Can't lower f64 if it is split"); 2385 // Depending on available argument GPRS, f64 may be passed in a pair of 2386 // GPRs, split between a GPR and the stack, or passed completely on the 2387 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 2388 // cases. 2389 Register Reg = State.AllocateReg(ArgGPRs); 2390 LocVT = MVT::i32; 2391 if (!Reg) { 2392 unsigned StackOffset = State.AllocateStack(8, Align(8)); 2393 State.addLoc( 2394 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 2395 return false; 2396 } 2397 if (!State.AllocateReg(ArgGPRs)) 2398 State.AllocateStack(4, Align(4)); 2399 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2400 return false; 2401 } 2402 2403 // Split arguments might be passed indirectly, so keep track of the pending 2404 // values. 2405 if (ArgFlags.isSplit() || !PendingLocs.empty()) { 2406 LocVT = XLenVT; 2407 LocInfo = CCValAssign::Indirect; 2408 PendingLocs.push_back( 2409 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 2410 PendingArgFlags.push_back(ArgFlags); 2411 if (!ArgFlags.isSplitEnd()) { 2412 return false; 2413 } 2414 } 2415 2416 // If the split argument only had two elements, it should be passed directly 2417 // in registers or on the stack. 2418 if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) { 2419 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 2420 // Apply the normal calling convention rules to the first half of the 2421 // split argument. 2422 CCValAssign VA = PendingLocs[0]; 2423 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 2424 PendingLocs.clear(); 2425 PendingArgFlags.clear(); 2426 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 2427 ArgFlags); 2428 } 2429 2430 // Allocate to a register if possible, or else a stack slot. 2431 Register Reg; 2432 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 2433 Reg = State.AllocateReg(ArgFPR16s); 2434 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 2435 Reg = State.AllocateReg(ArgFPR32s); 2436 else if (ValVT == MVT::f64 && !UseGPRForF64) 2437 Reg = State.AllocateReg(ArgFPR64s); 2438 else if (ValVT.isScalableVector()) { 2439 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 2440 if (RC == &RISCV::VRRegClass) { 2441 // Assign the first mask argument to V0. 2442 // This is an interim calling convention and it may be changed in the 2443 // future. 2444 if (FirstMaskArgument.hasValue() && 2445 ValNo == FirstMaskArgument.getValue()) { 2446 Reg = State.AllocateReg(RISCV::V0); 2447 } else { 2448 Reg = State.AllocateReg(ArgVRs); 2449 } 2450 } else if (RC == &RISCV::VRM2RegClass) { 2451 Reg = State.AllocateReg(ArgVRM2s); 2452 } else if (RC == &RISCV::VRM4RegClass) { 2453 Reg = State.AllocateReg(ArgVRM4s); 2454 } else if (RC == &RISCV::VRM8RegClass) { 2455 Reg = State.AllocateReg(ArgVRM8s); 2456 } else { 2457 llvm_unreachable("Unhandled class register for ValueType"); 2458 } 2459 if (!Reg) { 2460 LocInfo = CCValAssign::Indirect; 2461 // Try using a GPR to pass the address 2462 Reg = State.AllocateReg(ArgGPRs); 2463 LocVT = XLenVT; 2464 } 2465 } else 2466 Reg = State.AllocateReg(ArgGPRs); 2467 unsigned StackOffset = 2468 Reg ? 0 : State.AllocateStack(XLen / 8, Align(XLen / 8)); 2469 2470 // If we reach this point and PendingLocs is non-empty, we must be at the 2471 // end of a split argument that must be passed indirectly. 2472 if (!PendingLocs.empty()) { 2473 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 2474 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 2475 2476 for (auto &It : PendingLocs) { 2477 if (Reg) 2478 It.convertToReg(Reg); 2479 else 2480 It.convertToMem(StackOffset); 2481 State.addLoc(It); 2482 } 2483 PendingLocs.clear(); 2484 PendingArgFlags.clear(); 2485 return false; 2486 } 2487 2488 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 2489 (TLI.getSubtarget().hasStdExtV() && ValVT.isScalableVector())) && 2490 "Expected an XLenVT or scalable vector types at this stage"); 2491 2492 if (Reg) { 2493 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2494 return false; 2495 } 2496 2497 // When a floating-point value is passed on the stack, no bit-conversion is 2498 // needed. 2499 if (ValVT.isFloatingPoint()) { 2500 LocVT = ValVT; 2501 LocInfo = CCValAssign::Full; 2502 } 2503 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 2504 return false; 2505 } 2506 2507 template <typename ArgTy> 2508 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 2509 for (const auto &ArgIdx : enumerate(Args)) { 2510 MVT ArgVT = ArgIdx.value().VT; 2511 if (ArgVT.isScalableVector() && 2512 ArgVT.getVectorElementType().SimpleTy == MVT::i1) 2513 return ArgIdx.index(); 2514 } 2515 return None; 2516 } 2517 2518 void RISCVTargetLowering::analyzeInputArgs( 2519 MachineFunction &MF, CCState &CCInfo, 2520 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const { 2521 unsigned NumArgs = Ins.size(); 2522 FunctionType *FType = MF.getFunction().getFunctionType(); 2523 2524 Optional<unsigned> FirstMaskArgument; 2525 if (Subtarget.hasStdExtV()) 2526 FirstMaskArgument = preAssignMask(Ins); 2527 2528 for (unsigned i = 0; i != NumArgs; ++i) { 2529 MVT ArgVT = Ins[i].VT; 2530 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 2531 2532 Type *ArgTy = nullptr; 2533 if (IsRet) 2534 ArgTy = FType->getReturnType(); 2535 else if (Ins[i].isOrigArg()) 2536 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 2537 2538 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 2539 if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 2540 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 2541 FirstMaskArgument)) { 2542 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 2543 << EVT(ArgVT).getEVTString() << '\n'); 2544 llvm_unreachable(nullptr); 2545 } 2546 } 2547 } 2548 2549 void RISCVTargetLowering::analyzeOutputArgs( 2550 MachineFunction &MF, CCState &CCInfo, 2551 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 2552 CallLoweringInfo *CLI) const { 2553 unsigned NumArgs = Outs.size(); 2554 2555 Optional<unsigned> FirstMaskArgument; 2556 if (Subtarget.hasStdExtV()) 2557 FirstMaskArgument = preAssignMask(Outs); 2558 2559 for (unsigned i = 0; i != NumArgs; i++) { 2560 MVT ArgVT = Outs[i].VT; 2561 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 2562 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 2563 2564 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 2565 if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 2566 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 2567 FirstMaskArgument)) { 2568 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 2569 << EVT(ArgVT).getEVTString() << "\n"); 2570 llvm_unreachable(nullptr); 2571 } 2572 } 2573 } 2574 2575 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 2576 // values. 2577 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 2578 const CCValAssign &VA, const SDLoc &DL) { 2579 switch (VA.getLocInfo()) { 2580 default: 2581 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 2582 case CCValAssign::Full: 2583 break; 2584 case CCValAssign::BCvt: 2585 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 2586 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 2587 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 2588 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 2589 else 2590 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2591 break; 2592 } 2593 return Val; 2594 } 2595 2596 // The caller is responsible for loading the full value if the argument is 2597 // passed with CCValAssign::Indirect. 2598 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 2599 const CCValAssign &VA, const SDLoc &DL, 2600 const RISCVTargetLowering &TLI) { 2601 MachineFunction &MF = DAG.getMachineFunction(); 2602 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 2603 EVT LocVT = VA.getLocVT(); 2604 SDValue Val; 2605 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 2606 Register VReg = RegInfo.createVirtualRegister(RC); 2607 RegInfo.addLiveIn(VA.getLocReg(), VReg); 2608 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 2609 2610 if (VA.getLocInfo() == CCValAssign::Indirect) 2611 return Val; 2612 2613 return convertLocVTToValVT(DAG, Val, VA, DL); 2614 } 2615 2616 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 2617 const CCValAssign &VA, const SDLoc &DL) { 2618 EVT LocVT = VA.getLocVT(); 2619 2620 switch (VA.getLocInfo()) { 2621 default: 2622 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 2623 case CCValAssign::Full: 2624 break; 2625 case CCValAssign::BCvt: 2626 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 2627 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 2628 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 2629 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 2630 else 2631 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 2632 break; 2633 } 2634 return Val; 2635 } 2636 2637 // The caller is responsible for loading the full value if the argument is 2638 // passed with CCValAssign::Indirect. 2639 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 2640 const CCValAssign &VA, const SDLoc &DL) { 2641 MachineFunction &MF = DAG.getMachineFunction(); 2642 MachineFrameInfo &MFI = MF.getFrameInfo(); 2643 EVT LocVT = VA.getLocVT(); 2644 EVT ValVT = VA.getValVT(); 2645 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 2646 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8, 2647 VA.getLocMemOffset(), /*Immutable=*/true); 2648 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2649 SDValue Val; 2650 2651 ISD::LoadExtType ExtType; 2652 switch (VA.getLocInfo()) { 2653 default: 2654 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 2655 case CCValAssign::Full: 2656 case CCValAssign::Indirect: 2657 case CCValAssign::BCvt: 2658 ExtType = ISD::NON_EXTLOAD; 2659 break; 2660 } 2661 Val = DAG.getExtLoad( 2662 ExtType, DL, LocVT, Chain, FIN, 2663 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 2664 return Val; 2665 } 2666 2667 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 2668 const CCValAssign &VA, const SDLoc &DL) { 2669 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 2670 "Unexpected VA"); 2671 MachineFunction &MF = DAG.getMachineFunction(); 2672 MachineFrameInfo &MFI = MF.getFrameInfo(); 2673 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 2674 2675 if (VA.isMemLoc()) { 2676 // f64 is passed on the stack. 2677 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 2678 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 2679 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 2680 MachinePointerInfo::getFixedStack(MF, FI)); 2681 } 2682 2683 assert(VA.isRegLoc() && "Expected register VA assignment"); 2684 2685 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 2686 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 2687 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 2688 SDValue Hi; 2689 if (VA.getLocReg() == RISCV::X17) { 2690 // Second half of f64 is passed on the stack. 2691 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 2692 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 2693 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 2694 MachinePointerInfo::getFixedStack(MF, FI)); 2695 } else { 2696 // Second half of f64 is passed in another GPR. 2697 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 2698 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 2699 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 2700 } 2701 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 2702 } 2703 2704 // FastCC has less than 1% performance improvement for some particular 2705 // benchmark. But theoretically, it may has benenfit for some cases. 2706 static bool CC_RISCV_FastCC(unsigned ValNo, MVT ValVT, MVT LocVT, 2707 CCValAssign::LocInfo LocInfo, 2708 ISD::ArgFlagsTy ArgFlags, CCState &State) { 2709 2710 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 2711 // X5 and X6 might be used for save-restore libcall. 2712 static const MCPhysReg GPRList[] = { 2713 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 2714 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 2715 RISCV::X29, RISCV::X30, RISCV::X31}; 2716 if (unsigned Reg = State.AllocateReg(GPRList)) { 2717 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2718 return false; 2719 } 2720 } 2721 2722 if (LocVT == MVT::f16) { 2723 static const MCPhysReg FPR16List[] = { 2724 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 2725 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 2726 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 2727 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 2728 if (unsigned Reg = State.AllocateReg(FPR16List)) { 2729 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2730 return false; 2731 } 2732 } 2733 2734 if (LocVT == MVT::f32) { 2735 static const MCPhysReg FPR32List[] = { 2736 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 2737 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 2738 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 2739 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 2740 if (unsigned Reg = State.AllocateReg(FPR32List)) { 2741 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2742 return false; 2743 } 2744 } 2745 2746 if (LocVT == MVT::f64) { 2747 static const MCPhysReg FPR64List[] = { 2748 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 2749 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 2750 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 2751 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 2752 if (unsigned Reg = State.AllocateReg(FPR64List)) { 2753 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2754 return false; 2755 } 2756 } 2757 2758 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 2759 unsigned Offset4 = State.AllocateStack(4, Align(4)); 2760 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 2761 return false; 2762 } 2763 2764 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 2765 unsigned Offset5 = State.AllocateStack(8, Align(8)); 2766 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 2767 return false; 2768 } 2769 2770 return true; // CC didn't match. 2771 } 2772 2773 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 2774 CCValAssign::LocInfo LocInfo, 2775 ISD::ArgFlagsTy ArgFlags, CCState &State) { 2776 2777 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 2778 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 2779 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 2780 static const MCPhysReg GPRList[] = { 2781 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 2782 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 2783 if (unsigned Reg = State.AllocateReg(GPRList)) { 2784 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2785 return false; 2786 } 2787 } 2788 2789 if (LocVT == MVT::f32) { 2790 // Pass in STG registers: F1, ..., F6 2791 // fs0 ... fs5 2792 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 2793 RISCV::F18_F, RISCV::F19_F, 2794 RISCV::F20_F, RISCV::F21_F}; 2795 if (unsigned Reg = State.AllocateReg(FPR32List)) { 2796 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2797 return false; 2798 } 2799 } 2800 2801 if (LocVT == MVT::f64) { 2802 // Pass in STG registers: D1, ..., D6 2803 // fs6 ... fs11 2804 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 2805 RISCV::F24_D, RISCV::F25_D, 2806 RISCV::F26_D, RISCV::F27_D}; 2807 if (unsigned Reg = State.AllocateReg(FPR64List)) { 2808 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2809 return false; 2810 } 2811 } 2812 2813 report_fatal_error("No registers left in GHC calling convention"); 2814 return true; 2815 } 2816 2817 // Transform physical registers into virtual registers. 2818 SDValue RISCVTargetLowering::LowerFormalArguments( 2819 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 2820 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2821 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2822 2823 MachineFunction &MF = DAG.getMachineFunction(); 2824 2825 switch (CallConv) { 2826 default: 2827 report_fatal_error("Unsupported calling convention"); 2828 case CallingConv::C: 2829 case CallingConv::Fast: 2830 break; 2831 case CallingConv::GHC: 2832 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 2833 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 2834 report_fatal_error( 2835 "GHC calling convention requires the F and D instruction set extensions"); 2836 } 2837 2838 const Function &Func = MF.getFunction(); 2839 if (Func.hasFnAttribute("interrupt")) { 2840 if (!Func.arg_empty()) 2841 report_fatal_error( 2842 "Functions with the interrupt attribute cannot have arguments!"); 2843 2844 StringRef Kind = 2845 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 2846 2847 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 2848 report_fatal_error( 2849 "Function interrupt attribute argument not supported!"); 2850 } 2851 2852 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2853 MVT XLenVT = Subtarget.getXLenVT(); 2854 unsigned XLenInBytes = Subtarget.getXLen() / 8; 2855 // Used with vargs to acumulate store chains. 2856 std::vector<SDValue> OutChains; 2857 2858 // Assign locations to all of the incoming arguments. 2859 SmallVector<CCValAssign, 16> ArgLocs; 2860 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2861 2862 if (CallConv == CallingConv::Fast) 2863 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_FastCC); 2864 else if (CallConv == CallingConv::GHC) 2865 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 2866 else 2867 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false); 2868 2869 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2870 CCValAssign &VA = ArgLocs[i]; 2871 SDValue ArgValue; 2872 // Passing f64 on RV32D with a soft float ABI must be handled as a special 2873 // case. 2874 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 2875 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 2876 else if (VA.isRegLoc()) 2877 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 2878 else 2879 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 2880 2881 if (VA.getLocInfo() == CCValAssign::Indirect) { 2882 // If the original argument was split and passed by reference (e.g. i128 2883 // on RV32), we need to load all parts of it here (using the same 2884 // address). 2885 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 2886 MachinePointerInfo())); 2887 unsigned ArgIndex = Ins[i].OrigArgIndex; 2888 assert(Ins[i].PartOffset == 0); 2889 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 2890 CCValAssign &PartVA = ArgLocs[i + 1]; 2891 unsigned PartOffset = Ins[i + 1].PartOffset; 2892 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, 2893 DAG.getIntPtrConstant(PartOffset, DL)); 2894 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 2895 MachinePointerInfo())); 2896 ++i; 2897 } 2898 continue; 2899 } 2900 InVals.push_back(ArgValue); 2901 } 2902 2903 if (IsVarArg) { 2904 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 2905 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 2906 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 2907 MachineFrameInfo &MFI = MF.getFrameInfo(); 2908 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 2909 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 2910 2911 // Offset of the first variable argument from stack pointer, and size of 2912 // the vararg save area. For now, the varargs save area is either zero or 2913 // large enough to hold a0-a7. 2914 int VaArgOffset, VarArgsSaveSize; 2915 2916 // If all registers are allocated, then all varargs must be passed on the 2917 // stack and we don't need to save any argregs. 2918 if (ArgRegs.size() == Idx) { 2919 VaArgOffset = CCInfo.getNextStackOffset(); 2920 VarArgsSaveSize = 0; 2921 } else { 2922 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 2923 VaArgOffset = -VarArgsSaveSize; 2924 } 2925 2926 // Record the frame index of the first variable argument 2927 // which is a value necessary to VASTART. 2928 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 2929 RVFI->setVarArgsFrameIndex(FI); 2930 2931 // If saving an odd number of registers then create an extra stack slot to 2932 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 2933 // offsets to even-numbered registered remain 2*XLEN-aligned. 2934 if (Idx % 2) { 2935 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 2936 VarArgsSaveSize += XLenInBytes; 2937 } 2938 2939 // Copy the integer registers that may have been used for passing varargs 2940 // to the vararg save area. 2941 for (unsigned I = Idx; I < ArgRegs.size(); 2942 ++I, VaArgOffset += XLenInBytes) { 2943 const Register Reg = RegInfo.createVirtualRegister(RC); 2944 RegInfo.addLiveIn(ArgRegs[I], Reg); 2945 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 2946 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 2947 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2948 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 2949 MachinePointerInfo::getFixedStack(MF, FI)); 2950 cast<StoreSDNode>(Store.getNode()) 2951 ->getMemOperand() 2952 ->setValue((Value *)nullptr); 2953 OutChains.push_back(Store); 2954 } 2955 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 2956 } 2957 2958 // All stores are grouped in one node to allow the matching between 2959 // the size of Ins and InVals. This only happens for vararg functions. 2960 if (!OutChains.empty()) { 2961 OutChains.push_back(Chain); 2962 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 2963 } 2964 2965 return Chain; 2966 } 2967 2968 /// isEligibleForTailCallOptimization - Check whether the call is eligible 2969 /// for tail call optimization. 2970 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 2971 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 2972 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 2973 const SmallVector<CCValAssign, 16> &ArgLocs) const { 2974 2975 auto &Callee = CLI.Callee; 2976 auto CalleeCC = CLI.CallConv; 2977 auto &Outs = CLI.Outs; 2978 auto &Caller = MF.getFunction(); 2979 auto CallerCC = Caller.getCallingConv(); 2980 2981 // Exception-handling functions need a special set of instructions to 2982 // indicate a return to the hardware. Tail-calling another function would 2983 // probably break this. 2984 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 2985 // should be expanded as new function attributes are introduced. 2986 if (Caller.hasFnAttribute("interrupt")) 2987 return false; 2988 2989 // Do not tail call opt if the stack is used to pass parameters. 2990 if (CCInfo.getNextStackOffset() != 0) 2991 return false; 2992 2993 // Do not tail call opt if any parameters need to be passed indirectly. 2994 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 2995 // passed indirectly. So the address of the value will be passed in a 2996 // register, or if not available, then the address is put on the stack. In 2997 // order to pass indirectly, space on the stack often needs to be allocated 2998 // in order to store the value. In this case the CCInfo.getNextStackOffset() 2999 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 3000 // are passed CCValAssign::Indirect. 3001 for (auto &VA : ArgLocs) 3002 if (VA.getLocInfo() == CCValAssign::Indirect) 3003 return false; 3004 3005 // Do not tail call opt if either caller or callee uses struct return 3006 // semantics. 3007 auto IsCallerStructRet = Caller.hasStructRetAttr(); 3008 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 3009 if (IsCallerStructRet || IsCalleeStructRet) 3010 return false; 3011 3012 // Externally-defined functions with weak linkage should not be 3013 // tail-called. The behaviour of branch instructions in this situation (as 3014 // used for tail calls) is implementation-defined, so we cannot rely on the 3015 // linker replacing the tail call with a return. 3016 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3017 const GlobalValue *GV = G->getGlobal(); 3018 if (GV->hasExternalWeakLinkage()) 3019 return false; 3020 } 3021 3022 // The callee has to preserve all registers the caller needs to preserve. 3023 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 3024 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3025 if (CalleeCC != CallerCC) { 3026 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3027 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3028 return false; 3029 } 3030 3031 // Byval parameters hand the function a pointer directly into the stack area 3032 // we want to reuse during a tail call. Working around this *is* possible 3033 // but less efficient and uglier in LowerCall. 3034 for (auto &Arg : Outs) 3035 if (Arg.Flags.isByVal()) 3036 return false; 3037 3038 return true; 3039 } 3040 3041 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 3042 // and output parameter nodes. 3043 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 3044 SmallVectorImpl<SDValue> &InVals) const { 3045 SelectionDAG &DAG = CLI.DAG; 3046 SDLoc &DL = CLI.DL; 3047 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 3048 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 3049 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 3050 SDValue Chain = CLI.Chain; 3051 SDValue Callee = CLI.Callee; 3052 bool &IsTailCall = CLI.IsTailCall; 3053 CallingConv::ID CallConv = CLI.CallConv; 3054 bool IsVarArg = CLI.IsVarArg; 3055 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3056 MVT XLenVT = Subtarget.getXLenVT(); 3057 3058 MachineFunction &MF = DAG.getMachineFunction(); 3059 3060 // Analyze the operands of the call, assigning locations to each operand. 3061 SmallVector<CCValAssign, 16> ArgLocs; 3062 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3063 3064 if (CallConv == CallingConv::Fast) 3065 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_FastCC); 3066 else if (CallConv == CallingConv::GHC) 3067 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 3068 else 3069 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI); 3070 3071 // Check if it's really possible to do a tail call. 3072 if (IsTailCall) 3073 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 3074 3075 if (IsTailCall) 3076 ++NumTailCalls; 3077 else if (CLI.CB && CLI.CB->isMustTailCall()) 3078 report_fatal_error("failed to perform tail call elimination on a call " 3079 "site marked musttail"); 3080 3081 // Get a count of how many bytes are to be pushed on the stack. 3082 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 3083 3084 // Create local copies for byval args 3085 SmallVector<SDValue, 8> ByValArgs; 3086 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 3087 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3088 if (!Flags.isByVal()) 3089 continue; 3090 3091 SDValue Arg = OutVals[i]; 3092 unsigned Size = Flags.getByValSize(); 3093 Align Alignment = Flags.getNonZeroByValAlign(); 3094 3095 int FI = 3096 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 3097 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3098 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 3099 3100 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 3101 /*IsVolatile=*/false, 3102 /*AlwaysInline=*/false, IsTailCall, 3103 MachinePointerInfo(), MachinePointerInfo()); 3104 ByValArgs.push_back(FIPtr); 3105 } 3106 3107 if (!IsTailCall) 3108 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 3109 3110 // Copy argument values to their designated locations. 3111 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 3112 SmallVector<SDValue, 8> MemOpChains; 3113 SDValue StackPtr; 3114 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 3115 CCValAssign &VA = ArgLocs[i]; 3116 SDValue ArgValue = OutVals[i]; 3117 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3118 3119 // Handle passing f64 on RV32D with a soft float ABI as a special case. 3120 bool IsF64OnRV32DSoftABI = 3121 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 3122 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 3123 SDValue SplitF64 = DAG.getNode( 3124 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 3125 SDValue Lo = SplitF64.getValue(0); 3126 SDValue Hi = SplitF64.getValue(1); 3127 3128 Register RegLo = VA.getLocReg(); 3129 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 3130 3131 if (RegLo == RISCV::X17) { 3132 // Second half of f64 is passed on the stack. 3133 // Work out the address of the stack slot. 3134 if (!StackPtr.getNode()) 3135 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 3136 // Emit the store. 3137 MemOpChains.push_back( 3138 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 3139 } else { 3140 // Second half of f64 is passed in another GPR. 3141 assert(RegLo < RISCV::X31 && "Invalid register pair"); 3142 Register RegHigh = RegLo + 1; 3143 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 3144 } 3145 continue; 3146 } 3147 3148 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 3149 // as any other MemLoc. 3150 3151 // Promote the value if needed. 3152 // For now, only handle fully promoted and indirect arguments. 3153 if (VA.getLocInfo() == CCValAssign::Indirect) { 3154 // Store the argument in a stack slot and pass its address. 3155 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT); 3156 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 3157 MemOpChains.push_back( 3158 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 3159 MachinePointerInfo::getFixedStack(MF, FI))); 3160 // If the original argument was split (e.g. i128), we need 3161 // to store all parts of it here (and pass just one address). 3162 unsigned ArgIndex = Outs[i].OrigArgIndex; 3163 assert(Outs[i].PartOffset == 0); 3164 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 3165 SDValue PartValue = OutVals[i + 1]; 3166 unsigned PartOffset = Outs[i + 1].PartOffset; 3167 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, 3168 DAG.getIntPtrConstant(PartOffset, DL)); 3169 MemOpChains.push_back( 3170 DAG.getStore(Chain, DL, PartValue, Address, 3171 MachinePointerInfo::getFixedStack(MF, FI))); 3172 ++i; 3173 } 3174 ArgValue = SpillSlot; 3175 } else { 3176 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL); 3177 } 3178 3179 // Use local copy if it is a byval arg. 3180 if (Flags.isByVal()) 3181 ArgValue = ByValArgs[j++]; 3182 3183 if (VA.isRegLoc()) { 3184 // Queue up the argument copies and emit them at the end. 3185 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 3186 } else { 3187 assert(VA.isMemLoc() && "Argument not register or memory"); 3188 assert(!IsTailCall && "Tail call not allowed if stack is used " 3189 "for passing parameters"); 3190 3191 // Work out the address of the stack slot. 3192 if (!StackPtr.getNode()) 3193 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 3194 SDValue Address = 3195 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 3196 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 3197 3198 // Emit the store. 3199 MemOpChains.push_back( 3200 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 3201 } 3202 } 3203 3204 // Join the stores, which are independent of one another. 3205 if (!MemOpChains.empty()) 3206 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3207 3208 SDValue Glue; 3209 3210 // Build a sequence of copy-to-reg nodes, chained and glued together. 3211 for (auto &Reg : RegsToPass) { 3212 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 3213 Glue = Chain.getValue(1); 3214 } 3215 3216 // Validate that none of the argument registers have been marked as 3217 // reserved, if so report an error. Do the same for the return address if this 3218 // is not a tailcall. 3219 validateCCReservedRegs(RegsToPass, MF); 3220 if (!IsTailCall && 3221 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 3222 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 3223 MF.getFunction(), 3224 "Return address register required, but has been reserved."}); 3225 3226 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 3227 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 3228 // split it and then direct call can be matched by PseudoCALL. 3229 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 3230 const GlobalValue *GV = S->getGlobal(); 3231 3232 unsigned OpFlags = RISCVII::MO_CALL; 3233 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 3234 OpFlags = RISCVII::MO_PLT; 3235 3236 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 3237 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3238 unsigned OpFlags = RISCVII::MO_CALL; 3239 3240 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 3241 nullptr)) 3242 OpFlags = RISCVII::MO_PLT; 3243 3244 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 3245 } 3246 3247 // The first call operand is the chain and the second is the target address. 3248 SmallVector<SDValue, 8> Ops; 3249 Ops.push_back(Chain); 3250 Ops.push_back(Callee); 3251 3252 // Add argument registers to the end of the list so that they are 3253 // known live into the call. 3254 for (auto &Reg : RegsToPass) 3255 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 3256 3257 if (!IsTailCall) { 3258 // Add a register mask operand representing the call-preserved registers. 3259 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 3260 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3261 assert(Mask && "Missing call preserved mask for calling convention"); 3262 Ops.push_back(DAG.getRegisterMask(Mask)); 3263 } 3264 3265 // Glue the call to the argument copies, if any. 3266 if (Glue.getNode()) 3267 Ops.push_back(Glue); 3268 3269 // Emit the call. 3270 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3271 3272 if (IsTailCall) { 3273 MF.getFrameInfo().setHasTailCall(); 3274 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 3275 } 3276 3277 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 3278 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 3279 Glue = Chain.getValue(1); 3280 3281 // Mark the end of the call, which is glued to the call itself. 3282 Chain = DAG.getCALLSEQ_END(Chain, 3283 DAG.getConstant(NumBytes, DL, PtrVT, true), 3284 DAG.getConstant(0, DL, PtrVT, true), 3285 Glue, DL); 3286 Glue = Chain.getValue(1); 3287 3288 // Assign locations to each value returned by this call. 3289 SmallVector<CCValAssign, 16> RVLocs; 3290 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 3291 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true); 3292 3293 // Copy all of the result registers out of their specified physreg. 3294 for (auto &VA : RVLocs) { 3295 // Copy the value out 3296 SDValue RetValue = 3297 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 3298 // Glue the RetValue to the end of the call sequence 3299 Chain = RetValue.getValue(1); 3300 Glue = RetValue.getValue(2); 3301 3302 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 3303 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 3304 SDValue RetValue2 = 3305 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 3306 Chain = RetValue2.getValue(1); 3307 Glue = RetValue2.getValue(2); 3308 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 3309 RetValue2); 3310 } 3311 3312 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL); 3313 3314 InVals.push_back(RetValue); 3315 } 3316 3317 return Chain; 3318 } 3319 3320 bool RISCVTargetLowering::CanLowerReturn( 3321 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 3322 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 3323 SmallVector<CCValAssign, 16> RVLocs; 3324 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 3325 3326 Optional<unsigned> FirstMaskArgument; 3327 if (Subtarget.hasStdExtV()) 3328 FirstMaskArgument = preAssignMask(Outs); 3329 3330 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 3331 MVT VT = Outs[i].VT; 3332 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3333 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 3334 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 3335 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 3336 *this, FirstMaskArgument)) 3337 return false; 3338 } 3339 return true; 3340 } 3341 3342 SDValue 3343 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 3344 bool IsVarArg, 3345 const SmallVectorImpl<ISD::OutputArg> &Outs, 3346 const SmallVectorImpl<SDValue> &OutVals, 3347 const SDLoc &DL, SelectionDAG &DAG) const { 3348 const MachineFunction &MF = DAG.getMachineFunction(); 3349 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 3350 3351 // Stores the assignment of the return value to a location. 3352 SmallVector<CCValAssign, 16> RVLocs; 3353 3354 // Info about the registers and stack slot. 3355 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 3356 *DAG.getContext()); 3357 3358 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 3359 nullptr); 3360 3361 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 3362 report_fatal_error("GHC functions return void only"); 3363 3364 SDValue Glue; 3365 SmallVector<SDValue, 4> RetOps(1, Chain); 3366 3367 // Copy the result values into the output registers. 3368 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 3369 SDValue Val = OutVals[i]; 3370 CCValAssign &VA = RVLocs[i]; 3371 assert(VA.isRegLoc() && "Can only return in registers!"); 3372 3373 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 3374 // Handle returning f64 on RV32D with a soft float ABI. 3375 assert(VA.isRegLoc() && "Expected return via registers"); 3376 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 3377 DAG.getVTList(MVT::i32, MVT::i32), Val); 3378 SDValue Lo = SplitF64.getValue(0); 3379 SDValue Hi = SplitF64.getValue(1); 3380 Register RegLo = VA.getLocReg(); 3381 assert(RegLo < RISCV::X31 && "Invalid register pair"); 3382 Register RegHi = RegLo + 1; 3383 3384 if (STI.isRegisterReservedByUser(RegLo) || 3385 STI.isRegisterReservedByUser(RegHi)) 3386 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 3387 MF.getFunction(), 3388 "Return value register required, but has been reserved."}); 3389 3390 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 3391 Glue = Chain.getValue(1); 3392 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 3393 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 3394 Glue = Chain.getValue(1); 3395 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 3396 } else { 3397 // Handle a 'normal' return. 3398 Val = convertValVTToLocVT(DAG, Val, VA, DL); 3399 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 3400 3401 if (STI.isRegisterReservedByUser(VA.getLocReg())) 3402 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 3403 MF.getFunction(), 3404 "Return value register required, but has been reserved."}); 3405 3406 // Guarantee that all emitted copies are stuck together. 3407 Glue = Chain.getValue(1); 3408 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3409 } 3410 } 3411 3412 RetOps[0] = Chain; // Update chain. 3413 3414 // Add the glue node if we have it. 3415 if (Glue.getNode()) { 3416 RetOps.push_back(Glue); 3417 } 3418 3419 // Interrupt service routines use different return instructions. 3420 const Function &Func = DAG.getMachineFunction().getFunction(); 3421 if (Func.hasFnAttribute("interrupt")) { 3422 if (!Func.getReturnType()->isVoidTy()) 3423 report_fatal_error( 3424 "Functions with the interrupt attribute must have void return type!"); 3425 3426 MachineFunction &MF = DAG.getMachineFunction(); 3427 StringRef Kind = 3428 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 3429 3430 unsigned RetOpc; 3431 if (Kind == "user") 3432 RetOpc = RISCVISD::URET_FLAG; 3433 else if (Kind == "supervisor") 3434 RetOpc = RISCVISD::SRET_FLAG; 3435 else 3436 RetOpc = RISCVISD::MRET_FLAG; 3437 3438 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 3439 } 3440 3441 return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps); 3442 } 3443 3444 void RISCVTargetLowering::validateCCReservedRegs( 3445 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 3446 MachineFunction &MF) const { 3447 const Function &F = MF.getFunction(); 3448 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 3449 3450 if (llvm::any_of(Regs, [&STI](auto Reg) { 3451 return STI.isRegisterReservedByUser(Reg.first); 3452 })) 3453 F.getContext().diagnose(DiagnosticInfoUnsupported{ 3454 F, "Argument register required, but has been reserved."}); 3455 } 3456 3457 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3458 return CI->isTailCall(); 3459 } 3460 3461 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 3462 #define NODE_NAME_CASE(NODE) \ 3463 case RISCVISD::NODE: \ 3464 return "RISCVISD::" #NODE; 3465 // clang-format off 3466 switch ((RISCVISD::NodeType)Opcode) { 3467 case RISCVISD::FIRST_NUMBER: 3468 break; 3469 NODE_NAME_CASE(RET_FLAG) 3470 NODE_NAME_CASE(URET_FLAG) 3471 NODE_NAME_CASE(SRET_FLAG) 3472 NODE_NAME_CASE(MRET_FLAG) 3473 NODE_NAME_CASE(CALL) 3474 NODE_NAME_CASE(SELECT_CC) 3475 NODE_NAME_CASE(BuildPairF64) 3476 NODE_NAME_CASE(SplitF64) 3477 NODE_NAME_CASE(TAIL) 3478 NODE_NAME_CASE(SLLW) 3479 NODE_NAME_CASE(SRAW) 3480 NODE_NAME_CASE(SRLW) 3481 NODE_NAME_CASE(DIVW) 3482 NODE_NAME_CASE(DIVUW) 3483 NODE_NAME_CASE(REMUW) 3484 NODE_NAME_CASE(ROLW) 3485 NODE_NAME_CASE(RORW) 3486 NODE_NAME_CASE(FSLW) 3487 NODE_NAME_CASE(FSRW) 3488 NODE_NAME_CASE(FMV_H_X) 3489 NODE_NAME_CASE(FMV_X_ANYEXTH) 3490 NODE_NAME_CASE(FMV_W_X_RV64) 3491 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 3492 NODE_NAME_CASE(READ_CYCLE_WIDE) 3493 NODE_NAME_CASE(GREVI) 3494 NODE_NAME_CASE(GREVIW) 3495 NODE_NAME_CASE(GORCI) 3496 NODE_NAME_CASE(GORCIW) 3497 NODE_NAME_CASE(VMV_X_S) 3498 NODE_NAME_CASE(SPLAT_VECTOR_I64) 3499 } 3500 // clang-format on 3501 return nullptr; 3502 #undef NODE_NAME_CASE 3503 } 3504 3505 /// getConstraintType - Given a constraint letter, return the type of 3506 /// constraint it is for this target. 3507 RISCVTargetLowering::ConstraintType 3508 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 3509 if (Constraint.size() == 1) { 3510 switch (Constraint[0]) { 3511 default: 3512 break; 3513 case 'f': 3514 return C_RegisterClass; 3515 case 'I': 3516 case 'J': 3517 case 'K': 3518 return C_Immediate; 3519 case 'A': 3520 return C_Memory; 3521 } 3522 } 3523 return TargetLowering::getConstraintType(Constraint); 3524 } 3525 3526 std::pair<unsigned, const TargetRegisterClass *> 3527 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 3528 StringRef Constraint, 3529 MVT VT) const { 3530 // First, see if this is a constraint that directly corresponds to a 3531 // RISCV register class. 3532 if (Constraint.size() == 1) { 3533 switch (Constraint[0]) { 3534 case 'r': 3535 return std::make_pair(0U, &RISCV::GPRRegClass); 3536 case 'f': 3537 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 3538 return std::make_pair(0U, &RISCV::FPR16RegClass); 3539 if (Subtarget.hasStdExtF() && VT == MVT::f32) 3540 return std::make_pair(0U, &RISCV::FPR32RegClass); 3541 if (Subtarget.hasStdExtD() && VT == MVT::f64) 3542 return std::make_pair(0U, &RISCV::FPR64RegClass); 3543 break; 3544 default: 3545 break; 3546 } 3547 } 3548 3549 // Clang will correctly decode the usage of register name aliases into their 3550 // official names. However, other frontends like `rustc` do not. This allows 3551 // users of these frontends to use the ABI names for registers in LLVM-style 3552 // register constraints. 3553 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 3554 .Case("{zero}", RISCV::X0) 3555 .Case("{ra}", RISCV::X1) 3556 .Case("{sp}", RISCV::X2) 3557 .Case("{gp}", RISCV::X3) 3558 .Case("{tp}", RISCV::X4) 3559 .Case("{t0}", RISCV::X5) 3560 .Case("{t1}", RISCV::X6) 3561 .Case("{t2}", RISCV::X7) 3562 .Cases("{s0}", "{fp}", RISCV::X8) 3563 .Case("{s1}", RISCV::X9) 3564 .Case("{a0}", RISCV::X10) 3565 .Case("{a1}", RISCV::X11) 3566 .Case("{a2}", RISCV::X12) 3567 .Case("{a3}", RISCV::X13) 3568 .Case("{a4}", RISCV::X14) 3569 .Case("{a5}", RISCV::X15) 3570 .Case("{a6}", RISCV::X16) 3571 .Case("{a7}", RISCV::X17) 3572 .Case("{s2}", RISCV::X18) 3573 .Case("{s3}", RISCV::X19) 3574 .Case("{s4}", RISCV::X20) 3575 .Case("{s5}", RISCV::X21) 3576 .Case("{s6}", RISCV::X22) 3577 .Case("{s7}", RISCV::X23) 3578 .Case("{s8}", RISCV::X24) 3579 .Case("{s9}", RISCV::X25) 3580 .Case("{s10}", RISCV::X26) 3581 .Case("{s11}", RISCV::X27) 3582 .Case("{t3}", RISCV::X28) 3583 .Case("{t4}", RISCV::X29) 3584 .Case("{t5}", RISCV::X30) 3585 .Case("{t6}", RISCV::X31) 3586 .Default(RISCV::NoRegister); 3587 if (XRegFromAlias != RISCV::NoRegister) 3588 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 3589 3590 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 3591 // TableGen record rather than the AsmName to choose registers for InlineAsm 3592 // constraints, plus we want to match those names to the widest floating point 3593 // register type available, manually select floating point registers here. 3594 // 3595 // The second case is the ABI name of the register, so that frontends can also 3596 // use the ABI names in register constraint lists. 3597 if (Subtarget.hasStdExtF()) { 3598 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 3599 .Cases("{f0}", "{ft0}", RISCV::F0_F) 3600 .Cases("{f1}", "{ft1}", RISCV::F1_F) 3601 .Cases("{f2}", "{ft2}", RISCV::F2_F) 3602 .Cases("{f3}", "{ft3}", RISCV::F3_F) 3603 .Cases("{f4}", "{ft4}", RISCV::F4_F) 3604 .Cases("{f5}", "{ft5}", RISCV::F5_F) 3605 .Cases("{f6}", "{ft6}", RISCV::F6_F) 3606 .Cases("{f7}", "{ft7}", RISCV::F7_F) 3607 .Cases("{f8}", "{fs0}", RISCV::F8_F) 3608 .Cases("{f9}", "{fs1}", RISCV::F9_F) 3609 .Cases("{f10}", "{fa0}", RISCV::F10_F) 3610 .Cases("{f11}", "{fa1}", RISCV::F11_F) 3611 .Cases("{f12}", "{fa2}", RISCV::F12_F) 3612 .Cases("{f13}", "{fa3}", RISCV::F13_F) 3613 .Cases("{f14}", "{fa4}", RISCV::F14_F) 3614 .Cases("{f15}", "{fa5}", RISCV::F15_F) 3615 .Cases("{f16}", "{fa6}", RISCV::F16_F) 3616 .Cases("{f17}", "{fa7}", RISCV::F17_F) 3617 .Cases("{f18}", "{fs2}", RISCV::F18_F) 3618 .Cases("{f19}", "{fs3}", RISCV::F19_F) 3619 .Cases("{f20}", "{fs4}", RISCV::F20_F) 3620 .Cases("{f21}", "{fs5}", RISCV::F21_F) 3621 .Cases("{f22}", "{fs6}", RISCV::F22_F) 3622 .Cases("{f23}", "{fs7}", RISCV::F23_F) 3623 .Cases("{f24}", "{fs8}", RISCV::F24_F) 3624 .Cases("{f25}", "{fs9}", RISCV::F25_F) 3625 .Cases("{f26}", "{fs10}", RISCV::F26_F) 3626 .Cases("{f27}", "{fs11}", RISCV::F27_F) 3627 .Cases("{f28}", "{ft8}", RISCV::F28_F) 3628 .Cases("{f29}", "{ft9}", RISCV::F29_F) 3629 .Cases("{f30}", "{ft10}", RISCV::F30_F) 3630 .Cases("{f31}", "{ft11}", RISCV::F31_F) 3631 .Default(RISCV::NoRegister); 3632 if (FReg != RISCV::NoRegister) { 3633 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 3634 if (Subtarget.hasStdExtD()) { 3635 unsigned RegNo = FReg - RISCV::F0_F; 3636 unsigned DReg = RISCV::F0_D + RegNo; 3637 return std::make_pair(DReg, &RISCV::FPR64RegClass); 3638 } 3639 return std::make_pair(FReg, &RISCV::FPR32RegClass); 3640 } 3641 } 3642 3643 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 3644 } 3645 3646 unsigned 3647 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 3648 // Currently only support length 1 constraints. 3649 if (ConstraintCode.size() == 1) { 3650 switch (ConstraintCode[0]) { 3651 case 'A': 3652 return InlineAsm::Constraint_A; 3653 default: 3654 break; 3655 } 3656 } 3657 3658 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 3659 } 3660 3661 void RISCVTargetLowering::LowerAsmOperandForConstraint( 3662 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 3663 SelectionDAG &DAG) const { 3664 // Currently only support length 1 constraints. 3665 if (Constraint.length() == 1) { 3666 switch (Constraint[0]) { 3667 case 'I': 3668 // Validate & create a 12-bit signed immediate operand. 3669 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3670 uint64_t CVal = C->getSExtValue(); 3671 if (isInt<12>(CVal)) 3672 Ops.push_back( 3673 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 3674 } 3675 return; 3676 case 'J': 3677 // Validate & create an integer zero operand. 3678 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 3679 if (C->getZExtValue() == 0) 3680 Ops.push_back( 3681 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 3682 return; 3683 case 'K': 3684 // Validate & create a 5-bit unsigned immediate operand. 3685 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3686 uint64_t CVal = C->getZExtValue(); 3687 if (isUInt<5>(CVal)) 3688 Ops.push_back( 3689 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 3690 } 3691 return; 3692 default: 3693 break; 3694 } 3695 } 3696 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 3697 } 3698 3699 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 3700 Instruction *Inst, 3701 AtomicOrdering Ord) const { 3702 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 3703 return Builder.CreateFence(Ord); 3704 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 3705 return Builder.CreateFence(AtomicOrdering::Release); 3706 return nullptr; 3707 } 3708 3709 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 3710 Instruction *Inst, 3711 AtomicOrdering Ord) const { 3712 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 3713 return Builder.CreateFence(AtomicOrdering::Acquire); 3714 return nullptr; 3715 } 3716 3717 TargetLowering::AtomicExpansionKind 3718 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 3719 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 3720 // point operations can't be used in an lr/sc sequence without breaking the 3721 // forward-progress guarantee. 3722 if (AI->isFloatingPointOperation()) 3723 return AtomicExpansionKind::CmpXChg; 3724 3725 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 3726 if (Size == 8 || Size == 16) 3727 return AtomicExpansionKind::MaskedIntrinsic; 3728 return AtomicExpansionKind::None; 3729 } 3730 3731 static Intrinsic::ID 3732 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 3733 if (XLen == 32) { 3734 switch (BinOp) { 3735 default: 3736 llvm_unreachable("Unexpected AtomicRMW BinOp"); 3737 case AtomicRMWInst::Xchg: 3738 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 3739 case AtomicRMWInst::Add: 3740 return Intrinsic::riscv_masked_atomicrmw_add_i32; 3741 case AtomicRMWInst::Sub: 3742 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 3743 case AtomicRMWInst::Nand: 3744 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 3745 case AtomicRMWInst::Max: 3746 return Intrinsic::riscv_masked_atomicrmw_max_i32; 3747 case AtomicRMWInst::Min: 3748 return Intrinsic::riscv_masked_atomicrmw_min_i32; 3749 case AtomicRMWInst::UMax: 3750 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 3751 case AtomicRMWInst::UMin: 3752 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 3753 } 3754 } 3755 3756 if (XLen == 64) { 3757 switch (BinOp) { 3758 default: 3759 llvm_unreachable("Unexpected AtomicRMW BinOp"); 3760 case AtomicRMWInst::Xchg: 3761 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 3762 case AtomicRMWInst::Add: 3763 return Intrinsic::riscv_masked_atomicrmw_add_i64; 3764 case AtomicRMWInst::Sub: 3765 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 3766 case AtomicRMWInst::Nand: 3767 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 3768 case AtomicRMWInst::Max: 3769 return Intrinsic::riscv_masked_atomicrmw_max_i64; 3770 case AtomicRMWInst::Min: 3771 return Intrinsic::riscv_masked_atomicrmw_min_i64; 3772 case AtomicRMWInst::UMax: 3773 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 3774 case AtomicRMWInst::UMin: 3775 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 3776 } 3777 } 3778 3779 llvm_unreachable("Unexpected XLen\n"); 3780 } 3781 3782 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 3783 IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 3784 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 3785 unsigned XLen = Subtarget.getXLen(); 3786 Value *Ordering = 3787 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 3788 Type *Tys[] = {AlignedAddr->getType()}; 3789 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 3790 AI->getModule(), 3791 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 3792 3793 if (XLen == 64) { 3794 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 3795 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 3796 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 3797 } 3798 3799 Value *Result; 3800 3801 // Must pass the shift amount needed to sign extend the loaded value prior 3802 // to performing a signed comparison for min/max. ShiftAmt is the number of 3803 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 3804 // is the number of bits to left+right shift the value in order to 3805 // sign-extend. 3806 if (AI->getOperation() == AtomicRMWInst::Min || 3807 AI->getOperation() == AtomicRMWInst::Max) { 3808 const DataLayout &DL = AI->getModule()->getDataLayout(); 3809 unsigned ValWidth = 3810 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 3811 Value *SextShamt = 3812 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 3813 Result = Builder.CreateCall(LrwOpScwLoop, 3814 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 3815 } else { 3816 Result = 3817 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 3818 } 3819 3820 if (XLen == 64) 3821 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 3822 return Result; 3823 } 3824 3825 TargetLowering::AtomicExpansionKind 3826 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 3827 AtomicCmpXchgInst *CI) const { 3828 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 3829 if (Size == 8 || Size == 16) 3830 return AtomicExpansionKind::MaskedIntrinsic; 3831 return AtomicExpansionKind::None; 3832 } 3833 3834 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 3835 IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 3836 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 3837 unsigned XLen = Subtarget.getXLen(); 3838 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 3839 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 3840 if (XLen == 64) { 3841 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 3842 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 3843 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 3844 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 3845 } 3846 Type *Tys[] = {AlignedAddr->getType()}; 3847 Function *MaskedCmpXchg = 3848 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 3849 Value *Result = Builder.CreateCall( 3850 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 3851 if (XLen == 64) 3852 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 3853 return Result; 3854 } 3855 3856 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 3857 EVT VT) const { 3858 VT = VT.getScalarType(); 3859 3860 if (!VT.isSimple()) 3861 return false; 3862 3863 switch (VT.getSimpleVT().SimpleTy) { 3864 case MVT::f16: 3865 return Subtarget.hasStdExtZfh(); 3866 case MVT::f32: 3867 return Subtarget.hasStdExtF(); 3868 case MVT::f64: 3869 return Subtarget.hasStdExtD(); 3870 default: 3871 break; 3872 } 3873 3874 return false; 3875 } 3876 3877 Register RISCVTargetLowering::getExceptionPointerRegister( 3878 const Constant *PersonalityFn) const { 3879 return RISCV::X10; 3880 } 3881 3882 Register RISCVTargetLowering::getExceptionSelectorRegister( 3883 const Constant *PersonalityFn) const { 3884 return RISCV::X11; 3885 } 3886 3887 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 3888 // Return false to suppress the unnecessary extensions if the LibCall 3889 // arguments or return value is f32 type for LP64 ABI. 3890 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 3891 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 3892 return false; 3893 3894 return true; 3895 } 3896 3897 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 3898 SDValue C) const { 3899 // Check integral scalar types. 3900 if (VT.isScalarInteger()) { 3901 // Omit the optimization if the sub target has the M extension and the data 3902 // size exceeds XLen. 3903 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 3904 return false; 3905 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 3906 // Break the MUL to a SLLI and an ADD/SUB. 3907 const APInt &Imm = ConstNode->getAPIntValue(); 3908 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 3909 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 3910 return true; 3911 // Omit the following optimization if the sub target has the M extension 3912 // and the data size >= XLen. 3913 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 3914 return false; 3915 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 3916 // a pair of LUI/ADDI. 3917 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 3918 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 3919 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 3920 (1 - ImmS).isPowerOf2()) 3921 return true; 3922 } 3923 } 3924 } 3925 3926 return false; 3927 } 3928 3929 #define GET_REGISTER_MATCHER 3930 #include "RISCVGenAsmMatcher.inc" 3931 3932 Register 3933 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 3934 const MachineFunction &MF) const { 3935 Register Reg = MatchRegisterAltName(RegName); 3936 if (Reg == RISCV::NoRegister) 3937 Reg = MatchRegisterName(RegName); 3938 if (Reg == RISCV::NoRegister) 3939 report_fatal_error( 3940 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 3941 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 3942 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 3943 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 3944 StringRef(RegName) + "\".")); 3945 return Reg; 3946 } 3947 3948 namespace llvm { 3949 namespace RISCVVIntrinsicsTable { 3950 3951 #define GET_RISCVVIntrinsicsTable_IMPL 3952 #include "RISCVGenSearchableTables.inc" 3953 3954 } // namespace RISCVVIntrinsicsTable 3955 } // namespace llvm 3956