874f018db9f92e1a206b41172851df5743cfb7db
[oota-llvm.git] / lib / CodeGen / AggressiveAntiDepBreaker.cpp
1 //===----- AggressiveAntiDepBreaker.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 AggressiveAntiDepBreaker class, which
11 // implements register anti-dependence breaking during post-RA
12 // scheduling. It attempts to break all anti-dependencies within a
13 // block.
14 //
15 //===----------------------------------------------------------------------===//
16
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/TargetInstrInfo.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"
29 using namespace llvm;
30
31 // If DebugDiv > 0 then only break antidep with (ID % DebugDiv) == DebugMod
32 static cl::opt<int>
33 DebugDiv("agg-antidep-debugdiv",
34          cl::desc("Debug control for aggressive anti-dep breaker"),
35          cl::init(0), cl::Hidden);
36 static cl::opt<int>
37 DebugMod("agg-antidep-debugmod",
38          cl::desc("Debug control for aggressive anti-dep breaker"),
39          cl::init(0), cl::Hidden);
40
41 AggressiveAntiDepState::AggressiveAntiDepState(const unsigned TargetRegs,
42                                                MachineBasicBlock *BB) :
43   NumTargetRegs(TargetRegs), GroupNodes(TargetRegs, 0) {
44   KillIndices.reserve(TargetRegs);
45   DefIndices.reserve(TargetRegs);
46
47   const unsigned BBSize = BB->size();
48   for (unsigned i = 0; i < NumTargetRegs; ++i) {
49     // Initialize all registers to be in their own group. Initially we
50     // assign the register to the same-indexed GroupNode.
51     GroupNodeIndices[i] = i;
52     // Initialize the indices to indicate that no registers are live.
53     KillIndices[i] = ~0u;
54     DefIndices[i] = BBSize;
55   }
56 }
57
58 unsigned AggressiveAntiDepState::GetGroup(unsigned Reg)
59 {
60   unsigned Node = GroupNodeIndices[Reg];
61   while (GroupNodes[Node] != Node)
62     Node = GroupNodes[Node];
63
64   return Node;
65 }
66
67 void AggressiveAntiDepState::GetGroupRegs(
68   unsigned Group,
69   std::vector<unsigned> &Regs,
70   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference> *RegRefs)
71 {
72   for (unsigned Reg = 0; Reg != NumTargetRegs; ++Reg) {
73     if ((GetGroup(Reg) == Group) && (RegRefs->count(Reg) > 0))
74       Regs.push_back(Reg);
75   }
76 }
77
78 unsigned AggressiveAntiDepState::UnionGroups(unsigned Reg1, unsigned Reg2)
79 {
80   assert(GroupNodes[0] == 0 && "GroupNode 0 not parent!");
81   assert(GroupNodeIndices[0] == 0 && "Reg 0 not in Group 0!");
82
83   // find group for each register
84   unsigned Group1 = GetGroup(Reg1);
85   unsigned Group2 = GetGroup(Reg2);
86
87   // if either group is 0, then that must become the parent
88   unsigned Parent = (Group1 == 0) ? Group1 : Group2;
89   unsigned Other = (Parent == Group1) ? Group2 : Group1;
90   GroupNodes.at(Other) = Parent;
91   return Parent;
92 }
93
94 unsigned AggressiveAntiDepState::LeaveGroup(unsigned Reg)
95 {
96   // Create a new GroupNode for Reg. Reg's existing GroupNode must
97   // stay as is because there could be other GroupNodes referring to
98   // it.
99   unsigned idx = GroupNodes.size();
100   GroupNodes.push_back(idx);
101   GroupNodeIndices[Reg] = idx;
102   return idx;
103 }
104
105 bool AggressiveAntiDepState::IsLive(unsigned Reg)
106 {
107   // KillIndex must be defined and DefIndex not defined for a register
108   // to be live.
109   return((KillIndices[Reg] != ~0u) && (DefIndices[Reg] == ~0u));
110 }
111
112
113
114 AggressiveAntiDepBreaker::
115 AggressiveAntiDepBreaker(MachineFunction& MFi,
116                          TargetSubtarget::RegClassVector& CriticalPathRCs) :
117   AntiDepBreaker(), MF(MFi),
118   MRI(MF.getRegInfo()),
119   TII(MF.getTarget().getInstrInfo()),
120   TRI(MF.getTarget().getRegisterInfo()),
121   AllocatableSet(TRI->getAllocatableSet(MF)),
122   State(NULL) {
123   /* Collect a bitset of all registers that are only broken if they
124      are on the critical path. */
125   for (unsigned i = 0, e = CriticalPathRCs.size(); i < e; ++i) {
126     BitVector CPSet = TRI->getAllocatableSet(MF, CriticalPathRCs[i]);
127     if (CriticalPathSet.none())
128       CriticalPathSet = CPSet;
129     else
130       CriticalPathSet |= CPSet;
131    }
132
133   DEBUG(dbgs() << "AntiDep Critical-Path Registers:");
134   DEBUG(for (int r = CriticalPathSet.find_first(); r != -1;
135              r = CriticalPathSet.find_next(r))
136           dbgs() << " " << TRI->getName(r));
137   DEBUG(dbgs() << '\n');
138 }
139
140 AggressiveAntiDepBreaker::~AggressiveAntiDepBreaker() {
141   delete State;
142 }
143
144 void AggressiveAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
145   assert(State == NULL);
146   State = new AggressiveAntiDepState(TRI->getNumRegs(), BB);
147
148   bool IsReturnBlock = (!BB->empty() && BB->back().getDesc().isReturn());
149   std::vector<unsigned> &KillIndices = State->GetKillIndices();
150   std::vector<unsigned> &DefIndices = State->GetDefIndices();
151
152   // Determine the live-out physregs for this block.
153   if (IsReturnBlock) {
154     // In a return block, examine the function live-out regs.
155     for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
156          E = MRI.liveout_end(); I != E; ++I) {
157       unsigned Reg = *I;
158       State->UnionGroups(Reg, 0);
159       KillIndices[Reg] = BB->size();
160       DefIndices[Reg] = ~0u;
161       // Repeat, for all aliases.
162       for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
163         unsigned AliasReg = *Alias;
164         State->UnionGroups(AliasReg, 0);
165         KillIndices[AliasReg] = BB->size();
166         DefIndices[AliasReg] = ~0u;
167       }
168     }
169   }
170
171   // In a non-return block, examine the live-in regs of all successors.
172   // Note a return block can have successors if the return instruction is
173   // predicated.
174   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
175          SE = BB->succ_end(); SI != SE; ++SI)
176     for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
177            E = (*SI)->livein_end(); I != E; ++I) {
178       unsigned Reg = *I;
179       State->UnionGroups(Reg, 0);
180       KillIndices[Reg] = BB->size();
181       DefIndices[Reg] = ~0u;
182       // Repeat, for all aliases.
183       for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
184         unsigned AliasReg = *Alias;
185         State->UnionGroups(AliasReg, 0);
186         KillIndices[AliasReg] = BB->size();
187         DefIndices[AliasReg] = ~0u;
188       }
189     }
190
191   // Mark live-out callee-saved registers. In a return block this is
192   // all callee-saved registers. In non-return this is any
193   // callee-saved register that is not saved in the prolog.
194   const MachineFrameInfo *MFI = MF.getFrameInfo();
195   BitVector Pristine = MFI->getPristineRegs(BB);
196   for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
197     unsigned Reg = *I;
198     if (!IsReturnBlock && !Pristine.test(Reg)) continue;
199     State->UnionGroups(Reg, 0);
200     KillIndices[Reg] = BB->size();
201     DefIndices[Reg] = ~0u;
202     // Repeat, for all aliases.
203     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
204       unsigned AliasReg = *Alias;
205       State->UnionGroups(AliasReg, 0);
206       KillIndices[AliasReg] = BB->size();
207       DefIndices[AliasReg] = ~0u;
208     }
209   }
210 }
211
212 void AggressiveAntiDepBreaker::FinishBlock() {
213   delete State;
214   State = NULL;
215 }
216
217 void AggressiveAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
218                                        unsigned InsertPosIndex) {
219   assert(Count < InsertPosIndex && "Instruction index out of expected range!");
220
221   std::set<unsigned> PassthruRegs;
222   GetPassthruRegs(MI, PassthruRegs);
223   PrescanInstruction(MI, Count, PassthruRegs);
224   ScanInstruction(MI, Count);
225
226   DEBUG(dbgs() << "Observe: ");
227   DEBUG(MI->dump());
228   DEBUG(dbgs() << "\tRegs:");
229
230   std::vector<unsigned> &DefIndices = State->GetDefIndices();
231   for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
232     // If Reg is current live, then mark that it can't be renamed as
233     // we don't know the extent of its live-range anymore (now that it
234     // has been scheduled). If it is not live but was defined in the
235     // previous schedule region, then set its def index to the most
236     // conservative location (i.e. the beginning of the previous
237     // schedule region).
238     if (State->IsLive(Reg)) {
239       DEBUG(if (State->GetGroup(Reg) != 0)
240               dbgs() << " " << TRI->getName(Reg) << "=g" <<
241                 State->GetGroup(Reg) << "->g0(region live-out)");
242       State->UnionGroups(Reg, 0);
243     } else if ((DefIndices[Reg] < InsertPosIndex)
244                && (DefIndices[Reg] >= Count)) {
245       DefIndices[Reg] = Count;
246     }
247   }
248   DEBUG(dbgs() << '\n');
249 }
250
251 bool AggressiveAntiDepBreaker::IsImplicitDefUse(MachineInstr *MI,
252                                                 MachineOperand& MO)
253 {
254   if (!MO.isReg() || !MO.isImplicit())
255     return false;
256
257   unsigned Reg = MO.getReg();
258   if (Reg == 0)
259     return false;
260
261   MachineOperand *Op = NULL;
262   if (MO.isDef())
263     Op = MI->findRegisterUseOperand(Reg, true);
264   else
265     Op = MI->findRegisterDefOperand(Reg);
266
267   return((Op != NULL) && Op->isImplicit());
268 }
269
270 void AggressiveAntiDepBreaker::GetPassthruRegs(MachineInstr *MI,
271                                            std::set<unsigned>& PassthruRegs) {
272   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
273     MachineOperand &MO = MI->getOperand(i);
274     if (!MO.isReg()) continue;
275     if ((MO.isDef() && MI->isRegTiedToUseOperand(i)) ||
276         IsImplicitDefUse(MI, MO)) {
277       const unsigned Reg = MO.getReg();
278       PassthruRegs.insert(Reg);
279       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
280            *Subreg; ++Subreg) {
281         PassthruRegs.insert(*Subreg);
282       }
283     }
284   }
285 }
286
287 /// AntiDepEdges - Return in Edges the anti- and output- dependencies
288 /// in SU that we want to consider for breaking.
289 static void AntiDepEdges(const SUnit *SU, std::vector<const SDep*>& Edges) {
290   SmallSet<unsigned, 4> RegSet;
291   for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
292        P != PE; ++P) {
293     if ((P->getKind() == SDep::Anti) || (P->getKind() == SDep::Output)) {
294       unsigned Reg = P->getReg();
295       if (RegSet.count(Reg) == 0) {
296         Edges.push_back(&*P);
297         RegSet.insert(Reg);
298       }
299     }
300   }
301 }
302
303 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
304 /// critical path.
305 static const SUnit *CriticalPathStep(const SUnit *SU) {
306   const SDep *Next = 0;
307   unsigned NextDepth = 0;
308   // Find the predecessor edge with the greatest depth.
309   if (SU != 0) {
310     for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
311          P != PE; ++P) {
312       const SUnit *PredSU = P->getSUnit();
313       unsigned PredLatency = P->getLatency();
314       unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
315       // In the case of a latency tie, prefer an anti-dependency edge over
316       // other types of edges.
317       if (NextDepth < PredTotalLatency ||
318           (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
319         NextDepth = PredTotalLatency;
320         Next = &*P;
321       }
322     }
323   }
324
325   return (Next) ? Next->getSUnit() : 0;
326 }
327
328 void AggressiveAntiDepBreaker::HandleLastUse(unsigned Reg, unsigned KillIdx,
329                                              const char *tag,
330                                              const char *header,
331                                              const char *footer) {
332   std::vector<unsigned> &KillIndices = State->GetKillIndices();
333   std::vector<unsigned> &DefIndices = State->GetDefIndices();
334   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
335     RegRefs = State->GetRegRefs();
336
337   if (!State->IsLive(Reg)) {
338     KillIndices[Reg] = KillIdx;
339     DefIndices[Reg] = ~0u;
340     RegRefs.erase(Reg);
341     State->LeaveGroup(Reg);
342     DEBUG(if (header != NULL) {
343         dbgs() << header << TRI->getName(Reg); header = NULL; });
344     DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << tag);
345   }
346   // Repeat for subregisters.
347   for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
348        *Subreg; ++Subreg) {
349     unsigned SubregReg = *Subreg;
350     if (!State->IsLive(SubregReg)) {
351       KillIndices[SubregReg] = KillIdx;
352       DefIndices[SubregReg] = ~0u;
353       RegRefs.erase(SubregReg);
354       State->LeaveGroup(SubregReg);
355       DEBUG(if (header != NULL) {
356           dbgs() << header << TRI->getName(Reg); header = NULL; });
357       DEBUG(dbgs() << " " << TRI->getName(SubregReg) << "->g" <<
358             State->GetGroup(SubregReg) << tag);
359     }
360   }
361
362   DEBUG(if ((header == NULL) && (footer != NULL)) dbgs() << footer);
363 }
364
365 void AggressiveAntiDepBreaker::PrescanInstruction(MachineInstr *MI,
366                                                   unsigned Count,
367                                              std::set<unsigned>& PassthruRegs) {
368   std::vector<unsigned> &DefIndices = State->GetDefIndices();
369   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
370     RegRefs = State->GetRegRefs();
371
372   // Handle dead defs by simulating a last-use of the register just
373   // after the def. A dead def can occur because the def is truely
374   // dead, or because only a subregister is live at the def. If we
375   // don't do this the dead def will be incorrectly merged into the
376   // previous def.
377   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
378     MachineOperand &MO = MI->getOperand(i);
379     if (!MO.isReg() || !MO.isDef()) continue;
380     unsigned Reg = MO.getReg();
381     if (Reg == 0) continue;
382
383     HandleLastUse(Reg, Count + 1, "", "\tDead Def: ", "\n");
384   }
385
386   DEBUG(dbgs() << "\tDef Groups:");
387   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
388     MachineOperand &MO = MI->getOperand(i);
389     if (!MO.isReg() || !MO.isDef()) continue;
390     unsigned Reg = MO.getReg();
391     if (Reg == 0) continue;
392
393     DEBUG(dbgs() << " " << TRI->getName(Reg) << "=g" << State->GetGroup(Reg));
394
395     // If MI's defs have a special allocation requirement, don't allow
396     // any def registers to be changed. Also assume all registers
397     // defined in a call must not be changed (ABI).
398     if (MI->getDesc().isCall() || MI->getDesc().hasExtraDefRegAllocReq() ||
399         TII->isPredicated(MI)) {
400       DEBUG(if (State->GetGroup(Reg) != 0) dbgs() << "->g0(alloc-req)");
401       State->UnionGroups(Reg, 0);
402     }
403
404     // Any aliased that are live at this point are completely or
405     // partially defined here, so group those aliases with Reg.
406     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
407       unsigned AliasReg = *Alias;
408       if (State->IsLive(AliasReg)) {
409         State->UnionGroups(Reg, AliasReg);
410         DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << "(via " <<
411               TRI->getName(AliasReg) << ")");
412       }
413     }
414
415     // Note register reference...
416     const TargetRegisterClass *RC = NULL;
417     if (i < MI->getDesc().getNumOperands())
418       RC = MI->getDesc().OpInfo[i].getRegClass(TRI);
419     AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
420     RegRefs.insert(std::make_pair(Reg, RR));
421   }
422
423   DEBUG(dbgs() << '\n');
424
425   // Scan the register defs for this instruction and update
426   // live-ranges.
427   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
428     MachineOperand &MO = MI->getOperand(i);
429     if (!MO.isReg() || !MO.isDef()) continue;
430     unsigned Reg = MO.getReg();
431     if (Reg == 0) continue;
432     // Ignore KILLs and passthru registers for liveness...
433     if (MI->isKill() || (PassthruRegs.count(Reg) != 0))
434       continue;
435
436     // Update def for Reg and aliases.
437     DefIndices[Reg] = Count;
438     for (const unsigned *Alias = TRI->getAliasSet(Reg);
439          *Alias; ++Alias) {
440       unsigned AliasReg = *Alias;
441       DefIndices[AliasReg] = Count;
442     }
443   }
444 }
445
446 void AggressiveAntiDepBreaker::ScanInstruction(MachineInstr *MI,
447                                                unsigned Count) {
448   DEBUG(dbgs() << "\tUse Groups:");
449   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
450     RegRefs = State->GetRegRefs();
451
452   // If MI's uses have special allocation requirement, don't allow
453   // any use registers to be changed. Also assume all registers
454   // used in a call must not be changed (ABI).
455   // FIXME: The issue with predicated instruction is more complex. We are being
456   // conservatively here because the kill markers cannot be trusted after
457   // if-conversion:
458   // %R6<def> = LDR %SP, %reg0, 92, pred:14, pred:%reg0; mem:LD4[FixedStack14]
459   // ...
460   // STR %R0, %R6<kill>, %reg0, 0, pred:0, pred:%CPSR; mem:ST4[%395]
461   // %R6<def> = LDR %SP, %reg0, 100, pred:0, pred:%CPSR; mem:LD4[FixedStack12]
462   // STR %R0, %R6<kill>, %reg0, 0, pred:14, pred:%reg0; mem:ST4[%396](align=8)
463   //
464   // The first R6 kill is not really a kill since it's killed by a predicated
465   // instruction which may not be executed. The second R6 def may or may not
466   // re-define R6 so it's not safe to change it since the last R6 use cannot be
467   // changed.
468   bool Special = MI->getDesc().isCall() ||
469     MI->getDesc().hasExtraSrcRegAllocReq() ||
470     TII->isPredicated(MI);
471
472   // Scan the register uses for this instruction and update
473   // live-ranges, groups and RegRefs.
474   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
475     MachineOperand &MO = MI->getOperand(i);
476     if (!MO.isReg() || !MO.isUse()) continue;
477     unsigned Reg = MO.getReg();
478     if (Reg == 0) continue;
479
480     DEBUG(dbgs() << " " << TRI->getName(Reg) << "=g" <<
481           State->GetGroup(Reg));
482
483     // It wasn't previously live but now it is, this is a kill. Forget
484     // the previous live-range information and start a new live-range
485     // for the register.
486     HandleLastUse(Reg, Count, "(last-use)");
487
488     if (Special) {
489       DEBUG(if (State->GetGroup(Reg) != 0) dbgs() << "->g0(alloc-req)");
490       State->UnionGroups(Reg, 0);
491     }
492
493     // Note register reference...
494     const TargetRegisterClass *RC = NULL;
495     if (i < MI->getDesc().getNumOperands())
496       RC = MI->getDesc().OpInfo[i].getRegClass(TRI);
497     AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
498     RegRefs.insert(std::make_pair(Reg, RR));
499   }
500
501   DEBUG(dbgs() << '\n');
502
503   // Form a group of all defs and uses of a KILL instruction to ensure
504   // that all registers are renamed as a group.
505   if (MI->isKill()) {
506     DEBUG(dbgs() << "\tKill Group:");
507
508     unsigned FirstReg = 0;
509     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
510       MachineOperand &MO = MI->getOperand(i);
511       if (!MO.isReg()) continue;
512       unsigned Reg = MO.getReg();
513       if (Reg == 0) continue;
514
515       if (FirstReg != 0) {
516         DEBUG(dbgs() << "=" << TRI->getName(Reg));
517         State->UnionGroups(FirstReg, Reg);
518       } else {
519         DEBUG(dbgs() << " " << TRI->getName(Reg));
520         FirstReg = Reg;
521       }
522     }
523
524     DEBUG(dbgs() << "->g" << State->GetGroup(FirstReg) << '\n');
525   }
526 }
527
528 BitVector AggressiveAntiDepBreaker::GetRenameRegisters(unsigned Reg) {
529   BitVector BV(TRI->getNumRegs(), false);
530   bool first = true;
531
532   // Check all references that need rewriting for Reg. For each, use
533   // the corresponding register class to narrow the set of registers
534   // that are appropriate for renaming.
535   std::pair<std::multimap<unsigned,
536                      AggressiveAntiDepState::RegisterReference>::iterator,
537             std::multimap<unsigned,
538                      AggressiveAntiDepState::RegisterReference>::iterator>
539     Range = State->GetRegRefs().equal_range(Reg);
540   for (std::multimap<unsigned,
541        AggressiveAntiDepState::RegisterReference>::iterator Q = Range.first,
542        QE = Range.second; Q != QE; ++Q) {
543     const TargetRegisterClass *RC = Q->second.RC;
544     if (RC == NULL) continue;
545
546     BitVector RCBV = TRI->getAllocatableSet(MF, RC);
547     if (first) {
548       BV |= RCBV;
549       first = false;
550     } else {
551       BV &= RCBV;
552     }
553
554     DEBUG(dbgs() << " " << RC->getName());
555   }
556
557   return BV;
558 }
559
560 bool AggressiveAntiDepBreaker::FindSuitableFreeRegisters(
561                                 unsigned AntiDepGroupIndex,
562                                 RenameOrderType& RenameOrder,
563                                 std::map<unsigned, unsigned> &RenameMap) {
564   std::vector<unsigned> &KillIndices = State->GetKillIndices();
565   std::vector<unsigned> &DefIndices = State->GetDefIndices();
566   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
567     RegRefs = State->GetRegRefs();
568
569   // Collect all referenced registers in the same group as
570   // AntiDepReg. These all need to be renamed together if we are to
571   // break the anti-dependence.
572   std::vector<unsigned> Regs;
573   State->GetGroupRegs(AntiDepGroupIndex, Regs, &RegRefs);
574   assert(Regs.size() > 0 && "Empty register group!");
575   if (Regs.size() == 0)
576     return false;
577
578   // Find the "superest" register in the group. At the same time,
579   // collect the BitVector of registers that can be used to rename
580   // each register.
581   DEBUG(dbgs() << "\tRename Candidates for Group g" << AntiDepGroupIndex
582         << ":\n");
583   std::map<unsigned, BitVector> RenameRegisterMap;
584   unsigned SuperReg = 0;
585   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
586     unsigned Reg = Regs[i];
587     if ((SuperReg == 0) || TRI->isSuperRegister(SuperReg, Reg))
588       SuperReg = Reg;
589
590     // If Reg has any references, then collect possible rename regs
591     if (RegRefs.count(Reg) > 0) {
592       DEBUG(dbgs() << "\t\t" << TRI->getName(Reg) << ":");
593
594       BitVector BV = GetRenameRegisters(Reg);
595       RenameRegisterMap.insert(std::pair<unsigned, BitVector>(Reg, BV));
596
597       DEBUG(dbgs() << " ::");
598       DEBUG(for (int r = BV.find_first(); r != -1; r = BV.find_next(r))
599               dbgs() << " " << TRI->getName(r));
600       DEBUG(dbgs() << "\n");
601     }
602   }
603
604   // All group registers should be a subreg of SuperReg.
605   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
606     unsigned Reg = Regs[i];
607     if (Reg == SuperReg) continue;
608     bool IsSub = TRI->isSubRegister(SuperReg, Reg);
609     assert(IsSub && "Expecting group subregister");
610     if (!IsSub)
611       return false;
612   }
613
614 #ifndef NDEBUG
615   // If DebugDiv > 0 then only rename (renamecnt % DebugDiv) == DebugMod
616   if (DebugDiv > 0) {
617     static int renamecnt = 0;
618     if (renamecnt++ % DebugDiv != DebugMod)
619       return false;
620
621     dbgs() << "*** Performing rename " << TRI->getName(SuperReg) <<
622       " for debug ***\n";
623   }
624 #endif
625
626   // Check each possible rename register for SuperReg in round-robin
627   // order. If that register is available, and the corresponding
628   // registers are available for the other group subregisters, then we
629   // can use those registers to rename.
630
631   // FIXME: Using getMinimalPhysRegClass is very conservative. We should
632   // check every use of the register and find the largest register class
633   // that can be used in all of them.
634   const TargetRegisterClass *SuperRC =
635     TRI->getMinimalPhysRegClass(SuperReg, MVT::Other);
636
637   const TargetRegisterClass::iterator RB = SuperRC->allocation_order_begin(MF);
638   const TargetRegisterClass::iterator RE = SuperRC->allocation_order_end(MF);
639   if (RB == RE) {
640     DEBUG(dbgs() << "\tEmpty Super Regclass!!\n");
641     return false;
642   }
643
644   DEBUG(dbgs() << "\tFind Registers:");
645
646   if (RenameOrder.count(SuperRC) == 0)
647     RenameOrder.insert(RenameOrderType::value_type(SuperRC, RE));
648
649   const TargetRegisterClass::iterator OrigR = RenameOrder[SuperRC];
650   const TargetRegisterClass::iterator EndR = ((OrigR == RE) ? RB : OrigR);
651   TargetRegisterClass::iterator R = OrigR;
652   do {
653     if (R == RB) R = RE;
654     --R;
655     const unsigned NewSuperReg = *R;
656     // Don't replace a register with itself.
657     if (NewSuperReg == SuperReg) continue;
658
659     DEBUG(dbgs() << " [" << TRI->getName(NewSuperReg) << ':');
660     RenameMap.clear();
661
662     // For each referenced group register (which must be a SuperReg or
663     // a subregister of SuperReg), find the corresponding subregister
664     // of NewSuperReg and make sure it is free to be renamed.
665     for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
666       unsigned Reg = Regs[i];
667       unsigned NewReg = 0;
668       if (Reg == SuperReg) {
669         NewReg = NewSuperReg;
670       } else {
671         unsigned NewSubRegIdx = TRI->getSubRegIndex(SuperReg, Reg);
672         if (NewSubRegIdx != 0)
673           NewReg = TRI->getSubReg(NewSuperReg, NewSubRegIdx);
674       }
675
676       DEBUG(dbgs() << " " << TRI->getName(NewReg));
677
678       // Check if Reg can be renamed to NewReg.
679       BitVector BV = RenameRegisterMap[Reg];
680       if (!BV.test(NewReg)) {
681         DEBUG(dbgs() << "(no rename)");
682         goto next_super_reg;
683       }
684
685       // If NewReg is dead and NewReg's most recent def is not before
686       // Regs's kill, it's safe to replace Reg with NewReg. We
687       // must also check all aliases of NewReg, because we can't define a
688       // register when any sub or super is already live.
689       if (State->IsLive(NewReg) || (KillIndices[Reg] > DefIndices[NewReg])) {
690         DEBUG(dbgs() << "(live)");
691         goto next_super_reg;
692       } else {
693         bool found = false;
694         for (const unsigned *Alias = TRI->getAliasSet(NewReg);
695              *Alias; ++Alias) {
696           unsigned AliasReg = *Alias;
697           if (State->IsLive(AliasReg) ||
698               (KillIndices[Reg] > DefIndices[AliasReg])) {
699             DEBUG(dbgs() << "(alias " << TRI->getName(AliasReg) << " live)");
700             found = true;
701             break;
702           }
703         }
704         if (found)
705           goto next_super_reg;
706       }
707
708       // Record that 'Reg' can be renamed to 'NewReg'.
709       RenameMap.insert(std::pair<unsigned, unsigned>(Reg, NewReg));
710     }
711
712     // If we fall-out here, then every register in the group can be
713     // renamed, as recorded in RenameMap.
714     RenameOrder.erase(SuperRC);
715     RenameOrder.insert(RenameOrderType::value_type(SuperRC, R));
716     DEBUG(dbgs() << "]\n");
717     return true;
718
719   next_super_reg:
720     DEBUG(dbgs() << ']');
721   } while (R != EndR);
722
723   DEBUG(dbgs() << '\n');
724
725   // No registers are free and available!
726   return false;
727 }
728
729 /// BreakAntiDependencies - Identifiy anti-dependencies within the
730 /// ScheduleDAG and break them by renaming registers.
731 ///
732 unsigned AggressiveAntiDepBreaker::BreakAntiDependencies(
733                               const std::vector<SUnit>& SUnits,
734                               MachineBasicBlock::iterator Begin,
735                               MachineBasicBlock::iterator End,
736                               unsigned InsertPosIndex) {
737   std::vector<unsigned> &KillIndices = State->GetKillIndices();
738   std::vector<unsigned> &DefIndices = State->GetDefIndices();
739   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
740     RegRefs = State->GetRegRefs();
741
742   // The code below assumes that there is at least one instruction,
743   // so just duck out immediately if the block is empty.
744   if (SUnits.empty()) return 0;
745
746   // For each regclass the next register to use for renaming.
747   RenameOrderType RenameOrder;
748
749   // ...need a map from MI to SUnit.
750   std::map<MachineInstr *, const SUnit *> MISUnitMap;
751   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
752     const SUnit *SU = &SUnits[i];
753     MISUnitMap.insert(std::pair<MachineInstr *, const SUnit *>(SU->getInstr(),
754                                                                SU));
755   }
756
757   // Track progress along the critical path through the SUnit graph as
758   // we walk the instructions. This is needed for regclasses that only
759   // break critical-path anti-dependencies.
760   const SUnit *CriticalPathSU = 0;
761   MachineInstr *CriticalPathMI = 0;
762   if (CriticalPathSet.any()) {
763     for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
764       const SUnit *SU = &SUnits[i];
765       if (!CriticalPathSU ||
766           ((SU->getDepth() + SU->Latency) >
767            (CriticalPathSU->getDepth() + CriticalPathSU->Latency))) {
768         CriticalPathSU = SU;
769       }
770     }
771
772     CriticalPathMI = CriticalPathSU->getInstr();
773   }
774
775 #ifndef NDEBUG
776   DEBUG(dbgs() << "\n===== Aggressive anti-dependency breaking\n");
777   DEBUG(dbgs() << "Available regs:");
778   for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
779     if (!State->IsLive(Reg))
780       DEBUG(dbgs() << " " << TRI->getName(Reg));
781   }
782   DEBUG(dbgs() << '\n');
783 #endif
784
785   // Attempt to break anti-dependence edges. Walk the instructions
786   // from the bottom up, tracking information about liveness as we go
787   // to help determine which registers are available.
788   unsigned Broken = 0;
789   unsigned Count = InsertPosIndex - 1;
790   for (MachineBasicBlock::iterator I = End, E = Begin;
791        I != E; --Count) {
792     MachineInstr *MI = --I;
793
794     DEBUG(dbgs() << "Anti: ");
795     DEBUG(MI->dump());
796
797     std::set<unsigned> PassthruRegs;
798     GetPassthruRegs(MI, PassthruRegs);
799
800     // Process the defs in MI...
801     PrescanInstruction(MI, Count, PassthruRegs);
802
803     // The dependence edges that represent anti- and output-
804     // dependencies that are candidates for breaking.
805     std::vector<const SDep *> Edges;
806     const SUnit *PathSU = MISUnitMap[MI];
807     AntiDepEdges(PathSU, Edges);
808
809     // If MI is not on the critical path, then we don't rename
810     // registers in the CriticalPathSet.
811     BitVector *ExcludeRegs = NULL;
812     if (MI == CriticalPathMI) {
813       CriticalPathSU = CriticalPathStep(CriticalPathSU);
814       CriticalPathMI = (CriticalPathSU) ? CriticalPathSU->getInstr() : 0;
815     } else {
816       ExcludeRegs = &CriticalPathSet;
817     }
818
819     // Ignore KILL instructions (they form a group in ScanInstruction
820     // but don't cause any anti-dependence breaking themselves)
821     if (!MI->isKill()) {
822       // Attempt to break each anti-dependency...
823       for (unsigned i = 0, e = Edges.size(); i != e; ++i) {
824         const SDep *Edge = Edges[i];
825         SUnit *NextSU = Edge->getSUnit();
826
827         if ((Edge->getKind() != SDep::Anti) &&
828             (Edge->getKind() != SDep::Output)) continue;
829
830         unsigned AntiDepReg = Edge->getReg();
831         DEBUG(dbgs() << "\tAntidep reg: " << TRI->getName(AntiDepReg));
832         assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
833
834         if (!AllocatableSet.test(AntiDepReg)) {
835           // Don't break anti-dependencies on non-allocatable registers.
836           DEBUG(dbgs() << " (non-allocatable)\n");
837           continue;
838         } else if ((ExcludeRegs != NULL) && ExcludeRegs->test(AntiDepReg)) {
839           // Don't break anti-dependencies for critical path registers
840           // if not on the critical path
841           DEBUG(dbgs() << " (not critical-path)\n");
842           continue;
843         } else if (PassthruRegs.count(AntiDepReg) != 0) {
844           // If the anti-dep register liveness "passes-thru", then
845           // don't try to change it. It will be changed along with
846           // the use if required to break an earlier antidep.
847           DEBUG(dbgs() << " (passthru)\n");
848           continue;
849         } else {
850           // No anti-dep breaking for implicit deps
851           MachineOperand *AntiDepOp = MI->findRegisterDefOperand(AntiDepReg);
852           assert(AntiDepOp != NULL &&
853                  "Can't find index for defined register operand");
854           if ((AntiDepOp == NULL) || AntiDepOp->isImplicit()) {
855             DEBUG(dbgs() << " (implicit)\n");
856             continue;
857           }
858
859           // If the SUnit has other dependencies on the SUnit that
860           // it anti-depends on, don't bother breaking the
861           // anti-dependency since those edges would prevent such
862           // units from being scheduled past each other
863           // regardless.
864           //
865           // Also, if there are dependencies on other SUnits with the
866           // same register as the anti-dependency, don't attempt to
867           // break it.
868           for (SUnit::const_pred_iterator P = PathSU->Preds.begin(),
869                  PE = PathSU->Preds.end(); P != PE; ++P) {
870             if (P->getSUnit() == NextSU ?
871                 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
872                 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
873               AntiDepReg = 0;
874               break;
875             }
876           }
877           for (SUnit::const_pred_iterator P = PathSU->Preds.begin(),
878                  PE = PathSU->Preds.end(); P != PE; ++P) {
879             if ((P->getSUnit() == NextSU) && (P->getKind() != SDep::Anti) &&
880                 (P->getKind() != SDep::Output)) {
881               DEBUG(dbgs() << " (real dependency)\n");
882               AntiDepReg = 0;
883               break;
884             } else if ((P->getSUnit() != NextSU) &&
885                        (P->getKind() == SDep::Data) &&
886                        (P->getReg() == AntiDepReg)) {
887               DEBUG(dbgs() << " (other dependency)\n");
888               AntiDepReg = 0;
889               break;
890             }
891           }
892
893           if (AntiDepReg == 0) continue;
894         }
895
896         assert(AntiDepReg != 0);
897         if (AntiDepReg == 0) continue;
898
899         // Determine AntiDepReg's register group.
900         const unsigned GroupIndex = State->GetGroup(AntiDepReg);
901         if (GroupIndex == 0) {
902           DEBUG(dbgs() << " (zero group)\n");
903           continue;
904         }
905
906         DEBUG(dbgs() << '\n');
907
908         // Look for a suitable register to use to break the anti-dependence.
909         std::map<unsigned, unsigned> RenameMap;
910         if (FindSuitableFreeRegisters(GroupIndex, RenameOrder, RenameMap)) {
911           DEBUG(dbgs() << "\tBreaking anti-dependence edge on "
912                 << TRI->getName(AntiDepReg) << ":");
913
914           // Handle each group register...
915           for (std::map<unsigned, unsigned>::iterator
916                  S = RenameMap.begin(), E = RenameMap.end(); S != E; ++S) {
917             unsigned CurrReg = S->first;
918             unsigned NewReg = S->second;
919
920             DEBUG(dbgs() << " " << TRI->getName(CurrReg) << "->" <<
921                   TRI->getName(NewReg) << "(" <<
922                   RegRefs.count(CurrReg) << " refs)");
923
924             // Update the references to the old register CurrReg to
925             // refer to the new register NewReg.
926             std::pair<std::multimap<unsigned,
927                            AggressiveAntiDepState::RegisterReference>::iterator,
928                       std::multimap<unsigned,
929                            AggressiveAntiDepState::RegisterReference>::iterator>
930               Range = RegRefs.equal_range(CurrReg);
931             for (std::multimap<unsigned,
932                  AggressiveAntiDepState::RegisterReference>::iterator
933                    Q = Range.first, QE = Range.second; Q != QE; ++Q) {
934               Q->second.Operand->setReg(NewReg);
935               // If the SU for the instruction being updated has debug
936               // information related to the anti-dependency register, make
937               // sure to update that as well.
938               const SUnit *SU = MISUnitMap[Q->second.Operand->getParent()];
939               if (!SU) continue;
940               for (unsigned i = 0, e = SU->DbgInstrList.size() ; i < e ; ++i) {
941                 MachineInstr *DI = SU->DbgInstrList[i];
942                 assert (DI->getNumOperands()==3 && DI->getOperand(0).isReg() &&
943                         DI->getOperand(0).getReg()
944                         && "Non register dbg_value attached to SUnit!");
945                 if (DI->getOperand(0).getReg() == AntiDepReg)
946                   DI->getOperand(0).setReg(NewReg);
947               }
948             }
949
950             // We just went back in time and modified history; the
951             // liveness information for CurrReg is now inconsistent. Set
952             // the state as if it were dead.
953             State->UnionGroups(NewReg, 0);
954             RegRefs.erase(NewReg);
955             DefIndices[NewReg] = DefIndices[CurrReg];
956             KillIndices[NewReg] = KillIndices[CurrReg];
957
958             State->UnionGroups(CurrReg, 0);
959             RegRefs.erase(CurrReg);
960             DefIndices[CurrReg] = KillIndices[CurrReg];
961             KillIndices[CurrReg] = ~0u;
962             assert(((KillIndices[CurrReg] == ~0u) !=
963                     (DefIndices[CurrReg] == ~0u)) &&
964                    "Kill and Def maps aren't consistent for AntiDepReg!");
965           }
966
967           ++Broken;
968           DEBUG(dbgs() << '\n');
969         }
970       }
971     }
972
973     ScanInstruction(MI, Count);
974   }
975
976   return Broken;
977 }