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