1 //===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file This implements the ScheduleDAGInstrs class, which implements
11 /// re-scheduling of MachineInstrs.
12 //
13 //===----------------------------------------------------------------------===//
14 
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"
58 #include <algorithm>
59 #include <cassert>
60 #include <iterator>
61 #include <string>
62 #include <utility>
63 #include <vector>
64 
65 using namespace llvm;
66 
67 #define DEBUG_TYPE "machine-scheduler"
68 
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"));
72 
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"));
75 
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.
79 
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."));
86 
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."));
91 
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;
97   return ReductionSize;
98 }
99 
100 static void dumpSUList(ScheduleDAGInstrs::SUList &L) {
101 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
102   dbgs() << "{ ";
103   for (const SUnit *su : L) {
104     dbgs() << "SU(" << su->NodeNum << ")";
105     if (su != L.back())
106       dbgs() << ", ";
107   }
108   dbgs() << "}\n";
109 #endif
110 }
111 
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()))) {
119   DbgValues.clear();
120 
121   const TargetSubtargetInfo &ST = mf.getSubtarget();
122   SchedModel.init(&ST);
123 }
124 
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())
136         return false;
137 
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
143         // object.
144         if (MFI.hasTailCall())
145           return false;
146 
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
149         // such aliases.
150         if (PSV->isAliased(&MFI))
151           return false;
152 
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))
158           return false;
159 
160         for (Value *V : Objs) {
161           assert(isIdentifiedObject(V));
162           Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
163         }
164       } else
165         return false;
166     }
167     return true;
168   };
169 
170   if (!allMMOsOkay()) {
171     Objects.clear();
172     return false;
173   }
174 
175   return true;
176 }
177 
178 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
179   BB = bb;
180 }
181 
182 void ScheduleDAGInstrs::finishBlock() {
183   // Subclasses should no longer refer to the old block.
184   BB = nullptr;
185 }
186 
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");
192   RegionBegin = begin;
193   RegionEnd = end;
194   NumRegionInstrs = regioninstrs;
195 }
196 
197 void ScheduleDAGInstrs::exitRegion() {
198   // Nothing to do.
199 }
200 
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.
205   if (ExitMI) {
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));
213       }
214     }
215   }
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));
223       }
224     }
225   }
226 }
227 
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");
233 
234   // Ask the target if address-backscheduling is desirable, and if so how much.
235   const TargetSubtargetInfo &ST = MF.getSubtarget();
236 
237   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
238        Alias.isValid(); ++Alias) {
239     if (!Uses.contains(*Alias))
240       continue;
241     for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
242       SUnit *UseSU = I->SU;
243       if (UseSU == SU)
244         continue;
245 
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;
250       SDep Dep;
251       if (UseOp < 0)
252         Dep = SDep(SU, SDep::Artificial);
253       else {
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();
259       }
260       Dep.setLatency(
261         SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
262                                          UseOp));
263 
264       ST.adjustSchedDependency(SU, UseSU, Dep);
265       UseSU->addPred(Dep);
266     }
267   }
268 }
269 
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))
279     return;
280 
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))
290       continue;
291     for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
292       SUnit *DefSU = I->SU;
293       if (DefSU == &ExitSU)
294         continue;
295       if (DefSU != SU &&
296           (Kind != SDep::Output || !MO.isDead() ||
297            !DefSU->getInstr()->registerDefIsDead(*Alias))) {
298         if (Kind == SDep::Anti)
299           DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
300         else {
301           SDep Dep(SU, Kind, /*Reg=*/*Alias);
302           Dep.setLatency(
303             SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
304           DefSU->addPred(Dep);
305         }
306       }
307     }
308   }
309 
310   if (!MO.isDef()) {
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));
316     if (RemoveKillFlags)
317       MO.setIsKill(false);
318   } else {
319     addPhysRegDataDeps(SU, OperIdx);
320 
321     // clear this register's use list
322     if (Uses.contains(Reg))
323       Uses.eraseAll(Reg);
324 
325     if (!MO.isDead()) {
326       Defs.eraseAll(Reg);
327     } else if (SU->isCall) {
328       // Calls will not be reordered because of chain dependencies (see
329       // below). Since call operands are dead, calls may continue to be added
330       // to the DefList making dependence checking quadratic in the size of
331       // the block. Instead, we leave only one call at the back of the
332       // DefList.
333       Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
334       Reg2SUnitsMap::iterator B = P.first;
335       Reg2SUnitsMap::iterator I = P.second;
336       for (bool isBegin = I == B; !isBegin; /* empty */) {
337         isBegin = (--I) == B;
338         if (!I->SU->isCall)
339           break;
340         I = Defs.erase(I);
341       }
342     }
343 
344     // Defs are pushed in the order they are visited and never reordered.
345     Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
346   }
347 }
348 
349 LaneBitmask ScheduleDAGInstrs::getLaneMaskForMO(const MachineOperand &MO) const
350 {
351   unsigned Reg = MO.getReg();
352   // No point in tracking lanemasks if we don't have interesting subregisters.
353   const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
354   if (!RC.HasDisjunctSubRegs)
355     return LaneBitmask::getAll();
356 
357   unsigned SubReg = MO.getSubReg();
358   if (SubReg == 0)
359     return RC.getLaneMask();
360   return TRI->getSubRegIndexLaneMask(SubReg);
361 }
362 
363 /// Adds register output and data dependencies from this SUnit to instructions
364 /// that occur later in the same scheduling region if they read from or write to
365 /// the virtual register defined at OperIdx.
366 ///
367 /// TODO: Hoist loop induction variable increments. This has to be
368 /// reevaluated. Generally, IV scheduling should be done before coalescing.
369 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
370   MachineInstr *MI = SU->getInstr();
371   MachineOperand &MO = MI->getOperand(OperIdx);
372   unsigned Reg = MO.getReg();
373 
374   LaneBitmask DefLaneMask;
375   LaneBitmask KillLaneMask;
376   if (TrackLaneMasks) {
377     bool IsKill = MO.getSubReg() == 0 || MO.isUndef();
378     DefLaneMask = getLaneMaskForMO(MO);
379     // If we have a <read-undef> flag, none of the lane values comes from an
380     // earlier instruction.
381     KillLaneMask = IsKill ? LaneBitmask::getAll() : DefLaneMask;
382 
383     // Clear undef flag, we'll re-add it later once we know which subregister
384     // Def is first.
385     MO.setIsUndef(false);
386   } else {
387     DefLaneMask = LaneBitmask::getAll();
388     KillLaneMask = LaneBitmask::getAll();
389   }
390 
391   if (MO.isDead()) {
392     assert(CurrentVRegUses.find(Reg) == CurrentVRegUses.end() &&
393            "Dead defs should have no uses");
394   } else {
395     // Add data dependence to all uses we found so far.
396     const TargetSubtargetInfo &ST = MF.getSubtarget();
397     for (VReg2SUnitOperIdxMultiMap::iterator I = CurrentVRegUses.find(Reg),
398          E = CurrentVRegUses.end(); I != E; /*empty*/) {
399       LaneBitmask LaneMask = I->LaneMask;
400       // Ignore uses of other lanes.
401       if ((LaneMask & KillLaneMask).none()) {
402         ++I;
403         continue;
404       }
405 
406       if ((LaneMask & DefLaneMask).any()) {
407         SUnit *UseSU = I->SU;
408         MachineInstr *Use = UseSU->getInstr();
409         SDep Dep(SU, SDep::Data, Reg);
410         Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use,
411                                                         I->OperandIndex));
412         ST.adjustSchedDependency(SU, UseSU, Dep);
413         UseSU->addPred(Dep);
414       }
415 
416       LaneMask &= ~KillLaneMask;
417       // If we found a Def for all lanes of this use, remove it from the list.
418       if (LaneMask.any()) {
419         I->LaneMask = LaneMask;
420         ++I;
421       } else
422         I = CurrentVRegUses.erase(I);
423     }
424   }
425 
426   // Shortcut: Singly defined vregs do not have output/anti dependencies.
427   if (MRI.hasOneDef(Reg))
428     return;
429 
430   // Add output dependence to the next nearest defs of this vreg.
431   //
432   // Unless this definition is dead, the output dependence should be
433   // transitively redundant with antidependencies from this definition's
434   // uses. We're conservative for now until we have a way to guarantee the uses
435   // are not eliminated sometime during scheduling. The output dependence edge
436   // is also useful if output latency exceeds def-use latency.
437   LaneBitmask LaneMask = DefLaneMask;
438   for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
439                                      CurrentVRegDefs.end())) {
440     // Ignore defs for other lanes.
441     if ((V2SU.LaneMask & LaneMask).none())
442       continue;
443     // Add an output dependence.
444     SUnit *DefSU = V2SU.SU;
445     // Ignore additional defs of the same lanes in one instruction. This can
446     // happen because lanemasks are shared for targets with too many
447     // subregisters. We also use some representration tricks/hacks where we
448     // add super-register defs/uses, to imply that although we only access parts
449     // of the reg we care about the full one.
450     if (DefSU == SU)
451       continue;
452     SDep Dep(SU, SDep::Output, Reg);
453     Dep.setLatency(
454       SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
455     DefSU->addPred(Dep);
456 
457     // Update current definition. This can get tricky if the def was about a
458     // bigger lanemask before. We then have to shrink it and create a new
459     // VReg2SUnit for the non-overlapping part.
460     LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
461     LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
462     V2SU.SU = SU;
463     V2SU.LaneMask = OverlapMask;
464     if (NonOverlapMask.any())
465       CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, DefSU));
466   }
467   // If there was no CurrentVRegDefs entry for some lanes yet, create one.
468   if (LaneMask.any())
469     CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU));
470 }
471 
472 /// Adds a register data dependency if the instruction that defines the
473 /// virtual register used at OperIdx is mapped to an SUnit. Add a register
474 /// antidependency from this SUnit to instructions that occur later in the same
475 /// scheduling region if they write the virtual register.
476 ///
477 /// TODO: Handle ExitSU "uses" properly.
478 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
479   const MachineInstr *MI = SU->getInstr();
480   const MachineOperand &MO = MI->getOperand(OperIdx);
481   unsigned Reg = MO.getReg();
482 
483   // Remember the use. Data dependencies will be added when we find the def.
484   LaneBitmask LaneMask = TrackLaneMasks ? getLaneMaskForMO(MO)
485                                         : LaneBitmask::getAll();
486   CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU));
487 
488   // Add antidependences to the following defs of the vreg.
489   for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
490                                      CurrentVRegDefs.end())) {
491     // Ignore defs for unrelated lanes.
492     LaneBitmask PrevDefLaneMask = V2SU.LaneMask;
493     if ((PrevDefLaneMask & LaneMask).none())
494       continue;
495     if (V2SU.SU == SU)
496       continue;
497 
498     V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg));
499   }
500 }
501 
502 /// Returns true if MI is an instruction we are unable to reason about
503 /// (like a call or something with unmodeled side effects).
504 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
505   return MI->isCall() || MI->hasUnmodeledSideEffects() ||
506          (MI->hasOrderedMemoryRef() && !MI->isDereferenceableInvariantLoad(AA));
507 }
508 
509 void ScheduleDAGInstrs::addChainDependency (SUnit *SUa, SUnit *SUb,
510                                             unsigned Latency) {
511   if (SUa->getInstr()->mayAlias(AAForDep, *SUb->getInstr(), UseTBAA)) {
512     SDep Dep(SUa, SDep::MayAliasMem);
513     Dep.setLatency(Latency);
514     SUb->addPred(Dep);
515   }
516 }
517 
518 /// Creates an SUnit for each real instruction, numbered in top-down
519 /// topological order. The instruction order A < B, implies that no edge exists
520 /// from B to A.
521 ///
522 /// Map each real instruction to its SUnit.
523 ///
524 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
525 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
526 /// instead of pointers.
527 ///
528 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
529 /// the original instruction list.
530 void ScheduleDAGInstrs::initSUnits() {
531   // We'll be allocating one SUnit for each real instruction in the region,
532   // which is contained within a basic block.
533   SUnits.reserve(NumRegionInstrs);
534 
535   for (MachineInstr &MI : make_range(RegionBegin, RegionEnd)) {
536     if (MI.isDebugInstr())
537       continue;
538 
539     SUnit *SU = newSUnit(&MI);
540     MISUnitMap[&MI] = SU;
541 
542     SU->isCall = MI.isCall();
543     SU->isCommutable = MI.isCommutable();
544 
545     // Assign the Latency field of SU using target-provided information.
546     SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
547 
548     // If this SUnit uses a reserved or unbuffered resource, mark it as such.
549     //
550     // Reserved resources block an instruction from issuing and stall the
551     // entire pipeline. These are identified by BufferSize=0.
552     //
553     // Unbuffered resources prevent execution of subsequent instructions that
554     // require the same resources. This is used for in-order execution pipelines
555     // within an out-of-order core. These are identified by BufferSize=1.
556     if (SchedModel.hasInstrSchedModel()) {
557       const MCSchedClassDesc *SC = getSchedClass(SU);
558       for (const MCWriteProcResEntry &PRE :
559            make_range(SchedModel.getWriteProcResBegin(SC),
560                       SchedModel.getWriteProcResEnd(SC))) {
561         switch (SchedModel.getProcResource(PRE.ProcResourceIdx)->BufferSize) {
562         case 0:
563           SU->hasReservedResource = true;
564           break;
565         case 1:
566           SU->isUnbuffered = true;
567           break;
568         default:
569           break;
570         }
571       }
572     }
573   }
574 }
575 
576 class ScheduleDAGInstrs::Value2SUsMap : public MapVector<ValueType, SUList> {
577   /// Current total number of SUs in map.
578   unsigned NumNodes = 0;
579 
580   /// 1 for loads, 0 for stores. (see comment in SUList)
581   unsigned TrueMemOrderLatency;
582 
583 public:
584   Value2SUsMap(unsigned lat = 0) : TrueMemOrderLatency(lat) {}
585 
586   /// To keep NumNodes up to date, insert() is used instead of
587   /// this operator w/ push_back().
588   ValueType &operator[](const SUList &Key) {
589     llvm_unreachable("Don't use. Use insert() instead."); };
590 
591   /// Adds SU to the SUList of V. If Map grows huge, reduce its size by calling
592   /// reduce().
593   void inline insert(SUnit *SU, ValueType V) {
594     MapVector::operator[](V).push_back(SU);
595     NumNodes++;
596   }
597 
598   /// Clears the list of SUs mapped to V.
599   void inline clearList(ValueType V) {
600     iterator Itr = find(V);
601     if (Itr != end()) {
602       assert(NumNodes >= Itr->second.size());
603       NumNodes -= Itr->second.size();
604 
605       Itr->second.clear();
606     }
607   }
608 
609   /// Clears map from all contents.
610   void clear() {
611     MapVector<ValueType, SUList>::clear();
612     NumNodes = 0;
613   }
614 
615   unsigned inline size() const { return NumNodes; }
616 
617   /// Counts the number of SUs in this map after a reduction.
618   void reComputeSize() {
619     NumNodes = 0;
620     for (auto &I : *this)
621       NumNodes += I.second.size();
622   }
623 
624   unsigned inline getTrueMemOrderLatency() const {
625     return TrueMemOrderLatency;
626   }
627 
628   void dump();
629 };
630 
631 void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
632                                              Value2SUsMap &Val2SUsMap) {
633   for (auto &I : Val2SUsMap)
634     addChainDependencies(SU, I.second,
635                          Val2SUsMap.getTrueMemOrderLatency());
636 }
637 
638 void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
639                                              Value2SUsMap &Val2SUsMap,
640                                              ValueType V) {
641   Value2SUsMap::iterator Itr = Val2SUsMap.find(V);
642   if (Itr != Val2SUsMap.end())
643     addChainDependencies(SU, Itr->second,
644                          Val2SUsMap.getTrueMemOrderLatency());
645 }
646 
647 void ScheduleDAGInstrs::addBarrierChain(Value2SUsMap &map) {
648   assert(BarrierChain != nullptr);
649 
650   for (auto &I : map) {
651     SUList &sus = I.second;
652     for (auto *SU : sus)
653       SU->addPredBarrier(BarrierChain);
654   }
655   map.clear();
656 }
657 
658 void ScheduleDAGInstrs::insertBarrierChain(Value2SUsMap &map) {
659   assert(BarrierChain != nullptr);
660 
661   // Go through all lists of SUs.
662   for (Value2SUsMap::iterator I = map.begin(), EE = map.end(); I != EE;) {
663     Value2SUsMap::iterator CurrItr = I++;
664     SUList &sus = CurrItr->second;
665     SUList::iterator SUItr = sus.begin(), SUEE = sus.end();
666     for (; SUItr != SUEE; ++SUItr) {
667       // Stop on BarrierChain or any instruction above it.
668       if ((*SUItr)->NodeNum <= BarrierChain->NodeNum)
669         break;
670 
671       (*SUItr)->addPredBarrier(BarrierChain);
672     }
673 
674     // Remove also the BarrierChain from list if present.
675     if (SUItr != SUEE && *SUItr == BarrierChain)
676       SUItr++;
677 
678     // Remove all SUs that are now successors of BarrierChain.
679     if (SUItr != sus.begin())
680       sus.erase(sus.begin(), SUItr);
681   }
682 
683   // Remove all entries with empty su lists.
684   map.remove_if([&](std::pair<ValueType, SUList> &mapEntry) {
685       return (mapEntry.second.empty()); });
686 
687   // Recompute the size of the map (NumNodes).
688   map.reComputeSize();
689 }
690 
691 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
692                                         RegPressureTracker *RPTracker,
693                                         PressureDiffs *PDiffs,
694                                         LiveIntervals *LIS,
695                                         bool TrackLaneMasks) {
696   const TargetSubtargetInfo &ST = MF.getSubtarget();
697   bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
698                                                        : ST.useAA();
699   AAForDep = UseAA ? AA : nullptr;
700 
701   BarrierChain = nullptr;
702 
703   this->TrackLaneMasks = TrackLaneMasks;
704   MISUnitMap.clear();
705   ScheduleDAG::clearDAG();
706 
707   // Create an SUnit for each real instruction.
708   initSUnits();
709 
710   if (PDiffs)
711     PDiffs->init(SUnits.size());
712 
713   // We build scheduling units by walking a block's instruction list
714   // from bottom to top.
715 
716   // Each MIs' memory operand(s) is analyzed to a list of underlying
717   // objects. The SU is then inserted in the SUList(s) mapped from the
718   // Value(s). Each Value thus gets mapped to lists of SUs depending
719   // on it, stores and loads kept separately. Two SUs are trivially
720   // non-aliasing if they both depend on only identified Values and do
721   // not share any common Value.
722   Value2SUsMap Stores, Loads(1 /*TrueMemOrderLatency*/);
723 
724   // Certain memory accesses are known to not alias any SU in Stores
725   // or Loads, and have therefore their own 'NonAlias'
726   // domain. E.g. spill / reload instructions never alias LLVM I/R
727   // Values. It would be nice to assume that this type of memory
728   // accesses always have a proper memory operand modelling, and are
729   // therefore never unanalyzable, but this is conservatively not
730   // done.
731   Value2SUsMap NonAliasStores, NonAliasLoads(1 /*TrueMemOrderLatency*/);
732 
733   // Remove any stale debug info; sometimes BuildSchedGraph is called again
734   // without emitting the info from the previous call.
735   DbgValues.clear();
736   FirstDbgValue = nullptr;
737 
738   assert(Defs.empty() && Uses.empty() &&
739          "Only BuildGraph should update Defs/Uses");
740   Defs.setUniverse(TRI->getNumRegs());
741   Uses.setUniverse(TRI->getNumRegs());
742 
743   assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
744   assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
745   unsigned NumVirtRegs = MRI.getNumVirtRegs();
746   CurrentVRegDefs.setUniverse(NumVirtRegs);
747   CurrentVRegUses.setUniverse(NumVirtRegs);
748 
749   // Model data dependencies between instructions being scheduled and the
750   // ExitSU.
751   addSchedBarrierDeps();
752 
753   // Walk the list of instructions, from bottom moving up.
754   MachineInstr *DbgMI = nullptr;
755   for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
756        MII != MIE; --MII) {
757     MachineInstr &MI = *std::prev(MII);
758     if (DbgMI) {
759       DbgValues.push_back(std::make_pair(DbgMI, &MI));
760       DbgMI = nullptr;
761     }
762 
763     if (MI.isDebugValue()) {
764       DbgMI = &MI;
765       continue;
766     }
767     if (MI.isDebugLabel())
768       continue;
769 
770     SUnit *SU = MISUnitMap[&MI];
771     assert(SU && "No SUnit mapped to this MI");
772 
773     if (RPTracker) {
774       RegisterOperands RegOpers;
775       RegOpers.collect(MI, *TRI, MRI, TrackLaneMasks, false);
776       if (TrackLaneMasks) {
777         SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
778         RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx);
779       }
780       if (PDiffs != nullptr)
781         PDiffs->addInstruction(SU->NodeNum, RegOpers, MRI);
782 
783       if (RPTracker->getPos() == RegionEnd || &*RPTracker->getPos() != &MI)
784         RPTracker->recedeSkipDebugValues();
785       assert(&*RPTracker->getPos() == &MI && "RPTracker in sync");
786       RPTracker->recede(RegOpers);
787     }
788 
789     assert(
790         (CanHandleTerminators || (!MI.isTerminator() && !MI.isPosition())) &&
791         "Cannot schedule terminators or labels!");
792 
793     // Add register-based dependencies (data, anti, and output).
794     // For some instructions (calls, returns, inline-asm, etc.) there can
795     // be explicit uses and implicit defs, in which case the use will appear
796     // on the operand list before the def. Do two passes over the operand
797     // list to make sure that defs are processed before any uses.
798     bool HasVRegDef = false;
799     for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
800       const MachineOperand &MO = MI.getOperand(j);
801       if (!MO.isReg() || !MO.isDef())
802         continue;
803       unsigned Reg = MO.getReg();
804       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
805         addPhysRegDeps(SU, j);
806       } else if (TargetRegisterInfo::isVirtualRegister(Reg)) {
807         HasVRegDef = true;
808         addVRegDefDeps(SU, j);
809       }
810     }
811     // Now process all uses.
812     for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
813       const MachineOperand &MO = MI.getOperand(j);
814       // Only look at use operands.
815       // We do not need to check for MO.readsReg() here because subsequent
816       // subregister defs will get output dependence edges and need no
817       // additional use dependencies.
818       if (!MO.isReg() || !MO.isUse())
819         continue;
820       unsigned Reg = MO.getReg();
821       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
822         addPhysRegDeps(SU, j);
823       } else if (TargetRegisterInfo::isVirtualRegister(Reg) && MO.readsReg()) {
824         addVRegUseDeps(SU, j);
825       }
826     }
827 
828     // If we haven't seen any uses in this scheduling region, create a
829     // dependence edge to ExitSU to model the live-out latency. This is required
830     // for vreg defs with no in-region use, and prefetches with no vreg def.
831     //
832     // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
833     // check currently relies on being called before adding chain deps.
834     if (SU->NumSuccs == 0 && SU->Latency > 1 && (HasVRegDef || MI.mayLoad())) {
835       SDep Dep(SU, SDep::Artificial);
836       Dep.setLatency(SU->Latency - 1);
837       ExitSU.addPred(Dep);
838     }
839 
840     // Add memory dependencies (Note: isStoreToStackSlot and
841     // isLoadFromStackSLot are not usable after stack slots are lowered to
842     // actual addresses).
843 
844     // This is a barrier event that acts as a pivotal node in the DAG.
845     if (isGlobalMemoryObject(AA, &MI)) {
846 
847       // Become the barrier chain.
848       if (BarrierChain)
849         BarrierChain->addPredBarrier(SU);
850       BarrierChain = SU;
851 
852       LLVM_DEBUG(dbgs() << "Global memory object and new barrier chain: SU("
853                         << BarrierChain->NodeNum << ").\n";);
854 
855       // Add dependencies against everything below it and clear maps.
856       addBarrierChain(Stores);
857       addBarrierChain(Loads);
858       addBarrierChain(NonAliasStores);
859       addBarrierChain(NonAliasLoads);
860 
861       continue;
862     }
863 
864     // If it's not a store or a variant load, we're done.
865     if (!MI.mayStore() &&
866         !(MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA)))
867       continue;
868 
869     // Always add dependecy edge to BarrierChain if present.
870     if (BarrierChain)
871       BarrierChain->addPredBarrier(SU);
872 
873     // Find the underlying objects for MI. The Objs vector is either
874     // empty, or filled with the Values of memory locations which this
875     // SU depends on.
876     UnderlyingObjectsVector Objs;
877     bool ObjsFound = getUnderlyingObjectsForInstr(&MI, MFI, Objs,
878                                                   MF.getDataLayout());
879 
880     if (MI.mayStore()) {
881       if (!ObjsFound) {
882         // An unknown store depends on all stores and loads.
883         addChainDependencies(SU, Stores);
884         addChainDependencies(SU, NonAliasStores);
885         addChainDependencies(SU, Loads);
886         addChainDependencies(SU, NonAliasLoads);
887 
888         // Map this store to 'UnknownValue'.
889         Stores.insert(SU, UnknownValue);
890       } else {
891         // Add precise dependencies against all previously seen memory
892         // accesses mapped to the same Value(s).
893         for (const UnderlyingObject &UnderlObj : Objs) {
894           ValueType V = UnderlObj.getValue();
895           bool ThisMayAlias = UnderlObj.mayAlias();
896 
897           // Add dependencies to previous stores and loads mapped to V.
898           addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
899           addChainDependencies(SU, (ThisMayAlias ? Loads : NonAliasLoads), V);
900         }
901         // Update the store map after all chains have been added to avoid adding
902         // self-loop edge if multiple underlying objects are present.
903         for (const UnderlyingObject &UnderlObj : Objs) {
904           ValueType V = UnderlObj.getValue();
905           bool ThisMayAlias = UnderlObj.mayAlias();
906 
907           // Map this store to V.
908           (ThisMayAlias ? Stores : NonAliasStores).insert(SU, V);
909         }
910         // The store may have dependencies to unanalyzable loads and
911         // stores.
912         addChainDependencies(SU, Loads, UnknownValue);
913         addChainDependencies(SU, Stores, UnknownValue);
914       }
915     } else { // SU is a load.
916       if (!ObjsFound) {
917         // An unknown load depends on all stores.
918         addChainDependencies(SU, Stores);
919         addChainDependencies(SU, NonAliasStores);
920 
921         Loads.insert(SU, UnknownValue);
922       } else {
923         for (const UnderlyingObject &UnderlObj : Objs) {
924           ValueType V = UnderlObj.getValue();
925           bool ThisMayAlias = UnderlObj.mayAlias();
926 
927           // Add precise dependencies against all previously seen stores
928           // mapping to the same Value(s).
929           addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
930 
931           // Map this load to V.
932           (ThisMayAlias ? Loads : NonAliasLoads).insert(SU, V);
933         }
934         // The load may have dependencies to unanalyzable stores.
935         addChainDependencies(SU, Stores, UnknownValue);
936       }
937     }
938 
939     // Reduce maps if they grow huge.
940     if (Stores.size() + Loads.size() >= HugeRegion) {
941       LLVM_DEBUG(dbgs() << "Reducing Stores and Loads maps.\n";);
942       reduceHugeMemNodeMaps(Stores, Loads, getReductionSize());
943     }
944     if (NonAliasStores.size() + NonAliasLoads.size() >= HugeRegion) {
945       LLVM_DEBUG(
946           dbgs() << "Reducing NonAliasStores and NonAliasLoads maps.\n";);
947       reduceHugeMemNodeMaps(NonAliasStores, NonAliasLoads, getReductionSize());
948     }
949   }
950 
951   if (DbgMI)
952     FirstDbgValue = DbgMI;
953 
954   Defs.clear();
955   Uses.clear();
956   CurrentVRegDefs.clear();
957   CurrentVRegUses.clear();
958 }
959 
960 raw_ostream &llvm::operator<<(raw_ostream &OS, const PseudoSourceValue* PSV) {
961   PSV->printCustom(OS);
962   return OS;
963 }
964 
965 void ScheduleDAGInstrs::Value2SUsMap::dump() {
966   for (auto &Itr : *this) {
967     if (Itr.first.is<const Value*>()) {
968       const Value *V = Itr.first.get<const Value*>();
969       if (isa<UndefValue>(V))
970         dbgs() << "Unknown";
971       else
972         V->printAsOperand(dbgs());
973     }
974     else if (Itr.first.is<const PseudoSourceValue*>())
975       dbgs() <<  Itr.first.get<const PseudoSourceValue*>();
976     else
977       llvm_unreachable("Unknown Value type.");
978 
979     dbgs() << " : ";
980     dumpSUList(Itr.second);
981   }
982 }
983 
984 void ScheduleDAGInstrs::reduceHugeMemNodeMaps(Value2SUsMap &stores,
985                                               Value2SUsMap &loads, unsigned N) {
986   LLVM_DEBUG(dbgs() << "Before reduction:\nStoring SUnits:\n"; stores.dump();
987              dbgs() << "Loading SUnits:\n"; loads.dump());
988 
989   // Insert all SU's NodeNums into a vector and sort it.
990   std::vector<unsigned> NodeNums;
991   NodeNums.reserve(stores.size() + loads.size());
992   for (auto &I : stores)
993     for (auto *SU : I.second)
994       NodeNums.push_back(SU->NodeNum);
995   for (auto &I : loads)
996     for (auto *SU : I.second)
997       NodeNums.push_back(SU->NodeNum);
998   llvm::sort(NodeNums.begin(), NodeNums.end());
999 
1000   // The N last elements in NodeNums will be removed, and the SU with
1001   // the lowest NodeNum of them will become the new BarrierChain to
1002   // let the not yet seen SUs have a dependency to the removed SUs.
1003   assert(N <= NodeNums.size());
1004   SUnit *newBarrierChain = &SUnits[*(NodeNums.end() - N)];
1005   if (BarrierChain) {
1006     // The aliasing and non-aliasing maps reduce independently of each
1007     // other, but share a common BarrierChain. Check if the
1008     // newBarrierChain is above the former one. If it is not, it may
1009     // introduce a loop to use newBarrierChain, so keep the old one.
1010     if (newBarrierChain->NodeNum < BarrierChain->NodeNum) {
1011       BarrierChain->addPredBarrier(newBarrierChain);
1012       BarrierChain = newBarrierChain;
1013       LLVM_DEBUG(dbgs() << "Inserting new barrier chain: SU("
1014                         << BarrierChain->NodeNum << ").\n";);
1015     }
1016     else
1017       LLVM_DEBUG(dbgs() << "Keeping old barrier chain: SU("
1018                         << BarrierChain->NodeNum << ").\n";);
1019   }
1020   else
1021     BarrierChain = newBarrierChain;
1022 
1023   insertBarrierChain(stores);
1024   insertBarrierChain(loads);
1025 
1026   LLVM_DEBUG(dbgs() << "After reduction:\nStoring SUnits:\n"; stores.dump();
1027              dbgs() << "Loading SUnits:\n"; loads.dump());
1028 }
1029 
1030 static void toggleKills(const MachineRegisterInfo &MRI, LivePhysRegs &LiveRegs,
1031                         MachineInstr &MI, bool addToLiveRegs) {
1032   for (MachineOperand &MO : MI.operands()) {
1033     if (!MO.isReg() || !MO.readsReg())
1034       continue;
1035     unsigned Reg = MO.getReg();
1036     if (!Reg)
1037       continue;
1038 
1039     // Things that are available after the instruction are killed by it.
1040     bool IsKill = LiveRegs.available(MRI, Reg);
1041     MO.setIsKill(IsKill);
1042     if (addToLiveRegs)
1043       LiveRegs.addReg(Reg);
1044   }
1045 }
1046 
1047 void ScheduleDAGInstrs::fixupKills(MachineBasicBlock &MBB) {
1048   LLVM_DEBUG(dbgs() << "Fixup kills for " << printMBBReference(MBB) << '\n');
1049 
1050   LiveRegs.init(*TRI);
1051   LiveRegs.addLiveOuts(MBB);
1052 
1053   // Examine block from end to start...
1054   for (MachineInstr &MI : make_range(MBB.rbegin(), MBB.rend())) {
1055     if (MI.isDebugInstr())
1056       continue;
1057 
1058     // Update liveness.  Registers that are defed but not used in this
1059     // instruction are now dead. Mark register and all subregs as they
1060     // are completely defined.
1061     for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
1062       const MachineOperand &MO = *O;
1063       if (MO.isReg()) {
1064         if (!MO.isDef())
1065           continue;
1066         unsigned Reg = MO.getReg();
1067         if (!Reg)
1068           continue;
1069         LiveRegs.removeReg(Reg);
1070       } else if (MO.isRegMask()) {
1071         LiveRegs.removeRegsInMask(MO);
1072       }
1073     }
1074 
1075     // If there is a bundle header fix it up first.
1076     if (!MI.isBundled()) {
1077       toggleKills(MRI, LiveRegs, MI, true);
1078     } else {
1079       MachineBasicBlock::instr_iterator First = MI.getIterator();
1080       if (MI.isBundle()) {
1081         toggleKills(MRI, LiveRegs, MI, false);
1082         ++First;
1083       }
1084       // Some targets make the (questionable) assumtion that the instructions
1085       // inside the bundle are ordered and consequently only the last use of
1086       // a register inside the bundle can kill it.
1087       MachineBasicBlock::instr_iterator I = std::next(First);
1088       while (I->isBundledWithSucc())
1089         ++I;
1090       do {
1091         if (!I->isDebugInstr())
1092           toggleKills(MRI, LiveRegs, *I, true);
1093         --I;
1094       } while(I != First);
1095     }
1096   }
1097 }
1098 
1099 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
1100   // Cannot completely remove virtual function even in release mode.
1101 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1102   SU->getInstr()->dump();
1103 #endif
1104 }
1105 
1106 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1107   std::string s;
1108   raw_string_ostream oss(s);
1109   if (SU == &EntrySU)
1110     oss << "<entry>";
1111   else if (SU == &ExitSU)
1112     oss << "<exit>";
1113   else
1114     SU->getInstr()->print(oss, /*SkipOpers=*/true);
1115   return oss.str();
1116 }
1117 
1118 /// Return the basic block label. It is not necessarilly unique because a block
1119 /// contains multiple scheduling regions. But it is fine for visualization.
1120 std::string ScheduleDAGInstrs::getDAGName() const {
1121   return "dag." + BB->getFullName();
1122 }
1123 
1124 //===----------------------------------------------------------------------===//
1125 // SchedDFSResult Implementation
1126 //===----------------------------------------------------------------------===//
1127 
1128 namespace llvm {
1129 
1130 /// Internal state used to compute SchedDFSResult.
1131 class SchedDFSImpl {
1132   SchedDFSResult &R;
1133 
1134   /// Join DAG nodes into equivalence classes by their subtree.
1135   IntEqClasses SubtreeClasses;
1136   /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1137   std::vector<std::pair<const SUnit *, const SUnit*>> ConnectionPairs;
1138 
1139   struct RootData {
1140     unsigned NodeID;
1141     unsigned ParentNodeID;  ///< Parent node (member of the parent subtree).
1142     unsigned SubInstrCount = 0; ///< Instr count in this tree only, not
1143                                 /// children.
1144 
1145     RootData(unsigned id): NodeID(id),
1146                            ParentNodeID(SchedDFSResult::InvalidSubtreeID) {}
1147 
1148     unsigned getSparseSetIndex() const { return NodeID; }
1149   };
1150 
1151   SparseSet<RootData> RootSet;
1152 
1153 public:
1154   SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1155     RootSet.setUniverse(R.DFSNodeData.size());
1156   }
1157 
1158   /// Returns true if this node been visited by the DFS traversal.
1159   ///
1160   /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1161   /// ID. Later, SubtreeID is updated but remains valid.
1162   bool isVisited(const SUnit *SU) const {
1163     return R.DFSNodeData[SU->NodeNum].SubtreeID
1164       != SchedDFSResult::InvalidSubtreeID;
1165   }
1166 
1167   /// Initializes this node's instruction count. We don't need to flag the node
1168   /// visited until visitPostorder because the DAG cannot have cycles.
1169   void visitPreorder(const SUnit *SU) {
1170     R.DFSNodeData[SU->NodeNum].InstrCount =
1171       SU->getInstr()->isTransient() ? 0 : 1;
1172   }
1173 
1174   /// Called once for each node after all predecessors are visited. Revisit this
1175   /// node's predecessors and potentially join them now that we know the ILP of
1176   /// the other predecessors.
1177   void visitPostorderNode(const SUnit *SU) {
1178     // Mark this node as the root of a subtree. It may be joined with its
1179     // successors later.
1180     R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1181     RootData RData(SU->NodeNum);
1182     RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
1183 
1184     // If any predecessors are still in their own subtree, they either cannot be
1185     // joined or are large enough to remain separate. If this parent node's
1186     // total instruction count is not greater than a child subtree by at least
1187     // the subtree limit, then try to join it now since splitting subtrees is
1188     // only useful if multiple high-pressure paths are possible.
1189     unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
1190     for (const SDep &PredDep : SU->Preds) {
1191       if (PredDep.getKind() != SDep::Data)
1192         continue;
1193       unsigned PredNum = PredDep.getSUnit()->NodeNum;
1194       if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
1195         joinPredSubtree(PredDep, SU, /*CheckLimit=*/false);
1196 
1197       // Either link or merge the TreeData entry from the child to the parent.
1198       if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1199         // If the predecessor's parent is invalid, this is a tree edge and the
1200         // current node is the parent.
1201         if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1202           RootSet[PredNum].ParentNodeID = SU->NodeNum;
1203       }
1204       else if (RootSet.count(PredNum)) {
1205         // The predecessor is not a root, but is still in the root set. This
1206         // must be the new parent that it was just joined to. Note that
1207         // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1208         // set to the original parent.
1209         RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1210         RootSet.erase(PredNum);
1211       }
1212     }
1213     RootSet[SU->NodeNum] = RData;
1214   }
1215 
1216   /// Called once for each tree edge after calling visitPostOrderNode on
1217   /// the predecessor. Increment the parent node's instruction count and
1218   /// preemptively join this subtree to its parent's if it is small enough.
1219   void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1220     R.DFSNodeData[Succ->NodeNum].InstrCount
1221       += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1222     joinPredSubtree(PredDep, Succ);
1223   }
1224 
1225   /// Adds a connection for cross edges.
1226   void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
1227     ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1228   }
1229 
1230   /// Sets each node's subtree ID to the representative ID and record
1231   /// connections between trees.
1232   void finalize() {
1233     SubtreeClasses.compress();
1234     R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1235     assert(SubtreeClasses.getNumClasses() == RootSet.size()
1236            && "number of roots should match trees");
1237     for (const RootData &Root : RootSet) {
1238       unsigned TreeID = SubtreeClasses[Root.NodeID];
1239       if (Root.ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1240         R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[Root.ParentNodeID];
1241       R.DFSTreeData[TreeID].SubInstrCount = Root.SubInstrCount;
1242       // Note that SubInstrCount may be greater than InstrCount if we joined
1243       // subtrees across a cross edge. InstrCount will be attributed to the
1244       // original parent, while SubInstrCount will be attributed to the joined
1245       // parent.
1246     }
1247     R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1248     R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1249     LLVM_DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
1250     for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1251       R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
1252       LLVM_DEBUG(dbgs() << "  SU(" << Idx << ") in tree "
1253                         << R.DFSNodeData[Idx].SubtreeID << '\n');
1254     }
1255     for (const std::pair<const SUnit*, const SUnit*> &P : ConnectionPairs) {
1256       unsigned PredTree = SubtreeClasses[P.first->NodeNum];
1257       unsigned SuccTree = SubtreeClasses[P.second->NodeNum];
1258       if (PredTree == SuccTree)
1259         continue;
1260       unsigned Depth = P.first->getDepth();
1261       addConnection(PredTree, SuccTree, Depth);
1262       addConnection(SuccTree, PredTree, Depth);
1263     }
1264   }
1265 
1266 protected:
1267   /// Joins the predecessor subtree with the successor that is its DFS parent.
1268   /// Applies some heuristics before joining.
1269   bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1270                        bool CheckLimit = true) {
1271     assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1272 
1273     // Check if the predecessor is already joined.
1274     const SUnit *PredSU = PredDep.getSUnit();
1275     unsigned PredNum = PredSU->NodeNum;
1276     if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
1277       return false;
1278 
1279     // Four is the magic number of successors before a node is considered a
1280     // pinch point.
1281     unsigned NumDataSucs = 0;
1282     for (const SDep &SuccDep : PredSU->Succs) {
1283       if (SuccDep.getKind() == SDep::Data) {
1284         if (++NumDataSucs >= 4)
1285           return false;
1286       }
1287     }
1288     if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
1289       return false;
1290     R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
1291     SubtreeClasses.join(Succ->NodeNum, PredNum);
1292     return true;
1293   }
1294 
1295   /// Called by finalize() to record a connection between trees.
1296   void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1297     if (!Depth)
1298       return;
1299 
1300     do {
1301       SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1302         R.SubtreeConnections[FromTree];
1303       for (SchedDFSResult::Connection &C : Connections) {
1304         if (C.TreeID == ToTree) {
1305           C.Level = std::max(C.Level, Depth);
1306           return;
1307         }
1308       }
1309       Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1310       FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1311     } while (FromTree != SchedDFSResult::InvalidSubtreeID);
1312   }
1313 };
1314 
1315 } // end namespace llvm
1316 
1317 namespace {
1318 
1319 /// Manage the stack used by a reverse depth-first search over the DAG.
1320 class SchedDAGReverseDFS {
1321   std::vector<std::pair<const SUnit *, SUnit::const_pred_iterator>> DFSStack;
1322 
1323 public:
1324   bool isComplete() const { return DFSStack.empty(); }
1325 
1326   void follow(const SUnit *SU) {
1327     DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1328   }
1329   void advance() { ++DFSStack.back().second; }
1330 
1331   const SDep *backtrack() {
1332     DFSStack.pop_back();
1333     return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
1334   }
1335 
1336   const SUnit *getCurr() const { return DFSStack.back().first; }
1337 
1338   SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1339 
1340   SUnit::const_pred_iterator getPredEnd() const {
1341     return getCurr()->Preds.end();
1342   }
1343 };
1344 
1345 } // end anonymous namespace
1346 
1347 static bool hasDataSucc(const SUnit *SU) {
1348   for (const SDep &SuccDep : SU->Succs) {
1349     if (SuccDep.getKind() == SDep::Data &&
1350         !SuccDep.getSUnit()->isBoundaryNode())
1351       return true;
1352   }
1353   return false;
1354 }
1355 
1356 /// Computes an ILP metric for all nodes in the subDAG reachable via depth-first
1357 /// search from this root.
1358 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
1359   if (!IsBottomUp)
1360     llvm_unreachable("Top-down ILP metric is unimplemented");
1361 
1362   SchedDFSImpl Impl(*this);
1363   for (const SUnit &SU : SUnits) {
1364     if (Impl.isVisited(&SU) || hasDataSucc(&SU))
1365       continue;
1366 
1367     SchedDAGReverseDFS DFS;
1368     Impl.visitPreorder(&SU);
1369     DFS.follow(&SU);
1370     while (true) {
1371       // Traverse the leftmost path as far as possible.
1372       while (DFS.getPred() != DFS.getPredEnd()) {
1373         const SDep &PredDep = *DFS.getPred();
1374         DFS.advance();
1375         // Ignore non-data edges.
1376         if (PredDep.getKind() != SDep::Data
1377             || PredDep.getSUnit()->isBoundaryNode()) {
1378           continue;
1379         }
1380         // An already visited edge is a cross edge, assuming an acyclic DAG.
1381         if (Impl.isVisited(PredDep.getSUnit())) {
1382           Impl.visitCrossEdge(PredDep, DFS.getCurr());
1383           continue;
1384         }
1385         Impl.visitPreorder(PredDep.getSUnit());
1386         DFS.follow(PredDep.getSUnit());
1387       }
1388       // Visit the top of the stack in postorder and backtrack.
1389       const SUnit *Child = DFS.getCurr();
1390       const SDep *PredDep = DFS.backtrack();
1391       Impl.visitPostorderNode(Child);
1392       if (PredDep)
1393         Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
1394       if (DFS.isComplete())
1395         break;
1396     }
1397   }
1398   Impl.finalize();
1399 }
1400 
1401 /// The root of the given SubtreeID was just scheduled. For all subtrees
1402 /// connected to this tree, record the depth of the connection so that the
1403 /// nearest connected subtrees can be prioritized.
1404 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1405   for (const Connection &C : SubtreeConnections[SubtreeID]) {
1406     SubtreeConnectLevels[C.TreeID] =
1407       std::max(SubtreeConnectLevels[C.TreeID], C.Level);
1408     LLVM_DEBUG(dbgs() << "  Tree: " << C.TreeID << " @"
1409                       << SubtreeConnectLevels[C.TreeID] << '\n');
1410   }
1411 }
1412 
1413 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1414 LLVM_DUMP_METHOD void ILPValue::print(raw_ostream &OS) const {
1415   OS << InstrCount << " / " << Length << " = ";
1416   if (!Length)
1417     OS << "BADILP";
1418   else
1419     OS << format("%g", ((double)InstrCount / Length));
1420 }
1421 
1422 LLVM_DUMP_METHOD void ILPValue::dump() const {
1423   dbgs() << *this << '\n';
1424 }
1425 
1426 namespace llvm {
1427 
1428 LLVM_DUMP_METHOD
1429 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1430   Val.print(OS);
1431   return OS;
1432 }
1433 
1434 } // end namespace llvm
1435 
1436 #endif
1437