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 #define DEBUG_TYPE "post-RA-sched"
18 #include "AggressiveAntiDepBreaker.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
32 AntiDepTrials("agg-antidep-trials",
33 cl::desc("Maximum number of anti-dependency breaking passes"),
34 cl::init(1), cl::Hidden);
36 AggressiveAntiDepState::AggressiveAntiDepState(MachineBasicBlock *BB) :
37 GroupNodes(TargetRegisterInfo::FirstVirtualRegister, 0) {
38 // Initialize all registers to be in their own group. Initially we
39 // assign the register to the same-indexed GroupNode.
40 for (unsigned i = 0; i < TargetRegisterInfo::FirstVirtualRegister; ++i)
41 GroupNodeIndices[i] = i;
43 // Initialize the indices to indicate that no registers are live.
44 std::fill(KillIndices, array_endof(KillIndices), ~0u);
45 std::fill(DefIndices, array_endof(DefIndices), BB->size());
48 unsigned AggressiveAntiDepState::GetGroup(unsigned Reg)
50 unsigned Node = GroupNodeIndices[Reg];
51 while (GroupNodes[Node] != Node)
52 Node = GroupNodes[Node];
57 void AggressiveAntiDepState::GetGroupRegs(
59 std::vector<unsigned> &Regs,
60 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference> *RegRefs)
62 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg) {
63 if ((GetGroup(Reg) == Group) && (RegRefs->count(Reg) > 0))
68 unsigned AggressiveAntiDepState::UnionGroups(unsigned Reg1, unsigned Reg2)
70 assert(GroupNodes[0] == 0 && "GroupNode 0 not parent!");
71 assert(GroupNodeIndices[0] == 0 && "Reg 0 not in Group 0!");
73 // find group for each register
74 unsigned Group1 = GetGroup(Reg1);
75 unsigned Group2 = GetGroup(Reg2);
77 // if either group is 0, then that must become the parent
78 unsigned Parent = (Group1 == 0) ? Group1 : Group2;
79 unsigned Other = (Parent == Group1) ? Group2 : Group1;
80 GroupNodes.at(Other) = Parent;
84 unsigned AggressiveAntiDepState::LeaveGroup(unsigned Reg)
86 // Create a new GroupNode for Reg. Reg's existing GroupNode must
87 // stay as is because there could be other GroupNodes referring to
89 unsigned idx = GroupNodes.size();
90 GroupNodes.push_back(idx);
91 GroupNodeIndices[Reg] = idx;
95 bool AggressiveAntiDepState::IsLive(unsigned Reg)
97 // KillIndex must be defined and DefIndex not defined for a register
99 return((KillIndices[Reg] != ~0u) && (DefIndices[Reg] == ~0u));
104 AggressiveAntiDepBreaker::
105 AggressiveAntiDepBreaker(MachineFunction& MFi,
106 TargetSubtarget::RegClassVector& CriticalPathRCs) :
107 AntiDepBreaker(), MF(MFi),
108 MRI(MF.getRegInfo()),
109 TRI(MF.getTarget().getRegisterInfo()),
110 AllocatableSet(TRI->getAllocatableSet(MF)),
111 State(NULL), SavedState(NULL) {
112 /* Collect a bitset of all registers that are only broken if they
113 are on the critical path. */
114 for (unsigned i = 0, e = CriticalPathRCs.size(); i < e; ++i) {
115 BitVector CPSet = TRI->getAllocatableSet(MF, CriticalPathRCs[i]);
116 if (CriticalPathSet.none())
117 CriticalPathSet = CPSet;
119 CriticalPathSet |= CPSet;
122 DEBUG(errs() << "AntiDep Critical-Path Registers:");
123 DEBUG(for (int r = CriticalPathSet.find_first(); r != -1;
124 r = CriticalPathSet.find_next(r))
125 errs() << " " << TRI->getName(r));
126 DEBUG(errs() << '\n');
129 AggressiveAntiDepBreaker::~AggressiveAntiDepBreaker() {
134 unsigned AggressiveAntiDepBreaker::GetMaxTrials() {
135 if (AntiDepTrials <= 0)
137 return AntiDepTrials;
140 void AggressiveAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
141 assert(State == NULL);
142 State = new AggressiveAntiDepState(BB);
144 bool IsReturnBlock = (!BB->empty() && BB->back().getDesc().isReturn());
145 unsigned *KillIndices = State->GetKillIndices();
146 unsigned *DefIndices = State->GetDefIndices();
148 // Determine the live-out physregs for this block.
150 // In a return block, examine the function live-out regs.
151 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
152 E = MRI.liveout_end(); I != E; ++I) {
154 State->UnionGroups(Reg, 0);
155 KillIndices[Reg] = BB->size();
156 DefIndices[Reg] = ~0u;
157 // Repeat, for all aliases.
158 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
159 unsigned AliasReg = *Alias;
160 State->UnionGroups(AliasReg, 0);
161 KillIndices[AliasReg] = BB->size();
162 DefIndices[AliasReg] = ~0u;
166 // In a non-return block, examine the live-in regs of all successors.
167 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
168 SE = BB->succ_end(); SI != SE; ++SI)
169 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
170 E = (*SI)->livein_end(); I != E; ++I) {
172 State->UnionGroups(Reg, 0);
173 KillIndices[Reg] = BB->size();
174 DefIndices[Reg] = ~0u;
175 // Repeat, for all aliases.
176 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
177 unsigned AliasReg = *Alias;
178 State->UnionGroups(AliasReg, 0);
179 KillIndices[AliasReg] = BB->size();
180 DefIndices[AliasReg] = ~0u;
185 // Mark live-out callee-saved registers. In a return block this is
186 // all callee-saved registers. In non-return this is any
187 // callee-saved register that is not saved in the prolog.
188 const MachineFrameInfo *MFI = MF.getFrameInfo();
189 BitVector Pristine = MFI->getPristineRegs(BB);
190 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
192 if (!IsReturnBlock && !Pristine.test(Reg)) continue;
193 State->UnionGroups(Reg, 0);
194 KillIndices[Reg] = BB->size();
195 DefIndices[Reg] = ~0u;
196 // Repeat, for all aliases.
197 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
198 unsigned AliasReg = *Alias;
199 State->UnionGroups(AliasReg, 0);
200 KillIndices[AliasReg] = BB->size();
201 DefIndices[AliasReg] = ~0u;
206 void AggressiveAntiDepBreaker::FinishBlock() {
213 void AggressiveAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
214 unsigned InsertPosIndex) {
215 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
217 std::set<unsigned> PassthruRegs;
218 GetPassthruRegs(MI, PassthruRegs);
219 PrescanInstruction(MI, Count, PassthruRegs);
220 ScanInstruction(MI, Count);
222 DEBUG(errs() << "Observe: ");
224 DEBUG(errs() << "\tRegs:");
226 unsigned *DefIndices = State->GetDefIndices();
227 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg) {
228 // If Reg is current live, then mark that it can't be renamed as
229 // we don't know the extent of its live-range anymore (now that it
230 // has been scheduled). If it is not live but was defined in the
231 // previous schedule region, then set its def index to the most
232 // conservative location (i.e. the beginning of the previous
234 if (State->IsLive(Reg)) {
235 DEBUG(if (State->GetGroup(Reg) != 0)
236 errs() << " " << TRI->getName(Reg) << "=g" <<
237 State->GetGroup(Reg) << "->g0(region live-out)");
238 State->UnionGroups(Reg, 0);
239 } else if ((DefIndices[Reg] < InsertPosIndex) && (DefIndices[Reg] >= Count)) {
240 DefIndices[Reg] = Count;
243 DEBUG(errs() << '\n');
245 // We're starting a new schedule region so forget any saved state.
250 bool AggressiveAntiDepBreaker::IsImplicitDefUse(MachineInstr *MI,
253 if (!MO.isReg() || !MO.isImplicit())
256 unsigned Reg = MO.getReg();
260 MachineOperand *Op = NULL;
262 Op = MI->findRegisterUseOperand(Reg, true);
264 Op = MI->findRegisterDefOperand(Reg);
266 return((Op != NULL) && Op->isImplicit());
269 void AggressiveAntiDepBreaker::GetPassthruRegs(MachineInstr *MI,
270 std::set<unsigned>& PassthruRegs) {
271 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
272 MachineOperand &MO = MI->getOperand(i);
273 if (!MO.isReg()) continue;
274 if ((MO.isDef() && MI->isRegTiedToUseOperand(i)) ||
275 IsImplicitDefUse(MI, MO)) {
276 const unsigned Reg = MO.getReg();
277 PassthruRegs.insert(Reg);
278 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
280 PassthruRegs.insert(*Subreg);
286 /// AntiDepEdges - Return in Edges the anti- and output-
287 /// dependencies on Regs in SU that we want to consider for breaking.
288 static void AntiDepEdges(SUnit *SU,
289 const AntiDepBreaker::AntiDepRegVector& Regs,
290 std::vector<SDep*>& Edges) {
291 AntiDepBreaker::AntiDepRegSet RegSet;
292 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
293 RegSet.insert(Regs[i]);
295 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
297 if ((P->getKind() == SDep::Anti) || (P->getKind() == SDep::Output)) {
298 unsigned Reg = P->getReg();
299 if (RegSet.count(Reg) != 0) {
300 Edges.push_back(&*P);
306 assert(RegSet.empty() && "Expected all antidep registers to be found");
309 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
311 static SUnit *CriticalPathStep(SUnit *SU) {
313 unsigned NextDepth = 0;
314 // Find the predecessor edge with the greatest depth.
316 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
318 SUnit *PredSU = P->getSUnit();
319 unsigned PredLatency = P->getLatency();
320 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
321 // In the case of a latency tie, prefer an anti-dependency edge over
322 // other types of edges.
323 if (NextDepth < PredTotalLatency ||
324 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
325 NextDepth = PredTotalLatency;
331 return (Next) ? Next->getSUnit() : 0;
334 void AggressiveAntiDepBreaker::HandleLastUse(unsigned Reg, unsigned KillIdx,
336 unsigned *KillIndices = State->GetKillIndices();
337 unsigned *DefIndices = State->GetDefIndices();
338 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
339 RegRefs = State->GetRegRefs();
341 if (!State->IsLive(Reg)) {
342 KillIndices[Reg] = KillIdx;
343 DefIndices[Reg] = ~0u;
345 State->LeaveGroup(Reg);
346 DEBUG(errs() << "->g" << State->GetGroup(Reg) << tag);
348 // Repeat for subregisters.
349 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
351 unsigned SubregReg = *Subreg;
352 if (!State->IsLive(SubregReg)) {
353 KillIndices[SubregReg] = KillIdx;
354 DefIndices[SubregReg] = ~0u;
355 RegRefs.erase(SubregReg);
356 State->LeaveGroup(SubregReg);
357 DEBUG(errs() << " " << TRI->getName(SubregReg) << "->g" <<
358 State->GetGroup(SubregReg) << tag);
363 void AggressiveAntiDepBreaker::PrescanInstruction(MachineInstr *MI, unsigned Count,
364 std::set<unsigned>& PassthruRegs) {
365 unsigned *DefIndices = State->GetDefIndices();
366 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
367 RegRefs = State->GetRegRefs();
369 // Handle dead defs by simulating a last-use of the register just
370 // after the def. A dead def can occur because the def is truely
371 // dead, or because only a subregister is live at the def. If we
372 // don't do this the dead def will be incorrectly merged into the
374 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
375 MachineOperand &MO = MI->getOperand(i);
376 if (!MO.isReg() || !MO.isDef()) continue;
377 unsigned Reg = MO.getReg();
378 if (Reg == 0) continue;
380 DEBUG(errs() << "\tDead Def: " << TRI->getName(Reg));
381 HandleLastUse(Reg, Count + 1, "");
382 DEBUG(errs() << '\n');
385 DEBUG(errs() << "\tDef Groups:");
386 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
387 MachineOperand &MO = MI->getOperand(i);
388 if (!MO.isReg() || !MO.isDef()) continue;
389 unsigned Reg = MO.getReg();
390 if (Reg == 0) continue;
392 DEBUG(errs() << " " << TRI->getName(Reg) << "=g" << State->GetGroup(Reg));
394 // If MI's defs have a special allocation requirement, don't allow
395 // any def registers to be changed. Also assume all registers
396 // defined in a call must not be changed (ABI).
397 if (MI->getDesc().isCall() || MI->getDesc().hasExtraDefRegAllocReq()) {
398 DEBUG(if (State->GetGroup(Reg) != 0) errs() << "->g0(alloc-req)");
399 State->UnionGroups(Reg, 0);
402 // Any aliased that are live at this point are completely or
403 // partially defined here, so group those aliases with Reg.
404 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
405 unsigned AliasReg = *Alias;
406 if (State->IsLive(AliasReg)) {
407 State->UnionGroups(Reg, AliasReg);
408 DEBUG(errs() << "->g" << State->GetGroup(Reg) << "(via " <<
409 TRI->getName(AliasReg) << ")");
413 // Note register reference...
414 const TargetRegisterClass *RC = NULL;
415 if (i < MI->getDesc().getNumOperands())
416 RC = MI->getDesc().OpInfo[i].getRegClass(TRI);
417 AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
418 RegRefs.insert(std::make_pair(Reg, RR));
421 DEBUG(errs() << '\n');
423 // Scan the register defs for this instruction and update
425 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
426 MachineOperand &MO = MI->getOperand(i);
427 if (!MO.isReg() || !MO.isDef()) continue;
428 unsigned Reg = MO.getReg();
429 if (Reg == 0) continue;
430 // Ignore passthru registers for liveness...
431 if (PassthruRegs.count(Reg) != 0) continue;
433 // Update def for Reg and subregs.
434 DefIndices[Reg] = Count;
435 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
437 unsigned SubregReg = *Subreg;
438 DefIndices[SubregReg] = Count;
443 void AggressiveAntiDepBreaker::ScanInstruction(MachineInstr *MI,
445 DEBUG(errs() << "\tUse Groups:");
446 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
447 RegRefs = State->GetRegRefs();
449 // Scan the register uses for this instruction and update
450 // live-ranges, groups and RegRefs.
451 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
452 MachineOperand &MO = MI->getOperand(i);
453 if (!MO.isReg() || !MO.isUse()) continue;
454 unsigned Reg = MO.getReg();
455 if (Reg == 0) continue;
457 DEBUG(errs() << " " << TRI->getName(Reg) << "=g" <<
458 State->GetGroup(Reg));
460 // It wasn't previously live but now it is, this is a kill. Forget
461 // the previous live-range information and start a new live-range
463 HandleLastUse(Reg, Count, "(last-use)");
465 // If MI's uses have special allocation requirement, don't allow
466 // any use registers to be changed. Also assume all registers
467 // used in a call must not be changed (ABI).
468 if (MI->getDesc().isCall() || MI->getDesc().hasExtraSrcRegAllocReq()) {
469 DEBUG(if (State->GetGroup(Reg) != 0) errs() << "->g0(alloc-req)");
470 State->UnionGroups(Reg, 0);
473 // Note register reference...
474 const TargetRegisterClass *RC = NULL;
475 if (i < MI->getDesc().getNumOperands())
476 RC = MI->getDesc().OpInfo[i].getRegClass(TRI);
477 AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
478 RegRefs.insert(std::make_pair(Reg, RR));
481 DEBUG(errs() << '\n');
483 // Form a group of all defs and uses of a KILL instruction to ensure
484 // that all registers are renamed as a group.
485 if (MI->getOpcode() == TargetInstrInfo::KILL) {
486 DEBUG(errs() << "\tKill Group:");
488 unsigned FirstReg = 0;
489 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
490 MachineOperand &MO = MI->getOperand(i);
491 if (!MO.isReg()) continue;
492 unsigned Reg = MO.getReg();
493 if (Reg == 0) continue;
496 DEBUG(errs() << "=" << TRI->getName(Reg));
497 State->UnionGroups(FirstReg, Reg);
499 DEBUG(errs() << " " << TRI->getName(Reg));
504 DEBUG(errs() << "->g" << State->GetGroup(FirstReg) << '\n');
508 BitVector AggressiveAntiDepBreaker::GetRenameRegisters(unsigned Reg) {
509 BitVector BV(TRI->getNumRegs(), false);
512 // Check all references that need rewriting for Reg. For each, use
513 // the corresponding register class to narrow the set of registers
514 // that are appropriate for renaming.
515 std::pair<std::multimap<unsigned,
516 AggressiveAntiDepState::RegisterReference>::iterator,
517 std::multimap<unsigned,
518 AggressiveAntiDepState::RegisterReference>::iterator>
519 Range = State->GetRegRefs().equal_range(Reg);
520 for (std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>::iterator
521 Q = Range.first, QE = Range.second; Q != QE; ++Q) {
522 const TargetRegisterClass *RC = Q->second.RC;
523 if (RC == NULL) continue;
525 BitVector RCBV = TRI->getAllocatableSet(MF, RC);
533 DEBUG(errs() << " " << RC->getName());
539 bool AggressiveAntiDepBreaker::FindSuitableFreeRegisters(
540 unsigned AntiDepGroupIndex,
541 RenameOrderType& RenameOrder,
542 std::map<unsigned, unsigned> &RenameMap) {
543 unsigned *KillIndices = State->GetKillIndices();
544 unsigned *DefIndices = State->GetDefIndices();
545 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
546 RegRefs = State->GetRegRefs();
548 // Collect all referenced registers in the same group as
549 // AntiDepReg. These all need to be renamed together if we are to
550 // break the anti-dependence.
551 std::vector<unsigned> Regs;
552 State->GetGroupRegs(AntiDepGroupIndex, Regs, &RegRefs);
553 assert(Regs.size() > 0 && "Empty register group!");
554 if (Regs.size() == 0)
557 // Find the "superest" register in the group. At the same time,
558 // collect the BitVector of registers that can be used to rename
560 DEBUG(errs() << "\tRename Candidates for Group g" << AntiDepGroupIndex << ":\n");
561 std::map<unsigned, BitVector> RenameRegisterMap;
562 unsigned SuperReg = 0;
563 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
564 unsigned Reg = Regs[i];
565 if ((SuperReg == 0) || TRI->isSuperRegister(SuperReg, Reg))
568 // If Reg has any references, then collect possible rename regs
569 if (RegRefs.count(Reg) > 0) {
570 DEBUG(errs() << "\t\t" << TRI->getName(Reg) << ":");
572 BitVector BV = GetRenameRegisters(Reg);
573 RenameRegisterMap.insert(std::pair<unsigned, BitVector>(Reg, BV));
575 DEBUG(errs() << " ::");
576 DEBUG(for (int r = BV.find_first(); r != -1; r = BV.find_next(r))
577 errs() << " " << TRI->getName(r));
578 DEBUG(errs() << "\n");
582 // All group registers should be a subreg of SuperReg.
583 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
584 unsigned Reg = Regs[i];
585 if (Reg == SuperReg) continue;
586 bool IsSub = TRI->isSubRegister(SuperReg, Reg);
587 assert(IsSub && "Expecting group subregister");
592 // FIXME: for now just handle single register in group case...
593 if (Regs.size() > 1) {
594 DEBUG(errs() << "\tMultiple rename registers in group\n");
598 // Check each possible rename register for SuperReg in round-robin
599 // order. If that register is available, and the corresponding
600 // registers are available for the other group subregisters, then we
601 // can use those registers to rename.
602 BitVector SuperBV = RenameRegisterMap[SuperReg];
603 const TargetRegisterClass *SuperRC =
604 TRI->getPhysicalRegisterRegClass(SuperReg, MVT::Other);
606 const TargetRegisterClass::iterator RB = SuperRC->allocation_order_begin(MF);
607 const TargetRegisterClass::iterator RE = SuperRC->allocation_order_end(MF);
609 DEBUG(errs() << "\tEmpty Regclass!!\n");
613 if (RenameOrder.count(SuperRC) == 0)
614 RenameOrder.insert(RenameOrderType::value_type(SuperRC, RE));
616 DEBUG(errs() << "\tFind Register:");
618 const TargetRegisterClass::iterator OrigR = RenameOrder[SuperRC];
619 const TargetRegisterClass::iterator EndR = ((OrigR == RE) ? RB : OrigR);
620 TargetRegisterClass::iterator R = OrigR;
624 const unsigned Reg = *R;
625 // Don't replace a register with itself.
626 if (Reg == SuperReg) continue;
628 DEBUG(errs() << " " << TRI->getName(Reg));
630 // If Reg is dead and Reg's most recent def is not before
631 // SuperRegs's kill, it's safe to replace SuperReg with Reg. We
632 // must also check all subregisters of Reg.
633 if (State->IsLive(Reg) || (KillIndices[SuperReg] > DefIndices[Reg])) {
634 DEBUG(errs() << "(live)");
638 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
640 unsigned SubregReg = *Subreg;
641 if (State->IsLive(SubregReg) || (KillIndices[SuperReg] > DefIndices[SubregReg])) {
642 DEBUG(errs() << "(subreg " << TRI->getName(SubregReg) << " live)");
652 DEBUG(errs() << '\n');
653 RenameOrder.erase(SuperRC);
654 RenameOrder.insert(RenameOrderType::value_type(SuperRC, R));
655 RenameMap.insert(std::pair<unsigned, unsigned>(SuperReg, Reg));
660 DEBUG(errs() << '\n');
662 // No registers are free and available!
666 /// BreakAntiDependencies - Identifiy anti-dependencies within the
667 /// ScheduleDAG and break them by renaming registers.
669 unsigned AggressiveAntiDepBreaker::BreakAntiDependencies(
670 std::vector<SUnit>& SUnits,
671 CandidateMap& Candidates,
672 MachineBasicBlock::iterator& Begin,
673 MachineBasicBlock::iterator& End,
674 unsigned InsertPosIndex) {
675 unsigned *KillIndices = State->GetKillIndices();
676 unsigned *DefIndices = State->GetDefIndices();
677 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
678 RegRefs = State->GetRegRefs();
680 // The code below assumes that there is at least one instruction,
681 // so just duck out immediately if the block is empty.
682 if (SUnits.empty()) return 0;
684 // Manage saved state to enable multiple passes...
685 if (AntiDepTrials > 1) {
686 if (SavedState == NULL) {
687 SavedState = new AggressiveAntiDepState(*State);
690 State = new AggressiveAntiDepState(*SavedState);
694 // For each regclass the next register to use for renaming.
695 RenameOrderType RenameOrder;
697 // ...need a map from MI to SUnit.
698 std::map<MachineInstr *, SUnit *> MISUnitMap;
699 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
700 SUnit *SU = &SUnits[i];
701 MISUnitMap.insert(std::pair<MachineInstr *, SUnit *>(SU->getInstr(), SU));
704 // Track progress along the critical path through the SUnit graph as
705 // we walk the instructions. This is needed for regclasses that only
706 // break critical-path anti-dependencies.
707 SUnit *CriticalPathSU = 0;
708 MachineInstr *CriticalPathMI = 0;
709 if (CriticalPathSet.any()) {
710 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
711 SUnit *SU = &SUnits[i];
712 if (!CriticalPathSU ||
713 ((SU->getDepth() + SU->Latency) >
714 (CriticalPathSU->getDepth() + CriticalPathSU->Latency))) {
719 CriticalPathMI = CriticalPathSU->getInstr();
722 // Even if there are no anti-dependencies we still need to go
723 // through the instructions to update Def, Kills, etc.
725 if (Candidates.empty()) {
726 DEBUG(errs() << "\n===== No anti-dependency candidates\n");
728 DEBUG(errs() << "\n===== Attempting to break " << Candidates.size() <<
729 " anti-dependencies\n");
730 DEBUG(errs() << "Available regs:");
731 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
732 if (!State->IsLive(Reg))
733 DEBUG(errs() << " " << TRI->getName(Reg));
735 DEBUG(errs() << '\n');
739 // Attempt to break anti-dependence edges. Walk the instructions
740 // from the bottom up, tracking information about liveness as we go
741 // to help determine which registers are available.
743 unsigned Count = InsertPosIndex - 1;
744 for (MachineBasicBlock::iterator I = End, E = Begin;
746 MachineInstr *MI = --I;
748 DEBUG(errs() << "Anti: ");
751 std::set<unsigned> PassthruRegs;
752 GetPassthruRegs(MI, PassthruRegs);
754 // Process the defs in MI...
755 PrescanInstruction(MI, Count, PassthruRegs);
757 // The the dependence edges that represent anti- and output-
758 // dependencies that are candidates for breaking.
759 std::vector<SDep*> Edges;
760 SUnit *PathSU = MISUnitMap[MI];
761 AntiDepBreaker::CandidateMap::iterator
762 citer = Candidates.find(PathSU);
763 if (citer != Candidates.end())
764 AntiDepEdges(PathSU, citer->second, Edges);
766 // If MI is not on the critical path, then we don't rename
767 // registers in the CriticalPathSet.
768 BitVector *ExcludeRegs = NULL;
769 if (MI == CriticalPathMI) {
770 CriticalPathSU = CriticalPathStep(CriticalPathSU);
771 CriticalPathMI = (CriticalPathSU) ? CriticalPathSU->getInstr() : 0;
773 ExcludeRegs = &CriticalPathSet;
776 // Ignore KILL instructions (they form a group in ScanInstruction
777 // but don't cause any anti-dependence breaking themselves)
778 if (MI->getOpcode() != TargetInstrInfo::KILL) {
779 // Attempt to break each anti-dependency...
780 for (unsigned i = 0, e = Edges.size(); i != e; ++i) {
781 SDep *Edge = Edges[i];
782 SUnit *NextSU = Edge->getSUnit();
784 if ((Edge->getKind() != SDep::Anti) &&
785 (Edge->getKind() != SDep::Output)) continue;
787 unsigned AntiDepReg = Edge->getReg();
788 DEBUG(errs() << "\tAntidep reg: " << TRI->getName(AntiDepReg));
789 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
791 if (!AllocatableSet.test(AntiDepReg)) {
792 // Don't break anti-dependencies on non-allocatable registers.
793 DEBUG(errs() << " (non-allocatable)\n");
795 } else if ((ExcludeRegs != NULL) && ExcludeRegs->test(AntiDepReg)) {
796 // Don't break anti-dependencies for critical path registers
797 // if not on the critical path
798 DEBUG(errs() << " (not critical-path)\n");
800 } else if (PassthruRegs.count(AntiDepReg) != 0) {
801 // If the anti-dep register liveness "passes-thru", then
802 // don't try to change it. It will be changed along with
803 // the use if required to break an earlier antidep.
804 DEBUG(errs() << " (passthru)\n");
807 // No anti-dep breaking for implicit deps
808 MachineOperand *AntiDepOp = MI->findRegisterDefOperand(AntiDepReg);
809 assert(AntiDepOp != NULL && "Can't find index for defined register operand");
810 if ((AntiDepOp == NULL) || AntiDepOp->isImplicit()) {
811 DEBUG(errs() << " (implicit)\n");
815 // If the SUnit has other dependencies on the SUnit that
816 // it anti-depends on, don't bother breaking the
817 // anti-dependency since those edges would prevent such
818 // units from being scheduled past each other
820 for (SUnit::pred_iterator P = PathSU->Preds.begin(),
821 PE = PathSU->Preds.end(); P != PE; ++P) {
822 if ((P->getSUnit() == NextSU) && (P->getKind() != SDep::Anti)) {
823 DEBUG(errs() << " (real dependency)\n");
829 if (AntiDepReg == 0) continue;
832 assert(AntiDepReg != 0);
833 if (AntiDepReg == 0) continue;
835 // Determine AntiDepReg's register group.
836 const unsigned GroupIndex = State->GetGroup(AntiDepReg);
837 if (GroupIndex == 0) {
838 DEBUG(errs() << " (zero group)\n");
842 DEBUG(errs() << '\n');
844 // Look for a suitable register to use to break the anti-dependence.
845 std::map<unsigned, unsigned> RenameMap;
846 if (FindSuitableFreeRegisters(GroupIndex, RenameOrder, RenameMap)) {
847 DEBUG(errs() << "\tBreaking anti-dependence edge on "
848 << TRI->getName(AntiDepReg) << ":");
850 // Handle each group register...
851 for (std::map<unsigned, unsigned>::iterator
852 S = RenameMap.begin(), E = RenameMap.end(); S != E; ++S) {
853 unsigned CurrReg = S->first;
854 unsigned NewReg = S->second;
856 DEBUG(errs() << " " << TRI->getName(CurrReg) << "->" <<
857 TRI->getName(NewReg) << "(" <<
858 RegRefs.count(CurrReg) << " refs)");
860 // Update the references to the old register CurrReg to
861 // refer to the new register NewReg.
862 std::pair<std::multimap<unsigned,
863 AggressiveAntiDepState::RegisterReference>::iterator,
864 std::multimap<unsigned,
865 AggressiveAntiDepState::RegisterReference>::iterator>
866 Range = RegRefs.equal_range(CurrReg);
867 for (std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>::iterator
868 Q = Range.first, QE = Range.second; Q != QE; ++Q) {
869 Q->second.Operand->setReg(NewReg);
872 // We just went back in time and modified history; the
873 // liveness information for CurrReg is now inconsistent. Set
874 // the state as if it were dead.
875 State->UnionGroups(NewReg, 0);
876 RegRefs.erase(NewReg);
877 DefIndices[NewReg] = DefIndices[CurrReg];
878 KillIndices[NewReg] = KillIndices[CurrReg];
880 State->UnionGroups(CurrReg, 0);
881 RegRefs.erase(CurrReg);
882 DefIndices[CurrReg] = KillIndices[CurrReg];
883 KillIndices[CurrReg] = ~0u;
884 assert(((KillIndices[CurrReg] == ~0u) !=
885 (DefIndices[CurrReg] == ~0u)) &&
886 "Kill and Def maps aren't consistent for AntiDepReg!");
890 DEBUG(errs() << '\n');
895 ScanInstruction(MI, Count);