17330f729Sjoerg //===- CriticalAntiDepBreaker.cpp - Anti-dep breaker ----------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This file implements the CriticalAntiDepBreaker class, which
107330f729Sjoerg // implements register anti-dependence breaking along a blocks
117330f729Sjoerg // critical path during post-RA scheduler.
127330f729Sjoerg //
137330f729Sjoerg //===----------------------------------------------------------------------===//
147330f729Sjoerg
157330f729Sjoerg #include "CriticalAntiDepBreaker.h"
167330f729Sjoerg #include "llvm/ADT/ArrayRef.h"
177330f729Sjoerg #include "llvm/ADT/DenseMap.h"
187330f729Sjoerg #include "llvm/ADT/SmallVector.h"
197330f729Sjoerg #include "llvm/CodeGen/MachineBasicBlock.h"
207330f729Sjoerg #include "llvm/CodeGen/MachineFrameInfo.h"
217330f729Sjoerg #include "llvm/CodeGen/MachineFunction.h"
227330f729Sjoerg #include "llvm/CodeGen/MachineInstr.h"
237330f729Sjoerg #include "llvm/CodeGen/MachineOperand.h"
247330f729Sjoerg #include "llvm/CodeGen/MachineRegisterInfo.h"
257330f729Sjoerg #include "llvm/CodeGen/RegisterClassInfo.h"
267330f729Sjoerg #include "llvm/CodeGen/ScheduleDAG.h"
277330f729Sjoerg #include "llvm/CodeGen/TargetInstrInfo.h"
287330f729Sjoerg #include "llvm/CodeGen/TargetRegisterInfo.h"
297330f729Sjoerg #include "llvm/CodeGen/TargetSubtargetInfo.h"
307330f729Sjoerg #include "llvm/MC/MCInstrDesc.h"
317330f729Sjoerg #include "llvm/MC/MCRegisterInfo.h"
327330f729Sjoerg #include "llvm/Support/Debug.h"
337330f729Sjoerg #include "llvm/Support/raw_ostream.h"
347330f729Sjoerg #include <cassert>
357330f729Sjoerg #include <utility>
367330f729Sjoerg
377330f729Sjoerg using namespace llvm;
387330f729Sjoerg
397330f729Sjoerg #define DEBUG_TYPE "post-RA-sched"
407330f729Sjoerg
CriticalAntiDepBreaker(MachineFunction & MFi,const RegisterClassInfo & RCI)417330f729Sjoerg CriticalAntiDepBreaker::CriticalAntiDepBreaker(MachineFunction &MFi,
427330f729Sjoerg const RegisterClassInfo &RCI)
437330f729Sjoerg : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()),
447330f729Sjoerg TII(MF.getSubtarget().getInstrInfo()),
457330f729Sjoerg TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI),
467330f729Sjoerg Classes(TRI->getNumRegs(), nullptr), KillIndices(TRI->getNumRegs(), 0),
477330f729Sjoerg DefIndices(TRI->getNumRegs(), 0), KeepRegs(TRI->getNumRegs(), false) {}
487330f729Sjoerg
497330f729Sjoerg CriticalAntiDepBreaker::~CriticalAntiDepBreaker() = default;
507330f729Sjoerg
StartBlock(MachineBasicBlock * BB)517330f729Sjoerg void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
527330f729Sjoerg const unsigned BBSize = BB->size();
537330f729Sjoerg for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) {
547330f729Sjoerg // Clear out the register class data.
557330f729Sjoerg Classes[i] = nullptr;
567330f729Sjoerg
577330f729Sjoerg // Initialize the indices to indicate that no registers are live.
587330f729Sjoerg KillIndices[i] = ~0u;
597330f729Sjoerg DefIndices[i] = BBSize;
607330f729Sjoerg }
617330f729Sjoerg
627330f729Sjoerg // Clear "do not change" set.
637330f729Sjoerg KeepRegs.reset();
647330f729Sjoerg
657330f729Sjoerg bool IsReturnBlock = BB->isReturnBlock();
667330f729Sjoerg
677330f729Sjoerg // Examine the live-in regs of all successors.
68*82d56013Sjoerg for (const MachineBasicBlock *Succ : BB->successors())
69*82d56013Sjoerg for (const auto &LI : Succ->liveins()) {
707330f729Sjoerg for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI) {
717330f729Sjoerg unsigned Reg = *AI;
727330f729Sjoerg Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
737330f729Sjoerg KillIndices[Reg] = BBSize;
747330f729Sjoerg DefIndices[Reg] = ~0u;
757330f729Sjoerg }
767330f729Sjoerg }
777330f729Sjoerg
787330f729Sjoerg // Mark live-out callee-saved registers. In a return block this is
797330f729Sjoerg // all callee-saved registers. In non-return this is any
807330f729Sjoerg // callee-saved register that is not saved in the prolog.
817330f729Sjoerg const MachineFrameInfo &MFI = MF.getFrameInfo();
827330f729Sjoerg BitVector Pristine = MFI.getPristineRegs(MF);
837330f729Sjoerg for (const MCPhysReg *I = MF.getRegInfo().getCalleeSavedRegs(); *I;
847330f729Sjoerg ++I) {
857330f729Sjoerg unsigned Reg = *I;
867330f729Sjoerg if (!IsReturnBlock && !Pristine.test(Reg))
877330f729Sjoerg continue;
887330f729Sjoerg for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
897330f729Sjoerg unsigned Reg = *AI;
907330f729Sjoerg Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
917330f729Sjoerg KillIndices[Reg] = BBSize;
927330f729Sjoerg DefIndices[Reg] = ~0u;
937330f729Sjoerg }
947330f729Sjoerg }
957330f729Sjoerg }
967330f729Sjoerg
FinishBlock()977330f729Sjoerg void CriticalAntiDepBreaker::FinishBlock() {
987330f729Sjoerg RegRefs.clear();
997330f729Sjoerg KeepRegs.reset();
1007330f729Sjoerg }
1017330f729Sjoerg
Observe(MachineInstr & MI,unsigned Count,unsigned InsertPosIndex)1027330f729Sjoerg void CriticalAntiDepBreaker::Observe(MachineInstr &MI, unsigned Count,
1037330f729Sjoerg unsigned InsertPosIndex) {
1047330f729Sjoerg // Kill instructions can define registers but are really nops, and there might
1057330f729Sjoerg // be a real definition earlier that needs to be paired with uses dominated by
1067330f729Sjoerg // this kill.
1077330f729Sjoerg
1087330f729Sjoerg // FIXME: It may be possible to remove the isKill() restriction once PR18663
1097330f729Sjoerg // has been properly fixed. There can be value in processing kills as seen in
1107330f729Sjoerg // the AggressiveAntiDepBreaker class.
1117330f729Sjoerg if (MI.isDebugInstr() || MI.isKill())
1127330f729Sjoerg return;
1137330f729Sjoerg assert(Count < InsertPosIndex && "Instruction index out of expected range!");
1147330f729Sjoerg
1157330f729Sjoerg for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
1167330f729Sjoerg if (KillIndices[Reg] != ~0u) {
1177330f729Sjoerg // If Reg is currently live, then mark that it can't be renamed as
1187330f729Sjoerg // we don't know the extent of its live-range anymore (now that it
1197330f729Sjoerg // has been scheduled).
1207330f729Sjoerg Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
1217330f729Sjoerg KillIndices[Reg] = Count;
1227330f729Sjoerg } else if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
1237330f729Sjoerg // Any register which was defined within the previous scheduling region
1247330f729Sjoerg // may have been rescheduled and its lifetime may overlap with registers
1257330f729Sjoerg // in ways not reflected in our current liveness state. For each such
1267330f729Sjoerg // register, adjust the liveness state to be conservatively correct.
1277330f729Sjoerg Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
1287330f729Sjoerg
1297330f729Sjoerg // Move the def index to the end of the previous region, to reflect
1307330f729Sjoerg // that the def could theoretically have been scheduled at the end.
1317330f729Sjoerg DefIndices[Reg] = InsertPosIndex;
1327330f729Sjoerg }
1337330f729Sjoerg }
1347330f729Sjoerg
1357330f729Sjoerg PrescanInstruction(MI);
1367330f729Sjoerg ScanInstruction(MI, Count);
1377330f729Sjoerg }
1387330f729Sjoerg
1397330f729Sjoerg /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
1407330f729Sjoerg /// critical path.
CriticalPathStep(const SUnit * SU)1417330f729Sjoerg static const SDep *CriticalPathStep(const SUnit *SU) {
1427330f729Sjoerg const SDep *Next = nullptr;
1437330f729Sjoerg unsigned NextDepth = 0;
1447330f729Sjoerg // Find the predecessor edge with the greatest depth.
145*82d56013Sjoerg for (const SDep &P : SU->Preds) {
146*82d56013Sjoerg const SUnit *PredSU = P.getSUnit();
147*82d56013Sjoerg unsigned PredLatency = P.getLatency();
1487330f729Sjoerg unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
1497330f729Sjoerg // In the case of a latency tie, prefer an anti-dependency edge over
1507330f729Sjoerg // other types of edges.
1517330f729Sjoerg if (NextDepth < PredTotalLatency ||
152*82d56013Sjoerg (NextDepth == PredTotalLatency && P.getKind() == SDep::Anti)) {
1537330f729Sjoerg NextDepth = PredTotalLatency;
154*82d56013Sjoerg Next = &P;
1557330f729Sjoerg }
1567330f729Sjoerg }
1577330f729Sjoerg return Next;
1587330f729Sjoerg }
1597330f729Sjoerg
PrescanInstruction(MachineInstr & MI)1607330f729Sjoerg void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr &MI) {
1617330f729Sjoerg // It's not safe to change register allocation for source operands of
1627330f729Sjoerg // instructions that have special allocation requirements. Also assume all
1637330f729Sjoerg // registers used in a call must not be changed (ABI).
1647330f729Sjoerg // FIXME: The issue with predicated instruction is more complex. We are being
1657330f729Sjoerg // conservative here because the kill markers cannot be trusted after
1667330f729Sjoerg // if-conversion:
1677330f729Sjoerg // %r6 = LDR %sp, %reg0, 92, 14, %reg0; mem:LD4[FixedStack14]
1687330f729Sjoerg // ...
1697330f729Sjoerg // STR %r0, killed %r6, %reg0, 0, 0, %cpsr; mem:ST4[%395]
1707330f729Sjoerg // %r6 = LDR %sp, %reg0, 100, 0, %cpsr; mem:LD4[FixedStack12]
1717330f729Sjoerg // STR %r0, killed %r6, %reg0, 0, 14, %reg0; mem:ST4[%396](align=8)
1727330f729Sjoerg //
1737330f729Sjoerg // The first R6 kill is not really a kill since it's killed by a predicated
1747330f729Sjoerg // instruction which may not be executed. The second R6 def may or may not
1757330f729Sjoerg // re-define R6 so it's not safe to change it since the last R6 use cannot be
1767330f729Sjoerg // changed.
1777330f729Sjoerg bool Special =
1787330f729Sjoerg MI.isCall() || MI.hasExtraSrcRegAllocReq() || TII->isPredicated(MI);
1797330f729Sjoerg
1807330f729Sjoerg // Scan the register operands for this instruction and update
1817330f729Sjoerg // Classes and RegRefs.
1827330f729Sjoerg for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1837330f729Sjoerg MachineOperand &MO = MI.getOperand(i);
1847330f729Sjoerg if (!MO.isReg()) continue;
1857330f729Sjoerg Register Reg = MO.getReg();
1867330f729Sjoerg if (Reg == 0) continue;
1877330f729Sjoerg const TargetRegisterClass *NewRC = nullptr;
1887330f729Sjoerg
1897330f729Sjoerg if (i < MI.getDesc().getNumOperands())
1907330f729Sjoerg NewRC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
1917330f729Sjoerg
1927330f729Sjoerg // For now, only allow the register to be changed if its register
1937330f729Sjoerg // class is consistent across all uses.
1947330f729Sjoerg if (!Classes[Reg] && NewRC)
1957330f729Sjoerg Classes[Reg] = NewRC;
1967330f729Sjoerg else if (!NewRC || Classes[Reg] != NewRC)
1977330f729Sjoerg Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
1987330f729Sjoerg
1997330f729Sjoerg // Now check for aliases.
2007330f729Sjoerg for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
2017330f729Sjoerg // If an alias of the reg is used during the live range, give up.
2027330f729Sjoerg // Note that this allows us to skip checking if AntiDepReg
2037330f729Sjoerg // overlaps with any of the aliases, among other things.
2047330f729Sjoerg unsigned AliasReg = *AI;
2057330f729Sjoerg if (Classes[AliasReg]) {
2067330f729Sjoerg Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
2077330f729Sjoerg Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
2087330f729Sjoerg }
2097330f729Sjoerg }
2107330f729Sjoerg
2117330f729Sjoerg // If we're still willing to consider this register, note the reference.
2127330f729Sjoerg if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
2137330f729Sjoerg RegRefs.insert(std::make_pair(Reg, &MO));
2147330f729Sjoerg
2157330f729Sjoerg // If this reg is tied and live (Classes[Reg] is set to -1), we can't change
2167330f729Sjoerg // it or any of its sub or super regs. We need to use KeepRegs to mark the
2177330f729Sjoerg // reg because not all uses of the same reg within an instruction are
2187330f729Sjoerg // necessarily tagged as tied.
2197330f729Sjoerg // Example: an x86 "xor %eax, %eax" will have one source operand tied to the
2207330f729Sjoerg // def register but not the second (see PR20020 for details).
2217330f729Sjoerg // FIXME: can this check be relaxed to account for undef uses
2227330f729Sjoerg // of a register? In the above 'xor' example, the uses of %eax are undef, so
2237330f729Sjoerg // earlier instructions could still replace %eax even though the 'xor'
2247330f729Sjoerg // itself can't be changed.
2257330f729Sjoerg if (MI.isRegTiedToUseOperand(i) &&
2267330f729Sjoerg Classes[Reg] == reinterpret_cast<TargetRegisterClass *>(-1)) {
2277330f729Sjoerg for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
2287330f729Sjoerg SubRegs.isValid(); ++SubRegs) {
2297330f729Sjoerg KeepRegs.set(*SubRegs);
2307330f729Sjoerg }
2317330f729Sjoerg for (MCSuperRegIterator SuperRegs(Reg, TRI);
2327330f729Sjoerg SuperRegs.isValid(); ++SuperRegs) {
2337330f729Sjoerg KeepRegs.set(*SuperRegs);
2347330f729Sjoerg }
2357330f729Sjoerg }
2367330f729Sjoerg
2377330f729Sjoerg if (MO.isUse() && Special) {
2387330f729Sjoerg if (!KeepRegs.test(Reg)) {
2397330f729Sjoerg for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
2407330f729Sjoerg SubRegs.isValid(); ++SubRegs)
2417330f729Sjoerg KeepRegs.set(*SubRegs);
2427330f729Sjoerg }
2437330f729Sjoerg }
2447330f729Sjoerg }
2457330f729Sjoerg }
2467330f729Sjoerg
ScanInstruction(MachineInstr & MI,unsigned Count)2477330f729Sjoerg void CriticalAntiDepBreaker::ScanInstruction(MachineInstr &MI, unsigned Count) {
2487330f729Sjoerg // Update liveness.
2497330f729Sjoerg // Proceeding upwards, registers that are defed but not used in this
2507330f729Sjoerg // instruction are now dead.
2517330f729Sjoerg assert(!MI.isKill() && "Attempting to scan a kill instruction");
2527330f729Sjoerg
2537330f729Sjoerg if (!TII->isPredicated(MI)) {
2547330f729Sjoerg // Predicated defs are modeled as read + write, i.e. similar to two
2557330f729Sjoerg // address updates.
2567330f729Sjoerg for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2577330f729Sjoerg MachineOperand &MO = MI.getOperand(i);
2587330f729Sjoerg
259*82d56013Sjoerg if (MO.isRegMask()) {
260*82d56013Sjoerg auto ClobbersPhysRegAndSubRegs = [&](unsigned PhysReg) {
261*82d56013Sjoerg for (MCSubRegIterator SRI(PhysReg, TRI, true); SRI.isValid(); ++SRI)
262*82d56013Sjoerg if (!MO.clobbersPhysReg(*SRI))
263*82d56013Sjoerg return false;
264*82d56013Sjoerg
265*82d56013Sjoerg return true;
266*82d56013Sjoerg };
267*82d56013Sjoerg
268*82d56013Sjoerg for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) {
269*82d56013Sjoerg if (ClobbersPhysRegAndSubRegs(i)) {
2707330f729Sjoerg DefIndices[i] = Count;
2717330f729Sjoerg KillIndices[i] = ~0u;
2727330f729Sjoerg KeepRegs.reset(i);
2737330f729Sjoerg Classes[i] = nullptr;
2747330f729Sjoerg RegRefs.erase(i);
2757330f729Sjoerg }
276*82d56013Sjoerg }
277*82d56013Sjoerg }
2787330f729Sjoerg
2797330f729Sjoerg if (!MO.isReg()) continue;
2807330f729Sjoerg Register Reg = MO.getReg();
2817330f729Sjoerg if (Reg == 0) continue;
2827330f729Sjoerg if (!MO.isDef()) continue;
2837330f729Sjoerg
2847330f729Sjoerg // Ignore two-addr defs.
2857330f729Sjoerg if (MI.isRegTiedToUseOperand(i))
2867330f729Sjoerg continue;
2877330f729Sjoerg
2887330f729Sjoerg // If we've already marked this reg as unchangeable, don't remove
2897330f729Sjoerg // it or any of its subregs from KeepRegs.
2907330f729Sjoerg bool Keep = KeepRegs.test(Reg);
2917330f729Sjoerg
2927330f729Sjoerg // For the reg itself and all subregs: update the def to current;
2937330f729Sjoerg // reset the kill state, any restrictions, and references.
2947330f729Sjoerg for (MCSubRegIterator SRI(Reg, TRI, true); SRI.isValid(); ++SRI) {
2957330f729Sjoerg unsigned SubregReg = *SRI;
2967330f729Sjoerg DefIndices[SubregReg] = Count;
2977330f729Sjoerg KillIndices[SubregReg] = ~0u;
2987330f729Sjoerg Classes[SubregReg] = nullptr;
2997330f729Sjoerg RegRefs.erase(SubregReg);
3007330f729Sjoerg if (!Keep)
3017330f729Sjoerg KeepRegs.reset(SubregReg);
3027330f729Sjoerg }
3037330f729Sjoerg // Conservatively mark super-registers as unusable.
3047330f729Sjoerg for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
3057330f729Sjoerg Classes[*SR] = reinterpret_cast<TargetRegisterClass *>(-1);
3067330f729Sjoerg }
3077330f729Sjoerg }
3087330f729Sjoerg for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
3097330f729Sjoerg MachineOperand &MO = MI.getOperand(i);
3107330f729Sjoerg if (!MO.isReg()) continue;
3117330f729Sjoerg Register Reg = MO.getReg();
3127330f729Sjoerg if (Reg == 0) continue;
3137330f729Sjoerg if (!MO.isUse()) continue;
3147330f729Sjoerg
3157330f729Sjoerg const TargetRegisterClass *NewRC = nullptr;
3167330f729Sjoerg if (i < MI.getDesc().getNumOperands())
3177330f729Sjoerg NewRC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
3187330f729Sjoerg
3197330f729Sjoerg // For now, only allow the register to be changed if its register
3207330f729Sjoerg // class is consistent across all uses.
3217330f729Sjoerg if (!Classes[Reg] && NewRC)
3227330f729Sjoerg Classes[Reg] = NewRC;
3237330f729Sjoerg else if (!NewRC || Classes[Reg] != NewRC)
3247330f729Sjoerg Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
3257330f729Sjoerg
3267330f729Sjoerg RegRefs.insert(std::make_pair(Reg, &MO));
3277330f729Sjoerg
3287330f729Sjoerg // It wasn't previously live but now it is, this is a kill.
3297330f729Sjoerg // Repeat for all aliases.
3307330f729Sjoerg for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
3317330f729Sjoerg unsigned AliasReg = *AI;
3327330f729Sjoerg if (KillIndices[AliasReg] == ~0u) {
3337330f729Sjoerg KillIndices[AliasReg] = Count;
3347330f729Sjoerg DefIndices[AliasReg] = ~0u;
3357330f729Sjoerg }
3367330f729Sjoerg }
3377330f729Sjoerg }
3387330f729Sjoerg }
3397330f729Sjoerg
3407330f729Sjoerg // Check all machine operands that reference the antidependent register and must
3417330f729Sjoerg // be replaced by NewReg. Return true if any of their parent instructions may
3427330f729Sjoerg // clobber the new register.
3437330f729Sjoerg //
3447330f729Sjoerg // Note: AntiDepReg may be referenced by a two-address instruction such that
3457330f729Sjoerg // it's use operand is tied to a def operand. We guard against the case in which
3467330f729Sjoerg // the two-address instruction also defines NewReg, as may happen with
3477330f729Sjoerg // pre/postincrement loads. In this case, both the use and def operands are in
3487330f729Sjoerg // RegRefs because the def is inserted by PrescanInstruction and not erased
3497330f729Sjoerg // during ScanInstruction. So checking for an instruction with definitions of
3507330f729Sjoerg // both NewReg and AntiDepReg covers it.
3517330f729Sjoerg bool
isNewRegClobberedByRefs(RegRefIter RegRefBegin,RegRefIter RegRefEnd,unsigned NewReg)3527330f729Sjoerg CriticalAntiDepBreaker::isNewRegClobberedByRefs(RegRefIter RegRefBegin,
3537330f729Sjoerg RegRefIter RegRefEnd,
3547330f729Sjoerg unsigned NewReg) {
3557330f729Sjoerg for (RegRefIter I = RegRefBegin; I != RegRefEnd; ++I ) {
3567330f729Sjoerg MachineOperand *RefOper = I->second;
3577330f729Sjoerg
3587330f729Sjoerg // Don't allow the instruction defining AntiDepReg to earlyclobber its
3597330f729Sjoerg // operands, in case they may be assigned to NewReg. In this case antidep
3607330f729Sjoerg // breaking must fail, but it's too rare to bother optimizing.
3617330f729Sjoerg if (RefOper->isDef() && RefOper->isEarlyClobber())
3627330f729Sjoerg return true;
3637330f729Sjoerg
3647330f729Sjoerg // Handle cases in which this instruction defines NewReg.
3657330f729Sjoerg MachineInstr *MI = RefOper->getParent();
3667330f729Sjoerg for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
3677330f729Sjoerg const MachineOperand &CheckOper = MI->getOperand(i);
3687330f729Sjoerg
3697330f729Sjoerg if (CheckOper.isRegMask() && CheckOper.clobbersPhysReg(NewReg))
3707330f729Sjoerg return true;
3717330f729Sjoerg
3727330f729Sjoerg if (!CheckOper.isReg() || !CheckOper.isDef() ||
3737330f729Sjoerg CheckOper.getReg() != NewReg)
3747330f729Sjoerg continue;
3757330f729Sjoerg
3767330f729Sjoerg // Don't allow the instruction to define NewReg and AntiDepReg.
3777330f729Sjoerg // When AntiDepReg is renamed it will be an illegal op.
3787330f729Sjoerg if (RefOper->isDef())
3797330f729Sjoerg return true;
3807330f729Sjoerg
3817330f729Sjoerg // Don't allow an instruction using AntiDepReg to be earlyclobbered by
3827330f729Sjoerg // NewReg.
3837330f729Sjoerg if (CheckOper.isEarlyClobber())
3847330f729Sjoerg return true;
3857330f729Sjoerg
3867330f729Sjoerg // Don't allow inline asm to define NewReg at all. Who knows what it's
3877330f729Sjoerg // doing with it.
3887330f729Sjoerg if (MI->isInlineAsm())
3897330f729Sjoerg return true;
3907330f729Sjoerg }
3917330f729Sjoerg }
3927330f729Sjoerg return false;
3937330f729Sjoerg }
3947330f729Sjoerg
3957330f729Sjoerg unsigned CriticalAntiDepBreaker::
findSuitableFreeRegister(RegRefIter RegRefBegin,RegRefIter RegRefEnd,unsigned AntiDepReg,unsigned LastNewReg,const TargetRegisterClass * RC,SmallVectorImpl<unsigned> & Forbid)3967330f729Sjoerg findSuitableFreeRegister(RegRefIter RegRefBegin,
3977330f729Sjoerg RegRefIter RegRefEnd,
3987330f729Sjoerg unsigned AntiDepReg,
3997330f729Sjoerg unsigned LastNewReg,
4007330f729Sjoerg const TargetRegisterClass *RC,
4017330f729Sjoerg SmallVectorImpl<unsigned> &Forbid) {
4027330f729Sjoerg ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(RC);
4037330f729Sjoerg for (unsigned i = 0; i != Order.size(); ++i) {
4047330f729Sjoerg unsigned NewReg = Order[i];
4057330f729Sjoerg // Don't replace a register with itself.
4067330f729Sjoerg if (NewReg == AntiDepReg) continue;
4077330f729Sjoerg // Don't replace a register with one that was recently used to repair
4087330f729Sjoerg // an anti-dependence with this AntiDepReg, because that would
4097330f729Sjoerg // re-introduce that anti-dependence.
4107330f729Sjoerg if (NewReg == LastNewReg) continue;
4117330f729Sjoerg // If any instructions that define AntiDepReg also define the NewReg, it's
4127330f729Sjoerg // not suitable. For example, Instruction with multiple definitions can
4137330f729Sjoerg // result in this condition.
4147330f729Sjoerg if (isNewRegClobberedByRefs(RegRefBegin, RegRefEnd, NewReg)) continue;
4157330f729Sjoerg // If NewReg is dead and NewReg's most recent def is not before
4167330f729Sjoerg // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
4177330f729Sjoerg assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u))
4187330f729Sjoerg && "Kill and Def maps aren't consistent for AntiDepReg!");
4197330f729Sjoerg assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u))
4207330f729Sjoerg && "Kill and Def maps aren't consistent for NewReg!");
4217330f729Sjoerg if (KillIndices[NewReg] != ~0u ||
4227330f729Sjoerg Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
4237330f729Sjoerg KillIndices[AntiDepReg] > DefIndices[NewReg])
4247330f729Sjoerg continue;
4257330f729Sjoerg // If NewReg overlaps any of the forbidden registers, we can't use it.
4267330f729Sjoerg bool Forbidden = false;
427*82d56013Sjoerg for (unsigned R : Forbid)
428*82d56013Sjoerg if (TRI->regsOverlap(NewReg, R)) {
4297330f729Sjoerg Forbidden = true;
4307330f729Sjoerg break;
4317330f729Sjoerg }
4327330f729Sjoerg if (Forbidden) continue;
4337330f729Sjoerg return NewReg;
4347330f729Sjoerg }
4357330f729Sjoerg
4367330f729Sjoerg // No registers are free and available!
4377330f729Sjoerg return 0;
4387330f729Sjoerg }
4397330f729Sjoerg
4407330f729Sjoerg unsigned CriticalAntiDepBreaker::
BreakAntiDependencies(const std::vector<SUnit> & SUnits,MachineBasicBlock::iterator Begin,MachineBasicBlock::iterator End,unsigned InsertPosIndex,DbgValueVector & DbgValues)4417330f729Sjoerg BreakAntiDependencies(const std::vector<SUnit> &SUnits,
4427330f729Sjoerg MachineBasicBlock::iterator Begin,
4437330f729Sjoerg MachineBasicBlock::iterator End,
4447330f729Sjoerg unsigned InsertPosIndex,
4457330f729Sjoerg DbgValueVector &DbgValues) {
4467330f729Sjoerg // The code below assumes that there is at least one instruction,
4477330f729Sjoerg // so just duck out immediately if the block is empty.
4487330f729Sjoerg if (SUnits.empty()) return 0;
4497330f729Sjoerg
4507330f729Sjoerg // Keep a map of the MachineInstr*'s back to the SUnit representing them.
4517330f729Sjoerg // This is used for updating debug information.
4527330f729Sjoerg //
4537330f729Sjoerg // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap
4547330f729Sjoerg DenseMap<MachineInstr *, const SUnit *> MISUnitMap;
4557330f729Sjoerg
4567330f729Sjoerg // Find the node at the bottom of the critical path.
4577330f729Sjoerg const SUnit *Max = nullptr;
4587330f729Sjoerg for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
4597330f729Sjoerg const SUnit *SU = &SUnits[i];
4607330f729Sjoerg MISUnitMap[SU->getInstr()] = SU;
4617330f729Sjoerg if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
4627330f729Sjoerg Max = SU;
4637330f729Sjoerg }
4647330f729Sjoerg assert(Max && "Failed to find bottom of the critical path");
4657330f729Sjoerg
4667330f729Sjoerg #ifndef NDEBUG
4677330f729Sjoerg {
4687330f729Sjoerg LLVM_DEBUG(dbgs() << "Critical path has total latency "
4697330f729Sjoerg << (Max->getDepth() + Max->Latency) << "\n");
4707330f729Sjoerg LLVM_DEBUG(dbgs() << "Available regs:");
4717330f729Sjoerg for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
4727330f729Sjoerg if (KillIndices[Reg] == ~0u)
4737330f729Sjoerg LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI));
4747330f729Sjoerg }
4757330f729Sjoerg LLVM_DEBUG(dbgs() << '\n');
4767330f729Sjoerg }
4777330f729Sjoerg #endif
4787330f729Sjoerg
4797330f729Sjoerg // Track progress along the critical path through the SUnit graph as we walk
4807330f729Sjoerg // the instructions.
4817330f729Sjoerg const SUnit *CriticalPathSU = Max;
4827330f729Sjoerg MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
4837330f729Sjoerg
4847330f729Sjoerg // Consider this pattern:
4857330f729Sjoerg // A = ...
4867330f729Sjoerg // ... = A
4877330f729Sjoerg // A = ...
4887330f729Sjoerg // ... = A
4897330f729Sjoerg // A = ...
4907330f729Sjoerg // ... = A
4917330f729Sjoerg // A = ...
4927330f729Sjoerg // ... = A
4937330f729Sjoerg // There are three anti-dependencies here, and without special care,
4947330f729Sjoerg // we'd break all of them using the same register:
4957330f729Sjoerg // A = ...
4967330f729Sjoerg // ... = A
4977330f729Sjoerg // B = ...
4987330f729Sjoerg // ... = B
4997330f729Sjoerg // B = ...
5007330f729Sjoerg // ... = B
5017330f729Sjoerg // B = ...
5027330f729Sjoerg // ... = B
5037330f729Sjoerg // because at each anti-dependence, B is the first register that
5047330f729Sjoerg // isn't A which is free. This re-introduces anti-dependencies
5057330f729Sjoerg // at all but one of the original anti-dependencies that we were
5067330f729Sjoerg // trying to break. To avoid this, keep track of the most recent
5077330f729Sjoerg // register that each register was replaced with, avoid
5087330f729Sjoerg // using it to repair an anti-dependence on the same register.
5097330f729Sjoerg // This lets us produce this:
5107330f729Sjoerg // A = ...
5117330f729Sjoerg // ... = A
5127330f729Sjoerg // B = ...
5137330f729Sjoerg // ... = B
5147330f729Sjoerg // C = ...
5157330f729Sjoerg // ... = C
5167330f729Sjoerg // B = ...
5177330f729Sjoerg // ... = B
5187330f729Sjoerg // This still has an anti-dependence on B, but at least it isn't on the
5197330f729Sjoerg // original critical path.
5207330f729Sjoerg //
5217330f729Sjoerg // TODO: If we tracked more than one register here, we could potentially
5227330f729Sjoerg // fix that remaining critical edge too. This is a little more involved,
5237330f729Sjoerg // because unlike the most recent register, less recent registers should
5247330f729Sjoerg // still be considered, though only if no other registers are available.
5257330f729Sjoerg std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0);
5267330f729Sjoerg
5277330f729Sjoerg // Attempt to break anti-dependence edges on the critical path. Walk the
5287330f729Sjoerg // instructions from the bottom up, tracking information about liveness
5297330f729Sjoerg // as we go to help determine which registers are available.
5307330f729Sjoerg unsigned Broken = 0;
5317330f729Sjoerg unsigned Count = InsertPosIndex - 1;
5327330f729Sjoerg for (MachineBasicBlock::iterator I = End, E = Begin; I != E; --Count) {
5337330f729Sjoerg MachineInstr &MI = *--I;
5347330f729Sjoerg // Kill instructions can define registers but are really nops, and there
5357330f729Sjoerg // might be a real definition earlier that needs to be paired with uses
5367330f729Sjoerg // dominated by this kill.
5377330f729Sjoerg
5387330f729Sjoerg // FIXME: It may be possible to remove the isKill() restriction once PR18663
5397330f729Sjoerg // has been properly fixed. There can be value in processing kills as seen
5407330f729Sjoerg // in the AggressiveAntiDepBreaker class.
5417330f729Sjoerg if (MI.isDebugInstr() || MI.isKill())
5427330f729Sjoerg continue;
5437330f729Sjoerg
5447330f729Sjoerg // Check if this instruction has a dependence on the critical path that
5457330f729Sjoerg // is an anti-dependence that we may be able to break. If it is, set
5467330f729Sjoerg // AntiDepReg to the non-zero register associated with the anti-dependence.
5477330f729Sjoerg //
5487330f729Sjoerg // We limit our attention to the critical path as a heuristic to avoid
5497330f729Sjoerg // breaking anti-dependence edges that aren't going to significantly
5507330f729Sjoerg // impact the overall schedule. There are a limited number of registers
5517330f729Sjoerg // and we want to save them for the important edges.
5527330f729Sjoerg //
5537330f729Sjoerg // TODO: Instructions with multiple defs could have multiple
5547330f729Sjoerg // anti-dependencies. The current code here only knows how to break one
5557330f729Sjoerg // edge per instruction. Note that we'd have to be able to break all of
5567330f729Sjoerg // the anti-dependencies in an instruction in order to be effective.
5577330f729Sjoerg unsigned AntiDepReg = 0;
5587330f729Sjoerg if (&MI == CriticalPathMI) {
5597330f729Sjoerg if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) {
5607330f729Sjoerg const SUnit *NextSU = Edge->getSUnit();
5617330f729Sjoerg
5627330f729Sjoerg // Only consider anti-dependence edges.
5637330f729Sjoerg if (Edge->getKind() == SDep::Anti) {
5647330f729Sjoerg AntiDepReg = Edge->getReg();
5657330f729Sjoerg assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
5667330f729Sjoerg if (!MRI.isAllocatable(AntiDepReg))
5677330f729Sjoerg // Don't break anti-dependencies on non-allocatable registers.
5687330f729Sjoerg AntiDepReg = 0;
5697330f729Sjoerg else if (KeepRegs.test(AntiDepReg))
5707330f729Sjoerg // Don't break anti-dependencies if a use down below requires
5717330f729Sjoerg // this exact register.
5727330f729Sjoerg AntiDepReg = 0;
5737330f729Sjoerg else {
5747330f729Sjoerg // If the SUnit has other dependencies on the SUnit that it
5757330f729Sjoerg // anti-depends on, don't bother breaking the anti-dependency
5767330f729Sjoerg // since those edges would prevent such units from being
5777330f729Sjoerg // scheduled past each other regardless.
5787330f729Sjoerg //
5797330f729Sjoerg // Also, if there are dependencies on other SUnits with the
5807330f729Sjoerg // same register as the anti-dependency, don't attempt to
5817330f729Sjoerg // break it.
582*82d56013Sjoerg for (const SDep &P : CriticalPathSU->Preds)
583*82d56013Sjoerg if (P.getSUnit() == NextSU
584*82d56013Sjoerg ? (P.getKind() != SDep::Anti || P.getReg() != AntiDepReg)
585*82d56013Sjoerg : (P.getKind() == SDep::Data &&
586*82d56013Sjoerg P.getReg() == AntiDepReg)) {
5877330f729Sjoerg AntiDepReg = 0;
5887330f729Sjoerg break;
5897330f729Sjoerg }
5907330f729Sjoerg }
5917330f729Sjoerg }
5927330f729Sjoerg CriticalPathSU = NextSU;
5937330f729Sjoerg CriticalPathMI = CriticalPathSU->getInstr();
5947330f729Sjoerg } else {
5957330f729Sjoerg // We've reached the end of the critical path.
5967330f729Sjoerg CriticalPathSU = nullptr;
5977330f729Sjoerg CriticalPathMI = nullptr;
5987330f729Sjoerg }
5997330f729Sjoerg }
6007330f729Sjoerg
6017330f729Sjoerg PrescanInstruction(MI);
6027330f729Sjoerg
6037330f729Sjoerg SmallVector<unsigned, 2> ForbidRegs;
6047330f729Sjoerg
6057330f729Sjoerg // If MI's defs have a special allocation requirement, don't allow
6067330f729Sjoerg // any def registers to be changed. Also assume all registers
6077330f729Sjoerg // defined in a call must not be changed (ABI).
6087330f729Sjoerg if (MI.isCall() || MI.hasExtraDefRegAllocReq() || TII->isPredicated(MI))
6097330f729Sjoerg // If this instruction's defs have special allocation requirement, don't
6107330f729Sjoerg // break this anti-dependency.
6117330f729Sjoerg AntiDepReg = 0;
6127330f729Sjoerg else if (AntiDepReg) {
6137330f729Sjoerg // If this instruction has a use of AntiDepReg, breaking it
6147330f729Sjoerg // is invalid. If the instruction defines other registers,
6157330f729Sjoerg // save a list of them so that we don't pick a new register
6167330f729Sjoerg // that overlaps any of them.
6177330f729Sjoerg for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
6187330f729Sjoerg MachineOperand &MO = MI.getOperand(i);
6197330f729Sjoerg if (!MO.isReg()) continue;
6207330f729Sjoerg Register Reg = MO.getReg();
6217330f729Sjoerg if (Reg == 0) continue;
6227330f729Sjoerg if (MO.isUse() && TRI->regsOverlap(AntiDepReg, Reg)) {
6237330f729Sjoerg AntiDepReg = 0;
6247330f729Sjoerg break;
6257330f729Sjoerg }
6267330f729Sjoerg if (MO.isDef() && Reg != AntiDepReg)
6277330f729Sjoerg ForbidRegs.push_back(Reg);
6287330f729Sjoerg }
6297330f729Sjoerg }
6307330f729Sjoerg
6317330f729Sjoerg // Determine AntiDepReg's register class, if it is live and is
6327330f729Sjoerg // consistently used within a single class.
6337330f729Sjoerg const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg]
6347330f729Sjoerg : nullptr;
6357330f729Sjoerg assert((AntiDepReg == 0 || RC != nullptr) &&
6367330f729Sjoerg "Register should be live if it's causing an anti-dependence!");
6377330f729Sjoerg if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
6387330f729Sjoerg AntiDepReg = 0;
6397330f729Sjoerg
6407330f729Sjoerg // Look for a suitable register to use to break the anti-dependence.
6417330f729Sjoerg //
6427330f729Sjoerg // TODO: Instead of picking the first free register, consider which might
6437330f729Sjoerg // be the best.
6447330f729Sjoerg if (AntiDepReg != 0) {
6457330f729Sjoerg std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
6467330f729Sjoerg std::multimap<unsigned, MachineOperand *>::iterator>
6477330f729Sjoerg Range = RegRefs.equal_range(AntiDepReg);
6487330f729Sjoerg if (unsigned NewReg = findSuitableFreeRegister(Range.first, Range.second,
6497330f729Sjoerg AntiDepReg,
6507330f729Sjoerg LastNewReg[AntiDepReg],
6517330f729Sjoerg RC, ForbidRegs)) {
6527330f729Sjoerg LLVM_DEBUG(dbgs() << "Breaking anti-dependence edge on "
6537330f729Sjoerg << printReg(AntiDepReg, TRI) << " with "
6547330f729Sjoerg << RegRefs.count(AntiDepReg) << " references"
6557330f729Sjoerg << " using " << printReg(NewReg, TRI) << "!\n");
6567330f729Sjoerg
6577330f729Sjoerg // Update the references to the old register to refer to the new
6587330f729Sjoerg // register.
6597330f729Sjoerg for (std::multimap<unsigned, MachineOperand *>::iterator
6607330f729Sjoerg Q = Range.first, QE = Range.second; Q != QE; ++Q) {
6617330f729Sjoerg Q->second->setReg(NewReg);
6627330f729Sjoerg // If the SU for the instruction being updated has debug information
6637330f729Sjoerg // related to the anti-dependency register, make sure to update that
6647330f729Sjoerg // as well.
6657330f729Sjoerg const SUnit *SU = MISUnitMap[Q->second->getParent()];
6667330f729Sjoerg if (!SU) continue;
6677330f729Sjoerg UpdateDbgValues(DbgValues, Q->second->getParent(),
6687330f729Sjoerg AntiDepReg, NewReg);
6697330f729Sjoerg }
6707330f729Sjoerg
6717330f729Sjoerg // We just went back in time and modified history; the
6727330f729Sjoerg // liveness information for the anti-dependence reg is now
6737330f729Sjoerg // inconsistent. Set the state as if it were dead.
6747330f729Sjoerg Classes[NewReg] = Classes[AntiDepReg];
6757330f729Sjoerg DefIndices[NewReg] = DefIndices[AntiDepReg];
6767330f729Sjoerg KillIndices[NewReg] = KillIndices[AntiDepReg];
6777330f729Sjoerg assert(((KillIndices[NewReg] == ~0u) !=
6787330f729Sjoerg (DefIndices[NewReg] == ~0u)) &&
6797330f729Sjoerg "Kill and Def maps aren't consistent for NewReg!");
6807330f729Sjoerg
6817330f729Sjoerg Classes[AntiDepReg] = nullptr;
6827330f729Sjoerg DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
6837330f729Sjoerg KillIndices[AntiDepReg] = ~0u;
6847330f729Sjoerg assert(((KillIndices[AntiDepReg] == ~0u) !=
6857330f729Sjoerg (DefIndices[AntiDepReg] == ~0u)) &&
6867330f729Sjoerg "Kill and Def maps aren't consistent for AntiDepReg!");
6877330f729Sjoerg
6887330f729Sjoerg RegRefs.erase(AntiDepReg);
6897330f729Sjoerg LastNewReg[AntiDepReg] = NewReg;
6907330f729Sjoerg ++Broken;
6917330f729Sjoerg }
6927330f729Sjoerg }
6937330f729Sjoerg
6947330f729Sjoerg ScanInstruction(MI, Count);
6957330f729Sjoerg }
6967330f729Sjoerg
6977330f729Sjoerg return Broken;
6987330f729Sjoerg }
699*82d56013Sjoerg
700*82d56013Sjoerg AntiDepBreaker *
createCriticalAntiDepBreaker(MachineFunction & MFi,const RegisterClassInfo & RCI)701*82d56013Sjoerg llvm::createCriticalAntiDepBreaker(MachineFunction &MFi,
702*82d56013Sjoerg const RegisterClassInfo &RCI) {
703*82d56013Sjoerg return new CriticalAntiDepBreaker(MFi, RCI);
704*82d56013Sjoerg }
705