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