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