CriticalAntiDepBreaker.cpp revision fa0ccf5802433e433f39167caf3d1e1732d388c3
1//===----- CriticalAntiDepBreaker.cpp - Anti-dep breaker -------- ---------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the CriticalAntiDepBreaker class, which 11// implements register anti-dependence breaking along a blocks 12// critical path during post-RA scheduler. 13// 14//===----------------------------------------------------------------------===// 15 16#define DEBUG_TYPE "post-RA-sched" 17#include "CriticalAntiDepBreaker.h" 18#include "llvm/CodeGen/MachineBasicBlock.h" 19#include "llvm/CodeGen/MachineFrameInfo.h" 20#include "llvm/Target/TargetMachine.h" 21#include "llvm/Target/TargetRegisterInfo.h" 22#include "llvm/Support/Debug.h" 23#include "llvm/Support/ErrorHandling.h" 24#include "llvm/Support/raw_ostream.h" 25 26using namespace llvm; 27 28CriticalAntiDepBreaker:: 29CriticalAntiDepBreaker(MachineFunction& MFi) : 30 AntiDepBreaker(), MF(MFi), 31 MRI(MF.getRegInfo()), 32 TRI(MF.getTarget().getRegisterInfo()), 33 AllocatableSet(TRI->getAllocatableSet(MF)) 34{ 35} 36 37CriticalAntiDepBreaker::~CriticalAntiDepBreaker() { 38} 39 40void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) { 41 // Clear out the register class data. 42 std::fill(Classes, array_endof(Classes), 43 static_cast<const TargetRegisterClass *>(0)); 44 45 // Initialize the indices to indicate that no registers are live. 46 const unsigned BBSize = BB->size(); 47 for (unsigned i = 0; i < TRI->getNumRegs(); ++i) { 48 KillIndices[i] = ~0u; 49 DefIndices[i] = BBSize; 50 } 51 52 // Clear "do not change" set. 53 KeepRegs.clear(); 54 55 bool IsReturnBlock = (!BB->empty() && BB->back().getDesc().isReturn()); 56 57 // Determine the live-out physregs for this block. 58 if (IsReturnBlock) { 59 // In a return block, examine the function live-out regs. 60 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(), 61 E = MRI.liveout_end(); I != E; ++I) { 62 unsigned Reg = *I; 63 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 64 KillIndices[Reg] = BB->size(); 65 DefIndices[Reg] = ~0u; 66 // Repeat, for all aliases. 67 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) { 68 unsigned AliasReg = *Alias; 69 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1); 70 KillIndices[AliasReg] = BB->size(); 71 DefIndices[AliasReg] = ~0u; 72 } 73 } 74 } else { 75 // In a non-return block, examine the live-in regs of all successors. 76 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 77 SE = BB->succ_end(); SI != SE; ++SI) 78 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(), 79 E = (*SI)->livein_end(); I != E; ++I) { 80 unsigned Reg = *I; 81 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 82 KillIndices[Reg] = BB->size(); 83 DefIndices[Reg] = ~0u; 84 // Repeat, for all aliases. 85 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) { 86 unsigned AliasReg = *Alias; 87 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1); 88 KillIndices[AliasReg] = BB->size(); 89 DefIndices[AliasReg] = ~0u; 90 } 91 } 92 } 93 94 // Mark live-out callee-saved registers. In a return block this is 95 // all callee-saved registers. In non-return this is any 96 // callee-saved register that is not saved in the prolog. 97 const MachineFrameInfo *MFI = MF.getFrameInfo(); 98 BitVector Pristine = MFI->getPristineRegs(BB); 99 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) { 100 unsigned Reg = *I; 101 if (!IsReturnBlock && !Pristine.test(Reg)) continue; 102 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 103 KillIndices[Reg] = BB->size(); 104 DefIndices[Reg] = ~0u; 105 // Repeat, for all aliases. 106 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) { 107 unsigned AliasReg = *Alias; 108 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1); 109 KillIndices[AliasReg] = BB->size(); 110 DefIndices[AliasReg] = ~0u; 111 } 112 } 113} 114 115void CriticalAntiDepBreaker::FinishBlock() { 116 RegRefs.clear(); 117 KeepRegs.clear(); 118} 119 120void CriticalAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count, 121 unsigned InsertPosIndex) { 122 if (MI->isDebugValue()) 123 return; 124 assert(Count < InsertPosIndex && "Instruction index out of expected range!"); 125 126 // Any register which was defined within the previous scheduling region 127 // may have been rescheduled and its lifetime may overlap with registers 128 // in ways not reflected in our current liveness state. For each such 129 // register, adjust the liveness state to be conservatively correct. 130 for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) 131 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) { 132 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!"); 133 // Mark this register to be non-renamable. 134 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 135 // Move the def index to the end of the previous region, to reflect 136 // that the def could theoretically have been scheduled at the end. 137 DefIndices[Reg] = InsertPosIndex; 138 } 139 140 PrescanInstruction(MI); 141 ScanInstruction(MI, Count); 142} 143 144/// CriticalPathStep - Return the next SUnit after SU on the bottom-up 145/// critical path. 146static const SDep *CriticalPathStep(const SUnit *SU) { 147 const SDep *Next = 0; 148 unsigned NextDepth = 0; 149 // Find the predecessor edge with the greatest depth. 150 for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end(); 151 P != PE; ++P) { 152 const SUnit *PredSU = P->getSUnit(); 153 unsigned PredLatency = P->getLatency(); 154 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency; 155 // In the case of a latency tie, prefer an anti-dependency edge over 156 // other types of edges. 157 if (NextDepth < PredTotalLatency || 158 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) { 159 NextDepth = PredTotalLatency; 160 Next = &*P; 161 } 162 } 163 return Next; 164} 165 166void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr *MI) { 167 // Scan the register operands for this instruction and update 168 // Classes and RegRefs. 169 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 170 MachineOperand &MO = MI->getOperand(i); 171 if (!MO.isReg()) continue; 172 unsigned Reg = MO.getReg(); 173 if (Reg == 0) continue; 174 const TargetRegisterClass *NewRC = 0; 175 176 if (i < MI->getDesc().getNumOperands()) 177 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI); 178 179 // For now, only allow the register to be changed if its register 180 // class is consistent across all uses. 181 if (!Classes[Reg] && NewRC) 182 Classes[Reg] = NewRC; 183 else if (!NewRC || Classes[Reg] != NewRC) 184 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 185 186 // Now check for aliases. 187 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) { 188 // If an alias of the reg is used during the live range, give up. 189 // Note that this allows us to skip checking if AntiDepReg 190 // overlaps with any of the aliases, among other things. 191 unsigned AliasReg = *Alias; 192 if (Classes[AliasReg]) { 193 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1); 194 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 195 } 196 } 197 198 // If we're still willing to consider this register, note the reference. 199 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1)) 200 RegRefs.insert(std::make_pair(Reg, &MO)); 201 202 // It's not safe to change register allocation for source operands of 203 // that have special allocation requirements. 204 if (MO.isUse() && MI->getDesc().hasExtraSrcRegAllocReq()) { 205 if (KeepRegs.insert(Reg)) { 206 for (const unsigned *Subreg = TRI->getSubRegisters(Reg); 207 *Subreg; ++Subreg) 208 KeepRegs.insert(*Subreg); 209 } 210 } 211 } 212} 213 214void CriticalAntiDepBreaker::ScanInstruction(MachineInstr *MI, 215 unsigned Count) { 216 // Update liveness. 217 // Proceding upwards, registers that are defed but not used in this 218 // instruction are now dead. 219 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 220 MachineOperand &MO = MI->getOperand(i); 221 if (!MO.isReg()) continue; 222 unsigned Reg = MO.getReg(); 223 if (Reg == 0) continue; 224 if (!MO.isDef()) continue; 225 // Ignore two-addr defs. 226 if (MI->isRegTiedToUseOperand(i)) continue; 227 228 DefIndices[Reg] = Count; 229 KillIndices[Reg] = ~0u; 230 assert(((KillIndices[Reg] == ~0u) != 231 (DefIndices[Reg] == ~0u)) && 232 "Kill and Def maps aren't consistent for Reg!"); 233 KeepRegs.erase(Reg); 234 Classes[Reg] = 0; 235 RegRefs.erase(Reg); 236 // Repeat, for all subregs. 237 for (const unsigned *Subreg = TRI->getSubRegisters(Reg); 238 *Subreg; ++Subreg) { 239 unsigned SubregReg = *Subreg; 240 DefIndices[SubregReg] = Count; 241 KillIndices[SubregReg] = ~0u; 242 KeepRegs.erase(SubregReg); 243 Classes[SubregReg] = 0; 244 RegRefs.erase(SubregReg); 245 } 246 // Conservatively mark super-registers as unusable. 247 for (const unsigned *Super = TRI->getSuperRegisters(Reg); 248 *Super; ++Super) { 249 unsigned SuperReg = *Super; 250 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1); 251 } 252 } 253 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 254 MachineOperand &MO = MI->getOperand(i); 255 if (!MO.isReg()) continue; 256 unsigned Reg = MO.getReg(); 257 if (Reg == 0) continue; 258 if (!MO.isUse()) continue; 259 260 const TargetRegisterClass *NewRC = 0; 261 if (i < MI->getDesc().getNumOperands()) 262 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI); 263 264 // For now, only allow the register to be changed if its register 265 // class is consistent across all uses. 266 if (!Classes[Reg] && NewRC) 267 Classes[Reg] = NewRC; 268 else if (!NewRC || Classes[Reg] != NewRC) 269 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 270 271 RegRefs.insert(std::make_pair(Reg, &MO)); 272 273 // It wasn't previously live but now it is, this is a kill. 274 if (KillIndices[Reg] == ~0u) { 275 KillIndices[Reg] = Count; 276 DefIndices[Reg] = ~0u; 277 assert(((KillIndices[Reg] == ~0u) != 278 (DefIndices[Reg] == ~0u)) && 279 "Kill and Def maps aren't consistent for Reg!"); 280 } 281 // Repeat, for all aliases. 282 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) { 283 unsigned AliasReg = *Alias; 284 if (KillIndices[AliasReg] == ~0u) { 285 KillIndices[AliasReg] = Count; 286 DefIndices[AliasReg] = ~0u; 287 } 288 } 289 } 290} 291 292unsigned 293CriticalAntiDepBreaker::findSuitableFreeRegister(MachineInstr *MI, 294 unsigned AntiDepReg, 295 unsigned LastNewReg, 296 const TargetRegisterClass *RC) 297{ 298 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF), 299 RE = RC->allocation_order_end(MF); R != RE; ++R) { 300 unsigned NewReg = *R; 301 // Don't replace a register with itself. 302 if (NewReg == AntiDepReg) continue; 303 // Don't replace a register with one that was recently used to repair 304 // an anti-dependence with this AntiDepReg, because that would 305 // re-introduce that anti-dependence. 306 if (NewReg == LastNewReg) continue; 307 // If the instruction already has a def of the NewReg, it's not suitable. 308 // For example, Instruction with multiple definitions can result in this 309 // condition. 310 if (MI->modifiesRegister(NewReg, TRI)) continue; 311 // If NewReg is dead and NewReg's most recent def is not before 312 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg. 313 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) 314 && "Kill and Def maps aren't consistent for AntiDepReg!"); 315 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) 316 && "Kill and Def maps aren't consistent for NewReg!"); 317 if (KillIndices[NewReg] != ~0u || 318 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) || 319 KillIndices[AntiDepReg] > DefIndices[NewReg]) 320 continue; 321 return NewReg; 322 } 323 324 // No registers are free and available! 325 return 0; 326} 327 328unsigned CriticalAntiDepBreaker:: 329BreakAntiDependencies(const std::vector<SUnit>& SUnits, 330 MachineBasicBlock::iterator Begin, 331 MachineBasicBlock::iterator End, 332 unsigned InsertPosIndex) { 333 // The code below assumes that there is at least one instruction, 334 // so just duck out immediately if the block is empty. 335 if (SUnits.empty()) return 0; 336 337 // Find the node at the bottom of the critical path. 338 const SUnit *Max = 0; 339 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) { 340 const SUnit *SU = &SUnits[i]; 341 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency) 342 Max = SU; 343 } 344 345#ifndef NDEBUG 346 { 347 DEBUG(dbgs() << "Critical path has total latency " 348 << (Max->getDepth() + Max->Latency) << "\n"); 349 DEBUG(dbgs() << "Available regs:"); 350 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) { 351 if (KillIndices[Reg] == ~0u) 352 DEBUG(dbgs() << " " << TRI->getName(Reg)); 353 } 354 DEBUG(dbgs() << '\n'); 355 } 356#endif 357 358 // Track progress along the critical path through the SUnit graph as we walk 359 // the instructions. 360 const SUnit *CriticalPathSU = Max; 361 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr(); 362 363 // Consider this pattern: 364 // A = ... 365 // ... = A 366 // A = ... 367 // ... = A 368 // A = ... 369 // ... = A 370 // A = ... 371 // ... = A 372 // There are three anti-dependencies here, and without special care, 373 // we'd break all of them using the same register: 374 // A = ... 375 // ... = A 376 // B = ... 377 // ... = B 378 // B = ... 379 // ... = B 380 // B = ... 381 // ... = B 382 // because at each anti-dependence, B is the first register that 383 // isn't A which is free. This re-introduces anti-dependencies 384 // at all but one of the original anti-dependencies that we were 385 // trying to break. To avoid this, keep track of the most recent 386 // register that each register was replaced with, avoid 387 // using it to repair an anti-dependence on the same register. 388 // This lets us produce this: 389 // A = ... 390 // ... = A 391 // B = ... 392 // ... = B 393 // C = ... 394 // ... = C 395 // B = ... 396 // ... = B 397 // This still has an anti-dependence on B, but at least it isn't on the 398 // original critical path. 399 // 400 // TODO: If we tracked more than one register here, we could potentially 401 // fix that remaining critical edge too. This is a little more involved, 402 // because unlike the most recent register, less recent registers should 403 // still be considered, though only if no other registers are available. 404 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {}; 405 406 // Attempt to break anti-dependence edges on the critical path. Walk the 407 // instructions from the bottom up, tracking information about liveness 408 // as we go to help determine which registers are available. 409 unsigned Broken = 0; 410 unsigned Count = InsertPosIndex - 1; 411 for (MachineBasicBlock::iterator I = End, E = Begin; 412 I != E; --Count) { 413 MachineInstr *MI = --I; 414 if (MI->isDebugValue()) 415 continue; 416 417 // Check if this instruction has a dependence on the critical path that 418 // is an anti-dependence that we may be able to break. If it is, set 419 // AntiDepReg to the non-zero register associated with the anti-dependence. 420 // 421 // We limit our attention to the critical path as a heuristic to avoid 422 // breaking anti-dependence edges that aren't going to significantly 423 // impact the overall schedule. There are a limited number of registers 424 // and we want to save them for the important edges. 425 // 426 // TODO: Instructions with multiple defs could have multiple 427 // anti-dependencies. The current code here only knows how to break one 428 // edge per instruction. Note that we'd have to be able to break all of 429 // the anti-dependencies in an instruction in order to be effective. 430 unsigned AntiDepReg = 0; 431 if (MI == CriticalPathMI) { 432 if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) { 433 const SUnit *NextSU = Edge->getSUnit(); 434 435 // Only consider anti-dependence edges. 436 if (Edge->getKind() == SDep::Anti) { 437 AntiDepReg = Edge->getReg(); 438 assert(AntiDepReg != 0 && "Anti-dependence on reg0?"); 439 if (!AllocatableSet.test(AntiDepReg)) 440 // Don't break anti-dependencies on non-allocatable registers. 441 AntiDepReg = 0; 442 else if (KeepRegs.count(AntiDepReg)) 443 // Don't break anti-dependencies if an use down below requires 444 // this exact register. 445 AntiDepReg = 0; 446 else { 447 // If the SUnit has other dependencies on the SUnit that it 448 // anti-depends on, don't bother breaking the anti-dependency 449 // since those edges would prevent such units from being 450 // scheduled past each other regardless. 451 // 452 // Also, if there are dependencies on other SUnits with the 453 // same register as the anti-dependency, don't attempt to 454 // break it. 455 for (SUnit::const_pred_iterator P = CriticalPathSU->Preds.begin(), 456 PE = CriticalPathSU->Preds.end(); P != PE; ++P) 457 if (P->getSUnit() == NextSU ? 458 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) : 459 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) { 460 AntiDepReg = 0; 461 break; 462 } 463 } 464 } 465 CriticalPathSU = NextSU; 466 CriticalPathMI = CriticalPathSU->getInstr(); 467 } else { 468 // We've reached the end of the critical path. 469 CriticalPathSU = 0; 470 CriticalPathMI = 0; 471 } 472 } 473 474 PrescanInstruction(MI); 475 476 if (MI->getDesc().hasExtraDefRegAllocReq()) 477 // If this instruction's defs have special allocation requirement, don't 478 // break this anti-dependency. 479 AntiDepReg = 0; 480 else if (AntiDepReg) { 481 // If this instruction has a use of AntiDepReg, breaking it 482 // is invalid. 483 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 484 MachineOperand &MO = MI->getOperand(i); 485 if (!MO.isReg()) continue; 486 unsigned Reg = MO.getReg(); 487 if (Reg == 0) continue; 488 if (MO.isUse() && AntiDepReg == Reg) { 489 AntiDepReg = 0; 490 break; 491 } 492 } 493 } 494 495 // Determine AntiDepReg's register class, if it is live and is 496 // consistently used within a single class. 497 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0; 498 assert((AntiDepReg == 0 || RC != NULL) && 499 "Register should be live if it's causing an anti-dependence!"); 500 if (RC == reinterpret_cast<TargetRegisterClass *>(-1)) 501 AntiDepReg = 0; 502 503 // Look for a suitable register to use to break the anti-depenence. 504 // 505 // TODO: Instead of picking the first free register, consider which might 506 // be the best. 507 if (AntiDepReg != 0) { 508 if (unsigned NewReg = findSuitableFreeRegister(MI, AntiDepReg, 509 LastNewReg[AntiDepReg], 510 RC)) { 511 DEBUG(dbgs() << "Breaking anti-dependence edge on " 512 << TRI->getName(AntiDepReg) 513 << " with " << RegRefs.count(AntiDepReg) << " references" 514 << " using " << TRI->getName(NewReg) << "!\n"); 515 516 // Update the references to the old register to refer to the new 517 // register. 518 std::pair<std::multimap<unsigned, MachineOperand *>::iterator, 519 std::multimap<unsigned, MachineOperand *>::iterator> 520 Range = RegRefs.equal_range(AntiDepReg); 521 for (std::multimap<unsigned, MachineOperand *>::iterator 522 Q = Range.first, QE = Range.second; Q != QE; ++Q) 523 Q->second->setReg(NewReg); 524 525 // We just went back in time and modified history; the 526 // liveness information for the anti-depenence reg is now 527 // inconsistent. Set the state as if it were dead. 528 Classes[NewReg] = Classes[AntiDepReg]; 529 DefIndices[NewReg] = DefIndices[AntiDepReg]; 530 KillIndices[NewReg] = KillIndices[AntiDepReg]; 531 assert(((KillIndices[NewReg] == ~0u) != 532 (DefIndices[NewReg] == ~0u)) && 533 "Kill and Def maps aren't consistent for NewReg!"); 534 535 Classes[AntiDepReg] = 0; 536 DefIndices[AntiDepReg] = KillIndices[AntiDepReg]; 537 KillIndices[AntiDepReg] = ~0u; 538 assert(((KillIndices[AntiDepReg] == ~0u) != 539 (DefIndices[AntiDepReg] == ~0u)) && 540 "Kill and Def maps aren't consistent for AntiDepReg!"); 541 542 RegRefs.erase(AntiDepReg); 543 LastNewReg[AntiDepReg] = NewReg; 544 ++Broken; 545 } 546 } 547 548 ScanInstruction(MI, Count); 549 } 550 551 return Broken; 552} 553