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