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