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