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