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 i = 0, e = Regs.size(); i != e; ++i) {
565     unsigned Reg = Regs[i];
566     if ((SuperReg == 0) || TRI->isSuperRegister(SuperReg, Reg))
567       SuperReg = Reg;
568 
569     // If Reg has any references, then collect possible rename regs
570     if (RegRefs.count(Reg) > 0) {
571       LLVM_DEBUG(dbgs() << "\t\t" << printReg(Reg, TRI) << ":");
572 
573       BitVector &BV = RenameRegisterMap[Reg];
574       assert(BV.empty());
575       BV = GetRenameRegisters(Reg);
576 
577       LLVM_DEBUG({
578         dbgs() << " ::";
579         for (unsigned r : BV.set_bits())
580           dbgs() << " " << printReg(r, TRI);
581         dbgs() << "\n";
582       });
583     }
584   }
585 
586   // All group registers should be a subreg of SuperReg.
587   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
588     unsigned Reg = Regs[i];
589     if (Reg == SuperReg) continue;
590     bool IsSub = TRI->isSubRegister(SuperReg, Reg);
591     // FIXME: remove this once PR18663 has been properly fixed. For now,
592     // return a conservative answer:
593     // assert(IsSub && "Expecting group subregister");
594     if (!IsSub)
595       return false;
596   }
597 
598 #ifndef NDEBUG
599   // If DebugDiv > 0 then only rename (renamecnt % DebugDiv) == DebugMod
600   if (DebugDiv > 0) {
601     static int renamecnt = 0;
602     if (renamecnt++ % DebugDiv != DebugMod)
603       return false;
604 
605     dbgs() << "*** Performing rename " << printReg(SuperReg, TRI)
606            << " for debug ***\n";
607   }
608 #endif
609 
610   // Check each possible rename register for SuperReg in round-robin
611   // order. If that register is available, and the corresponding
612   // registers are available for the other group subregisters, then we
613   // can use those registers to rename.
614 
615   // FIXME: Using getMinimalPhysRegClass is very conservative. We should
616   // check every use of the register and find the largest register class
617   // that can be used in all of them.
618   const TargetRegisterClass *SuperRC =
619     TRI->getMinimalPhysRegClass(SuperReg, MVT::Other);
620 
621   ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(SuperRC);
622   if (Order.empty()) {
623     LLVM_DEBUG(dbgs() << "\tEmpty Super Regclass!!\n");
624     return false;
625   }
626 
627   LLVM_DEBUG(dbgs() << "\tFind Registers:");
628 
629   RenameOrder.insert(RenameOrderType::value_type(SuperRC, Order.size()));
630 
631   unsigned OrigR = RenameOrder[SuperRC];
632   unsigned EndR = ((OrigR == Order.size()) ? 0 : OrigR);
633   unsigned R = OrigR;
634   do {
635     if (R == 0) R = Order.size();
636     --R;
637     const unsigned NewSuperReg = Order[R];
638     // Don't consider non-allocatable registers
639     if (!MRI.isAllocatable(NewSuperReg)) continue;
640     // Don't replace a register with itself.
641     if (NewSuperReg == SuperReg) continue;
642 
643     LLVM_DEBUG(dbgs() << " [" << printReg(NewSuperReg, TRI) << ':');
644     RenameMap.clear();
645 
646     // For each referenced group register (which must be a SuperReg or
647     // a subregister of SuperReg), find the corresponding subregister
648     // of NewSuperReg and make sure it is free to be renamed.
649     for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
650       unsigned Reg = Regs[i];
651       unsigned NewReg = 0;
652       if (Reg == SuperReg) {
653         NewReg = NewSuperReg;
654       } else {
655         unsigned NewSubRegIdx = TRI->getSubRegIndex(SuperReg, Reg);
656         if (NewSubRegIdx != 0)
657           NewReg = TRI->getSubReg(NewSuperReg, NewSubRegIdx);
658       }
659 
660       LLVM_DEBUG(dbgs() << " " << printReg(NewReg, TRI));
661 
662       // Check if Reg can be renamed to NewReg.
663       if (!RenameRegisterMap[Reg].test(NewReg)) {
664         LLVM_DEBUG(dbgs() << "(no rename)");
665         goto next_super_reg;
666       }
667 
668       // If NewReg is dead and NewReg's most recent def is not before
669       // Regs's kill, it's safe to replace Reg with NewReg. We
670       // must also check all aliases of NewReg, because we can't define a
671       // register when any sub or super is already live.
672       if (State->IsLive(NewReg) || (KillIndices[Reg] > DefIndices[NewReg])) {
673         LLVM_DEBUG(dbgs() << "(live)");
674         goto next_super_reg;
675       } else {
676         bool found = false;
677         for (MCRegAliasIterator AI(NewReg, TRI, false); AI.isValid(); ++AI) {
678           unsigned AliasReg = *AI;
679           if (State->IsLive(AliasReg) ||
680               (KillIndices[Reg] > DefIndices[AliasReg])) {
681             LLVM_DEBUG(dbgs()
682                        << "(alias " << printReg(AliasReg, TRI) << " live)");
683             found = true;
684             break;
685           }
686         }
687         if (found)
688           goto next_super_reg;
689       }
690 
691       // We cannot rename 'Reg' to 'NewReg' if one of the uses of 'Reg' also
692       // defines 'NewReg' via an early-clobber operand.
693       for (const auto &Q : make_range(RegRefs.equal_range(Reg))) {
694         MachineInstr *UseMI = Q.second.Operand->getParent();
695         int Idx = UseMI->findRegisterDefOperandIdx(NewReg, false, true, TRI);
696         if (Idx == -1)
697           continue;
698 
699         if (UseMI->getOperand(Idx).isEarlyClobber()) {
700           LLVM_DEBUG(dbgs() << "(ec)");
701           goto next_super_reg;
702         }
703       }
704 
705       // Also, we cannot rename 'Reg' to 'NewReg' if the instruction defining
706       // 'Reg' is an early-clobber define and that instruction also uses
707       // 'NewReg'.
708       for (const auto &Q : make_range(RegRefs.equal_range(Reg))) {
709         if (!Q.second.Operand->isDef() || !Q.second.Operand->isEarlyClobber())
710           continue;
711 
712         MachineInstr *DefMI = Q.second.Operand->getParent();
713         if (DefMI->readsRegister(NewReg, TRI)) {
714           LLVM_DEBUG(dbgs() << "(ec)");
715           goto next_super_reg;
716         }
717       }
718 
719       // Record that 'Reg' can be renamed to 'NewReg'.
720       RenameMap.insert(std::pair<unsigned, unsigned>(Reg, NewReg));
721     }
722 
723     // If we fall-out here, then every register in the group can be
724     // renamed, as recorded in RenameMap.
725     RenameOrder.erase(SuperRC);
726     RenameOrder.insert(RenameOrderType::value_type(SuperRC, R));
727     LLVM_DEBUG(dbgs() << "]\n");
728     return true;
729 
730   next_super_reg:
731     LLVM_DEBUG(dbgs() << ']');
732   } while (R != EndR);
733 
734   LLVM_DEBUG(dbgs() << '\n');
735 
736   // No registers are free and available!
737   return false;
738 }
739 
740 /// BreakAntiDependencies - Identifiy anti-dependencies within the
741 /// ScheduleDAG and break them by renaming registers.
742 unsigned AggressiveAntiDepBreaker::BreakAntiDependencies(
743                               const std::vector<SUnit> &SUnits,
744                               MachineBasicBlock::iterator Begin,
745                               MachineBasicBlock::iterator End,
746                               unsigned InsertPosIndex,
747                               DbgValueVector &DbgValues) {
748   std::vector<unsigned> &KillIndices = State->GetKillIndices();
749   std::vector<unsigned> &DefIndices = State->GetDefIndices();
750   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
751     RegRefs = State->GetRegRefs();
752 
753   // The code below assumes that there is at least one instruction,
754   // so just duck out immediately if the block is empty.
755   if (SUnits.empty()) return 0;
756 
757   // For each regclass the next register to use for renaming.
758   RenameOrderType RenameOrder;
759 
760   // ...need a map from MI to SUnit.
761   std::map<MachineInstr *, const SUnit *> MISUnitMap;
762   for (const SUnit &SU : SUnits)
763     MISUnitMap.insert(std::make_pair(SU.getInstr(), &SU));
764 
765   // Track progress along the critical path through the SUnit graph as
766   // we walk the instructions. This is needed for regclasses that only
767   // break critical-path anti-dependencies.
768   const SUnit *CriticalPathSU = nullptr;
769   MachineInstr *CriticalPathMI = nullptr;
770   if (CriticalPathSet.any()) {
771     for (const SUnit &SU : SUnits) {
772       if (!CriticalPathSU ||
773           ((SU.getDepth() + SU.Latency) >
774            (CriticalPathSU->getDepth() + CriticalPathSU->Latency))) {
775         CriticalPathSU = &SU;
776       }
777     }
778     assert(CriticalPathSU && "Failed to find SUnit critical path");
779     CriticalPathMI = CriticalPathSU->getInstr();
780   }
781 
782 #ifndef NDEBUG
783   LLVM_DEBUG(dbgs() << "\n===== Aggressive anti-dependency breaking\n");
784   LLVM_DEBUG(dbgs() << "Available regs:");
785   for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
786     if (!State->IsLive(Reg))
787       LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI));
788   }
789   LLVM_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.isDebugInstr())
804       continue;
805 
806     LLVM_DEBUG(dbgs() << "Anti: ");
807     LLVM_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 (const SDep *Edge : Edges) {
836         SUnit *NextSU = Edge->getSUnit();
837 
838         if ((Edge->getKind() != SDep::Anti) &&
839             (Edge->getKind() != SDep::Output)) continue;
840 
841         unsigned AntiDepReg = Edge->getReg();
842         LLVM_DEBUG(dbgs() << "\tAntidep reg: " << printReg(AntiDepReg, TRI));
843         assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
844 
845         if (!MRI.isAllocatable(AntiDepReg)) {
846           // Don't break anti-dependencies on non-allocatable registers.
847           LLVM_DEBUG(dbgs() << " (non-allocatable)\n");
848           continue;
849         } else if (ExcludeRegs && ExcludeRegs->test(AntiDepReg)) {
850           // Don't break anti-dependencies for critical path registers
851           // if not on the critical path
852           LLVM_DEBUG(dbgs() << " (not critical-path)\n");
853           continue;
854         } else if (PassthruRegs.count(AntiDepReg) != 0) {
855           // If the anti-dep register liveness "passes-thru", then
856           // don't try to change it. It will be changed along with
857           // the use if required to break an earlier antidep.
858           LLVM_DEBUG(dbgs() << " (passthru)\n");
859           continue;
860         } else {
861           // No anti-dep breaking for implicit deps
862           MachineOperand *AntiDepOp = MI.findRegisterDefOperand(AntiDepReg);
863           assert(AntiDepOp && "Can't find index for defined register operand");
864           if (!AntiDepOp || AntiDepOp->isImplicit()) {
865             LLVM_DEBUG(dbgs() << " (implicit)\n");
866             continue;
867           }
868 
869           // If the SUnit has other dependencies on the SUnit that
870           // it anti-depends on, don't bother breaking the
871           // anti-dependency since those edges would prevent such
872           // units from being scheduled past each other
873           // regardless.
874           //
875           // Also, if there are dependencies on other SUnits with the
876           // same register as the anti-dependency, don't attempt to
877           // break it.
878           for (const SDep &Pred : PathSU->Preds) {
879             if (Pred.getSUnit() == NextSU ? (Pred.getKind() != SDep::Anti ||
880                                              Pred.getReg() != AntiDepReg)
881                                           : (Pred.getKind() == SDep::Data &&
882                                              Pred.getReg() == AntiDepReg)) {
883               AntiDepReg = 0;
884               break;
885             }
886           }
887           for (const SDep &Pred : PathSU->Preds) {
888             if ((Pred.getSUnit() == NextSU) && (Pred.getKind() != SDep::Anti) &&
889                 (Pred.getKind() != SDep::Output)) {
890               LLVM_DEBUG(dbgs() << " (real dependency)\n");
891               AntiDepReg = 0;
892               break;
893             } else if ((Pred.getSUnit() != NextSU) &&
894                        (Pred.getKind() == SDep::Data) &&
895                        (Pred.getReg() == AntiDepReg)) {
896               LLVM_DEBUG(dbgs() << " (other dependency)\n");
897               AntiDepReg = 0;
898               break;
899             }
900           }
901 
902           if (AntiDepReg == 0) continue;
903 
904           // If the definition of the anti-dependency register does not start
905           // a new live range, bail out. This can happen if the anti-dep
906           // register is a sub-register of another register whose live range
907           // spans over PathSU. In such case, PathSU defines only a part of
908           // the larger register.
909           RegAliases.reset();
910           for (MCRegAliasIterator AI(AntiDepReg, TRI, true); AI.isValid(); ++AI)
911             RegAliases.set(*AI);
912           for (SDep S : PathSU->Succs) {
913             SDep::Kind K = S.getKind();
914             if (K != SDep::Data && K != SDep::Output && K != SDep::Anti)
915               continue;
916             unsigned R = S.getReg();
917             if (!RegAliases[R])
918               continue;
919             if (R == AntiDepReg || TRI->isSubRegister(AntiDepReg, R))
920               continue;
921             AntiDepReg = 0;
922             break;
923           }
924 
925           if (AntiDepReg == 0) continue;
926         }
927 
928         assert(AntiDepReg != 0);
929         if (AntiDepReg == 0) continue;
930 
931         // Determine AntiDepReg's register group.
932         const unsigned GroupIndex = State->GetGroup(AntiDepReg);
933         if (GroupIndex == 0) {
934           LLVM_DEBUG(dbgs() << " (zero group)\n");
935           continue;
936         }
937 
938         LLVM_DEBUG(dbgs() << '\n');
939 
940         // Look for a suitable register to use to break the anti-dependence.
941         std::map<unsigned, unsigned> RenameMap;
942         if (FindSuitableFreeRegisters(GroupIndex, RenameOrder, RenameMap)) {
943           LLVM_DEBUG(dbgs() << "\tBreaking anti-dependence edge on "
944                             << printReg(AntiDepReg, TRI) << ":");
945 
946           // Handle each group register...
947           for (const auto &P : RenameMap) {
948             unsigned CurrReg = P.first;
949             unsigned NewReg = P.second;
950 
951             LLVM_DEBUG(dbgs() << " " << printReg(CurrReg, TRI) << "->"
952                               << printReg(NewReg, TRI) << "("
953                               << RegRefs.count(CurrReg) << " refs)");
954 
955             // Update the references to the old register CurrReg to
956             // refer to the new register NewReg.
957             for (const auto &Q : make_range(RegRefs.equal_range(CurrReg))) {
958               Q.second.Operand->setReg(NewReg);
959               // If the SU for the instruction being updated has debug
960               // information related to the anti-dependency register, make
961               // sure to update that as well.
962               const SUnit *SU = MISUnitMap[Q.second.Operand->getParent()];
963               if (!SU) continue;
964               UpdateDbgValues(DbgValues, Q.second.Operand->getParent(),
965                               AntiDepReg, NewReg);
966             }
967 
968             // We just went back in time and modified history; the
969             // liveness information for CurrReg is now inconsistent. Set
970             // the state as if it were dead.
971             State->UnionGroups(NewReg, 0);
972             RegRefs.erase(NewReg);
973             DefIndices[NewReg] = DefIndices[CurrReg];
974             KillIndices[NewReg] = KillIndices[CurrReg];
975 
976             State->UnionGroups(CurrReg, 0);
977             RegRefs.erase(CurrReg);
978             DefIndices[CurrReg] = KillIndices[CurrReg];
979             KillIndices[CurrReg] = ~0u;
980             assert(((KillIndices[CurrReg] == ~0u) !=
981                     (DefIndices[CurrReg] == ~0u)) &&
982                    "Kill and Def maps aren't consistent for AntiDepReg!");
983           }
984 
985           ++Broken;
986           LLVM_DEBUG(dbgs() << '\n');
987         }
988       }
989     }
990 
991     ScanInstruction(MI, Count);
992   }
993 
994   return Broken;
995 }
996 
997 AntiDepBreaker *llvm::createAggressiveAntiDepBreaker(
998     MachineFunction &MFi, const RegisterClassInfo &RCI,
999     TargetSubtargetInfo::RegClassVector &CriticalPathRCs) {
1000   return new AggressiveAntiDepBreaker(MFi, RCI, CriticalPathRCs);
1001 }
1002