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