1 //===- MachineCSE.cpp - Machine Common Subexpression Elimination Pass -----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass performs global common subexpression elimination on machine 10 // instructions using a scoped hash table based value numbering scheme. It 11 // must be run while the machine function is still in SSA form. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/ScopedHashTable.h" 17 #include "llvm/ADT/SmallPtrSet.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/AliasAnalysis.h" 22 #include "llvm/Analysis/CFG.h" 23 #include "llvm/CodeGen/MachineBasicBlock.h" 24 #include "llvm/CodeGen/MachineDominators.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineFunctionPass.h" 27 #include "llvm/CodeGen/MachineInstr.h" 28 #include "llvm/CodeGen/MachineOperand.h" 29 #include "llvm/CodeGen/MachineRegisterInfo.h" 30 #include "llvm/CodeGen/Passes.h" 31 #include "llvm/CodeGen/TargetInstrInfo.h" 32 #include "llvm/CodeGen/TargetOpcodes.h" 33 #include "llvm/CodeGen/TargetRegisterInfo.h" 34 #include "llvm/CodeGen/TargetSubtargetInfo.h" 35 #include "llvm/MC/MCInstrDesc.h" 36 #include "llvm/MC/MCRegisterInfo.h" 37 #include "llvm/Pass.h" 38 #include "llvm/Support/Allocator.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Support/RecyclingAllocator.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include <cassert> 43 #include <iterator> 44 #include <utility> 45 #include <vector> 46 47 using namespace llvm; 48 49 #define DEBUG_TYPE "machine-cse" 50 51 STATISTIC(NumCoalesces, "Number of copies coalesced"); 52 STATISTIC(NumCSEs, "Number of common subexpression eliminated"); 53 STATISTIC(NumPREs, "Number of partial redundant expression" 54 " transformed to fully redundant"); 55 STATISTIC(NumPhysCSEs, 56 "Number of physreg referencing common subexpr eliminated"); 57 STATISTIC(NumCrossBBCSEs, 58 "Number of cross-MBB physreg referencing CS eliminated"); 59 STATISTIC(NumCommutes, "Number of copies coalesced after commuting"); 60 61 namespace { 62 63 class MachineCSE : public MachineFunctionPass { 64 const TargetInstrInfo *TII; 65 const TargetRegisterInfo *TRI; 66 AliasAnalysis *AA; 67 MachineDominatorTree *DT; 68 MachineRegisterInfo *MRI; 69 70 public: 71 static char ID; // Pass identification 72 73 MachineCSE() : MachineFunctionPass(ID) { 74 initializeMachineCSEPass(*PassRegistry::getPassRegistry()); 75 } 76 77 bool runOnMachineFunction(MachineFunction &MF) override; 78 79 void getAnalysisUsage(AnalysisUsage &AU) const override { 80 AU.setPreservesCFG(); 81 MachineFunctionPass::getAnalysisUsage(AU); 82 AU.addRequired<AAResultsWrapperPass>(); 83 AU.addPreservedID(MachineLoopInfoID); 84 AU.addRequired<MachineDominatorTree>(); 85 AU.addPreserved<MachineDominatorTree>(); 86 } 87 88 void releaseMemory() override { 89 ScopeMap.clear(); 90 PREMap.clear(); 91 Exps.clear(); 92 } 93 94 private: 95 using AllocatorTy = RecyclingAllocator<BumpPtrAllocator, 96 ScopedHashTableVal<MachineInstr *, unsigned>>; 97 using ScopedHTType = 98 ScopedHashTable<MachineInstr *, unsigned, MachineInstrExpressionTrait, 99 AllocatorTy>; 100 using ScopeType = ScopedHTType::ScopeTy; 101 using PhysDefVector = SmallVector<std::pair<unsigned, unsigned>, 2>; 102 103 unsigned LookAheadLimit = 0; 104 DenseMap<MachineBasicBlock *, ScopeType *> ScopeMap; 105 DenseMap<MachineInstr *, MachineBasicBlock *, MachineInstrExpressionTrait> 106 PREMap; 107 ScopedHTType VNT; 108 SmallVector<MachineInstr *, 64> Exps; 109 unsigned CurrVN = 0; 110 111 bool PerformTrivialCopyPropagation(MachineInstr *MI, 112 MachineBasicBlock *MBB); 113 bool isPhysDefTriviallyDead(unsigned Reg, 114 MachineBasicBlock::const_iterator I, 115 MachineBasicBlock::const_iterator E) const; 116 bool hasLivePhysRegDefUses(const MachineInstr *MI, 117 const MachineBasicBlock *MBB, 118 SmallSet<unsigned, 8> &PhysRefs, 119 PhysDefVector &PhysDefs, bool &PhysUseDef) const; 120 bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI, 121 SmallSet<unsigned, 8> &PhysRefs, 122 PhysDefVector &PhysDefs, bool &NonLocal) const; 123 bool isCSECandidate(MachineInstr *MI); 124 bool isProfitableToCSE(unsigned CSReg, unsigned Reg, 125 MachineBasicBlock *CSBB, MachineInstr *MI); 126 void EnterScope(MachineBasicBlock *MBB); 127 void ExitScope(MachineBasicBlock *MBB); 128 bool ProcessBlockCSE(MachineBasicBlock *MBB); 129 void ExitScopeIfDone(MachineDomTreeNode *Node, 130 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren); 131 bool PerformCSE(MachineDomTreeNode *Node); 132 133 bool isPRECandidate(MachineInstr *MI); 134 bool ProcessBlockPRE(MachineDominatorTree *MDT, MachineBasicBlock *MBB); 135 bool PerformSimplePRE(MachineDominatorTree *DT); 136 }; 137 138 } // end anonymous namespace 139 140 char MachineCSE::ID = 0; 141 142 char &llvm::MachineCSEID = MachineCSE::ID; 143 144 INITIALIZE_PASS_BEGIN(MachineCSE, DEBUG_TYPE, 145 "Machine Common Subexpression Elimination", false, false) 146 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 147 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 148 INITIALIZE_PASS_END(MachineCSE, DEBUG_TYPE, 149 "Machine Common Subexpression Elimination", false, false) 150 151 /// The source register of a COPY machine instruction can be propagated to all 152 /// its users, and this propagation could increase the probability of finding 153 /// common subexpressions. If the COPY has only one user, the COPY itself can 154 /// be removed. 155 bool MachineCSE::PerformTrivialCopyPropagation(MachineInstr *MI, 156 MachineBasicBlock *MBB) { 157 bool Changed = false; 158 for (MachineOperand &MO : MI->operands()) { 159 if (!MO.isReg() || !MO.isUse()) 160 continue; 161 unsigned Reg = MO.getReg(); 162 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 163 continue; 164 bool OnlyOneUse = MRI->hasOneNonDBGUse(Reg); 165 MachineInstr *DefMI = MRI->getVRegDef(Reg); 166 if (!DefMI->isCopy()) 167 continue; 168 unsigned SrcReg = DefMI->getOperand(1).getReg(); 169 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) 170 continue; 171 if (DefMI->getOperand(0).getSubReg()) 172 continue; 173 // FIXME: We should trivially coalesce subregister copies to expose CSE 174 // opportunities on instructions with truncated operands (see 175 // cse-add-with-overflow.ll). This can be done here as follows: 176 // if (SrcSubReg) 177 // RC = TRI->getMatchingSuperRegClass(MRI->getRegClass(SrcReg), RC, 178 // SrcSubReg); 179 // MO.substVirtReg(SrcReg, SrcSubReg, *TRI); 180 // 181 // The 2-addr pass has been updated to handle coalesced subregs. However, 182 // some machine-specific code still can't handle it. 183 // To handle it properly we also need a way find a constrained subregister 184 // class given a super-reg class and subreg index. 185 if (DefMI->getOperand(1).getSubReg()) 186 continue; 187 if (!MRI->constrainRegAttrs(SrcReg, Reg)) 188 continue; 189 LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI); 190 LLVM_DEBUG(dbgs() << "*** to: " << *MI); 191 192 // Update matching debug values. 193 DefMI->changeDebugValuesDefReg(SrcReg); 194 195 // Propagate SrcReg of copies to MI. 196 MO.setReg(SrcReg); 197 MRI->clearKillFlags(SrcReg); 198 // Coalesce single use copies. 199 if (OnlyOneUse) { 200 DefMI->eraseFromParent(); 201 ++NumCoalesces; 202 } 203 Changed = true; 204 } 205 206 return Changed; 207 } 208 209 bool 210 MachineCSE::isPhysDefTriviallyDead(unsigned Reg, 211 MachineBasicBlock::const_iterator I, 212 MachineBasicBlock::const_iterator E) const { 213 unsigned LookAheadLeft = LookAheadLimit; 214 while (LookAheadLeft) { 215 // Skip over dbg_value's. 216 I = skipDebugInstructionsForward(I, E); 217 218 if (I == E) 219 // Reached end of block, we don't know if register is dead or not. 220 return false; 221 222 bool SeenDef = false; 223 for (const MachineOperand &MO : I->operands()) { 224 if (MO.isRegMask() && MO.clobbersPhysReg(Reg)) 225 SeenDef = true; 226 if (!MO.isReg() || !MO.getReg()) 227 continue; 228 if (!TRI->regsOverlap(MO.getReg(), Reg)) 229 continue; 230 if (MO.isUse()) 231 // Found a use! 232 return false; 233 SeenDef = true; 234 } 235 if (SeenDef) 236 // See a def of Reg (or an alias) before encountering any use, it's 237 // trivially dead. 238 return true; 239 240 --LookAheadLeft; 241 ++I; 242 } 243 return false; 244 } 245 246 static bool isCallerPreservedOrConstPhysReg(unsigned Reg, 247 const MachineFunction &MF, 248 const TargetRegisterInfo &TRI) { 249 // MachineRegisterInfo::isConstantPhysReg directly called by 250 // MachineRegisterInfo::isCallerPreservedOrConstPhysReg expects the 251 // reserved registers to be frozen. That doesn't cause a problem post-ISel as 252 // most (if not all) targets freeze reserved registers right after ISel. 253 // 254 // It does cause issues mid-GlobalISel, however, hence the additional 255 // reservedRegsFrozen check. 256 const MachineRegisterInfo &MRI = MF.getRegInfo(); 257 return TRI.isCallerPreservedPhysReg(Reg, MF) || 258 (MRI.reservedRegsFrozen() && MRI.isConstantPhysReg(Reg)); 259 } 260 261 /// hasLivePhysRegDefUses - Return true if the specified instruction read/write 262 /// physical registers (except for dead defs of physical registers). It also 263 /// returns the physical register def by reference if it's the only one and the 264 /// instruction does not uses a physical register. 265 bool MachineCSE::hasLivePhysRegDefUses(const MachineInstr *MI, 266 const MachineBasicBlock *MBB, 267 SmallSet<unsigned, 8> &PhysRefs, 268 PhysDefVector &PhysDefs, 269 bool &PhysUseDef) const { 270 // First, add all uses to PhysRefs. 271 for (const MachineOperand &MO : MI->operands()) { 272 if (!MO.isReg() || MO.isDef()) 273 continue; 274 unsigned Reg = MO.getReg(); 275 if (!Reg) 276 continue; 277 if (TargetRegisterInfo::isVirtualRegister(Reg)) 278 continue; 279 // Reading either caller preserved or constant physregs is ok. 280 if (!isCallerPreservedOrConstPhysReg(Reg, *MI->getMF(), *TRI)) 281 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) 282 PhysRefs.insert(*AI); 283 } 284 285 // Next, collect all defs into PhysDefs. If any is already in PhysRefs 286 // (which currently contains only uses), set the PhysUseDef flag. 287 PhysUseDef = false; 288 MachineBasicBlock::const_iterator I = MI; I = std::next(I); 289 for (const auto &MOP : llvm::enumerate(MI->operands())) { 290 const MachineOperand &MO = MOP.value(); 291 if (!MO.isReg() || !MO.isDef()) 292 continue; 293 unsigned Reg = MO.getReg(); 294 if (!Reg) 295 continue; 296 if (TargetRegisterInfo::isVirtualRegister(Reg)) 297 continue; 298 // Check against PhysRefs even if the def is "dead". 299 if (PhysRefs.count(Reg)) 300 PhysUseDef = true; 301 // If the def is dead, it's ok. But the def may not marked "dead". That's 302 // common since this pass is run before livevariables. We can scan 303 // forward a few instructions and check if it is obviously dead. 304 if (!MO.isDead() && !isPhysDefTriviallyDead(Reg, I, MBB->end())) 305 PhysDefs.push_back(std::make_pair(MOP.index(), Reg)); 306 } 307 308 // Finally, add all defs to PhysRefs as well. 309 for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) 310 for (MCRegAliasIterator AI(PhysDefs[i].second, TRI, true); AI.isValid(); 311 ++AI) 312 PhysRefs.insert(*AI); 313 314 return !PhysRefs.empty(); 315 } 316 317 bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI, 318 SmallSet<unsigned, 8> &PhysRefs, 319 PhysDefVector &PhysDefs, 320 bool &NonLocal) const { 321 // For now conservatively returns false if the common subexpression is 322 // not in the same basic block as the given instruction. The only exception 323 // is if the common subexpression is in the sole predecessor block. 324 const MachineBasicBlock *MBB = MI->getParent(); 325 const MachineBasicBlock *CSMBB = CSMI->getParent(); 326 327 bool CrossMBB = false; 328 if (CSMBB != MBB) { 329 if (MBB->pred_size() != 1 || *MBB->pred_begin() != CSMBB) 330 return false; 331 332 for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) { 333 if (MRI->isAllocatable(PhysDefs[i].second) || 334 MRI->isReserved(PhysDefs[i].second)) 335 // Avoid extending live range of physical registers if they are 336 //allocatable or reserved. 337 return false; 338 } 339 CrossMBB = true; 340 } 341 MachineBasicBlock::const_iterator I = CSMI; I = std::next(I); 342 MachineBasicBlock::const_iterator E = MI; 343 MachineBasicBlock::const_iterator EE = CSMBB->end(); 344 unsigned LookAheadLeft = LookAheadLimit; 345 while (LookAheadLeft) { 346 // Skip over dbg_value's. 347 while (I != E && I != EE && I->isDebugInstr()) 348 ++I; 349 350 if (I == EE) { 351 assert(CrossMBB && "Reaching end-of-MBB without finding MI?"); 352 (void)CrossMBB; 353 CrossMBB = false; 354 NonLocal = true; 355 I = MBB->begin(); 356 EE = MBB->end(); 357 continue; 358 } 359 360 if (I == E) 361 return true; 362 363 for (const MachineOperand &MO : I->operands()) { 364 // RegMasks go on instructions like calls that clobber lots of physregs. 365 // Don't attempt to CSE across such an instruction. 366 if (MO.isRegMask()) 367 return false; 368 if (!MO.isReg() || !MO.isDef()) 369 continue; 370 unsigned MOReg = MO.getReg(); 371 if (TargetRegisterInfo::isVirtualRegister(MOReg)) 372 continue; 373 if (PhysRefs.count(MOReg)) 374 return false; 375 } 376 377 --LookAheadLeft; 378 ++I; 379 } 380 381 return false; 382 } 383 384 bool MachineCSE::isCSECandidate(MachineInstr *MI) { 385 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() || MI->isKill() || 386 MI->isInlineAsm() || MI->isDebugInstr()) 387 return false; 388 389 // Ignore copies. 390 if (MI->isCopyLike()) 391 return false; 392 393 // Ignore stuff that we obviously can't move. 394 if (MI->mayStore() || MI->isCall() || MI->isTerminator() || 395 MI->mayRaiseFPException() || MI->hasUnmodeledSideEffects()) 396 return false; 397 398 if (MI->mayLoad()) { 399 // Okay, this instruction does a load. As a refinement, we allow the target 400 // to decide whether the loaded value is actually a constant. If so, we can 401 // actually use it as a load. 402 if (!MI->isDereferenceableInvariantLoad(AA)) 403 // FIXME: we should be able to hoist loads with no other side effects if 404 // there are no other instructions which can change memory in this loop. 405 // This is a trivial form of alias analysis. 406 return false; 407 } 408 409 // Ignore stack guard loads, otherwise the register that holds CSEed value may 410 // be spilled and get loaded back with corrupted data. 411 if (MI->getOpcode() == TargetOpcode::LOAD_STACK_GUARD) 412 return false; 413 414 return true; 415 } 416 417 /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a 418 /// common expression that defines Reg. CSBB is basic block where CSReg is 419 /// defined. 420 bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg, 421 MachineBasicBlock *CSBB, MachineInstr *MI) { 422 // FIXME: Heuristics that works around the lack the live range splitting. 423 424 // If CSReg is used at all uses of Reg, CSE should not increase register 425 // pressure of CSReg. 426 bool MayIncreasePressure = true; 427 if (TargetRegisterInfo::isVirtualRegister(CSReg) && 428 TargetRegisterInfo::isVirtualRegister(Reg)) { 429 MayIncreasePressure = false; 430 SmallPtrSet<MachineInstr*, 8> CSUses; 431 for (MachineInstr &MI : MRI->use_nodbg_instructions(CSReg)) { 432 CSUses.insert(&MI); 433 } 434 for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) { 435 if (!CSUses.count(&MI)) { 436 MayIncreasePressure = true; 437 break; 438 } 439 } 440 } 441 if (!MayIncreasePressure) return true; 442 443 // Heuristics #1: Don't CSE "cheap" computation if the def is not local or in 444 // an immediate predecessor. We don't want to increase register pressure and 445 // end up causing other computation to be spilled. 446 if (TII->isAsCheapAsAMove(*MI)) { 447 MachineBasicBlock *BB = MI->getParent(); 448 if (CSBB != BB && !CSBB->isSuccessor(BB)) 449 return false; 450 } 451 452 // Heuristics #2: If the expression doesn't not use a vr and the only use 453 // of the redundant computation are copies, do not cse. 454 bool HasVRegUse = false; 455 for (const MachineOperand &MO : MI->operands()) { 456 if (MO.isReg() && MO.isUse() && 457 TargetRegisterInfo::isVirtualRegister(MO.getReg())) { 458 HasVRegUse = true; 459 break; 460 } 461 } 462 if (!HasVRegUse) { 463 bool HasNonCopyUse = false; 464 for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) { 465 // Ignore copies. 466 if (!MI.isCopyLike()) { 467 HasNonCopyUse = true; 468 break; 469 } 470 } 471 if (!HasNonCopyUse) 472 return false; 473 } 474 475 // Heuristics #3: If the common subexpression is used by PHIs, do not reuse 476 // it unless the defined value is already used in the BB of the new use. 477 bool HasPHI = false; 478 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(CSReg)) { 479 HasPHI |= UseMI.isPHI(); 480 if (UseMI.getParent() == MI->getParent()) 481 return true; 482 } 483 484 return !HasPHI; 485 } 486 487 void MachineCSE::EnterScope(MachineBasicBlock *MBB) { 488 LLVM_DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n'); 489 ScopeType *Scope = new ScopeType(VNT); 490 ScopeMap[MBB] = Scope; 491 } 492 493 void MachineCSE::ExitScope(MachineBasicBlock *MBB) { 494 LLVM_DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n'); 495 DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB); 496 assert(SI != ScopeMap.end()); 497 delete SI->second; 498 ScopeMap.erase(SI); 499 } 500 501 bool MachineCSE::ProcessBlockCSE(MachineBasicBlock *MBB) { 502 bool Changed = false; 503 504 SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs; 505 SmallVector<unsigned, 2> ImplicitDefsToUpdate; 506 SmallVector<unsigned, 2> ImplicitDefs; 507 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) { 508 MachineInstr *MI = &*I; 509 ++I; 510 511 if (!isCSECandidate(MI)) 512 continue; 513 514 bool FoundCSE = VNT.count(MI); 515 if (!FoundCSE) { 516 // Using trivial copy propagation to find more CSE opportunities. 517 if (PerformTrivialCopyPropagation(MI, MBB)) { 518 Changed = true; 519 520 // After coalescing MI itself may become a copy. 521 if (MI->isCopyLike()) 522 continue; 523 524 // Try again to see if CSE is possible. 525 FoundCSE = VNT.count(MI); 526 } 527 } 528 529 // Commute commutable instructions. 530 bool Commuted = false; 531 if (!FoundCSE && MI->isCommutable()) { 532 if (MachineInstr *NewMI = TII->commuteInstruction(*MI)) { 533 Commuted = true; 534 FoundCSE = VNT.count(NewMI); 535 if (NewMI != MI) { 536 // New instruction. It doesn't need to be kept. 537 NewMI->eraseFromParent(); 538 Changed = true; 539 } else if (!FoundCSE) 540 // MI was changed but it didn't help, commute it back! 541 (void)TII->commuteInstruction(*MI); 542 } 543 } 544 545 // If the instruction defines physical registers and the values *may* be 546 // used, then it's not safe to replace it with a common subexpression. 547 // It's also not safe if the instruction uses physical registers. 548 bool CrossMBBPhysDef = false; 549 SmallSet<unsigned, 8> PhysRefs; 550 PhysDefVector PhysDefs; 551 bool PhysUseDef = false; 552 if (FoundCSE && hasLivePhysRegDefUses(MI, MBB, PhysRefs, 553 PhysDefs, PhysUseDef)) { 554 FoundCSE = false; 555 556 // ... Unless the CS is local or is in the sole predecessor block 557 // and it also defines the physical register which is not clobbered 558 // in between and the physical register uses were not clobbered. 559 // This can never be the case if the instruction both uses and 560 // defines the same physical register, which was detected above. 561 if (!PhysUseDef) { 562 unsigned CSVN = VNT.lookup(MI); 563 MachineInstr *CSMI = Exps[CSVN]; 564 if (PhysRegDefsReach(CSMI, MI, PhysRefs, PhysDefs, CrossMBBPhysDef)) 565 FoundCSE = true; 566 } 567 } 568 569 if (!FoundCSE) { 570 VNT.insert(MI, CurrVN++); 571 Exps.push_back(MI); 572 continue; 573 } 574 575 // Found a common subexpression, eliminate it. 576 unsigned CSVN = VNT.lookup(MI); 577 MachineInstr *CSMI = Exps[CSVN]; 578 LLVM_DEBUG(dbgs() << "Examining: " << *MI); 579 LLVM_DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI); 580 581 // Check if it's profitable to perform this CSE. 582 bool DoCSE = true; 583 unsigned NumDefs = MI->getNumDefs(); 584 585 for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) { 586 MachineOperand &MO = MI->getOperand(i); 587 if (!MO.isReg() || !MO.isDef()) 588 continue; 589 unsigned OldReg = MO.getReg(); 590 unsigned NewReg = CSMI->getOperand(i).getReg(); 591 592 // Go through implicit defs of CSMI and MI, if a def is not dead at MI, 593 // we should make sure it is not dead at CSMI. 594 if (MO.isImplicit() && !MO.isDead() && CSMI->getOperand(i).isDead()) 595 ImplicitDefsToUpdate.push_back(i); 596 597 // Keep track of implicit defs of CSMI and MI, to clear possibly 598 // made-redundant kill flags. 599 if (MO.isImplicit() && !MO.isDead() && OldReg == NewReg) 600 ImplicitDefs.push_back(OldReg); 601 602 if (OldReg == NewReg) { 603 --NumDefs; 604 continue; 605 } 606 607 assert(TargetRegisterInfo::isVirtualRegister(OldReg) && 608 TargetRegisterInfo::isVirtualRegister(NewReg) && 609 "Do not CSE physical register defs!"); 610 611 if (!isProfitableToCSE(NewReg, OldReg, CSMI->getParent(), MI)) { 612 LLVM_DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n"); 613 DoCSE = false; 614 break; 615 } 616 617 // Don't perform CSE if the result of the new instruction cannot exist 618 // within the constraints (register class, bank, or low-level type) of 619 // the old instruction. 620 if (!MRI->constrainRegAttrs(NewReg, OldReg)) { 621 LLVM_DEBUG( 622 dbgs() << "*** Not the same register constraints, avoid CSE!\n"); 623 DoCSE = false; 624 break; 625 } 626 627 CSEPairs.push_back(std::make_pair(OldReg, NewReg)); 628 --NumDefs; 629 } 630 631 // Actually perform the elimination. 632 if (DoCSE) { 633 for (std::pair<unsigned, unsigned> &CSEPair : CSEPairs) { 634 unsigned OldReg = CSEPair.first; 635 unsigned NewReg = CSEPair.second; 636 // OldReg may have been unused but is used now, clear the Dead flag 637 MachineInstr *Def = MRI->getUniqueVRegDef(NewReg); 638 assert(Def != nullptr && "CSEd register has no unique definition?"); 639 Def->clearRegisterDeads(NewReg); 640 // Replace with NewReg and clear kill flags which may be wrong now. 641 MRI->replaceRegWith(OldReg, NewReg); 642 MRI->clearKillFlags(NewReg); 643 } 644 645 // Go through implicit defs of CSMI and MI, if a def is not dead at MI, 646 // we should make sure it is not dead at CSMI. 647 for (unsigned ImplicitDefToUpdate : ImplicitDefsToUpdate) 648 CSMI->getOperand(ImplicitDefToUpdate).setIsDead(false); 649 for (auto PhysDef : PhysDefs) 650 if (!MI->getOperand(PhysDef.first).isDead()) 651 CSMI->getOperand(PhysDef.first).setIsDead(false); 652 653 // Go through implicit defs of CSMI and MI, and clear the kill flags on 654 // their uses in all the instructions between CSMI and MI. 655 // We might have made some of the kill flags redundant, consider: 656 // subs ... implicit-def %nzcv <- CSMI 657 // csinc ... implicit killed %nzcv <- this kill flag isn't valid anymore 658 // subs ... implicit-def %nzcv <- MI, to be eliminated 659 // csinc ... implicit killed %nzcv 660 // Since we eliminated MI, and reused a register imp-def'd by CSMI 661 // (here %nzcv), that register, if it was killed before MI, should have 662 // that kill flag removed, because it's lifetime was extended. 663 if (CSMI->getParent() == MI->getParent()) { 664 for (MachineBasicBlock::iterator II = CSMI, IE = MI; II != IE; ++II) 665 for (auto ImplicitDef : ImplicitDefs) 666 if (MachineOperand *MO = II->findRegisterUseOperand( 667 ImplicitDef, /*isKill=*/true, TRI)) 668 MO->setIsKill(false); 669 } else { 670 // If the instructions aren't in the same BB, bail out and clear the 671 // kill flag on all uses of the imp-def'd register. 672 for (auto ImplicitDef : ImplicitDefs) 673 MRI->clearKillFlags(ImplicitDef); 674 } 675 676 if (CrossMBBPhysDef) { 677 // Add physical register defs now coming in from a predecessor to MBB 678 // livein list. 679 while (!PhysDefs.empty()) { 680 auto LiveIn = PhysDefs.pop_back_val(); 681 if (!MBB->isLiveIn(LiveIn.second)) 682 MBB->addLiveIn(LiveIn.second); 683 } 684 ++NumCrossBBCSEs; 685 } 686 687 MI->eraseFromParent(); 688 ++NumCSEs; 689 if (!PhysRefs.empty()) 690 ++NumPhysCSEs; 691 if (Commuted) 692 ++NumCommutes; 693 Changed = true; 694 } else { 695 VNT.insert(MI, CurrVN++); 696 Exps.push_back(MI); 697 } 698 CSEPairs.clear(); 699 ImplicitDefsToUpdate.clear(); 700 ImplicitDefs.clear(); 701 } 702 703 return Changed; 704 } 705 706 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given 707 /// dominator tree node if its a leaf or all of its children are done. Walk 708 /// up the dominator tree to destroy ancestors which are now done. 709 void 710 MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node, 711 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren) { 712 if (OpenChildren[Node]) 713 return; 714 715 // Pop scope. 716 ExitScope(Node->getBlock()); 717 718 // Now traverse upwards to pop ancestors whose offsprings are all done. 719 while (MachineDomTreeNode *Parent = Node->getIDom()) { 720 unsigned Left = --OpenChildren[Parent]; 721 if (Left != 0) 722 break; 723 ExitScope(Parent->getBlock()); 724 Node = Parent; 725 } 726 } 727 728 bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) { 729 SmallVector<MachineDomTreeNode*, 32> Scopes; 730 SmallVector<MachineDomTreeNode*, 8> WorkList; 731 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren; 732 733 CurrVN = 0; 734 735 // Perform a DFS walk to determine the order of visit. 736 WorkList.push_back(Node); 737 do { 738 Node = WorkList.pop_back_val(); 739 Scopes.push_back(Node); 740 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren(); 741 OpenChildren[Node] = Children.size(); 742 for (MachineDomTreeNode *Child : Children) 743 WorkList.push_back(Child); 744 } while (!WorkList.empty()); 745 746 // Now perform CSE. 747 bool Changed = false; 748 for (MachineDomTreeNode *Node : Scopes) { 749 MachineBasicBlock *MBB = Node->getBlock(); 750 EnterScope(MBB); 751 Changed |= ProcessBlockCSE(MBB); 752 // If it's a leaf node, it's done. Traverse upwards to pop ancestors. 753 ExitScopeIfDone(Node, OpenChildren); 754 } 755 756 return Changed; 757 } 758 759 // We use stronger checks for PRE candidate rather than for CSE ones to embrace 760 // checks inside ProcessBlockCSE(), not only inside isCSECandidate(). This helps 761 // to exclude instrs created by PRE that won't be CSEed later. 762 bool MachineCSE::isPRECandidate(MachineInstr *MI) { 763 if (!isCSECandidate(MI) || 764 MI->isNotDuplicable() || 765 MI->mayLoad() || 766 MI->isAsCheapAsAMove() || 767 MI->getNumDefs() != 1 || 768 MI->getNumExplicitDefs() != 1) 769 return false; 770 771 for (auto def : MI->defs()) 772 if (!TRI->isVirtualRegister(def.getReg())) 773 return false; 774 775 for (auto use : MI->uses()) 776 if (use.isReg() && !TRI->isVirtualRegister(use.getReg())) 777 return false; 778 779 return true; 780 } 781 782 bool MachineCSE::ProcessBlockPRE(MachineDominatorTree *DT, 783 MachineBasicBlock *MBB) { 784 bool Changed = false; 785 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;) { 786 MachineInstr *MI = &*I; 787 ++I; 788 789 if (!isPRECandidate(MI)) 790 continue; 791 792 if (!PREMap.count(MI)) { 793 PREMap[MI] = MBB; 794 continue; 795 } 796 797 auto MBB1 = PREMap[MI]; 798 assert( 799 !DT->properlyDominates(MBB, MBB1) && 800 "MBB cannot properly dominate MBB1 while DFS through dominators tree!"); 801 auto CMBB = DT->findNearestCommonDominator(MBB, MBB1); 802 803 // Two instrs are partial redundant if their basic blocks are reachable 804 // from one to another but one doesn't dominate another. 805 if (CMBB != MBB1) { 806 auto BB = MBB->getBasicBlock(), BB1 = MBB1->getBasicBlock(); 807 if (BB != nullptr && BB1 != nullptr && 808 (isPotentiallyReachable(BB1, BB) || 809 isPotentiallyReachable(BB, BB1))) { 810 811 assert(MI->getOperand(0).isDef() && 812 "First operand of instr with one explicit def must be this def"); 813 unsigned VReg = MI->getOperand(0).getReg(); 814 unsigned NewReg = MRI->cloneVirtualRegister(VReg); 815 if (!isProfitableToCSE(NewReg, VReg, CMBB, MI)) 816 continue; 817 MachineInstr &NewMI = 818 TII->duplicate(*CMBB, CMBB->getFirstTerminator(), *MI); 819 NewMI.getOperand(0).setReg(NewReg); 820 821 PREMap[MI] = CMBB; 822 ++NumPREs; 823 Changed = true; 824 } 825 } 826 } 827 return Changed; 828 } 829 830 // This simple PRE (partial redundancy elimination) pass doesn't actually 831 // eliminate partial redundancy but transforms it to full redundancy, 832 // anticipating that the next CSE step will eliminate this created redundancy. 833 // If CSE doesn't eliminate this, than created instruction will remain dead 834 // and eliminated later by Remove Dead Machine Instructions pass. 835 bool MachineCSE::PerformSimplePRE(MachineDominatorTree *DT) { 836 SmallVector<MachineDomTreeNode *, 32> BBs; 837 838 PREMap.clear(); 839 bool Changed = false; 840 BBs.push_back(DT->getRootNode()); 841 do { 842 auto Node = BBs.pop_back_val(); 843 const std::vector<MachineDomTreeNode *> &Children = Node->getChildren(); 844 for (MachineDomTreeNode *Child : Children) 845 BBs.push_back(Child); 846 847 MachineBasicBlock *MBB = Node->getBlock(); 848 Changed |= ProcessBlockPRE(DT, MBB); 849 850 } while (!BBs.empty()); 851 852 return Changed; 853 } 854 855 bool MachineCSE::runOnMachineFunction(MachineFunction &MF) { 856 if (skipFunction(MF.getFunction())) 857 return false; 858 859 TII = MF.getSubtarget().getInstrInfo(); 860 TRI = MF.getSubtarget().getRegisterInfo(); 861 MRI = &MF.getRegInfo(); 862 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 863 DT = &getAnalysis<MachineDominatorTree>(); 864 LookAheadLimit = TII->getMachineCSELookAheadLimit(); 865 bool ChangedPRE, ChangedCSE; 866 ChangedPRE = PerformSimplePRE(DT); 867 ChangedCSE = PerformCSE(DT->getRootNode()); 868 return ChangedPRE || ChangedCSE; 869 } 870