41#include "llvm/Config/llvm-config.h"
64#define DEBUG_TYPE "machine-scheduler"
68 cl::desc(
"Enable use of AA during MI DAG construction"));
75 cl::desc(
"Use TargetSchedModel for latency lookup"));
79 cl::desc(
"Use InstrItineraryData for latency lookup"));
89 cl::desc(
"The limit to use while constructing the DAG "
90 "prior to scheduling, at which point a trade-off "
91 "is made to avoid excessive compile time."));
95 cl::desc(
"Enable the store-sequencing DAG construction algorithm. This can "
96 "eliminate a large number of redundant control dependencies and "
97 "spurious alias analysis queries at the cost of some unnecessary "
100#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
103 cl::desc(
"Report top/bottom cycles when dumping SUnit instances"));
125 bool AllObjectsIdentified =
true;
129 if (MMO->isVolatile() || MMO->isAtomic()) {
130 AllObjectsIdentified =
false;
141 AllObjectsIdentified =
false;
142 }
else if (PSV->isAliased(&MFI)) {
146 AllObjectsIdentified =
false;
150 }
else if (
const Value *V = MMO->getValue()) {
153 AllObjectsIdentified &= ObjectsIdentified;
155 for (
Value *V : Objs) {
160 AllObjectsIdentified =
false;
164 return AllObjectsIdentified;
179 unsigned regioninstrs) {
180 assert(bb ==
BB &&
"startBlock should set BB");
200 unsigned OpIdx = MO.getOperandNo();
202 if (Reg.isPhysical()) {
213 for (MCRegUnit Unit :
TRI->regunits(Reg))
215 }
else if (Reg.isVirtual() && MO.readsReg()) {
224 for (
const auto &LI : Succ->liveins()) {
226 auto [Unit, Mask] = *U;
227 if ((Mask & LI.LaneMask).any() && !
Uses.contains(Unit))
248 bool ImplicitPseudoDef = (OperIdx >= DefMIDesc.
getNumOperands() &&
250 for (MCRegUnit Unit :
TRI->regunits(Reg)) {
260 int UseOpIdx =
I->OpIdx;
261 bool ImplicitPseudoUse =
false;
273 ImplicitPseudoUse = UseOpIdx >= ((int)UseMIDesc.
getNumOperands()) &&
278 if (!ImplicitPseudoDef && !ImplicitPseudoUse) {
280 UseInstr, UseOpIdx));
284 ST.adjustSchedDependency(SU, OperIdx, UseSU, UseOpIdx, Dep, &
SchedModel);
298 if (
MRI.isConstantPhysReg(Reg))
310 for (MCRegUnit Unit :
TRI->regunits(Reg)) {
323 SchedModel.computeOutputLatency(
MI, OperIdx, DefInstr));
325 ST.adjustSchedDependency(SU, OperIdx, DefSU,
I->OpIdx, Dep,
337 for (MCRegUnit Unit :
TRI->regunits(Reg))
345 for (MCRegUnit Unit :
TRI->regunits(Reg)) {
357 for (MCRegUnit Unit :
TRI->regunits(Reg)) {
361 for (
bool isBegin =
I ==
B; !isBegin; ) {
362 isBegin = (--
I) ==
B;
371 for (MCRegUnit Unit :
TRI->regunits(Reg))
387 return TRI->getSubRegIndexLaneMask(SubReg);
424 if (OtherMO.isReg() && OtherMO.isDef() && OtherMO.getReg() == Reg)
445 if ((LaneMask & KillLaneMask).
none()) {
450 if ((LaneMask & DefLaneMask).any()) {
456 ST.adjustSchedDependency(SU, OperIdx, UseSU,
I->OperandIndex, Dep,
461 LaneMask &= ~KillLaneMask;
463 if (LaneMask.
any()) {
464 I->LaneMask = LaneMask;
472 if (
MRI.hasOneDef(Reg))
486 if ((V2SU.LaneMask & LaneMask).none())
489 SUnit *DefSU = V2SU.SU;
505 LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
506 LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
508 V2SU.LaneMask = OverlapMask;
509 if (NonOverlapMask.
any())
525 assert(!
MI->isDebugOrPseudoInstr());
540 if ((PrevDefLaneMask & LaneMask).
none())
567 if (
MI.isDebugOrPseudoInstr())
592 switch (
SchedModel.getResourceBufferSize(PRE.ProcResourceIdx)) {
613using SUList = std::list<SUnit *>;
615static void dumpSUList(
const SUList &L) {
616#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
618 for (
const SUnit *SU : L) {
629 unsigned NumNodes = 0;
632 unsigned TrueMemOrderLatency;
635 Value2SUsMap(
unsigned lat = 0) : TrueMemOrderLatency(lat) {}
645 void inline insert(SUnit *SU,
ValueType V) {
654 assert(NumNodes >= Itr->second.size());
655 NumNodes -= Itr->second.size();
663 SmallMapVector<ValueType, SUList, 4>::clear();
667 unsigned inline size()
const {
return NumNodes; }
670 void reComputeSize() {
672 for (
auto &
I : *
this)
673 NumNodes +=
I.second.size();
676 unsigned inline getTrueMemOrderLatency()
const {
677 return TrueMemOrderLatency;
683void Value2SUsMap::dump() {
684 for (
const auto &[ValType, SUs] : *
this) {
690 V->printAsOperand(
dbgs());
718 Value2SUsMap Stores, Loads;
726 Value2SUsMap FPExceptions;
765 struct UnanalyzableFrontier {
767 SUnit *SequencingStore =
nullptr;
771 Value2SUsMap Stores, Loads{1 };
774 bool SeenSequencingLoad =
false;
792 UnanalyzableFrontier Frontier;
800 SUnit *BarrierChain =
nullptr;
802 unsigned MemOpsProcessed = 0;
808 : DAG(DAG), AA(AA), RPTracker(RPTracker), PDiffs(PDiffs), LIS(LIS),
809 Stores(), Loads(1), FPExceptions(), Frontier(),
821 void addChainDependencies(
SUnit *SU, SUList &SUs,
unsigned Latency);
822 void addChainDependencies(
SUnit *SU, Value2SUsMap &Val2SUsMap);
823 void addChainDependencies(
SUnit *SU, Value2SUsMap &Val2SUsMap,
ValueType V);
824 void addChainDependencies(
SUnit *SU, UnanalyzableFrontier &UF,
bool IsStore);
826 void addBarrierChain(Value2SUsMap &map);
827 void addBarrierChain(UnanalyzableFrontier &UF);
831 void updateSequencingStore(UnanalyzableFrontier &UF,
SUnit *SU,
839bool ScheduleDAGDependencyBuilder::UnanalyzableFrontier::shouldUpdate(
843 return !SequencingStore || SeenSequencingLoad || escapesBaseObjects(Objs);
846bool ScheduleDAGDependencyBuilder::UnanalyzableFrontier::escapesBaseObjects(
856void ScheduleDAGDependencyBuilder::UnanalyzableFrontier::clear() {
857 SequencingStore =
nullptr;
858 SeenSequencingLoad =
false;
864bool ScheduleDAGDependencyBuilder::addChainDependency(SUnit *SUa, SUnit *SUb,
875void ScheduleDAGDependencyBuilder::addChainDependencies(SUnit *SU, SUList &SUs,
877 for (SUnit *Entry : SUs)
878 addChainDependency(SU, Entry,
Latency);
881void ScheduleDAGDependencyBuilder::addChainDependencies(
882 SUnit *SU, Value2SUsMap &Val2SUsMap) {
883 for (
auto &
I : Val2SUsMap)
884 addChainDependencies(SU,
I.second, Val2SUsMap.getTrueMemOrderLatency());
887void ScheduleDAGDependencyBuilder::addChainDependencies(
888 SUnit *SU, Value2SUsMap &Val2SUsMap,
ValueType V) {
889 Value2SUsMap::iterator Itr = Val2SUsMap.find(V);
890 if (Itr != Val2SUsMap.end())
891 addChainDependencies(SU, Itr->second, Val2SUsMap.getTrueMemOrderLatency());
894void ScheduleDAGDependencyBuilder::addChainDependencies(
895 SUnit *SU, UnanalyzableFrontier &UF,
bool IsStore) {
896 if (
UF.SequencingStore)
897 UF.SequencingStore->addPredBarrier(SU);
899 addChainDependencies(SU,
UF.Stores, UnknownValue);
901 addChainDependencies(SU,
UF.Loads, UnknownValue);
904void ScheduleDAGDependencyBuilder::addBarrierChain(Value2SUsMap &map) {
905 assert(BarrierChain !=
nullptr);
907 for (
auto &[V, SUs] : map) {
916void ScheduleDAGDependencyBuilder::addBarrierChain(UnanalyzableFrontier &UF) {
917 assert(BarrierChain !=
nullptr);
919 addBarrierChain(
UF.Stores);
920 addBarrierChain(
UF.Loads);
922 if (
UF.SequencingStore)
923 UF.SequencingStore->addPredBarrier(BarrierChain);
928void ScheduleDAGDependencyBuilder::updateSequencingStore(
931 "Only store instructions should be used as sequencing stores");
933 if (
UF.SequencingStore)
934 UF.SequencingStore->addPredBarrier(SU);
937 for (
auto &[V, SUs] :
UF.Stores) {
939 S->addPredBarrier(SU);
948 for (
auto &[V, SUs] :
UF.Loads) {
949 for (
auto It = SUs.begin(); It != SUs.end();) {
950 if (addChainDependency(SU, *It, 1)) {
961 UF.SequencingStore = SU;
962 UF.BaseObjects = std::move(Objs);
963 UF.SeenSequencingLoad =
false;
974 DAG.addSchedBarrierDeps();
982 DAG.DbgValues.emplace_back(DbgMI, &
MI);
986 if (
MI.isDebugValue() ||
MI.isDebugPHI()) {
991 if (
MI.isDebugLabel() ||
MI.isDebugRef() ||
MI.isPseudoProbe())
994 SUnit *SU = DAG.MISUnitMap[&
MI];
995 assert(SU &&
"No SUnit mapped to this MI");
999 RegOpers.
collect(
MI, *DAG.TRI, DAG.MRI, DAG.TrackLaneMasks,
false);
1000 if (DAG.TrackLaneMasks) {
1008 if (PDiffs !=
nullptr)
1009 PDiffs->addInstruction(SU->
NodeNum, RegOpers, DAG.MRI);
1011 if (RPTracker->getPos() == DAG.RegionEnd || &*RPTracker->getPos() != &
MI)
1012 RPTracker->recedeSkipDebugValues();
1013 assert(&*RPTracker->getPos() == &
MI &&
"RPTracker in sync");
1014 RPTracker->recede(RegOpers);
1017 assert((DAG.CanHandleTerminators ||
1018 (!
MI.isTerminator() && !
MI.isPosition())) &&
1019 "Cannot schedule terminators or labels!");
1026 bool HasVRegDef =
false;
1027 for (
unsigned j = 0, n =
MI.getNumOperands(); j != n; ++j) {
1032 if (Reg.isPhysical()) {
1033 DAG.addPhysRegDeps(SU, j);
1034 }
else if (Reg.isVirtual()) {
1036 DAG.addVRegDefDeps(SU, j);
1040 for (
unsigned j = 0, n =
MI.getNumOperands(); j != n; ++j) {
1049 if (Reg.isPhysical()) {
1050 DAG.addPhysRegDeps(SU, j);
1051 }
else if (Reg.isVirtual() && MO.
readsReg()) {
1052 DAG.addVRegUseDeps(SU, j);
1065 DAG.ExitSU.addPred(Dep);
1074 if (
TII->isGlobalMemoryObject(&
MI)) {
1078 BarrierChain->addPredBarrier(SU);
1081 LLVM_DEBUG(
dbgs() <<
"Global memory object and new barrier chain: "
1082 << *BarrierChain <<
".\n");
1085 addBarrierChain(Stores);
1086 addBarrierChain(Loads);
1087 addBarrierChain(FPExceptions);
1088 addBarrierChain(Frontier);
1095 if (
MI.mayRaiseFPException()) {
1097 BarrierChain->addPredBarrier(SU);
1102 <<
"Creating barrier chain and clearing FPExceptions map.\n");
1104 addBarrierChain(FPExceptions);
1106 FPExceptions.insert(SU, UnknownValue);
1111 if (!
MI.mayStore() &&
1112 !(
MI.mayLoad() && !
MI.isDereferenceableInvariantLoad()))
1118 if (BarrierChain && BarrierChain != SU)
1119 BarrierChain->addPredBarrier(SU);
1130 LLVM_DEBUG(
dbgs() <<
"Creating barrier chain and clearing maps.\n");
1134 addBarrierChain(Stores);
1135 addBarrierChain(Loads);
1136 addBarrierChain(Frontier);
1138 MemOpsProcessed = 0;
1147 DAG.MF.getDataLayout());
1149 if (
MI.mayStore()) {
1150 if (!ObjsIdentified) {
1152 addChainDependencies(SU, Stores);
1153 addChainDependencies(SU, Loads);
1155 if (Frontier.shouldUpdate(Objs)) {
1156 LLVM_DEBUG(
dbgs() <<
"Promoting " << *SU <<
" to sequencing store\n");
1157 updateSequencingStore(Frontier, SU, Objs);
1159 addChainDependencies(SU, Frontier,
true);
1160 Frontier.Stores.insert(SU, UnknownValue);
1167 addChainDependencies(SU, Stores, V);
1168 addChainDependencies(SU, Loads, V);
1173 Stores.insert(SU, V);
1177 addChainDependencies(SU, Frontier,
true);
1180 if (!ObjsIdentified) {
1182 addChainDependencies(SU, Stores);
1183 addChainDependencies(SU, Frontier,
false);
1185 Frontier.Loads.insert(SU, UnknownValue);
1186 if (Frontier.escapesBaseObjects(Objs))
1187 Frontier.SeenSequencingLoad =
true;
1192 addChainDependencies(SU, Stores, V);
1195 Loads.insert(SU, V);
1198 addChainDependencies(SU, Frontier,
false);
1204 DAG.FirstDbgValue = DbgMI;
1231 "Only BuildGraph should update Defs/Uses");
1232 Defs.setUniverse(
TRI->getNumRegs());
1233 Uses.setUniverse(
TRI->getNumRegs());
1237 unsigned NumVirtRegs =
MRI.getNumVirtRegs();
1241 std::optional<BatchAAResults> BatchAA;
1243 BatchAA.emplace(*
AA);
1246 *
this, BatchAA.has_value() ? &BatchAA.value() :
nullptr, RPTracker,
1259 PSV->printCustom(OS);
1266 if (!MO.isReg() || !MO.readsReg())
1290 if (
MI.isDebugOrPseudoInstr())
1311 if (!
MI.isBundled()) {
1322 while (
I->isBundledWithSucc())
1325 if (!
I->isDebugOrPseudoInstr())
1328 }
while (
I != Bundle);
1334#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1345#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1346 if (
EntrySU.getInstr() !=
nullptr)
1350 if (
ExitSU.getInstr() !=
nullptr)
1355#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1356std::string ScheduleDAGInstrs::getGraphNodeLabel(
const SUnit *SU)
const {
1361 else if (SU == &ExitSU)
1372 return "dag." +
BB->getFullName();
1376 return SuccSU == &
ExitSU || !
Topo.IsReachable(PredSU, SuccSU);
1405 std::vector<std::pair<const SUnit *, const SUnit*>> ConnectionPairs;
1409 unsigned ParentNodeID;
1410 unsigned SubInstrCount = 0;
1413 RootData(
unsigned id): NodeID(
id),
1414 ParentNodeID(SchedDFSResult::InvalidSubtreeID) {}
1416 unsigned getSparseSetIndex()
const {
return NodeID; }
1423 RootSet.setUniverse(R.DFSNodeData.size());
1431 return R.DFSNodeData[SU->
NodeNum].SubtreeID
1432 != SchedDFSResult::InvalidSubtreeID;
1438 R.DFSNodeData[SU->
NodeNum].InstrCount =
1462 if ((
InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
1466 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1469 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1470 RootSet[PredNum].ParentNodeID = SU->
NodeNum;
1472 else if (RootSet.count(PredNum)) {
1477 RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1478 RootSet.erase(PredNum);
1488 R.DFSNodeData[Succ->
NodeNum].InstrCount
1495 ConnectionPairs.emplace_back(PredDep.
getSUnit(), Succ);
1501 SubtreeClasses.compress();
1502 R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1503 assert(SubtreeClasses.getNumClasses() == RootSet.size()
1504 &&
"number of roots should match trees");
1505 for (
const RootData &Root : RootSet) {
1506 unsigned TreeID = SubtreeClasses[Root.NodeID];
1507 if (Root.ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1508 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[Root.ParentNodeID];
1509 R.DFSTreeData[TreeID].SubInstrCount = Root.SubInstrCount;
1515 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1516 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1518 for (
unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1519 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
1521 << R.DFSNodeData[Idx].SubtreeID <<
'\n');
1523 for (
const auto &[Pred, Succ] : ConnectionPairs) {
1524 unsigned PredTree = SubtreeClasses[Pred->NodeNum];
1525 unsigned SuccTree = SubtreeClasses[Succ->NodeNum];
1526 if (PredTree == SuccTree)
1528 unsigned Depth = Pred->getDepth();
1538 bool CheckLimit =
true) {
1543 unsigned PredNum = PredSU->
NodeNum;
1544 if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
1549 unsigned NumDataSucs = 0;
1550 for (
const SDep &SuccDep : PredSU->
Succs) {
1552 if (++NumDataSucs >= 4)
1556 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
1558 R.DFSNodeData[PredNum].SubtreeID = Succ->
NodeNum;
1559 SubtreeClasses.join(Succ->
NodeNum, PredNum);
1570 R.SubtreeConnections[FromTree];
1571 for (SchedDFSResult::Connection &
C : Connections) {
1572 if (
C.TreeID == ToTree) {
1573 C.Level = std::max(
C.Level,
Depth);
1577 Connections.
push_back(SchedDFSResult::Connection(ToTree,
Depth));
1578 FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1579 }
while (FromTree != SchedDFSResult::InvalidSubtreeID);
1588class SchedDAGReverseDFS {
1589 std::vector<std::pair<const SUnit *, SUnit::const_pred_iterator>> DFSStack;
1592 bool isComplete()
const {
return DFSStack.empty(); }
1594 void follow(
const SUnit *SU) {
1595 DFSStack.emplace_back(SU, SU->
Preds.begin());
1597 void advance() { ++DFSStack.back().second; }
1599 const SDep *backtrack() {
1600 DFSStack.pop_back();
1601 return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
1604 const SUnit *getCurr()
const {
return DFSStack.back().first; }
1609 return getCurr()->Preds.
end();
1631 for (
const SUnit &SU : SUnits) {
1635 SchedDAGReverseDFS DFS;
1636 Impl.visitPreorder(&SU);
1640 while (DFS.getPred() != DFS.getPredEnd()) {
1641 const SDep &PredDep = *DFS.getPred();
1649 if (Impl.isVisited(PredDep.
getSUnit())) {
1650 Impl.visitCrossEdge(PredDep, DFS.getCurr());
1653 Impl.visitPreorder(PredDep.
getSUnit());
1657 const SUnit *Child = DFS.getCurr();
1658 const SDep *PredDep = DFS.backtrack();
1659 Impl.visitPostorderNode(Child);
1661 Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
1662 if (DFS.isComplete())
1673 for (
const Connection &
C : SubtreeConnections[SubtreeID]) {
1674 SubtreeConnectLevels[
C.TreeID] =
1675 std::max(SubtreeConnectLevels[
C.TreeID],
C.Level);
1677 << SubtreeConnectLevels[
C.TreeID] <<
'\n');
1681#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1691 dbgs() << *
this <<
'\n';
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static unsigned InstrCount
static cl::opt< bool > UseAA("amdgpu-use-aa-in-codegen", cl::desc("Enable the use of AA during codegen."), cl::init(true))
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
Equivalence classes for small integers.
A common definition of LaneBitmask for use in TableGen and CodeGen.
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
This file implements a map that provides insertion order iteration.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
static void toggleKills(const MachineRegisterInfo &MRI, LiveRegUnits &LiveRegs, MachineInstr &MI, bool addToLiveRegs)
static bool getUnderlyingObjectsForInstr(const MachineInstr *MI, const MachineFrameInfo &MFI, UnderlyingObjectsVector &Objects, const DataLayout &DL)
If this machine instruction has memory reference information, collect the list of underlying objects ...
static bool hasDataSucc(const SUnit *SU)
static cl::opt< bool > EnableStoreSequencing("enable-unanalyzable-store-sequencing", cl::Hidden, cl::init(false), cl::desc("Enable the store-sequencing DAG construction algorithm. This can " "eliminate a large number of redundant control dependencies and " "spurious alias analysis queries at the cost of some unnecessary " "dependencies."))
static cl::opt< bool > EnableSchedModel("schedmodel", cl::Hidden, cl::init(true), cl::desc("Use TargetSchedModel for latency lookup"))
static cl::opt< bool > EnableAASchedMI("enable-aa-sched-mi", cl::Hidden, cl::desc("Enable use of AA during MI DAG construction"))
static cl::opt< bool > UseTBAA("use-tbaa-in-sched-mi", cl::Hidden, cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"))
static cl::opt< unsigned > HugeRegion("dag-maps-huge-region", cl::Hidden, cl::init(500), cl::desc("The limit to use while constructing the DAG " "prior to scheduling, at which point a trade-off " "is made to avoid excessive compile time."))
static cl::opt< bool > EnableSchedItins("scheditins", cl::Hidden, cl::init(true), cl::desc("Use InstrItineraryData for latency lookup"))
static cl::opt< bool > SchedPrintCycles("sched-print-cycles", cl::Hidden, cl::init(false), cl::desc("Report top/bottom cycles when dumping SUnit instances"))
This file defines the SmallVector class.
This file defines the SparseSet class derived from the version described in Briggs,...
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
ConstMIBundleOperands - Iterate over all operands in a const bundle of machine instructions.
A parsed version of the target data layout string in and methods for querying it.
A set of register units used to track register liveness.
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
bool hasImplicitUseOfPhysReg(MCRegister Reg) const
Return true if this instruction implicitly uses the specified physical register.
LLVM_ABI bool hasImplicitDefOfPhysReg(MCRegister Reg, const MCRegisterInfo *MRI=nullptr) const
Return true if this instruction implicitly defines the specified physical register.
MCRegUnitMaskIterator enumerates a list of register units and their associated lane masks for Reg.
bool isValid() const
Returns true if this iterator is not yet at the end.
LaneBitmask getLaneMask() const
Returns the combination of all lane masks of register in this class.
const bool HasDisjunctSubRegs
Whether the class supports two (or more) disjunct subregister indices.
Instructions::iterator instr_iterator
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasTailCall() const
Returns true if the function contains a tail call.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Representation of each machine instruction.
bool isBarrier(QueryType Type=AnyInBundle) const
Returns true if the specified instruction stops control flow from executing the instruction immediate...
bool isCall(QueryType Type=AnyInBundle) const
LLVM_ABI bool mayAlias(BatchAAResults *AA, const MachineInstr &Other, bool UseTBAA) const
Returns true if this instruction's memory access aliases the memory access of Other.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
LLVM_ABI void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
filtered_mop_range all_uses()
Returns an iterator range over all operands that are (explicit or implicit) register uses.
bool isTransient() const
Return true if this is a transient instruction that is either very likely to be eliminated during reg...
LLVM_ABI void dump() const
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
void setIsKill(bool Val=true)
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
ValueT & operator[](const KeyT &Key)
LLVM_ABI void init(unsigned N)
Initialize an array of N PressureDiffs.
Special value supplied for machine level alias analysis.
Track the current register pressure at some position in the instruction stream, and remember the high...
List of registers defined and used by a machine instruction.
LLVM_ABI void detectDeadDefs(const MachineInstr &MI, LiveIntervals &LIS, const MachineRegisterInfo &MRI)
Use liveness information to find dead defs at MI's dead slot not marked with a dead flag and move the...
LLVM_ABI void adjustLaneLiveness(LiveIntervals &LIS, const MachineRegisterInfo &MRI, SlotIndex Pos)
Use liveness information to find out which uses/defs are partially undefined/dead at Pos and adjust t...
LLVM_ABI void collect(const MachineInstr &MI, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, bool TrackLaneMasks, bool IgnoreDead)
Analyze the given instruction MI and fill in the Uses, Defs and DeadDefs list based on the MachineOpe...
Wrapper class representing virtual and physical registers.
Kind getKind() const
Returns an enum value representing the kind of the dependence.
Kind
These are the different kinds of scheduling dependencies.
@ Output
A register output-dependence (aka WAW).
@ Anti
A register anti-dependence (aka WAR).
@ Data
Regular data dependence (aka true-dependence).
void setLatency(unsigned Lat)
Sets the latency for this edge.
@ Artificial
Arbitrary strong DAG edge (no real dependence).
@ MayAliasMem
Nonvolatile load/Store instructions that may alias.
bool isArtificial() const
Tests if this is an Order dependence that is marked as "artificial", meaning it isn't necessary for c...
Scheduling unit. This is a node in the scheduling DAG.
bool isCall
Is a function call.
bool addPredBarrier(SUnit *SU)
Adds a barrier edge to SU by calling addPred(), with latency 0 generally or latency 1 for a store fol...
unsigned TopReadyCycle
Cycle relative to start when node is ready.
unsigned NodeNum
Entry # of node in the node vector.
bool isUnbuffered
Uses an unbuffered resource.
SmallVectorImpl< SDep >::const_iterator const_pred_iterator
unsigned short Latency
Node latency.
bool isBoundaryNode() const
Boundary nodes are placeholders for the boundary of the scheduling region.
bool hasPhysRegDefs
Has physreg defs that are being used.
unsigned BotReadyCycle
Cycle relative to end when node is ready.
SmallVector< SDep, 4 > Succs
All sunit successors.
bool hasReservedResource
Uses a reserved resource.
bool isCommutable
Is a commutable instruction.
bool hasPhysRegUses
Has physreg uses.
SmallVector< SDep, 4 > Preds
All sunit predecessors.
LLVM_ABI bool addPred(const SDep &D, bool Required=true)
Adds the specified edge as a pred of the current node if not already.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
void visitPostorderNode(const SUnit *SU)
Called once for each node after all predecessors are visited.
bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ, bool CheckLimit=true)
Joins the predecessor subtree with the successor that is its DFS parent.
void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth)
Called by finalize() to record a connection between trees.
void finalize()
Sets each node's subtree ID to the representative ID and record connections between trees.
void visitCrossEdge(const SDep &PredDep, const SUnit *Succ)
Adds a connection for cross edges.
void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ)
Called once for each tree edge after calling visitPostOrderNode on the predecessor.
void visitPreorder(const SUnit *SU)
Initializes this node's instruction count.
bool isVisited(const SUnit *SU) const
Returns true if this node been visited by the DFS traversal.
SchedDFSImpl(SchedDFSResult &r)
Compute the values of each DAG node for various metrics during DFS.
friend class SchedDFSImpl
LLVM_ABI void compute(ArrayRef< SUnit > SUnits)
Compute various metrics for the DAG with given roots.
LLVM_ABI void scheduleTree(unsigned SubtreeID)
Scheduler callback to update SubtreeConnectLevels when a tree is initially scheduled.
ScheduleDAGDependencyBuilder(ScheduleDAGInstrs &DAG, BatchAAResults *AA, RegPressureTracker *RPTracker, PressureDiffs *PDiffs, LiveIntervals *LIS)
A ScheduleDAG for scheduling lists of MachineInstr.
LiveRegUnits LiveRegs
Set of live physical registers for updating kill flags.
DenseMap< MachineInstr *, SUnit * > MISUnitMap
After calling BuildSchedGraph, each machine instruction in the current scheduling region is mapped to...
void addVRegUseDeps(SUnit *SU, unsigned OperIdx)
Adds a register data dependency if the instruction that defines the virtual register used at OperIdx ...
void addVRegDefDeps(SUnit *SU, unsigned OperIdx)
Adds register output and data dependencies from this SUnit to instructions that occur later in the sa...
virtual void finishBlock()
Cleans up after scheduling in the given block.
MachineBasicBlock::iterator end() const
Returns an iterator to the bottom of the current scheduling region.
std::string getDAGName() const override
Returns a label for the region of code covered by the DAG.
MachineBasicBlock * BB
The block in which to insert instructions.
MachineInstr * FirstDbgValue
virtual void startBlock(MachineBasicBlock *BB)
Prepares to perform scheduling in the given block.
void addPhysRegDeps(SUnit *SU, unsigned OperIdx)
Adds register dependencies (data, anti, and output) from this SUnit to following instructions in the ...
friend class ScheduleDAGDependencyBuilder
MachineBasicBlock::iterator RegionEnd
The end of the range to be scheduled.
VReg2SUnitOperIdxMultiMap CurrentVRegUses
Tracks the last instructions in this region using each virtual register.
const MCSchedClassDesc * getSchedClass(SUnit *SU) const
Resolves and cache a resolved scheduling class for an SUnit.
void fixupKills(MachineBasicBlock &MBB)
Fixes register kill flags that scheduling has made invalid.
void addPhysRegDataDeps(SUnit *SU, unsigned OperIdx)
MO is an operand of SU's instruction that defines a physical register.
ScheduleDAGInstrs(MachineFunction &mf, const MachineLoopInfo *mli, bool RemoveKillFlags=false)
LaneBitmask getLaneMaskForMO(const MachineOperand &MO) const
Returns a mask for which lanes get read/written by the given (register) machine operand.
DbgValueVector DbgValues
Remember instruction that precedes DBG_VALUE.
SUnit * newSUnit(MachineInstr *MI)
Creates a new SUnit and return a ptr to it.
void initSUnits()
Creates an SUnit for each real instruction, numbered in top-down topological order.
bool addEdge(SUnit *SuccSU, const SDep &PredDep)
Add a DAG edge to the given SU with the given predecessor dependence data.
ScheduleDAGTopologicalSort Topo
Topo - A topological ordering for SUnits which permits fast IsReachable and similar queries.
bool TrackLaneMasks
Whether lane masks should get tracked.
void dumpNode(const SUnit &SU) const override
RegUnit2SUnitsMap Defs
Defs, Uses - Remember where defs and uses of each register are as we iterate upward through the instr...
VReg2SUnitMultiMap CurrentVRegDefs
Tracks the last instruction(s) in this region defining each virtual register.
MachineBasicBlock::iterator begin() const
Returns an iterator to the top of the current scheduling region.
void buildSchedGraph(AAResults *AA, RegPressureTracker *RPTracker=nullptr, PressureDiffs *PDiffs=nullptr, LiveIntervals *LIS=nullptr, bool TrackLaneMasks=false)
Builds SUnits for the current region.
TargetSchedModel SchedModel
TargetSchedModel provides an interface to the machine model.
virtual void exitRegion()
Called when the scheduler has finished scheduling the current region.
bool canAddEdge(SUnit *SuccSU, SUnit *PredSU)
True if an edge can be added from PredSU to SuccSU without creating a cycle.
const MachineLoopInfo * MLI
bool RemoveKillFlags
True if the DAG builder should remove kill flags (in preparation for rescheduling).
MachineBasicBlock::iterator RegionBegin
The beginning of the range to be scheduled.
void addSchedBarrierDeps()
Adds dependencies from instructions in the current list of instructions being scheduled to scheduling...
virtual void enterRegion(MachineBasicBlock *bb, MachineBasicBlock::iterator begin, MachineBasicBlock::iterator end, unsigned regioninstrs)
Initialize the DAG and common scheduler state for a new scheduling region.
void dump() const override
unsigned NumRegionInstrs
Instructions in this region (distance(RegionBegin, RegionEnd)).
const MachineFrameInfo & MFI
bool deadDefHasNoUse(const MachineOperand &MO)
Returns true if the def register in MO has no uses.
MachineRegisterInfo & MRI
Virtual/real register map.
void clearDAG()
Clears the DAG state (between regions).
std::vector< SUnit > SUnits
The scheduling units.
const TargetRegisterInfo * TRI
Target processor register info.
SUnit EntrySU
Special node for the region entry.
MachineFunction & MF
Machine function.
ScheduleDAG(const ScheduleDAG &)=delete
void dumpNodeAll(const SUnit &SU) const
void dumpNodeName(const SUnit &SU) const
SUnit ExitSU
Special node for the region exit.
SlotIndex - An opaque wrapper around machine indexes.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< iterator, iterator > RangePair
iterator_base< SparseMultiSet * > iterator
SparseSet - Fast set implementation for objects that can be identified by small unsigned keys.
TargetInstrInfo - Interface to description of machine instruction set.
TargetSubtargetInfo - Generic base class for all target subtargets.
The instances of the Type class are immutable: once they are created, they are never changed.
'undef' values are things that do not have specified contents.
A Use represents the edge between a Value definition and its users.
LLVM Value Representation.
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
SmallVector< ValueType, 4 > UnderlyingObjectsVector
LLVM_ABI bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
auto reverse(ContainerTy &&C)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IterT skipDebugInstructionsBackward(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It until it points to a non-debug instruction or to Begin and return the resulting iterator...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Represent the ILP of the subDAG rooted at a DAG node.
unsigned Length
Length may either correspond to depth or height, depending on direction, and cycles or nodes dependin...
LLVM_ABI void dump() const
LLVM_ABI void print(raw_ostream &OS) const
static constexpr LaneBitmask getAll()
constexpr bool any() const
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Identify one of the processor resource kinds consumed by a particular scheduling class for the specif...
Record a physical register access.
A MapVector that performs no allocations if smaller than a certain size.
Mapping from virtual register to SUnit including an operand index.
An individual mapping from virtual register number to SUnit.