brintos

brintos / llvm-project-archived public Read only

0
0
Text · 27.5 KiB · 3259a3e Raw
702 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8//9// This file implements the CriticalAntiDepBreaker class, which10// implements register anti-dependence breaking along a blocks11// 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 37using namespace llvm;38 39#define DEBUG_TYPE "post-RA-sched"40 41CriticalAntiDepBreaker::CriticalAntiDepBreaker(MachineFunction &MFi,42                                               const RegisterClassInfo &RCI)43    : MF(MFi), MRI(MF.getRegInfo()), TII(MF.getSubtarget().getInstrInfo()),44      TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI),45      Classes(TRI->getNumRegs(), nullptr), KillIndices(TRI->getNumRegs(), 0),46      DefIndices(TRI->getNumRegs(), 0), KeepRegs(TRI->getNumRegs(), false) {}47 48CriticalAntiDepBreaker::~CriticalAntiDepBreaker() = default;49 50void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {51  const unsigned BBSize = BB->size();52  for (unsigned i = 1, e = TRI->getNumRegs(); i != e; ++i) {53    // Clear out the register class data.54    Classes[i] = nullptr;55 56    // Initialize the indices to indicate that no registers are live.57    KillIndices[i] = ~0u;58    DefIndices[i] = BBSize;59  }60 61  // Clear "do not change" set.62  KeepRegs.reset();63 64  bool IsReturnBlock = BB->isReturnBlock();65 66  // Examine the live-in regs of all successors.67  for (const MachineBasicBlock *Succ : BB->successors())68    for (const auto &LI : Succ->liveins()) {69      for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI) {70        MCRegister Reg = *AI;71        Classes[Reg.id()] = reinterpret_cast<TargetRegisterClass *>(-1);72        KillIndices[Reg.id()] = BBSize;73        DefIndices[Reg.id()] = ~0u;74      }75    }76 77  // Mark live-out callee-saved registers. In a return block this is78  // all callee-saved registers. In non-return this is any79  // callee-saved register that is not saved in the prolog.80  const MachineFrameInfo &MFI = MF.getFrameInfo();81  BitVector Pristine = MFI.getPristineRegs(MF);82  for (const MCPhysReg *I = MF.getRegInfo().getCalleeSavedRegs(); *I;83       ++I) {84    unsigned Reg = *I;85    if (!IsReturnBlock && !Pristine.test(Reg))86      continue;87    for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {88      MCRegister Reg = *AI;89      Classes[Reg.id()] = reinterpret_cast<TargetRegisterClass *>(-1);90      KillIndices[Reg.id()] = BBSize;91      DefIndices[Reg.id()] = ~0u;92    }93  }94}95 96void CriticalAntiDepBreaker::FinishBlock() {97  RegRefs.clear();98  KeepRegs.reset();99}100 101void CriticalAntiDepBreaker::Observe(MachineInstr &MI, unsigned Count,102                                     unsigned InsertPosIndex) {103  // Kill instructions can define registers but are really nops, and there might104  // be a real definition earlier that needs to be paired with uses dominated by105  // this kill.106 107  // FIXME: It may be possible to remove the isKill() restriction once PR18663108  // has been properly fixed. There can be value in processing kills as seen in109  // the AggressiveAntiDepBreaker class.110  if (MI.isDebugInstr() || MI.isKill())111    return;112  assert(Count < InsertPosIndex && "Instruction index out of expected range!");113 114  for (unsigned Reg = 1; Reg != TRI->getNumRegs(); ++Reg) {115    if (KillIndices[Reg] != ~0u) {116      // If Reg is currently live, then mark that it can't be renamed as117      // we don't know the extent of its live-range anymore (now that it118      // has been scheduled).119      Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);120      KillIndices[Reg] = Count;121    } else if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {122      // Any register which was defined within the previous scheduling region123      // may have been rescheduled and its lifetime may overlap with registers124      // in ways not reflected in our current liveness state. For each such125      // register, adjust the liveness state to be conservatively correct.126      Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);127 128      // Move the def index to the end of the previous region, to reflect129      // that the def could theoretically have been scheduled at the end.130      DefIndices[Reg] = InsertPosIndex;131    }132  }133 134  PrescanInstruction(MI);135  ScanInstruction(MI, Count);136}137 138/// CriticalPathStep - Return the next SUnit after SU on the bottom-up139/// critical path.140static const SDep *CriticalPathStep(const SUnit *SU) {141  const SDep *Next = nullptr;142  unsigned NextDepth = 0;143  // Find the predecessor edge with the greatest depth.144  for (const SDep &P : SU->Preds) {145    const SUnit *PredSU = P.getSUnit();146    unsigned PredLatency = P.getLatency();147    unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;148    // In the case of a latency tie, prefer an anti-dependency edge over149    // other types of edges.150    if (NextDepth < PredTotalLatency ||151        (NextDepth == PredTotalLatency && P.getKind() == SDep::Anti)) {152      NextDepth = PredTotalLatency;153      Next = &P;154    }155  }156  return Next;157}158 159void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr &MI) {160  // It's not safe to change register allocation for source operands of161  // instructions that have special allocation requirements. Also assume all162  // registers used in a call must not be changed (ABI).163  // FIXME: The issue with predicated instruction is more complex. We are being164  // conservative here because the kill markers cannot be trusted after165  // if-conversion:166  // %r6 = LDR %sp, %reg0, 92, 14, %reg0; mem:LD4[FixedStack14]167  // ...168  // STR %r0, killed %r6, %reg0, 0, 0, %cpsr; mem:ST4[%395]169  // %r6 = LDR %sp, %reg0, 100, 0, %cpsr; mem:LD4[FixedStack12]170  // STR %r0, killed %r6, %reg0, 0, 14, %reg0; mem:ST4[%396](align=8)171  //172  // The first R6 kill is not really a kill since it's killed by a predicated173  // instruction which may not be executed. The second R6 def may or may not174  // re-define R6 so it's not safe to change it since the last R6 use cannot be175  // changed.176  bool Special =177      MI.isCall() || MI.hasExtraSrcRegAllocReq() || TII->isPredicated(MI);178 179  // Scan the register operands for this instruction and update180  // Classes and RegRefs.181  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {182    MachineOperand &MO = MI.getOperand(i);183    if (!MO.isReg()) continue;184    Register Reg = MO.getReg();185    if (!Reg)186      continue;187    const TargetRegisterClass *NewRC = nullptr;188 189    if (i < MI.getDesc().getNumOperands())190      NewRC = TII->getRegClass(MI.getDesc(), i);191 192    // For now, only allow the register to be changed if its register193    // class is consistent across all uses.194    if (!Classes[Reg.id()] && NewRC)195      Classes[Reg.id()] = NewRC;196    else if (!NewRC || Classes[Reg.id()] != NewRC)197      Classes[Reg.id()] = reinterpret_cast<TargetRegisterClass *>(-1);198 199    // Now check for aliases.200    for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {201      // If an alias of the reg is used during the live range, give up.202      // Note that this allows us to skip checking if AntiDepReg203      // overlaps with any of the aliases, among other things.204      unsigned AliasReg = (*AI).id();205      if (Classes[AliasReg]) {206        Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);207        Classes[Reg.id()] = reinterpret_cast<TargetRegisterClass *>(-1);208      }209    }210 211    // If we're still willing to consider this register, note the reference.212    if (Classes[Reg.id()] != reinterpret_cast<TargetRegisterClass *>(-1))213      RegRefs.emplace(Reg, &MO);214 215    if (MO.isUse() && Special) {216      if (!KeepRegs.test(Reg.id())) {217        for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg))218          KeepRegs.set(SubReg);219      }220    }221  }222 223  for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {224    const MachineOperand &MO = MI.getOperand(I);225    if (!MO.isReg()) continue;226    Register Reg = MO.getReg();227    if (!Reg.isValid())228      continue;229    // If this reg is tied and live (Classes[Reg] is set to -1), we can't change230    // it or any of its sub or super regs. We need to use KeepRegs to mark the231    // reg because not all uses of the same reg within an instruction are232    // necessarily tagged as tied.233    // Example: an x86 "xor %eax, %eax" will have one source operand tied to the234    // def register but not the second (see PR20020 for details).235    // FIXME: can this check be relaxed to account for undef uses236    // of a register? In the above 'xor' example, the uses of %eax are undef, so237    // earlier instructions could still replace %eax even though the 'xor'238    // itself can't be changed.239    if (MI.isRegTiedToUseOperand(I) &&240        Classes[Reg.id()] == reinterpret_cast<TargetRegisterClass *>(-1)) {241      for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg)) {242        KeepRegs.set(SubReg);243      }244      for (MCPhysReg SuperReg : TRI->superregs(Reg)) {245        KeepRegs.set(SuperReg);246      }247    }248  }249}250 251void CriticalAntiDepBreaker::ScanInstruction(MachineInstr &MI, unsigned Count) {252  // Update liveness.253  // Proceeding upwards, registers that are defed but not used in this254  // instruction are now dead.255  assert(!MI.isKill() && "Attempting to scan a kill instruction");256 257  if (!TII->isPredicated(MI)) {258    // Predicated defs are modeled as read + write, i.e. similar to two259    // address updates.260    for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {261      MachineOperand &MO = MI.getOperand(i);262 263      if (MO.isRegMask()) {264        auto ClobbersPhysRegAndSubRegs = [&](unsigned PhysReg) {265          return all_of(TRI->subregs_inclusive(PhysReg),266                        [&](MCPhysReg SR) { return MO.clobbersPhysReg(SR); });267        };268 269        for (unsigned i = 1, e = TRI->getNumRegs(); i != e; ++i) {270          if (ClobbersPhysRegAndSubRegs(i)) {271            DefIndices[i] = Count;272            KillIndices[i] = ~0u;273            KeepRegs.reset(i);274            Classes[i] = nullptr;275            RegRefs.erase(i);276          }277        }278      }279 280      if (!MO.isReg()) continue;281      Register Reg = MO.getReg();282      if (!Reg)283        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 remove291      // it or any of its subregs from KeepRegs.292      bool Keep = KeepRegs.test(Reg.id());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 (MCPhysReg SubregReg : TRI->subregs_inclusive(Reg)) {297        DefIndices[SubregReg] = Count;298        KillIndices[SubregReg] = ~0u;299        Classes[SubregReg] = nullptr;300        RegRefs.erase(SubregReg);301        if (!Keep)302          KeepRegs.reset(SubregReg);303      }304      // Conservatively mark super-registers as unusable.305      for (MCPhysReg SR : TRI->superregs(Reg))306        Classes[SR] = reinterpret_cast<TargetRegisterClass *>(-1);307    }308  }309  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {310    MachineOperand &MO = MI.getOperand(i);311    if (!MO.isReg()) continue;312    Register Reg = MO.getReg();313    if (!Reg)314      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);320 321    // For now, only allow the register to be changed if its register322    // class is consistent across all uses.323    if (!Classes[Reg.id()] && NewRC)324      Classes[Reg.id()] = NewRC;325    else if (!NewRC || Classes[Reg.id()] != NewRC)326      Classes[Reg.id()] = reinterpret_cast<TargetRegisterClass *>(-1);327 328    RegRefs.emplace(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      MCRegister AliasReg = *AI;334      if (KillIndices[AliasReg.id()] == ~0u) {335        KillIndices[AliasReg.id()] = Count;336        DefIndices[AliasReg.id()] = ~0u;337      }338    }339  }340}341 342// Check all machine operands that reference the antidependent register and must343// be replaced by NewReg. Return true if any of their parent instructions may344// clobber the new register.345//346// Note: AntiDepReg may be referenced by a two-address instruction such that347// it's use operand is tied to a def operand. We guard against the case in which348// the two-address instruction also defines NewReg, as may happen with349// pre/postincrement loads. In this case, both the use and def operands are in350// RegRefs because the def is inserted by PrescanInstruction and not erased351// during ScanInstruction. So checking for an instruction with definitions of352// both NewReg and AntiDepReg covers it.353bool CriticalAntiDepBreaker::isNewRegClobberedByRefs(RegRefIter RegRefBegin,354                                                     RegRefIter RegRefEnd,355                                                     MCRegister NewReg) {356  for (RegRefIter I = RegRefBegin; I != RegRefEnd; ++I ) {357    MachineOperand *RefOper = I->second;358 359    // Don't allow the instruction defining AntiDepReg to earlyclobber its360    // operands, in case they may be assigned to NewReg. In this case antidep361    // breaking must fail, but it's too rare to bother optimizing.362    if (RefOper->isDef() && RefOper->isEarlyClobber())363      return true;364 365    // Handle cases in which this instruction defines NewReg.366    MachineInstr *MI = RefOper->getParent();367    for (const MachineOperand &CheckOper : MI->operands()) {368      if (CheckOper.isRegMask() && CheckOper.clobbersPhysReg(NewReg))369        return true;370 371      if (!CheckOper.isReg() || !CheckOper.isDef() ||372          CheckOper.getReg() != NewReg)373        continue;374 375      // Don't allow the instruction to define NewReg and AntiDepReg.376      // When AntiDepReg is renamed it will be an illegal op.377      if (RefOper->isDef())378        return true;379 380      // Don't allow an instruction using AntiDepReg to be earlyclobbered by381      // NewReg.382      if (CheckOper.isEarlyClobber())383        return true;384 385      // Don't allow inline asm to define NewReg at all. Who knows what it's386      // doing with it.387      if (MI->isInlineAsm())388        return true;389    }390  }391  return false;392}393 394MCRegister CriticalAntiDepBreaker::findSuitableFreeRegister(395    RegRefIter RegRefBegin, RegRefIter RegRefEnd, MCRegister AntiDepReg,396    MCRegister LastNewReg, const TargetRegisterClass *RC,397    const SmallVectorImpl<Register> &Forbid) {398  ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(RC);399  for (MCRegister NewReg : Order) {400    // Don't replace a register with itself.401    if (NewReg == AntiDepReg) continue;402    // Don't replace a register with one that was recently used to repair403    // an anti-dependence with this AntiDepReg, because that would404    // re-introduce that anti-dependence.405    if (NewReg == LastNewReg) continue;406    // If any instructions that define AntiDepReg also define the NewReg, it's407    // not suitable.  For example, Instruction with multiple definitions can408    // result in this condition.409    if (isNewRegClobberedByRefs(RegRefBegin, RegRefEnd, NewReg)) continue;410    // If NewReg is dead and NewReg's most recent def is not before411    // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.412    assert(((KillIndices[AntiDepReg.id()] == ~0u) !=413            (DefIndices[AntiDepReg.id()] == ~0u)) &&414           "Kill and Def maps aren't consistent for AntiDepReg!");415    assert(((KillIndices[NewReg.id()] == ~0u) !=416            (DefIndices[NewReg.id()] == ~0u)) &&417           "Kill and Def maps aren't consistent for NewReg!");418    if (KillIndices[NewReg.id()] != ~0u ||419        Classes[NewReg.id()] == reinterpret_cast<TargetRegisterClass *>(-1) ||420        KillIndices[AntiDepReg.id()] > DefIndices[NewReg.id()])421      continue;422    // If NewReg overlaps any of the forbidden registers, we can't use it.423    bool Forbidden = false;424    for (Register R : Forbid)425      if (TRI->regsOverlap(NewReg, R)) {426        Forbidden = true;427        break;428      }429    if (Forbidden) continue;430    return NewReg;431  }432 433  // No registers are free and available!434  return MCRegister();435}436 437unsigned CriticalAntiDepBreaker::438BreakAntiDependencies(const std::vector<SUnit> &SUnits,439                      MachineBasicBlock::iterator Begin,440                      MachineBasicBlock::iterator End,441                      unsigned InsertPosIndex,442                      DbgValueVector &DbgValues) {443  // The code below assumes that there is at least one instruction,444  // so just duck out immediately if the block is empty.445  if (SUnits.empty()) return 0;446 447  // Keep a map of the MachineInstr*'s back to the SUnit representing them.448  // This is used for updating debug information.449  //450  // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap451  DenseMap<MachineInstr *, const SUnit *> MISUnitMap;452 453  // Find the node at the bottom of the critical path.454  const SUnit *Max = nullptr;455  for (const SUnit &SU : SUnits) {456    MISUnitMap[SU.getInstr()] = &SU;457    if (!Max || SU.getDepth() + SU.Latency > Max->getDepth() + Max->Latency)458      Max = &SU;459  }460  assert(Max && "Failed to find bottom of the critical path");461 462#ifndef NDEBUG463  {464    LLVM_DEBUG(dbgs() << "Critical path has total latency "465                      << (Max->getDepth() + Max->Latency) << "\n");466    LLVM_DEBUG(dbgs() << "Available regs:");467    for (unsigned Reg = 1; Reg < TRI->getNumRegs(); ++Reg) {468      if (KillIndices[Reg] == ~0u)469        LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI));470    }471    LLVM_DEBUG(dbgs() << '\n');472  }473#endif474 475  // Track progress along the critical path through the SUnit graph as we walk476  // the instructions.477  const SUnit *CriticalPathSU = Max;478  MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();479 480  // Consider this pattern:481  //   A = ...482  //   ... = A483  //   A = ...484  //   ... = A485  //   A = ...486  //   ... = A487  //   A = ...488  //   ... = A489  // There are three anti-dependencies here, and without special care,490  // we'd break all of them using the same register:491  //   A = ...492  //   ... = A493  //   B = ...494  //   ... = B495  //   B = ...496  //   ... = B497  //   B = ...498  //   ... = B499  // because at each anti-dependence, B is the first register that500  // isn't A which is free.  This re-introduces anti-dependencies501  // at all but one of the original anti-dependencies that we were502  // trying to break.  To avoid this, keep track of the most recent503  // register that each register was replaced with, avoid504  // using it to repair an anti-dependence on the same register.505  // This lets us produce this:506  //   A = ...507  //   ... = A508  //   B = ...509  //   ... = B510  //   C = ...511  //   ... = C512  //   B = ...513  //   ... = B514  // This still has an anti-dependence on B, but at least it isn't on the515  // original critical path.516  //517  // TODO: If we tracked more than one register here, we could potentially518  // fix that remaining critical edge too. This is a little more involved,519  // because unlike the most recent register, less recent registers should520  // still be considered, though only if no other registers are available.521  std::vector<MCRegister> LastNewReg(TRI->getNumRegs(), MCRegister());522 523  // Attempt to break anti-dependence edges on the critical path. Walk the524  // instructions from the bottom up, tracking information about liveness525  // as we go to help determine which registers are available.526  unsigned Broken = 0;527  unsigned Count = InsertPosIndex - 1;528  for (MachineBasicBlock::iterator I = End, E = Begin; I != E; --Count) {529    MachineInstr &MI = *--I;530    // Kill instructions can define registers but are really nops, and there531    // might be a real definition earlier that needs to be paired with uses532    // dominated by this kill.533 534    // FIXME: It may be possible to remove the isKill() restriction once PR18663535    // has been properly fixed. There can be value in processing kills as seen536    // in the AggressiveAntiDepBreaker class.537    if (MI.isDebugInstr() || MI.isKill())538      continue;539 540    // Check if this instruction has a dependence on the critical path that541    // is an anti-dependence that we may be able to break. If it is, set542    // AntiDepReg to the non-zero register associated with the anti-dependence.543    //544    // We limit our attention to the critical path as a heuristic to avoid545    // breaking anti-dependence edges that aren't going to significantly546    // impact the overall schedule. There are a limited number of registers547    // and we want to save them for the important edges.548    //549    // TODO: Instructions with multiple defs could have multiple550    // anti-dependencies. The current code here only knows how to break one551    // edge per instruction. Note that we'd have to be able to break all of552    // the anti-dependencies in an instruction in order to be effective.553    MCRegister AntiDepReg;554    if (&MI == CriticalPathMI) {555      if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) {556        const SUnit *NextSU = Edge->getSUnit();557 558        // Only consider anti-dependence edges.559        if (Edge->getKind() == SDep::Anti) {560          AntiDepReg = Edge->getReg().asMCReg();561          assert(AntiDepReg && "Anti-dependence on reg0?");562          if (!MRI.isAllocatable(AntiDepReg))563            // Don't break anti-dependencies on non-allocatable registers.564            AntiDepReg = MCRegister();565          else if (KeepRegs.test(AntiDepReg.id()))566            // Don't break anti-dependencies if a use down below requires567            // this exact register.568            AntiDepReg = MCRegister();569          else {570            // If the SUnit has other dependencies on the SUnit that it571            // anti-depends on, don't bother breaking the anti-dependency572            // since those edges would prevent such units from being573            // scheduled past each other regardless.574            //575            // Also, if there are dependencies on other SUnits with the576            // same register as the anti-dependency, don't attempt to577            // break it.578            for (const SDep &P : CriticalPathSU->Preds)579              if (P.getSUnit() == NextSU580                      ? (P.getKind() != SDep::Anti || P.getReg() != AntiDepReg)581                      : (P.getKind() == SDep::Data &&582                         P.getReg() == AntiDepReg)) {583                AntiDepReg = MCRegister();584                break;585              }586          }587        }588        CriticalPathSU = NextSU;589        CriticalPathMI = CriticalPathSU->getInstr();590      } else {591        // We've reached the end of the critical path.592        CriticalPathSU = nullptr;593        CriticalPathMI = nullptr;594      }595    }596 597    PrescanInstruction(MI);598 599    SmallVector<Register, 2> ForbidRegs;600 601    // If MI's defs have a special allocation requirement, don't allow602    // any def registers to be changed. Also assume all registers603    // defined in a call must not be changed (ABI).604    if (MI.isCall() || MI.hasExtraDefRegAllocReq() || TII->isPredicated(MI))605      // If this instruction's defs have special allocation requirement, don't606      // break this anti-dependency.607      AntiDepReg = MCRegister();608    else if (AntiDepReg) {609      // If this instruction has a use of AntiDepReg, breaking it610      // is invalid.  If the instruction defines other registers,611      // save a list of them so that we don't pick a new register612      // that overlaps any of them.613      for (const MachineOperand &MO : MI.operands()) {614        if (!MO.isReg()) continue;615        Register Reg = MO.getReg();616        if (!Reg)617          continue;618        if (MO.isUse() && TRI->regsOverlap(AntiDepReg, Reg)) {619          AntiDepReg = MCRegister();620          break;621        }622        if (MO.isDef() && Reg != AntiDepReg)623          ForbidRegs.push_back(Reg);624      }625    }626 627    // Determine AntiDepReg's register class, if it is live and is628    // consistently used within a single class.629    const TargetRegisterClass *RC =630        AntiDepReg ? Classes[AntiDepReg.id()] : nullptr;631    assert((!AntiDepReg || RC != nullptr) &&632           "Register should be live if it's causing an anti-dependence!");633    if (RC == reinterpret_cast<TargetRegisterClass *>(-1))634      AntiDepReg = MCRegister();635 636    // Look for a suitable register to use to break the anti-dependence.637    //638    // TODO: Instead of picking the first free register, consider which might639    // be the best.640    if (AntiDepReg) {641      std::pair<std::multimap<MCRegister, MachineOperand *>::iterator,642                std::multimap<MCRegister, MachineOperand *>::iterator>643          Range = RegRefs.equal_range(AntiDepReg);644      if (MCRegister NewReg = findSuitableFreeRegister(645              Range.first, Range.second, AntiDepReg,646              LastNewReg[AntiDepReg.id()], RC, ForbidRegs)) {647        LLVM_DEBUG(dbgs() << "Breaking anti-dependence edge on "648                          << printReg(AntiDepReg, TRI) << " with "649                          << RegRefs.count(AntiDepReg) << " references"650                          << " using " << printReg(NewReg, TRI) << "!\n");651 652        // Update the references to the old register to refer to the new653        // register.654        for (std::multimap<MCRegister, MachineOperand *>::iterator655                 Q = Range.first,656                 QE = Range.second;657             Q != QE; ++Q) {658          Q->second->setReg(NewReg);659          // If the SU for the instruction being updated has debug information660          // related to the anti-dependency register, make sure to update that661          // as well.662          const SUnit *SU = MISUnitMap[Q->second->getParent()];663          if (!SU) continue;664          UpdateDbgValues(DbgValues, Q->second->getParent(),665                          AntiDepReg, NewReg);666        }667 668        // We just went back in time and modified history; the669        // liveness information for the anti-dependence reg is now670        // inconsistent. Set the state as if it were dead.671        Classes[NewReg.id()] = Classes[AntiDepReg.id()];672        DefIndices[NewReg.id()] = DefIndices[AntiDepReg.id()];673        KillIndices[NewReg.id()] = KillIndices[AntiDepReg.id()];674        assert(((KillIndices[NewReg.id()] == ~0u) !=675                (DefIndices[NewReg.id()] == ~0u)) &&676               "Kill and Def maps aren't consistent for NewReg!");677 678        Classes[AntiDepReg.id()] = nullptr;679        DefIndices[AntiDepReg.id()] = KillIndices[AntiDepReg.id()];680        KillIndices[AntiDepReg.id()] = ~0u;681        assert(((KillIndices[AntiDepReg.id()] == ~0u) !=682                (DefIndices[AntiDepReg.id()] == ~0u)) &&683               "Kill and Def maps aren't consistent for AntiDepReg!");684 685        RegRefs.erase(AntiDepReg);686        LastNewReg[AntiDepReg.id()] = NewReg;687        ++Broken;688      }689    }690 691    ScanInstruction(MI, Count);692  }693 694  return Broken;695}696 697AntiDepBreaker *698llvm::createCriticalAntiDepBreaker(MachineFunction &MFi,699                                   const RegisterClassInfo &RCI) {700  return new CriticalAntiDepBreaker(MFi, RCI);701}702