1 //===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// \file This implements the ScheduleDAGInstrs class, which implements
11 /// re-scheduling of MachineInstrs.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
16 #include "llvm/ADT/IntEqClasses.h"
17 #include "llvm/ADT/MapVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/SparseSet.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/CodeGen/LiveIntervals.h"
25 #include "llvm/CodeGen/LivePhysRegs.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineInstrBundle.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/MachineOperand.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/RegisterPressure.h"
36 #include "llvm/CodeGen/ScheduleDAG.h"
37 #include "llvm/CodeGen/ScheduleDFS.h"
38 #include "llvm/CodeGen/SlotIndexes.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSubtargetInfo.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/Instruction.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/Operator.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/IR/Value.h"
48 #include "llvm/MC/LaneBitmask.h"
49 #include "llvm/MC/MCRegisterInfo.h"
50 #include "llvm/Support/Casting.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/Format.h"
56 #include "llvm/Support/raw_ostream.h"
66 #define DEBUG_TYPE "machine-scheduler"
68 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
69 cl::ZeroOrMore, cl::init(false),
70 cl::desc("Enable use of AA during MI DAG construction"));
72 static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
73 cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"));
75 // Note: the two options below might be used in tuning compile time vs
76 // output quality. Setting HugeRegion so large that it will never be
77 // reached means best-effort, but may be slow.
79 // When Stores and Loads maps (or NonAliasStores and NonAliasLoads)
80 // together hold this many SUs, a reduction of maps will be done.
81 static cl::opt<unsigned> HugeRegion("dag-maps-huge-region", cl::Hidden,
82 cl::init(1000), cl::desc("The limit to use while constructing the DAG "
83 "prior to scheduling, at which point a trade-off "
84 "is made to avoid excessive compile time."));
86 static cl::opt<unsigned> ReductionSize(
87 "dag-maps-reduction-size", cl::Hidden,
88 cl::desc("A huge scheduling region will have maps reduced by this many "
89 "nodes at a time. Defaults to HugeRegion / 2."));
91 static unsigned getReductionSize() {
92 // Always reduce a huge region with half of the elements, except
93 // when user sets this number explicitly.
94 if (ReductionSize.getNumOccurrences() == 0)
95 return HugeRegion / 2;
99 static void dumpSUList(ScheduleDAGInstrs::SUList &L) {
100 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
102 for (const SUnit *su : L) {
103 dbgs() << "SU(" << su->NodeNum << ")";
111 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
112 const MachineLoopInfo *mli,
113 bool RemoveKillFlags)
114 : ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()),
115 RemoveKillFlags(RemoveKillFlags),
116 UnknownValue(UndefValue::get(
117 Type::getVoidTy(mf.getFunction().getContext()))) {
120 const TargetSubtargetInfo &ST = mf.getSubtarget();
121 SchedModel.init(ST.getSchedModel(), &ST, TII);
124 /// If this machine instr has memory reference information and it can be
125 /// tracked to a normal reference to a known object, return the Value
126 /// for that object. This function returns false the memory location is
127 /// unknown or may alias anything.
128 static bool getUnderlyingObjectsForInstr(const MachineInstr *MI,
129 const MachineFrameInfo &MFI,
130 UnderlyingObjectsVector &Objects,
131 const DataLayout &DL) {
132 auto allMMOsOkay = [&]() {
133 for (const MachineMemOperand *MMO : MI->memoperands()) {
134 if (MMO->isVolatile())
137 if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) {
138 // Function that contain tail calls don't have unique PseudoSourceValue
139 // objects. Two PseudoSourceValues might refer to the same or
140 // overlapping locations. The client code calling this function assumes
141 // this is not the case. So return a conservative answer of no known
143 if (MFI.hasTailCall())
146 // For now, ignore PseudoSourceValues which may alias LLVM IR values
147 // because the code that uses this function has no way to cope with
149 if (PSV->isAliased(&MFI))
152 bool MayAlias = PSV->mayAlias(&MFI);
153 Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
154 } else if (const Value *V = MMO->getValue()) {
155 SmallVector<Value *, 4> Objs;
156 if (!getUnderlyingObjectsForCodeGen(V, Objs, DL))
159 for (Value *V : Objs) {
160 assert(isIdentifiedObject(V));
161 Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
169 if (!allMMOsOkay()) {
177 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
181 void ScheduleDAGInstrs::finishBlock() {
182 // Subclasses should no longer refer to the old block.
186 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
187 MachineBasicBlock::iterator begin,
188 MachineBasicBlock::iterator end,
189 unsigned regioninstrs) {
190 assert(bb == BB && "startBlock should set BB");
193 NumRegionInstrs = regioninstrs;
196 void ScheduleDAGInstrs::exitRegion() {
200 void ScheduleDAGInstrs::addSchedBarrierDeps() {
201 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr;
202 ExitSU.setInstr(ExitMI);
203 // Add dependencies on the defs and uses of the instruction.
205 for (const MachineOperand &MO : ExitMI->operands()) {
206 if (!MO.isReg() || MO.isDef()) continue;
207 unsigned Reg = MO.getReg();
208 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
209 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
210 } else if (TargetRegisterInfo::isVirtualRegister(Reg) && MO.readsReg()) {
211 addVRegUseDeps(&ExitSU, ExitMI->getOperandNo(&MO));
215 if (!ExitMI || (!ExitMI->isCall() && !ExitMI->isBarrier())) {
216 // For others, e.g. fallthrough, conditional branch, assume the exit
217 // uses all the registers that are livein to the successor blocks.
218 for (const MachineBasicBlock *Succ : BB->successors()) {
219 for (const auto &LI : Succ->liveins()) {
220 if (!Uses.contains(LI.PhysReg))
221 Uses.insert(PhysRegSUOper(&ExitSU, -1, LI.PhysReg));
227 /// MO is an operand of SU's instruction that defines a physical register. Adds
228 /// data dependencies from SU to any uses of the physical register.
229 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
230 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
231 assert(MO.isDef() && "expect physreg def");
233 // Ask the target if address-backscheduling is desirable, and if so how much.
234 const TargetSubtargetInfo &ST = MF.getSubtarget();
236 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
237 Alias.isValid(); ++Alias) {
238 if (!Uses.contains(*Alias))
240 for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
241 SUnit *UseSU = I->SU;
245 // Adjust the dependence latency using operand def/use information,
246 // then allow the target to perform its own adjustments.
247 int UseOp = I->OpIdx;
248 MachineInstr *RegUse = nullptr;
251 Dep = SDep(SU, SDep::Artificial);
253 // Set the hasPhysRegDefs only for physreg defs that have a use within
254 // the scheduling region.
255 SU->hasPhysRegDefs = true;
256 Dep = SDep(SU, SDep::Data, *Alias);
257 RegUse = UseSU->getInstr();
260 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
263 ST.adjustSchedDependency(SU, UseSU, Dep);
269 /// \brief Adds register dependencies (data, anti, and output) from this SUnit
270 /// to following instructions in the same scheduling region that depend the
271 /// physical register referenced at OperIdx.
272 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
273 MachineInstr *MI = SU->getInstr();
274 MachineOperand &MO = MI->getOperand(OperIdx);
275 unsigned Reg = MO.getReg();
276 // We do not need to track any dependencies for constant registers.
277 if (MRI.isConstantPhysReg(Reg))
280 // Optionally add output and anti dependencies. For anti
281 // dependencies we use a latency of 0 because for a multi-issue
282 // target we want to allow the defining instruction to issue
283 // in the same cycle as the using instruction.
284 // TODO: Using a latency of 1 here for output dependencies assumes
285 // there's no cost for reusing registers.
286 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
287 for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
288 if (!Defs.contains(*Alias))
290 for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
291 SUnit *DefSU = I->SU;
292 if (DefSU == &ExitSU)
295 (Kind != SDep::Output || !MO.isDead() ||
296 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
297 if (Kind == SDep::Anti)
298 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
300 SDep Dep(SU, Kind, /*Reg=*/*Alias);
302 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
310 SU->hasPhysRegUses = true;
311 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
312 // retrieve the existing SUnits list for this register's uses.
313 // Push this SUnit on the use list.
314 Uses.insert(PhysRegSUOper(SU, OperIdx, Reg));
318 addPhysRegDataDeps(SU, OperIdx);
320 // clear this register's use list
321 if (Uses.contains(Reg))
326 } else if (SU->isCall) {
327 // Calls will not be reordered because of chain dependencies (see
328 // below). Since call operands are dead, calls may continue to be added
329 // to the DefList making dependence checking quadratic in the size of
330 // the block. Instead, we leave only one call at the back of the
332 Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
333 Reg2SUnitsMap::iterator B = P.first;
334 Reg2SUnitsMap::iterator I = P.second;
335 for (bool isBegin = I == B; !isBegin; /* empty */) {
336 isBegin = (--I) == B;
343 // Defs are pushed in the order they are visited and never reordered.
344 Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
348 LaneBitmask ScheduleDAGInstrs::getLaneMaskForMO(const MachineOperand &MO) const
350 unsigned Reg = MO.getReg();
351 // No point in tracking lanemasks if we don't have interesting subregisters.
352 const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
353 if (!RC.HasDisjunctSubRegs)
354 return LaneBitmask::getAll();
356 unsigned SubReg = MO.getSubReg();
358 return RC.getLaneMask();
359 return TRI->getSubRegIndexLaneMask(SubReg);
362 /// Adds register output and data dependencies from this SUnit to instructions
363 /// that occur later in the same scheduling region if they read from or write to
364 /// the virtual register defined at OperIdx.
366 /// TODO: Hoist loop induction variable increments. This has to be
367 /// reevaluated. Generally, IV scheduling should be done before coalescing.
368 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
369 MachineInstr *MI = SU->getInstr();
370 MachineOperand &MO = MI->getOperand(OperIdx);
371 unsigned Reg = MO.getReg();
373 LaneBitmask DefLaneMask;
374 LaneBitmask KillLaneMask;
375 if (TrackLaneMasks) {
376 bool IsKill = MO.getSubReg() == 0 || MO.isUndef();
377 DefLaneMask = getLaneMaskForMO(MO);
378 // If we have a <read-undef> flag, none of the lane values comes from an
379 // earlier instruction.
380 KillLaneMask = IsKill ? LaneBitmask::getAll() : DefLaneMask;
382 // Clear undef flag, we'll re-add it later once we know which subregister
384 MO.setIsUndef(false);
386 DefLaneMask = LaneBitmask::getAll();
387 KillLaneMask = LaneBitmask::getAll();
391 assert(CurrentVRegUses.find(Reg) == CurrentVRegUses.end() &&
392 "Dead defs should have no uses");
394 // Add data dependence to all uses we found so far.
395 const TargetSubtargetInfo &ST = MF.getSubtarget();
396 for (VReg2SUnitOperIdxMultiMap::iterator I = CurrentVRegUses.find(Reg),
397 E = CurrentVRegUses.end(); I != E; /*empty*/) {
398 LaneBitmask LaneMask = I->LaneMask;
399 // Ignore uses of other lanes.
400 if ((LaneMask & KillLaneMask).none()) {
405 if ((LaneMask & DefLaneMask).any()) {
406 SUnit *UseSU = I->SU;
407 MachineInstr *Use = UseSU->getInstr();
408 SDep Dep(SU, SDep::Data, Reg);
409 Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use,
411 ST.adjustSchedDependency(SU, UseSU, Dep);
415 LaneMask &= ~KillLaneMask;
416 // If we found a Def for all lanes of this use, remove it from the list.
417 if (LaneMask.any()) {
418 I->LaneMask = LaneMask;
421 I = CurrentVRegUses.erase(I);
425 // Shortcut: Singly defined vregs do not have output/anti dependencies.
426 if (MRI.hasOneDef(Reg))
429 // Add output dependence to the next nearest defs of this vreg.
431 // Unless this definition is dead, the output dependence should be
432 // transitively redundant with antidependencies from this definition's
433 // uses. We're conservative for now until we have a way to guarantee the uses
434 // are not eliminated sometime during scheduling. The output dependence edge
435 // is also useful if output latency exceeds def-use latency.
436 LaneBitmask LaneMask = DefLaneMask;
437 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
438 CurrentVRegDefs.end())) {
439 // Ignore defs for other lanes.
440 if ((V2SU.LaneMask & LaneMask).none())
442 // Add an output dependence.
443 SUnit *DefSU = V2SU.SU;
444 // Ignore additional defs of the same lanes in one instruction. This can
445 // happen because lanemasks are shared for targets with too many
446 // subregisters. We also use some representration tricks/hacks where we
447 // add super-register defs/uses, to imply that although we only access parts
448 // of the reg we care about the full one.
451 SDep Dep(SU, SDep::Output, Reg);
453 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
456 // Update current definition. This can get tricky if the def was about a
457 // bigger lanemask before. We then have to shrink it and create a new
458 // VReg2SUnit for the non-overlapping part.
459 LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
460 LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
462 V2SU.LaneMask = OverlapMask;
463 if (NonOverlapMask.any())
464 CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, DefSU));
466 // If there was no CurrentVRegDefs entry for some lanes yet, create one.
468 CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU));
471 /// \brief Adds a register data dependency if the instruction that defines the
472 /// virtual register used at OperIdx is mapped to an SUnit. Add a register
473 /// antidependency from this SUnit to instructions that occur later in the same
474 /// scheduling region if they write the virtual register.
476 /// TODO: Handle ExitSU "uses" properly.
477 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
478 const MachineInstr *MI = SU->getInstr();
479 const MachineOperand &MO = MI->getOperand(OperIdx);
480 unsigned Reg = MO.getReg();
482 // Remember the use. Data dependencies will be added when we find the def.
483 LaneBitmask LaneMask = TrackLaneMasks ? getLaneMaskForMO(MO)
484 : LaneBitmask::getAll();
485 CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU));
487 // Add antidependences to the following defs of the vreg.
488 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
489 CurrentVRegDefs.end())) {
490 // Ignore defs for unrelated lanes.
491 LaneBitmask PrevDefLaneMask = V2SU.LaneMask;
492 if ((PrevDefLaneMask & LaneMask).none())
497 V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg));
501 /// Returns true if MI is an instruction we are unable to reason about
502 /// (like a call or something with unmodeled side effects).
503 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
504 return MI->isCall() || MI->hasUnmodeledSideEffects() ||
505 (MI->hasOrderedMemoryRef() && !MI->isDereferenceableInvariantLoad(AA));
508 void ScheduleDAGInstrs::addChainDependency (SUnit *SUa, SUnit *SUb,
510 if (SUa->getInstr()->mayAlias(AAForDep, *SUb->getInstr(), UseTBAA)) {
511 SDep Dep(SUa, SDep::MayAliasMem);
512 Dep.setLatency(Latency);
517 /// \brief Creates an SUnit for each real instruction, numbered in top-down
518 /// topological order. The instruction order A < B, implies that no edge exists
521 /// Map each real instruction to its SUnit.
523 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
524 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
525 /// instead of pointers.
527 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
528 /// the original instruction list.
529 void ScheduleDAGInstrs::initSUnits() {
530 // We'll be allocating one SUnit for each real instruction in the region,
531 // which is contained within a basic block.
532 SUnits.reserve(NumRegionInstrs);
534 for (MachineInstr &MI : make_range(RegionBegin, RegionEnd)) {
535 if (MI.isDebugValue())
538 SUnit *SU = newSUnit(&MI);
539 MISUnitMap[&MI] = SU;
541 SU->isCall = MI.isCall();
542 SU->isCommutable = MI.isCommutable();
544 // Assign the Latency field of SU using target-provided information.
545 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
547 // If this SUnit uses a reserved or unbuffered resource, mark it as such.
549 // Reserved resources block an instruction from issuing and stall the
550 // entire pipeline. These are identified by BufferSize=0.
552 // Unbuffered resources prevent execution of subsequent instructions that
553 // require the same resources. This is used for in-order execution pipelines
554 // within an out-of-order core. These are identified by BufferSize=1.
555 if (SchedModel.hasInstrSchedModel()) {
556 const MCSchedClassDesc *SC = getSchedClass(SU);
557 for (const MCWriteProcResEntry &PRE :
558 make_range(SchedModel.getWriteProcResBegin(SC),
559 SchedModel.getWriteProcResEnd(SC))) {
560 switch (SchedModel.getProcResource(PRE.ProcResourceIdx)->BufferSize) {
562 SU->hasReservedResource = true;
565 SU->isUnbuffered = true;
575 class ScheduleDAGInstrs::Value2SUsMap : public MapVector<ValueType, SUList> {
576 /// Current total number of SUs in map.
577 unsigned NumNodes = 0;
579 /// 1 for loads, 0 for stores. (see comment in SUList)
580 unsigned TrueMemOrderLatency;
583 Value2SUsMap(unsigned lat = 0) : TrueMemOrderLatency(lat) {}
585 /// To keep NumNodes up to date, insert() is used instead of
586 /// this operator w/ push_back().
587 ValueType &operator[](const SUList &Key) {
588 llvm_unreachable("Don't use. Use insert() instead."); };
590 /// Adds SU to the SUList of V. If Map grows huge, reduce its size by calling
592 void inline insert(SUnit *SU, ValueType V) {
593 MapVector::operator[](V).push_back(SU);
597 /// Clears the list of SUs mapped to V.
598 void inline clearList(ValueType V) {
599 iterator Itr = find(V);
601 assert(NumNodes >= Itr->second.size());
602 NumNodes -= Itr->second.size();
608 /// Clears map from all contents.
610 MapVector<ValueType, SUList>::clear();
614 unsigned inline size() const { return NumNodes; }
616 /// Counts the number of SUs in this map after a reduction.
617 void reComputeSize() {
619 for (auto &I : *this)
620 NumNodes += I.second.size();
623 unsigned inline getTrueMemOrderLatency() const {
624 return TrueMemOrderLatency;
630 void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
631 Value2SUsMap &Val2SUsMap) {
632 for (auto &I : Val2SUsMap)
633 addChainDependencies(SU, I.second,
634 Val2SUsMap.getTrueMemOrderLatency());
637 void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
638 Value2SUsMap &Val2SUsMap,
640 Value2SUsMap::iterator Itr = Val2SUsMap.find(V);
641 if (Itr != Val2SUsMap.end())
642 addChainDependencies(SU, Itr->second,
643 Val2SUsMap.getTrueMemOrderLatency());
646 void ScheduleDAGInstrs::addBarrierChain(Value2SUsMap &map) {
647 assert(BarrierChain != nullptr);
649 for (auto &I : map) {
650 SUList &sus = I.second;
652 SU->addPredBarrier(BarrierChain);
657 void ScheduleDAGInstrs::insertBarrierChain(Value2SUsMap &map) {
658 assert(BarrierChain != nullptr);
660 // Go through all lists of SUs.
661 for (Value2SUsMap::iterator I = map.begin(), EE = map.end(); I != EE;) {
662 Value2SUsMap::iterator CurrItr = I++;
663 SUList &sus = CurrItr->second;
664 SUList::iterator SUItr = sus.begin(), SUEE = sus.end();
665 for (; SUItr != SUEE; ++SUItr) {
666 // Stop on BarrierChain or any instruction above it.
667 if ((*SUItr)->NodeNum <= BarrierChain->NodeNum)
670 (*SUItr)->addPredBarrier(BarrierChain);
673 // Remove also the BarrierChain from list if present.
674 if (SUItr != SUEE && *SUItr == BarrierChain)
677 // Remove all SUs that are now successors of BarrierChain.
678 if (SUItr != sus.begin())
679 sus.erase(sus.begin(), SUItr);
682 // Remove all entries with empty su lists.
683 map.remove_if([&](std::pair<ValueType, SUList> &mapEntry) {
684 return (mapEntry.second.empty()); });
686 // Recompute the size of the map (NumNodes).
690 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
691 RegPressureTracker *RPTracker,
692 PressureDiffs *PDiffs,
694 bool TrackLaneMasks) {
695 const TargetSubtargetInfo &ST = MF.getSubtarget();
696 bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
698 AAForDep = UseAA ? AA : nullptr;
700 BarrierChain = nullptr;
702 this->TrackLaneMasks = TrackLaneMasks;
704 ScheduleDAG::clearDAG();
706 // Create an SUnit for each real instruction.
710 PDiffs->init(SUnits.size());
712 // We build scheduling units by walking a block's instruction list
713 // from bottom to top.
715 // Each MIs' memory operand(s) is analyzed to a list of underlying
716 // objects. The SU is then inserted in the SUList(s) mapped from the
717 // Value(s). Each Value thus gets mapped to lists of SUs depending
718 // on it, stores and loads kept separately. Two SUs are trivially
719 // non-aliasing if they both depend on only identified Values and do
720 // not share any common Value.
721 Value2SUsMap Stores, Loads(1 /*TrueMemOrderLatency*/);
723 // Certain memory accesses are known to not alias any SU in Stores
724 // or Loads, and have therefore their own 'NonAlias'
725 // domain. E.g. spill / reload instructions never alias LLVM I/R
726 // Values. It would be nice to assume that this type of memory
727 // accesses always have a proper memory operand modelling, and are
728 // therefore never unanalyzable, but this is conservatively not
730 Value2SUsMap NonAliasStores, NonAliasLoads(1 /*TrueMemOrderLatency*/);
732 // Remove any stale debug info; sometimes BuildSchedGraph is called again
733 // without emitting the info from the previous call.
735 FirstDbgValue = nullptr;
737 assert(Defs.empty() && Uses.empty() &&
738 "Only BuildGraph should update Defs/Uses");
739 Defs.setUniverse(TRI->getNumRegs());
740 Uses.setUniverse(TRI->getNumRegs());
742 assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
743 assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
744 unsigned NumVirtRegs = MRI.getNumVirtRegs();
745 CurrentVRegDefs.setUniverse(NumVirtRegs);
746 CurrentVRegUses.setUniverse(NumVirtRegs);
748 // Model data dependencies between instructions being scheduled and the
750 addSchedBarrierDeps();
752 // Walk the list of instructions, from bottom moving up.
753 MachineInstr *DbgMI = nullptr;
754 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
756 MachineInstr &MI = *std::prev(MII);
758 DbgValues.push_back(std::make_pair(DbgMI, &MI));
762 if (MI.isDebugValue()) {
766 SUnit *SU = MISUnitMap[&MI];
767 assert(SU && "No SUnit mapped to this MI");
770 RegisterOperands RegOpers;
771 RegOpers.collect(MI, *TRI, MRI, TrackLaneMasks, false);
772 if (TrackLaneMasks) {
773 SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
774 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx);
776 if (PDiffs != nullptr)
777 PDiffs->addInstruction(SU->NodeNum, RegOpers, MRI);
779 if (RPTracker->getPos() == RegionEnd || &*RPTracker->getPos() != &MI)
780 RPTracker->recedeSkipDebugValues();
781 assert(&*RPTracker->getPos() == &MI && "RPTracker in sync");
782 RPTracker->recede(RegOpers);
786 (CanHandleTerminators || (!MI.isTerminator() && !MI.isPosition())) &&
787 "Cannot schedule terminators or labels!");
789 // Add register-based dependencies (data, anti, and output).
790 // For some instructions (calls, returns, inline-asm, etc.) there can
791 // be explicit uses and implicit defs, in which case the use will appear
792 // on the operand list before the def. Do two passes over the operand
793 // list to make sure that defs are processed before any uses.
794 bool HasVRegDef = false;
795 for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
796 const MachineOperand &MO = MI.getOperand(j);
797 if (!MO.isReg() || !MO.isDef())
799 unsigned Reg = MO.getReg();
800 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
801 addPhysRegDeps(SU, j);
802 } else if (TargetRegisterInfo::isVirtualRegister(Reg)) {
804 addVRegDefDeps(SU, j);
807 // Now process all uses.
808 for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
809 const MachineOperand &MO = MI.getOperand(j);
810 // Only look at use operands.
811 // We do not need to check for MO.readsReg() here because subsequent
812 // subregister defs will get output dependence edges and need no
813 // additional use dependencies.
814 if (!MO.isReg() || !MO.isUse())
816 unsigned Reg = MO.getReg();
817 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
818 addPhysRegDeps(SU, j);
819 } else if (TargetRegisterInfo::isVirtualRegister(Reg) && MO.readsReg()) {
820 addVRegUseDeps(SU, j);
824 // If we haven't seen any uses in this scheduling region, create a
825 // dependence edge to ExitSU to model the live-out latency. This is required
826 // for vreg defs with no in-region use, and prefetches with no vreg def.
828 // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
829 // check currently relies on being called before adding chain deps.
830 if (SU->NumSuccs == 0 && SU->Latency > 1 && (HasVRegDef || MI.mayLoad())) {
831 SDep Dep(SU, SDep::Artificial);
832 Dep.setLatency(SU->Latency - 1);
836 // Add memory dependencies (Note: isStoreToStackSlot and
837 // isLoadFromStackSLot are not usable after stack slots are lowered to
838 // actual addresses).
840 // This is a barrier event that acts as a pivotal node in the DAG.
841 if (isGlobalMemoryObject(AA, &MI)) {
843 // Become the barrier chain.
845 BarrierChain->addPredBarrier(SU);
848 DEBUG(dbgs() << "Global memory object and new barrier chain: SU("
849 << BarrierChain->NodeNum << ").\n";);
851 // Add dependencies against everything below it and clear maps.
852 addBarrierChain(Stores);
853 addBarrierChain(Loads);
854 addBarrierChain(NonAliasStores);
855 addBarrierChain(NonAliasLoads);
860 // If it's not a store or a variant load, we're done.
861 if (!MI.mayStore() &&
862 !(MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA)))
865 // Always add dependecy edge to BarrierChain if present.
867 BarrierChain->addPredBarrier(SU);
869 // Find the underlying objects for MI. The Objs vector is either
870 // empty, or filled with the Values of memory locations which this
872 UnderlyingObjectsVector Objs;
873 bool ObjsFound = getUnderlyingObjectsForInstr(&MI, MFI, Objs,
878 // An unknown store depends on all stores and loads.
879 addChainDependencies(SU, Stores);
880 addChainDependencies(SU, NonAliasStores);
881 addChainDependencies(SU, Loads);
882 addChainDependencies(SU, NonAliasLoads);
884 // Map this store to 'UnknownValue'.
885 Stores.insert(SU, UnknownValue);
887 // Add precise dependencies against all previously seen memory
888 // accesses mapped to the same Value(s).
889 for (const UnderlyingObject &UnderlObj : Objs) {
890 ValueType V = UnderlObj.getValue();
891 bool ThisMayAlias = UnderlObj.mayAlias();
893 // Add dependencies to previous stores and loads mapped to V.
894 addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
895 addChainDependencies(SU, (ThisMayAlias ? Loads : NonAliasLoads), V);
897 // Update the store map after all chains have been added to avoid adding
898 // self-loop edge if multiple underlying objects are present.
899 for (const UnderlyingObject &UnderlObj : Objs) {
900 ValueType V = UnderlObj.getValue();
901 bool ThisMayAlias = UnderlObj.mayAlias();
903 // Map this store to V.
904 (ThisMayAlias ? Stores : NonAliasStores).insert(SU, V);
906 // The store may have dependencies to unanalyzable loads and
908 addChainDependencies(SU, Loads, UnknownValue);
909 addChainDependencies(SU, Stores, UnknownValue);
911 } else { // SU is a load.
913 // An unknown load depends on all stores.
914 addChainDependencies(SU, Stores);
915 addChainDependencies(SU, NonAliasStores);
917 Loads.insert(SU, UnknownValue);
919 for (const UnderlyingObject &UnderlObj : Objs) {
920 ValueType V = UnderlObj.getValue();
921 bool ThisMayAlias = UnderlObj.mayAlias();
923 // Add precise dependencies against all previously seen stores
924 // mapping to the same Value(s).
925 addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
927 // Map this load to V.
928 (ThisMayAlias ? Loads : NonAliasLoads).insert(SU, V);
930 // The load may have dependencies to unanalyzable stores.
931 addChainDependencies(SU, Stores, UnknownValue);
935 // Reduce maps if they grow huge.
936 if (Stores.size() + Loads.size() >= HugeRegion) {
937 DEBUG(dbgs() << "Reducing Stores and Loads maps.\n";);
938 reduceHugeMemNodeMaps(Stores, Loads, getReductionSize());
940 if (NonAliasStores.size() + NonAliasLoads.size() >= HugeRegion) {
941 DEBUG(dbgs() << "Reducing NonAliasStores and NonAliasLoads maps.\n";);
942 reduceHugeMemNodeMaps(NonAliasStores, NonAliasLoads, getReductionSize());
947 FirstDbgValue = DbgMI;
951 CurrentVRegDefs.clear();
952 CurrentVRegUses.clear();
955 raw_ostream &llvm::operator<<(raw_ostream &OS, const PseudoSourceValue* PSV) {
956 PSV->printCustom(OS);
960 void ScheduleDAGInstrs::Value2SUsMap::dump() {
961 for (auto &Itr : *this) {
962 if (Itr.first.is<const Value*>()) {
963 const Value *V = Itr.first.get<const Value*>();
964 if (isa<UndefValue>(V))
967 V->printAsOperand(dbgs());
969 else if (Itr.first.is<const PseudoSourceValue*>())
970 dbgs() << Itr.first.get<const PseudoSourceValue*>();
972 llvm_unreachable("Unknown Value type.");
975 dumpSUList(Itr.second);
979 void ScheduleDAGInstrs::reduceHugeMemNodeMaps(Value2SUsMap &stores,
980 Value2SUsMap &loads, unsigned N) {
981 DEBUG(dbgs() << "Before reduction:\nStoring SUnits:\n";
983 dbgs() << "Loading SUnits:\n";
986 // Insert all SU's NodeNums into a vector and sort it.
987 std::vector<unsigned> NodeNums;
988 NodeNums.reserve(stores.size() + loads.size());
989 for (auto &I : stores)
990 for (auto *SU : I.second)
991 NodeNums.push_back(SU->NodeNum);
992 for (auto &I : loads)
993 for (auto *SU : I.second)
994 NodeNums.push_back(SU->NodeNum);
995 std::sort(NodeNums.begin(), NodeNums.end());
997 // The N last elements in NodeNums will be removed, and the SU with
998 // the lowest NodeNum of them will become the new BarrierChain to
999 // let the not yet seen SUs have a dependency to the removed SUs.
1000 assert(N <= NodeNums.size());
1001 SUnit *newBarrierChain = &SUnits[*(NodeNums.end() - N)];
1003 // The aliasing and non-aliasing maps reduce independently of each
1004 // other, but share a common BarrierChain. Check if the
1005 // newBarrierChain is above the former one. If it is not, it may
1006 // introduce a loop to use newBarrierChain, so keep the old one.
1007 if (newBarrierChain->NodeNum < BarrierChain->NodeNum) {
1008 BarrierChain->addPredBarrier(newBarrierChain);
1009 BarrierChain = newBarrierChain;
1010 DEBUG(dbgs() << "Inserting new barrier chain: SU("
1011 << BarrierChain->NodeNum << ").\n";);
1014 DEBUG(dbgs() << "Keeping old barrier chain: SU("
1015 << BarrierChain->NodeNum << ").\n";);
1018 BarrierChain = newBarrierChain;
1020 insertBarrierChain(stores);
1021 insertBarrierChain(loads);
1023 DEBUG(dbgs() << "After reduction:\nStoring SUnits:\n";
1025 dbgs() << "Loading SUnits:\n";
1029 static void toggleKills(const MachineRegisterInfo &MRI, LivePhysRegs &LiveRegs,
1030 MachineInstr &MI, bool addToLiveRegs) {
1031 for (MachineOperand &MO : MI.operands()) {
1032 if (!MO.isReg() || !MO.readsReg())
1034 unsigned Reg = MO.getReg();
1038 // Things that are available after the instruction are killed by it.
1039 bool IsKill = LiveRegs.available(MRI, Reg);
1040 MO.setIsKill(IsKill);
1042 LiveRegs.addReg(Reg);
1046 void ScheduleDAGInstrs::fixupKills(MachineBasicBlock &MBB) {
1047 DEBUG(dbgs() << "Fixup kills for " << printMBBReference(MBB) << '\n');
1049 LiveRegs.init(*TRI);
1050 LiveRegs.addLiveOuts(MBB);
1052 // Examine block from end to start...
1053 for (MachineInstr &MI : make_range(MBB.rbegin(), MBB.rend())) {
1054 if (MI.isDebugValue())
1057 // Update liveness. Registers that are defed but not used in this
1058 // instruction are now dead. Mark register and all subregs as they
1059 // are completely defined.
1060 for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
1061 const MachineOperand &MO = *O;
1065 unsigned Reg = MO.getReg();
1068 LiveRegs.removeReg(Reg);
1069 } else if (MO.isRegMask()) {
1070 LiveRegs.removeRegsInMask(MO);
1074 // If there is a bundle header fix it up first.
1075 if (!MI.isBundled()) {
1076 toggleKills(MRI, LiveRegs, MI, true);
1078 MachineBasicBlock::instr_iterator First = MI.getIterator();
1079 if (MI.isBundle()) {
1080 toggleKills(MRI, LiveRegs, MI, false);
1083 // Some targets make the (questionable) assumtion that the instructions
1084 // inside the bundle are ordered and consequently only the last use of
1085 // a register inside the bundle can kill it.
1086 MachineBasicBlock::instr_iterator I = std::next(First);
1087 while (I->isBundledWithSucc())
1090 if (!I->isDebugValue())
1091 toggleKills(MRI, LiveRegs, *I, true);
1093 } while(I != First);
1098 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
1099 // Cannot completely remove virtual function even in release mode.
1100 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1101 SU->getInstr()->dump();
1105 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1107 raw_string_ostream oss(s);
1110 else if (SU == &ExitSU)
1113 SU->getInstr()->print(oss, /*SkipOpers=*/true);
1117 /// Return the basic block label. It is not necessarilly unique because a block
1118 /// contains multiple scheduling regions. But it is fine for visualization.
1119 std::string ScheduleDAGInstrs::getDAGName() const {
1120 return "dag." + BB->getFullName();
1123 //===----------------------------------------------------------------------===//
1124 // SchedDFSResult Implementation
1125 //===----------------------------------------------------------------------===//
1129 /// Internal state used to compute SchedDFSResult.
1130 class SchedDFSImpl {
1133 /// Join DAG nodes into equivalence classes by their subtree.
1134 IntEqClasses SubtreeClasses;
1135 /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1136 std::vector<std::pair<const SUnit *, const SUnit*>> ConnectionPairs;
1140 unsigned ParentNodeID; ///< Parent node (member of the parent subtree).
1141 unsigned SubInstrCount = 0; ///< Instr count in this tree only, not
1144 RootData(unsigned id): NodeID(id),
1145 ParentNodeID(SchedDFSResult::InvalidSubtreeID) {}
1147 unsigned getSparseSetIndex() const { return NodeID; }
1150 SparseSet<RootData> RootSet;
1153 SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1154 RootSet.setUniverse(R.DFSNodeData.size());
1157 /// Returns true if this node been visited by the DFS traversal.
1159 /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1160 /// ID. Later, SubtreeID is updated but remains valid.
1161 bool isVisited(const SUnit *SU) const {
1162 return R.DFSNodeData[SU->NodeNum].SubtreeID
1163 != SchedDFSResult::InvalidSubtreeID;
1166 /// Initializes this node's instruction count. We don't need to flag the node
1167 /// visited until visitPostorder because the DAG cannot have cycles.
1168 void visitPreorder(const SUnit *SU) {
1169 R.DFSNodeData[SU->NodeNum].InstrCount =
1170 SU->getInstr()->isTransient() ? 0 : 1;
1173 /// Called once for each node after all predecessors are visited. Revisit this
1174 /// node's predecessors and potentially join them now that we know the ILP of
1175 /// the other predecessors.
1176 void visitPostorderNode(const SUnit *SU) {
1177 // Mark this node as the root of a subtree. It may be joined with its
1178 // successors later.
1179 R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1180 RootData RData(SU->NodeNum);
1181 RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
1183 // If any predecessors are still in their own subtree, they either cannot be
1184 // joined or are large enough to remain separate. If this parent node's
1185 // total instruction count is not greater than a child subtree by at least
1186 // the subtree limit, then try to join it now since splitting subtrees is
1187 // only useful if multiple high-pressure paths are possible.
1188 unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
1189 for (const SDep &PredDep : SU->Preds) {
1190 if (PredDep.getKind() != SDep::Data)
1192 unsigned PredNum = PredDep.getSUnit()->NodeNum;
1193 if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
1194 joinPredSubtree(PredDep, SU, /*CheckLimit=*/false);
1196 // Either link or merge the TreeData entry from the child to the parent.
1197 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1198 // If the predecessor's parent is invalid, this is a tree edge and the
1199 // current node is the parent.
1200 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1201 RootSet[PredNum].ParentNodeID = SU->NodeNum;
1203 else if (RootSet.count(PredNum)) {
1204 // The predecessor is not a root, but is still in the root set. This
1205 // must be the new parent that it was just joined to. Note that
1206 // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1207 // set to the original parent.
1208 RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1209 RootSet.erase(PredNum);
1212 RootSet[SU->NodeNum] = RData;
1215 /// \brief Called once for each tree edge after calling visitPostOrderNode on
1216 /// the predecessor. Increment the parent node's instruction count and
1217 /// preemptively join this subtree to its parent's if it is small enough.
1218 void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1219 R.DFSNodeData[Succ->NodeNum].InstrCount
1220 += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1221 joinPredSubtree(PredDep, Succ);
1224 /// Adds a connection for cross edges.
1225 void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
1226 ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1229 /// Sets each node's subtree ID to the representative ID and record
1230 /// connections between trees.
1232 SubtreeClasses.compress();
1233 R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1234 assert(SubtreeClasses.getNumClasses() == RootSet.size()
1235 && "number of roots should match trees");
1236 for (const RootData &Root : RootSet) {
1237 unsigned TreeID = SubtreeClasses[Root.NodeID];
1238 if (Root.ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1239 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[Root.ParentNodeID];
1240 R.DFSTreeData[TreeID].SubInstrCount = Root.SubInstrCount;
1241 // Note that SubInstrCount may be greater than InstrCount if we joined
1242 // subtrees across a cross edge. InstrCount will be attributed to the
1243 // original parent, while SubInstrCount will be attributed to the joined
1246 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1247 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1248 DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
1249 for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1250 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
1251 DEBUG(dbgs() << " SU(" << Idx << ") in tree "
1252 << R.DFSNodeData[Idx].SubtreeID << '\n');
1254 for (const std::pair<const SUnit*, const SUnit*> &P : ConnectionPairs) {
1255 unsigned PredTree = SubtreeClasses[P.first->NodeNum];
1256 unsigned SuccTree = SubtreeClasses[P.second->NodeNum];
1257 if (PredTree == SuccTree)
1259 unsigned Depth = P.first->getDepth();
1260 addConnection(PredTree, SuccTree, Depth);
1261 addConnection(SuccTree, PredTree, Depth);
1266 /// Joins the predecessor subtree with the successor that is its DFS parent.
1267 /// Applies some heuristics before joining.
1268 bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1269 bool CheckLimit = true) {
1270 assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1272 // Check if the predecessor is already joined.
1273 const SUnit *PredSU = PredDep.getSUnit();
1274 unsigned PredNum = PredSU->NodeNum;
1275 if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
1278 // Four is the magic number of successors before a node is considered a
1280 unsigned NumDataSucs = 0;
1281 for (const SDep &SuccDep : PredSU->Succs) {
1282 if (SuccDep.getKind() == SDep::Data) {
1283 if (++NumDataSucs >= 4)
1287 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
1289 R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
1290 SubtreeClasses.join(Succ->NodeNum, PredNum);
1294 /// Called by finalize() to record a connection between trees.
1295 void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1300 SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1301 R.SubtreeConnections[FromTree];
1302 for (SchedDFSResult::Connection &C : Connections) {
1303 if (C.TreeID == ToTree) {
1304 C.Level = std::max(C.Level, Depth);
1308 Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1309 FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1310 } while (FromTree != SchedDFSResult::InvalidSubtreeID);
1314 } // end namespace llvm
1318 /// Manage the stack used by a reverse depth-first search over the DAG.
1319 class SchedDAGReverseDFS {
1320 std::vector<std::pair<const SUnit *, SUnit::const_pred_iterator>> DFSStack;
1323 bool isComplete() const { return DFSStack.empty(); }
1325 void follow(const SUnit *SU) {
1326 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1328 void advance() { ++DFSStack.back().second; }
1330 const SDep *backtrack() {
1331 DFSStack.pop_back();
1332 return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
1335 const SUnit *getCurr() const { return DFSStack.back().first; }
1337 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1339 SUnit::const_pred_iterator getPredEnd() const {
1340 return getCurr()->Preds.end();
1344 } // end anonymous namespace
1346 static bool hasDataSucc(const SUnit *SU) {
1347 for (const SDep &SuccDep : SU->Succs) {
1348 if (SuccDep.getKind() == SDep::Data &&
1349 !SuccDep.getSUnit()->isBoundaryNode())
1355 /// Computes an ILP metric for all nodes in the subDAG reachable via depth-first
1356 /// search from this root.
1357 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
1359 llvm_unreachable("Top-down ILP metric is unimplemented");
1361 SchedDFSImpl Impl(*this);
1362 for (const SUnit &SU : SUnits) {
1363 if (Impl.isVisited(&SU) || hasDataSucc(&SU))
1366 SchedDAGReverseDFS DFS;
1367 Impl.visitPreorder(&SU);
1370 // Traverse the leftmost path as far as possible.
1371 while (DFS.getPred() != DFS.getPredEnd()) {
1372 const SDep &PredDep = *DFS.getPred();
1374 // Ignore non-data edges.
1375 if (PredDep.getKind() != SDep::Data
1376 || PredDep.getSUnit()->isBoundaryNode()) {
1379 // An already visited edge is a cross edge, assuming an acyclic DAG.
1380 if (Impl.isVisited(PredDep.getSUnit())) {
1381 Impl.visitCrossEdge(PredDep, DFS.getCurr());
1384 Impl.visitPreorder(PredDep.getSUnit());
1385 DFS.follow(PredDep.getSUnit());
1387 // Visit the top of the stack in postorder and backtrack.
1388 const SUnit *Child = DFS.getCurr();
1389 const SDep *PredDep = DFS.backtrack();
1390 Impl.visitPostorderNode(Child);
1392 Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
1393 if (DFS.isComplete())
1400 /// The root of the given SubtreeID was just scheduled. For all subtrees
1401 /// connected to this tree, record the depth of the connection so that the
1402 /// nearest connected subtrees can be prioritized.
1403 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1404 for (const Connection &C : SubtreeConnections[SubtreeID]) {
1405 SubtreeConnectLevels[C.TreeID] =
1406 std::max(SubtreeConnectLevels[C.TreeID], C.Level);
1407 DEBUG(dbgs() << " Tree: " << C.TreeID
1408 << " @" << SubtreeConnectLevels[C.TreeID] << '\n');
1412 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1413 LLVM_DUMP_METHOD void ILPValue::print(raw_ostream &OS) const {
1414 OS << InstrCount << " / " << Length << " = ";
1418 OS << format("%g", ((double)InstrCount / Length));
1421 LLVM_DUMP_METHOD void ILPValue::dump() const {
1422 dbgs() << *this << '\n';
1428 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1433 } // end namespace llvm