1 //===-- lib/CodeGen/GlobalISel/GICombinerHelper.cpp -----------------------===// 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 #include "llvm/CodeGen/GlobalISel/CombinerHelper.h" 9 #include "llvm/ADT/SetVector.h" 10 #include "llvm/ADT/SmallBitVector.h" 11 #include "llvm/CodeGen/GlobalISel/Combiner.h" 12 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h" 13 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 14 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h" 15 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h" 16 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h" 17 #include "llvm/CodeGen/GlobalISel/Utils.h" 18 #include "llvm/CodeGen/LowLevelType.h" 19 #include "llvm/CodeGen/MachineBasicBlock.h" 20 #include "llvm/CodeGen/MachineDominators.h" 21 #include "llvm/CodeGen/MachineFrameInfo.h" 22 #include "llvm/CodeGen/MachineInstr.h" 23 #include "llvm/CodeGen/MachineMemOperand.h" 24 #include "llvm/CodeGen/MachineRegisterInfo.h" 25 #include "llvm/CodeGen/TargetInstrInfo.h" 26 #include "llvm/CodeGen/TargetLowering.h" 27 #include "llvm/CodeGen/TargetOpcodes.h" 28 #include "llvm/Support/MathExtras.h" 29 #include "llvm/Target/TargetMachine.h" 30 31 #define DEBUG_TYPE "gi-combiner" 32 33 using namespace llvm; 34 using namespace MIPatternMatch; 35 36 // Option to allow testing of the combiner while no targets know about indexed 37 // addressing. 38 static cl::opt<bool> 39 ForceLegalIndexing("force-legal-indexing", cl::Hidden, cl::init(false), 40 cl::desc("Force all indexed operations to be " 41 "legal for the GlobalISel combiner")); 42 43 CombinerHelper::CombinerHelper(GISelChangeObserver &Observer, 44 MachineIRBuilder &B, GISelKnownBits *KB, 45 MachineDominatorTree *MDT, 46 const LegalizerInfo *LI) 47 : Builder(B), MRI(Builder.getMF().getRegInfo()), Observer(Observer), 48 KB(KB), MDT(MDT), LI(LI) { 49 (void)this->KB; 50 } 51 52 const TargetLowering &CombinerHelper::getTargetLowering() const { 53 return *Builder.getMF().getSubtarget().getTargetLowering(); 54 } 55 56 /// \returns The little endian in-memory byte position of byte \p I in a 57 /// \p ByteWidth bytes wide type. 58 /// 59 /// E.g. Given a 4-byte type x, x[0] -> byte 0 60 static unsigned littleEndianByteAt(const unsigned ByteWidth, const unsigned I) { 61 assert(I < ByteWidth && "I must be in [0, ByteWidth)"); 62 return I; 63 } 64 65 /// \returns The big endian in-memory byte position of byte \p I in a 66 /// \p ByteWidth bytes wide type. 67 /// 68 /// E.g. Given a 4-byte type x, x[0] -> byte 3 69 static unsigned bigEndianByteAt(const unsigned ByteWidth, const unsigned I) { 70 assert(I < ByteWidth && "I must be in [0, ByteWidth)"); 71 return ByteWidth - I - 1; 72 } 73 74 /// Given a map from byte offsets in memory to indices in a load/store, 75 /// determine if that map corresponds to a little or big endian byte pattern. 76 /// 77 /// \param MemOffset2Idx maps memory offsets to address offsets. 78 /// \param LowestIdx is the lowest index in \p MemOffset2Idx. 79 /// 80 /// \returns true if the map corresponds to a big endian byte pattern, false 81 /// if it corresponds to a little endian byte pattern, and None otherwise. 82 /// 83 /// E.g. given a 32-bit type x, and x[AddrOffset], the in-memory byte patterns 84 /// are as follows: 85 /// 86 /// AddrOffset Little endian Big endian 87 /// 0 0 3 88 /// 1 1 2 89 /// 2 2 1 90 /// 3 3 0 91 static Optional<bool> 92 isBigEndian(const SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx, 93 int64_t LowestIdx) { 94 // Need at least two byte positions to decide on endianness. 95 unsigned Width = MemOffset2Idx.size(); 96 if (Width < 2) 97 return None; 98 bool BigEndian = true, LittleEndian = true; 99 for (unsigned MemOffset = 0; MemOffset < Width; ++ MemOffset) { 100 auto MemOffsetAndIdx = MemOffset2Idx.find(MemOffset); 101 if (MemOffsetAndIdx == MemOffset2Idx.end()) 102 return None; 103 const int64_t Idx = MemOffsetAndIdx->second - LowestIdx; 104 assert(Idx >= 0 && "Expected non-negative byte offset?"); 105 LittleEndian &= Idx == littleEndianByteAt(Width, MemOffset); 106 BigEndian &= Idx == bigEndianByteAt(Width, MemOffset); 107 if (!BigEndian && !LittleEndian) 108 return None; 109 } 110 111 assert((BigEndian != LittleEndian) && 112 "Pattern cannot be both big and little endian!"); 113 return BigEndian; 114 } 115 116 bool CombinerHelper::isLegalOrBeforeLegalizer( 117 const LegalityQuery &Query) const { 118 return !LI || LI->getAction(Query).Action == LegalizeActions::Legal; 119 } 120 121 void CombinerHelper::replaceRegWith(MachineRegisterInfo &MRI, Register FromReg, 122 Register ToReg) const { 123 Observer.changingAllUsesOfReg(MRI, FromReg); 124 125 if (MRI.constrainRegAttrs(ToReg, FromReg)) 126 MRI.replaceRegWith(FromReg, ToReg); 127 else 128 Builder.buildCopy(ToReg, FromReg); 129 130 Observer.finishedChangingAllUsesOfReg(); 131 } 132 133 void CombinerHelper::replaceRegOpWith(MachineRegisterInfo &MRI, 134 MachineOperand &FromRegOp, 135 Register ToReg) const { 136 assert(FromRegOp.getParent() && "Expected an operand in an MI"); 137 Observer.changingInstr(*FromRegOp.getParent()); 138 139 FromRegOp.setReg(ToReg); 140 141 Observer.changedInstr(*FromRegOp.getParent()); 142 } 143 144 bool CombinerHelper::tryCombineCopy(MachineInstr &MI) { 145 if (matchCombineCopy(MI)) { 146 applyCombineCopy(MI); 147 return true; 148 } 149 return false; 150 } 151 bool CombinerHelper::matchCombineCopy(MachineInstr &MI) { 152 if (MI.getOpcode() != TargetOpcode::COPY) 153 return false; 154 Register DstReg = MI.getOperand(0).getReg(); 155 Register SrcReg = MI.getOperand(1).getReg(); 156 return canReplaceReg(DstReg, SrcReg, MRI); 157 } 158 void CombinerHelper::applyCombineCopy(MachineInstr &MI) { 159 Register DstReg = MI.getOperand(0).getReg(); 160 Register SrcReg = MI.getOperand(1).getReg(); 161 MI.eraseFromParent(); 162 replaceRegWith(MRI, DstReg, SrcReg); 163 } 164 165 bool CombinerHelper::tryCombineConcatVectors(MachineInstr &MI) { 166 bool IsUndef = false; 167 SmallVector<Register, 4> Ops; 168 if (matchCombineConcatVectors(MI, IsUndef, Ops)) { 169 applyCombineConcatVectors(MI, IsUndef, Ops); 170 return true; 171 } 172 return false; 173 } 174 175 bool CombinerHelper::matchCombineConcatVectors(MachineInstr &MI, bool &IsUndef, 176 SmallVectorImpl<Register> &Ops) { 177 assert(MI.getOpcode() == TargetOpcode::G_CONCAT_VECTORS && 178 "Invalid instruction"); 179 IsUndef = true; 180 MachineInstr *Undef = nullptr; 181 182 // Walk over all the operands of concat vectors and check if they are 183 // build_vector themselves or undef. 184 // Then collect their operands in Ops. 185 for (const MachineOperand &MO : MI.uses()) { 186 Register Reg = MO.getReg(); 187 MachineInstr *Def = MRI.getVRegDef(Reg); 188 assert(Def && "Operand not defined"); 189 switch (Def->getOpcode()) { 190 case TargetOpcode::G_BUILD_VECTOR: 191 IsUndef = false; 192 // Remember the operands of the build_vector to fold 193 // them into the yet-to-build flattened concat vectors. 194 for (const MachineOperand &BuildVecMO : Def->uses()) 195 Ops.push_back(BuildVecMO.getReg()); 196 break; 197 case TargetOpcode::G_IMPLICIT_DEF: { 198 LLT OpType = MRI.getType(Reg); 199 // Keep one undef value for all the undef operands. 200 if (!Undef) { 201 Builder.setInsertPt(*MI.getParent(), MI); 202 Undef = Builder.buildUndef(OpType.getScalarType()); 203 } 204 assert(MRI.getType(Undef->getOperand(0).getReg()) == 205 OpType.getScalarType() && 206 "All undefs should have the same type"); 207 // Break the undef vector in as many scalar elements as needed 208 // for the flattening. 209 for (unsigned EltIdx = 0, EltEnd = OpType.getNumElements(); 210 EltIdx != EltEnd; ++EltIdx) 211 Ops.push_back(Undef->getOperand(0).getReg()); 212 break; 213 } 214 default: 215 return false; 216 } 217 } 218 return true; 219 } 220 void CombinerHelper::applyCombineConcatVectors( 221 MachineInstr &MI, bool IsUndef, const ArrayRef<Register> Ops) { 222 // We determined that the concat_vectors can be flatten. 223 // Generate the flattened build_vector. 224 Register DstReg = MI.getOperand(0).getReg(); 225 Builder.setInsertPt(*MI.getParent(), MI); 226 Register NewDstReg = MRI.cloneVirtualRegister(DstReg); 227 228 // Note: IsUndef is sort of redundant. We could have determine it by 229 // checking that at all Ops are undef. Alternatively, we could have 230 // generate a build_vector of undefs and rely on another combine to 231 // clean that up. For now, given we already gather this information 232 // in tryCombineConcatVectors, just save compile time and issue the 233 // right thing. 234 if (IsUndef) 235 Builder.buildUndef(NewDstReg); 236 else 237 Builder.buildBuildVector(NewDstReg, Ops); 238 MI.eraseFromParent(); 239 replaceRegWith(MRI, DstReg, NewDstReg); 240 } 241 242 bool CombinerHelper::tryCombineShuffleVector(MachineInstr &MI) { 243 SmallVector<Register, 4> Ops; 244 if (matchCombineShuffleVector(MI, Ops)) { 245 applyCombineShuffleVector(MI, Ops); 246 return true; 247 } 248 return false; 249 } 250 251 bool CombinerHelper::matchCombineShuffleVector(MachineInstr &MI, 252 SmallVectorImpl<Register> &Ops) { 253 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR && 254 "Invalid instruction kind"); 255 LLT DstType = MRI.getType(MI.getOperand(0).getReg()); 256 Register Src1 = MI.getOperand(1).getReg(); 257 LLT SrcType = MRI.getType(Src1); 258 // As bizarre as it may look, shuffle vector can actually produce 259 // scalar! This is because at the IR level a <1 x ty> shuffle 260 // vector is perfectly valid. 261 unsigned DstNumElts = DstType.isVector() ? DstType.getNumElements() : 1; 262 unsigned SrcNumElts = SrcType.isVector() ? SrcType.getNumElements() : 1; 263 264 // If the resulting vector is smaller than the size of the source 265 // vectors being concatenated, we won't be able to replace the 266 // shuffle vector into a concat_vectors. 267 // 268 // Note: We may still be able to produce a concat_vectors fed by 269 // extract_vector_elt and so on. It is less clear that would 270 // be better though, so don't bother for now. 271 // 272 // If the destination is a scalar, the size of the sources doesn't 273 // matter. we will lower the shuffle to a plain copy. This will 274 // work only if the source and destination have the same size. But 275 // that's covered by the next condition. 276 // 277 // TODO: If the size between the source and destination don't match 278 // we could still emit an extract vector element in that case. 279 if (DstNumElts < 2 * SrcNumElts && DstNumElts != 1) 280 return false; 281 282 // Check that the shuffle mask can be broken evenly between the 283 // different sources. 284 if (DstNumElts % SrcNumElts != 0) 285 return false; 286 287 // Mask length is a multiple of the source vector length. 288 // Check if the shuffle is some kind of concatenation of the input 289 // vectors. 290 unsigned NumConcat = DstNumElts / SrcNumElts; 291 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 292 ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask(); 293 for (unsigned i = 0; i != DstNumElts; ++i) { 294 int Idx = Mask[i]; 295 // Undef value. 296 if (Idx < 0) 297 continue; 298 // Ensure the indices in each SrcType sized piece are sequential and that 299 // the same source is used for the whole piece. 300 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 301 (ConcatSrcs[i / SrcNumElts] >= 0 && 302 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) 303 return false; 304 // Remember which source this index came from. 305 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 306 } 307 308 // The shuffle is concatenating multiple vectors together. 309 // Collect the different operands for that. 310 Register UndefReg; 311 Register Src2 = MI.getOperand(2).getReg(); 312 for (auto Src : ConcatSrcs) { 313 if (Src < 0) { 314 if (!UndefReg) { 315 Builder.setInsertPt(*MI.getParent(), MI); 316 UndefReg = Builder.buildUndef(SrcType).getReg(0); 317 } 318 Ops.push_back(UndefReg); 319 } else if (Src == 0) 320 Ops.push_back(Src1); 321 else 322 Ops.push_back(Src2); 323 } 324 return true; 325 } 326 327 void CombinerHelper::applyCombineShuffleVector(MachineInstr &MI, 328 const ArrayRef<Register> Ops) { 329 Register DstReg = MI.getOperand(0).getReg(); 330 Builder.setInsertPt(*MI.getParent(), MI); 331 Register NewDstReg = MRI.cloneVirtualRegister(DstReg); 332 333 if (Ops.size() == 1) 334 Builder.buildCopy(NewDstReg, Ops[0]); 335 else 336 Builder.buildMerge(NewDstReg, Ops); 337 338 MI.eraseFromParent(); 339 replaceRegWith(MRI, DstReg, NewDstReg); 340 } 341 342 namespace { 343 344 /// Select a preference between two uses. CurrentUse is the current preference 345 /// while *ForCandidate is attributes of the candidate under consideration. 346 PreferredTuple ChoosePreferredUse(PreferredTuple &CurrentUse, 347 const LLT TyForCandidate, 348 unsigned OpcodeForCandidate, 349 MachineInstr *MIForCandidate) { 350 if (!CurrentUse.Ty.isValid()) { 351 if (CurrentUse.ExtendOpcode == OpcodeForCandidate || 352 CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT) 353 return {TyForCandidate, OpcodeForCandidate, MIForCandidate}; 354 return CurrentUse; 355 } 356 357 // We permit the extend to hoist through basic blocks but this is only 358 // sensible if the target has extending loads. If you end up lowering back 359 // into a load and extend during the legalizer then the end result is 360 // hoisting the extend up to the load. 361 362 // Prefer defined extensions to undefined extensions as these are more 363 // likely to reduce the number of instructions. 364 if (OpcodeForCandidate == TargetOpcode::G_ANYEXT && 365 CurrentUse.ExtendOpcode != TargetOpcode::G_ANYEXT) 366 return CurrentUse; 367 else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT && 368 OpcodeForCandidate != TargetOpcode::G_ANYEXT) 369 return {TyForCandidate, OpcodeForCandidate, MIForCandidate}; 370 371 // Prefer sign extensions to zero extensions as sign-extensions tend to be 372 // more expensive. 373 if (CurrentUse.Ty == TyForCandidate) { 374 if (CurrentUse.ExtendOpcode == TargetOpcode::G_SEXT && 375 OpcodeForCandidate == TargetOpcode::G_ZEXT) 376 return CurrentUse; 377 else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ZEXT && 378 OpcodeForCandidate == TargetOpcode::G_SEXT) 379 return {TyForCandidate, OpcodeForCandidate, MIForCandidate}; 380 } 381 382 // This is potentially target specific. We've chosen the largest type 383 // because G_TRUNC is usually free. One potential catch with this is that 384 // some targets have a reduced number of larger registers than smaller 385 // registers and this choice potentially increases the live-range for the 386 // larger value. 387 if (TyForCandidate.getSizeInBits() > CurrentUse.Ty.getSizeInBits()) { 388 return {TyForCandidate, OpcodeForCandidate, MIForCandidate}; 389 } 390 return CurrentUse; 391 } 392 393 /// Find a suitable place to insert some instructions and insert them. This 394 /// function accounts for special cases like inserting before a PHI node. 395 /// The current strategy for inserting before PHI's is to duplicate the 396 /// instructions for each predecessor. However, while that's ok for G_TRUNC 397 /// on most targets since it generally requires no code, other targets/cases may 398 /// want to try harder to find a dominating block. 399 static void InsertInsnsWithoutSideEffectsBeforeUse( 400 MachineIRBuilder &Builder, MachineInstr &DefMI, MachineOperand &UseMO, 401 std::function<void(MachineBasicBlock *, MachineBasicBlock::iterator, 402 MachineOperand &UseMO)> 403 Inserter) { 404 MachineInstr &UseMI = *UseMO.getParent(); 405 406 MachineBasicBlock *InsertBB = UseMI.getParent(); 407 408 // If the use is a PHI then we want the predecessor block instead. 409 if (UseMI.isPHI()) { 410 MachineOperand *PredBB = std::next(&UseMO); 411 InsertBB = PredBB->getMBB(); 412 } 413 414 // If the block is the same block as the def then we want to insert just after 415 // the def instead of at the start of the block. 416 if (InsertBB == DefMI.getParent()) { 417 MachineBasicBlock::iterator InsertPt = &DefMI; 418 Inserter(InsertBB, std::next(InsertPt), UseMO); 419 return; 420 } 421 422 // Otherwise we want the start of the BB 423 Inserter(InsertBB, InsertBB->getFirstNonPHI(), UseMO); 424 } 425 } // end anonymous namespace 426 427 bool CombinerHelper::tryCombineExtendingLoads(MachineInstr &MI) { 428 PreferredTuple Preferred; 429 if (matchCombineExtendingLoads(MI, Preferred)) { 430 applyCombineExtendingLoads(MI, Preferred); 431 return true; 432 } 433 return false; 434 } 435 436 bool CombinerHelper::matchCombineExtendingLoads(MachineInstr &MI, 437 PreferredTuple &Preferred) { 438 // We match the loads and follow the uses to the extend instead of matching 439 // the extends and following the def to the load. This is because the load 440 // must remain in the same position for correctness (unless we also add code 441 // to find a safe place to sink it) whereas the extend is freely movable. 442 // It also prevents us from duplicating the load for the volatile case or just 443 // for performance. 444 445 if (MI.getOpcode() != TargetOpcode::G_LOAD && 446 MI.getOpcode() != TargetOpcode::G_SEXTLOAD && 447 MI.getOpcode() != TargetOpcode::G_ZEXTLOAD) 448 return false; 449 450 auto &LoadValue = MI.getOperand(0); 451 assert(LoadValue.isReg() && "Result wasn't a register?"); 452 453 LLT LoadValueTy = MRI.getType(LoadValue.getReg()); 454 if (!LoadValueTy.isScalar()) 455 return false; 456 457 // Most architectures are going to legalize <s8 loads into at least a 1 byte 458 // load, and the MMOs can only describe memory accesses in multiples of bytes. 459 // If we try to perform extload combining on those, we can end up with 460 // %a(s8) = extload %ptr (load 1 byte from %ptr) 461 // ... which is an illegal extload instruction. 462 if (LoadValueTy.getSizeInBits() < 8) 463 return false; 464 465 // For non power-of-2 types, they will very likely be legalized into multiple 466 // loads. Don't bother trying to match them into extending loads. 467 if (!isPowerOf2_32(LoadValueTy.getSizeInBits())) 468 return false; 469 470 // Find the preferred type aside from the any-extends (unless it's the only 471 // one) and non-extending ops. We'll emit an extending load to that type and 472 // and emit a variant of (extend (trunc X)) for the others according to the 473 // relative type sizes. At the same time, pick an extend to use based on the 474 // extend involved in the chosen type. 475 unsigned PreferredOpcode = MI.getOpcode() == TargetOpcode::G_LOAD 476 ? TargetOpcode::G_ANYEXT 477 : MI.getOpcode() == TargetOpcode::G_SEXTLOAD 478 ? TargetOpcode::G_SEXT 479 : TargetOpcode::G_ZEXT; 480 Preferred = {LLT(), PreferredOpcode, nullptr}; 481 for (auto &UseMI : MRI.use_nodbg_instructions(LoadValue.getReg())) { 482 if (UseMI.getOpcode() == TargetOpcode::G_SEXT || 483 UseMI.getOpcode() == TargetOpcode::G_ZEXT || 484 (UseMI.getOpcode() == TargetOpcode::G_ANYEXT)) { 485 // Check for legality. 486 if (LI) { 487 LegalityQuery::MemDesc MMDesc; 488 const auto &MMO = **MI.memoperands_begin(); 489 MMDesc.SizeInBits = MMO.getSizeInBits(); 490 MMDesc.AlignInBits = MMO.getAlign().value() * 8; 491 MMDesc.Ordering = MMO.getOrdering(); 492 LLT UseTy = MRI.getType(UseMI.getOperand(0).getReg()); 493 LLT SrcTy = MRI.getType(MI.getOperand(1).getReg()); 494 if (LI->getAction({MI.getOpcode(), {UseTy, SrcTy}, {MMDesc}}).Action != 495 LegalizeActions::Legal) 496 continue; 497 } 498 Preferred = ChoosePreferredUse(Preferred, 499 MRI.getType(UseMI.getOperand(0).getReg()), 500 UseMI.getOpcode(), &UseMI); 501 } 502 } 503 504 // There were no extends 505 if (!Preferred.MI) 506 return false; 507 // It should be impossible to chose an extend without selecting a different 508 // type since by definition the result of an extend is larger. 509 assert(Preferred.Ty != LoadValueTy && "Extending to same type?"); 510 511 LLVM_DEBUG(dbgs() << "Preferred use is: " << *Preferred.MI); 512 return true; 513 } 514 515 void CombinerHelper::applyCombineExtendingLoads(MachineInstr &MI, 516 PreferredTuple &Preferred) { 517 // Rewrite the load to the chosen extending load. 518 Register ChosenDstReg = Preferred.MI->getOperand(0).getReg(); 519 520 // Inserter to insert a truncate back to the original type at a given point 521 // with some basic CSE to limit truncate duplication to one per BB. 522 DenseMap<MachineBasicBlock *, MachineInstr *> EmittedInsns; 523 auto InsertTruncAt = [&](MachineBasicBlock *InsertIntoBB, 524 MachineBasicBlock::iterator InsertBefore, 525 MachineOperand &UseMO) { 526 MachineInstr *PreviouslyEmitted = EmittedInsns.lookup(InsertIntoBB); 527 if (PreviouslyEmitted) { 528 Observer.changingInstr(*UseMO.getParent()); 529 UseMO.setReg(PreviouslyEmitted->getOperand(0).getReg()); 530 Observer.changedInstr(*UseMO.getParent()); 531 return; 532 } 533 534 Builder.setInsertPt(*InsertIntoBB, InsertBefore); 535 Register NewDstReg = MRI.cloneVirtualRegister(MI.getOperand(0).getReg()); 536 MachineInstr *NewMI = Builder.buildTrunc(NewDstReg, ChosenDstReg); 537 EmittedInsns[InsertIntoBB] = NewMI; 538 replaceRegOpWith(MRI, UseMO, NewDstReg); 539 }; 540 541 Observer.changingInstr(MI); 542 MI.setDesc( 543 Builder.getTII().get(Preferred.ExtendOpcode == TargetOpcode::G_SEXT 544 ? TargetOpcode::G_SEXTLOAD 545 : Preferred.ExtendOpcode == TargetOpcode::G_ZEXT 546 ? TargetOpcode::G_ZEXTLOAD 547 : TargetOpcode::G_LOAD)); 548 549 // Rewrite all the uses to fix up the types. 550 auto &LoadValue = MI.getOperand(0); 551 SmallVector<MachineOperand *, 4> Uses; 552 for (auto &UseMO : MRI.use_operands(LoadValue.getReg())) 553 Uses.push_back(&UseMO); 554 555 for (auto *UseMO : Uses) { 556 MachineInstr *UseMI = UseMO->getParent(); 557 558 // If the extend is compatible with the preferred extend then we should fix 559 // up the type and extend so that it uses the preferred use. 560 if (UseMI->getOpcode() == Preferred.ExtendOpcode || 561 UseMI->getOpcode() == TargetOpcode::G_ANYEXT) { 562 Register UseDstReg = UseMI->getOperand(0).getReg(); 563 MachineOperand &UseSrcMO = UseMI->getOperand(1); 564 const LLT UseDstTy = MRI.getType(UseDstReg); 565 if (UseDstReg != ChosenDstReg) { 566 if (Preferred.Ty == UseDstTy) { 567 // If the use has the same type as the preferred use, then merge 568 // the vregs and erase the extend. For example: 569 // %1:_(s8) = G_LOAD ... 570 // %2:_(s32) = G_SEXT %1(s8) 571 // %3:_(s32) = G_ANYEXT %1(s8) 572 // ... = ... %3(s32) 573 // rewrites to: 574 // %2:_(s32) = G_SEXTLOAD ... 575 // ... = ... %2(s32) 576 replaceRegWith(MRI, UseDstReg, ChosenDstReg); 577 Observer.erasingInstr(*UseMO->getParent()); 578 UseMO->getParent()->eraseFromParent(); 579 } else if (Preferred.Ty.getSizeInBits() < UseDstTy.getSizeInBits()) { 580 // If the preferred size is smaller, then keep the extend but extend 581 // from the result of the extending load. For example: 582 // %1:_(s8) = G_LOAD ... 583 // %2:_(s32) = G_SEXT %1(s8) 584 // %3:_(s64) = G_ANYEXT %1(s8) 585 // ... = ... %3(s64) 586 /// rewrites to: 587 // %2:_(s32) = G_SEXTLOAD ... 588 // %3:_(s64) = G_ANYEXT %2:_(s32) 589 // ... = ... %3(s64) 590 replaceRegOpWith(MRI, UseSrcMO, ChosenDstReg); 591 } else { 592 // If the preferred size is large, then insert a truncate. For 593 // example: 594 // %1:_(s8) = G_LOAD ... 595 // %2:_(s64) = G_SEXT %1(s8) 596 // %3:_(s32) = G_ZEXT %1(s8) 597 // ... = ... %3(s32) 598 /// rewrites to: 599 // %2:_(s64) = G_SEXTLOAD ... 600 // %4:_(s8) = G_TRUNC %2:_(s32) 601 // %3:_(s64) = G_ZEXT %2:_(s8) 602 // ... = ... %3(s64) 603 InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO, 604 InsertTruncAt); 605 } 606 continue; 607 } 608 // The use is (one of) the uses of the preferred use we chose earlier. 609 // We're going to update the load to def this value later so just erase 610 // the old extend. 611 Observer.erasingInstr(*UseMO->getParent()); 612 UseMO->getParent()->eraseFromParent(); 613 continue; 614 } 615 616 // The use isn't an extend. Truncate back to the type we originally loaded. 617 // This is free on many targets. 618 InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO, InsertTruncAt); 619 } 620 621 MI.getOperand(0).setReg(ChosenDstReg); 622 Observer.changedInstr(MI); 623 } 624 625 bool CombinerHelper::isPredecessor(const MachineInstr &DefMI, 626 const MachineInstr &UseMI) { 627 assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() && 628 "shouldn't consider debug uses"); 629 assert(DefMI.getParent() == UseMI.getParent()); 630 if (&DefMI == &UseMI) 631 return false; 632 const MachineBasicBlock &MBB = *DefMI.getParent(); 633 auto DefOrUse = find_if(MBB, [&DefMI, &UseMI](const MachineInstr &MI) { 634 return &MI == &DefMI || &MI == &UseMI; 635 }); 636 if (DefOrUse == MBB.end()) 637 llvm_unreachable("Block must contain both DefMI and UseMI!"); 638 return &*DefOrUse == &DefMI; 639 } 640 641 bool CombinerHelper::dominates(const MachineInstr &DefMI, 642 const MachineInstr &UseMI) { 643 assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() && 644 "shouldn't consider debug uses"); 645 if (MDT) 646 return MDT->dominates(&DefMI, &UseMI); 647 else if (DefMI.getParent() != UseMI.getParent()) 648 return false; 649 650 return isPredecessor(DefMI, UseMI); 651 } 652 653 bool CombinerHelper::matchSextTruncSextLoad(MachineInstr &MI) { 654 assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG); 655 Register SrcReg = MI.getOperand(1).getReg(); 656 Register LoadUser = SrcReg; 657 658 if (MRI.getType(SrcReg).isVector()) 659 return false; 660 661 Register TruncSrc; 662 if (mi_match(SrcReg, MRI, m_GTrunc(m_Reg(TruncSrc)))) 663 LoadUser = TruncSrc; 664 665 uint64_t SizeInBits = MI.getOperand(2).getImm(); 666 // If the source is a G_SEXTLOAD from the same bit width, then we don't 667 // need any extend at all, just a truncate. 668 if (auto *LoadMI = getOpcodeDef(TargetOpcode::G_SEXTLOAD, LoadUser, MRI)) { 669 const auto &MMO = **LoadMI->memoperands_begin(); 670 // If truncating more than the original extended value, abort. 671 if (TruncSrc && MRI.getType(TruncSrc).getSizeInBits() < MMO.getSizeInBits()) 672 return false; 673 if (MMO.getSizeInBits() == SizeInBits) 674 return true; 675 } 676 return false; 677 } 678 679 bool CombinerHelper::applySextTruncSextLoad(MachineInstr &MI) { 680 assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG); 681 Builder.setInstrAndDebugLoc(MI); 682 Builder.buildCopy(MI.getOperand(0).getReg(), MI.getOperand(1).getReg()); 683 MI.eraseFromParent(); 684 return true; 685 } 686 687 bool CombinerHelper::matchSextInRegOfLoad( 688 MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) { 689 assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG); 690 691 // Only supports scalars for now. 692 if (MRI.getType(MI.getOperand(0).getReg()).isVector()) 693 return false; 694 695 Register SrcReg = MI.getOperand(1).getReg(); 696 MachineInstr *LoadDef = getOpcodeDef(TargetOpcode::G_LOAD, SrcReg, MRI); 697 if (!LoadDef || !MRI.hasOneNonDBGUse(LoadDef->getOperand(0).getReg())) 698 return false; 699 700 // If the sign extend extends from a narrower width than the load's width, 701 // then we can narrow the load width when we combine to a G_SEXTLOAD. 702 auto &MMO = **LoadDef->memoperands_begin(); 703 // Don't do this for non-simple loads. 704 if (MMO.isAtomic() || MMO.isVolatile()) 705 return false; 706 707 // Avoid widening the load at all. 708 unsigned NewSizeBits = 709 std::min((uint64_t)MI.getOperand(2).getImm(), MMO.getSizeInBits()); 710 711 // Don't generate G_SEXTLOADs with a < 1 byte width. 712 if (NewSizeBits < 8) 713 return false; 714 // Don't bother creating a non-power-2 sextload, it will likely be broken up 715 // anyway for most targets. 716 if (!isPowerOf2_32(NewSizeBits)) 717 return false; 718 MatchInfo = std::make_tuple(LoadDef->getOperand(0).getReg(), NewSizeBits); 719 return true; 720 } 721 722 bool CombinerHelper::applySextInRegOfLoad( 723 MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) { 724 assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG); 725 Register LoadReg; 726 unsigned ScalarSizeBits; 727 std::tie(LoadReg, ScalarSizeBits) = MatchInfo; 728 auto *LoadDef = MRI.getVRegDef(LoadReg); 729 assert(LoadDef && "Expected a load reg"); 730 731 // If we have the following: 732 // %ld = G_LOAD %ptr, (load 2) 733 // %ext = G_SEXT_INREG %ld, 8 734 // ==> 735 // %ld = G_SEXTLOAD %ptr (load 1) 736 737 auto &MMO = **LoadDef->memoperands_begin(); 738 Builder.setInstrAndDebugLoc(*LoadDef); 739 auto &MF = Builder.getMF(); 740 auto PtrInfo = MMO.getPointerInfo(); 741 auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, ScalarSizeBits / 8); 742 Builder.buildLoadInstr(TargetOpcode::G_SEXTLOAD, MI.getOperand(0).getReg(), 743 LoadDef->getOperand(1).getReg(), *NewMMO); 744 MI.eraseFromParent(); 745 return true; 746 } 747 748 bool CombinerHelper::findPostIndexCandidate(MachineInstr &MI, Register &Addr, 749 Register &Base, Register &Offset) { 750 auto &MF = *MI.getParent()->getParent(); 751 const auto &TLI = *MF.getSubtarget().getTargetLowering(); 752 753 #ifndef NDEBUG 754 unsigned Opcode = MI.getOpcode(); 755 assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD || 756 Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE); 757 #endif 758 759 Base = MI.getOperand(1).getReg(); 760 MachineInstr *BaseDef = MRI.getUniqueVRegDef(Base); 761 if (BaseDef && BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) 762 return false; 763 764 LLVM_DEBUG(dbgs() << "Searching for post-indexing opportunity for: " << MI); 765 // FIXME: The following use traversal needs a bail out for patholigical cases. 766 for (auto &Use : MRI.use_nodbg_instructions(Base)) { 767 if (Use.getOpcode() != TargetOpcode::G_PTR_ADD) 768 continue; 769 770 Offset = Use.getOperand(2).getReg(); 771 if (!ForceLegalIndexing && 772 !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ false, MRI)) { 773 LLVM_DEBUG(dbgs() << " Ignoring candidate with illegal addrmode: " 774 << Use); 775 continue; 776 } 777 778 // Make sure the offset calculation is before the potentially indexed op. 779 // FIXME: we really care about dependency here. The offset calculation might 780 // be movable. 781 MachineInstr *OffsetDef = MRI.getUniqueVRegDef(Offset); 782 if (!OffsetDef || !dominates(*OffsetDef, MI)) { 783 LLVM_DEBUG(dbgs() << " Ignoring candidate with offset after mem-op: " 784 << Use); 785 continue; 786 } 787 788 // FIXME: check whether all uses of Base are load/store with foldable 789 // addressing modes. If so, using the normal addr-modes is better than 790 // forming an indexed one. 791 792 bool MemOpDominatesAddrUses = true; 793 for (auto &PtrAddUse : 794 MRI.use_nodbg_instructions(Use.getOperand(0).getReg())) { 795 if (!dominates(MI, PtrAddUse)) { 796 MemOpDominatesAddrUses = false; 797 break; 798 } 799 } 800 801 if (!MemOpDominatesAddrUses) { 802 LLVM_DEBUG( 803 dbgs() << " Ignoring candidate as memop does not dominate uses: " 804 << Use); 805 continue; 806 } 807 808 LLVM_DEBUG(dbgs() << " Found match: " << Use); 809 Addr = Use.getOperand(0).getReg(); 810 return true; 811 } 812 813 return false; 814 } 815 816 bool CombinerHelper::findPreIndexCandidate(MachineInstr &MI, Register &Addr, 817 Register &Base, Register &Offset) { 818 auto &MF = *MI.getParent()->getParent(); 819 const auto &TLI = *MF.getSubtarget().getTargetLowering(); 820 821 #ifndef NDEBUG 822 unsigned Opcode = MI.getOpcode(); 823 assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD || 824 Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE); 825 #endif 826 827 Addr = MI.getOperand(1).getReg(); 828 MachineInstr *AddrDef = getOpcodeDef(TargetOpcode::G_PTR_ADD, Addr, MRI); 829 if (!AddrDef || MRI.hasOneNonDBGUse(Addr)) 830 return false; 831 832 Base = AddrDef->getOperand(1).getReg(); 833 Offset = AddrDef->getOperand(2).getReg(); 834 835 LLVM_DEBUG(dbgs() << "Found potential pre-indexed load_store: " << MI); 836 837 if (!ForceLegalIndexing && 838 !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ true, MRI)) { 839 LLVM_DEBUG(dbgs() << " Skipping, not legal for target"); 840 return false; 841 } 842 843 MachineInstr *BaseDef = getDefIgnoringCopies(Base, MRI); 844 if (BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) { 845 LLVM_DEBUG(dbgs() << " Skipping, frame index would need copy anyway."); 846 return false; 847 } 848 849 if (MI.getOpcode() == TargetOpcode::G_STORE) { 850 // Would require a copy. 851 if (Base == MI.getOperand(0).getReg()) { 852 LLVM_DEBUG(dbgs() << " Skipping, storing base so need copy anyway."); 853 return false; 854 } 855 856 // We're expecting one use of Addr in MI, but it could also be the 857 // value stored, which isn't actually dominated by the instruction. 858 if (MI.getOperand(0).getReg() == Addr) { 859 LLVM_DEBUG(dbgs() << " Skipping, does not dominate all addr uses"); 860 return false; 861 } 862 } 863 864 // FIXME: check whether all uses of the base pointer are constant PtrAdds. 865 // That might allow us to end base's liveness here by adjusting the constant. 866 867 for (auto &UseMI : MRI.use_nodbg_instructions(Addr)) { 868 if (!dominates(MI, UseMI)) { 869 LLVM_DEBUG(dbgs() << " Skipping, does not dominate all addr uses."); 870 return false; 871 } 872 } 873 874 return true; 875 } 876 877 bool CombinerHelper::tryCombineIndexedLoadStore(MachineInstr &MI) { 878 IndexedLoadStoreMatchInfo MatchInfo; 879 if (matchCombineIndexedLoadStore(MI, MatchInfo)) { 880 applyCombineIndexedLoadStore(MI, MatchInfo); 881 return true; 882 } 883 return false; 884 } 885 886 bool CombinerHelper::matchCombineIndexedLoadStore(MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) { 887 unsigned Opcode = MI.getOpcode(); 888 if (Opcode != TargetOpcode::G_LOAD && Opcode != TargetOpcode::G_SEXTLOAD && 889 Opcode != TargetOpcode::G_ZEXTLOAD && Opcode != TargetOpcode::G_STORE) 890 return false; 891 892 // For now, no targets actually support these opcodes so don't waste time 893 // running these unless we're forced to for testing. 894 if (!ForceLegalIndexing) 895 return false; 896 897 MatchInfo.IsPre = findPreIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base, 898 MatchInfo.Offset); 899 if (!MatchInfo.IsPre && 900 !findPostIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base, 901 MatchInfo.Offset)) 902 return false; 903 904 return true; 905 } 906 907 void CombinerHelper::applyCombineIndexedLoadStore( 908 MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) { 909 MachineInstr &AddrDef = *MRI.getUniqueVRegDef(MatchInfo.Addr); 910 MachineIRBuilder MIRBuilder(MI); 911 unsigned Opcode = MI.getOpcode(); 912 bool IsStore = Opcode == TargetOpcode::G_STORE; 913 unsigned NewOpcode; 914 switch (Opcode) { 915 case TargetOpcode::G_LOAD: 916 NewOpcode = TargetOpcode::G_INDEXED_LOAD; 917 break; 918 case TargetOpcode::G_SEXTLOAD: 919 NewOpcode = TargetOpcode::G_INDEXED_SEXTLOAD; 920 break; 921 case TargetOpcode::G_ZEXTLOAD: 922 NewOpcode = TargetOpcode::G_INDEXED_ZEXTLOAD; 923 break; 924 case TargetOpcode::G_STORE: 925 NewOpcode = TargetOpcode::G_INDEXED_STORE; 926 break; 927 default: 928 llvm_unreachable("Unknown load/store opcode"); 929 } 930 931 auto MIB = MIRBuilder.buildInstr(NewOpcode); 932 if (IsStore) { 933 MIB.addDef(MatchInfo.Addr); 934 MIB.addUse(MI.getOperand(0).getReg()); 935 } else { 936 MIB.addDef(MI.getOperand(0).getReg()); 937 MIB.addDef(MatchInfo.Addr); 938 } 939 940 MIB.addUse(MatchInfo.Base); 941 MIB.addUse(MatchInfo.Offset); 942 MIB.addImm(MatchInfo.IsPre); 943 MI.eraseFromParent(); 944 AddrDef.eraseFromParent(); 945 946 LLVM_DEBUG(dbgs() << " Combinined to indexed operation"); 947 } 948 949 bool CombinerHelper::matchCombineDivRem(MachineInstr &MI, 950 MachineInstr *&OtherMI) { 951 unsigned Opcode = MI.getOpcode(); 952 bool IsDiv, IsSigned; 953 954 switch (Opcode) { 955 default: 956 llvm_unreachable("Unexpected opcode!"); 957 case TargetOpcode::G_SDIV: 958 case TargetOpcode::G_UDIV: { 959 IsDiv = true; 960 IsSigned = Opcode == TargetOpcode::G_SDIV; 961 break; 962 } 963 case TargetOpcode::G_SREM: 964 case TargetOpcode::G_UREM: { 965 IsDiv = false; 966 IsSigned = Opcode == TargetOpcode::G_SREM; 967 break; 968 } 969 } 970 971 Register Src1 = MI.getOperand(1).getReg(); 972 unsigned DivOpcode, RemOpcode, DivremOpcode; 973 if (IsSigned) { 974 DivOpcode = TargetOpcode::G_SDIV; 975 RemOpcode = TargetOpcode::G_SREM; 976 DivremOpcode = TargetOpcode::G_SDIVREM; 977 } else { 978 DivOpcode = TargetOpcode::G_UDIV; 979 RemOpcode = TargetOpcode::G_UREM; 980 DivremOpcode = TargetOpcode::G_UDIVREM; 981 } 982 983 if (!isLegalOrBeforeLegalizer({DivremOpcode, {MRI.getType(Src1)}})) 984 return false; 985 986 // Combine: 987 // %div:_ = G_[SU]DIV %src1:_, %src2:_ 988 // %rem:_ = G_[SU]REM %src1:_, %src2:_ 989 // into: 990 // %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_ 991 992 // Combine: 993 // %rem:_ = G_[SU]REM %src1:_, %src2:_ 994 // %div:_ = G_[SU]DIV %src1:_, %src2:_ 995 // into: 996 // %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_ 997 998 for (auto &UseMI : MRI.use_nodbg_instructions(Src1)) { 999 if (MI.getParent() == UseMI.getParent() && 1000 ((IsDiv && UseMI.getOpcode() == RemOpcode) || 1001 (!IsDiv && UseMI.getOpcode() == DivOpcode)) && 1002 matchEqualDefs(MI.getOperand(2), UseMI.getOperand(2))) { 1003 OtherMI = &UseMI; 1004 return true; 1005 } 1006 } 1007 1008 return false; 1009 } 1010 1011 void CombinerHelper::applyCombineDivRem(MachineInstr &MI, 1012 MachineInstr *&OtherMI) { 1013 unsigned Opcode = MI.getOpcode(); 1014 assert(OtherMI && "OtherMI shouldn't be empty."); 1015 1016 Register DestDivReg, DestRemReg; 1017 if (Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_UDIV) { 1018 DestDivReg = MI.getOperand(0).getReg(); 1019 DestRemReg = OtherMI->getOperand(0).getReg(); 1020 } else { 1021 DestDivReg = OtherMI->getOperand(0).getReg(); 1022 DestRemReg = MI.getOperand(0).getReg(); 1023 } 1024 1025 bool IsSigned = 1026 Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_SREM; 1027 Builder.setInstrAndDebugLoc(MI); 1028 Builder.buildInstr(IsSigned ? TargetOpcode::G_SDIVREM 1029 : TargetOpcode::G_UDIVREM, 1030 {DestDivReg, DestRemReg}, 1031 {MI.getOperand(1).getReg(), MI.getOperand(2).getReg()}); 1032 MI.eraseFromParent(); 1033 OtherMI->eraseFromParent(); 1034 } 1035 1036 bool CombinerHelper::matchOptBrCondByInvertingCond(MachineInstr &MI, 1037 MachineInstr *&BrCond) { 1038 assert(MI.getOpcode() == TargetOpcode::G_BR); 1039 1040 // Try to match the following: 1041 // bb1: 1042 // G_BRCOND %c1, %bb2 1043 // G_BR %bb3 1044 // bb2: 1045 // ... 1046 // bb3: 1047 1048 // The above pattern does not have a fall through to the successor bb2, always 1049 // resulting in a branch no matter which path is taken. Here we try to find 1050 // and replace that pattern with conditional branch to bb3 and otherwise 1051 // fallthrough to bb2. This is generally better for branch predictors. 1052 1053 MachineBasicBlock *MBB = MI.getParent(); 1054 MachineBasicBlock::iterator BrIt(MI); 1055 if (BrIt == MBB->begin()) 1056 return false; 1057 assert(std::next(BrIt) == MBB->end() && "expected G_BR to be a terminator"); 1058 1059 BrCond = &*std::prev(BrIt); 1060 if (BrCond->getOpcode() != TargetOpcode::G_BRCOND) 1061 return false; 1062 1063 // Check that the next block is the conditional branch target. Also make sure 1064 // that it isn't the same as the G_BR's target (otherwise, this will loop.) 1065 MachineBasicBlock *BrCondTarget = BrCond->getOperand(1).getMBB(); 1066 return BrCondTarget != MI.getOperand(0).getMBB() && 1067 MBB->isLayoutSuccessor(BrCondTarget); 1068 } 1069 1070 void CombinerHelper::applyOptBrCondByInvertingCond(MachineInstr &MI, 1071 MachineInstr *&BrCond) { 1072 MachineBasicBlock *BrTarget = MI.getOperand(0).getMBB(); 1073 Builder.setInstrAndDebugLoc(*BrCond); 1074 LLT Ty = MRI.getType(BrCond->getOperand(0).getReg()); 1075 // FIXME: Does int/fp matter for this? If so, we might need to restrict 1076 // this to i1 only since we might not know for sure what kind of 1077 // compare generated the condition value. 1078 auto True = Builder.buildConstant( 1079 Ty, getICmpTrueVal(getTargetLowering(), false, false)); 1080 auto Xor = Builder.buildXor(Ty, BrCond->getOperand(0), True); 1081 1082 auto *FallthroughBB = BrCond->getOperand(1).getMBB(); 1083 Observer.changingInstr(MI); 1084 MI.getOperand(0).setMBB(FallthroughBB); 1085 Observer.changedInstr(MI); 1086 1087 // Change the conditional branch to use the inverted condition and 1088 // new target block. 1089 Observer.changingInstr(*BrCond); 1090 BrCond->getOperand(0).setReg(Xor.getReg(0)); 1091 BrCond->getOperand(1).setMBB(BrTarget); 1092 Observer.changedInstr(*BrCond); 1093 } 1094 1095 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) { 1096 // On Darwin, -Os means optimize for size without hurting performance, so 1097 // only really optimize for size when -Oz (MinSize) is used. 1098 if (MF.getTarget().getTargetTriple().isOSDarwin()) 1099 return MF.getFunction().hasMinSize(); 1100 return MF.getFunction().hasOptSize(); 1101 } 1102 1103 // Returns a list of types to use for memory op lowering in MemOps. A partial 1104 // port of findOptimalMemOpLowering in TargetLowering. 1105 static bool findGISelOptimalMemOpLowering(std::vector<LLT> &MemOps, 1106 unsigned Limit, const MemOp &Op, 1107 unsigned DstAS, unsigned SrcAS, 1108 const AttributeList &FuncAttributes, 1109 const TargetLowering &TLI) { 1110 if (Op.isMemcpyWithFixedDstAlign() && Op.getSrcAlign() < Op.getDstAlign()) 1111 return false; 1112 1113 LLT Ty = TLI.getOptimalMemOpLLT(Op, FuncAttributes); 1114 1115 if (Ty == LLT()) { 1116 // Use the largest scalar type whose alignment constraints are satisfied. 1117 // We only need to check DstAlign here as SrcAlign is always greater or 1118 // equal to DstAlign (or zero). 1119 Ty = LLT::scalar(64); 1120 if (Op.isFixedDstAlign()) 1121 while (Op.getDstAlign() < Ty.getSizeInBytes() && 1122 !TLI.allowsMisalignedMemoryAccesses(Ty, DstAS, Op.getDstAlign())) 1123 Ty = LLT::scalar(Ty.getSizeInBytes()); 1124 assert(Ty.getSizeInBits() > 0 && "Could not find valid type"); 1125 // FIXME: check for the largest legal type we can load/store to. 1126 } 1127 1128 unsigned NumMemOps = 0; 1129 uint64_t Size = Op.size(); 1130 while (Size) { 1131 unsigned TySize = Ty.getSizeInBytes(); 1132 while (TySize > Size) { 1133 // For now, only use non-vector load / store's for the left-over pieces. 1134 LLT NewTy = Ty; 1135 // FIXME: check for mem op safety and legality of the types. Not all of 1136 // SDAGisms map cleanly to GISel concepts. 1137 if (NewTy.isVector()) 1138 NewTy = NewTy.getSizeInBits() > 64 ? LLT::scalar(64) : LLT::scalar(32); 1139 NewTy = LLT::scalar(PowerOf2Floor(NewTy.getSizeInBits() - 1)); 1140 unsigned NewTySize = NewTy.getSizeInBytes(); 1141 assert(NewTySize > 0 && "Could not find appropriate type"); 1142 1143 // If the new LLT cannot cover all of the remaining bits, then consider 1144 // issuing a (or a pair of) unaligned and overlapping load / store. 1145 bool Fast; 1146 // Need to get a VT equivalent for allowMisalignedMemoryAccesses(). 1147 MVT VT = getMVTForLLT(Ty); 1148 if (NumMemOps && Op.allowOverlap() && NewTySize < Size && 1149 TLI.allowsMisalignedMemoryAccesses( 1150 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1), 1151 MachineMemOperand::MONone, &Fast) && 1152 Fast) 1153 TySize = Size; 1154 else { 1155 Ty = NewTy; 1156 TySize = NewTySize; 1157 } 1158 } 1159 1160 if (++NumMemOps > Limit) 1161 return false; 1162 1163 MemOps.push_back(Ty); 1164 Size -= TySize; 1165 } 1166 1167 return true; 1168 } 1169 1170 static Type *getTypeForLLT(LLT Ty, LLVMContext &C) { 1171 if (Ty.isVector()) 1172 return FixedVectorType::get(IntegerType::get(C, Ty.getScalarSizeInBits()), 1173 Ty.getNumElements()); 1174 return IntegerType::get(C, Ty.getSizeInBits()); 1175 } 1176 1177 // Get a vectorized representation of the memset value operand, GISel edition. 1178 static Register getMemsetValue(Register Val, LLT Ty, MachineIRBuilder &MIB) { 1179 MachineRegisterInfo &MRI = *MIB.getMRI(); 1180 unsigned NumBits = Ty.getScalarSizeInBits(); 1181 auto ValVRegAndVal = getConstantVRegValWithLookThrough(Val, MRI); 1182 if (!Ty.isVector() && ValVRegAndVal) { 1183 APInt Scalar = ValVRegAndVal->Value.truncOrSelf(8); 1184 APInt SplatVal = APInt::getSplat(NumBits, Scalar); 1185 return MIB.buildConstant(Ty, SplatVal).getReg(0); 1186 } 1187 1188 // Extend the byte value to the larger type, and then multiply by a magic 1189 // value 0x010101... in order to replicate it across every byte. 1190 // Unless it's zero, in which case just emit a larger G_CONSTANT 0. 1191 if (ValVRegAndVal && ValVRegAndVal->Value == 0) { 1192 return MIB.buildConstant(Ty, 0).getReg(0); 1193 } 1194 1195 LLT ExtType = Ty.getScalarType(); 1196 auto ZExt = MIB.buildZExtOrTrunc(ExtType, Val); 1197 if (NumBits > 8) { 1198 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 1199 auto MagicMI = MIB.buildConstant(ExtType, Magic); 1200 Val = MIB.buildMul(ExtType, ZExt, MagicMI).getReg(0); 1201 } 1202 1203 // For vector types create a G_BUILD_VECTOR. 1204 if (Ty.isVector()) 1205 Val = MIB.buildSplatVector(Ty, Val).getReg(0); 1206 1207 return Val; 1208 } 1209 1210 bool CombinerHelper::optimizeMemset(MachineInstr &MI, Register Dst, 1211 Register Val, unsigned KnownLen, 1212 Align Alignment, bool IsVolatile) { 1213 auto &MF = *MI.getParent()->getParent(); 1214 const auto &TLI = *MF.getSubtarget().getTargetLowering(); 1215 auto &DL = MF.getDataLayout(); 1216 LLVMContext &C = MF.getFunction().getContext(); 1217 1218 assert(KnownLen != 0 && "Have a zero length memset length!"); 1219 1220 bool DstAlignCanChange = false; 1221 MachineFrameInfo &MFI = MF.getFrameInfo(); 1222 bool OptSize = shouldLowerMemFuncForSize(MF); 1223 1224 MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI); 1225 if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex())) 1226 DstAlignCanChange = true; 1227 1228 unsigned Limit = TLI.getMaxStoresPerMemset(OptSize); 1229 std::vector<LLT> MemOps; 1230 1231 const auto &DstMMO = **MI.memoperands_begin(); 1232 MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo(); 1233 1234 auto ValVRegAndVal = getConstantVRegValWithLookThrough(Val, MRI); 1235 bool IsZeroVal = ValVRegAndVal && ValVRegAndVal->Value == 0; 1236 1237 if (!findGISelOptimalMemOpLowering(MemOps, Limit, 1238 MemOp::Set(KnownLen, DstAlignCanChange, 1239 Alignment, 1240 /*IsZeroMemset=*/IsZeroVal, 1241 /*IsVolatile=*/IsVolatile), 1242 DstPtrInfo.getAddrSpace(), ~0u, 1243 MF.getFunction().getAttributes(), TLI)) 1244 return false; 1245 1246 if (DstAlignCanChange) { 1247 // Get an estimate of the type from the LLT. 1248 Type *IRTy = getTypeForLLT(MemOps[0], C); 1249 Align NewAlign = DL.getABITypeAlign(IRTy); 1250 if (NewAlign > Alignment) { 1251 Alignment = NewAlign; 1252 unsigned FI = FIDef->getOperand(1).getIndex(); 1253 // Give the stack frame object a larger alignment if needed. 1254 if (MFI.getObjectAlign(FI) < Alignment) 1255 MFI.setObjectAlignment(FI, Alignment); 1256 } 1257 } 1258 1259 MachineIRBuilder MIB(MI); 1260 // Find the largest store and generate the bit pattern for it. 1261 LLT LargestTy = MemOps[0]; 1262 for (unsigned i = 1; i < MemOps.size(); i++) 1263 if (MemOps[i].getSizeInBits() > LargestTy.getSizeInBits()) 1264 LargestTy = MemOps[i]; 1265 1266 // The memset stored value is always defined as an s8, so in order to make it 1267 // work with larger store types we need to repeat the bit pattern across the 1268 // wider type. 1269 Register MemSetValue = getMemsetValue(Val, LargestTy, MIB); 1270 1271 if (!MemSetValue) 1272 return false; 1273 1274 // Generate the stores. For each store type in the list, we generate the 1275 // matching store of that type to the destination address. 1276 LLT PtrTy = MRI.getType(Dst); 1277 unsigned DstOff = 0; 1278 unsigned Size = KnownLen; 1279 for (unsigned I = 0; I < MemOps.size(); I++) { 1280 LLT Ty = MemOps[I]; 1281 unsigned TySize = Ty.getSizeInBytes(); 1282 if (TySize > Size) { 1283 // Issuing an unaligned load / store pair that overlaps with the previous 1284 // pair. Adjust the offset accordingly. 1285 assert(I == MemOps.size() - 1 && I != 0); 1286 DstOff -= TySize - Size; 1287 } 1288 1289 // If this store is smaller than the largest store see whether we can get 1290 // the smaller value for free with a truncate. 1291 Register Value = MemSetValue; 1292 if (Ty.getSizeInBits() < LargestTy.getSizeInBits()) { 1293 MVT VT = getMVTForLLT(Ty); 1294 MVT LargestVT = getMVTForLLT(LargestTy); 1295 if (!LargestTy.isVector() && !Ty.isVector() && 1296 TLI.isTruncateFree(LargestVT, VT)) 1297 Value = MIB.buildTrunc(Ty, MemSetValue).getReg(0); 1298 else 1299 Value = getMemsetValue(Val, Ty, MIB); 1300 if (!Value) 1301 return false; 1302 } 1303 1304 auto *StoreMMO = 1305 MF.getMachineMemOperand(&DstMMO, DstOff, Ty.getSizeInBytes()); 1306 1307 Register Ptr = Dst; 1308 if (DstOff != 0) { 1309 auto Offset = 1310 MIB.buildConstant(LLT::scalar(PtrTy.getSizeInBits()), DstOff); 1311 Ptr = MIB.buildPtrAdd(PtrTy, Dst, Offset).getReg(0); 1312 } 1313 1314 MIB.buildStore(Value, Ptr, *StoreMMO); 1315 DstOff += Ty.getSizeInBytes(); 1316 Size -= TySize; 1317 } 1318 1319 MI.eraseFromParent(); 1320 return true; 1321 } 1322 1323 bool CombinerHelper::optimizeMemcpy(MachineInstr &MI, Register Dst, 1324 Register Src, unsigned KnownLen, 1325 Align DstAlign, Align SrcAlign, 1326 bool IsVolatile) { 1327 auto &MF = *MI.getParent()->getParent(); 1328 const auto &TLI = *MF.getSubtarget().getTargetLowering(); 1329 auto &DL = MF.getDataLayout(); 1330 LLVMContext &C = MF.getFunction().getContext(); 1331 1332 assert(KnownLen != 0 && "Have a zero length memcpy length!"); 1333 1334 bool DstAlignCanChange = false; 1335 MachineFrameInfo &MFI = MF.getFrameInfo(); 1336 bool OptSize = shouldLowerMemFuncForSize(MF); 1337 Align Alignment = commonAlignment(DstAlign, SrcAlign); 1338 1339 MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI); 1340 if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex())) 1341 DstAlignCanChange = true; 1342 1343 // FIXME: infer better src pointer alignment like SelectionDAG does here. 1344 // FIXME: also use the equivalent of isMemSrcFromConstant and alwaysinlining 1345 // if the memcpy is in a tail call position. 1346 1347 unsigned Limit = TLI.getMaxStoresPerMemcpy(OptSize); 1348 std::vector<LLT> MemOps; 1349 1350 const auto &DstMMO = **MI.memoperands_begin(); 1351 const auto &SrcMMO = **std::next(MI.memoperands_begin()); 1352 MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo(); 1353 MachinePointerInfo SrcPtrInfo = SrcMMO.getPointerInfo(); 1354 1355 if (!findGISelOptimalMemOpLowering( 1356 MemOps, Limit, 1357 MemOp::Copy(KnownLen, DstAlignCanChange, Alignment, SrcAlign, 1358 IsVolatile), 1359 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 1360 MF.getFunction().getAttributes(), TLI)) 1361 return false; 1362 1363 if (DstAlignCanChange) { 1364 // Get an estimate of the type from the LLT. 1365 Type *IRTy = getTypeForLLT(MemOps[0], C); 1366 Align NewAlign = DL.getABITypeAlign(IRTy); 1367 1368 // Don't promote to an alignment that would require dynamic stack 1369 // realignment. 1370 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1371 if (!TRI->hasStackRealignment(MF)) 1372 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 1373 NewAlign = NewAlign / 2; 1374 1375 if (NewAlign > Alignment) { 1376 Alignment = NewAlign; 1377 unsigned FI = FIDef->getOperand(1).getIndex(); 1378 // Give the stack frame object a larger alignment if needed. 1379 if (MFI.getObjectAlign(FI) < Alignment) 1380 MFI.setObjectAlignment(FI, Alignment); 1381 } 1382 } 1383 1384 LLVM_DEBUG(dbgs() << "Inlining memcpy: " << MI << " into loads & stores\n"); 1385 1386 MachineIRBuilder MIB(MI); 1387 // Now we need to emit a pair of load and stores for each of the types we've 1388 // collected. I.e. for each type, generate a load from the source pointer of 1389 // that type width, and then generate a corresponding store to the dest buffer 1390 // of that value loaded. This can result in a sequence of loads and stores 1391 // mixed types, depending on what the target specifies as good types to use. 1392 unsigned CurrOffset = 0; 1393 LLT PtrTy = MRI.getType(Src); 1394 unsigned Size = KnownLen; 1395 for (auto CopyTy : MemOps) { 1396 // Issuing an unaligned load / store pair that overlaps with the previous 1397 // pair. Adjust the offset accordingly. 1398 if (CopyTy.getSizeInBytes() > Size) 1399 CurrOffset -= CopyTy.getSizeInBytes() - Size; 1400 1401 // Construct MMOs for the accesses. 1402 auto *LoadMMO = 1403 MF.getMachineMemOperand(&SrcMMO, CurrOffset, CopyTy.getSizeInBytes()); 1404 auto *StoreMMO = 1405 MF.getMachineMemOperand(&DstMMO, CurrOffset, CopyTy.getSizeInBytes()); 1406 1407 // Create the load. 1408 Register LoadPtr = Src; 1409 Register Offset; 1410 if (CurrOffset != 0) { 1411 Offset = MIB.buildConstant(LLT::scalar(PtrTy.getSizeInBits()), CurrOffset) 1412 .getReg(0); 1413 LoadPtr = MIB.buildPtrAdd(PtrTy, Src, Offset).getReg(0); 1414 } 1415 auto LdVal = MIB.buildLoad(CopyTy, LoadPtr, *LoadMMO); 1416 1417 // Create the store. 1418 Register StorePtr = 1419 CurrOffset == 0 ? Dst : MIB.buildPtrAdd(PtrTy, Dst, Offset).getReg(0); 1420 MIB.buildStore(LdVal, StorePtr, *StoreMMO); 1421 CurrOffset += CopyTy.getSizeInBytes(); 1422 Size -= CopyTy.getSizeInBytes(); 1423 } 1424 1425 MI.eraseFromParent(); 1426 return true; 1427 } 1428 1429 bool CombinerHelper::optimizeMemmove(MachineInstr &MI, Register Dst, 1430 Register Src, unsigned KnownLen, 1431 Align DstAlign, Align SrcAlign, 1432 bool IsVolatile) { 1433 auto &MF = *MI.getParent()->getParent(); 1434 const auto &TLI = *MF.getSubtarget().getTargetLowering(); 1435 auto &DL = MF.getDataLayout(); 1436 LLVMContext &C = MF.getFunction().getContext(); 1437 1438 assert(KnownLen != 0 && "Have a zero length memmove length!"); 1439 1440 bool DstAlignCanChange = false; 1441 MachineFrameInfo &MFI = MF.getFrameInfo(); 1442 bool OptSize = shouldLowerMemFuncForSize(MF); 1443 Align Alignment = commonAlignment(DstAlign, SrcAlign); 1444 1445 MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI); 1446 if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex())) 1447 DstAlignCanChange = true; 1448 1449 unsigned Limit = TLI.getMaxStoresPerMemmove(OptSize); 1450 std::vector<LLT> MemOps; 1451 1452 const auto &DstMMO = **MI.memoperands_begin(); 1453 const auto &SrcMMO = **std::next(MI.memoperands_begin()); 1454 MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo(); 1455 MachinePointerInfo SrcPtrInfo = SrcMMO.getPointerInfo(); 1456 1457 // FIXME: SelectionDAG always passes false for 'AllowOverlap', apparently due 1458 // to a bug in it's findOptimalMemOpLowering implementation. For now do the 1459 // same thing here. 1460 if (!findGISelOptimalMemOpLowering( 1461 MemOps, Limit, 1462 MemOp::Copy(KnownLen, DstAlignCanChange, Alignment, SrcAlign, 1463 /*IsVolatile*/ true), 1464 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 1465 MF.getFunction().getAttributes(), TLI)) 1466 return false; 1467 1468 if (DstAlignCanChange) { 1469 // Get an estimate of the type from the LLT. 1470 Type *IRTy = getTypeForLLT(MemOps[0], C); 1471 Align NewAlign = DL.getABITypeAlign(IRTy); 1472 1473 // Don't promote to an alignment that would require dynamic stack 1474 // realignment. 1475 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1476 if (!TRI->hasStackRealignment(MF)) 1477 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 1478 NewAlign = NewAlign / 2; 1479 1480 if (NewAlign > Alignment) { 1481 Alignment = NewAlign; 1482 unsigned FI = FIDef->getOperand(1).getIndex(); 1483 // Give the stack frame object a larger alignment if needed. 1484 if (MFI.getObjectAlign(FI) < Alignment) 1485 MFI.setObjectAlignment(FI, Alignment); 1486 } 1487 } 1488 1489 LLVM_DEBUG(dbgs() << "Inlining memmove: " << MI << " into loads & stores\n"); 1490 1491 MachineIRBuilder MIB(MI); 1492 // Memmove requires that we perform the loads first before issuing the stores. 1493 // Apart from that, this loop is pretty much doing the same thing as the 1494 // memcpy codegen function. 1495 unsigned CurrOffset = 0; 1496 LLT PtrTy = MRI.getType(Src); 1497 SmallVector<Register, 16> LoadVals; 1498 for (auto CopyTy : MemOps) { 1499 // Construct MMO for the load. 1500 auto *LoadMMO = 1501 MF.getMachineMemOperand(&SrcMMO, CurrOffset, CopyTy.getSizeInBytes()); 1502 1503 // Create the load. 1504 Register LoadPtr = Src; 1505 if (CurrOffset != 0) { 1506 auto Offset = 1507 MIB.buildConstant(LLT::scalar(PtrTy.getSizeInBits()), CurrOffset); 1508 LoadPtr = MIB.buildPtrAdd(PtrTy, Src, Offset).getReg(0); 1509 } 1510 LoadVals.push_back(MIB.buildLoad(CopyTy, LoadPtr, *LoadMMO).getReg(0)); 1511 CurrOffset += CopyTy.getSizeInBytes(); 1512 } 1513 1514 CurrOffset = 0; 1515 for (unsigned I = 0; I < MemOps.size(); ++I) { 1516 LLT CopyTy = MemOps[I]; 1517 // Now store the values loaded. 1518 auto *StoreMMO = 1519 MF.getMachineMemOperand(&DstMMO, CurrOffset, CopyTy.getSizeInBytes()); 1520 1521 Register StorePtr = Dst; 1522 if (CurrOffset != 0) { 1523 auto Offset = 1524 MIB.buildConstant(LLT::scalar(PtrTy.getSizeInBits()), CurrOffset); 1525 StorePtr = MIB.buildPtrAdd(PtrTy, Dst, Offset).getReg(0); 1526 } 1527 MIB.buildStore(LoadVals[I], StorePtr, *StoreMMO); 1528 CurrOffset += CopyTy.getSizeInBytes(); 1529 } 1530 MI.eraseFromParent(); 1531 return true; 1532 } 1533 1534 bool CombinerHelper::tryCombineMemCpyFamily(MachineInstr &MI, unsigned MaxLen) { 1535 const unsigned Opc = MI.getOpcode(); 1536 // This combine is fairly complex so it's not written with a separate 1537 // matcher function. 1538 assert((Opc == TargetOpcode::G_MEMCPY || Opc == TargetOpcode::G_MEMMOVE || 1539 Opc == TargetOpcode::G_MEMSET) && "Expected memcpy like instruction"); 1540 1541 auto MMOIt = MI.memoperands_begin(); 1542 const MachineMemOperand *MemOp = *MMOIt; 1543 bool IsVolatile = MemOp->isVolatile(); 1544 // Don't try to optimize volatile. 1545 if (IsVolatile) 1546 return false; 1547 1548 Align DstAlign = MemOp->getBaseAlign(); 1549 Align SrcAlign; 1550 Register Dst = MI.getOperand(0).getReg(); 1551 Register Src = MI.getOperand(1).getReg(); 1552 Register Len = MI.getOperand(2).getReg(); 1553 1554 if (Opc != TargetOpcode::G_MEMSET) { 1555 assert(MMOIt != MI.memoperands_end() && "Expected a second MMO on MI"); 1556 MemOp = *(++MMOIt); 1557 SrcAlign = MemOp->getBaseAlign(); 1558 } 1559 1560 // See if this is a constant length copy 1561 auto LenVRegAndVal = getConstantVRegValWithLookThrough(Len, MRI); 1562 if (!LenVRegAndVal) 1563 return false; // Leave it to the legalizer to lower it to a libcall. 1564 unsigned KnownLen = LenVRegAndVal->Value.getZExtValue(); 1565 1566 if (KnownLen == 0) { 1567 MI.eraseFromParent(); 1568 return true; 1569 } 1570 1571 if (MaxLen && KnownLen > MaxLen) 1572 return false; 1573 1574 if (Opc == TargetOpcode::G_MEMCPY) 1575 return optimizeMemcpy(MI, Dst, Src, KnownLen, DstAlign, SrcAlign, IsVolatile); 1576 if (Opc == TargetOpcode::G_MEMMOVE) 1577 return optimizeMemmove(MI, Dst, Src, KnownLen, DstAlign, SrcAlign, IsVolatile); 1578 if (Opc == TargetOpcode::G_MEMSET) 1579 return optimizeMemset(MI, Dst, Src, KnownLen, DstAlign, IsVolatile); 1580 return false; 1581 } 1582 1583 static Optional<APFloat> constantFoldFpUnary(unsigned Opcode, LLT DstTy, 1584 const Register Op, 1585 const MachineRegisterInfo &MRI) { 1586 const ConstantFP *MaybeCst = getConstantFPVRegVal(Op, MRI); 1587 if (!MaybeCst) 1588 return None; 1589 1590 APFloat V = MaybeCst->getValueAPF(); 1591 switch (Opcode) { 1592 default: 1593 llvm_unreachable("Unexpected opcode!"); 1594 case TargetOpcode::G_FNEG: { 1595 V.changeSign(); 1596 return V; 1597 } 1598 case TargetOpcode::G_FABS: { 1599 V.clearSign(); 1600 return V; 1601 } 1602 case TargetOpcode::G_FPTRUNC: 1603 break; 1604 case TargetOpcode::G_FSQRT: { 1605 bool Unused; 1606 V.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &Unused); 1607 V = APFloat(sqrt(V.convertToDouble())); 1608 break; 1609 } 1610 case TargetOpcode::G_FLOG2: { 1611 bool Unused; 1612 V.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &Unused); 1613 V = APFloat(log2(V.convertToDouble())); 1614 break; 1615 } 1616 } 1617 // Convert `APFloat` to appropriate IEEE type depending on `DstTy`. Otherwise, 1618 // `buildFConstant` will assert on size mismatch. Only `G_FPTRUNC`, `G_FSQRT`, 1619 // and `G_FLOG2` reach here. 1620 bool Unused; 1621 V.convert(getFltSemanticForLLT(DstTy), APFloat::rmNearestTiesToEven, &Unused); 1622 return V; 1623 } 1624 1625 bool CombinerHelper::matchCombineConstantFoldFpUnary(MachineInstr &MI, 1626 Optional<APFloat> &Cst) { 1627 Register DstReg = MI.getOperand(0).getReg(); 1628 Register SrcReg = MI.getOperand(1).getReg(); 1629 LLT DstTy = MRI.getType(DstReg); 1630 Cst = constantFoldFpUnary(MI.getOpcode(), DstTy, SrcReg, MRI); 1631 return Cst.hasValue(); 1632 } 1633 1634 bool CombinerHelper::applyCombineConstantFoldFpUnary(MachineInstr &MI, 1635 Optional<APFloat> &Cst) { 1636 assert(Cst.hasValue() && "Optional is unexpectedly empty!"); 1637 Builder.setInstrAndDebugLoc(MI); 1638 MachineFunction &MF = Builder.getMF(); 1639 auto *FPVal = ConstantFP::get(MF.getFunction().getContext(), *Cst); 1640 Register DstReg = MI.getOperand(0).getReg(); 1641 Builder.buildFConstant(DstReg, *FPVal); 1642 MI.eraseFromParent(); 1643 return true; 1644 } 1645 1646 bool CombinerHelper::matchPtrAddImmedChain(MachineInstr &MI, 1647 PtrAddChain &MatchInfo) { 1648 // We're trying to match the following pattern: 1649 // %t1 = G_PTR_ADD %base, G_CONSTANT imm1 1650 // %root = G_PTR_ADD %t1, G_CONSTANT imm2 1651 // --> 1652 // %root = G_PTR_ADD %base, G_CONSTANT (imm1 + imm2) 1653 1654 if (MI.getOpcode() != TargetOpcode::G_PTR_ADD) 1655 return false; 1656 1657 Register Add2 = MI.getOperand(1).getReg(); 1658 Register Imm1 = MI.getOperand(2).getReg(); 1659 auto MaybeImmVal = getConstantVRegValWithLookThrough(Imm1, MRI); 1660 if (!MaybeImmVal) 1661 return false; 1662 1663 MachineInstr *Add2Def = MRI.getUniqueVRegDef(Add2); 1664 if (!Add2Def || Add2Def->getOpcode() != TargetOpcode::G_PTR_ADD) 1665 return false; 1666 1667 Register Base = Add2Def->getOperand(1).getReg(); 1668 Register Imm2 = Add2Def->getOperand(2).getReg(); 1669 auto MaybeImm2Val = getConstantVRegValWithLookThrough(Imm2, MRI); 1670 if (!MaybeImm2Val) 1671 return false; 1672 1673 // Pass the combined immediate to the apply function. 1674 MatchInfo.Imm = (MaybeImmVal->Value + MaybeImm2Val->Value).getSExtValue(); 1675 MatchInfo.Base = Base; 1676 return true; 1677 } 1678 1679 bool CombinerHelper::applyPtrAddImmedChain(MachineInstr &MI, 1680 PtrAddChain &MatchInfo) { 1681 assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected G_PTR_ADD"); 1682 MachineIRBuilder MIB(MI); 1683 LLT OffsetTy = MRI.getType(MI.getOperand(2).getReg()); 1684 auto NewOffset = MIB.buildConstant(OffsetTy, MatchInfo.Imm); 1685 Observer.changingInstr(MI); 1686 MI.getOperand(1).setReg(MatchInfo.Base); 1687 MI.getOperand(2).setReg(NewOffset.getReg(0)); 1688 Observer.changedInstr(MI); 1689 return true; 1690 } 1691 1692 bool CombinerHelper::matchShiftImmedChain(MachineInstr &MI, 1693 RegisterImmPair &MatchInfo) { 1694 // We're trying to match the following pattern with any of 1695 // G_SHL/G_ASHR/G_LSHR/G_SSHLSAT/G_USHLSAT shift instructions: 1696 // %t1 = SHIFT %base, G_CONSTANT imm1 1697 // %root = SHIFT %t1, G_CONSTANT imm2 1698 // --> 1699 // %root = SHIFT %base, G_CONSTANT (imm1 + imm2) 1700 1701 unsigned Opcode = MI.getOpcode(); 1702 assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR || 1703 Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT || 1704 Opcode == TargetOpcode::G_USHLSAT) && 1705 "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT"); 1706 1707 Register Shl2 = MI.getOperand(1).getReg(); 1708 Register Imm1 = MI.getOperand(2).getReg(); 1709 auto MaybeImmVal = getConstantVRegValWithLookThrough(Imm1, MRI); 1710 if (!MaybeImmVal) 1711 return false; 1712 1713 MachineInstr *Shl2Def = MRI.getUniqueVRegDef(Shl2); 1714 if (Shl2Def->getOpcode() != Opcode) 1715 return false; 1716 1717 Register Base = Shl2Def->getOperand(1).getReg(); 1718 Register Imm2 = Shl2Def->getOperand(2).getReg(); 1719 auto MaybeImm2Val = getConstantVRegValWithLookThrough(Imm2, MRI); 1720 if (!MaybeImm2Val) 1721 return false; 1722 1723 // Pass the combined immediate to the apply function. 1724 MatchInfo.Imm = 1725 (MaybeImmVal->Value.getSExtValue() + MaybeImm2Val->Value).getSExtValue(); 1726 MatchInfo.Reg = Base; 1727 1728 // There is no simple replacement for a saturating unsigned left shift that 1729 // exceeds the scalar size. 1730 if (Opcode == TargetOpcode::G_USHLSAT && 1731 MatchInfo.Imm >= MRI.getType(Shl2).getScalarSizeInBits()) 1732 return false; 1733 1734 return true; 1735 } 1736 1737 bool CombinerHelper::applyShiftImmedChain(MachineInstr &MI, 1738 RegisterImmPair &MatchInfo) { 1739 unsigned Opcode = MI.getOpcode(); 1740 assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR || 1741 Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT || 1742 Opcode == TargetOpcode::G_USHLSAT) && 1743 "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT"); 1744 1745 Builder.setInstrAndDebugLoc(MI); 1746 LLT Ty = MRI.getType(MI.getOperand(1).getReg()); 1747 unsigned const ScalarSizeInBits = Ty.getScalarSizeInBits(); 1748 auto Imm = MatchInfo.Imm; 1749 1750 if (Imm >= ScalarSizeInBits) { 1751 // Any logical shift that exceeds scalar size will produce zero. 1752 if (Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_LSHR) { 1753 Builder.buildConstant(MI.getOperand(0), 0); 1754 MI.eraseFromParent(); 1755 return true; 1756 } 1757 // Arithmetic shift and saturating signed left shift have no effect beyond 1758 // scalar size. 1759 Imm = ScalarSizeInBits - 1; 1760 } 1761 1762 LLT ImmTy = MRI.getType(MI.getOperand(2).getReg()); 1763 Register NewImm = Builder.buildConstant(ImmTy, Imm).getReg(0); 1764 Observer.changingInstr(MI); 1765 MI.getOperand(1).setReg(MatchInfo.Reg); 1766 MI.getOperand(2).setReg(NewImm); 1767 Observer.changedInstr(MI); 1768 return true; 1769 } 1770 1771 bool CombinerHelper::matchShiftOfShiftedLogic(MachineInstr &MI, 1772 ShiftOfShiftedLogic &MatchInfo) { 1773 // We're trying to match the following pattern with any of 1774 // G_SHL/G_ASHR/G_LSHR/G_USHLSAT/G_SSHLSAT shift instructions in combination 1775 // with any of G_AND/G_OR/G_XOR logic instructions. 1776 // %t1 = SHIFT %X, G_CONSTANT C0 1777 // %t2 = LOGIC %t1, %Y 1778 // %root = SHIFT %t2, G_CONSTANT C1 1779 // --> 1780 // %t3 = SHIFT %X, G_CONSTANT (C0+C1) 1781 // %t4 = SHIFT %Y, G_CONSTANT C1 1782 // %root = LOGIC %t3, %t4 1783 unsigned ShiftOpcode = MI.getOpcode(); 1784 assert((ShiftOpcode == TargetOpcode::G_SHL || 1785 ShiftOpcode == TargetOpcode::G_ASHR || 1786 ShiftOpcode == TargetOpcode::G_LSHR || 1787 ShiftOpcode == TargetOpcode::G_USHLSAT || 1788 ShiftOpcode == TargetOpcode::G_SSHLSAT) && 1789 "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT"); 1790 1791 // Match a one-use bitwise logic op. 1792 Register LogicDest = MI.getOperand(1).getReg(); 1793 if (!MRI.hasOneNonDBGUse(LogicDest)) 1794 return false; 1795 1796 MachineInstr *LogicMI = MRI.getUniqueVRegDef(LogicDest); 1797 unsigned LogicOpcode = LogicMI->getOpcode(); 1798 if (LogicOpcode != TargetOpcode::G_AND && LogicOpcode != TargetOpcode::G_OR && 1799 LogicOpcode != TargetOpcode::G_XOR) 1800 return false; 1801 1802 // Find a matching one-use shift by constant. 1803 const Register C1 = MI.getOperand(2).getReg(); 1804 auto MaybeImmVal = getConstantVRegValWithLookThrough(C1, MRI); 1805 if (!MaybeImmVal) 1806 return false; 1807 1808 const uint64_t C1Val = MaybeImmVal->Value.getZExtValue(); 1809 1810 auto matchFirstShift = [&](const MachineInstr *MI, uint64_t &ShiftVal) { 1811 // Shift should match previous one and should be a one-use. 1812 if (MI->getOpcode() != ShiftOpcode || 1813 !MRI.hasOneNonDBGUse(MI->getOperand(0).getReg())) 1814 return false; 1815 1816 // Must be a constant. 1817 auto MaybeImmVal = 1818 getConstantVRegValWithLookThrough(MI->getOperand(2).getReg(), MRI); 1819 if (!MaybeImmVal) 1820 return false; 1821 1822 ShiftVal = MaybeImmVal->Value.getSExtValue(); 1823 return true; 1824 }; 1825 1826 // Logic ops are commutative, so check each operand for a match. 1827 Register LogicMIReg1 = LogicMI->getOperand(1).getReg(); 1828 MachineInstr *LogicMIOp1 = MRI.getUniqueVRegDef(LogicMIReg1); 1829 Register LogicMIReg2 = LogicMI->getOperand(2).getReg(); 1830 MachineInstr *LogicMIOp2 = MRI.getUniqueVRegDef(LogicMIReg2); 1831 uint64_t C0Val; 1832 1833 if (matchFirstShift(LogicMIOp1, C0Val)) { 1834 MatchInfo.LogicNonShiftReg = LogicMIReg2; 1835 MatchInfo.Shift2 = LogicMIOp1; 1836 } else if (matchFirstShift(LogicMIOp2, C0Val)) { 1837 MatchInfo.LogicNonShiftReg = LogicMIReg1; 1838 MatchInfo.Shift2 = LogicMIOp2; 1839 } else 1840 return false; 1841 1842 MatchInfo.ValSum = C0Val + C1Val; 1843 1844 // The fold is not valid if the sum of the shift values exceeds bitwidth. 1845 if (MatchInfo.ValSum >= MRI.getType(LogicDest).getScalarSizeInBits()) 1846 return false; 1847 1848 MatchInfo.Logic = LogicMI; 1849 return true; 1850 } 1851 1852 bool CombinerHelper::applyShiftOfShiftedLogic(MachineInstr &MI, 1853 ShiftOfShiftedLogic &MatchInfo) { 1854 unsigned Opcode = MI.getOpcode(); 1855 assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR || 1856 Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_USHLSAT || 1857 Opcode == TargetOpcode::G_SSHLSAT) && 1858 "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT"); 1859 1860 LLT ShlType = MRI.getType(MI.getOperand(2).getReg()); 1861 LLT DestType = MRI.getType(MI.getOperand(0).getReg()); 1862 Builder.setInstrAndDebugLoc(MI); 1863 1864 Register Const = Builder.buildConstant(ShlType, MatchInfo.ValSum).getReg(0); 1865 1866 Register Shift1Base = MatchInfo.Shift2->getOperand(1).getReg(); 1867 Register Shift1 = 1868 Builder.buildInstr(Opcode, {DestType}, {Shift1Base, Const}).getReg(0); 1869 1870 Register Shift2Const = MI.getOperand(2).getReg(); 1871 Register Shift2 = Builder 1872 .buildInstr(Opcode, {DestType}, 1873 {MatchInfo.LogicNonShiftReg, Shift2Const}) 1874 .getReg(0); 1875 1876 Register Dest = MI.getOperand(0).getReg(); 1877 Builder.buildInstr(MatchInfo.Logic->getOpcode(), {Dest}, {Shift1, Shift2}); 1878 1879 // These were one use so it's safe to remove them. 1880 MatchInfo.Shift2->eraseFromParent(); 1881 MatchInfo.Logic->eraseFromParent(); 1882 1883 MI.eraseFromParent(); 1884 return true; 1885 } 1886 1887 bool CombinerHelper::matchCombineMulToShl(MachineInstr &MI, 1888 unsigned &ShiftVal) { 1889 assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL"); 1890 auto MaybeImmVal = 1891 getConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI); 1892 if (!MaybeImmVal) 1893 return false; 1894 1895 ShiftVal = MaybeImmVal->Value.exactLogBase2(); 1896 return (static_cast<int32_t>(ShiftVal) != -1); 1897 } 1898 1899 bool CombinerHelper::applyCombineMulToShl(MachineInstr &MI, 1900 unsigned &ShiftVal) { 1901 assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL"); 1902 MachineIRBuilder MIB(MI); 1903 LLT ShiftTy = MRI.getType(MI.getOperand(0).getReg()); 1904 auto ShiftCst = MIB.buildConstant(ShiftTy, ShiftVal); 1905 Observer.changingInstr(MI); 1906 MI.setDesc(MIB.getTII().get(TargetOpcode::G_SHL)); 1907 MI.getOperand(2).setReg(ShiftCst.getReg(0)); 1908 Observer.changedInstr(MI); 1909 return true; 1910 } 1911 1912 // shl ([sza]ext x), y => zext (shl x, y), if shift does not overflow source 1913 bool CombinerHelper::matchCombineShlOfExtend(MachineInstr &MI, 1914 RegisterImmPair &MatchData) { 1915 assert(MI.getOpcode() == TargetOpcode::G_SHL && KB); 1916 1917 Register LHS = MI.getOperand(1).getReg(); 1918 1919 Register ExtSrc; 1920 if (!mi_match(LHS, MRI, m_GAnyExt(m_Reg(ExtSrc))) && 1921 !mi_match(LHS, MRI, m_GZExt(m_Reg(ExtSrc))) && 1922 !mi_match(LHS, MRI, m_GSExt(m_Reg(ExtSrc)))) 1923 return false; 1924 1925 // TODO: Should handle vector splat. 1926 Register RHS = MI.getOperand(2).getReg(); 1927 auto MaybeShiftAmtVal = getConstantVRegValWithLookThrough(RHS, MRI); 1928 if (!MaybeShiftAmtVal) 1929 return false; 1930 1931 if (LI) { 1932 LLT SrcTy = MRI.getType(ExtSrc); 1933 1934 // We only really care about the legality with the shifted value. We can 1935 // pick any type the constant shift amount, so ask the target what to 1936 // use. Otherwise we would have to guess and hope it is reported as legal. 1937 LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(SrcTy); 1938 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SHL, {SrcTy, ShiftAmtTy}})) 1939 return false; 1940 } 1941 1942 int64_t ShiftAmt = MaybeShiftAmtVal->Value.getSExtValue(); 1943 MatchData.Reg = ExtSrc; 1944 MatchData.Imm = ShiftAmt; 1945 1946 unsigned MinLeadingZeros = KB->getKnownZeroes(ExtSrc).countLeadingOnes(); 1947 return MinLeadingZeros >= ShiftAmt; 1948 } 1949 1950 bool CombinerHelper::applyCombineShlOfExtend(MachineInstr &MI, 1951 const RegisterImmPair &MatchData) { 1952 Register ExtSrcReg = MatchData.Reg; 1953 int64_t ShiftAmtVal = MatchData.Imm; 1954 1955 LLT ExtSrcTy = MRI.getType(ExtSrcReg); 1956 Builder.setInstrAndDebugLoc(MI); 1957 auto ShiftAmt = Builder.buildConstant(ExtSrcTy, ShiftAmtVal); 1958 auto NarrowShift = 1959 Builder.buildShl(ExtSrcTy, ExtSrcReg, ShiftAmt, MI.getFlags()); 1960 Builder.buildZExt(MI.getOperand(0), NarrowShift); 1961 MI.eraseFromParent(); 1962 return true; 1963 } 1964 1965 static Register peekThroughBitcast(Register Reg, 1966 const MachineRegisterInfo &MRI) { 1967 while (mi_match(Reg, MRI, m_GBitcast(m_Reg(Reg)))) 1968 ; 1969 1970 return Reg; 1971 } 1972 1973 bool CombinerHelper::matchCombineUnmergeMergeToPlainValues( 1974 MachineInstr &MI, SmallVectorImpl<Register> &Operands) { 1975 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && 1976 "Expected an unmerge"); 1977 Register SrcReg = 1978 peekThroughBitcast(MI.getOperand(MI.getNumOperands() - 1).getReg(), MRI); 1979 1980 MachineInstr *SrcInstr = MRI.getVRegDef(SrcReg); 1981 if (SrcInstr->getOpcode() != TargetOpcode::G_MERGE_VALUES && 1982 SrcInstr->getOpcode() != TargetOpcode::G_BUILD_VECTOR && 1983 SrcInstr->getOpcode() != TargetOpcode::G_CONCAT_VECTORS) 1984 return false; 1985 1986 // Check the source type of the merge. 1987 LLT SrcMergeTy = MRI.getType(SrcInstr->getOperand(1).getReg()); 1988 LLT Dst0Ty = MRI.getType(MI.getOperand(0).getReg()); 1989 bool SameSize = Dst0Ty.getSizeInBits() == SrcMergeTy.getSizeInBits(); 1990 if (SrcMergeTy != Dst0Ty && !SameSize) 1991 return false; 1992 // They are the same now (modulo a bitcast). 1993 // We can collect all the src registers. 1994 for (unsigned Idx = 1, EndIdx = SrcInstr->getNumOperands(); Idx != EndIdx; 1995 ++Idx) 1996 Operands.push_back(SrcInstr->getOperand(Idx).getReg()); 1997 return true; 1998 } 1999 2000 bool CombinerHelper::applyCombineUnmergeMergeToPlainValues( 2001 MachineInstr &MI, SmallVectorImpl<Register> &Operands) { 2002 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && 2003 "Expected an unmerge"); 2004 assert((MI.getNumOperands() - 1 == Operands.size()) && 2005 "Not enough operands to replace all defs"); 2006 unsigned NumElems = MI.getNumOperands() - 1; 2007 2008 LLT SrcTy = MRI.getType(Operands[0]); 2009 LLT DstTy = MRI.getType(MI.getOperand(0).getReg()); 2010 bool CanReuseInputDirectly = DstTy == SrcTy; 2011 Builder.setInstrAndDebugLoc(MI); 2012 for (unsigned Idx = 0; Idx < NumElems; ++Idx) { 2013 Register DstReg = MI.getOperand(Idx).getReg(); 2014 Register SrcReg = Operands[Idx]; 2015 if (CanReuseInputDirectly) 2016 replaceRegWith(MRI, DstReg, SrcReg); 2017 else 2018 Builder.buildCast(DstReg, SrcReg); 2019 } 2020 MI.eraseFromParent(); 2021 return true; 2022 } 2023 2024 bool CombinerHelper::matchCombineUnmergeConstant(MachineInstr &MI, 2025 SmallVectorImpl<APInt> &Csts) { 2026 unsigned SrcIdx = MI.getNumOperands() - 1; 2027 Register SrcReg = MI.getOperand(SrcIdx).getReg(); 2028 MachineInstr *SrcInstr = MRI.getVRegDef(SrcReg); 2029 if (SrcInstr->getOpcode() != TargetOpcode::G_CONSTANT && 2030 SrcInstr->getOpcode() != TargetOpcode::G_FCONSTANT) 2031 return false; 2032 // Break down the big constant in smaller ones. 2033 const MachineOperand &CstVal = SrcInstr->getOperand(1); 2034 APInt Val = SrcInstr->getOpcode() == TargetOpcode::G_CONSTANT 2035 ? CstVal.getCImm()->getValue() 2036 : CstVal.getFPImm()->getValueAPF().bitcastToAPInt(); 2037 2038 LLT Dst0Ty = MRI.getType(MI.getOperand(0).getReg()); 2039 unsigned ShiftAmt = Dst0Ty.getSizeInBits(); 2040 // Unmerge a constant. 2041 for (unsigned Idx = 0; Idx != SrcIdx; ++Idx) { 2042 Csts.emplace_back(Val.trunc(ShiftAmt)); 2043 Val = Val.lshr(ShiftAmt); 2044 } 2045 2046 return true; 2047 } 2048 2049 bool CombinerHelper::applyCombineUnmergeConstant(MachineInstr &MI, 2050 SmallVectorImpl<APInt> &Csts) { 2051 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && 2052 "Expected an unmerge"); 2053 assert((MI.getNumOperands() - 1 == Csts.size()) && 2054 "Not enough operands to replace all defs"); 2055 unsigned NumElems = MI.getNumOperands() - 1; 2056 Builder.setInstrAndDebugLoc(MI); 2057 for (unsigned Idx = 0; Idx < NumElems; ++Idx) { 2058 Register DstReg = MI.getOperand(Idx).getReg(); 2059 Builder.buildConstant(DstReg, Csts[Idx]); 2060 } 2061 2062 MI.eraseFromParent(); 2063 return true; 2064 } 2065 2066 bool CombinerHelper::matchCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) { 2067 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && 2068 "Expected an unmerge"); 2069 // Check that all the lanes are dead except the first one. 2070 for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) { 2071 if (!MRI.use_nodbg_empty(MI.getOperand(Idx).getReg())) 2072 return false; 2073 } 2074 return true; 2075 } 2076 2077 bool CombinerHelper::applyCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) { 2078 Builder.setInstrAndDebugLoc(MI); 2079 Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg(); 2080 // Truncating a vector is going to truncate every single lane, 2081 // whereas we want the full lowbits. 2082 // Do the operation on a scalar instead. 2083 LLT SrcTy = MRI.getType(SrcReg); 2084 if (SrcTy.isVector()) 2085 SrcReg = 2086 Builder.buildCast(LLT::scalar(SrcTy.getSizeInBits()), SrcReg).getReg(0); 2087 2088 Register Dst0Reg = MI.getOperand(0).getReg(); 2089 LLT Dst0Ty = MRI.getType(Dst0Reg); 2090 if (Dst0Ty.isVector()) { 2091 auto MIB = Builder.buildTrunc(LLT::scalar(Dst0Ty.getSizeInBits()), SrcReg); 2092 Builder.buildCast(Dst0Reg, MIB); 2093 } else 2094 Builder.buildTrunc(Dst0Reg, SrcReg); 2095 MI.eraseFromParent(); 2096 return true; 2097 } 2098 2099 bool CombinerHelper::matchCombineUnmergeZExtToZExt(MachineInstr &MI) { 2100 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && 2101 "Expected an unmerge"); 2102 Register Dst0Reg = MI.getOperand(0).getReg(); 2103 LLT Dst0Ty = MRI.getType(Dst0Reg); 2104 // G_ZEXT on vector applies to each lane, so it will 2105 // affect all destinations. Therefore we won't be able 2106 // to simplify the unmerge to just the first definition. 2107 if (Dst0Ty.isVector()) 2108 return false; 2109 Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg(); 2110 LLT SrcTy = MRI.getType(SrcReg); 2111 if (SrcTy.isVector()) 2112 return false; 2113 2114 Register ZExtSrcReg; 2115 if (!mi_match(SrcReg, MRI, m_GZExt(m_Reg(ZExtSrcReg)))) 2116 return false; 2117 2118 // Finally we can replace the first definition with 2119 // a zext of the source if the definition is big enough to hold 2120 // all of ZExtSrc bits. 2121 LLT ZExtSrcTy = MRI.getType(ZExtSrcReg); 2122 return ZExtSrcTy.getSizeInBits() <= Dst0Ty.getSizeInBits(); 2123 } 2124 2125 bool CombinerHelper::applyCombineUnmergeZExtToZExt(MachineInstr &MI) { 2126 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && 2127 "Expected an unmerge"); 2128 2129 Register Dst0Reg = MI.getOperand(0).getReg(); 2130 2131 MachineInstr *ZExtInstr = 2132 MRI.getVRegDef(MI.getOperand(MI.getNumDefs()).getReg()); 2133 assert(ZExtInstr && ZExtInstr->getOpcode() == TargetOpcode::G_ZEXT && 2134 "Expecting a G_ZEXT"); 2135 2136 Register ZExtSrcReg = ZExtInstr->getOperand(1).getReg(); 2137 LLT Dst0Ty = MRI.getType(Dst0Reg); 2138 LLT ZExtSrcTy = MRI.getType(ZExtSrcReg); 2139 2140 Builder.setInstrAndDebugLoc(MI); 2141 2142 if (Dst0Ty.getSizeInBits() > ZExtSrcTy.getSizeInBits()) { 2143 Builder.buildZExt(Dst0Reg, ZExtSrcReg); 2144 } else { 2145 assert(Dst0Ty.getSizeInBits() == ZExtSrcTy.getSizeInBits() && 2146 "ZExt src doesn't fit in destination"); 2147 replaceRegWith(MRI, Dst0Reg, ZExtSrcReg); 2148 } 2149 2150 Register ZeroReg; 2151 for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) { 2152 if (!ZeroReg) 2153 ZeroReg = Builder.buildConstant(Dst0Ty, 0).getReg(0); 2154 replaceRegWith(MRI, MI.getOperand(Idx).getReg(), ZeroReg); 2155 } 2156 MI.eraseFromParent(); 2157 return true; 2158 } 2159 2160 bool CombinerHelper::matchCombineShiftToUnmerge(MachineInstr &MI, 2161 unsigned TargetShiftSize, 2162 unsigned &ShiftVal) { 2163 assert((MI.getOpcode() == TargetOpcode::G_SHL || 2164 MI.getOpcode() == TargetOpcode::G_LSHR || 2165 MI.getOpcode() == TargetOpcode::G_ASHR) && "Expected a shift"); 2166 2167 LLT Ty = MRI.getType(MI.getOperand(0).getReg()); 2168 if (Ty.isVector()) // TODO: 2169 return false; 2170 2171 // Don't narrow further than the requested size. 2172 unsigned Size = Ty.getSizeInBits(); 2173 if (Size <= TargetShiftSize) 2174 return false; 2175 2176 auto MaybeImmVal = 2177 getConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI); 2178 if (!MaybeImmVal) 2179 return false; 2180 2181 ShiftVal = MaybeImmVal->Value.getSExtValue(); 2182 return ShiftVal >= Size / 2 && ShiftVal < Size; 2183 } 2184 2185 bool CombinerHelper::applyCombineShiftToUnmerge(MachineInstr &MI, 2186 const unsigned &ShiftVal) { 2187 Register DstReg = MI.getOperand(0).getReg(); 2188 Register SrcReg = MI.getOperand(1).getReg(); 2189 LLT Ty = MRI.getType(SrcReg); 2190 unsigned Size = Ty.getSizeInBits(); 2191 unsigned HalfSize = Size / 2; 2192 assert(ShiftVal >= HalfSize); 2193 2194 LLT HalfTy = LLT::scalar(HalfSize); 2195 2196 Builder.setInstr(MI); 2197 auto Unmerge = Builder.buildUnmerge(HalfTy, SrcReg); 2198 unsigned NarrowShiftAmt = ShiftVal - HalfSize; 2199 2200 if (MI.getOpcode() == TargetOpcode::G_LSHR) { 2201 Register Narrowed = Unmerge.getReg(1); 2202 2203 // dst = G_LSHR s64:x, C for C >= 32 2204 // => 2205 // lo, hi = G_UNMERGE_VALUES x 2206 // dst = G_MERGE_VALUES (G_LSHR hi, C - 32), 0 2207 2208 if (NarrowShiftAmt != 0) { 2209 Narrowed = Builder.buildLShr(HalfTy, Narrowed, 2210 Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0); 2211 } 2212 2213 auto Zero = Builder.buildConstant(HalfTy, 0); 2214 Builder.buildMerge(DstReg, { Narrowed, Zero }); 2215 } else if (MI.getOpcode() == TargetOpcode::G_SHL) { 2216 Register Narrowed = Unmerge.getReg(0); 2217 // dst = G_SHL s64:x, C for C >= 32 2218 // => 2219 // lo, hi = G_UNMERGE_VALUES x 2220 // dst = G_MERGE_VALUES 0, (G_SHL hi, C - 32) 2221 if (NarrowShiftAmt != 0) { 2222 Narrowed = Builder.buildShl(HalfTy, Narrowed, 2223 Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0); 2224 } 2225 2226 auto Zero = Builder.buildConstant(HalfTy, 0); 2227 Builder.buildMerge(DstReg, { Zero, Narrowed }); 2228 } else { 2229 assert(MI.getOpcode() == TargetOpcode::G_ASHR); 2230 auto Hi = Builder.buildAShr( 2231 HalfTy, Unmerge.getReg(1), 2232 Builder.buildConstant(HalfTy, HalfSize - 1)); 2233 2234 if (ShiftVal == HalfSize) { 2235 // (G_ASHR i64:x, 32) -> 2236 // G_MERGE_VALUES hi_32(x), (G_ASHR hi_32(x), 31) 2237 Builder.buildMerge(DstReg, { Unmerge.getReg(1), Hi }); 2238 } else if (ShiftVal == Size - 1) { 2239 // Don't need a second shift. 2240 // (G_ASHR i64:x, 63) -> 2241 // %narrowed = (G_ASHR hi_32(x), 31) 2242 // G_MERGE_VALUES %narrowed, %narrowed 2243 Builder.buildMerge(DstReg, { Hi, Hi }); 2244 } else { 2245 auto Lo = Builder.buildAShr( 2246 HalfTy, Unmerge.getReg(1), 2247 Builder.buildConstant(HalfTy, ShiftVal - HalfSize)); 2248 2249 // (G_ASHR i64:x, C) ->, for C >= 32 2250 // G_MERGE_VALUES (G_ASHR hi_32(x), C - 32), (G_ASHR hi_32(x), 31) 2251 Builder.buildMerge(DstReg, { Lo, Hi }); 2252 } 2253 } 2254 2255 MI.eraseFromParent(); 2256 return true; 2257 } 2258 2259 bool CombinerHelper::tryCombineShiftToUnmerge(MachineInstr &MI, 2260 unsigned TargetShiftAmount) { 2261 unsigned ShiftAmt; 2262 if (matchCombineShiftToUnmerge(MI, TargetShiftAmount, ShiftAmt)) { 2263 applyCombineShiftToUnmerge(MI, ShiftAmt); 2264 return true; 2265 } 2266 2267 return false; 2268 } 2269 2270 bool CombinerHelper::matchCombineI2PToP2I(MachineInstr &MI, Register &Reg) { 2271 assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR"); 2272 Register DstReg = MI.getOperand(0).getReg(); 2273 LLT DstTy = MRI.getType(DstReg); 2274 Register SrcReg = MI.getOperand(1).getReg(); 2275 return mi_match(SrcReg, MRI, 2276 m_GPtrToInt(m_all_of(m_SpecificType(DstTy), m_Reg(Reg)))); 2277 } 2278 2279 bool CombinerHelper::applyCombineI2PToP2I(MachineInstr &MI, Register &Reg) { 2280 assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR"); 2281 Register DstReg = MI.getOperand(0).getReg(); 2282 Builder.setInstr(MI); 2283 Builder.buildCopy(DstReg, Reg); 2284 MI.eraseFromParent(); 2285 return true; 2286 } 2287 2288 bool CombinerHelper::matchCombineP2IToI2P(MachineInstr &MI, Register &Reg) { 2289 assert(MI.getOpcode() == TargetOpcode::G_PTRTOINT && "Expected a G_PTRTOINT"); 2290 Register SrcReg = MI.getOperand(1).getReg(); 2291 return mi_match(SrcReg, MRI, m_GIntToPtr(m_Reg(Reg))); 2292 } 2293 2294 bool CombinerHelper::applyCombineP2IToI2P(MachineInstr &MI, Register &Reg) { 2295 assert(MI.getOpcode() == TargetOpcode::G_PTRTOINT && "Expected a G_PTRTOINT"); 2296 Register DstReg = MI.getOperand(0).getReg(); 2297 Builder.setInstr(MI); 2298 Builder.buildZExtOrTrunc(DstReg, Reg); 2299 MI.eraseFromParent(); 2300 return true; 2301 } 2302 2303 bool CombinerHelper::matchCombineAddP2IToPtrAdd( 2304 MachineInstr &MI, std::pair<Register, bool> &PtrReg) { 2305 assert(MI.getOpcode() == TargetOpcode::G_ADD); 2306 Register LHS = MI.getOperand(1).getReg(); 2307 Register RHS = MI.getOperand(2).getReg(); 2308 LLT IntTy = MRI.getType(LHS); 2309 2310 // G_PTR_ADD always has the pointer in the LHS, so we may need to commute the 2311 // instruction. 2312 PtrReg.second = false; 2313 for (Register SrcReg : {LHS, RHS}) { 2314 if (mi_match(SrcReg, MRI, m_GPtrToInt(m_Reg(PtrReg.first)))) { 2315 // Don't handle cases where the integer is implicitly converted to the 2316 // pointer width. 2317 LLT PtrTy = MRI.getType(PtrReg.first); 2318 if (PtrTy.getScalarSizeInBits() == IntTy.getScalarSizeInBits()) 2319 return true; 2320 } 2321 2322 PtrReg.second = true; 2323 } 2324 2325 return false; 2326 } 2327 2328 bool CombinerHelper::applyCombineAddP2IToPtrAdd( 2329 MachineInstr &MI, std::pair<Register, bool> &PtrReg) { 2330 Register Dst = MI.getOperand(0).getReg(); 2331 Register LHS = MI.getOperand(1).getReg(); 2332 Register RHS = MI.getOperand(2).getReg(); 2333 2334 const bool DoCommute = PtrReg.second; 2335 if (DoCommute) 2336 std::swap(LHS, RHS); 2337 LHS = PtrReg.first; 2338 2339 LLT PtrTy = MRI.getType(LHS); 2340 2341 Builder.setInstrAndDebugLoc(MI); 2342 auto PtrAdd = Builder.buildPtrAdd(PtrTy, LHS, RHS); 2343 Builder.buildPtrToInt(Dst, PtrAdd); 2344 MI.eraseFromParent(); 2345 return true; 2346 } 2347 2348 bool CombinerHelper::matchCombineConstPtrAddToI2P(MachineInstr &MI, 2349 int64_t &NewCst) { 2350 assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected a G_PTR_ADD"); 2351 Register LHS = MI.getOperand(1).getReg(); 2352 Register RHS = MI.getOperand(2).getReg(); 2353 MachineRegisterInfo &MRI = Builder.getMF().getRegInfo(); 2354 2355 if (auto RHSCst = getConstantVRegSExtVal(RHS, MRI)) { 2356 int64_t Cst; 2357 if (mi_match(LHS, MRI, m_GIntToPtr(m_ICst(Cst)))) { 2358 NewCst = Cst + *RHSCst; 2359 return true; 2360 } 2361 } 2362 2363 return false; 2364 } 2365 2366 bool CombinerHelper::applyCombineConstPtrAddToI2P(MachineInstr &MI, 2367 int64_t &NewCst) { 2368 assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected a G_PTR_ADD"); 2369 Register Dst = MI.getOperand(0).getReg(); 2370 2371 Builder.setInstrAndDebugLoc(MI); 2372 Builder.buildConstant(Dst, NewCst); 2373 MI.eraseFromParent(); 2374 return true; 2375 } 2376 2377 bool CombinerHelper::matchCombineAnyExtTrunc(MachineInstr &MI, Register &Reg) { 2378 assert(MI.getOpcode() == TargetOpcode::G_ANYEXT && "Expected a G_ANYEXT"); 2379 Register DstReg = MI.getOperand(0).getReg(); 2380 Register SrcReg = MI.getOperand(1).getReg(); 2381 LLT DstTy = MRI.getType(DstReg); 2382 return mi_match(SrcReg, MRI, 2383 m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy)))); 2384 } 2385 2386 bool CombinerHelper::matchCombineZextTrunc(MachineInstr &MI, Register &Reg) { 2387 assert(MI.getOpcode() == TargetOpcode::G_ZEXT && "Expected a G_ZEXT"); 2388 Register DstReg = MI.getOperand(0).getReg(); 2389 Register SrcReg = MI.getOperand(1).getReg(); 2390 LLT DstTy = MRI.getType(DstReg); 2391 if (mi_match(SrcReg, MRI, 2392 m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))))) { 2393 unsigned DstSize = DstTy.getScalarSizeInBits(); 2394 unsigned SrcSize = MRI.getType(SrcReg).getScalarSizeInBits(); 2395 return KB->getKnownBits(Reg).countMinLeadingZeros() >= DstSize - SrcSize; 2396 } 2397 return false; 2398 } 2399 2400 bool CombinerHelper::matchCombineExtOfExt( 2401 MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) { 2402 assert((MI.getOpcode() == TargetOpcode::G_ANYEXT || 2403 MI.getOpcode() == TargetOpcode::G_SEXT || 2404 MI.getOpcode() == TargetOpcode::G_ZEXT) && 2405 "Expected a G_[ASZ]EXT"); 2406 Register SrcReg = MI.getOperand(1).getReg(); 2407 MachineInstr *SrcMI = MRI.getVRegDef(SrcReg); 2408 // Match exts with the same opcode, anyext([sz]ext) and sext(zext). 2409 unsigned Opc = MI.getOpcode(); 2410 unsigned SrcOpc = SrcMI->getOpcode(); 2411 if (Opc == SrcOpc || 2412 (Opc == TargetOpcode::G_ANYEXT && 2413 (SrcOpc == TargetOpcode::G_SEXT || SrcOpc == TargetOpcode::G_ZEXT)) || 2414 (Opc == TargetOpcode::G_SEXT && SrcOpc == TargetOpcode::G_ZEXT)) { 2415 MatchInfo = std::make_tuple(SrcMI->getOperand(1).getReg(), SrcOpc); 2416 return true; 2417 } 2418 return false; 2419 } 2420 2421 bool CombinerHelper::applyCombineExtOfExt( 2422 MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) { 2423 assert((MI.getOpcode() == TargetOpcode::G_ANYEXT || 2424 MI.getOpcode() == TargetOpcode::G_SEXT || 2425 MI.getOpcode() == TargetOpcode::G_ZEXT) && 2426 "Expected a G_[ASZ]EXT"); 2427 2428 Register Reg = std::get<0>(MatchInfo); 2429 unsigned SrcExtOp = std::get<1>(MatchInfo); 2430 2431 // Combine exts with the same opcode. 2432 if (MI.getOpcode() == SrcExtOp) { 2433 Observer.changingInstr(MI); 2434 MI.getOperand(1).setReg(Reg); 2435 Observer.changedInstr(MI); 2436 return true; 2437 } 2438 2439 // Combine: 2440 // - anyext([sz]ext x) to [sz]ext x 2441 // - sext(zext x) to zext x 2442 if (MI.getOpcode() == TargetOpcode::G_ANYEXT || 2443 (MI.getOpcode() == TargetOpcode::G_SEXT && 2444 SrcExtOp == TargetOpcode::G_ZEXT)) { 2445 Register DstReg = MI.getOperand(0).getReg(); 2446 Builder.setInstrAndDebugLoc(MI); 2447 Builder.buildInstr(SrcExtOp, {DstReg}, {Reg}); 2448 MI.eraseFromParent(); 2449 return true; 2450 } 2451 2452 return false; 2453 } 2454 2455 bool CombinerHelper::applyCombineMulByNegativeOne(MachineInstr &MI) { 2456 assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL"); 2457 Register DstReg = MI.getOperand(0).getReg(); 2458 Register SrcReg = MI.getOperand(1).getReg(); 2459 LLT DstTy = MRI.getType(DstReg); 2460 2461 Builder.setInstrAndDebugLoc(MI); 2462 Builder.buildSub(DstReg, Builder.buildConstant(DstTy, 0), SrcReg, 2463 MI.getFlags()); 2464 MI.eraseFromParent(); 2465 return true; 2466 } 2467 2468 bool CombinerHelper::matchCombineFNegOfFNeg(MachineInstr &MI, Register &Reg) { 2469 assert(MI.getOpcode() == TargetOpcode::G_FNEG && "Expected a G_FNEG"); 2470 Register SrcReg = MI.getOperand(1).getReg(); 2471 return mi_match(SrcReg, MRI, m_GFNeg(m_Reg(Reg))); 2472 } 2473 2474 bool CombinerHelper::matchCombineFAbsOfFAbs(MachineInstr &MI, Register &Src) { 2475 assert(MI.getOpcode() == TargetOpcode::G_FABS && "Expected a G_FABS"); 2476 Src = MI.getOperand(1).getReg(); 2477 Register AbsSrc; 2478 return mi_match(Src, MRI, m_GFabs(m_Reg(AbsSrc))); 2479 } 2480 2481 bool CombinerHelper::matchCombineTruncOfExt( 2482 MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) { 2483 assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC"); 2484 Register SrcReg = MI.getOperand(1).getReg(); 2485 MachineInstr *SrcMI = MRI.getVRegDef(SrcReg); 2486 unsigned SrcOpc = SrcMI->getOpcode(); 2487 if (SrcOpc == TargetOpcode::G_ANYEXT || SrcOpc == TargetOpcode::G_SEXT || 2488 SrcOpc == TargetOpcode::G_ZEXT) { 2489 MatchInfo = std::make_pair(SrcMI->getOperand(1).getReg(), SrcOpc); 2490 return true; 2491 } 2492 return false; 2493 } 2494 2495 bool CombinerHelper::applyCombineTruncOfExt( 2496 MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) { 2497 assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC"); 2498 Register SrcReg = MatchInfo.first; 2499 unsigned SrcExtOp = MatchInfo.second; 2500 Register DstReg = MI.getOperand(0).getReg(); 2501 LLT SrcTy = MRI.getType(SrcReg); 2502 LLT DstTy = MRI.getType(DstReg); 2503 if (SrcTy == DstTy) { 2504 MI.eraseFromParent(); 2505 replaceRegWith(MRI, DstReg, SrcReg); 2506 return true; 2507 } 2508 Builder.setInstrAndDebugLoc(MI); 2509 if (SrcTy.getSizeInBits() < DstTy.getSizeInBits()) 2510 Builder.buildInstr(SrcExtOp, {DstReg}, {SrcReg}); 2511 else 2512 Builder.buildTrunc(DstReg, SrcReg); 2513 MI.eraseFromParent(); 2514 return true; 2515 } 2516 2517 bool CombinerHelper::matchCombineTruncOfShl( 2518 MachineInstr &MI, std::pair<Register, Register> &MatchInfo) { 2519 assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC"); 2520 Register DstReg = MI.getOperand(0).getReg(); 2521 Register SrcReg = MI.getOperand(1).getReg(); 2522 LLT DstTy = MRI.getType(DstReg); 2523 Register ShiftSrc; 2524 Register ShiftAmt; 2525 2526 if (MRI.hasOneNonDBGUse(SrcReg) && 2527 mi_match(SrcReg, MRI, m_GShl(m_Reg(ShiftSrc), m_Reg(ShiftAmt))) && 2528 isLegalOrBeforeLegalizer( 2529 {TargetOpcode::G_SHL, 2530 {DstTy, getTargetLowering().getPreferredShiftAmountTy(DstTy)}})) { 2531 KnownBits Known = KB->getKnownBits(ShiftAmt); 2532 unsigned Size = DstTy.getSizeInBits(); 2533 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) { 2534 MatchInfo = std::make_pair(ShiftSrc, ShiftAmt); 2535 return true; 2536 } 2537 } 2538 return false; 2539 } 2540 2541 bool CombinerHelper::applyCombineTruncOfShl( 2542 MachineInstr &MI, std::pair<Register, Register> &MatchInfo) { 2543 assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC"); 2544 Register DstReg = MI.getOperand(0).getReg(); 2545 Register SrcReg = MI.getOperand(1).getReg(); 2546 LLT DstTy = MRI.getType(DstReg); 2547 MachineInstr *SrcMI = MRI.getVRegDef(SrcReg); 2548 2549 Register ShiftSrc = MatchInfo.first; 2550 Register ShiftAmt = MatchInfo.second; 2551 Builder.setInstrAndDebugLoc(MI); 2552 auto TruncShiftSrc = Builder.buildTrunc(DstTy, ShiftSrc); 2553 Builder.buildShl(DstReg, TruncShiftSrc, ShiftAmt, SrcMI->getFlags()); 2554 MI.eraseFromParent(); 2555 return true; 2556 } 2557 2558 bool CombinerHelper::matchAnyExplicitUseIsUndef(MachineInstr &MI) { 2559 return any_of(MI.explicit_uses(), [this](const MachineOperand &MO) { 2560 return MO.isReg() && 2561 getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI); 2562 }); 2563 } 2564 2565 bool CombinerHelper::matchAllExplicitUsesAreUndef(MachineInstr &MI) { 2566 return all_of(MI.explicit_uses(), [this](const MachineOperand &MO) { 2567 return !MO.isReg() || 2568 getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI); 2569 }); 2570 } 2571 2572 bool CombinerHelper::matchUndefShuffleVectorMask(MachineInstr &MI) { 2573 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR); 2574 ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask(); 2575 return all_of(Mask, [](int Elt) { return Elt < 0; }); 2576 } 2577 2578 bool CombinerHelper::matchUndefStore(MachineInstr &MI) { 2579 assert(MI.getOpcode() == TargetOpcode::G_STORE); 2580 return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(0).getReg(), 2581 MRI); 2582 } 2583 2584 bool CombinerHelper::matchUndefSelectCmp(MachineInstr &MI) { 2585 assert(MI.getOpcode() == TargetOpcode::G_SELECT); 2586 return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(1).getReg(), 2587 MRI); 2588 } 2589 2590 bool CombinerHelper::matchConstantSelectCmp(MachineInstr &MI, unsigned &OpIdx) { 2591 assert(MI.getOpcode() == TargetOpcode::G_SELECT); 2592 if (auto MaybeCstCmp = 2593 getConstantVRegValWithLookThrough(MI.getOperand(1).getReg(), MRI)) { 2594 OpIdx = MaybeCstCmp->Value.isNullValue() ? 3 : 2; 2595 return true; 2596 } 2597 return false; 2598 } 2599 2600 bool CombinerHelper::eraseInst(MachineInstr &MI) { 2601 MI.eraseFromParent(); 2602 return true; 2603 } 2604 2605 bool CombinerHelper::matchEqualDefs(const MachineOperand &MOP1, 2606 const MachineOperand &MOP2) { 2607 if (!MOP1.isReg() || !MOP2.isReg()) 2608 return false; 2609 MachineInstr *I1 = getDefIgnoringCopies(MOP1.getReg(), MRI); 2610 if (!I1) 2611 return false; 2612 MachineInstr *I2 = getDefIgnoringCopies(MOP2.getReg(), MRI); 2613 if (!I2) 2614 return false; 2615 2616 // Handle a case like this: 2617 // 2618 // %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<2 x s64>) 2619 // 2620 // Even though %0 and %1 are produced by the same instruction they are not 2621 // the same values. 2622 if (I1 == I2) 2623 return MOP1.getReg() == MOP2.getReg(); 2624 2625 // If we have an instruction which loads or stores, we can't guarantee that 2626 // it is identical. 2627 // 2628 // For example, we may have 2629 // 2630 // %x1 = G_LOAD %addr (load N from @somewhere) 2631 // ... 2632 // call @foo 2633 // ... 2634 // %x2 = G_LOAD %addr (load N from @somewhere) 2635 // ... 2636 // %or = G_OR %x1, %x2 2637 // 2638 // It's possible that @foo will modify whatever lives at the address we're 2639 // loading from. To be safe, let's just assume that all loads and stores 2640 // are different (unless we have something which is guaranteed to not 2641 // change.) 2642 if (I1->mayLoadOrStore() && !I1->isDereferenceableInvariantLoad(nullptr)) 2643 return false; 2644 2645 // Check for physical registers on the instructions first to avoid cases 2646 // like this: 2647 // 2648 // %a = COPY $physreg 2649 // ... 2650 // SOMETHING implicit-def $physreg 2651 // ... 2652 // %b = COPY $physreg 2653 // 2654 // These copies are not equivalent. 2655 if (any_of(I1->uses(), [](const MachineOperand &MO) { 2656 return MO.isReg() && MO.getReg().isPhysical(); 2657 })) { 2658 // Check if we have a case like this: 2659 // 2660 // %a = COPY $physreg 2661 // %b = COPY %a 2662 // 2663 // In this case, I1 and I2 will both be equal to %a = COPY $physreg. 2664 // From that, we know that they must have the same value, since they must 2665 // have come from the same COPY. 2666 return I1->isIdenticalTo(*I2); 2667 } 2668 2669 // We don't have any physical registers, so we don't necessarily need the 2670 // same vreg defs. 2671 // 2672 // On the off-chance that there's some target instruction feeding into the 2673 // instruction, let's use produceSameValue instead of isIdenticalTo. 2674 return Builder.getTII().produceSameValue(*I1, *I2, &MRI); 2675 } 2676 2677 bool CombinerHelper::matchConstantOp(const MachineOperand &MOP, int64_t C) { 2678 if (!MOP.isReg()) 2679 return false; 2680 // MIPatternMatch doesn't let us look through G_ZEXT etc. 2681 auto ValAndVReg = getConstantVRegValWithLookThrough(MOP.getReg(), MRI); 2682 return ValAndVReg && ValAndVReg->Value == C; 2683 } 2684 2685 bool CombinerHelper::replaceSingleDefInstWithOperand(MachineInstr &MI, 2686 unsigned OpIdx) { 2687 assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?"); 2688 Register OldReg = MI.getOperand(0).getReg(); 2689 Register Replacement = MI.getOperand(OpIdx).getReg(); 2690 assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?"); 2691 MI.eraseFromParent(); 2692 replaceRegWith(MRI, OldReg, Replacement); 2693 return true; 2694 } 2695 2696 bool CombinerHelper::replaceSingleDefInstWithReg(MachineInstr &MI, 2697 Register Replacement) { 2698 assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?"); 2699 Register OldReg = MI.getOperand(0).getReg(); 2700 assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?"); 2701 MI.eraseFromParent(); 2702 replaceRegWith(MRI, OldReg, Replacement); 2703 return true; 2704 } 2705 2706 bool CombinerHelper::matchSelectSameVal(MachineInstr &MI) { 2707 assert(MI.getOpcode() == TargetOpcode::G_SELECT); 2708 // Match (cond ? x : x) 2709 return matchEqualDefs(MI.getOperand(2), MI.getOperand(3)) && 2710 canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(2).getReg(), 2711 MRI); 2712 } 2713 2714 bool CombinerHelper::matchBinOpSameVal(MachineInstr &MI) { 2715 return matchEqualDefs(MI.getOperand(1), MI.getOperand(2)) && 2716 canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(1).getReg(), 2717 MRI); 2718 } 2719 2720 bool CombinerHelper::matchOperandIsZero(MachineInstr &MI, unsigned OpIdx) { 2721 return matchConstantOp(MI.getOperand(OpIdx), 0) && 2722 canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(OpIdx).getReg(), 2723 MRI); 2724 } 2725 2726 bool CombinerHelper::matchOperandIsUndef(MachineInstr &MI, unsigned OpIdx) { 2727 MachineOperand &MO = MI.getOperand(OpIdx); 2728 return MO.isReg() && 2729 getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI); 2730 } 2731 2732 bool CombinerHelper::matchOperandIsKnownToBeAPowerOfTwo(MachineInstr &MI, 2733 unsigned OpIdx) { 2734 MachineOperand &MO = MI.getOperand(OpIdx); 2735 return isKnownToBeAPowerOfTwo(MO.getReg(), MRI, KB); 2736 } 2737 2738 bool CombinerHelper::replaceInstWithFConstant(MachineInstr &MI, double C) { 2739 assert(MI.getNumDefs() == 1 && "Expected only one def?"); 2740 Builder.setInstr(MI); 2741 Builder.buildFConstant(MI.getOperand(0), C); 2742 MI.eraseFromParent(); 2743 return true; 2744 } 2745 2746 bool CombinerHelper::replaceInstWithConstant(MachineInstr &MI, int64_t C) { 2747 assert(MI.getNumDefs() == 1 && "Expected only one def?"); 2748 Builder.setInstr(MI); 2749 Builder.buildConstant(MI.getOperand(0), C); 2750 MI.eraseFromParent(); 2751 return true; 2752 } 2753 2754 bool CombinerHelper::replaceInstWithUndef(MachineInstr &MI) { 2755 assert(MI.getNumDefs() == 1 && "Expected only one def?"); 2756 Builder.setInstr(MI); 2757 Builder.buildUndef(MI.getOperand(0)); 2758 MI.eraseFromParent(); 2759 return true; 2760 } 2761 2762 bool CombinerHelper::matchSimplifyAddToSub( 2763 MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) { 2764 Register LHS = MI.getOperand(1).getReg(); 2765 Register RHS = MI.getOperand(2).getReg(); 2766 Register &NewLHS = std::get<0>(MatchInfo); 2767 Register &NewRHS = std::get<1>(MatchInfo); 2768 2769 // Helper lambda to check for opportunities for 2770 // ((0-A) + B) -> B - A 2771 // (A + (0-B)) -> A - B 2772 auto CheckFold = [&](Register &MaybeSub, Register &MaybeNewLHS) { 2773 if (!mi_match(MaybeSub, MRI, m_Neg(m_Reg(NewRHS)))) 2774 return false; 2775 NewLHS = MaybeNewLHS; 2776 return true; 2777 }; 2778 2779 return CheckFold(LHS, RHS) || CheckFold(RHS, LHS); 2780 } 2781 2782 bool CombinerHelper::matchCombineInsertVecElts( 2783 MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) { 2784 assert(MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT && 2785 "Invalid opcode"); 2786 Register DstReg = MI.getOperand(0).getReg(); 2787 LLT DstTy = MRI.getType(DstReg); 2788 assert(DstTy.isVector() && "Invalid G_INSERT_VECTOR_ELT?"); 2789 unsigned NumElts = DstTy.getNumElements(); 2790 // If this MI is part of a sequence of insert_vec_elts, then 2791 // don't do the combine in the middle of the sequence. 2792 if (MRI.hasOneUse(DstReg) && MRI.use_instr_begin(DstReg)->getOpcode() == 2793 TargetOpcode::G_INSERT_VECTOR_ELT) 2794 return false; 2795 MachineInstr *CurrInst = &MI; 2796 MachineInstr *TmpInst; 2797 int64_t IntImm; 2798 Register TmpReg; 2799 MatchInfo.resize(NumElts); 2800 while (mi_match( 2801 CurrInst->getOperand(0).getReg(), MRI, 2802 m_GInsertVecElt(m_MInstr(TmpInst), m_Reg(TmpReg), m_ICst(IntImm)))) { 2803 if (IntImm >= NumElts) 2804 return false; 2805 if (!MatchInfo[IntImm]) 2806 MatchInfo[IntImm] = TmpReg; 2807 CurrInst = TmpInst; 2808 } 2809 // Variable index. 2810 if (CurrInst->getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT) 2811 return false; 2812 if (TmpInst->getOpcode() == TargetOpcode::G_BUILD_VECTOR) { 2813 for (unsigned I = 1; I < TmpInst->getNumOperands(); ++I) { 2814 if (!MatchInfo[I - 1].isValid()) 2815 MatchInfo[I - 1] = TmpInst->getOperand(I).getReg(); 2816 } 2817 return true; 2818 } 2819 // If we didn't end in a G_IMPLICIT_DEF, bail out. 2820 return TmpInst->getOpcode() == TargetOpcode::G_IMPLICIT_DEF; 2821 } 2822 2823 bool CombinerHelper::applyCombineInsertVecElts( 2824 MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) { 2825 Builder.setInstr(MI); 2826 Register UndefReg; 2827 auto GetUndef = [&]() { 2828 if (UndefReg) 2829 return UndefReg; 2830 LLT DstTy = MRI.getType(MI.getOperand(0).getReg()); 2831 UndefReg = Builder.buildUndef(DstTy.getScalarType()).getReg(0); 2832 return UndefReg; 2833 }; 2834 for (unsigned I = 0; I < MatchInfo.size(); ++I) { 2835 if (!MatchInfo[I]) 2836 MatchInfo[I] = GetUndef(); 2837 } 2838 Builder.buildBuildVector(MI.getOperand(0).getReg(), MatchInfo); 2839 MI.eraseFromParent(); 2840 return true; 2841 } 2842 2843 bool CombinerHelper::applySimplifyAddToSub( 2844 MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) { 2845 Builder.setInstr(MI); 2846 Register SubLHS, SubRHS; 2847 std::tie(SubLHS, SubRHS) = MatchInfo; 2848 Builder.buildSub(MI.getOperand(0).getReg(), SubLHS, SubRHS); 2849 MI.eraseFromParent(); 2850 return true; 2851 } 2852 2853 bool CombinerHelper::matchHoistLogicOpWithSameOpcodeHands( 2854 MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) { 2855 // Matches: logic (hand x, ...), (hand y, ...) -> hand (logic x, y), ... 2856 // 2857 // Creates the new hand + logic instruction (but does not insert them.) 2858 // 2859 // On success, MatchInfo is populated with the new instructions. These are 2860 // inserted in applyHoistLogicOpWithSameOpcodeHands. 2861 unsigned LogicOpcode = MI.getOpcode(); 2862 assert(LogicOpcode == TargetOpcode::G_AND || 2863 LogicOpcode == TargetOpcode::G_OR || 2864 LogicOpcode == TargetOpcode::G_XOR); 2865 MachineIRBuilder MIB(MI); 2866 Register Dst = MI.getOperand(0).getReg(); 2867 Register LHSReg = MI.getOperand(1).getReg(); 2868 Register RHSReg = MI.getOperand(2).getReg(); 2869 2870 // Don't recompute anything. 2871 if (!MRI.hasOneNonDBGUse(LHSReg) || !MRI.hasOneNonDBGUse(RHSReg)) 2872 return false; 2873 2874 // Make sure we have (hand x, ...), (hand y, ...) 2875 MachineInstr *LeftHandInst = getDefIgnoringCopies(LHSReg, MRI); 2876 MachineInstr *RightHandInst = getDefIgnoringCopies(RHSReg, MRI); 2877 if (!LeftHandInst || !RightHandInst) 2878 return false; 2879 unsigned HandOpcode = LeftHandInst->getOpcode(); 2880 if (HandOpcode != RightHandInst->getOpcode()) 2881 return false; 2882 if (!LeftHandInst->getOperand(1).isReg() || 2883 !RightHandInst->getOperand(1).isReg()) 2884 return false; 2885 2886 // Make sure the types match up, and if we're doing this post-legalization, 2887 // we end up with legal types. 2888 Register X = LeftHandInst->getOperand(1).getReg(); 2889 Register Y = RightHandInst->getOperand(1).getReg(); 2890 LLT XTy = MRI.getType(X); 2891 LLT YTy = MRI.getType(Y); 2892 if (XTy != YTy) 2893 return false; 2894 if (!isLegalOrBeforeLegalizer({LogicOpcode, {XTy, YTy}})) 2895 return false; 2896 2897 // Optional extra source register. 2898 Register ExtraHandOpSrcReg; 2899 switch (HandOpcode) { 2900 default: 2901 return false; 2902 case TargetOpcode::G_ANYEXT: 2903 case TargetOpcode::G_SEXT: 2904 case TargetOpcode::G_ZEXT: { 2905 // Match: logic (ext X), (ext Y) --> ext (logic X, Y) 2906 break; 2907 } 2908 case TargetOpcode::G_AND: 2909 case TargetOpcode::G_ASHR: 2910 case TargetOpcode::G_LSHR: 2911 case TargetOpcode::G_SHL: { 2912 // Match: logic (binop x, z), (binop y, z) -> binop (logic x, y), z 2913 MachineOperand &ZOp = LeftHandInst->getOperand(2); 2914 if (!matchEqualDefs(ZOp, RightHandInst->getOperand(2))) 2915 return false; 2916 ExtraHandOpSrcReg = ZOp.getReg(); 2917 break; 2918 } 2919 } 2920 2921 // Record the steps to build the new instructions. 2922 // 2923 // Steps to build (logic x, y) 2924 auto NewLogicDst = MRI.createGenericVirtualRegister(XTy); 2925 OperandBuildSteps LogicBuildSteps = { 2926 [=](MachineInstrBuilder &MIB) { MIB.addDef(NewLogicDst); }, 2927 [=](MachineInstrBuilder &MIB) { MIB.addReg(X); }, 2928 [=](MachineInstrBuilder &MIB) { MIB.addReg(Y); }}; 2929 InstructionBuildSteps LogicSteps(LogicOpcode, LogicBuildSteps); 2930 2931 // Steps to build hand (logic x, y), ...z 2932 OperandBuildSteps HandBuildSteps = { 2933 [=](MachineInstrBuilder &MIB) { MIB.addDef(Dst); }, 2934 [=](MachineInstrBuilder &MIB) { MIB.addReg(NewLogicDst); }}; 2935 if (ExtraHandOpSrcReg.isValid()) 2936 HandBuildSteps.push_back( 2937 [=](MachineInstrBuilder &MIB) { MIB.addReg(ExtraHandOpSrcReg); }); 2938 InstructionBuildSteps HandSteps(HandOpcode, HandBuildSteps); 2939 2940 MatchInfo = InstructionStepsMatchInfo({LogicSteps, HandSteps}); 2941 return true; 2942 } 2943 2944 bool CombinerHelper::applyBuildInstructionSteps( 2945 MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) { 2946 assert(MatchInfo.InstrsToBuild.size() && 2947 "Expected at least one instr to build?"); 2948 Builder.setInstr(MI); 2949 for (auto &InstrToBuild : MatchInfo.InstrsToBuild) { 2950 assert(InstrToBuild.Opcode && "Expected a valid opcode?"); 2951 assert(InstrToBuild.OperandFns.size() && "Expected at least one operand?"); 2952 MachineInstrBuilder Instr = Builder.buildInstr(InstrToBuild.Opcode); 2953 for (auto &OperandFn : InstrToBuild.OperandFns) 2954 OperandFn(Instr); 2955 } 2956 MI.eraseFromParent(); 2957 return true; 2958 } 2959 2960 bool CombinerHelper::matchAshrShlToSextInreg( 2961 MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) { 2962 assert(MI.getOpcode() == TargetOpcode::G_ASHR); 2963 int64_t ShlCst, AshrCst; 2964 Register Src; 2965 // FIXME: detect splat constant vectors. 2966 if (!mi_match(MI.getOperand(0).getReg(), MRI, 2967 m_GAShr(m_GShl(m_Reg(Src), m_ICst(ShlCst)), m_ICst(AshrCst)))) 2968 return false; 2969 if (ShlCst != AshrCst) 2970 return false; 2971 if (!isLegalOrBeforeLegalizer( 2972 {TargetOpcode::G_SEXT_INREG, {MRI.getType(Src)}})) 2973 return false; 2974 MatchInfo = std::make_tuple(Src, ShlCst); 2975 return true; 2976 } 2977 bool CombinerHelper::applyAshShlToSextInreg( 2978 MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) { 2979 assert(MI.getOpcode() == TargetOpcode::G_ASHR); 2980 Register Src; 2981 int64_t ShiftAmt; 2982 std::tie(Src, ShiftAmt) = MatchInfo; 2983 unsigned Size = MRI.getType(Src).getScalarSizeInBits(); 2984 Builder.setInstrAndDebugLoc(MI); 2985 Builder.buildSExtInReg(MI.getOperand(0).getReg(), Src, Size - ShiftAmt); 2986 MI.eraseFromParent(); 2987 return true; 2988 } 2989 2990 bool CombinerHelper::matchRedundantAnd(MachineInstr &MI, 2991 Register &Replacement) { 2992 // Given 2993 // 2994 // %y:_(sN) = G_SOMETHING 2995 // %x:_(sN) = G_SOMETHING 2996 // %res:_(sN) = G_AND %x, %y 2997 // 2998 // Eliminate the G_AND when it is known that x & y == x or x & y == y. 2999 // 3000 // Patterns like this can appear as a result of legalization. E.g. 3001 // 3002 // %cmp:_(s32) = G_ICMP intpred(pred), %x(s32), %y 3003 // %one:_(s32) = G_CONSTANT i32 1 3004 // %and:_(s32) = G_AND %cmp, %one 3005 // 3006 // In this case, G_ICMP only produces a single bit, so x & 1 == x. 3007 assert(MI.getOpcode() == TargetOpcode::G_AND); 3008 if (!KB) 3009 return false; 3010 3011 Register AndDst = MI.getOperand(0).getReg(); 3012 LLT DstTy = MRI.getType(AndDst); 3013 3014 // FIXME: This should be removed once GISelKnownBits supports vectors. 3015 if (DstTy.isVector()) 3016 return false; 3017 3018 Register LHS = MI.getOperand(1).getReg(); 3019 Register RHS = MI.getOperand(2).getReg(); 3020 KnownBits LHSBits = KB->getKnownBits(LHS); 3021 KnownBits RHSBits = KB->getKnownBits(RHS); 3022 3023 // Check that x & Mask == x. 3024 // x & 1 == x, always 3025 // x & 0 == x, only if x is also 0 3026 // Meaning Mask has no effect if every bit is either one in Mask or zero in x. 3027 // 3028 // Check if we can replace AndDst with the LHS of the G_AND 3029 if (canReplaceReg(AndDst, LHS, MRI) && 3030 (LHSBits.Zero | RHSBits.One).isAllOnesValue()) { 3031 Replacement = LHS; 3032 return true; 3033 } 3034 3035 // Check if we can replace AndDst with the RHS of the G_AND 3036 if (canReplaceReg(AndDst, RHS, MRI) && 3037 (LHSBits.One | RHSBits.Zero).isAllOnesValue()) { 3038 Replacement = RHS; 3039 return true; 3040 } 3041 3042 return false; 3043 } 3044 3045 bool CombinerHelper::matchRedundantOr(MachineInstr &MI, Register &Replacement) { 3046 // Given 3047 // 3048 // %y:_(sN) = G_SOMETHING 3049 // %x:_(sN) = G_SOMETHING 3050 // %res:_(sN) = G_OR %x, %y 3051 // 3052 // Eliminate the G_OR when it is known that x | y == x or x | y == y. 3053 assert(MI.getOpcode() == TargetOpcode::G_OR); 3054 if (!KB) 3055 return false; 3056 3057 Register OrDst = MI.getOperand(0).getReg(); 3058 LLT DstTy = MRI.getType(OrDst); 3059 3060 // FIXME: This should be removed once GISelKnownBits supports vectors. 3061 if (DstTy.isVector()) 3062 return false; 3063 3064 Register LHS = MI.getOperand(1).getReg(); 3065 Register RHS = MI.getOperand(2).getReg(); 3066 KnownBits LHSBits = KB->getKnownBits(LHS); 3067 KnownBits RHSBits = KB->getKnownBits(RHS); 3068 3069 // Check that x | Mask == x. 3070 // x | 0 == x, always 3071 // x | 1 == x, only if x is also 1 3072 // Meaning Mask has no effect if every bit is either zero in Mask or one in x. 3073 // 3074 // Check if we can replace OrDst with the LHS of the G_OR 3075 if (canReplaceReg(OrDst, LHS, MRI) && 3076 (LHSBits.One | RHSBits.Zero).isAllOnesValue()) { 3077 Replacement = LHS; 3078 return true; 3079 } 3080 3081 // Check if we can replace OrDst with the RHS of the G_OR 3082 if (canReplaceReg(OrDst, RHS, MRI) && 3083 (LHSBits.Zero | RHSBits.One).isAllOnesValue()) { 3084 Replacement = RHS; 3085 return true; 3086 } 3087 3088 return false; 3089 } 3090 3091 bool CombinerHelper::matchRedundantSExtInReg(MachineInstr &MI) { 3092 // If the input is already sign extended, just drop the extension. 3093 Register Src = MI.getOperand(1).getReg(); 3094 unsigned ExtBits = MI.getOperand(2).getImm(); 3095 unsigned TypeSize = MRI.getType(Src).getScalarSizeInBits(); 3096 return KB->computeNumSignBits(Src) >= (TypeSize - ExtBits + 1); 3097 } 3098 3099 static bool isConstValidTrue(const TargetLowering &TLI, unsigned ScalarSizeBits, 3100 int64_t Cst, bool IsVector, bool IsFP) { 3101 // For i1, Cst will always be -1 regardless of boolean contents. 3102 return (ScalarSizeBits == 1 && Cst == -1) || 3103 isConstTrueVal(TLI, Cst, IsVector, IsFP); 3104 } 3105 3106 bool CombinerHelper::matchNotCmp(MachineInstr &MI, 3107 SmallVectorImpl<Register> &RegsToNegate) { 3108 assert(MI.getOpcode() == TargetOpcode::G_XOR); 3109 LLT Ty = MRI.getType(MI.getOperand(0).getReg()); 3110 const auto &TLI = *Builder.getMF().getSubtarget().getTargetLowering(); 3111 Register XorSrc; 3112 Register CstReg; 3113 // We match xor(src, true) here. 3114 if (!mi_match(MI.getOperand(0).getReg(), MRI, 3115 m_GXor(m_Reg(XorSrc), m_Reg(CstReg)))) 3116 return false; 3117 3118 if (!MRI.hasOneNonDBGUse(XorSrc)) 3119 return false; 3120 3121 // Check that XorSrc is the root of a tree of comparisons combined with ANDs 3122 // and ORs. The suffix of RegsToNegate starting from index I is used a work 3123 // list of tree nodes to visit. 3124 RegsToNegate.push_back(XorSrc); 3125 // Remember whether the comparisons are all integer or all floating point. 3126 bool IsInt = false; 3127 bool IsFP = false; 3128 for (unsigned I = 0; I < RegsToNegate.size(); ++I) { 3129 Register Reg = RegsToNegate[I]; 3130 if (!MRI.hasOneNonDBGUse(Reg)) 3131 return false; 3132 MachineInstr *Def = MRI.getVRegDef(Reg); 3133 switch (Def->getOpcode()) { 3134 default: 3135 // Don't match if the tree contains anything other than ANDs, ORs and 3136 // comparisons. 3137 return false; 3138 case TargetOpcode::G_ICMP: 3139 if (IsFP) 3140 return false; 3141 IsInt = true; 3142 // When we apply the combine we will invert the predicate. 3143 break; 3144 case TargetOpcode::G_FCMP: 3145 if (IsInt) 3146 return false; 3147 IsFP = true; 3148 // When we apply the combine we will invert the predicate. 3149 break; 3150 case TargetOpcode::G_AND: 3151 case TargetOpcode::G_OR: 3152 // Implement De Morgan's laws: 3153 // ~(x & y) -> ~x | ~y 3154 // ~(x | y) -> ~x & ~y 3155 // When we apply the combine we will change the opcode and recursively 3156 // negate the operands. 3157 RegsToNegate.push_back(Def->getOperand(1).getReg()); 3158 RegsToNegate.push_back(Def->getOperand(2).getReg()); 3159 break; 3160 } 3161 } 3162 3163 // Now we know whether the comparisons are integer or floating point, check 3164 // the constant in the xor. 3165 int64_t Cst; 3166 if (Ty.isVector()) { 3167 MachineInstr *CstDef = MRI.getVRegDef(CstReg); 3168 auto MaybeCst = getBuildVectorConstantSplat(*CstDef, MRI); 3169 if (!MaybeCst) 3170 return false; 3171 if (!isConstValidTrue(TLI, Ty.getScalarSizeInBits(), *MaybeCst, true, IsFP)) 3172 return false; 3173 } else { 3174 if (!mi_match(CstReg, MRI, m_ICst(Cst))) 3175 return false; 3176 if (!isConstValidTrue(TLI, Ty.getSizeInBits(), Cst, false, IsFP)) 3177 return false; 3178 } 3179 3180 return true; 3181 } 3182 3183 bool CombinerHelper::applyNotCmp(MachineInstr &MI, 3184 SmallVectorImpl<Register> &RegsToNegate) { 3185 for (Register Reg : RegsToNegate) { 3186 MachineInstr *Def = MRI.getVRegDef(Reg); 3187 Observer.changingInstr(*Def); 3188 // For each comparison, invert the opcode. For each AND and OR, change the 3189 // opcode. 3190 switch (Def->getOpcode()) { 3191 default: 3192 llvm_unreachable("Unexpected opcode"); 3193 case TargetOpcode::G_ICMP: 3194 case TargetOpcode::G_FCMP: { 3195 MachineOperand &PredOp = Def->getOperand(1); 3196 CmpInst::Predicate NewP = CmpInst::getInversePredicate( 3197 (CmpInst::Predicate)PredOp.getPredicate()); 3198 PredOp.setPredicate(NewP); 3199 break; 3200 } 3201 case TargetOpcode::G_AND: 3202 Def->setDesc(Builder.getTII().get(TargetOpcode::G_OR)); 3203 break; 3204 case TargetOpcode::G_OR: 3205 Def->setDesc(Builder.getTII().get(TargetOpcode::G_AND)); 3206 break; 3207 } 3208 Observer.changedInstr(*Def); 3209 } 3210 3211 replaceRegWith(MRI, MI.getOperand(0).getReg(), MI.getOperand(1).getReg()); 3212 MI.eraseFromParent(); 3213 return true; 3214 } 3215 3216 bool CombinerHelper::matchXorOfAndWithSameReg( 3217 MachineInstr &MI, std::pair<Register, Register> &MatchInfo) { 3218 // Match (xor (and x, y), y) (or any of its commuted cases) 3219 assert(MI.getOpcode() == TargetOpcode::G_XOR); 3220 Register &X = MatchInfo.first; 3221 Register &Y = MatchInfo.second; 3222 Register AndReg = MI.getOperand(1).getReg(); 3223 Register SharedReg = MI.getOperand(2).getReg(); 3224 3225 // Find a G_AND on either side of the G_XOR. 3226 // Look for one of 3227 // 3228 // (xor (and x, y), SharedReg) 3229 // (xor SharedReg, (and x, y)) 3230 if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y)))) { 3231 std::swap(AndReg, SharedReg); 3232 if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y)))) 3233 return false; 3234 } 3235 3236 // Only do this if we'll eliminate the G_AND. 3237 if (!MRI.hasOneNonDBGUse(AndReg)) 3238 return false; 3239 3240 // We can combine if SharedReg is the same as either the LHS or RHS of the 3241 // G_AND. 3242 if (Y != SharedReg) 3243 std::swap(X, Y); 3244 return Y == SharedReg; 3245 } 3246 3247 bool CombinerHelper::applyXorOfAndWithSameReg( 3248 MachineInstr &MI, std::pair<Register, Register> &MatchInfo) { 3249 // Fold (xor (and x, y), y) -> (and (not x), y) 3250 Builder.setInstrAndDebugLoc(MI); 3251 Register X, Y; 3252 std::tie(X, Y) = MatchInfo; 3253 auto Not = Builder.buildNot(MRI.getType(X), X); 3254 Observer.changingInstr(MI); 3255 MI.setDesc(Builder.getTII().get(TargetOpcode::G_AND)); 3256 MI.getOperand(1).setReg(Not->getOperand(0).getReg()); 3257 MI.getOperand(2).setReg(Y); 3258 Observer.changedInstr(MI); 3259 return true; 3260 } 3261 3262 bool CombinerHelper::matchPtrAddZero(MachineInstr &MI) { 3263 Register DstReg = MI.getOperand(0).getReg(); 3264 LLT Ty = MRI.getType(DstReg); 3265 const DataLayout &DL = Builder.getMF().getDataLayout(); 3266 3267 if (DL.isNonIntegralAddressSpace(Ty.getScalarType().getAddressSpace())) 3268 return false; 3269 3270 if (Ty.isPointer()) { 3271 auto ConstVal = getConstantVRegVal(MI.getOperand(1).getReg(), MRI); 3272 return ConstVal && *ConstVal == 0; 3273 } 3274 3275 assert(Ty.isVector() && "Expecting a vector type"); 3276 const MachineInstr *VecMI = MRI.getVRegDef(MI.getOperand(1).getReg()); 3277 return isBuildVectorAllZeros(*VecMI, MRI); 3278 } 3279 3280 bool CombinerHelper::applyPtrAddZero(MachineInstr &MI) { 3281 assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD); 3282 Builder.setInstrAndDebugLoc(MI); 3283 Builder.buildIntToPtr(MI.getOperand(0), MI.getOperand(2)); 3284 MI.eraseFromParent(); 3285 return true; 3286 } 3287 3288 /// The second source operand is known to be a power of 2. 3289 bool CombinerHelper::applySimplifyURemByPow2(MachineInstr &MI) { 3290 Register DstReg = MI.getOperand(0).getReg(); 3291 Register Src0 = MI.getOperand(1).getReg(); 3292 Register Pow2Src1 = MI.getOperand(2).getReg(); 3293 LLT Ty = MRI.getType(DstReg); 3294 Builder.setInstrAndDebugLoc(MI); 3295 3296 // Fold (urem x, pow2) -> (and x, pow2-1) 3297 auto NegOne = Builder.buildConstant(Ty, -1); 3298 auto Add = Builder.buildAdd(Ty, Pow2Src1, NegOne); 3299 Builder.buildAnd(DstReg, Src0, Add); 3300 MI.eraseFromParent(); 3301 return true; 3302 } 3303 3304 Optional<SmallVector<Register, 8>> 3305 CombinerHelper::findCandidatesForLoadOrCombine(const MachineInstr *Root) const { 3306 assert(Root->getOpcode() == TargetOpcode::G_OR && "Expected G_OR only!"); 3307 // We want to detect if Root is part of a tree which represents a bunch 3308 // of loads being merged into a larger load. We'll try to recognize patterns 3309 // like, for example: 3310 // 3311 // Reg Reg 3312 // \ / 3313 // OR_1 Reg 3314 // \ / 3315 // OR_2 3316 // \ Reg 3317 // .. / 3318 // Root 3319 // 3320 // Reg Reg Reg Reg 3321 // \ / \ / 3322 // OR_1 OR_2 3323 // \ / 3324 // \ / 3325 // ... 3326 // Root 3327 // 3328 // Each "Reg" may have been produced by a load + some arithmetic. This 3329 // function will save each of them. 3330 SmallVector<Register, 8> RegsToVisit; 3331 SmallVector<const MachineInstr *, 7> Ors = {Root}; 3332 3333 // In the "worst" case, we're dealing with a load for each byte. So, there 3334 // are at most #bytes - 1 ORs. 3335 const unsigned MaxIter = 3336 MRI.getType(Root->getOperand(0).getReg()).getSizeInBytes() - 1; 3337 for (unsigned Iter = 0; Iter < MaxIter; ++Iter) { 3338 if (Ors.empty()) 3339 break; 3340 const MachineInstr *Curr = Ors.pop_back_val(); 3341 Register OrLHS = Curr->getOperand(1).getReg(); 3342 Register OrRHS = Curr->getOperand(2).getReg(); 3343 3344 // In the combine, we want to elimate the entire tree. 3345 if (!MRI.hasOneNonDBGUse(OrLHS) || !MRI.hasOneNonDBGUse(OrRHS)) 3346 return None; 3347 3348 // If it's a G_OR, save it and continue to walk. If it's not, then it's 3349 // something that may be a load + arithmetic. 3350 if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrLHS, MRI)) 3351 Ors.push_back(Or); 3352 else 3353 RegsToVisit.push_back(OrLHS); 3354 if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrRHS, MRI)) 3355 Ors.push_back(Or); 3356 else 3357 RegsToVisit.push_back(OrRHS); 3358 } 3359 3360 // We're going to try and merge each register into a wider power-of-2 type, 3361 // so we ought to have an even number of registers. 3362 if (RegsToVisit.empty() || RegsToVisit.size() % 2 != 0) 3363 return None; 3364 return RegsToVisit; 3365 } 3366 3367 /// Helper function for findLoadOffsetsForLoadOrCombine. 3368 /// 3369 /// Check if \p Reg is the result of loading a \p MemSizeInBits wide value, 3370 /// and then moving that value into a specific byte offset. 3371 /// 3372 /// e.g. x[i] << 24 3373 /// 3374 /// \returns The load instruction and the byte offset it is moved into. 3375 static Optional<std::pair<MachineInstr *, int64_t>> 3376 matchLoadAndBytePosition(Register Reg, unsigned MemSizeInBits, 3377 const MachineRegisterInfo &MRI) { 3378 assert(MRI.hasOneNonDBGUse(Reg) && 3379 "Expected Reg to only have one non-debug use?"); 3380 Register MaybeLoad; 3381 int64_t Shift; 3382 if (!mi_match(Reg, MRI, 3383 m_OneNonDBGUse(m_GShl(m_Reg(MaybeLoad), m_ICst(Shift))))) { 3384 Shift = 0; 3385 MaybeLoad = Reg; 3386 } 3387 3388 if (Shift % MemSizeInBits != 0) 3389 return None; 3390 3391 // TODO: Handle other types of loads. 3392 auto *Load = getOpcodeDef(TargetOpcode::G_ZEXTLOAD, MaybeLoad, MRI); 3393 if (!Load) 3394 return None; 3395 3396 const auto &MMO = **Load->memoperands_begin(); 3397 if (!MMO.isUnordered() || MMO.getSizeInBits() != MemSizeInBits) 3398 return None; 3399 3400 return std::make_pair(Load, Shift / MemSizeInBits); 3401 } 3402 3403 Optional<std::pair<MachineInstr *, int64_t>> 3404 CombinerHelper::findLoadOffsetsForLoadOrCombine( 3405 SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx, 3406 const SmallVector<Register, 8> &RegsToVisit, const unsigned MemSizeInBits) { 3407 3408 // Each load found for the pattern. There should be one for each RegsToVisit. 3409 SmallSetVector<const MachineInstr *, 8> Loads; 3410 3411 // The lowest index used in any load. (The lowest "i" for each x[i].) 3412 int64_t LowestIdx = INT64_MAX; 3413 3414 // The load which uses the lowest index. 3415 MachineInstr *LowestIdxLoad = nullptr; 3416 3417 // Keeps track of the load indices we see. We shouldn't see any indices twice. 3418 SmallSet<int64_t, 8> SeenIdx; 3419 3420 // Ensure each load is in the same MBB. 3421 // TODO: Support multiple MachineBasicBlocks. 3422 MachineBasicBlock *MBB = nullptr; 3423 const MachineMemOperand *MMO = nullptr; 3424 3425 // Earliest instruction-order load in the pattern. 3426 MachineInstr *EarliestLoad = nullptr; 3427 3428 // Latest instruction-order load in the pattern. 3429 MachineInstr *LatestLoad = nullptr; 3430 3431 // Base pointer which every load should share. 3432 Register BasePtr; 3433 3434 // We want to find a load for each register. Each load should have some 3435 // appropriate bit twiddling arithmetic. During this loop, we will also keep 3436 // track of the load which uses the lowest index. Later, we will check if we 3437 // can use its pointer in the final, combined load. 3438 for (auto Reg : RegsToVisit) { 3439 // Find the load, and find the position that it will end up in (e.g. a 3440 // shifted) value. 3441 auto LoadAndPos = matchLoadAndBytePosition(Reg, MemSizeInBits, MRI); 3442 if (!LoadAndPos) 3443 return None; 3444 MachineInstr *Load; 3445 int64_t DstPos; 3446 std::tie(Load, DstPos) = *LoadAndPos; 3447 3448 // TODO: Handle multiple MachineBasicBlocks. Currently not handled because 3449 // it is difficult to check for stores/calls/etc between loads. 3450 MachineBasicBlock *LoadMBB = Load->getParent(); 3451 if (!MBB) 3452 MBB = LoadMBB; 3453 if (LoadMBB != MBB) 3454 return None; 3455 3456 // Make sure that the MachineMemOperands of every seen load are compatible. 3457 const MachineMemOperand *LoadMMO = *Load->memoperands_begin(); 3458 if (!MMO) 3459 MMO = LoadMMO; 3460 if (MMO->getAddrSpace() != LoadMMO->getAddrSpace()) 3461 return None; 3462 3463 // Find out what the base pointer and index for the load is. 3464 Register LoadPtr; 3465 int64_t Idx; 3466 if (!mi_match(Load->getOperand(1).getReg(), MRI, 3467 m_GPtrAdd(m_Reg(LoadPtr), m_ICst(Idx)))) { 3468 LoadPtr = Load->getOperand(1).getReg(); 3469 Idx = 0; 3470 } 3471 3472 // Don't combine things like a[i], a[i] -> a bigger load. 3473 if (!SeenIdx.insert(Idx).second) 3474 return None; 3475 3476 // Every load must share the same base pointer; don't combine things like: 3477 // 3478 // a[i], b[i + 1] -> a bigger load. 3479 if (!BasePtr.isValid()) 3480 BasePtr = LoadPtr; 3481 if (BasePtr != LoadPtr) 3482 return None; 3483 3484 if (Idx < LowestIdx) { 3485 LowestIdx = Idx; 3486 LowestIdxLoad = Load; 3487 } 3488 3489 // Keep track of the byte offset that this load ends up at. If we have seen 3490 // the byte offset, then stop here. We do not want to combine: 3491 // 3492 // a[i] << 16, a[i + k] << 16 -> a bigger load. 3493 if (!MemOffset2Idx.try_emplace(DstPos, Idx).second) 3494 return None; 3495 Loads.insert(Load); 3496 3497 // Keep track of the position of the earliest/latest loads in the pattern. 3498 // We will check that there are no load fold barriers between them later 3499 // on. 3500 // 3501 // FIXME: Is there a better way to check for load fold barriers? 3502 if (!EarliestLoad || dominates(*Load, *EarliestLoad)) 3503 EarliestLoad = Load; 3504 if (!LatestLoad || dominates(*LatestLoad, *Load)) 3505 LatestLoad = Load; 3506 } 3507 3508 // We found a load for each register. Let's check if each load satisfies the 3509 // pattern. 3510 assert(Loads.size() == RegsToVisit.size() && 3511 "Expected to find a load for each register?"); 3512 assert(EarliestLoad != LatestLoad && EarliestLoad && 3513 LatestLoad && "Expected at least two loads?"); 3514 3515 // Check if there are any stores, calls, etc. between any of the loads. If 3516 // there are, then we can't safely perform the combine. 3517 // 3518 // MaxIter is chosen based off the (worst case) number of iterations it 3519 // typically takes to succeed in the LLVM test suite plus some padding. 3520 // 3521 // FIXME: Is there a better way to check for load fold barriers? 3522 const unsigned MaxIter = 20; 3523 unsigned Iter = 0; 3524 for (const auto &MI : instructionsWithoutDebug(EarliestLoad->getIterator(), 3525 LatestLoad->getIterator())) { 3526 if (Loads.count(&MI)) 3527 continue; 3528 if (MI.isLoadFoldBarrier()) 3529 return None; 3530 if (Iter++ == MaxIter) 3531 return None; 3532 } 3533 3534 return std::make_pair(LowestIdxLoad, LowestIdx); 3535 } 3536 3537 bool CombinerHelper::matchLoadOrCombine( 3538 MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) { 3539 assert(MI.getOpcode() == TargetOpcode::G_OR); 3540 MachineFunction &MF = *MI.getMF(); 3541 // Assuming a little-endian target, transform: 3542 // s8 *a = ... 3543 // s32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 3544 // => 3545 // s32 val = *((i32)a) 3546 // 3547 // s8 *a = ... 3548 // s32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 3549 // => 3550 // s32 val = BSWAP(*((s32)a)) 3551 Register Dst = MI.getOperand(0).getReg(); 3552 LLT Ty = MRI.getType(Dst); 3553 if (Ty.isVector()) 3554 return false; 3555 3556 // We need to combine at least two loads into this type. Since the smallest 3557 // possible load is into a byte, we need at least a 16-bit wide type. 3558 const unsigned WideMemSizeInBits = Ty.getSizeInBits(); 3559 if (WideMemSizeInBits < 16 || WideMemSizeInBits % 8 != 0) 3560 return false; 3561 3562 // Match a collection of non-OR instructions in the pattern. 3563 auto RegsToVisit = findCandidatesForLoadOrCombine(&MI); 3564 if (!RegsToVisit) 3565 return false; 3566 3567 // We have a collection of non-OR instructions. Figure out how wide each of 3568 // the small loads should be based off of the number of potential loads we 3569 // found. 3570 const unsigned NarrowMemSizeInBits = WideMemSizeInBits / RegsToVisit->size(); 3571 if (NarrowMemSizeInBits % 8 != 0) 3572 return false; 3573 3574 // Check if each register feeding into each OR is a load from the same 3575 // base pointer + some arithmetic. 3576 // 3577 // e.g. a[0], a[1] << 8, a[2] << 16, etc. 3578 // 3579 // Also verify that each of these ends up putting a[i] into the same memory 3580 // offset as a load into a wide type would. 3581 SmallDenseMap<int64_t, int64_t, 8> MemOffset2Idx; 3582 MachineInstr *LowestIdxLoad; 3583 int64_t LowestIdx; 3584 auto MaybeLoadInfo = findLoadOffsetsForLoadOrCombine( 3585 MemOffset2Idx, *RegsToVisit, NarrowMemSizeInBits); 3586 if (!MaybeLoadInfo) 3587 return false; 3588 std::tie(LowestIdxLoad, LowestIdx) = *MaybeLoadInfo; 3589 3590 // We have a bunch of loads being OR'd together. Using the addresses + offsets 3591 // we found before, check if this corresponds to a big or little endian byte 3592 // pattern. If it does, then we can represent it using a load + possibly a 3593 // BSWAP. 3594 bool IsBigEndianTarget = MF.getDataLayout().isBigEndian(); 3595 Optional<bool> IsBigEndian = isBigEndian(MemOffset2Idx, LowestIdx); 3596 if (!IsBigEndian.hasValue()) 3597 return false; 3598 bool NeedsBSwap = IsBigEndianTarget != *IsBigEndian; 3599 if (NeedsBSwap && !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {Ty}})) 3600 return false; 3601 3602 // Make sure that the load from the lowest index produces offset 0 in the 3603 // final value. 3604 // 3605 // This ensures that we won't combine something like this: 3606 // 3607 // load x[i] -> byte 2 3608 // load x[i+1] -> byte 0 ---> wide_load x[i] 3609 // load x[i+2] -> byte 1 3610 const unsigned NumLoadsInTy = WideMemSizeInBits / NarrowMemSizeInBits; 3611 const unsigned ZeroByteOffset = 3612 *IsBigEndian 3613 ? bigEndianByteAt(NumLoadsInTy, 0) 3614 : littleEndianByteAt(NumLoadsInTy, 0); 3615 auto ZeroOffsetIdx = MemOffset2Idx.find(ZeroByteOffset); 3616 if (ZeroOffsetIdx == MemOffset2Idx.end() || 3617 ZeroOffsetIdx->second != LowestIdx) 3618 return false; 3619 3620 // We wil reuse the pointer from the load which ends up at byte offset 0. It 3621 // may not use index 0. 3622 Register Ptr = LowestIdxLoad->getOperand(1).getReg(); 3623 const MachineMemOperand &MMO = **LowestIdxLoad->memoperands_begin(); 3624 LegalityQuery::MemDesc MMDesc; 3625 MMDesc.SizeInBits = WideMemSizeInBits; 3626 MMDesc.AlignInBits = MMO.getAlign().value() * 8; 3627 MMDesc.Ordering = MMO.getOrdering(); 3628 if (!isLegalOrBeforeLegalizer( 3629 {TargetOpcode::G_LOAD, {Ty, MRI.getType(Ptr)}, {MMDesc}})) 3630 return false; 3631 auto PtrInfo = MMO.getPointerInfo(); 3632 auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, WideMemSizeInBits / 8); 3633 3634 // Load must be allowed and fast on the target. 3635 LLVMContext &C = MF.getFunction().getContext(); 3636 auto &DL = MF.getDataLayout(); 3637 bool Fast = false; 3638 if (!getTargetLowering().allowsMemoryAccess(C, DL, Ty, *NewMMO, &Fast) || 3639 !Fast) 3640 return false; 3641 3642 MatchInfo = [=](MachineIRBuilder &MIB) { 3643 Register LoadDst = NeedsBSwap ? MRI.cloneVirtualRegister(Dst) : Dst; 3644 MIB.buildLoad(LoadDst, Ptr, *NewMMO); 3645 if (NeedsBSwap) 3646 MIB.buildBSwap(Dst, LoadDst); 3647 }; 3648 return true; 3649 } 3650 3651 bool CombinerHelper::matchExtendThroughPhis(MachineInstr &MI, 3652 MachineInstr *&ExtMI) { 3653 assert(MI.getOpcode() == TargetOpcode::G_PHI); 3654 3655 Register DstReg = MI.getOperand(0).getReg(); 3656 3657 // TODO: Extending a vector may be expensive, don't do this until heuristics 3658 // are better. 3659 if (MRI.getType(DstReg).isVector()) 3660 return false; 3661 3662 // Try to match a phi, whose only use is an extend. 3663 if (!MRI.hasOneNonDBGUse(DstReg)) 3664 return false; 3665 ExtMI = &*MRI.use_instr_nodbg_begin(DstReg); 3666 switch (ExtMI->getOpcode()) { 3667 case TargetOpcode::G_ANYEXT: 3668 return true; // G_ANYEXT is usually free. 3669 case TargetOpcode::G_ZEXT: 3670 case TargetOpcode::G_SEXT: 3671 break; 3672 default: 3673 return false; 3674 } 3675 3676 // If the target is likely to fold this extend away, don't propagate. 3677 if (Builder.getTII().isExtendLikelyToBeFolded(*ExtMI, MRI)) 3678 return false; 3679 3680 // We don't want to propagate the extends unless there's a good chance that 3681 // they'll be optimized in some way. 3682 // Collect the unique incoming values. 3683 SmallPtrSet<MachineInstr *, 4> InSrcs; 3684 for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) { 3685 auto *DefMI = getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI); 3686 switch (DefMI->getOpcode()) { 3687 case TargetOpcode::G_LOAD: 3688 case TargetOpcode::G_TRUNC: 3689 case TargetOpcode::G_SEXT: 3690 case TargetOpcode::G_ZEXT: 3691 case TargetOpcode::G_ANYEXT: 3692 case TargetOpcode::G_CONSTANT: 3693 InSrcs.insert(getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI)); 3694 // Don't try to propagate if there are too many places to create new 3695 // extends, chances are it'll increase code size. 3696 if (InSrcs.size() > 2) 3697 return false; 3698 break; 3699 default: 3700 return false; 3701 } 3702 } 3703 return true; 3704 } 3705 3706 bool CombinerHelper::applyExtendThroughPhis(MachineInstr &MI, 3707 MachineInstr *&ExtMI) { 3708 assert(MI.getOpcode() == TargetOpcode::G_PHI); 3709 Register DstReg = ExtMI->getOperand(0).getReg(); 3710 LLT ExtTy = MRI.getType(DstReg); 3711 3712 // Propagate the extension into the block of each incoming reg's block. 3713 // Use a SetVector here because PHIs can have duplicate edges, and we want 3714 // deterministic iteration order. 3715 SmallSetVector<MachineInstr *, 8> SrcMIs; 3716 SmallDenseMap<MachineInstr *, MachineInstr *, 8> OldToNewSrcMap; 3717 for (unsigned SrcIdx = 1; SrcIdx < MI.getNumOperands(); SrcIdx += 2) { 3718 auto *SrcMI = MRI.getVRegDef(MI.getOperand(SrcIdx).getReg()); 3719 if (!SrcMIs.insert(SrcMI)) 3720 continue; 3721 3722 // Build an extend after each src inst. 3723 auto *MBB = SrcMI->getParent(); 3724 MachineBasicBlock::iterator InsertPt = ++SrcMI->getIterator(); 3725 if (InsertPt != MBB->end() && InsertPt->isPHI()) 3726 InsertPt = MBB->getFirstNonPHI(); 3727 3728 Builder.setInsertPt(*SrcMI->getParent(), InsertPt); 3729 Builder.setDebugLoc(MI.getDebugLoc()); 3730 auto NewExt = Builder.buildExtOrTrunc(ExtMI->getOpcode(), ExtTy, 3731 SrcMI->getOperand(0).getReg()); 3732 OldToNewSrcMap[SrcMI] = NewExt; 3733 } 3734 3735 // Create a new phi with the extended inputs. 3736 Builder.setInstrAndDebugLoc(MI); 3737 auto NewPhi = Builder.buildInstrNoInsert(TargetOpcode::G_PHI); 3738 NewPhi.addDef(DstReg); 3739 for (unsigned SrcIdx = 1; SrcIdx < MI.getNumOperands(); ++SrcIdx) { 3740 auto &MO = MI.getOperand(SrcIdx); 3741 if (!MO.isReg()) { 3742 NewPhi.addMBB(MO.getMBB()); 3743 continue; 3744 } 3745 auto *NewSrc = OldToNewSrcMap[MRI.getVRegDef(MO.getReg())]; 3746 NewPhi.addUse(NewSrc->getOperand(0).getReg()); 3747 } 3748 Builder.insertInstr(NewPhi); 3749 ExtMI->eraseFromParent(); 3750 return true; 3751 } 3752 3753 bool CombinerHelper::matchExtractVecEltBuildVec(MachineInstr &MI, 3754 Register &Reg) { 3755 assert(MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT); 3756 // If we have a constant index, look for a G_BUILD_VECTOR source 3757 // and find the source register that the index maps to. 3758 Register SrcVec = MI.getOperand(1).getReg(); 3759 LLT SrcTy = MRI.getType(SrcVec); 3760 if (!isLegalOrBeforeLegalizer( 3761 {TargetOpcode::G_BUILD_VECTOR, {SrcTy, SrcTy.getElementType()}})) 3762 return false; 3763 3764 auto Cst = getConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI); 3765 if (!Cst || Cst->Value.getZExtValue() >= SrcTy.getNumElements()) 3766 return false; 3767 3768 unsigned VecIdx = Cst->Value.getZExtValue(); 3769 MachineInstr *BuildVecMI = 3770 getOpcodeDef(TargetOpcode::G_BUILD_VECTOR, SrcVec, MRI); 3771 if (!BuildVecMI) { 3772 BuildVecMI = getOpcodeDef(TargetOpcode::G_BUILD_VECTOR_TRUNC, SrcVec, MRI); 3773 if (!BuildVecMI) 3774 return false; 3775 LLT ScalarTy = MRI.getType(BuildVecMI->getOperand(1).getReg()); 3776 if (!isLegalOrBeforeLegalizer( 3777 {TargetOpcode::G_BUILD_VECTOR_TRUNC, {SrcTy, ScalarTy}})) 3778 return false; 3779 } 3780 3781 EVT Ty(getMVTForLLT(SrcTy)); 3782 if (!MRI.hasOneNonDBGUse(SrcVec) && 3783 !getTargetLowering().aggressivelyPreferBuildVectorSources(Ty)) 3784 return false; 3785 3786 Reg = BuildVecMI->getOperand(VecIdx + 1).getReg(); 3787 return true; 3788 } 3789 3790 void CombinerHelper::applyExtractVecEltBuildVec(MachineInstr &MI, 3791 Register &Reg) { 3792 // Check the type of the register, since it may have come from a 3793 // G_BUILD_VECTOR_TRUNC. 3794 LLT ScalarTy = MRI.getType(Reg); 3795 Register DstReg = MI.getOperand(0).getReg(); 3796 LLT DstTy = MRI.getType(DstReg); 3797 3798 Builder.setInstrAndDebugLoc(MI); 3799 if (ScalarTy != DstTy) { 3800 assert(ScalarTy.getSizeInBits() > DstTy.getSizeInBits()); 3801 Builder.buildTrunc(DstReg, Reg); 3802 MI.eraseFromParent(); 3803 return; 3804 } 3805 replaceSingleDefInstWithReg(MI, Reg); 3806 } 3807 3808 bool CombinerHelper::matchExtractAllEltsFromBuildVector( 3809 MachineInstr &MI, 3810 SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) { 3811 assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR); 3812 // This combine tries to find build_vector's which have every source element 3813 // extracted using G_EXTRACT_VECTOR_ELT. This can happen when transforms like 3814 // the masked load scalarization is run late in the pipeline. There's already 3815 // a combine for a similar pattern starting from the extract, but that 3816 // doesn't attempt to do it if there are multiple uses of the build_vector, 3817 // which in this case is true. Starting the combine from the build_vector 3818 // feels more natural than trying to find sibling nodes of extracts. 3819 // E.g. 3820 // %vec(<4 x s32>) = G_BUILD_VECTOR %s1(s32), %s2, %s3, %s4 3821 // %ext1 = G_EXTRACT_VECTOR_ELT %vec, 0 3822 // %ext2 = G_EXTRACT_VECTOR_ELT %vec, 1 3823 // %ext3 = G_EXTRACT_VECTOR_ELT %vec, 2 3824 // %ext4 = G_EXTRACT_VECTOR_ELT %vec, 3 3825 // ==> 3826 // replace ext{1,2,3,4} with %s{1,2,3,4} 3827 3828 Register DstReg = MI.getOperand(0).getReg(); 3829 LLT DstTy = MRI.getType(DstReg); 3830 unsigned NumElts = DstTy.getNumElements(); 3831 3832 SmallBitVector ExtractedElts(NumElts); 3833 for (auto &II : make_range(MRI.use_instr_nodbg_begin(DstReg), 3834 MRI.use_instr_nodbg_end())) { 3835 if (II.getOpcode() != TargetOpcode::G_EXTRACT_VECTOR_ELT) 3836 return false; 3837 auto Cst = getConstantVRegVal(II.getOperand(2).getReg(), MRI); 3838 if (!Cst) 3839 return false; 3840 unsigned Idx = Cst.getValue().getZExtValue(); 3841 if (Idx >= NumElts) 3842 return false; // Out of range. 3843 ExtractedElts.set(Idx); 3844 SrcDstPairs.emplace_back( 3845 std::make_pair(MI.getOperand(Idx + 1).getReg(), &II)); 3846 } 3847 // Match if every element was extracted. 3848 return ExtractedElts.all(); 3849 } 3850 3851 void CombinerHelper::applyExtractAllEltsFromBuildVector( 3852 MachineInstr &MI, 3853 SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) { 3854 assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR); 3855 for (auto &Pair : SrcDstPairs) { 3856 auto *ExtMI = Pair.second; 3857 replaceRegWith(MRI, ExtMI->getOperand(0).getReg(), Pair.first); 3858 ExtMI->eraseFromParent(); 3859 } 3860 MI.eraseFromParent(); 3861 } 3862 3863 bool CombinerHelper::applyBuildFn( 3864 MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) { 3865 Builder.setInstrAndDebugLoc(MI); 3866 MatchInfo(Builder); 3867 MI.eraseFromParent(); 3868 return true; 3869 } 3870 3871 /// Match an FSHL or FSHR that can be combined to a ROTR or ROTL rotate. 3872 bool CombinerHelper::matchFunnelShiftToRotate(MachineInstr &MI) { 3873 unsigned Opc = MI.getOpcode(); 3874 assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR); 3875 Register X = MI.getOperand(1).getReg(); 3876 Register Y = MI.getOperand(2).getReg(); 3877 if (X != Y) 3878 return false; 3879 unsigned RotateOpc = 3880 Opc == TargetOpcode::G_FSHL ? TargetOpcode::G_ROTL : TargetOpcode::G_ROTR; 3881 return isLegalOrBeforeLegalizer({RotateOpc, {MRI.getType(X), MRI.getType(Y)}}); 3882 } 3883 3884 void CombinerHelper::applyFunnelShiftToRotate(MachineInstr &MI) { 3885 unsigned Opc = MI.getOpcode(); 3886 assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR); 3887 bool IsFSHL = Opc == TargetOpcode::G_FSHL; 3888 Observer.changingInstr(MI); 3889 MI.setDesc(Builder.getTII().get(IsFSHL ? TargetOpcode::G_ROTL 3890 : TargetOpcode::G_ROTR)); 3891 MI.RemoveOperand(2); 3892 Observer.changedInstr(MI); 3893 } 3894 3895 // Fold (rot x, c) -> (rot x, c % BitSize) 3896 bool CombinerHelper::matchRotateOutOfRange(MachineInstr &MI) { 3897 assert(MI.getOpcode() == TargetOpcode::G_ROTL || 3898 MI.getOpcode() == TargetOpcode::G_ROTR); 3899 unsigned Bitsize = 3900 MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits(); 3901 Register AmtReg = MI.getOperand(2).getReg(); 3902 bool OutOfRange = false; 3903 auto MatchOutOfRange = [Bitsize, &OutOfRange](const Constant *C) { 3904 if (auto *CI = dyn_cast<ConstantInt>(C)) 3905 OutOfRange |= CI->getValue().uge(Bitsize); 3906 return true; 3907 }; 3908 return matchUnaryPredicate(MRI, AmtReg, MatchOutOfRange) && OutOfRange; 3909 } 3910 3911 void CombinerHelper::applyRotateOutOfRange(MachineInstr &MI) { 3912 assert(MI.getOpcode() == TargetOpcode::G_ROTL || 3913 MI.getOpcode() == TargetOpcode::G_ROTR); 3914 unsigned Bitsize = 3915 MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits(); 3916 Builder.setInstrAndDebugLoc(MI); 3917 Register Amt = MI.getOperand(2).getReg(); 3918 LLT AmtTy = MRI.getType(Amt); 3919 auto Bits = Builder.buildConstant(AmtTy, Bitsize); 3920 Amt = Builder.buildURem(AmtTy, MI.getOperand(2).getReg(), Bits).getReg(0); 3921 Observer.changingInstr(MI); 3922 MI.getOperand(2).setReg(Amt); 3923 Observer.changedInstr(MI); 3924 } 3925 3926 bool CombinerHelper::tryCombine(MachineInstr &MI) { 3927 if (tryCombineCopy(MI)) 3928 return true; 3929 if (tryCombineExtendingLoads(MI)) 3930 return true; 3931 if (tryCombineIndexedLoadStore(MI)) 3932 return true; 3933 return false; 3934 } 3935