1 //===- CriticalAntiDepBreaker.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 CriticalAntiDepBreaker class, which
10 // implements register anti-dependence breaking along a blocks
11 // critical path during post-RA scheduler.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "CriticalAntiDepBreaker.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineOperand.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/RegisterClassInfo.h"
26 #include "llvm/CodeGen/ScheduleDAG.h"
27 #include "llvm/CodeGen/TargetInstrInfo.h"
28 #include "llvm/CodeGen/TargetRegisterInfo.h"
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <cassert>
35 #include <utility>
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "post-RA-sched"
40 
CriticalAntiDepBreaker(MachineFunction & MFi,const RegisterClassInfo & RCI)41 CriticalAntiDepBreaker::CriticalAntiDepBreaker(MachineFunction &MFi,
42                                                const RegisterClassInfo &RCI)
43     : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()),
44       TII(MF.getSubtarget().getInstrInfo()),
45       TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI),
46       Classes(TRI->getNumRegs(), nullptr), KillIndices(TRI->getNumRegs(), 0),
47       DefIndices(TRI->getNumRegs(), 0), KeepRegs(TRI->getNumRegs(), false) {}
48 
49 CriticalAntiDepBreaker::~CriticalAntiDepBreaker() = default;
50 
StartBlock(MachineBasicBlock * BB)51 void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
52   const unsigned BBSize = BB->size();
53   for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) {
54     // Clear out the register class data.
55     Classes[i] = nullptr;
56 
57     // Initialize the indices to indicate that no registers are live.
58     KillIndices[i] = ~0u;
59     DefIndices[i] = BBSize;
60   }
61 
62   // Clear "do not change" set.
63   KeepRegs.reset();
64 
65   bool IsReturnBlock = BB->isReturnBlock();
66 
67   // Examine the live-in regs of all successors.
68   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
69          SE = BB->succ_end(); SI != SE; ++SI)
70     for (const auto &LI : (*SI)->liveins()) {
71       for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI) {
72         unsigned Reg = *AI;
73         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
74         KillIndices[Reg] = BBSize;
75         DefIndices[Reg] = ~0u;
76       }
77     }
78 
79   // Mark live-out callee-saved registers. In a return block this is
80   // all callee-saved registers. In non-return this is any
81   // callee-saved register that is not saved in the prolog.
82   const MachineFrameInfo &MFI = MF.getFrameInfo();
83   BitVector Pristine = MFI.getPristineRegs(MF);
84   for (const MCPhysReg *I = MF.getRegInfo().getCalleeSavedRegs(); *I;
85        ++I) {
86     unsigned Reg = *I;
87     if (!IsReturnBlock && !Pristine.test(Reg))
88       continue;
89     for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
90       unsigned Reg = *AI;
91       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
92       KillIndices[Reg] = BBSize;
93       DefIndices[Reg] = ~0u;
94     }
95   }
96 }
97 
FinishBlock()98 void CriticalAntiDepBreaker::FinishBlock() {
99   RegRefs.clear();
100   KeepRegs.reset();
101 }
102 
Observe(MachineInstr & MI,unsigned Count,unsigned InsertPosIndex)103 void CriticalAntiDepBreaker::Observe(MachineInstr &MI, unsigned Count,
104                                      unsigned InsertPosIndex) {
105   // Kill instructions can define registers but are really nops, and there might
106   // be a real definition earlier that needs to be paired with uses dominated by
107   // this kill.
108 
109   // FIXME: It may be possible to remove the isKill() restriction once PR18663
110   // has been properly fixed. There can be value in processing kills as seen in
111   // the AggressiveAntiDepBreaker class.
112   if (MI.isDebugInstr() || MI.isKill())
113     return;
114   assert(Count < InsertPosIndex && "Instruction index out of expected range!");
115 
116   for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
117     if (KillIndices[Reg] != ~0u) {
118       // If Reg is currently live, then mark that it can't be renamed as
119       // we don't know the extent of its live-range anymore (now that it
120       // has been scheduled).
121       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
122       KillIndices[Reg] = Count;
123     } else if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
124       // Any register which was defined within the previous scheduling region
125       // may have been rescheduled and its lifetime may overlap with registers
126       // in ways not reflected in our current liveness state. For each such
127       // register, adjust the liveness state to be conservatively correct.
128       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
129 
130       // Move the def index to the end of the previous region, to reflect
131       // that the def could theoretically have been scheduled at the end.
132       DefIndices[Reg] = InsertPosIndex;
133     }
134   }
135 
136   PrescanInstruction(MI);
137   ScanInstruction(MI, Count);
138 }
139 
140 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
141 /// critical path.
CriticalPathStep(const SUnit * SU)142 static const SDep *CriticalPathStep(const SUnit *SU) {
143   const SDep *Next = nullptr;
144   unsigned NextDepth = 0;
145   // Find the predecessor edge with the greatest depth.
146   for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
147        P != PE; ++P) {
148     const SUnit *PredSU = P->getSUnit();
149     unsigned PredLatency = P->getLatency();
150     unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
151     // In the case of a latency tie, prefer an anti-dependency edge over
152     // other types of edges.
153     if (NextDepth < PredTotalLatency ||
154         (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
155       NextDepth = PredTotalLatency;
156       Next = &*P;
157     }
158   }
159   return Next;
160 }
161 
PrescanInstruction(MachineInstr & MI)162 void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr &MI) {
163   // It's not safe to change register allocation for source operands of
164   // instructions that have special allocation requirements. Also assume all
165   // registers used in a call must not be changed (ABI).
166   // FIXME: The issue with predicated instruction is more complex. We are being
167   // conservative here because the kill markers cannot be trusted after
168   // if-conversion:
169   // %r6 = LDR %sp, %reg0, 92, 14, %reg0; mem:LD4[FixedStack14]
170   // ...
171   // STR %r0, killed %r6, %reg0, 0, 0, %cpsr; mem:ST4[%395]
172   // %r6 = LDR %sp, %reg0, 100, 0, %cpsr; mem:LD4[FixedStack12]
173   // STR %r0, killed %r6, %reg0, 0, 14, %reg0; mem:ST4[%396](align=8)
174   //
175   // The first R6 kill is not really a kill since it's killed by a predicated
176   // instruction which may not be executed. The second R6 def may or may not
177   // re-define R6 so it's not safe to change it since the last R6 use cannot be
178   // changed.
179   bool Special =
180       MI.isCall() || MI.hasExtraSrcRegAllocReq() || TII->isPredicated(MI);
181 
182   // Scan the register operands for this instruction and update
183   // Classes and RegRefs.
184   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
185     MachineOperand &MO = MI.getOperand(i);
186     if (!MO.isReg()) continue;
187     Register Reg = MO.getReg();
188     if (Reg == 0) continue;
189     const TargetRegisterClass *NewRC = nullptr;
190 
191     if (i < MI.getDesc().getNumOperands())
192       NewRC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
193 
194     // For now, only allow the register to be changed if its register
195     // class is consistent across all uses.
196     if (!Classes[Reg] && NewRC)
197       Classes[Reg] = NewRC;
198     else if (!NewRC || Classes[Reg] != NewRC)
199       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
200 
201     // Now check for aliases.
202     for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
203       // If an alias of the reg is used during the live range, give up.
204       // Note that this allows us to skip checking if AntiDepReg
205       // overlaps with any of the aliases, among other things.
206       unsigned AliasReg = *AI;
207       if (Classes[AliasReg]) {
208         Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
209         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
210       }
211     }
212 
213     // If we're still willing to consider this register, note the reference.
214     if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
215       RegRefs.insert(std::make_pair(Reg, &MO));
216 
217     // If this reg is tied and live (Classes[Reg] is set to -1), we can't change
218     // it or any of its sub or super regs. We need to use KeepRegs to mark the
219     // reg because not all uses of the same reg within an instruction are
220     // necessarily tagged as tied.
221     // Example: an x86 "xor %eax, %eax" will have one source operand tied to the
222     // def register but not the second (see PR20020 for details).
223     // FIXME: can this check be relaxed to account for undef uses
224     // of a register? In the above 'xor' example, the uses of %eax are undef, so
225     // earlier instructions could still replace %eax even though the 'xor'
226     // itself can't be changed.
227     if (MI.isRegTiedToUseOperand(i) &&
228         Classes[Reg] == reinterpret_cast<TargetRegisterClass *>(-1)) {
229       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
230            SubRegs.isValid(); ++SubRegs) {
231         KeepRegs.set(*SubRegs);
232       }
233       for (MCSuperRegIterator SuperRegs(Reg, TRI);
234            SuperRegs.isValid(); ++SuperRegs) {
235         KeepRegs.set(*SuperRegs);
236       }
237     }
238 
239     if (MO.isUse() && Special) {
240       if (!KeepRegs.test(Reg)) {
241         for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
242              SubRegs.isValid(); ++SubRegs)
243           KeepRegs.set(*SubRegs);
244       }
245     }
246   }
247 }
248 
ScanInstruction(MachineInstr & MI,unsigned Count)249 void CriticalAntiDepBreaker::ScanInstruction(MachineInstr &MI, unsigned Count) {
250   // Update liveness.
251   // Proceeding upwards, registers that are defed but not used in this
252   // instruction are now dead.
253   assert(!MI.isKill() && "Attempting to scan a kill instruction");
254 
255   if (!TII->isPredicated(MI)) {
256     // Predicated defs are modeled as read + write, i.e. similar to two
257     // address updates.
258     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
259       MachineOperand &MO = MI.getOperand(i);
260 
261       if (MO.isRegMask()) {
262         auto ClobbersPhysRegAndSubRegs = [&](unsigned PhysReg) {
263           for (MCSubRegIterator SRI(PhysReg, TRI, true); SRI.isValid(); ++SRI)
264             if (!MO.clobbersPhysReg(*SRI))
265               return false;
266 
267           return true;
268         };
269 
270         for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) {
271           if (ClobbersPhysRegAndSubRegs(i)) {
272             DefIndices[i] = Count;
273             KillIndices[i] = ~0u;
274             KeepRegs.reset(i);
275             Classes[i] = nullptr;
276             RegRefs.erase(i);
277           }
278         }
279       }
280 
281       if (!MO.isReg()) continue;
282       Register Reg = MO.getReg();
283       if (Reg == 0) continue;
284       if (!MO.isDef()) continue;
285 
286       // Ignore two-addr defs.
287       if (MI.isRegTiedToUseOperand(i))
288         continue;
289 
290       // If we've already marked this reg as unchangeable, don't remove
291       // it or any of its subregs from KeepRegs.
292       bool Keep = KeepRegs.test(Reg);
293 
294       // For the reg itself and all subregs: update the def to current;
295       // reset the kill state, any restrictions, and references.
296       for (MCSubRegIterator SRI(Reg, TRI, true); SRI.isValid(); ++SRI) {
297         unsigned SubregReg = *SRI;
298         DefIndices[SubregReg] = Count;
299         KillIndices[SubregReg] = ~0u;
300         Classes[SubregReg] = nullptr;
301         RegRefs.erase(SubregReg);
302         if (!Keep)
303           KeepRegs.reset(SubregReg);
304       }
305       // Conservatively mark super-registers as unusable.
306       for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
307         Classes[*SR] = reinterpret_cast<TargetRegisterClass *>(-1);
308     }
309   }
310   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
311     MachineOperand &MO = MI.getOperand(i);
312     if (!MO.isReg()) continue;
313     Register Reg = MO.getReg();
314     if (Reg == 0) continue;
315     if (!MO.isUse()) continue;
316 
317     const TargetRegisterClass *NewRC = nullptr;
318     if (i < MI.getDesc().getNumOperands())
319       NewRC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
320 
321     // For now, only allow the register to be changed if its register
322     // class is consistent across all uses.
323     if (!Classes[Reg] && NewRC)
324       Classes[Reg] = NewRC;
325     else if (!NewRC || Classes[Reg] != NewRC)
326       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
327 
328     RegRefs.insert(std::make_pair(Reg, &MO));
329 
330     // It wasn't previously live but now it is, this is a kill.
331     // Repeat for all aliases.
332     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
333       unsigned AliasReg = *AI;
334       if (KillIndices[AliasReg] == ~0u) {
335         KillIndices[AliasReg] = Count;
336         DefIndices[AliasReg] = ~0u;
337       }
338     }
339   }
340 }
341 
342 // Check all machine operands that reference the antidependent register and must
343 // be replaced by NewReg. Return true if any of their parent instructions may
344 // clobber the new register.
345 //
346 // Note: AntiDepReg may be referenced by a two-address instruction such that
347 // it's use operand is tied to a def operand. We guard against the case in which
348 // the two-address instruction also defines NewReg, as may happen with
349 // pre/postincrement loads. In this case, both the use and def operands are in
350 // RegRefs because the def is inserted by PrescanInstruction and not erased
351 // during ScanInstruction. So checking for an instruction with definitions of
352 // both NewReg and AntiDepReg covers it.
353 bool
isNewRegClobberedByRefs(RegRefIter RegRefBegin,RegRefIter RegRefEnd,unsigned NewReg)354 CriticalAntiDepBreaker::isNewRegClobberedByRefs(RegRefIter RegRefBegin,
355                                                 RegRefIter RegRefEnd,
356                                                 unsigned NewReg) {
357   for (RegRefIter I = RegRefBegin; I != RegRefEnd; ++I ) {
358     MachineOperand *RefOper = I->second;
359 
360     // Don't allow the instruction defining AntiDepReg to earlyclobber its
361     // operands, in case they may be assigned to NewReg. In this case antidep
362     // breaking must fail, but it's too rare to bother optimizing.
363     if (RefOper->isDef() && RefOper->isEarlyClobber())
364       return true;
365 
366     // Handle cases in which this instruction defines NewReg.
367     MachineInstr *MI = RefOper->getParent();
368     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
369       const MachineOperand &CheckOper = MI->getOperand(i);
370 
371       if (CheckOper.isRegMask() && CheckOper.clobbersPhysReg(NewReg))
372         return true;
373 
374       if (!CheckOper.isReg() || !CheckOper.isDef() ||
375           CheckOper.getReg() != NewReg)
376         continue;
377 
378       // Don't allow the instruction to define NewReg and AntiDepReg.
379       // When AntiDepReg is renamed it will be an illegal op.
380       if (RefOper->isDef())
381         return true;
382 
383       // Don't allow an instruction using AntiDepReg to be earlyclobbered by
384       // NewReg.
385       if (CheckOper.isEarlyClobber())
386         return true;
387 
388       // Don't allow inline asm to define NewReg at all. Who knows what it's
389       // doing with it.
390       if (MI->isInlineAsm())
391         return true;
392     }
393   }
394   return false;
395 }
396 
397 unsigned CriticalAntiDepBreaker::
findSuitableFreeRegister(RegRefIter RegRefBegin,RegRefIter RegRefEnd,unsigned AntiDepReg,unsigned LastNewReg,const TargetRegisterClass * RC,SmallVectorImpl<unsigned> & Forbid)398 findSuitableFreeRegister(RegRefIter RegRefBegin,
399                          RegRefIter RegRefEnd,
400                          unsigned AntiDepReg,
401                          unsigned LastNewReg,
402                          const TargetRegisterClass *RC,
403                          SmallVectorImpl<unsigned> &Forbid) {
404   ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(RC);
405   for (unsigned i = 0; i != Order.size(); ++i) {
406     unsigned NewReg = Order[i];
407     // Don't replace a register with itself.
408     if (NewReg == AntiDepReg) continue;
409     // Don't replace a register with one that was recently used to repair
410     // an anti-dependence with this AntiDepReg, because that would
411     // re-introduce that anti-dependence.
412     if (NewReg == LastNewReg) continue;
413     // If any instructions that define AntiDepReg also define the NewReg, it's
414     // not suitable.  For example, Instruction with multiple definitions can
415     // result in this condition.
416     if (isNewRegClobberedByRefs(RegRefBegin, RegRefEnd, NewReg)) continue;
417     // If NewReg is dead and NewReg's most recent def is not before
418     // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
419     assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u))
420            && "Kill and Def maps aren't consistent for AntiDepReg!");
421     assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u))
422            && "Kill and Def maps aren't consistent for NewReg!");
423     if (KillIndices[NewReg] != ~0u ||
424         Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
425         KillIndices[AntiDepReg] > DefIndices[NewReg])
426       continue;
427     // If NewReg overlaps any of the forbidden registers, we can't use it.
428     bool Forbidden = false;
429     for (SmallVectorImpl<unsigned>::iterator it = Forbid.begin(),
430            ite = Forbid.end(); it != ite; ++it)
431       if (TRI->regsOverlap(NewReg, *it)) {
432         Forbidden = true;
433         break;
434       }
435     if (Forbidden) continue;
436     return NewReg;
437   }
438 
439   // No registers are free and available!
440   return 0;
441 }
442 
443 unsigned CriticalAntiDepBreaker::
BreakAntiDependencies(const std::vector<SUnit> & SUnits,MachineBasicBlock::iterator Begin,MachineBasicBlock::iterator End,unsigned InsertPosIndex,DbgValueVector & DbgValues)444 BreakAntiDependencies(const std::vector<SUnit> &SUnits,
445                       MachineBasicBlock::iterator Begin,
446                       MachineBasicBlock::iterator End,
447                       unsigned InsertPosIndex,
448                       DbgValueVector &DbgValues) {
449   // The code below assumes that there is at least one instruction,
450   // so just duck out immediately if the block is empty.
451   if (SUnits.empty()) return 0;
452 
453   // Keep a map of the MachineInstr*'s back to the SUnit representing them.
454   // This is used for updating debug information.
455   //
456   // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap
457   DenseMap<MachineInstr *, const SUnit *> MISUnitMap;
458 
459   // Find the node at the bottom of the critical path.
460   const SUnit *Max = nullptr;
461   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
462     const SUnit *SU = &SUnits[i];
463     MISUnitMap[SU->getInstr()] = SU;
464     if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
465       Max = SU;
466   }
467   assert(Max && "Failed to find bottom of the critical path");
468 
469 #ifndef NDEBUG
470   {
471     LLVM_DEBUG(dbgs() << "Critical path has total latency "
472                       << (Max->getDepth() + Max->Latency) << "\n");
473     LLVM_DEBUG(dbgs() << "Available regs:");
474     for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
475       if (KillIndices[Reg] == ~0u)
476         LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI));
477     }
478     LLVM_DEBUG(dbgs() << '\n');
479   }
480 #endif
481 
482   // Track progress along the critical path through the SUnit graph as we walk
483   // the instructions.
484   const SUnit *CriticalPathSU = Max;
485   MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
486 
487   // Consider this pattern:
488   //   A = ...
489   //   ... = A
490   //   A = ...
491   //   ... = A
492   //   A = ...
493   //   ... = A
494   //   A = ...
495   //   ... = A
496   // There are three anti-dependencies here, and without special care,
497   // we'd break all of them using the same register:
498   //   A = ...
499   //   ... = A
500   //   B = ...
501   //   ... = B
502   //   B = ...
503   //   ... = B
504   //   B = ...
505   //   ... = B
506   // because at each anti-dependence, B is the first register that
507   // isn't A which is free.  This re-introduces anti-dependencies
508   // at all but one of the original anti-dependencies that we were
509   // trying to break.  To avoid this, keep track of the most recent
510   // register that each register was replaced with, avoid
511   // using it to repair an anti-dependence on the same register.
512   // This lets us produce this:
513   //   A = ...
514   //   ... = A
515   //   B = ...
516   //   ... = B
517   //   C = ...
518   //   ... = C
519   //   B = ...
520   //   ... = B
521   // This still has an anti-dependence on B, but at least it isn't on the
522   // original critical path.
523   //
524   // TODO: If we tracked more than one register here, we could potentially
525   // fix that remaining critical edge too. This is a little more involved,
526   // because unlike the most recent register, less recent registers should
527   // still be considered, though only if no other registers are available.
528   std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0);
529 
530   // Attempt to break anti-dependence edges on the critical path. Walk the
531   // instructions from the bottom up, tracking information about liveness
532   // as we go to help determine which registers are available.
533   unsigned Broken = 0;
534   unsigned Count = InsertPosIndex - 1;
535   for (MachineBasicBlock::iterator I = End, E = Begin; I != E; --Count) {
536     MachineInstr &MI = *--I;
537     // Kill instructions can define registers but are really nops, and there
538     // might be a real definition earlier that needs to be paired with uses
539     // dominated by this kill.
540 
541     // FIXME: It may be possible to remove the isKill() restriction once PR18663
542     // has been properly fixed. There can be value in processing kills as seen
543     // in the AggressiveAntiDepBreaker class.
544     if (MI.isDebugInstr() || MI.isKill())
545       continue;
546 
547     // Check if this instruction has a dependence on the critical path that
548     // is an anti-dependence that we may be able to break. If it is, set
549     // AntiDepReg to the non-zero register associated with the anti-dependence.
550     //
551     // We limit our attention to the critical path as a heuristic to avoid
552     // breaking anti-dependence edges that aren't going to significantly
553     // impact the overall schedule. There are a limited number of registers
554     // and we want to save them for the important edges.
555     //
556     // TODO: Instructions with multiple defs could have multiple
557     // anti-dependencies. The current code here only knows how to break one
558     // edge per instruction. Note that we'd have to be able to break all of
559     // the anti-dependencies in an instruction in order to be effective.
560     unsigned AntiDepReg = 0;
561     if (&MI == CriticalPathMI) {
562       if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) {
563         const SUnit *NextSU = Edge->getSUnit();
564 
565         // Only consider anti-dependence edges.
566         if (Edge->getKind() == SDep::Anti) {
567           AntiDepReg = Edge->getReg();
568           assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
569           if (!MRI.isAllocatable(AntiDepReg))
570             // Don't break anti-dependencies on non-allocatable registers.
571             AntiDepReg = 0;
572           else if (KeepRegs.test(AntiDepReg))
573             // Don't break anti-dependencies if a use down below requires
574             // this exact register.
575             AntiDepReg = 0;
576           else {
577             // If the SUnit has other dependencies on the SUnit that it
578             // anti-depends on, don't bother breaking the anti-dependency
579             // since those edges would prevent such units from being
580             // scheduled past each other regardless.
581             //
582             // Also, if there are dependencies on other SUnits with the
583             // same register as the anti-dependency, don't attempt to
584             // break it.
585             for (SUnit::const_pred_iterator P = CriticalPathSU->Preds.begin(),
586                  PE = CriticalPathSU->Preds.end(); P != PE; ++P)
587               if (P->getSUnit() == NextSU ?
588                     (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
589                     (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
590                 AntiDepReg = 0;
591                 break;
592               }
593           }
594         }
595         CriticalPathSU = NextSU;
596         CriticalPathMI = CriticalPathSU->getInstr();
597       } else {
598         // We've reached the end of the critical path.
599         CriticalPathSU = nullptr;
600         CriticalPathMI = nullptr;
601       }
602     }
603 
604     PrescanInstruction(MI);
605 
606     SmallVector<unsigned, 2> ForbidRegs;
607 
608     // If MI's defs have a special allocation requirement, don't allow
609     // any def registers to be changed. Also assume all registers
610     // defined in a call must not be changed (ABI).
611     if (MI.isCall() || MI.hasExtraDefRegAllocReq() || TII->isPredicated(MI))
612       // If this instruction's defs have special allocation requirement, don't
613       // break this anti-dependency.
614       AntiDepReg = 0;
615     else if (AntiDepReg) {
616       // If this instruction has a use of AntiDepReg, breaking it
617       // is invalid.  If the instruction defines other registers,
618       // save a list of them so that we don't pick a new register
619       // that overlaps any of them.
620       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
621         MachineOperand &MO = MI.getOperand(i);
622         if (!MO.isReg()) continue;
623         Register Reg = MO.getReg();
624         if (Reg == 0) continue;
625         if (MO.isUse() && TRI->regsOverlap(AntiDepReg, Reg)) {
626           AntiDepReg = 0;
627           break;
628         }
629         if (MO.isDef() && Reg != AntiDepReg)
630           ForbidRegs.push_back(Reg);
631       }
632     }
633 
634     // Determine AntiDepReg's register class, if it is live and is
635     // consistently used within a single class.
636     const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg]
637                                                     : nullptr;
638     assert((AntiDepReg == 0 || RC != nullptr) &&
639            "Register should be live if it's causing an anti-dependence!");
640     if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
641       AntiDepReg = 0;
642 
643     // Look for a suitable register to use to break the anti-dependence.
644     //
645     // TODO: Instead of picking the first free register, consider which might
646     // be the best.
647     if (AntiDepReg != 0) {
648       std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
649                 std::multimap<unsigned, MachineOperand *>::iterator>
650         Range = RegRefs.equal_range(AntiDepReg);
651       if (unsigned NewReg = findSuitableFreeRegister(Range.first, Range.second,
652                                                      AntiDepReg,
653                                                      LastNewReg[AntiDepReg],
654                                                      RC, ForbidRegs)) {
655         LLVM_DEBUG(dbgs() << "Breaking anti-dependence edge on "
656                           << printReg(AntiDepReg, TRI) << " with "
657                           << RegRefs.count(AntiDepReg) << " references"
658                           << " using " << printReg(NewReg, TRI) << "!\n");
659 
660         // Update the references to the old register to refer to the new
661         // register.
662         for (std::multimap<unsigned, MachineOperand *>::iterator
663              Q = Range.first, QE = Range.second; Q != QE; ++Q) {
664           Q->second->setReg(NewReg);
665           // If the SU for the instruction being updated has debug information
666           // related to the anti-dependency register, make sure to update that
667           // as well.
668           const SUnit *SU = MISUnitMap[Q->second->getParent()];
669           if (!SU) continue;
670           UpdateDbgValues(DbgValues, Q->second->getParent(),
671                           AntiDepReg, NewReg);
672         }
673 
674         // We just went back in time and modified history; the
675         // liveness information for the anti-dependence reg is now
676         // inconsistent. Set the state as if it were dead.
677         Classes[NewReg] = Classes[AntiDepReg];
678         DefIndices[NewReg] = DefIndices[AntiDepReg];
679         KillIndices[NewReg] = KillIndices[AntiDepReg];
680         assert(((KillIndices[NewReg] == ~0u) !=
681                 (DefIndices[NewReg] == ~0u)) &&
682              "Kill and Def maps aren't consistent for NewReg!");
683 
684         Classes[AntiDepReg] = nullptr;
685         DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
686         KillIndices[AntiDepReg] = ~0u;
687         assert(((KillIndices[AntiDepReg] == ~0u) !=
688                 (DefIndices[AntiDepReg] == ~0u)) &&
689              "Kill and Def maps aren't consistent for AntiDepReg!");
690 
691         RegRefs.erase(AntiDepReg);
692         LastNewReg[AntiDepReg] = NewReg;
693         ++Broken;
694       }
695     }
696 
697     ScanInstruction(MI, Count);
698   }
699 
700   return Broken;
701 }
702 
703 AntiDepBreaker *
createCriticalAntiDepBreaker(MachineFunction & MFi,const RegisterClassInfo & RCI)704 llvm::createCriticalAntiDepBreaker(MachineFunction &MFi,
705                                    const RegisterClassInfo &RCI) {
706   return new CriticalAntiDepBreaker(MFi, RCI);
707 }
708