1 //===- CriticalAntiDepBreaker.cpp - Anti-dep breaker ----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the CriticalAntiDepBreaker class, which 10 // implements register anti-dependence breaking along a blocks 11 // critical path during post-RA scheduler. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "CriticalAntiDepBreaker.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/CodeGen/MachineBasicBlock.h" 20 #include "llvm/CodeGen/MachineFrameInfo.h" 21 #include "llvm/CodeGen/MachineFunction.h" 22 #include "llvm/CodeGen/MachineInstr.h" 23 #include "llvm/CodeGen/MachineOperand.h" 24 #include "llvm/CodeGen/MachineRegisterInfo.h" 25 #include "llvm/CodeGen/RegisterClassInfo.h" 26 #include "llvm/CodeGen/ScheduleDAG.h" 27 #include "llvm/CodeGen/TargetInstrInfo.h" 28 #include "llvm/CodeGen/TargetRegisterInfo.h" 29 #include "llvm/CodeGen/TargetSubtargetInfo.h" 30 #include "llvm/MC/MCInstrDesc.h" 31 #include "llvm/MC/MCRegisterInfo.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include <cassert> 35 #include <utility> 36 37 using namespace llvm; 38 39 #define DEBUG_TYPE "post-RA-sched" 40 41 CriticalAntiDepBreaker::CriticalAntiDepBreaker(MachineFunction &MFi, 42 const RegisterClassInfo &RCI) 43 : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()), 44 TII(MF.getSubtarget().getInstrInfo()), 45 TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI), 46 Classes(TRI->getNumRegs(), nullptr), KillIndices(TRI->getNumRegs(), 0), 47 DefIndices(TRI->getNumRegs(), 0), KeepRegs(TRI->getNumRegs(), false) {} 48 49 CriticalAntiDepBreaker::~CriticalAntiDepBreaker() = default; 50 51 void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) { 52 const unsigned BBSize = BB->size(); 53 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) { 54 // Clear out the register class data. 55 Classes[i] = nullptr; 56 57 // Initialize the indices to indicate that no registers are live. 58 KillIndices[i] = ~0u; 59 DefIndices[i] = BBSize; 60 } 61 62 // Clear "do not change" set. 63 KeepRegs.reset(); 64 65 bool IsReturnBlock = BB->isReturnBlock(); 66 67 // Examine the live-in regs of all successors. 68 for (const MachineBasicBlock *Succ : BB->successors()) 69 for (const auto &LI : Succ->liveins()) { 70 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI) { 71 unsigned Reg = *AI; 72 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 73 KillIndices[Reg] = BBSize; 74 DefIndices[Reg] = ~0u; 75 } 76 } 77 78 // Mark live-out callee-saved registers. In a return block this is 79 // all callee-saved registers. In non-return this is any 80 // callee-saved register that is not saved in the prolog. 81 const MachineFrameInfo &MFI = MF.getFrameInfo(); 82 BitVector Pristine = MFI.getPristineRegs(MF); 83 for (const MCPhysReg *I = MF.getRegInfo().getCalleeSavedRegs(); *I; 84 ++I) { 85 unsigned Reg = *I; 86 if (!IsReturnBlock && !Pristine.test(Reg)) 87 continue; 88 for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) { 89 unsigned Reg = *AI; 90 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 91 KillIndices[Reg] = BBSize; 92 DefIndices[Reg] = ~0u; 93 } 94 } 95 } 96 97 void CriticalAntiDepBreaker::FinishBlock() { 98 RegRefs.clear(); 99 KeepRegs.reset(); 100 } 101 102 void CriticalAntiDepBreaker::Observe(MachineInstr &MI, unsigned Count, 103 unsigned InsertPosIndex) { 104 // Kill instructions can define registers but are really nops, and there might 105 // be a real definition earlier that needs to be paired with uses dominated by 106 // this kill. 107 108 // FIXME: It may be possible to remove the isKill() restriction once PR18663 109 // has been properly fixed. There can be value in processing kills as seen in 110 // the AggressiveAntiDepBreaker class. 111 if (MI.isDebugInstr() || MI.isKill()) 112 return; 113 assert(Count < InsertPosIndex && "Instruction index out of expected range!"); 114 115 for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) { 116 if (KillIndices[Reg] != ~0u) { 117 // If Reg is currently live, then mark that it can't be renamed as 118 // we don't know the extent of its live-range anymore (now that it 119 // has been scheduled). 120 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 121 KillIndices[Reg] = Count; 122 } else if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) { 123 // Any register which was defined within the previous scheduling region 124 // may have been rescheduled and its lifetime may overlap with registers 125 // in ways not reflected in our current liveness state. For each such 126 // register, adjust the liveness state to be conservatively correct. 127 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 128 129 // Move the def index to the end of the previous region, to reflect 130 // that the def could theoretically have been scheduled at the end. 131 DefIndices[Reg] = InsertPosIndex; 132 } 133 } 134 135 PrescanInstruction(MI); 136 ScanInstruction(MI, Count); 137 } 138 139 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up 140 /// critical path. 141 static const SDep *CriticalPathStep(const SUnit *SU) { 142 const SDep *Next = nullptr; 143 unsigned NextDepth = 0; 144 // Find the predecessor edge with the greatest depth. 145 for (const SDep &P : SU->Preds) { 146 const SUnit *PredSU = P.getSUnit(); 147 unsigned PredLatency = P.getLatency(); 148 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency; 149 // In the case of a latency tie, prefer an anti-dependency edge over 150 // other types of edges. 151 if (NextDepth < PredTotalLatency || 152 (NextDepth == PredTotalLatency && P.getKind() == SDep::Anti)) { 153 NextDepth = PredTotalLatency; 154 Next = &P; 155 } 156 } 157 return Next; 158 } 159 160 void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr &MI) { 161 // It's not safe to change register allocation for source operands of 162 // instructions that have special allocation requirements. Also assume all 163 // registers used in a call must not be changed (ABI). 164 // FIXME: The issue with predicated instruction is more complex. We are being 165 // conservative here because the kill markers cannot be trusted after 166 // if-conversion: 167 // %r6 = LDR %sp, %reg0, 92, 14, %reg0; mem:LD4[FixedStack14] 168 // ... 169 // STR %r0, killed %r6, %reg0, 0, 0, %cpsr; mem:ST4[%395] 170 // %r6 = LDR %sp, %reg0, 100, 0, %cpsr; mem:LD4[FixedStack12] 171 // STR %r0, killed %r6, %reg0, 0, 14, %reg0; mem:ST4[%396](align=8) 172 // 173 // The first R6 kill is not really a kill since it's killed by a predicated 174 // instruction which may not be executed. The second R6 def may or may not 175 // re-define R6 so it's not safe to change it since the last R6 use cannot be 176 // changed. 177 bool Special = 178 MI.isCall() || MI.hasExtraSrcRegAllocReq() || TII->isPredicated(MI); 179 180 // Scan the register operands for this instruction and update 181 // Classes and RegRefs. 182 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 183 MachineOperand &MO = MI.getOperand(i); 184 if (!MO.isReg()) continue; 185 Register Reg = MO.getReg(); 186 if (Reg == 0) continue; 187 const TargetRegisterClass *NewRC = nullptr; 188 189 if (i < MI.getDesc().getNumOperands()) 190 NewRC = TII->getRegClass(MI.getDesc(), i, TRI, MF); 191 192 // For now, only allow the register to be changed if its register 193 // class is consistent across all uses. 194 if (!Classes[Reg] && NewRC) 195 Classes[Reg] = NewRC; 196 else if (!NewRC || Classes[Reg] != NewRC) 197 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 198 199 // Now check for aliases. 200 for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) { 201 // If an alias of the reg is used during the live range, give up. 202 // Note that this allows us to skip checking if AntiDepReg 203 // overlaps with any of the aliases, among other things. 204 unsigned AliasReg = *AI; 205 if (Classes[AliasReg]) { 206 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1); 207 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 208 } 209 } 210 211 // If we're still willing to consider this register, note the reference. 212 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1)) 213 RegRefs.insert(std::make_pair(Reg, &MO)); 214 215 if (MO.isUse() && Special) { 216 if (!KeepRegs.test(Reg)) { 217 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true); 218 SubRegs.isValid(); ++SubRegs) 219 KeepRegs.set(*SubRegs); 220 } 221 } 222 } 223 224 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) { 225 const MachineOperand &MO = MI.getOperand(I); 226 if (!MO.isReg()) continue; 227 Register Reg = MO.getReg(); 228 if (!Reg.isValid()) 229 continue; 230 // If this reg is tied and live (Classes[Reg] is set to -1), we can't change 231 // it or any of its sub or super regs. We need to use KeepRegs to mark the 232 // reg because not all uses of the same reg within an instruction are 233 // necessarily tagged as tied. 234 // Example: an x86 "xor %eax, %eax" will have one source operand tied to the 235 // def register but not the second (see PR20020 for details). 236 // FIXME: can this check be relaxed to account for undef uses 237 // of a register? In the above 'xor' example, the uses of %eax are undef, so 238 // earlier instructions could still replace %eax even though the 'xor' 239 // itself can't be changed. 240 if (MI.isRegTiedToUseOperand(I) && 241 Classes[Reg] == reinterpret_cast<TargetRegisterClass *>(-1)) { 242 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true); 243 SubRegs.isValid(); ++SubRegs) { 244 KeepRegs.set(*SubRegs); 245 } 246 for (MCSuperRegIterator SuperRegs(Reg, TRI); 247 SuperRegs.isValid(); ++SuperRegs) { 248 KeepRegs.set(*SuperRegs); 249 } 250 } 251 } 252 } 253 254 void CriticalAntiDepBreaker::ScanInstruction(MachineInstr &MI, unsigned Count) { 255 // Update liveness. 256 // Proceeding upwards, registers that are defed but not used in this 257 // instruction are now dead. 258 assert(!MI.isKill() && "Attempting to scan a kill instruction"); 259 260 if (!TII->isPredicated(MI)) { 261 // Predicated defs are modeled as read + write, i.e. similar to two 262 // address updates. 263 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 264 MachineOperand &MO = MI.getOperand(i); 265 266 if (MO.isRegMask()) { 267 auto ClobbersPhysRegAndSubRegs = [&](unsigned PhysReg) { 268 for (MCSubRegIterator SRI(PhysReg, TRI, true); SRI.isValid(); ++SRI) 269 if (!MO.clobbersPhysReg(*SRI)) 270 return false; 271 272 return true; 273 }; 274 275 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) { 276 if (ClobbersPhysRegAndSubRegs(i)) { 277 DefIndices[i] = Count; 278 KillIndices[i] = ~0u; 279 KeepRegs.reset(i); 280 Classes[i] = nullptr; 281 RegRefs.erase(i); 282 } 283 } 284 } 285 286 if (!MO.isReg()) continue; 287 Register Reg = MO.getReg(); 288 if (Reg == 0) continue; 289 if (!MO.isDef()) continue; 290 291 // Ignore two-addr defs. 292 if (MI.isRegTiedToUseOperand(i)) 293 continue; 294 295 // If we've already marked this reg as unchangeable, don't remove 296 // it or any of its subregs from KeepRegs. 297 bool Keep = KeepRegs.test(Reg); 298 299 // For the reg itself and all subregs: update the def to current; 300 // reset the kill state, any restrictions, and references. 301 for (MCSubRegIterator SRI(Reg, TRI, true); SRI.isValid(); ++SRI) { 302 unsigned SubregReg = *SRI; 303 DefIndices[SubregReg] = Count; 304 KillIndices[SubregReg] = ~0u; 305 Classes[SubregReg] = nullptr; 306 RegRefs.erase(SubregReg); 307 if (!Keep) 308 KeepRegs.reset(SubregReg); 309 } 310 // Conservatively mark super-registers as unusable. 311 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) 312 Classes[*SR] = reinterpret_cast<TargetRegisterClass *>(-1); 313 } 314 } 315 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 316 MachineOperand &MO = MI.getOperand(i); 317 if (!MO.isReg()) continue; 318 Register Reg = MO.getReg(); 319 if (Reg == 0) continue; 320 if (!MO.isUse()) continue; 321 322 const TargetRegisterClass *NewRC = nullptr; 323 if (i < MI.getDesc().getNumOperands()) 324 NewRC = TII->getRegClass(MI.getDesc(), i, TRI, MF); 325 326 // For now, only allow the register to be changed if its register 327 // class is consistent across all uses. 328 if (!Classes[Reg] && NewRC) 329 Classes[Reg] = NewRC; 330 else if (!NewRC || Classes[Reg] != NewRC) 331 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 332 333 RegRefs.insert(std::make_pair(Reg, &MO)); 334 335 // It wasn't previously live but now it is, this is a kill. 336 // Repeat for all aliases. 337 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) { 338 unsigned AliasReg = *AI; 339 if (KillIndices[AliasReg] == ~0u) { 340 KillIndices[AliasReg] = Count; 341 DefIndices[AliasReg] = ~0u; 342 } 343 } 344 } 345 } 346 347 // Check all machine operands that reference the antidependent register and must 348 // be replaced by NewReg. Return true if any of their parent instructions may 349 // clobber the new register. 350 // 351 // Note: AntiDepReg may be referenced by a two-address instruction such that 352 // it's use operand is tied to a def operand. We guard against the case in which 353 // the two-address instruction also defines NewReg, as may happen with 354 // pre/postincrement loads. In this case, both the use and def operands are in 355 // RegRefs because the def is inserted by PrescanInstruction and not erased 356 // during ScanInstruction. So checking for an instruction with definitions of 357 // both NewReg and AntiDepReg covers it. 358 bool 359 CriticalAntiDepBreaker::isNewRegClobberedByRefs(RegRefIter RegRefBegin, 360 RegRefIter RegRefEnd, 361 unsigned NewReg) { 362 for (RegRefIter I = RegRefBegin; I != RegRefEnd; ++I ) { 363 MachineOperand *RefOper = I->second; 364 365 // Don't allow the instruction defining AntiDepReg to earlyclobber its 366 // operands, in case they may be assigned to NewReg. In this case antidep 367 // breaking must fail, but it's too rare to bother optimizing. 368 if (RefOper->isDef() && RefOper->isEarlyClobber()) 369 return true; 370 371 // Handle cases in which this instruction defines NewReg. 372 MachineInstr *MI = RefOper->getParent(); 373 for (const MachineOperand &CheckOper : MI->operands()) { 374 if (CheckOper.isRegMask() && CheckOper.clobbersPhysReg(NewReg)) 375 return true; 376 377 if (!CheckOper.isReg() || !CheckOper.isDef() || 378 CheckOper.getReg() != NewReg) 379 continue; 380 381 // Don't allow the instruction to define NewReg and AntiDepReg. 382 // When AntiDepReg is renamed it will be an illegal op. 383 if (RefOper->isDef()) 384 return true; 385 386 // Don't allow an instruction using AntiDepReg to be earlyclobbered by 387 // NewReg. 388 if (CheckOper.isEarlyClobber()) 389 return true; 390 391 // Don't allow inline asm to define NewReg at all. Who knows what it's 392 // doing with it. 393 if (MI->isInlineAsm()) 394 return true; 395 } 396 } 397 return false; 398 } 399 400 unsigned CriticalAntiDepBreaker:: 401 findSuitableFreeRegister(RegRefIter RegRefBegin, 402 RegRefIter RegRefEnd, 403 unsigned AntiDepReg, 404 unsigned LastNewReg, 405 const TargetRegisterClass *RC, 406 SmallVectorImpl<unsigned> &Forbid) { 407 ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(RC); 408 for (unsigned NewReg : Order) { 409 // Don't replace a register with itself. 410 if (NewReg == AntiDepReg) continue; 411 // Don't replace a register with one that was recently used to repair 412 // an anti-dependence with this AntiDepReg, because that would 413 // re-introduce that anti-dependence. 414 if (NewReg == LastNewReg) continue; 415 // If any instructions that define AntiDepReg also define the NewReg, it's 416 // not suitable. For example, Instruction with multiple definitions can 417 // result in this condition. 418 if (isNewRegClobberedByRefs(RegRefBegin, RegRefEnd, NewReg)) continue; 419 // If NewReg is dead and NewReg's most recent def is not before 420 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg. 421 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) 422 && "Kill and Def maps aren't consistent for AntiDepReg!"); 423 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) 424 && "Kill and Def maps aren't consistent for NewReg!"); 425 if (KillIndices[NewReg] != ~0u || 426 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) || 427 KillIndices[AntiDepReg] > DefIndices[NewReg]) 428 continue; 429 // If NewReg overlaps any of the forbidden registers, we can't use it. 430 bool Forbidden = false; 431 for (unsigned R : Forbid) 432 if (TRI->regsOverlap(NewReg, R)) { 433 Forbidden = true; 434 break; 435 } 436 if (Forbidden) continue; 437 return NewReg; 438 } 439 440 // No registers are free and available! 441 return 0; 442 } 443 444 unsigned CriticalAntiDepBreaker:: 445 BreakAntiDependencies(const std::vector<SUnit> &SUnits, 446 MachineBasicBlock::iterator Begin, 447 MachineBasicBlock::iterator End, 448 unsigned InsertPosIndex, 449 DbgValueVector &DbgValues) { 450 // The code below assumes that there is at least one instruction, 451 // so just duck out immediately if the block is empty. 452 if (SUnits.empty()) return 0; 453 454 // Keep a map of the MachineInstr*'s back to the SUnit representing them. 455 // This is used for updating debug information. 456 // 457 // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap 458 DenseMap<MachineInstr *, const SUnit *> MISUnitMap; 459 460 // Find the node at the bottom of the critical path. 461 const SUnit *Max = nullptr; 462 for (const SUnit &SU : SUnits) { 463 MISUnitMap[SU.getInstr()] = &SU; 464 if (!Max || SU.getDepth() + SU.Latency > Max->getDepth() + Max->Latency) 465 Max = &SU; 466 } 467 assert(Max && "Failed to find bottom of the critical path"); 468 469 #ifndef NDEBUG 470 { 471 LLVM_DEBUG(dbgs() << "Critical path has total latency " 472 << (Max->getDepth() + Max->Latency) << "\n"); 473 LLVM_DEBUG(dbgs() << "Available regs:"); 474 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) { 475 if (KillIndices[Reg] == ~0u) 476 LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI)); 477 } 478 LLVM_DEBUG(dbgs() << '\n'); 479 } 480 #endif 481 482 // Track progress along the critical path through the SUnit graph as we walk 483 // the instructions. 484 const SUnit *CriticalPathSU = Max; 485 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr(); 486 487 // Consider this pattern: 488 // A = ... 489 // ... = A 490 // A = ... 491 // ... = A 492 // A = ... 493 // ... = A 494 // A = ... 495 // ... = A 496 // There are three anti-dependencies here, and without special care, 497 // we'd break all of them using the same register: 498 // A = ... 499 // ... = A 500 // B = ... 501 // ... = B 502 // B = ... 503 // ... = B 504 // B = ... 505 // ... = B 506 // because at each anti-dependence, B is the first register that 507 // isn't A which is free. This re-introduces anti-dependencies 508 // at all but one of the original anti-dependencies that we were 509 // trying to break. To avoid this, keep track of the most recent 510 // register that each register was replaced with, avoid 511 // using it to repair an anti-dependence on the same register. 512 // This lets us produce this: 513 // A = ... 514 // ... = A 515 // B = ... 516 // ... = B 517 // C = ... 518 // ... = C 519 // B = ... 520 // ... = B 521 // This still has an anti-dependence on B, but at least it isn't on the 522 // original critical path. 523 // 524 // TODO: If we tracked more than one register here, we could potentially 525 // fix that remaining critical edge too. This is a little more involved, 526 // because unlike the most recent register, less recent registers should 527 // still be considered, though only if no other registers are available. 528 std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0); 529 530 // Attempt to break anti-dependence edges on the critical path. Walk the 531 // instructions from the bottom up, tracking information about liveness 532 // as we go to help determine which registers are available. 533 unsigned Broken = 0; 534 unsigned Count = InsertPosIndex - 1; 535 for (MachineBasicBlock::iterator I = End, E = Begin; I != E; --Count) { 536 MachineInstr &MI = *--I; 537 // Kill instructions can define registers but are really nops, and there 538 // might be a real definition earlier that needs to be paired with uses 539 // dominated by this kill. 540 541 // FIXME: It may be possible to remove the isKill() restriction once PR18663 542 // has been properly fixed. There can be value in processing kills as seen 543 // in the AggressiveAntiDepBreaker class. 544 if (MI.isDebugInstr() || MI.isKill()) 545 continue; 546 547 // Check if this instruction has a dependence on the critical path that 548 // is an anti-dependence that we may be able to break. If it is, set 549 // AntiDepReg to the non-zero register associated with the anti-dependence. 550 // 551 // We limit our attention to the critical path as a heuristic to avoid 552 // breaking anti-dependence edges that aren't going to significantly 553 // impact the overall schedule. There are a limited number of registers 554 // and we want to save them for the important edges. 555 // 556 // TODO: Instructions with multiple defs could have multiple 557 // anti-dependencies. The current code here only knows how to break one 558 // edge per instruction. Note that we'd have to be able to break all of 559 // the anti-dependencies in an instruction in order to be effective. 560 unsigned AntiDepReg = 0; 561 if (&MI == CriticalPathMI) { 562 if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) { 563 const SUnit *NextSU = Edge->getSUnit(); 564 565 // Only consider anti-dependence edges. 566 if (Edge->getKind() == SDep::Anti) { 567 AntiDepReg = Edge->getReg(); 568 assert(AntiDepReg != 0 && "Anti-dependence on reg0?"); 569 if (!MRI.isAllocatable(AntiDepReg)) 570 // Don't break anti-dependencies on non-allocatable registers. 571 AntiDepReg = 0; 572 else if (KeepRegs.test(AntiDepReg)) 573 // Don't break anti-dependencies if a use down below requires 574 // this exact register. 575 AntiDepReg = 0; 576 else { 577 // If the SUnit has other dependencies on the SUnit that it 578 // anti-depends on, don't bother breaking the anti-dependency 579 // since those edges would prevent such units from being 580 // scheduled past each other regardless. 581 // 582 // Also, if there are dependencies on other SUnits with the 583 // same register as the anti-dependency, don't attempt to 584 // break it. 585 for (const SDep &P : CriticalPathSU->Preds) 586 if (P.getSUnit() == NextSU 587 ? (P.getKind() != SDep::Anti || P.getReg() != AntiDepReg) 588 : (P.getKind() == SDep::Data && 589 P.getReg() == AntiDepReg)) { 590 AntiDepReg = 0; 591 break; 592 } 593 } 594 } 595 CriticalPathSU = NextSU; 596 CriticalPathMI = CriticalPathSU->getInstr(); 597 } else { 598 // We've reached the end of the critical path. 599 CriticalPathSU = nullptr; 600 CriticalPathMI = nullptr; 601 } 602 } 603 604 PrescanInstruction(MI); 605 606 SmallVector<unsigned, 2> ForbidRegs; 607 608 // If MI's defs have a special allocation requirement, don't allow 609 // any def registers to be changed. Also assume all registers 610 // defined in a call must not be changed (ABI). 611 if (MI.isCall() || MI.hasExtraDefRegAllocReq() || TII->isPredicated(MI)) 612 // If this instruction's defs have special allocation requirement, don't 613 // break this anti-dependency. 614 AntiDepReg = 0; 615 else if (AntiDepReg) { 616 // If this instruction has a use of AntiDepReg, breaking it 617 // is invalid. If the instruction defines other registers, 618 // save a list of them so that we don't pick a new register 619 // that overlaps any of them. 620 for (const MachineOperand &MO : MI.operands()) { 621 if (!MO.isReg()) continue; 622 Register Reg = MO.getReg(); 623 if (Reg == 0) continue; 624 if (MO.isUse() && TRI->regsOverlap(AntiDepReg, Reg)) { 625 AntiDepReg = 0; 626 break; 627 } 628 if (MO.isDef() && Reg != AntiDepReg) 629 ForbidRegs.push_back(Reg); 630 } 631 } 632 633 // Determine AntiDepReg's register class, if it is live and is 634 // consistently used within a single class. 635 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] 636 : nullptr; 637 assert((AntiDepReg == 0 || RC != nullptr) && 638 "Register should be live if it's causing an anti-dependence!"); 639 if (RC == reinterpret_cast<TargetRegisterClass *>(-1)) 640 AntiDepReg = 0; 641 642 // Look for a suitable register to use to break the anti-dependence. 643 // 644 // TODO: Instead of picking the first free register, consider which might 645 // be the best. 646 if (AntiDepReg != 0) { 647 std::pair<std::multimap<unsigned, MachineOperand *>::iterator, 648 std::multimap<unsigned, MachineOperand *>::iterator> 649 Range = RegRefs.equal_range(AntiDepReg); 650 if (unsigned NewReg = findSuitableFreeRegister(Range.first, Range.second, 651 AntiDepReg, 652 LastNewReg[AntiDepReg], 653 RC, ForbidRegs)) { 654 LLVM_DEBUG(dbgs() << "Breaking anti-dependence edge on " 655 << printReg(AntiDepReg, TRI) << " with " 656 << RegRefs.count(AntiDepReg) << " references" 657 << " using " << printReg(NewReg, TRI) << "!\n"); 658 659 // Update the references to the old register to refer to the new 660 // register. 661 for (std::multimap<unsigned, MachineOperand *>::iterator 662 Q = Range.first, QE = Range.second; Q != QE; ++Q) { 663 Q->second->setReg(NewReg); 664 // If the SU for the instruction being updated has debug information 665 // related to the anti-dependency register, make sure to update that 666 // as well. 667 const SUnit *SU = MISUnitMap[Q->second->getParent()]; 668 if (!SU) continue; 669 UpdateDbgValues(DbgValues, Q->second->getParent(), 670 AntiDepReg, NewReg); 671 } 672 673 // We just went back in time and modified history; the 674 // liveness information for the anti-dependence reg is now 675 // inconsistent. Set the state as if it were dead. 676 Classes[NewReg] = Classes[AntiDepReg]; 677 DefIndices[NewReg] = DefIndices[AntiDepReg]; 678 KillIndices[NewReg] = KillIndices[AntiDepReg]; 679 assert(((KillIndices[NewReg] == ~0u) != 680 (DefIndices[NewReg] == ~0u)) && 681 "Kill and Def maps aren't consistent for NewReg!"); 682 683 Classes[AntiDepReg] = nullptr; 684 DefIndices[AntiDepReg] = KillIndices[AntiDepReg]; 685 KillIndices[AntiDepReg] = ~0u; 686 assert(((KillIndices[AntiDepReg] == ~0u) != 687 (DefIndices[AntiDepReg] == ~0u)) && 688 "Kill and Def maps aren't consistent for AntiDepReg!"); 689 690 RegRefs.erase(AntiDepReg); 691 LastNewReg[AntiDepReg] = NewReg; 692 ++Broken; 693 } 694 } 695 696 ScanInstruction(MI, Count); 697 } 698 699 return Broken; 700 } 701 702 AntiDepBreaker * 703 llvm::createCriticalAntiDepBreaker(MachineFunction &MFi, 704 const RegisterClassInfo &RCI) { 705 return new CriticalAntiDepBreaker(MFi, RCI); 706 } 707