1 //===----- CriticalAntiDepBreaker.cpp - Anti-dep breaker -------- ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CriticalAntiDepBreaker class, which
11 // implements register anti-dependence breaking along a blocks
12 // critical path during post-RA scheduler.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "critical-antidep"
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"
28 CriticalAntiDepBreaker::
29 CriticalAntiDepBreaker(MachineFunction& MFi) :
30 AntiDepBreaker(), MF(MFi),
32 TRI(MF.getTarget().getRegisterInfo()),
33 AllocatableSet(TRI->getAllocatableSet(MF))
37 CriticalAntiDepBreaker::~CriticalAntiDepBreaker() {
40 void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
41 // Clear out the register class data.
42 std::fill(Classes, array_endof(Classes),
43 static_cast<const TargetRegisterClass *>(0));
45 // Initialize the indices to indicate that no registers are live.
46 std::fill(KillIndices, array_endof(KillIndices), ~0u);
47 std::fill(DefIndices, array_endof(DefIndices), BB->size());
49 // Clear "do not change" set.
52 bool IsReturnBlock = (!BB->empty() && BB->back().getDesc().isReturn());
54 // Determine the live-out physregs for this block.
56 // In a return block, examine the function live-out regs.
57 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
58 E = MRI.liveout_end(); I != E; ++I) {
60 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
61 KillIndices[Reg] = BB->size();
62 DefIndices[Reg] = ~0u;
63 // Repeat, for all aliases.
64 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
65 unsigned AliasReg = *Alias;
66 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
67 KillIndices[AliasReg] = BB->size();
68 DefIndices[AliasReg] = ~0u;
72 // In a non-return block, examine the live-in regs of all successors.
73 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
74 SE = BB->succ_end(); SI != SE; ++SI)
75 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
76 E = (*SI)->livein_end(); I != E; ++I) {
78 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
79 KillIndices[Reg] = BB->size();
80 DefIndices[Reg] = ~0u;
81 // Repeat, for all aliases.
82 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
83 unsigned AliasReg = *Alias;
84 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
85 KillIndices[AliasReg] = BB->size();
86 DefIndices[AliasReg] = ~0u;
91 // Mark live-out callee-saved registers. In a return block this is
92 // all callee-saved registers. In non-return this is any
93 // callee-saved register that is not saved in the prolog.
94 const MachineFrameInfo *MFI = MF.getFrameInfo();
95 BitVector Pristine = MFI->getPristineRegs(BB);
96 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
98 if (!IsReturnBlock && !Pristine.test(Reg)) continue;
99 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
100 KillIndices[Reg] = BB->size();
101 DefIndices[Reg] = ~0u;
102 // Repeat, for all aliases.
103 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
104 unsigned AliasReg = *Alias;
105 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
106 KillIndices[AliasReg] = BB->size();
107 DefIndices[AliasReg] = ~0u;
112 void CriticalAntiDepBreaker::FinishBlock() {
117 void CriticalAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
118 unsigned InsertPosIndex) {
119 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
121 // Any register which was defined within the previous scheduling region
122 // may have been rescheduled and its lifetime may overlap with registers
123 // in ways not reflected in our current liveness state. For each such
124 // register, adjust the liveness state to be conservatively correct.
125 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
126 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
127 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
128 // Mark this register to be non-renamable.
129 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
130 // Move the def index to the end of the previous region, to reflect
131 // that the def could theoretically have been scheduled at the end.
132 DefIndices[Reg] = InsertPosIndex;
135 PrescanInstruction(MI);
136 ScanInstruction(MI, Count);
139 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
141 static SDep *CriticalPathStep(SUnit *SU) {
143 unsigned NextDepth = 0;
144 // Find the predecessor edge with the greatest depth.
145 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
147 SUnit *PredSU = P->getSUnit();
148 unsigned PredLatency = P->getLatency();
149 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
150 // In the case of a latency tie, prefer an anti-dependency edge over
151 // other types of edges.
152 if (NextDepth < PredTotalLatency ||
153 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
154 NextDepth = PredTotalLatency;
161 void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr *MI) {
162 // Scan the register operands for this instruction and update
163 // Classes and RegRefs.
164 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
165 MachineOperand &MO = MI->getOperand(i);
166 if (!MO.isReg()) continue;
167 unsigned Reg = MO.getReg();
168 if (Reg == 0) continue;
169 const TargetRegisterClass *NewRC = 0;
171 if (i < MI->getDesc().getNumOperands())
172 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
174 // For now, only allow the register to be changed if its register
175 // class is consistent across all uses.
176 if (!Classes[Reg] && NewRC)
177 Classes[Reg] = NewRC;
178 else if (!NewRC || Classes[Reg] != NewRC)
179 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
181 // Now check for aliases.
182 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
183 // If an alias of the reg is used during the live range, give up.
184 // Note that this allows us to skip checking if AntiDepReg
185 // overlaps with any of the aliases, among other things.
186 unsigned AliasReg = *Alias;
187 if (Classes[AliasReg]) {
188 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
189 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
193 // If we're still willing to consider this register, note the reference.
194 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
195 RegRefs.insert(std::make_pair(Reg, &MO));
197 // It's not safe to change register allocation for source operands of
198 // that have special allocation requirements.
199 if (MO.isUse() && MI->getDesc().hasExtraSrcRegAllocReq()) {
200 if (KeepRegs.insert(Reg)) {
201 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
203 KeepRegs.insert(*Subreg);
209 void CriticalAntiDepBreaker::ScanInstruction(MachineInstr *MI,
212 // Proceding upwards, registers that are defed but not used in this
213 // instruction are now dead.
214 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
215 MachineOperand &MO = MI->getOperand(i);
216 if (!MO.isReg()) continue;
217 unsigned Reg = MO.getReg();
218 if (Reg == 0) continue;
219 if (!MO.isDef()) continue;
220 // Ignore two-addr defs.
221 if (MI->isRegTiedToUseOperand(i)) continue;
223 DefIndices[Reg] = Count;
224 KillIndices[Reg] = ~0u;
225 assert(((KillIndices[Reg] == ~0u) !=
226 (DefIndices[Reg] == ~0u)) &&
227 "Kill and Def maps aren't consistent for Reg!");
231 // Repeat, for all subregs.
232 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
234 unsigned SubregReg = *Subreg;
235 DefIndices[SubregReg] = Count;
236 KillIndices[SubregReg] = ~0u;
237 KeepRegs.erase(SubregReg);
238 Classes[SubregReg] = 0;
239 RegRefs.erase(SubregReg);
241 // Conservatively mark super-registers as unusable.
242 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
244 unsigned SuperReg = *Super;
245 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
248 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
249 MachineOperand &MO = MI->getOperand(i);
250 if (!MO.isReg()) continue;
251 unsigned Reg = MO.getReg();
252 if (Reg == 0) continue;
253 if (!MO.isUse()) continue;
255 const TargetRegisterClass *NewRC = 0;
256 if (i < MI->getDesc().getNumOperands())
257 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
259 // For now, only allow the register to be changed if its register
260 // class is consistent across all uses.
261 if (!Classes[Reg] && NewRC)
262 Classes[Reg] = NewRC;
263 else if (!NewRC || Classes[Reg] != NewRC)
264 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
266 RegRefs.insert(std::make_pair(Reg, &MO));
268 // It wasn't previously live but now it is, this is a kill.
269 if (KillIndices[Reg] == ~0u) {
270 KillIndices[Reg] = Count;
271 DefIndices[Reg] = ~0u;
272 assert(((KillIndices[Reg] == ~0u) !=
273 (DefIndices[Reg] == ~0u)) &&
274 "Kill and Def maps aren't consistent for Reg!");
276 // Repeat, for all aliases.
277 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
278 unsigned AliasReg = *Alias;
279 if (KillIndices[AliasReg] == ~0u) {
280 KillIndices[AliasReg] = Count;
281 DefIndices[AliasReg] = ~0u;
288 CriticalAntiDepBreaker::findSuitableFreeRegister(unsigned AntiDepReg,
290 const TargetRegisterClass *RC) {
291 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
292 RE = RC->allocation_order_end(MF); R != RE; ++R) {
293 unsigned NewReg = *R;
294 // Don't replace a register with itself.
295 if (NewReg == AntiDepReg) continue;
296 // Don't replace a register with one that was recently used to repair
297 // an anti-dependence with this AntiDepReg, because that would
298 // re-introduce that anti-dependence.
299 if (NewReg == LastNewReg) continue;
300 // If NewReg is dead and NewReg's most recent def is not before
301 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
302 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
303 "Kill and Def maps aren't consistent for AntiDepReg!");
304 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
305 "Kill and Def maps aren't consistent for NewReg!");
306 if (KillIndices[NewReg] != ~0u ||
307 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
308 KillIndices[AntiDepReg] > DefIndices[NewReg])
313 // No registers are free and available!
317 unsigned CriticalAntiDepBreaker::
318 BreakAntiDependencies(std::vector<SUnit>& SUnits,
319 MachineBasicBlock::iterator& Begin,
320 MachineBasicBlock::iterator& End,
321 unsigned InsertPosIndex) {
322 // The code below assumes that there is at least one instruction,
323 // so just duck out immediately if the block is empty.
324 if (SUnits.empty()) return 0;
326 // Find the node at the bottom of the critical path.
328 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
329 SUnit *SU = &SUnits[i];
330 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
336 DEBUG(errs() << "Critical path has total latency "
337 << (Max->getDepth() + Max->Latency) << "\n");
338 DEBUG(errs() << "Available regs:");
339 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
340 if (KillIndices[Reg] == ~0u)
341 DEBUG(errs() << " " << TRI->getName(Reg));
343 DEBUG(errs() << '\n');
347 // Track progress along the critical path through the SUnit graph as we walk
349 SUnit *CriticalPathSU = Max;
350 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
352 // Consider this pattern:
361 // There are three anti-dependencies here, and without special care,
362 // we'd break all of them using the same register:
371 // because at each anti-dependence, B is the first register that
372 // isn't A which is free. This re-introduces anti-dependencies
373 // at all but one of the original anti-dependencies that we were
374 // trying to break. To avoid this, keep track of the most recent
375 // register that each register was replaced with, avoid
376 // using it to repair an anti-dependence on the same register.
377 // This lets us produce this:
386 // This still has an anti-dependence on B, but at least it isn't on the
387 // original critical path.
389 // TODO: If we tracked more than one register here, we could potentially
390 // fix that remaining critical edge too. This is a little more involved,
391 // because unlike the most recent register, less recent registers should
392 // still be considered, though only if no other registers are available.
393 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
395 // Attempt to break anti-dependence edges on the critical path. Walk the
396 // instructions from the bottom up, tracking information about liveness
397 // as we go to help determine which registers are available.
399 unsigned Count = InsertPosIndex - 1;
400 for (MachineBasicBlock::iterator I = End, E = Begin;
402 MachineInstr *MI = --I;
404 // Check if this instruction has a dependence on the critical path that
405 // is an anti-dependence that we may be able to break. If it is, set
406 // AntiDepReg to the non-zero register associated with the anti-dependence.
408 // We limit our attention to the critical path as a heuristic to avoid
409 // breaking anti-dependence edges that aren't going to significantly
410 // impact the overall schedule. There are a limited number of registers
411 // and we want to save them for the important edges.
413 // TODO: Instructions with multiple defs could have multiple
414 // anti-dependencies. The current code here only knows how to break one
415 // edge per instruction. Note that we'd have to be able to break all of
416 // the anti-dependencies in an instruction in order to be effective.
417 unsigned AntiDepReg = 0;
418 if (MI == CriticalPathMI) {
419 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
420 SUnit *NextSU = Edge->getSUnit();
422 // Only consider anti-dependence edges.
423 if (Edge->getKind() == SDep::Anti) {
424 AntiDepReg = Edge->getReg();
425 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
426 if (!AllocatableSet.test(AntiDepReg))
427 // Don't break anti-dependencies on non-allocatable registers.
429 else if (KeepRegs.count(AntiDepReg))
430 // Don't break anti-dependencies if an use down below requires
431 // this exact register.
434 // If the SUnit has other dependencies on the SUnit that it
435 // anti-depends on, don't bother breaking the anti-dependency
436 // since those edges would prevent such units from being
437 // scheduled past each other regardless.
439 // Also, if there are dependencies on other SUnits with the
440 // same register as the anti-dependency, don't attempt to
442 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
443 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
444 if (P->getSUnit() == NextSU ?
445 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
446 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
452 CriticalPathSU = NextSU;
453 CriticalPathMI = CriticalPathSU->getInstr();
455 // We've reached the end of the critical path.
461 PrescanInstruction(MI);
463 if (MI->getDesc().hasExtraDefRegAllocReq())
464 // If this instruction's defs have special allocation requirement, don't
465 // break this anti-dependency.
467 else if (AntiDepReg) {
468 // If this instruction has a use of AntiDepReg, breaking it
470 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
471 MachineOperand &MO = MI->getOperand(i);
472 if (!MO.isReg()) continue;
473 unsigned Reg = MO.getReg();
474 if (Reg == 0) continue;
475 if (MO.isUse() && AntiDepReg == Reg) {
482 // Determine AntiDepReg's register class, if it is live and is
483 // consistently used within a single class.
484 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
485 assert((AntiDepReg == 0 || RC != NULL) &&
486 "Register should be live if it's causing an anti-dependence!");
487 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
490 // Look for a suitable register to use to break the anti-depenence.
492 // TODO: Instead of picking the first free register, consider which might
494 if (AntiDepReg != 0) {
495 if (unsigned NewReg = findSuitableFreeRegister(AntiDepReg,
496 LastNewReg[AntiDepReg],
498 DEBUG(errs() << "Breaking anti-dependence edge on "
499 << TRI->getName(AntiDepReg)
500 << " with " << RegRefs.count(AntiDepReg) << " references"
501 << " using " << TRI->getName(NewReg) << "!\n");
503 // Update the references to the old register to refer to the new
505 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
506 std::multimap<unsigned, MachineOperand *>::iterator>
507 Range = RegRefs.equal_range(AntiDepReg);
508 for (std::multimap<unsigned, MachineOperand *>::iterator
509 Q = Range.first, QE = Range.second; Q != QE; ++Q)
510 Q->second->setReg(NewReg);
512 // We just went back in time and modified history; the
513 // liveness information for the anti-depenence reg is now
514 // inconsistent. Set the state as if it were dead.
515 Classes[NewReg] = Classes[AntiDepReg];
516 DefIndices[NewReg] = DefIndices[AntiDepReg];
517 KillIndices[NewReg] = KillIndices[AntiDepReg];
518 assert(((KillIndices[NewReg] == ~0u) !=
519 (DefIndices[NewReg] == ~0u)) &&
520 "Kill and Def maps aren't consistent for NewReg!");
522 Classes[AntiDepReg] = 0;
523 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
524 KillIndices[AntiDepReg] = ~0u;
525 assert(((KillIndices[AntiDepReg] == ~0u) !=
526 (DefIndices[AntiDepReg] == ~0u)) &&
527 "Kill and Def maps aren't consistent for AntiDepReg!");
529 RegRefs.erase(AntiDepReg);
530 LastNewReg[AntiDepReg] = NewReg;
535 ScanInstruction(MI, Count);