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