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