1 //=== AArch64PostLegalizerLowering.cpp --------------------------*- C++ -*-===// 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 /// \file 10 /// Post-legalization lowering for instructions. 11 /// 12 /// This is used to offload pattern matching from the selector. 13 /// 14 /// For example, this combiner will notice that a G_SHUFFLE_VECTOR is actually 15 /// a G_ZIP, G_UZP, etc. 16 /// 17 /// General optimization combines should be handled by either the 18 /// AArch64PostLegalizerCombiner or the AArch64PreLegalizerCombiner. 19 /// 20 //===----------------------------------------------------------------------===// 21 22 #include "AArch64TargetMachine.h" 23 #include "AArch64GlobalISelUtils.h" 24 #include "MCTargetDesc/AArch64MCTargetDesc.h" 25 #include "llvm/CodeGen/GlobalISel/Combiner.h" 26 #include "llvm/CodeGen/GlobalISel/CombinerHelper.h" 27 #include "llvm/CodeGen/GlobalISel/CombinerInfo.h" 28 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h" 29 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h" 30 #include "llvm/CodeGen/GlobalISel/Utils.h" 31 #include "llvm/CodeGen/MachineFunctionPass.h" 32 #include "llvm/CodeGen/MachineInstrBuilder.h" 33 #include "llvm/CodeGen/MachineRegisterInfo.h" 34 #include "llvm/CodeGen/TargetOpcodes.h" 35 #include "llvm/CodeGen/TargetPassConfig.h" 36 #include "llvm/InitializePasses.h" 37 #include "llvm/Support/Debug.h" 38 39 #define DEBUG_TYPE "aarch64-postlegalizer-lowering" 40 41 using namespace llvm; 42 using namespace MIPatternMatch; 43 using namespace AArch64GISelUtils; 44 45 /// Represents a pseudo instruction which replaces a G_SHUFFLE_VECTOR. 46 /// 47 /// Used for matching target-supported shuffles before codegen. 48 struct ShuffleVectorPseudo { 49 unsigned Opc; ///< Opcode for the instruction. (E.g. G_ZIP1) 50 Register Dst; ///< Destination register. 51 SmallVector<SrcOp, 2> SrcOps; ///< Source registers. 52 ShuffleVectorPseudo(unsigned Opc, Register Dst, 53 std::initializer_list<SrcOp> SrcOps) 54 : Opc(Opc), Dst(Dst), SrcOps(SrcOps){}; 55 ShuffleVectorPseudo() {} 56 }; 57 58 /// Check if a vector shuffle corresponds to a REV instruction with the 59 /// specified blocksize. 60 static bool isREVMask(ArrayRef<int> M, unsigned EltSize, unsigned NumElts, 61 unsigned BlockSize) { 62 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 63 "Only possible block sizes for REV are: 16, 32, 64"); 64 assert(EltSize != 64 && "EltSize cannot be 64 for REV mask."); 65 66 unsigned BlockElts = M[0] + 1; 67 68 // If the first shuffle index is UNDEF, be optimistic. 69 if (M[0] < 0) 70 BlockElts = BlockSize / EltSize; 71 72 if (BlockSize <= EltSize || BlockSize != BlockElts * EltSize) 73 return false; 74 75 for (unsigned i = 0; i < NumElts; ++i) { 76 // Ignore undef indices. 77 if (M[i] < 0) 78 continue; 79 if (static_cast<unsigned>(M[i]) != 80 (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 81 return false; 82 } 83 84 return true; 85 } 86 87 /// Determines if \p M is a shuffle vector mask for a TRN of \p NumElts. 88 /// Whether or not G_TRN1 or G_TRN2 should be used is stored in \p WhichResult. 89 static bool isTRNMask(ArrayRef<int> M, unsigned NumElts, 90 unsigned &WhichResult) { 91 if (NumElts % 2 != 0) 92 return false; 93 WhichResult = (M[0] == 0 ? 0 : 1); 94 for (unsigned i = 0; i < NumElts; i += 2) { 95 if ((M[i] >= 0 && static_cast<unsigned>(M[i]) != i + WhichResult) || 96 (M[i + 1] >= 0 && 97 static_cast<unsigned>(M[i + 1]) != i + NumElts + WhichResult)) 98 return false; 99 } 100 return true; 101 } 102 103 /// Check if a G_EXT instruction can handle a shuffle mask \p M when the vector 104 /// sources of the shuffle are different. 105 static Optional<std::pair<bool, uint64_t>> getExtMask(ArrayRef<int> M, 106 unsigned NumElts) { 107 // Look for the first non-undef element. 108 auto FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; }); 109 if (FirstRealElt == M.end()) 110 return None; 111 112 // Use APInt to handle overflow when calculating expected element. 113 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 114 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 115 116 // The following shuffle indices must be the successive elements after the 117 // first real element. 118 if (any_of( 119 make_range(std::next(FirstRealElt), M.end()), 120 [&ExpectedElt](int Elt) { return Elt != ExpectedElt++ && Elt >= 0; })) 121 return None; 122 123 // The index of an EXT is the first element if it is not UNDEF. 124 // Watch out for the beginning UNDEFs. The EXT index should be the expected 125 // value of the first element. E.g. 126 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 127 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 128 // ExpectedElt is the last mask index plus 1. 129 uint64_t Imm = ExpectedElt.getZExtValue(); 130 bool ReverseExt = false; 131 132 // There are two difference cases requiring to reverse input vectors. 133 // For example, for vector <4 x i32> we have the following cases, 134 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 135 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 136 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 137 // to reverse two input vectors. 138 if (Imm < NumElts) 139 ReverseExt = true; 140 else 141 Imm -= NumElts; 142 return std::make_pair(ReverseExt, Imm); 143 } 144 145 /// Determines if \p M is a shuffle vector mask for a UZP of \p NumElts. 146 /// Whether or not G_UZP1 or G_UZP2 should be used is stored in \p WhichResult. 147 static bool isUZPMask(ArrayRef<int> M, unsigned NumElts, 148 unsigned &WhichResult) { 149 WhichResult = (M[0] == 0 ? 0 : 1); 150 for (unsigned i = 0; i != NumElts; ++i) { 151 // Skip undef indices. 152 if (M[i] < 0) 153 continue; 154 if (static_cast<unsigned>(M[i]) != 2 * i + WhichResult) 155 return false; 156 } 157 return true; 158 } 159 160 /// \return true if \p M is a zip mask for a shuffle vector of \p NumElts. 161 /// Whether or not G_ZIP1 or G_ZIP2 should be used is stored in \p WhichResult. 162 static bool isZipMask(ArrayRef<int> M, unsigned NumElts, 163 unsigned &WhichResult) { 164 if (NumElts % 2 != 0) 165 return false; 166 167 // 0 means use ZIP1, 1 means use ZIP2. 168 WhichResult = (M[0] == 0 ? 0 : 1); 169 unsigned Idx = WhichResult * NumElts / 2; 170 for (unsigned i = 0; i != NumElts; i += 2) { 171 if ((M[i] >= 0 && static_cast<unsigned>(M[i]) != Idx) || 172 (M[i + 1] >= 0 && static_cast<unsigned>(M[i + 1]) != Idx + NumElts)) 173 return false; 174 Idx += 1; 175 } 176 return true; 177 } 178 179 /// \return true if a G_SHUFFLE_VECTOR instruction \p MI can be replaced with a 180 /// G_REV instruction. Returns the appropriate G_REV opcode in \p Opc. 181 static bool matchREV(MachineInstr &MI, MachineRegisterInfo &MRI, 182 ShuffleVectorPseudo &MatchInfo) { 183 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR); 184 ArrayRef<int> ShuffleMask = MI.getOperand(3).getShuffleMask(); 185 Register Dst = MI.getOperand(0).getReg(); 186 Register Src = MI.getOperand(1).getReg(); 187 LLT Ty = MRI.getType(Dst); 188 unsigned EltSize = Ty.getScalarSizeInBits(); 189 190 // Element size for a rev cannot be 64. 191 if (EltSize == 64) 192 return false; 193 194 unsigned NumElts = Ty.getNumElements(); 195 196 // Try to produce G_REV64 197 if (isREVMask(ShuffleMask, EltSize, NumElts, 64)) { 198 MatchInfo = ShuffleVectorPseudo(AArch64::G_REV64, Dst, {Src}); 199 return true; 200 } 201 202 // TODO: Produce G_REV32 and G_REV16 once we have proper legalization support. 203 // This should be identical to above, but with a constant 32 and constant 204 // 16. 205 return false; 206 } 207 208 /// \return true if a G_SHUFFLE_VECTOR instruction \p MI can be replaced with 209 /// a G_TRN1 or G_TRN2 instruction. 210 static bool matchTRN(MachineInstr &MI, MachineRegisterInfo &MRI, 211 ShuffleVectorPseudo &MatchInfo) { 212 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR); 213 unsigned WhichResult; 214 ArrayRef<int> ShuffleMask = MI.getOperand(3).getShuffleMask(); 215 Register Dst = MI.getOperand(0).getReg(); 216 unsigned NumElts = MRI.getType(Dst).getNumElements(); 217 if (!isTRNMask(ShuffleMask, NumElts, WhichResult)) 218 return false; 219 unsigned Opc = (WhichResult == 0) ? AArch64::G_TRN1 : AArch64::G_TRN2; 220 Register V1 = MI.getOperand(1).getReg(); 221 Register V2 = MI.getOperand(2).getReg(); 222 MatchInfo = ShuffleVectorPseudo(Opc, Dst, {V1, V2}); 223 return true; 224 } 225 226 /// \return true if a G_SHUFFLE_VECTOR instruction \p MI can be replaced with 227 /// a G_UZP1 or G_UZP2 instruction. 228 /// 229 /// \param [in] MI - The shuffle vector instruction. 230 /// \param [out] MatchInfo - Either G_UZP1 or G_UZP2 on success. 231 static bool matchUZP(MachineInstr &MI, MachineRegisterInfo &MRI, 232 ShuffleVectorPseudo &MatchInfo) { 233 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR); 234 unsigned WhichResult; 235 ArrayRef<int> ShuffleMask = MI.getOperand(3).getShuffleMask(); 236 Register Dst = MI.getOperand(0).getReg(); 237 unsigned NumElts = MRI.getType(Dst).getNumElements(); 238 if (!isUZPMask(ShuffleMask, NumElts, WhichResult)) 239 return false; 240 unsigned Opc = (WhichResult == 0) ? AArch64::G_UZP1 : AArch64::G_UZP2; 241 Register V1 = MI.getOperand(1).getReg(); 242 Register V2 = MI.getOperand(2).getReg(); 243 MatchInfo = ShuffleVectorPseudo(Opc, Dst, {V1, V2}); 244 return true; 245 } 246 247 static bool matchZip(MachineInstr &MI, MachineRegisterInfo &MRI, 248 ShuffleVectorPseudo &MatchInfo) { 249 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR); 250 unsigned WhichResult; 251 ArrayRef<int> ShuffleMask = MI.getOperand(3).getShuffleMask(); 252 Register Dst = MI.getOperand(0).getReg(); 253 unsigned NumElts = MRI.getType(Dst).getNumElements(); 254 if (!isZipMask(ShuffleMask, NumElts, WhichResult)) 255 return false; 256 unsigned Opc = (WhichResult == 0) ? AArch64::G_ZIP1 : AArch64::G_ZIP2; 257 Register V1 = MI.getOperand(1).getReg(); 258 Register V2 = MI.getOperand(2).getReg(); 259 MatchInfo = ShuffleVectorPseudo(Opc, Dst, {V1, V2}); 260 return true; 261 } 262 263 /// Helper function for matchDup. 264 static bool matchDupFromInsertVectorElt(int Lane, MachineInstr &MI, 265 MachineRegisterInfo &MRI, 266 ShuffleVectorPseudo &MatchInfo) { 267 if (Lane != 0) 268 return false; 269 270 // Try to match a vector splat operation into a dup instruction. 271 // We're looking for this pattern: 272 // 273 // %scalar:gpr(s64) = COPY $x0 274 // %undef:fpr(<2 x s64>) = G_IMPLICIT_DEF 275 // %cst0:gpr(s32) = G_CONSTANT i32 0 276 // %zerovec:fpr(<2 x s32>) = G_BUILD_VECTOR %cst0(s32), %cst0(s32) 277 // %ins:fpr(<2 x s64>) = G_INSERT_VECTOR_ELT %undef, %scalar(s64), %cst0(s32) 278 // %splat:fpr(<2 x s64>) = G_SHUFFLE_VECTOR %ins(<2 x s64>), %undef, %zerovec(<2 x s32>) 279 // 280 // ...into: 281 // %splat = G_DUP %scalar 282 283 // Begin matching the insert. 284 auto *InsMI = getOpcodeDef(TargetOpcode::G_INSERT_VECTOR_ELT, 285 MI.getOperand(1).getReg(), MRI); 286 if (!InsMI) 287 return false; 288 // Match the undef vector operand. 289 if (!getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, InsMI->getOperand(1).getReg(), 290 MRI)) 291 return false; 292 293 // Match the index constant 0. 294 int64_t Index = 0; 295 if (!mi_match(InsMI->getOperand(3).getReg(), MRI, m_ICst(Index)) || Index) 296 return false; 297 298 MatchInfo = ShuffleVectorPseudo(AArch64::G_DUP, MI.getOperand(0).getReg(), 299 {InsMI->getOperand(2).getReg()}); 300 return true; 301 } 302 303 /// Helper function for matchDup. 304 static bool matchDupFromBuildVector(int Lane, MachineInstr &MI, 305 MachineRegisterInfo &MRI, 306 ShuffleVectorPseudo &MatchInfo) { 307 assert(Lane >= 0 && "Expected positive lane?"); 308 // Test if the LHS is a BUILD_VECTOR. If it is, then we can just reference the 309 // lane's definition directly. 310 auto *BuildVecMI = getOpcodeDef(TargetOpcode::G_BUILD_VECTOR, 311 MI.getOperand(1).getReg(), MRI); 312 if (!BuildVecMI) 313 return false; 314 Register Reg = BuildVecMI->getOperand(Lane + 1).getReg(); 315 MatchInfo = 316 ShuffleVectorPseudo(AArch64::G_DUP, MI.getOperand(0).getReg(), {Reg}); 317 return true; 318 } 319 320 static bool matchDup(MachineInstr &MI, MachineRegisterInfo &MRI, 321 ShuffleVectorPseudo &MatchInfo) { 322 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR); 323 auto MaybeLane = getSplatIndex(MI); 324 if (!MaybeLane) 325 return false; 326 int Lane = *MaybeLane; 327 // If this is undef splat, generate it via "just" vdup, if possible. 328 if (Lane < 0) 329 Lane = 0; 330 if (matchDupFromInsertVectorElt(Lane, MI, MRI, MatchInfo)) 331 return true; 332 if (matchDupFromBuildVector(Lane, MI, MRI, MatchInfo)) 333 return true; 334 return false; 335 } 336 337 static bool matchEXT(MachineInstr &MI, MachineRegisterInfo &MRI, 338 ShuffleVectorPseudo &MatchInfo) { 339 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR); 340 Register Dst = MI.getOperand(0).getReg(); 341 auto ExtInfo = getExtMask(MI.getOperand(3).getShuffleMask(), 342 MRI.getType(Dst).getNumElements()); 343 if (!ExtInfo) 344 return false; 345 bool ReverseExt; 346 uint64_t Imm; 347 std::tie(ReverseExt, Imm) = *ExtInfo; 348 Register V1 = MI.getOperand(1).getReg(); 349 Register V2 = MI.getOperand(2).getReg(); 350 if (ReverseExt) 351 std::swap(V1, V2); 352 uint64_t ExtFactor = MRI.getType(V1).getScalarSizeInBits() / 8; 353 Imm *= ExtFactor; 354 MatchInfo = ShuffleVectorPseudo(AArch64::G_EXT, Dst, {V1, V2, Imm}); 355 return true; 356 } 357 358 /// Replace a G_SHUFFLE_VECTOR instruction with a pseudo. 359 /// \p Opc is the opcode to use. \p MI is the G_SHUFFLE_VECTOR. 360 static bool applyShuffleVectorPseudo(MachineInstr &MI, 361 ShuffleVectorPseudo &MatchInfo) { 362 MachineIRBuilder MIRBuilder(MI); 363 MIRBuilder.buildInstr(MatchInfo.Opc, {MatchInfo.Dst}, MatchInfo.SrcOps); 364 MI.eraseFromParent(); 365 return true; 366 } 367 368 /// Replace a G_SHUFFLE_VECTOR instruction with G_EXT. 369 /// Special-cased because the constant operand must be emitted as a G_CONSTANT 370 /// for the imported tablegen patterns to work. 371 static bool applyEXT(MachineInstr &MI, ShuffleVectorPseudo &MatchInfo) { 372 MachineIRBuilder MIRBuilder(MI); 373 // Tablegen patterns expect an i32 G_CONSTANT as the final op. 374 auto Cst = 375 MIRBuilder.buildConstant(LLT::scalar(32), MatchInfo.SrcOps[2].getImm()); 376 MIRBuilder.buildInstr(MatchInfo.Opc, {MatchInfo.Dst}, 377 {MatchInfo.SrcOps[0], MatchInfo.SrcOps[1], Cst}); 378 MI.eraseFromParent(); 379 return true; 380 } 381 382 /// isVShiftRImm - Check if this is a valid vector for the immediate 383 /// operand of a vector shift right operation. The value must be in the range: 384 /// 1 <= Value <= ElementBits for a right shift. 385 static bool isVShiftRImm(Register Reg, MachineRegisterInfo &MRI, LLT Ty, 386 int64_t &Cnt) { 387 assert(Ty.isVector() && "vector shift count is not a vector type"); 388 MachineInstr *MI = MRI.getVRegDef(Reg); 389 auto Cst = getBuildVectorConstantSplat(*MI, MRI); 390 if (!Cst) 391 return false; 392 Cnt = *Cst; 393 int64_t ElementBits = Ty.getScalarSizeInBits(); 394 return Cnt >= 1 && Cnt <= ElementBits; 395 } 396 397 /// Match a vector G_ASHR or G_LSHR with a valid immediate shift. 398 static bool matchVAshrLshrImm(MachineInstr &MI, MachineRegisterInfo &MRI, 399 int64_t &Imm) { 400 assert(MI.getOpcode() == TargetOpcode::G_ASHR || 401 MI.getOpcode() == TargetOpcode::G_LSHR); 402 LLT Ty = MRI.getType(MI.getOperand(1).getReg()); 403 if (!Ty.isVector()) 404 return false; 405 return isVShiftRImm(MI.getOperand(2).getReg(), MRI, Ty, Imm); 406 } 407 408 static bool applyVAshrLshrImm(MachineInstr &MI, MachineRegisterInfo &MRI, 409 int64_t &Imm) { 410 unsigned Opc = MI.getOpcode(); 411 assert(Opc == TargetOpcode::G_ASHR || Opc == TargetOpcode::G_LSHR); 412 unsigned NewOpc = 413 Opc == TargetOpcode::G_ASHR ? AArch64::G_VASHR : AArch64::G_VLSHR; 414 MachineIRBuilder MIB(MI); 415 auto ImmDef = MIB.buildConstant(LLT::scalar(32), Imm); 416 MIB.buildInstr(NewOpc, {MI.getOperand(0)}, {MI.getOperand(1), ImmDef}); 417 MI.eraseFromParent(); 418 return true; 419 } 420 421 /// Determine if it is possible to modify the \p RHS and predicate \p P of a 422 /// G_ICMP instruction such that the right-hand side is an arithmetic immediate. 423 /// 424 /// \returns A pair containing the updated immediate and predicate which may 425 /// be used to optimize the instruction. 426 /// 427 /// \note This assumes that the comparison has been legalized. 428 Optional<std::pair<uint64_t, CmpInst::Predicate>> 429 tryAdjustICmpImmAndPred(Register RHS, CmpInst::Predicate P, 430 const MachineRegisterInfo &MRI) { 431 const auto &Ty = MRI.getType(RHS); 432 if (Ty.isVector()) 433 return None; 434 unsigned Size = Ty.getSizeInBits(); 435 assert((Size == 32 || Size == 64) && "Expected 32 or 64 bit compare only?"); 436 437 // If the RHS is not a constant, or the RHS is already a valid arithmetic 438 // immediate, then there is nothing to change. 439 auto ValAndVReg = getConstantVRegValWithLookThrough(RHS, MRI); 440 if (!ValAndVReg) 441 return None; 442 uint64_t C = ValAndVReg->Value; 443 if (isLegalArithImmed(C)) 444 return None; 445 446 // We have a non-arithmetic immediate. Check if adjusting the immediate and 447 // adjusting the predicate will result in a legal arithmetic immediate. 448 switch (P) { 449 default: 450 return None; 451 case CmpInst::ICMP_SLT: 452 case CmpInst::ICMP_SGE: 453 // Check for 454 // 455 // x slt c => x sle c - 1 456 // x sge c => x sgt c - 1 457 // 458 // When c is not the smallest possible negative number. 459 if ((Size == 64 && static_cast<int64_t>(C) == INT64_MIN) || 460 (Size == 32 && static_cast<int32_t>(C) == INT32_MIN)) 461 return None; 462 P = (P == CmpInst::ICMP_SLT) ? CmpInst::ICMP_SLE : CmpInst::ICMP_SGT; 463 C -= 1; 464 break; 465 case CmpInst::ICMP_ULT: 466 case CmpInst::ICMP_UGE: 467 // Check for 468 // 469 // x ult c => x ule c - 1 470 // x uge c => x ugt c - 1 471 // 472 // When c is not zero. 473 if (C == 0) 474 return None; 475 P = (P == CmpInst::ICMP_ULT) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT; 476 C -= 1; 477 break; 478 case CmpInst::ICMP_SLE: 479 case CmpInst::ICMP_SGT: 480 // Check for 481 // 482 // x sle c => x slt c + 1 483 // x sgt c => s sge c + 1 484 // 485 // When c is not the largest possible signed integer. 486 if ((Size == 32 && static_cast<int32_t>(C) == INT32_MAX) || 487 (Size == 64 && static_cast<int64_t>(C) == INT64_MAX)) 488 return None; 489 P = (P == CmpInst::ICMP_SLE) ? CmpInst::ICMP_SLT : CmpInst::ICMP_SGE; 490 C += 1; 491 break; 492 case CmpInst::ICMP_ULE: 493 case CmpInst::ICMP_UGT: 494 // Check for 495 // 496 // x ule c => x ult c + 1 497 // x ugt c => s uge c + 1 498 // 499 // When c is not the largest possible unsigned integer. 500 if ((Size == 32 && static_cast<uint32_t>(C) == UINT32_MAX) || 501 (Size == 64 && C == UINT64_MAX)) 502 return None; 503 P = (P == CmpInst::ICMP_ULE) ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE; 504 C += 1; 505 break; 506 } 507 508 // Check if the new constant is valid, and return the updated constant and 509 // predicate if it is. 510 if (Size == 32) 511 C = static_cast<uint32_t>(C); 512 if (!isLegalArithImmed(C)) 513 return None; 514 return {{C, P}}; 515 } 516 517 /// Determine whether or not it is possible to update the RHS and predicate of 518 /// a G_ICMP instruction such that the RHS will be selected as an arithmetic 519 /// immediate. 520 /// 521 /// \p MI - The G_ICMP instruction 522 /// \p MatchInfo - The new RHS immediate and predicate on success 523 /// 524 /// See tryAdjustICmpImmAndPred for valid transformations. 525 bool matchAdjustICmpImmAndPred( 526 MachineInstr &MI, const MachineRegisterInfo &MRI, 527 std::pair<uint64_t, CmpInst::Predicate> &MatchInfo) { 528 assert(MI.getOpcode() == TargetOpcode::G_ICMP); 529 Register RHS = MI.getOperand(3).getReg(); 530 auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate()); 531 if (auto MaybeNewImmAndPred = tryAdjustICmpImmAndPred(RHS, Pred, MRI)) { 532 MatchInfo = *MaybeNewImmAndPred; 533 return true; 534 } 535 return false; 536 } 537 538 bool applyAdjustICmpImmAndPred( 539 MachineInstr &MI, std::pair<uint64_t, CmpInst::Predicate> &MatchInfo, 540 MachineIRBuilder &MIB, GISelChangeObserver &Observer) { 541 MIB.setInstrAndDebugLoc(MI); 542 MachineOperand &RHS = MI.getOperand(3); 543 MachineRegisterInfo &MRI = *MIB.getMRI(); 544 auto Cst = MIB.buildConstant(MRI.cloneVirtualRegister(RHS.getReg()), 545 MatchInfo.first); 546 Observer.changingInstr(MI); 547 RHS.setReg(Cst->getOperand(0).getReg()); 548 MI.getOperand(1).setPredicate(MatchInfo.second); 549 Observer.changedInstr(MI); 550 return true; 551 } 552 553 bool matchDupLane(MachineInstr &MI, MachineRegisterInfo &MRI, 554 std::pair<unsigned, int> &MatchInfo) { 555 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR); 556 Register Src1Reg = MI.getOperand(1).getReg(); 557 const LLT SrcTy = MRI.getType(Src1Reg); 558 const LLT DstTy = MRI.getType(MI.getOperand(0).getReg()); 559 560 auto LaneIdx = getSplatIndex(MI); 561 if (!LaneIdx) 562 return false; 563 564 // The lane idx should be within the first source vector. 565 if (*LaneIdx >= SrcTy.getNumElements()) 566 return false; 567 568 if (DstTy != SrcTy) 569 return false; 570 571 LLT ScalarTy = SrcTy.getElementType(); 572 unsigned ScalarSize = ScalarTy.getSizeInBits(); 573 574 unsigned Opc = 0; 575 switch (SrcTy.getNumElements()) { 576 case 2: 577 if (ScalarSize == 64) 578 Opc = AArch64::G_DUPLANE64; 579 break; 580 case 4: 581 if (ScalarSize == 32) 582 Opc = AArch64::G_DUPLANE32; 583 break; 584 case 8: 585 if (ScalarSize == 16) 586 Opc = AArch64::G_DUPLANE16; 587 break; 588 case 16: 589 if (ScalarSize == 8) 590 Opc = AArch64::G_DUPLANE8; 591 break; 592 default: 593 break; 594 } 595 if (!Opc) 596 return false; 597 598 MatchInfo.first = Opc; 599 MatchInfo.second = *LaneIdx; 600 return true; 601 } 602 603 bool applyDupLane(MachineInstr &MI, MachineRegisterInfo &MRI, 604 MachineIRBuilder &B, std::pair<unsigned, int> &MatchInfo) { 605 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR); 606 B.setInstrAndDebugLoc(MI); 607 auto Lane = B.buildConstant(LLT::scalar(64), MatchInfo.second); 608 B.buildInstr(MatchInfo.first, {MI.getOperand(0).getReg()}, 609 {MI.getOperand(1).getReg(), Lane}); 610 MI.eraseFromParent(); 611 return true; 612 } 613 614 #define AARCH64POSTLEGALIZERLOWERINGHELPER_GENCOMBINERHELPER_DEPS 615 #include "AArch64GenPostLegalizeGILowering.inc" 616 #undef AARCH64POSTLEGALIZERLOWERINGHELPER_GENCOMBINERHELPER_DEPS 617 618 namespace { 619 #define AARCH64POSTLEGALIZERLOWERINGHELPER_GENCOMBINERHELPER_H 620 #include "AArch64GenPostLegalizeGILowering.inc" 621 #undef AARCH64POSTLEGALIZERLOWERINGHELPER_GENCOMBINERHELPER_H 622 623 class AArch64PostLegalizerLoweringInfo : public CombinerInfo { 624 public: 625 AArch64GenPostLegalizerLoweringHelperRuleConfig GeneratedRuleCfg; 626 627 AArch64PostLegalizerLoweringInfo(bool OptSize, bool MinSize) 628 : CombinerInfo(/*AllowIllegalOps*/ true, /*ShouldLegalizeIllegal*/ false, 629 /*LegalizerInfo*/ nullptr, /*OptEnabled = */ true, OptSize, 630 MinSize) { 631 if (!GeneratedRuleCfg.parseCommandLineOption()) 632 report_fatal_error("Invalid rule identifier"); 633 } 634 635 virtual bool combine(GISelChangeObserver &Observer, MachineInstr &MI, 636 MachineIRBuilder &B) const override; 637 }; 638 639 bool AArch64PostLegalizerLoweringInfo::combine(GISelChangeObserver &Observer, 640 MachineInstr &MI, 641 MachineIRBuilder &B) const { 642 CombinerHelper Helper(Observer, B); 643 AArch64GenPostLegalizerLoweringHelper Generated(GeneratedRuleCfg); 644 return Generated.tryCombineAll(Observer, MI, B, Helper); 645 } 646 647 #define AARCH64POSTLEGALIZERLOWERINGHELPER_GENCOMBINERHELPER_CPP 648 #include "AArch64GenPostLegalizeGILowering.inc" 649 #undef AARCH64POSTLEGALIZERLOWERINGHELPER_GENCOMBINERHELPER_CPP 650 651 class AArch64PostLegalizerLowering : public MachineFunctionPass { 652 public: 653 static char ID; 654 655 AArch64PostLegalizerLowering(); 656 657 StringRef getPassName() const override { 658 return "AArch64PostLegalizerLowering"; 659 } 660 661 bool runOnMachineFunction(MachineFunction &MF) override; 662 void getAnalysisUsage(AnalysisUsage &AU) const override; 663 }; 664 } // end anonymous namespace 665 666 void AArch64PostLegalizerLowering::getAnalysisUsage(AnalysisUsage &AU) const { 667 AU.addRequired<TargetPassConfig>(); 668 AU.setPreservesCFG(); 669 getSelectionDAGFallbackAnalysisUsage(AU); 670 MachineFunctionPass::getAnalysisUsage(AU); 671 } 672 673 AArch64PostLegalizerLowering::AArch64PostLegalizerLowering() 674 : MachineFunctionPass(ID) { 675 initializeAArch64PostLegalizerLoweringPass(*PassRegistry::getPassRegistry()); 676 } 677 678 bool AArch64PostLegalizerLowering::runOnMachineFunction(MachineFunction &MF) { 679 if (MF.getProperties().hasProperty( 680 MachineFunctionProperties::Property::FailedISel)) 681 return false; 682 assert(MF.getProperties().hasProperty( 683 MachineFunctionProperties::Property::Legalized) && 684 "Expected a legalized function?"); 685 auto *TPC = &getAnalysis<TargetPassConfig>(); 686 const Function &F = MF.getFunction(); 687 AArch64PostLegalizerLoweringInfo PCInfo(F.hasOptSize(), F.hasMinSize()); 688 Combiner C(PCInfo, TPC); 689 return C.combineMachineInstrs(MF, /*CSEInfo*/ nullptr); 690 } 691 692 char AArch64PostLegalizerLowering::ID = 0; 693 INITIALIZE_PASS_BEGIN(AArch64PostLegalizerLowering, DEBUG_TYPE, 694 "Lower AArch64 MachineInstrs after legalization", false, 695 false) 696 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 697 INITIALIZE_PASS_END(AArch64PostLegalizerLowering, DEBUG_TYPE, 698 "Lower AArch64 MachineInstrs after legalization", false, 699 false) 700 701 namespace llvm { 702 FunctionPass *createAArch64PostLegalizerLowering() { 703 return new AArch64PostLegalizerLowering(); 704 } 705 } // end namespace llvm 706