1 //===----- AggressiveAntiDepBreaker.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 AggressiveAntiDepBreaker class, which
11 // implements register anti-dependence breaking during post-RA
12 // scheduling. It attempts to break all anti-dependencies within a
15 //===----------------------------------------------------------------------===//
17 #include "AggressiveAntiDepBreaker.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/RegisterClassInfo.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
30 #define DEBUG_TYPE "post-RA-sched"
32 // If DebugDiv > 0 then only break antidep with (ID % DebugDiv) == DebugMod
34 DebugDiv("agg-antidep-debugdiv",
35 cl::desc("Debug control for aggressive anti-dep breaker"),
36 cl::init(0), cl::Hidden);
38 DebugMod("agg-antidep-debugmod",
39 cl::desc("Debug control for aggressive anti-dep breaker"),
40 cl::init(0), cl::Hidden);
42 AggressiveAntiDepState::AggressiveAntiDepState(const unsigned TargetRegs,
43 MachineBasicBlock *BB) :
44 NumTargetRegs(TargetRegs), GroupNodes(TargetRegs, 0),
45 GroupNodeIndices(TargetRegs, 0),
46 KillIndices(TargetRegs, 0),
47 DefIndices(TargetRegs, 0)
49 const unsigned BBSize = BB->size();
50 for (unsigned i = 0; i < NumTargetRegs; ++i) {
51 // Initialize all registers to be in their own group. Initially we
52 // assign the register to the same-indexed GroupNode.
53 GroupNodeIndices[i] = i;
54 // Initialize the indices to indicate that no registers are live.
56 DefIndices[i] = BBSize;
60 unsigned AggressiveAntiDepState::GetGroup(unsigned Reg) {
61 unsigned Node = GroupNodeIndices[Reg];
62 while (GroupNodes[Node] != Node)
63 Node = GroupNodes[Node];
68 void AggressiveAntiDepState::GetGroupRegs(
70 std::vector<unsigned> &Regs,
71 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference> *RegRefs)
73 for (unsigned Reg = 0; Reg != NumTargetRegs; ++Reg) {
74 if ((GetGroup(Reg) == Group) && (RegRefs->count(Reg) > 0))
79 unsigned AggressiveAntiDepState::UnionGroups(unsigned Reg1, unsigned Reg2)
81 assert(GroupNodes[0] == 0 && "GroupNode 0 not parent!");
82 assert(GroupNodeIndices[0] == 0 && "Reg 0 not in Group 0!");
84 // find group for each register
85 unsigned Group1 = GetGroup(Reg1);
86 unsigned Group2 = GetGroup(Reg2);
88 // if either group is 0, then that must become the parent
89 unsigned Parent = (Group1 == 0) ? Group1 : Group2;
90 unsigned Other = (Parent == Group1) ? Group2 : Group1;
91 GroupNodes.at(Other) = Parent;
95 unsigned AggressiveAntiDepState::LeaveGroup(unsigned Reg)
97 // Create a new GroupNode for Reg. Reg's existing GroupNode must
98 // stay as is because there could be other GroupNodes referring to
100 unsigned idx = GroupNodes.size();
101 GroupNodes.push_back(idx);
102 GroupNodeIndices[Reg] = idx;
106 bool AggressiveAntiDepState::IsLive(unsigned Reg)
108 // KillIndex must be defined and DefIndex not defined for a register
110 return((KillIndices[Reg] != ~0u) && (DefIndices[Reg] == ~0u));
113 AggressiveAntiDepBreaker::AggressiveAntiDepBreaker(
114 MachineFunction &MFi, const RegisterClassInfo &RCI,
115 TargetSubtargetInfo::RegClassVector &CriticalPathRCs)
116 : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()),
117 TII(MF.getSubtarget().getInstrInfo()),
118 TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI),
120 /* Collect a bitset of all registers that are only broken if they
121 are on the critical path. */
122 for (unsigned i = 0, e = CriticalPathRCs.size(); i < e; ++i) {
123 BitVector CPSet = TRI->getAllocatableSet(MF, CriticalPathRCs[i]);
124 if (CriticalPathSet.none())
125 CriticalPathSet = CPSet;
127 CriticalPathSet |= CPSet;
130 DEBUG(dbgs() << "AntiDep Critical-Path Registers:");
131 DEBUG(for (int r = CriticalPathSet.find_first(); r != -1;
132 r = CriticalPathSet.find_next(r))
133 dbgs() << " " << TRI->getName(r));
134 DEBUG(dbgs() << '\n');
137 AggressiveAntiDepBreaker::~AggressiveAntiDepBreaker() {
141 void AggressiveAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
143 State = new AggressiveAntiDepState(TRI->getNumRegs(), BB);
145 bool IsReturnBlock = BB->isReturnBlock();
146 std::vector<unsigned> &KillIndices = State->GetKillIndices();
147 std::vector<unsigned> &DefIndices = State->GetDefIndices();
149 // Examine the live-in regs of all successors.
150 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
151 SE = BB->succ_end(); SI != SE; ++SI)
152 for (const auto &LI : (*SI)->liveins()) {
153 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI) {
155 State->UnionGroups(Reg, 0);
156 KillIndices[Reg] = BB->size();
157 DefIndices[Reg] = ~0u;
161 // Mark live-out callee-saved registers. In a return block this is
162 // all callee-saved registers. In non-return this is any
163 // callee-saved register that is not saved in the prolog.
164 const MachineFrameInfo &MFI = MF.getFrameInfo();
165 BitVector Pristine = MFI.getPristineRegs(MF);
166 for (const MCPhysReg *I = MF.getRegInfo().getCalleeSavedRegs(); *I;
169 if (!IsReturnBlock && !(Pristine.test(Reg) || BB->isLiveIn(Reg)))
171 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
172 unsigned AliasReg = *AI;
173 State->UnionGroups(AliasReg, 0);
174 KillIndices[AliasReg] = BB->size();
175 DefIndices[AliasReg] = ~0u;
180 void AggressiveAntiDepBreaker::FinishBlock() {
185 void AggressiveAntiDepBreaker::Observe(MachineInstr &MI, unsigned Count,
186 unsigned InsertPosIndex) {
187 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
189 std::set<unsigned> PassthruRegs;
190 GetPassthruRegs(MI, PassthruRegs);
191 PrescanInstruction(MI, Count, PassthruRegs);
192 ScanInstruction(MI, Count);
194 DEBUG(dbgs() << "Observe: ");
196 DEBUG(dbgs() << "\tRegs:");
198 std::vector<unsigned> &DefIndices = State->GetDefIndices();
199 for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
200 // If Reg is current live, then mark that it can't be renamed as
201 // we don't know the extent of its live-range anymore (now that it
202 // has been scheduled). If it is not live but was defined in the
203 // previous schedule region, then set its def index to the most
204 // conservative location (i.e. the beginning of the previous
206 if (State->IsLive(Reg)) {
207 DEBUG(if (State->GetGroup(Reg) != 0)
208 dbgs() << " " << TRI->getName(Reg) << "=g" <<
209 State->GetGroup(Reg) << "->g0(region live-out)");
210 State->UnionGroups(Reg, 0);
211 } else if ((DefIndices[Reg] < InsertPosIndex)
212 && (DefIndices[Reg] >= Count)) {
213 DefIndices[Reg] = Count;
216 DEBUG(dbgs() << '\n');
219 bool AggressiveAntiDepBreaker::IsImplicitDefUse(MachineInstr &MI,
220 MachineOperand &MO) {
221 if (!MO.isReg() || !MO.isImplicit())
224 unsigned Reg = MO.getReg();
228 MachineOperand *Op = nullptr;
230 Op = MI.findRegisterUseOperand(Reg, true);
232 Op = MI.findRegisterDefOperand(Reg);
234 return(Op && Op->isImplicit());
237 void AggressiveAntiDepBreaker::GetPassthruRegs(
238 MachineInstr &MI, std::set<unsigned> &PassthruRegs) {
239 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
240 MachineOperand &MO = MI.getOperand(i);
241 if (!MO.isReg()) continue;
242 if ((MO.isDef() && MI.isRegTiedToUseOperand(i)) ||
243 IsImplicitDefUse(MI, MO)) {
244 const unsigned Reg = MO.getReg();
245 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
246 SubRegs.isValid(); ++SubRegs)
247 PassthruRegs.insert(*SubRegs);
252 /// AntiDepEdges - Return in Edges the anti- and output- dependencies
253 /// in SU that we want to consider for breaking.
254 static void AntiDepEdges(const SUnit *SU, std::vector<const SDep*>& Edges) {
255 SmallSet<unsigned, 4> RegSet;
256 for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
258 if ((P->getKind() == SDep::Anti) || (P->getKind() == SDep::Output)) {
259 if (RegSet.insert(P->getReg()).second)
260 Edges.push_back(&*P);
265 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
267 static const SUnit *CriticalPathStep(const SUnit *SU) {
268 const SDep *Next = nullptr;
269 unsigned NextDepth = 0;
270 // Find the predecessor edge with the greatest depth.
272 for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
274 const SUnit *PredSU = P->getSUnit();
275 unsigned PredLatency = P->getLatency();
276 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
277 // In the case of a latency tie, prefer an anti-dependency edge over
278 // other types of edges.
279 if (NextDepth < PredTotalLatency ||
280 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
281 NextDepth = PredTotalLatency;
287 return (Next) ? Next->getSUnit() : nullptr;
290 void AggressiveAntiDepBreaker::HandleLastUse(unsigned Reg, unsigned KillIdx,
293 const char *footer) {
294 std::vector<unsigned> &KillIndices = State->GetKillIndices();
295 std::vector<unsigned> &DefIndices = State->GetDefIndices();
296 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
297 RegRefs = State->GetRegRefs();
299 // FIXME: We must leave subregisters of live super registers as live, so that
300 // we don't clear out the register tracking information for subregisters of
301 // super registers we're still tracking (and with which we're unioning
302 // subregister definitions).
303 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
304 if (TRI->isSuperRegister(Reg, *AI) && State->IsLive(*AI)) {
305 DEBUG(if (!header && footer) dbgs() << footer);
309 if (!State->IsLive(Reg)) {
310 KillIndices[Reg] = KillIdx;
311 DefIndices[Reg] = ~0u;
313 State->LeaveGroup(Reg);
315 dbgs() << header << TRI->getName(Reg); header = nullptr; });
316 DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << tag);
317 // Repeat for subregisters. Note that we only do this if the superregister
318 // was not live because otherwise, regardless whether we have an explicit
319 // use of the subregister, the subregister's contents are needed for the
320 // uses of the superregister.
321 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
322 unsigned SubregReg = *SubRegs;
323 if (!State->IsLive(SubregReg)) {
324 KillIndices[SubregReg] = KillIdx;
325 DefIndices[SubregReg] = ~0u;
326 RegRefs.erase(SubregReg);
327 State->LeaveGroup(SubregReg);
329 dbgs() << header << TRI->getName(Reg); header = nullptr; });
330 DEBUG(dbgs() << " " << TRI->getName(SubregReg) << "->g" <<
331 State->GetGroup(SubregReg) << tag);
336 DEBUG(if (!header && footer) dbgs() << footer);
339 void AggressiveAntiDepBreaker::PrescanInstruction(
340 MachineInstr &MI, unsigned Count, std::set<unsigned> &PassthruRegs) {
341 std::vector<unsigned> &DefIndices = State->GetDefIndices();
342 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
343 RegRefs = State->GetRegRefs();
345 // Handle dead defs by simulating a last-use of the register just
346 // after the def. A dead def can occur because the def is truly
347 // dead, or because only a subregister is live at the def. If we
348 // don't do this the dead def will be incorrectly merged into the
350 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
351 MachineOperand &MO = MI.getOperand(i);
352 if (!MO.isReg() || !MO.isDef()) continue;
353 unsigned Reg = MO.getReg();
354 if (Reg == 0) continue;
356 HandleLastUse(Reg, Count + 1, "", "\tDead Def: ", "\n");
359 DEBUG(dbgs() << "\tDef Groups:");
360 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
361 MachineOperand &MO = MI.getOperand(i);
362 if (!MO.isReg() || !MO.isDef()) continue;
363 unsigned Reg = MO.getReg();
364 if (Reg == 0) continue;
366 DEBUG(dbgs() << " " << TRI->getName(Reg) << "=g" << State->GetGroup(Reg));
368 // If MI's defs have a special allocation requirement, don't allow
369 // any def registers to be changed. Also assume all registers
370 // defined in a call must not be changed (ABI). Inline assembly may
371 // reference either system calls or the register directly. Skip it until we
372 // can tell user specified registers from compiler-specified.
373 if (MI.isCall() || MI.hasExtraDefRegAllocReq() || TII->isPredicated(MI) ||
375 DEBUG(if (State->GetGroup(Reg) != 0) dbgs() << "->g0(alloc-req)");
376 State->UnionGroups(Reg, 0);
379 // Any aliased that are live at this point are completely or
380 // partially defined here, so group those aliases with Reg.
381 for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
382 unsigned AliasReg = *AI;
383 if (State->IsLive(AliasReg)) {
384 State->UnionGroups(Reg, AliasReg);
385 DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << "(via " <<
386 TRI->getName(AliasReg) << ")");
390 // Note register reference...
391 const TargetRegisterClass *RC = nullptr;
392 if (i < MI.getDesc().getNumOperands())
393 RC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
394 AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
395 RegRefs.insert(std::make_pair(Reg, RR));
398 DEBUG(dbgs() << '\n');
400 // Scan the register defs for this instruction and update
402 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
403 MachineOperand &MO = MI.getOperand(i);
404 if (!MO.isReg() || !MO.isDef()) continue;
405 unsigned Reg = MO.getReg();
406 if (Reg == 0) continue;
407 // Ignore KILLs and passthru registers for liveness...
408 if (MI.isKill() || (PassthruRegs.count(Reg) != 0))
411 // Update def for Reg and aliases.
412 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
413 // We need to be careful here not to define already-live super registers.
414 // If the super register is already live, then this definition is not
415 // a definition of the whole super register (just a partial insertion
416 // into it). Earlier subregister definitions (which we've not yet visited
417 // because we're iterating bottom-up) need to be linked to the same group
418 // as this definition.
419 if (TRI->isSuperRegister(Reg, *AI) && State->IsLive(*AI))
422 DefIndices[*AI] = Count;
427 void AggressiveAntiDepBreaker::ScanInstruction(MachineInstr &MI,
429 DEBUG(dbgs() << "\tUse Groups:");
430 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
431 RegRefs = State->GetRegRefs();
433 // If MI's uses have special allocation requirement, don't allow
434 // any use registers to be changed. Also assume all registers
435 // used in a call must not be changed (ABI).
436 // Inline Assembly register uses also cannot be safely changed.
437 // FIXME: The issue with predicated instruction is more complex. We are being
438 // conservatively here because the kill markers cannot be trusted after
440 // %R6<def> = LDR %SP, %reg0, 92, pred:14, pred:%reg0; mem:LD4[FixedStack14]
442 // STR %R0, %R6<kill>, %reg0, 0, pred:0, pred:%CPSR; mem:ST4[%395]
443 // %R6<def> = LDR %SP, %reg0, 100, pred:0, pred:%CPSR; mem:LD4[FixedStack12]
444 // STR %R0, %R6<kill>, %reg0, 0, pred:14, pred:%reg0; mem:ST4[%396](align=8)
446 // The first R6 kill is not really a kill since it's killed by a predicated
447 // instruction which may not be executed. The second R6 def may or may not
448 // re-define R6 so it's not safe to change it since the last R6 use cannot be
450 bool Special = MI.isCall() || MI.hasExtraSrcRegAllocReq() ||
451 TII->isPredicated(MI) || MI.isInlineAsm();
453 // Scan the register uses for this instruction and update
454 // live-ranges, groups and RegRefs.
455 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
456 MachineOperand &MO = MI.getOperand(i);
457 if (!MO.isReg() || !MO.isUse()) continue;
458 unsigned Reg = MO.getReg();
459 if (Reg == 0) continue;
461 DEBUG(dbgs() << " " << TRI->getName(Reg) << "=g" <<
462 State->GetGroup(Reg));
464 // It wasn't previously live but now it is, this is a kill. Forget
465 // the previous live-range information and start a new live-range
467 HandleLastUse(Reg, Count, "(last-use)");
470 DEBUG(if (State->GetGroup(Reg) != 0) dbgs() << "->g0(alloc-req)");
471 State->UnionGroups(Reg, 0);
474 // Note register reference...
475 const TargetRegisterClass *RC = nullptr;
476 if (i < MI.getDesc().getNumOperands())
477 RC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
478 AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
479 RegRefs.insert(std::make_pair(Reg, RR));
482 DEBUG(dbgs() << '\n');
484 // Form a group of all defs and uses of a KILL instruction to ensure
485 // that all registers are renamed as a group.
487 DEBUG(dbgs() << "\tKill Group:");
489 unsigned FirstReg = 0;
490 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
491 MachineOperand &MO = MI.getOperand(i);
492 if (!MO.isReg()) continue;
493 unsigned Reg = MO.getReg();
494 if (Reg == 0) continue;
497 DEBUG(dbgs() << "=" << TRI->getName(Reg));
498 State->UnionGroups(FirstReg, Reg);
500 DEBUG(dbgs() << " " << TRI->getName(Reg));
505 DEBUG(dbgs() << "->g" << State->GetGroup(FirstReg) << '\n');
509 BitVector AggressiveAntiDepBreaker::GetRenameRegisters(unsigned Reg) {
510 BitVector BV(TRI->getNumRegs(), false);
513 // Check all references that need rewriting for Reg. For each, use
514 // the corresponding register class to narrow the set of registers
515 // that are appropriate for renaming.
516 for (const auto &Q : make_range(State->GetRegRefs().equal_range(Reg))) {
517 const TargetRegisterClass *RC = Q.second.RC;
520 BitVector RCBV = TRI->getAllocatableSet(MF, RC);
528 DEBUG(dbgs() << " " << TRI->getRegClassName(RC));
534 bool AggressiveAntiDepBreaker::FindSuitableFreeRegisters(
535 unsigned AntiDepGroupIndex,
536 RenameOrderType& RenameOrder,
537 std::map<unsigned, unsigned> &RenameMap) {
538 std::vector<unsigned> &KillIndices = State->GetKillIndices();
539 std::vector<unsigned> &DefIndices = State->GetDefIndices();
540 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
541 RegRefs = State->GetRegRefs();
543 // Collect all referenced registers in the same group as
544 // AntiDepReg. These all need to be renamed together if we are to
545 // break the anti-dependence.
546 std::vector<unsigned> Regs;
547 State->GetGroupRegs(AntiDepGroupIndex, Regs, &RegRefs);
548 assert(Regs.size() > 0 && "Empty register group!");
549 if (Regs.size() == 0)
552 // Find the "superest" register in the group. At the same time,
553 // collect the BitVector of registers that can be used to rename
555 DEBUG(dbgs() << "\tRename Candidates for Group g" << AntiDepGroupIndex
557 std::map<unsigned, BitVector> RenameRegisterMap;
558 unsigned SuperReg = 0;
559 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
560 unsigned Reg = Regs[i];
561 if ((SuperReg == 0) || TRI->isSuperRegister(SuperReg, Reg))
564 // If Reg has any references, then collect possible rename regs
565 if (RegRefs.count(Reg) > 0) {
566 DEBUG(dbgs() << "\t\t" << TRI->getName(Reg) << ":");
568 BitVector &BV = RenameRegisterMap[Reg];
570 BV = GetRenameRegisters(Reg);
574 for (int r = BV.find_first(); r != -1; r = BV.find_next(r))
575 dbgs() << " " << TRI->getName(r);
581 // All group registers should be a subreg of SuperReg.
582 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
583 unsigned Reg = Regs[i];
584 if (Reg == SuperReg) continue;
585 bool IsSub = TRI->isSubRegister(SuperReg, Reg);
586 // FIXME: remove this once PR18663 has been properly fixed. For now,
587 // return a conservative answer:
588 // assert(IsSub && "Expecting group subregister");
594 // If DebugDiv > 0 then only rename (renamecnt % DebugDiv) == DebugMod
596 static int renamecnt = 0;
597 if (renamecnt++ % DebugDiv != DebugMod)
600 dbgs() << "*** Performing rename " << TRI->getName(SuperReg) <<
605 // Check each possible rename register for SuperReg in round-robin
606 // order. If that register is available, and the corresponding
607 // registers are available for the other group subregisters, then we
608 // can use those registers to rename.
610 // FIXME: Using getMinimalPhysRegClass is very conservative. We should
611 // check every use of the register and find the largest register class
612 // that can be used in all of them.
613 const TargetRegisterClass *SuperRC =
614 TRI->getMinimalPhysRegClass(SuperReg, MVT::Other);
616 ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(SuperRC);
618 DEBUG(dbgs() << "\tEmpty Super Regclass!!\n");
622 DEBUG(dbgs() << "\tFind Registers:");
624 RenameOrder.insert(RenameOrderType::value_type(SuperRC, Order.size()));
626 unsigned OrigR = RenameOrder[SuperRC];
627 unsigned EndR = ((OrigR == Order.size()) ? 0 : OrigR);
630 if (R == 0) R = Order.size();
632 const unsigned NewSuperReg = Order[R];
633 // Don't consider non-allocatable registers
634 if (!MRI.isAllocatable(NewSuperReg)) continue;
635 // Don't replace a register with itself.
636 if (NewSuperReg == SuperReg) continue;
638 DEBUG(dbgs() << " [" << TRI->getName(NewSuperReg) << ':');
641 // For each referenced group register (which must be a SuperReg or
642 // a subregister of SuperReg), find the corresponding subregister
643 // of NewSuperReg and make sure it is free to be renamed.
644 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
645 unsigned Reg = Regs[i];
647 if (Reg == SuperReg) {
648 NewReg = NewSuperReg;
650 unsigned NewSubRegIdx = TRI->getSubRegIndex(SuperReg, Reg);
651 if (NewSubRegIdx != 0)
652 NewReg = TRI->getSubReg(NewSuperReg, NewSubRegIdx);
655 DEBUG(dbgs() << " " << TRI->getName(NewReg));
657 // Check if Reg can be renamed to NewReg.
658 if (!RenameRegisterMap[Reg].test(NewReg)) {
659 DEBUG(dbgs() << "(no rename)");
663 // If NewReg is dead and NewReg's most recent def is not before
664 // Regs's kill, it's safe to replace Reg with NewReg. We
665 // must also check all aliases of NewReg, because we can't define a
666 // register when any sub or super is already live.
667 if (State->IsLive(NewReg) || (KillIndices[Reg] > DefIndices[NewReg])) {
668 DEBUG(dbgs() << "(live)");
672 for (MCRegAliasIterator AI(NewReg, TRI, false); AI.isValid(); ++AI) {
673 unsigned AliasReg = *AI;
674 if (State->IsLive(AliasReg) ||
675 (KillIndices[Reg] > DefIndices[AliasReg])) {
676 DEBUG(dbgs() << "(alias " << TRI->getName(AliasReg) << " live)");
685 // We cannot rename 'Reg' to 'NewReg' if one of the uses of 'Reg' also
686 // defines 'NewReg' via an early-clobber operand.
687 for (const auto &Q : make_range(RegRefs.equal_range(Reg))) {
688 MachineInstr *UseMI = Q.second.Operand->getParent();
689 int Idx = UseMI->findRegisterDefOperandIdx(NewReg, false, true, TRI);
693 if (UseMI->getOperand(Idx).isEarlyClobber()) {
694 DEBUG(dbgs() << "(ec)");
699 // Also, we cannot rename 'Reg' to 'NewReg' if the instruction defining
700 // 'Reg' is an early-clobber define and that instruction also uses
702 for (const auto &Q : make_range(RegRefs.equal_range(Reg))) {
703 if (!Q.second.Operand->isDef() || !Q.second.Operand->isEarlyClobber())
706 MachineInstr *DefMI = Q.second.Operand->getParent();
707 if (DefMI->readsRegister(NewReg, TRI)) {
708 DEBUG(dbgs() << "(ec)");
713 // Record that 'Reg' can be renamed to 'NewReg'.
714 RenameMap.insert(std::pair<unsigned, unsigned>(Reg, NewReg));
717 // If we fall-out here, then every register in the group can be
718 // renamed, as recorded in RenameMap.
719 RenameOrder.erase(SuperRC);
720 RenameOrder.insert(RenameOrderType::value_type(SuperRC, R));
721 DEBUG(dbgs() << "]\n");
725 DEBUG(dbgs() << ']');
728 DEBUG(dbgs() << '\n');
730 // No registers are free and available!
734 /// BreakAntiDependencies - Identifiy anti-dependencies within the
735 /// ScheduleDAG and break them by renaming registers.
737 unsigned AggressiveAntiDepBreaker::BreakAntiDependencies(
738 const std::vector<SUnit>& SUnits,
739 MachineBasicBlock::iterator Begin,
740 MachineBasicBlock::iterator End,
741 unsigned InsertPosIndex,
742 DbgValueVector &DbgValues) {
744 std::vector<unsigned> &KillIndices = State->GetKillIndices();
745 std::vector<unsigned> &DefIndices = State->GetDefIndices();
746 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
747 RegRefs = State->GetRegRefs();
749 // The code below assumes that there is at least one instruction,
750 // so just duck out immediately if the block is empty.
751 if (SUnits.empty()) return 0;
753 // For each regclass the next register to use for renaming.
754 RenameOrderType RenameOrder;
756 // ...need a map from MI to SUnit.
757 std::map<MachineInstr *, const SUnit *> MISUnitMap;
758 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
759 const SUnit *SU = &SUnits[i];
760 MISUnitMap.insert(std::pair<MachineInstr *, const SUnit *>(SU->getInstr(),
764 // Track progress along the critical path through the SUnit graph as
765 // we walk the instructions. This is needed for regclasses that only
766 // break critical-path anti-dependencies.
767 const SUnit *CriticalPathSU = nullptr;
768 MachineInstr *CriticalPathMI = nullptr;
769 if (CriticalPathSet.any()) {
770 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
771 const SUnit *SU = &SUnits[i];
772 if (!CriticalPathSU ||
773 ((SU->getDepth() + SU->Latency) >
774 (CriticalPathSU->getDepth() + CriticalPathSU->Latency))) {
779 CriticalPathMI = CriticalPathSU->getInstr();
783 DEBUG(dbgs() << "\n===== Aggressive anti-dependency breaking\n");
784 DEBUG(dbgs() << "Available regs:");
785 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
786 if (!State->IsLive(Reg))
787 DEBUG(dbgs() << " " << TRI->getName(Reg));
789 DEBUG(dbgs() << '\n');
792 BitVector RegAliases(TRI->getNumRegs());
794 // Attempt to break anti-dependence edges. Walk the instructions
795 // from the bottom up, tracking information about liveness as we go
796 // to help determine which registers are available.
798 unsigned Count = InsertPosIndex - 1;
799 for (MachineBasicBlock::iterator I = End, E = Begin;
801 MachineInstr &MI = *--I;
803 if (MI.isDebugValue())
806 DEBUG(dbgs() << "Anti: ");
809 std::set<unsigned> PassthruRegs;
810 GetPassthruRegs(MI, PassthruRegs);
812 // Process the defs in MI...
813 PrescanInstruction(MI, Count, PassthruRegs);
815 // The dependence edges that represent anti- and output-
816 // dependencies that are candidates for breaking.
817 std::vector<const SDep *> Edges;
818 const SUnit *PathSU = MISUnitMap[&MI];
819 AntiDepEdges(PathSU, Edges);
821 // If MI is not on the critical path, then we don't rename
822 // registers in the CriticalPathSet.
823 BitVector *ExcludeRegs = nullptr;
824 if (&MI == CriticalPathMI) {
825 CriticalPathSU = CriticalPathStep(CriticalPathSU);
826 CriticalPathMI = (CriticalPathSU) ? CriticalPathSU->getInstr() : nullptr;
827 } else if (CriticalPathSet.any()) {
828 ExcludeRegs = &CriticalPathSet;
831 // Ignore KILL instructions (they form a group in ScanInstruction
832 // but don't cause any anti-dependence breaking themselves)
834 // Attempt to break each anti-dependency...
835 for (unsigned i = 0, e = Edges.size(); i != e; ++i) {
836 const SDep *Edge = Edges[i];
837 SUnit *NextSU = Edge->getSUnit();
839 if ((Edge->getKind() != SDep::Anti) &&
840 (Edge->getKind() != SDep::Output)) continue;
842 unsigned AntiDepReg = Edge->getReg();
843 DEBUG(dbgs() << "\tAntidep reg: " << TRI->getName(AntiDepReg));
844 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
846 if (!MRI.isAllocatable(AntiDepReg)) {
847 // Don't break anti-dependencies on non-allocatable registers.
848 DEBUG(dbgs() << " (non-allocatable)\n");
850 } else if (ExcludeRegs && ExcludeRegs->test(AntiDepReg)) {
851 // Don't break anti-dependencies for critical path registers
852 // if not on the critical path
853 DEBUG(dbgs() << " (not critical-path)\n");
855 } else if (PassthruRegs.count(AntiDepReg) != 0) {
856 // If the anti-dep register liveness "passes-thru", then
857 // don't try to change it. It will be changed along with
858 // the use if required to break an earlier antidep.
859 DEBUG(dbgs() << " (passthru)\n");
862 // No anti-dep breaking for implicit deps
863 MachineOperand *AntiDepOp = MI.findRegisterDefOperand(AntiDepReg);
864 assert(AntiDepOp && "Can't find index for defined register operand");
865 if (!AntiDepOp || AntiDepOp->isImplicit()) {
866 DEBUG(dbgs() << " (implicit)\n");
870 // If the SUnit has other dependencies on the SUnit that
871 // it anti-depends on, don't bother breaking the
872 // anti-dependency since those edges would prevent such
873 // units from being scheduled past each other
876 // Also, if there are dependencies on other SUnits with the
877 // same register as the anti-dependency, don't attempt to
879 for (SUnit::const_pred_iterator P = PathSU->Preds.begin(),
880 PE = PathSU->Preds.end(); P != PE; ++P) {
881 if (P->getSUnit() == NextSU ?
882 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
883 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
888 for (SUnit::const_pred_iterator P = PathSU->Preds.begin(),
889 PE = PathSU->Preds.end(); P != PE; ++P) {
890 if ((P->getSUnit() == NextSU) && (P->getKind() != SDep::Anti) &&
891 (P->getKind() != SDep::Output)) {
892 DEBUG(dbgs() << " (real dependency)\n");
895 } else if ((P->getSUnit() != NextSU) &&
896 (P->getKind() == SDep::Data) &&
897 (P->getReg() == AntiDepReg)) {
898 DEBUG(dbgs() << " (other dependency)\n");
904 if (AntiDepReg == 0) continue;
906 // If the definition of the anti-dependency register does not start
907 // a new live range, bail out. This can happen if the anti-dep
908 // register is a sub-register of another register whose live range
909 // spans over PathSU. In such case, PathSU defines only a part of
910 // the larger register.
912 for (MCRegAliasIterator AI(AntiDepReg, TRI, true); AI.isValid(); ++AI)
914 for (SDep S : PathSU->Succs) {
915 SDep::Kind K = S.getKind();
916 if (K != SDep::Data && K != SDep::Output && K != SDep::Anti)
918 unsigned R = S.getReg();
921 if (R == AntiDepReg || TRI->isSubRegister(AntiDepReg, R))
927 if (AntiDepReg == 0) continue;
930 assert(AntiDepReg != 0);
931 if (AntiDepReg == 0) continue;
933 // Determine AntiDepReg's register group.
934 const unsigned GroupIndex = State->GetGroup(AntiDepReg);
935 if (GroupIndex == 0) {
936 DEBUG(dbgs() << " (zero group)\n");
940 DEBUG(dbgs() << '\n');
942 // Look for a suitable register to use to break the anti-dependence.
943 std::map<unsigned, unsigned> RenameMap;
944 if (FindSuitableFreeRegisters(GroupIndex, RenameOrder, RenameMap)) {
945 DEBUG(dbgs() << "\tBreaking anti-dependence edge on "
946 << TRI->getName(AntiDepReg) << ":");
948 // Handle each group register...
949 for (std::map<unsigned, unsigned>::iterator
950 S = RenameMap.begin(), E = RenameMap.end(); S != E; ++S) {
951 unsigned CurrReg = S->first;
952 unsigned NewReg = S->second;
954 DEBUG(dbgs() << " " << TRI->getName(CurrReg) << "->" <<
955 TRI->getName(NewReg) << "(" <<
956 RegRefs.count(CurrReg) << " refs)");
958 // Update the references to the old register CurrReg to
959 // refer to the new register NewReg.
960 for (const auto &Q : make_range(RegRefs.equal_range(CurrReg))) {
961 Q.second.Operand->setReg(NewReg);
962 // If the SU for the instruction being updated has debug
963 // information related to the anti-dependency register, make
964 // sure to update that as well.
965 const SUnit *SU = MISUnitMap[Q.second.Operand->getParent()];
967 for (DbgValueVector::iterator DVI = DbgValues.begin(),
968 DVE = DbgValues.end(); DVI != DVE; ++DVI)
969 if (DVI->second == Q.second.Operand->getParent())
970 UpdateDbgValue(*DVI->first, AntiDepReg, NewReg);
973 // We just went back in time and modified history; the
974 // liveness information for CurrReg is now inconsistent. Set
975 // the state as if it were dead.
976 State->UnionGroups(NewReg, 0);
977 RegRefs.erase(NewReg);
978 DefIndices[NewReg] = DefIndices[CurrReg];
979 KillIndices[NewReg] = KillIndices[CurrReg];
981 State->UnionGroups(CurrReg, 0);
982 RegRefs.erase(CurrReg);
983 DefIndices[CurrReg] = KillIndices[CurrReg];
984 KillIndices[CurrReg] = ~0u;
985 assert(((KillIndices[CurrReg] == ~0u) !=
986 (DefIndices[CurrReg] == ~0u)) &&
987 "Kill and Def maps aren't consistent for AntiDepReg!");
991 DEBUG(dbgs() << '\n');
996 ScanInstruction(MI, Count);