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/Config/llvm-config.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/Instruction.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Operator.h"
47 #include "llvm/IR/Type.h"
48 #include "llvm/IR/Value.h"
49 #include "llvm/MC/LaneBitmask.h"
50 #include "llvm/MC/MCRegisterInfo.h"
51 #include "llvm/Support/Casting.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/Format.h"
57 #include "llvm/Support/raw_ostream.h"
67 #define DEBUG_TYPE "machine-scheduler"
69 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
70 cl::ZeroOrMore, cl::init(false),
71 cl::desc("Enable use of AA during MI DAG construction"));
73 static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
74 cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"));
76 // Note: the two options below might be used in tuning compile time vs
77 // output quality. Setting HugeRegion so large that it will never be
78 // reached means best-effort, but may be slow.
80 // When Stores and Loads maps (or NonAliasStores and NonAliasLoads)
81 // together hold this many SUs, a reduction of maps will be done.
82 static cl::opt<unsigned> HugeRegion("dag-maps-huge-region", cl::Hidden,
83 cl::init(1000), cl::desc("The limit to use while constructing the DAG "
84 "prior to scheduling, at which point a trade-off "
85 "is made to avoid excessive compile time."));
87 static cl::opt<unsigned> ReductionSize(
88 "dag-maps-reduction-size", cl::Hidden,
89 cl::desc("A huge scheduling region will have maps reduced by this many "
90 "nodes at a time. Defaults to HugeRegion / 2."));
92 static unsigned getReductionSize() {
93 // Always reduce a huge region with half of the elements, except
94 // when user sets this number explicitly.
95 if (ReductionSize.getNumOccurrences() == 0)
96 return HugeRegion / 2;
100 static void dumpSUList(ScheduleDAGInstrs::SUList &L) {
101 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
103 for (const SUnit *su : L) {
104 dbgs() << "SU(" << su->NodeNum << ")";
112 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
113 const MachineLoopInfo *mli,
114 bool RemoveKillFlags)
115 : ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()),
116 RemoveKillFlags(RemoveKillFlags),
117 UnknownValue(UndefValue::get(
118 Type::getVoidTy(mf.getFunction().getContext()))) {
121 const TargetSubtargetInfo &ST = mf.getSubtarget();
122 SchedModel.init(&ST);
125 /// If this machine instr has memory reference information and it can be
126 /// tracked to a normal reference to a known object, return the Value
127 /// for that object. This function returns false the memory location is
128 /// unknown or may alias anything.
129 static bool getUnderlyingObjectsForInstr(const MachineInstr *MI,
130 const MachineFrameInfo &MFI,
131 UnderlyingObjectsVector &Objects,
132 const DataLayout &DL) {
133 auto allMMOsOkay = [&]() {
134 for (const MachineMemOperand *MMO : MI->memoperands()) {
135 if (MMO->isVolatile())
138 if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) {
139 // Function that contain tail calls don't have unique PseudoSourceValue
140 // objects. Two PseudoSourceValues might refer to the same or
141 // overlapping locations. The client code calling this function assumes
142 // this is not the case. So return a conservative answer of no known
144 if (MFI.hasTailCall())
147 // For now, ignore PseudoSourceValues which may alias LLVM IR values
148 // because the code that uses this function has no way to cope with
150 if (PSV->isAliased(&MFI))
153 bool MayAlias = PSV->mayAlias(&MFI);
154 Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
155 } else if (const Value *V = MMO->getValue()) {
156 SmallVector<Value *, 4> Objs;
157 if (!getUnderlyingObjectsForCodeGen(V, Objs, DL))
160 for (Value *V : Objs) {
161 assert(isIdentifiedObject(V));
162 Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
170 if (!allMMOsOkay()) {
178 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
182 void ScheduleDAGInstrs::finishBlock() {
183 // Subclasses should no longer refer to the old block.
187 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
188 MachineBasicBlock::iterator begin,
189 MachineBasicBlock::iterator end,
190 unsigned regioninstrs) {
191 assert(bb == BB && "startBlock should set BB");
194 NumRegionInstrs = regioninstrs;
197 void ScheduleDAGInstrs::exitRegion() {
201 void ScheduleDAGInstrs::addSchedBarrierDeps() {
202 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr;
203 ExitSU.setInstr(ExitMI);
204 // Add dependencies on the defs and uses of the instruction.
206 for (const MachineOperand &MO : ExitMI->operands()) {
207 if (!MO.isReg() || MO.isDef()) continue;
208 unsigned Reg = MO.getReg();
209 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
210 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
211 } else if (TargetRegisterInfo::isVirtualRegister(Reg) && MO.readsReg()) {
212 addVRegUseDeps(&ExitSU, ExitMI->getOperandNo(&MO));
216 if (!ExitMI || (!ExitMI->isCall() && !ExitMI->isBarrier())) {
217 // For others, e.g. fallthrough, conditional branch, assume the exit
218 // uses all the registers that are livein to the successor blocks.
219 for (const MachineBasicBlock *Succ : BB->successors()) {
220 for (const auto &LI : Succ->liveins()) {
221 if (!Uses.contains(LI.PhysReg))
222 Uses.insert(PhysRegSUOper(&ExitSU, -1, LI.PhysReg));
228 /// MO is an operand of SU's instruction that defines a physical register. Adds
229 /// data dependencies from SU to any uses of the physical register.
230 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
231 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
232 assert(MO.isDef() && "expect physreg def");
234 // Ask the target if address-backscheduling is desirable, and if so how much.
235 const TargetSubtargetInfo &ST = MF.getSubtarget();
237 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
238 Alias.isValid(); ++Alias) {
239 if (!Uses.contains(*Alias))
241 for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
242 SUnit *UseSU = I->SU;
246 // Adjust the dependence latency using operand def/use information,
247 // then allow the target to perform its own adjustments.
248 int UseOp = I->OpIdx;
249 MachineInstr *RegUse = nullptr;
252 Dep = SDep(SU, SDep::Artificial);
254 // Set the hasPhysRegDefs only for physreg defs that have a use within
255 // the scheduling region.
256 SU->hasPhysRegDefs = true;
257 Dep = SDep(SU, SDep::Data, *Alias);
258 RegUse = UseSU->getInstr();
261 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
264 ST.adjustSchedDependency(SU, UseSU, Dep);
270 /// Adds register dependencies (data, anti, and output) from this SUnit
271 /// to following instructions in the same scheduling region that depend the
272 /// physical register referenced at OperIdx.
273 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
274 MachineInstr *MI = SU->getInstr();
275 MachineOperand &MO = MI->getOperand(OperIdx);
276 unsigned Reg = MO.getReg();
277 // We do not need to track any dependencies for constant registers.
278 if (MRI.isConstantPhysReg(Reg))
281 // Optionally add output and anti dependencies. For anti
282 // dependencies we use a latency of 0 because for a multi-issue
283 // target we want to allow the defining instruction to issue
284 // in the same cycle as the using instruction.
285 // TODO: Using a latency of 1 here for output dependencies assumes
286 // there's no cost for reusing registers.
287 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
288 for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
289 if (!Defs.contains(*Alias))
291 for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
292 SUnit *DefSU = I->SU;
293 if (DefSU == &ExitSU)
296 (Kind != SDep::Output || !MO.isDead() ||
297 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
298 if (Kind == SDep::Anti)
299 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
301 SDep Dep(SU, Kind, /*Reg=*/*Alias);
303 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
311 SU->hasPhysRegUses = true;
312 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
313 // retrieve the existing SUnits list for this register's uses.
314 // Push this SUnit on the use list.
315 Uses.insert(PhysRegSUOper(SU, OperIdx, Reg));
319 addPhysRegDataDeps(SU, OperIdx);
321 // Clear previous uses and defs of this register and its subergisters.
322 for (MCSubRegIterator SubReg(Reg, TRI, true); SubReg.isValid(); ++SubReg) {
323 if (Uses.contains(*SubReg))
324 Uses.eraseAll(*SubReg);
326 Defs.eraseAll(*SubReg);
328 if (MO.isDead() && SU->isCall) {
329 // Calls will not be reordered because of chain dependencies (see
330 // below). Since call operands are dead, calls may continue to be added
331 // to the DefList making dependence checking quadratic in the size of
332 // the block. Instead, we leave only one call at the back of the
334 Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
335 Reg2SUnitsMap::iterator B = P.first;
336 Reg2SUnitsMap::iterator I = P.second;
337 for (bool isBegin = I == B; !isBegin; /* empty */) {
338 isBegin = (--I) == B;
345 // Defs are pushed in the order they are visited and never reordered.
346 Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
350 LaneBitmask ScheduleDAGInstrs::getLaneMaskForMO(const MachineOperand &MO) const
352 unsigned Reg = MO.getReg();
353 // No point in tracking lanemasks if we don't have interesting subregisters.
354 const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
355 if (!RC.HasDisjunctSubRegs)
356 return LaneBitmask::getAll();
358 unsigned SubReg = MO.getSubReg();
360 return RC.getLaneMask();
361 return TRI->getSubRegIndexLaneMask(SubReg);
364 /// Adds register output and data dependencies from this SUnit to instructions
365 /// that occur later in the same scheduling region if they read from or write to
366 /// the virtual register defined at OperIdx.
368 /// TODO: Hoist loop induction variable increments. This has to be
369 /// reevaluated. Generally, IV scheduling should be done before coalescing.
370 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
371 MachineInstr *MI = SU->getInstr();
372 MachineOperand &MO = MI->getOperand(OperIdx);
373 unsigned Reg = MO.getReg();
375 LaneBitmask DefLaneMask;
376 LaneBitmask KillLaneMask;
377 if (TrackLaneMasks) {
378 bool IsKill = MO.getSubReg() == 0 || MO.isUndef();
379 DefLaneMask = getLaneMaskForMO(MO);
380 // If we have a <read-undef> flag, none of the lane values comes from an
381 // earlier instruction.
382 KillLaneMask = IsKill ? LaneBitmask::getAll() : DefLaneMask;
384 // Clear undef flag, we'll re-add it later once we know which subregister
386 MO.setIsUndef(false);
388 DefLaneMask = LaneBitmask::getAll();
389 KillLaneMask = LaneBitmask::getAll();
393 assert(CurrentVRegUses.find(Reg) == CurrentVRegUses.end() &&
394 "Dead defs should have no uses");
396 // Add data dependence to all uses we found so far.
397 const TargetSubtargetInfo &ST = MF.getSubtarget();
398 for (VReg2SUnitOperIdxMultiMap::iterator I = CurrentVRegUses.find(Reg),
399 E = CurrentVRegUses.end(); I != E; /*empty*/) {
400 LaneBitmask LaneMask = I->LaneMask;
401 // Ignore uses of other lanes.
402 if ((LaneMask & KillLaneMask).none()) {
407 if ((LaneMask & DefLaneMask).any()) {
408 SUnit *UseSU = I->SU;
409 MachineInstr *Use = UseSU->getInstr();
410 SDep Dep(SU, SDep::Data, Reg);
411 Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use,
413 ST.adjustSchedDependency(SU, UseSU, Dep);
417 LaneMask &= ~KillLaneMask;
418 // If we found a Def for all lanes of this use, remove it from the list.
419 if (LaneMask.any()) {
420 I->LaneMask = LaneMask;
423 I = CurrentVRegUses.erase(I);
427 // Shortcut: Singly defined vregs do not have output/anti dependencies.
428 if (MRI.hasOneDef(Reg))
431 // Add output dependence to the next nearest defs of this vreg.
433 // Unless this definition is dead, the output dependence should be
434 // transitively redundant with antidependencies from this definition's
435 // uses. We're conservative for now until we have a way to guarantee the uses
436 // are not eliminated sometime during scheduling. The output dependence edge
437 // is also useful if output latency exceeds def-use latency.
438 LaneBitmask LaneMask = DefLaneMask;
439 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
440 CurrentVRegDefs.end())) {
441 // Ignore defs for other lanes.
442 if ((V2SU.LaneMask & LaneMask).none())
444 // Add an output dependence.
445 SUnit *DefSU = V2SU.SU;
446 // Ignore additional defs of the same lanes in one instruction. This can
447 // happen because lanemasks are shared for targets with too many
448 // subregisters. We also use some representration tricks/hacks where we
449 // add super-register defs/uses, to imply that although we only access parts
450 // of the reg we care about the full one.
453 SDep Dep(SU, SDep::Output, Reg);
455 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
458 // Update current definition. This can get tricky if the def was about a
459 // bigger lanemask before. We then have to shrink it and create a new
460 // VReg2SUnit for the non-overlapping part.
461 LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
462 LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
464 V2SU.LaneMask = OverlapMask;
465 if (NonOverlapMask.any())
466 CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, DefSU));
468 // If there was no CurrentVRegDefs entry for some lanes yet, create one.
470 CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU));
473 /// Adds a register data dependency if the instruction that defines the
474 /// virtual register used at OperIdx is mapped to an SUnit. Add a register
475 /// antidependency from this SUnit to instructions that occur later in the same
476 /// scheduling region if they write the virtual register.
478 /// TODO: Handle ExitSU "uses" properly.
479 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
480 const MachineInstr *MI = SU->getInstr();
481 const MachineOperand &MO = MI->getOperand(OperIdx);
482 unsigned Reg = MO.getReg();
484 // Remember the use. Data dependencies will be added when we find the def.
485 LaneBitmask LaneMask = TrackLaneMasks ? getLaneMaskForMO(MO)
486 : LaneBitmask::getAll();
487 CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU));
489 // Add antidependences to the following defs of the vreg.
490 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
491 CurrentVRegDefs.end())) {
492 // Ignore defs for unrelated lanes.
493 LaneBitmask PrevDefLaneMask = V2SU.LaneMask;
494 if ((PrevDefLaneMask & LaneMask).none())
499 V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg));
503 /// Returns true if MI is an instruction we are unable to reason about
504 /// (like a call or something with unmodeled side effects).
505 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
506 return MI->isCall() || MI->hasUnmodeledSideEffects() ||
507 (MI->hasOrderedMemoryRef() && !MI->isDereferenceableInvariantLoad(AA));
510 void ScheduleDAGInstrs::addChainDependency (SUnit *SUa, SUnit *SUb,
512 if (SUa->getInstr()->mayAlias(AAForDep, *SUb->getInstr(), UseTBAA)) {
513 SDep Dep(SUa, SDep::MayAliasMem);
514 Dep.setLatency(Latency);
519 /// Creates an SUnit for each real instruction, numbered in top-down
520 /// topological order. The instruction order A < B, implies that no edge exists
523 /// Map each real instruction to its SUnit.
525 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
526 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
527 /// instead of pointers.
529 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
530 /// the original instruction list.
531 void ScheduleDAGInstrs::initSUnits() {
532 // We'll be allocating one SUnit for each real instruction in the region,
533 // which is contained within a basic block.
534 SUnits.reserve(NumRegionInstrs);
536 for (MachineInstr &MI : make_range(RegionBegin, RegionEnd)) {
537 if (MI.isDebugInstr())
540 SUnit *SU = newSUnit(&MI);
541 MISUnitMap[&MI] = SU;
543 SU->isCall = MI.isCall();
544 SU->isCommutable = MI.isCommutable();
546 // Assign the Latency field of SU using target-provided information.
547 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
549 // If this SUnit uses a reserved or unbuffered resource, mark it as such.
551 // Reserved resources block an instruction from issuing and stall the
552 // entire pipeline. These are identified by BufferSize=0.
554 // Unbuffered resources prevent execution of subsequent instructions that
555 // require the same resources. This is used for in-order execution pipelines
556 // within an out-of-order core. These are identified by BufferSize=1.
557 if (SchedModel.hasInstrSchedModel()) {
558 const MCSchedClassDesc *SC = getSchedClass(SU);
559 for (const MCWriteProcResEntry &PRE :
560 make_range(SchedModel.getWriteProcResBegin(SC),
561 SchedModel.getWriteProcResEnd(SC))) {
562 switch (SchedModel.getProcResource(PRE.ProcResourceIdx)->BufferSize) {
564 SU->hasReservedResource = true;
567 SU->isUnbuffered = true;
577 class ScheduleDAGInstrs::Value2SUsMap : public MapVector<ValueType, SUList> {
578 /// Current total number of SUs in map.
579 unsigned NumNodes = 0;
581 /// 1 for loads, 0 for stores. (see comment in SUList)
582 unsigned TrueMemOrderLatency;
585 Value2SUsMap(unsigned lat = 0) : TrueMemOrderLatency(lat) {}
587 /// To keep NumNodes up to date, insert() is used instead of
588 /// this operator w/ push_back().
589 ValueType &operator[](const SUList &Key) {
590 llvm_unreachable("Don't use. Use insert() instead."); };
592 /// Adds SU to the SUList of V. If Map grows huge, reduce its size by calling
594 void inline insert(SUnit *SU, ValueType V) {
595 MapVector::operator[](V).push_back(SU);
599 /// Clears the list of SUs mapped to V.
600 void inline clearList(ValueType V) {
601 iterator Itr = find(V);
603 assert(NumNodes >= Itr->second.size());
604 NumNodes -= Itr->second.size();
610 /// Clears map from all contents.
612 MapVector<ValueType, SUList>::clear();
616 unsigned inline size() const { return NumNodes; }
618 /// Counts the number of SUs in this map after a reduction.
619 void reComputeSize() {
621 for (auto &I : *this)
622 NumNodes += I.second.size();
625 unsigned inline getTrueMemOrderLatency() const {
626 return TrueMemOrderLatency;
632 void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
633 Value2SUsMap &Val2SUsMap) {
634 for (auto &I : Val2SUsMap)
635 addChainDependencies(SU, I.second,
636 Val2SUsMap.getTrueMemOrderLatency());
639 void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
640 Value2SUsMap &Val2SUsMap,
642 Value2SUsMap::iterator Itr = Val2SUsMap.find(V);
643 if (Itr != Val2SUsMap.end())
644 addChainDependencies(SU, Itr->second,
645 Val2SUsMap.getTrueMemOrderLatency());
648 void ScheduleDAGInstrs::addBarrierChain(Value2SUsMap &map) {
649 assert(BarrierChain != nullptr);
651 for (auto &I : map) {
652 SUList &sus = I.second;
654 SU->addPredBarrier(BarrierChain);
659 void ScheduleDAGInstrs::insertBarrierChain(Value2SUsMap &map) {
660 assert(BarrierChain != nullptr);
662 // Go through all lists of SUs.
663 for (Value2SUsMap::iterator I = map.begin(), EE = map.end(); I != EE;) {
664 Value2SUsMap::iterator CurrItr = I++;
665 SUList &sus = CurrItr->second;
666 SUList::iterator SUItr = sus.begin(), SUEE = sus.end();
667 for (; SUItr != SUEE; ++SUItr) {
668 // Stop on BarrierChain or any instruction above it.
669 if ((*SUItr)->NodeNum <= BarrierChain->NodeNum)
672 (*SUItr)->addPredBarrier(BarrierChain);
675 // Remove also the BarrierChain from list if present.
676 if (SUItr != SUEE && *SUItr == BarrierChain)
679 // Remove all SUs that are now successors of BarrierChain.
680 if (SUItr != sus.begin())
681 sus.erase(sus.begin(), SUItr);
684 // Remove all entries with empty su lists.
685 map.remove_if([&](std::pair<ValueType, SUList> &mapEntry) {
686 return (mapEntry.second.empty()); });
688 // Recompute the size of the map (NumNodes).
692 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
693 RegPressureTracker *RPTracker,
694 PressureDiffs *PDiffs,
696 bool TrackLaneMasks) {
697 const TargetSubtargetInfo &ST = MF.getSubtarget();
698 bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
700 AAForDep = UseAA ? AA : nullptr;
702 BarrierChain = nullptr;
704 this->TrackLaneMasks = TrackLaneMasks;
706 ScheduleDAG::clearDAG();
708 // Create an SUnit for each real instruction.
712 PDiffs->init(SUnits.size());
714 // We build scheduling units by walking a block's instruction list
715 // from bottom to top.
717 // Each MIs' memory operand(s) is analyzed to a list of underlying
718 // objects. The SU is then inserted in the SUList(s) mapped from the
719 // Value(s). Each Value thus gets mapped to lists of SUs depending
720 // on it, stores and loads kept separately. Two SUs are trivially
721 // non-aliasing if they both depend on only identified Values and do
722 // not share any common Value.
723 Value2SUsMap Stores, Loads(1 /*TrueMemOrderLatency*/);
725 // Certain memory accesses are known to not alias any SU in Stores
726 // or Loads, and have therefore their own 'NonAlias'
727 // domain. E.g. spill / reload instructions never alias LLVM I/R
728 // Values. It would be nice to assume that this type of memory
729 // accesses always have a proper memory operand modelling, and are
730 // therefore never unanalyzable, but this is conservatively not
732 Value2SUsMap NonAliasStores, NonAliasLoads(1 /*TrueMemOrderLatency*/);
734 // Remove any stale debug info; sometimes BuildSchedGraph is called again
735 // without emitting the info from the previous call.
737 FirstDbgValue = nullptr;
739 assert(Defs.empty() && Uses.empty() &&
740 "Only BuildGraph should update Defs/Uses");
741 Defs.setUniverse(TRI->getNumRegs());
742 Uses.setUniverse(TRI->getNumRegs());
744 assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
745 assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
746 unsigned NumVirtRegs = MRI.getNumVirtRegs();
747 CurrentVRegDefs.setUniverse(NumVirtRegs);
748 CurrentVRegUses.setUniverse(NumVirtRegs);
750 // Model data dependencies between instructions being scheduled and the
752 addSchedBarrierDeps();
754 // Walk the list of instructions, from bottom moving up.
755 MachineInstr *DbgMI = nullptr;
756 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
758 MachineInstr &MI = *std::prev(MII);
760 DbgValues.push_back(std::make_pair(DbgMI, &MI));
764 if (MI.isDebugValue()) {
768 if (MI.isDebugLabel())
771 SUnit *SU = MISUnitMap[&MI];
772 assert(SU && "No SUnit mapped to this MI");
775 RegisterOperands RegOpers;
776 RegOpers.collect(MI, *TRI, MRI, TrackLaneMasks, false);
777 if (TrackLaneMasks) {
778 SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
779 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx);
781 if (PDiffs != nullptr)
782 PDiffs->addInstruction(SU->NodeNum, RegOpers, MRI);
784 if (RPTracker->getPos() == RegionEnd || &*RPTracker->getPos() != &MI)
785 RPTracker->recedeSkipDebugValues();
786 assert(&*RPTracker->getPos() == &MI && "RPTracker in sync");
787 RPTracker->recede(RegOpers);
791 (CanHandleTerminators || (!MI.isTerminator() && !MI.isPosition())) &&
792 "Cannot schedule terminators or labels!");
794 // Add register-based dependencies (data, anti, and output).
795 // For some instructions (calls, returns, inline-asm, etc.) there can
796 // be explicit uses and implicit defs, in which case the use will appear
797 // on the operand list before the def. Do two passes over the operand
798 // list to make sure that defs are processed before any uses.
799 bool HasVRegDef = false;
800 for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
801 const MachineOperand &MO = MI.getOperand(j);
802 if (!MO.isReg() || !MO.isDef())
804 unsigned Reg = MO.getReg();
805 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
806 addPhysRegDeps(SU, j);
807 } else if (TargetRegisterInfo::isVirtualRegister(Reg)) {
809 addVRegDefDeps(SU, j);
812 // Now process all uses.
813 for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
814 const MachineOperand &MO = MI.getOperand(j);
815 // Only look at use operands.
816 // We do not need to check for MO.readsReg() here because subsequent
817 // subregister defs will get output dependence edges and need no
818 // additional use dependencies.
819 if (!MO.isReg() || !MO.isUse())
821 unsigned Reg = MO.getReg();
822 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
823 addPhysRegDeps(SU, j);
824 } else if (TargetRegisterInfo::isVirtualRegister(Reg) && MO.readsReg()) {
825 addVRegUseDeps(SU, j);
829 // If we haven't seen any uses in this scheduling region, create a
830 // dependence edge to ExitSU to model the live-out latency. This is required
831 // for vreg defs with no in-region use, and prefetches with no vreg def.
833 // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
834 // check currently relies on being called before adding chain deps.
835 if (SU->NumSuccs == 0 && SU->Latency > 1 && (HasVRegDef || MI.mayLoad())) {
836 SDep Dep(SU, SDep::Artificial);
837 Dep.setLatency(SU->Latency - 1);
841 // Add memory dependencies (Note: isStoreToStackSlot and
842 // isLoadFromStackSLot are not usable after stack slots are lowered to
843 // actual addresses).
845 // This is a barrier event that acts as a pivotal node in the DAG.
846 if (isGlobalMemoryObject(AA, &MI)) {
848 // Become the barrier chain.
850 BarrierChain->addPredBarrier(SU);
853 LLVM_DEBUG(dbgs() << "Global memory object and new barrier chain: SU("
854 << BarrierChain->NodeNum << ").\n";);
856 // Add dependencies against everything below it and clear maps.
857 addBarrierChain(Stores);
858 addBarrierChain(Loads);
859 addBarrierChain(NonAliasStores);
860 addBarrierChain(NonAliasLoads);
865 // If it's not a store or a variant load, we're done.
866 if (!MI.mayStore() &&
867 !(MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA)))
870 // Always add dependecy edge to BarrierChain if present.
872 BarrierChain->addPredBarrier(SU);
874 // Find the underlying objects for MI. The Objs vector is either
875 // empty, or filled with the Values of memory locations which this
877 UnderlyingObjectsVector Objs;
878 bool ObjsFound = getUnderlyingObjectsForInstr(&MI, MFI, Objs,
883 // An unknown store depends on all stores and loads.
884 addChainDependencies(SU, Stores);
885 addChainDependencies(SU, NonAliasStores);
886 addChainDependencies(SU, Loads);
887 addChainDependencies(SU, NonAliasLoads);
889 // Map this store to 'UnknownValue'.
890 Stores.insert(SU, UnknownValue);
892 // Add precise dependencies against all previously seen memory
893 // accesses mapped to the same Value(s).
894 for (const UnderlyingObject &UnderlObj : Objs) {
895 ValueType V = UnderlObj.getValue();
896 bool ThisMayAlias = UnderlObj.mayAlias();
898 // Add dependencies to previous stores and loads mapped to V.
899 addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
900 addChainDependencies(SU, (ThisMayAlias ? Loads : NonAliasLoads), V);
902 // Update the store map after all chains have been added to avoid adding
903 // self-loop edge if multiple underlying objects are present.
904 for (const UnderlyingObject &UnderlObj : Objs) {
905 ValueType V = UnderlObj.getValue();
906 bool ThisMayAlias = UnderlObj.mayAlias();
908 // Map this store to V.
909 (ThisMayAlias ? Stores : NonAliasStores).insert(SU, V);
911 // The store may have dependencies to unanalyzable loads and
913 addChainDependencies(SU, Loads, UnknownValue);
914 addChainDependencies(SU, Stores, UnknownValue);
916 } else { // SU is a load.
918 // An unknown load depends on all stores.
919 addChainDependencies(SU, Stores);
920 addChainDependencies(SU, NonAliasStores);
922 Loads.insert(SU, UnknownValue);
924 for (const UnderlyingObject &UnderlObj : Objs) {
925 ValueType V = UnderlObj.getValue();
926 bool ThisMayAlias = UnderlObj.mayAlias();
928 // Add precise dependencies against all previously seen stores
929 // mapping to the same Value(s).
930 addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
932 // Map this load to V.
933 (ThisMayAlias ? Loads : NonAliasLoads).insert(SU, V);
935 // The load may have dependencies to unanalyzable stores.
936 addChainDependencies(SU, Stores, UnknownValue);
940 // Reduce maps if they grow huge.
941 if (Stores.size() + Loads.size() >= HugeRegion) {
942 LLVM_DEBUG(dbgs() << "Reducing Stores and Loads maps.\n";);
943 reduceHugeMemNodeMaps(Stores, Loads, getReductionSize());
945 if (NonAliasStores.size() + NonAliasLoads.size() >= HugeRegion) {
947 dbgs() << "Reducing NonAliasStores and NonAliasLoads maps.\n";);
948 reduceHugeMemNodeMaps(NonAliasStores, NonAliasLoads, getReductionSize());
953 FirstDbgValue = DbgMI;
957 CurrentVRegDefs.clear();
958 CurrentVRegUses.clear();
961 raw_ostream &llvm::operator<<(raw_ostream &OS, const PseudoSourceValue* PSV) {
962 PSV->printCustom(OS);
966 void ScheduleDAGInstrs::Value2SUsMap::dump() {
967 for (auto &Itr : *this) {
968 if (Itr.first.is<const Value*>()) {
969 const Value *V = Itr.first.get<const Value*>();
970 if (isa<UndefValue>(V))
973 V->printAsOperand(dbgs());
975 else if (Itr.first.is<const PseudoSourceValue*>())
976 dbgs() << Itr.first.get<const PseudoSourceValue*>();
978 llvm_unreachable("Unknown Value type.");
981 dumpSUList(Itr.second);
985 void ScheduleDAGInstrs::reduceHugeMemNodeMaps(Value2SUsMap &stores,
986 Value2SUsMap &loads, unsigned N) {
987 LLVM_DEBUG(dbgs() << "Before reduction:\nStoring SUnits:\n"; stores.dump();
988 dbgs() << "Loading SUnits:\n"; loads.dump());
990 // Insert all SU's NodeNums into a vector and sort it.
991 std::vector<unsigned> NodeNums;
992 NodeNums.reserve(stores.size() + loads.size());
993 for (auto &I : stores)
994 for (auto *SU : I.second)
995 NodeNums.push_back(SU->NodeNum);
996 for (auto &I : loads)
997 for (auto *SU : I.second)
998 NodeNums.push_back(SU->NodeNum);
999 llvm::sort(NodeNums.begin(), NodeNums.end());
1001 // The N last elements in NodeNums will be removed, and the SU with
1002 // the lowest NodeNum of them will become the new BarrierChain to
1003 // let the not yet seen SUs have a dependency to the removed SUs.
1004 assert(N <= NodeNums.size());
1005 SUnit *newBarrierChain = &SUnits[*(NodeNums.end() - N)];
1007 // The aliasing and non-aliasing maps reduce independently of each
1008 // other, but share a common BarrierChain. Check if the
1009 // newBarrierChain is above the former one. If it is not, it may
1010 // introduce a loop to use newBarrierChain, so keep the old one.
1011 if (newBarrierChain->NodeNum < BarrierChain->NodeNum) {
1012 BarrierChain->addPredBarrier(newBarrierChain);
1013 BarrierChain = newBarrierChain;
1014 LLVM_DEBUG(dbgs() << "Inserting new barrier chain: SU("
1015 << BarrierChain->NodeNum << ").\n";);
1018 LLVM_DEBUG(dbgs() << "Keeping old barrier chain: SU("
1019 << BarrierChain->NodeNum << ").\n";);
1022 BarrierChain = newBarrierChain;
1024 insertBarrierChain(stores);
1025 insertBarrierChain(loads);
1027 LLVM_DEBUG(dbgs() << "After reduction:\nStoring SUnits:\n"; stores.dump();
1028 dbgs() << "Loading SUnits:\n"; loads.dump());
1031 static void toggleKills(const MachineRegisterInfo &MRI, LivePhysRegs &LiveRegs,
1032 MachineInstr &MI, bool addToLiveRegs) {
1033 for (MachineOperand &MO : MI.operands()) {
1034 if (!MO.isReg() || !MO.readsReg())
1036 unsigned Reg = MO.getReg();
1040 // Things that are available after the instruction are killed by it.
1041 bool IsKill = LiveRegs.available(MRI, Reg);
1042 MO.setIsKill(IsKill);
1044 LiveRegs.addReg(Reg);
1048 void ScheduleDAGInstrs::fixupKills(MachineBasicBlock &MBB) {
1049 LLVM_DEBUG(dbgs() << "Fixup kills for " << printMBBReference(MBB) << '\n');
1051 LiveRegs.init(*TRI);
1052 LiveRegs.addLiveOuts(MBB);
1054 // Examine block from end to start...
1055 for (MachineInstr &MI : make_range(MBB.rbegin(), MBB.rend())) {
1056 if (MI.isDebugInstr())
1059 // Update liveness. Registers that are defed but not used in this
1060 // instruction are now dead. Mark register and all subregs as they
1061 // are completely defined.
1062 for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
1063 const MachineOperand &MO = *O;
1067 unsigned Reg = MO.getReg();
1070 LiveRegs.removeReg(Reg);
1071 } else if (MO.isRegMask()) {
1072 LiveRegs.removeRegsInMask(MO);
1076 // If there is a bundle header fix it up first.
1077 if (!MI.isBundled()) {
1078 toggleKills(MRI, LiveRegs, MI, true);
1080 MachineBasicBlock::instr_iterator First = MI.getIterator();
1081 if (MI.isBundle()) {
1082 toggleKills(MRI, LiveRegs, MI, false);
1085 // Some targets make the (questionable) assumtion that the instructions
1086 // inside the bundle are ordered and consequently only the last use of
1087 // a register inside the bundle can kill it.
1088 MachineBasicBlock::instr_iterator I = std::next(First);
1089 while (I->isBundledWithSucc())
1092 if (!I->isDebugInstr())
1093 toggleKills(MRI, LiveRegs, *I, true);
1095 } while(I != First);
1100 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
1101 // Cannot completely remove virtual function even in release mode.
1102 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1103 SU->getInstr()->dump();
1107 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1109 raw_string_ostream oss(s);
1112 else if (SU == &ExitSU)
1115 SU->getInstr()->print(oss, /*SkipOpers=*/true);
1119 /// Return the basic block label. It is not necessarilly unique because a block
1120 /// contains multiple scheduling regions. But it is fine for visualization.
1121 std::string ScheduleDAGInstrs::getDAGName() const {
1122 return "dag." + BB->getFullName();
1125 //===----------------------------------------------------------------------===//
1126 // SchedDFSResult Implementation
1127 //===----------------------------------------------------------------------===//
1131 /// Internal state used to compute SchedDFSResult.
1132 class SchedDFSImpl {
1135 /// Join DAG nodes into equivalence classes by their subtree.
1136 IntEqClasses SubtreeClasses;
1137 /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1138 std::vector<std::pair<const SUnit *, const SUnit*>> ConnectionPairs;
1142 unsigned ParentNodeID; ///< Parent node (member of the parent subtree).
1143 unsigned SubInstrCount = 0; ///< Instr count in this tree only, not
1146 RootData(unsigned id): NodeID(id),
1147 ParentNodeID(SchedDFSResult::InvalidSubtreeID) {}
1149 unsigned getSparseSetIndex() const { return NodeID; }
1152 SparseSet<RootData> RootSet;
1155 SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1156 RootSet.setUniverse(R.DFSNodeData.size());
1159 /// Returns true if this node been visited by the DFS traversal.
1161 /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1162 /// ID. Later, SubtreeID is updated but remains valid.
1163 bool isVisited(const SUnit *SU) const {
1164 return R.DFSNodeData[SU->NodeNum].SubtreeID
1165 != SchedDFSResult::InvalidSubtreeID;
1168 /// Initializes this node's instruction count. We don't need to flag the node
1169 /// visited until visitPostorder because the DAG cannot have cycles.
1170 void visitPreorder(const SUnit *SU) {
1171 R.DFSNodeData[SU->NodeNum].InstrCount =
1172 SU->getInstr()->isTransient() ? 0 : 1;
1175 /// Called once for each node after all predecessors are visited. Revisit this
1176 /// node's predecessors and potentially join them now that we know the ILP of
1177 /// the other predecessors.
1178 void visitPostorderNode(const SUnit *SU) {
1179 // Mark this node as the root of a subtree. It may be joined with its
1180 // successors later.
1181 R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1182 RootData RData(SU->NodeNum);
1183 RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
1185 // If any predecessors are still in their own subtree, they either cannot be
1186 // joined or are large enough to remain separate. If this parent node's
1187 // total instruction count is not greater than a child subtree by at least
1188 // the subtree limit, then try to join it now since splitting subtrees is
1189 // only useful if multiple high-pressure paths are possible.
1190 unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
1191 for (const SDep &PredDep : SU->Preds) {
1192 if (PredDep.getKind() != SDep::Data)
1194 unsigned PredNum = PredDep.getSUnit()->NodeNum;
1195 if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
1196 joinPredSubtree(PredDep, SU, /*CheckLimit=*/false);
1198 // Either link or merge the TreeData entry from the child to the parent.
1199 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1200 // If the predecessor's parent is invalid, this is a tree edge and the
1201 // current node is the parent.
1202 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1203 RootSet[PredNum].ParentNodeID = SU->NodeNum;
1205 else if (RootSet.count(PredNum)) {
1206 // The predecessor is not a root, but is still in the root set. This
1207 // must be the new parent that it was just joined to. Note that
1208 // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1209 // set to the original parent.
1210 RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1211 RootSet.erase(PredNum);
1214 RootSet[SU->NodeNum] = RData;
1217 /// Called once for each tree edge after calling visitPostOrderNode on
1218 /// the predecessor. Increment the parent node's instruction count and
1219 /// preemptively join this subtree to its parent's if it is small enough.
1220 void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1221 R.DFSNodeData[Succ->NodeNum].InstrCount
1222 += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1223 joinPredSubtree(PredDep, Succ);
1226 /// Adds a connection for cross edges.
1227 void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
1228 ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1231 /// Sets each node's subtree ID to the representative ID and record
1232 /// connections between trees.
1234 SubtreeClasses.compress();
1235 R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1236 assert(SubtreeClasses.getNumClasses() == RootSet.size()
1237 && "number of roots should match trees");
1238 for (const RootData &Root : RootSet) {
1239 unsigned TreeID = SubtreeClasses[Root.NodeID];
1240 if (Root.ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1241 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[Root.ParentNodeID];
1242 R.DFSTreeData[TreeID].SubInstrCount = Root.SubInstrCount;
1243 // Note that SubInstrCount may be greater than InstrCount if we joined
1244 // subtrees across a cross edge. InstrCount will be attributed to the
1245 // original parent, while SubInstrCount will be attributed to the joined
1248 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1249 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1250 LLVM_DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
1251 for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1252 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
1253 LLVM_DEBUG(dbgs() << " SU(" << Idx << ") in tree "
1254 << R.DFSNodeData[Idx].SubtreeID << '\n');
1256 for (const std::pair<const SUnit*, const SUnit*> &P : ConnectionPairs) {
1257 unsigned PredTree = SubtreeClasses[P.first->NodeNum];
1258 unsigned SuccTree = SubtreeClasses[P.second->NodeNum];
1259 if (PredTree == SuccTree)
1261 unsigned Depth = P.first->getDepth();
1262 addConnection(PredTree, SuccTree, Depth);
1263 addConnection(SuccTree, PredTree, Depth);
1268 /// Joins the predecessor subtree with the successor that is its DFS parent.
1269 /// Applies some heuristics before joining.
1270 bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1271 bool CheckLimit = true) {
1272 assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1274 // Check if the predecessor is already joined.
1275 const SUnit *PredSU = PredDep.getSUnit();
1276 unsigned PredNum = PredSU->NodeNum;
1277 if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
1280 // Four is the magic number of successors before a node is considered a
1282 unsigned NumDataSucs = 0;
1283 for (const SDep &SuccDep : PredSU->Succs) {
1284 if (SuccDep.getKind() == SDep::Data) {
1285 if (++NumDataSucs >= 4)
1289 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
1291 R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
1292 SubtreeClasses.join(Succ->NodeNum, PredNum);
1296 /// Called by finalize() to record a connection between trees.
1297 void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1302 SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1303 R.SubtreeConnections[FromTree];
1304 for (SchedDFSResult::Connection &C : Connections) {
1305 if (C.TreeID == ToTree) {
1306 C.Level = std::max(C.Level, Depth);
1310 Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1311 FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1312 } while (FromTree != SchedDFSResult::InvalidSubtreeID);
1316 } // end namespace llvm
1320 /// Manage the stack used by a reverse depth-first search over the DAG.
1321 class SchedDAGReverseDFS {
1322 std::vector<std::pair<const SUnit *, SUnit::const_pred_iterator>> DFSStack;
1325 bool isComplete() const { return DFSStack.empty(); }
1327 void follow(const SUnit *SU) {
1328 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1330 void advance() { ++DFSStack.back().second; }
1332 const SDep *backtrack() {
1333 DFSStack.pop_back();
1334 return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
1337 const SUnit *getCurr() const { return DFSStack.back().first; }
1339 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1341 SUnit::const_pred_iterator getPredEnd() const {
1342 return getCurr()->Preds.end();
1346 } // end anonymous namespace
1348 static bool hasDataSucc(const SUnit *SU) {
1349 for (const SDep &SuccDep : SU->Succs) {
1350 if (SuccDep.getKind() == SDep::Data &&
1351 !SuccDep.getSUnit()->isBoundaryNode())
1357 /// Computes an ILP metric for all nodes in the subDAG reachable via depth-first
1358 /// search from this root.
1359 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
1361 llvm_unreachable("Top-down ILP metric is unimplemented");
1363 SchedDFSImpl Impl(*this);
1364 for (const SUnit &SU : SUnits) {
1365 if (Impl.isVisited(&SU) || hasDataSucc(&SU))
1368 SchedDAGReverseDFS DFS;
1369 Impl.visitPreorder(&SU);
1372 // Traverse the leftmost path as far as possible.
1373 while (DFS.getPred() != DFS.getPredEnd()) {
1374 const SDep &PredDep = *DFS.getPred();
1376 // Ignore non-data edges.
1377 if (PredDep.getKind() != SDep::Data
1378 || PredDep.getSUnit()->isBoundaryNode()) {
1381 // An already visited edge is a cross edge, assuming an acyclic DAG.
1382 if (Impl.isVisited(PredDep.getSUnit())) {
1383 Impl.visitCrossEdge(PredDep, DFS.getCurr());
1386 Impl.visitPreorder(PredDep.getSUnit());
1387 DFS.follow(PredDep.getSUnit());
1389 // Visit the top of the stack in postorder and backtrack.
1390 const SUnit *Child = DFS.getCurr();
1391 const SDep *PredDep = DFS.backtrack();
1392 Impl.visitPostorderNode(Child);
1394 Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
1395 if (DFS.isComplete())
1402 /// The root of the given SubtreeID was just scheduled. For all subtrees
1403 /// connected to this tree, record the depth of the connection so that the
1404 /// nearest connected subtrees can be prioritized.
1405 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1406 for (const Connection &C : SubtreeConnections[SubtreeID]) {
1407 SubtreeConnectLevels[C.TreeID] =
1408 std::max(SubtreeConnectLevels[C.TreeID], C.Level);
1409 LLVM_DEBUG(dbgs() << " Tree: " << C.TreeID << " @"
1410 << SubtreeConnectLevels[C.TreeID] << '\n');
1414 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1415 LLVM_DUMP_METHOD void ILPValue::print(raw_ostream &OS) const {
1416 OS << InstrCount << " / " << Length << " = ";
1420 OS << format("%g", ((double)InstrCount / Length));
1423 LLVM_DUMP_METHOD void ILPValue::dump() const {
1424 dbgs() << *this << '\n';
1430 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1435 } // end namespace llvm