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 /// Returns true if the two MIs need a chain edge between them.
541 /// This is called on normal stores and loads.
542 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
543                              const DataLayout &DL, MachineInstr *MIa,
544                              MachineInstr *MIb) {
545   const MachineFunction *MF = MIa->getParent()->getParent();
546   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
547 
548   assert ((MIa->mayStore() || MIb->mayStore()) &&
549           "Dependency checked between two loads");
550 
551   // Let the target decide if memory accesses cannot possibly overlap.
552   if (TII->areMemAccessesTriviallyDisjoint(*MIa, *MIb, AA))
553     return false;
554 
555   // To this point analysis is generic. From here on we do need AA.
556   if (!AA)
557     return true;
558 
559   // FIXME: Need to handle multiple memory operands to support all targets.
560   if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
561     return true;
562 
563   MachineMemOperand *MMOa = *MIa->memoperands_begin();
564   MachineMemOperand *MMOb = *MIb->memoperands_begin();
565 
566   if (!MMOa->getValue() || !MMOb->getValue())
567     return true;
568 
569   // The following interface to AA is fashioned after DAGCombiner::isAlias
570   // and operates with MachineMemOperand offset with some important
571   // assumptions:
572   //   - LLVM fundamentally assumes flat address spaces.
573   //   - MachineOperand offset can *only* result from legalization and
574   //     cannot affect queries other than the trivial case of overlap
575   //     checking.
576   //   - These offsets never wrap and never step outside
577   //     of allocated objects.
578   //   - There should never be any negative offsets here.
579   //
580   // FIXME: Modify API to hide this math from "user"
581   // FIXME: Even before we go to AA we can reason locally about some
582   // memory objects. It can save compile time, and possibly catch some
583   // corner cases not currently covered.
584 
585   assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
586   assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
587 
588   int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
589   int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
590   int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
591 
592   AliasResult AAResult =
593       AA->alias(MemoryLocation(MMOa->getValue(), Overlapa,
594                                UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
595                 MemoryLocation(MMOb->getValue(), Overlapb,
596                                UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
597 
598   return (AAResult != NoAlias);
599 }
600 
601 void ScheduleDAGInstrs::addChainDependency (SUnit *SUa, SUnit *SUb,
602                                             unsigned Latency) {
603   if (MIsNeedChainEdge(AAForDep, &MFI, MF.getDataLayout(), SUa->getInstr(),
604                        SUb->getInstr())) {
605     SDep Dep(SUa, SDep::MayAliasMem);
606     Dep.setLatency(Latency);
607     SUb->addPred(Dep);
608   }
609 }
610 
611 /// \brief Creates an SUnit for each real instruction, numbered in top-down
612 /// topological order. The instruction order A < B, implies that no edge exists
613 /// from B to A.
614 ///
615 /// Map each real instruction to its SUnit.
616 ///
617 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
618 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
619 /// instead of pointers.
620 ///
621 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
622 /// the original instruction list.
623 void ScheduleDAGInstrs::initSUnits() {
624   // We'll be allocating one SUnit for each real instruction in the region,
625   // which is contained within a basic block.
626   SUnits.reserve(NumRegionInstrs);
627 
628   for (MachineInstr &MI : llvm::make_range(RegionBegin, RegionEnd)) {
629     if (MI.isDebugValue())
630       continue;
631 
632     SUnit *SU = newSUnit(&MI);
633     MISUnitMap[&MI] = SU;
634 
635     SU->isCall = MI.isCall();
636     SU->isCommutable = MI.isCommutable();
637 
638     // Assign the Latency field of SU using target-provided information.
639     SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
640 
641     // If this SUnit uses a reserved or unbuffered resource, mark it as such.
642     //
643     // Reserved resources block an instruction from issuing and stall the
644     // entire pipeline. These are identified by BufferSize=0.
645     //
646     // Unbuffered resources prevent execution of subsequent instructions that
647     // require the same resources. This is used for in-order execution pipelines
648     // within an out-of-order core. These are identified by BufferSize=1.
649     if (SchedModel.hasInstrSchedModel()) {
650       const MCSchedClassDesc *SC = getSchedClass(SU);
651       for (const MCWriteProcResEntry &PRE :
652            make_range(SchedModel.getWriteProcResBegin(SC),
653                       SchedModel.getWriteProcResEnd(SC))) {
654         switch (SchedModel.getProcResource(PRE.ProcResourceIdx)->BufferSize) {
655         case 0:
656           SU->hasReservedResource = true;
657           break;
658         case 1:
659           SU->isUnbuffered = true;
660           break;
661         default:
662           break;
663         }
664       }
665     }
666   }
667 }
668 
669 class ScheduleDAGInstrs::Value2SUsMap : public MapVector<ValueType, SUList> {
670   /// Current total number of SUs in map.
671   unsigned NumNodes;
672 
673   /// 1 for loads, 0 for stores. (see comment in SUList)
674   unsigned TrueMemOrderLatency;
675 
676 public:
677   Value2SUsMap(unsigned lat = 0) : NumNodes(0), TrueMemOrderLatency(lat) {}
678 
679   /// To keep NumNodes up to date, insert() is used instead of
680   /// this operator w/ push_back().
681   ValueType &operator[](const SUList &Key) {
682     llvm_unreachable("Don't use. Use insert() instead."); };
683 
684   /// Adds SU to the SUList of V. If Map grows huge, reduce its size by calling
685   /// reduce().
686   void inline insert(SUnit *SU, ValueType V) {
687     MapVector::operator[](V).push_back(SU);
688     NumNodes++;
689   }
690 
691   /// Clears the list of SUs mapped to V.
692   void inline clearList(ValueType V) {
693     iterator Itr = find(V);
694     if (Itr != end()) {
695       assert (NumNodes >= Itr->second.size());
696       NumNodes -= Itr->second.size();
697 
698       Itr->second.clear();
699     }
700   }
701 
702   /// Clears map from all contents.
703   void clear() {
704     MapVector<ValueType, SUList>::clear();
705     NumNodes = 0;
706   }
707 
708   unsigned inline size() const { return NumNodes; }
709 
710   /// Counts the number of SUs in this map after a reduction.
711   void reComputeSize(void) {
712     NumNodes = 0;
713     for (auto &I : *this)
714       NumNodes += I.second.size();
715   }
716 
717   unsigned inline getTrueMemOrderLatency() const {
718     return TrueMemOrderLatency;
719   }
720 
721   void dump();
722 };
723 
724 void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
725                                              Value2SUsMap &Val2SUsMap) {
726   for (auto &I : Val2SUsMap)
727     addChainDependencies(SU, I.second,
728                          Val2SUsMap.getTrueMemOrderLatency());
729 }
730 
731 void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
732                                              Value2SUsMap &Val2SUsMap,
733                                              ValueType V) {
734   Value2SUsMap::iterator Itr = Val2SUsMap.find(V);
735   if (Itr != Val2SUsMap.end())
736     addChainDependencies(SU, Itr->second,
737                          Val2SUsMap.getTrueMemOrderLatency());
738 }
739 
740 void ScheduleDAGInstrs::addBarrierChain(Value2SUsMap &map) {
741   assert (BarrierChain != nullptr);
742 
743   for (auto &I : map) {
744     SUList &sus = I.second;
745     for (auto *SU : sus)
746       SU->addPredBarrier(BarrierChain);
747   }
748   map.clear();
749 }
750 
751 void ScheduleDAGInstrs::insertBarrierChain(Value2SUsMap &map) {
752   assert (BarrierChain != nullptr);
753 
754   // Go through all lists of SUs.
755   for (Value2SUsMap::iterator I = map.begin(), EE = map.end(); I != EE;) {
756     Value2SUsMap::iterator CurrItr = I++;
757     SUList &sus = CurrItr->second;
758     SUList::iterator SUItr = sus.begin(), SUEE = sus.end();
759     for (; SUItr != SUEE; ++SUItr) {
760       // Stop on BarrierChain or any instruction above it.
761       if ((*SUItr)->NodeNum <= BarrierChain->NodeNum)
762         break;
763 
764       (*SUItr)->addPredBarrier(BarrierChain);
765     }
766 
767     // Remove also the BarrierChain from list if present.
768     if (SUItr != SUEE && *SUItr == BarrierChain)
769       SUItr++;
770 
771     // Remove all SUs that are now successors of BarrierChain.
772     if (SUItr != sus.begin())
773       sus.erase(sus.begin(), SUItr);
774   }
775 
776   // Remove all entries with empty su lists.
777   map.remove_if([&](std::pair<ValueType, SUList> &mapEntry) {
778       return (mapEntry.second.empty()); });
779 
780   // Recompute the size of the map (NumNodes).
781   map.reComputeSize();
782 }
783 
784 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
785                                         RegPressureTracker *RPTracker,
786                                         PressureDiffs *PDiffs,
787                                         LiveIntervals *LIS,
788                                         bool TrackLaneMasks) {
789   const TargetSubtargetInfo &ST = MF.getSubtarget();
790   bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
791                                                        : ST.useAA();
792   AAForDep = UseAA ? AA : nullptr;
793 
794   BarrierChain = nullptr;
795 
796   this->TrackLaneMasks = TrackLaneMasks;
797   MISUnitMap.clear();
798   ScheduleDAG::clearDAG();
799 
800   // Create an SUnit for each real instruction.
801   initSUnits();
802 
803   if (PDiffs)
804     PDiffs->init(SUnits.size());
805 
806   // We build scheduling units by walking a block's instruction list
807   // from bottom to top.
808 
809   // Each MIs' memory operand(s) is analyzed to a list of underlying
810   // objects. The SU is then inserted in the SUList(s) mapped from the
811   // Value(s). Each Value thus gets mapped to lists of SUs depending
812   // on it, stores and loads kept separately. Two SUs are trivially
813   // non-aliasing if they both depend on only identified Values and do
814   // not share any common Value.
815   Value2SUsMap Stores, Loads(1 /*TrueMemOrderLatency*/);
816 
817   // Certain memory accesses are known to not alias any SU in Stores
818   // or Loads, and have therefore their own 'NonAlias'
819   // domain. E.g. spill / reload instructions never alias LLVM I/R
820   // Values. It would be nice to assume that this type of memory
821   // accesses always have a proper memory operand modelling, and are
822   // therefore never unanalyzable, but this is conservatively not
823   // done.
824   Value2SUsMap NonAliasStores, NonAliasLoads(1 /*TrueMemOrderLatency*/);
825 
826   // Remove any stale debug info; sometimes BuildSchedGraph is called again
827   // without emitting the info from the previous call.
828   DbgValues.clear();
829   FirstDbgValue = nullptr;
830 
831   assert(Defs.empty() && Uses.empty() &&
832          "Only BuildGraph should update Defs/Uses");
833   Defs.setUniverse(TRI->getNumRegs());
834   Uses.setUniverse(TRI->getNumRegs());
835 
836   assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
837   assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
838   unsigned NumVirtRegs = MRI.getNumVirtRegs();
839   CurrentVRegDefs.setUniverse(NumVirtRegs);
840   CurrentVRegUses.setUniverse(NumVirtRegs);
841 
842   // Model data dependencies between instructions being scheduled and the
843   // ExitSU.
844   addSchedBarrierDeps();
845 
846   // Walk the list of instructions, from bottom moving up.
847   MachineInstr *DbgMI = nullptr;
848   for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
849        MII != MIE; --MII) {
850     MachineInstr &MI = *std::prev(MII);
851     if (DbgMI) {
852       DbgValues.push_back(std::make_pair(DbgMI, &MI));
853       DbgMI = nullptr;
854     }
855 
856     if (MI.isDebugValue()) {
857       DbgMI = &MI;
858       continue;
859     }
860     SUnit *SU = MISUnitMap[&MI];
861     assert(SU && "No SUnit mapped to this MI");
862 
863     if (RPTracker) {
864       RegisterOperands RegOpers;
865       RegOpers.collect(MI, *TRI, MRI, TrackLaneMasks, false);
866       if (TrackLaneMasks) {
867         SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
868         RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx);
869       }
870       if (PDiffs != nullptr)
871         PDiffs->addInstruction(SU->NodeNum, RegOpers, MRI);
872 
873       RPTracker->recedeSkipDebugValues();
874       assert(&*RPTracker->getPos() == &MI && "RPTracker in sync");
875       RPTracker->recede(RegOpers);
876     }
877 
878     assert(
879         (CanHandleTerminators || (!MI.isTerminator() && !MI.isPosition())) &&
880         "Cannot schedule terminators or labels!");
881 
882     // Add register-based dependencies (data, anti, and output).
883     // For some instructions (calls, returns, inline-asm, etc.) there can
884     // be explicit uses and implicit defs, in which case the use will appear
885     // on the operand list before the def. Do two passes over the operand
886     // list to make sure that defs are processed before any uses.
887     bool HasVRegDef = false;
888     for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
889       const MachineOperand &MO = MI.getOperand(j);
890       if (!MO.isReg() || !MO.isDef())
891         continue;
892       unsigned Reg = MO.getReg();
893       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
894         addPhysRegDeps(SU, j);
895       } else if (TargetRegisterInfo::isVirtualRegister(Reg)) {
896         HasVRegDef = true;
897         addVRegDefDeps(SU, j);
898       }
899     }
900     // Now process all uses.
901     for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
902       const MachineOperand &MO = MI.getOperand(j);
903       // Only look at use operands.
904       // We do not need to check for MO.readsReg() here because subsequent
905       // subregister defs will get output dependence edges and need no
906       // additional use dependencies.
907       if (!MO.isReg() || !MO.isUse())
908         continue;
909       unsigned Reg = MO.getReg();
910       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
911         addPhysRegDeps(SU, j);
912       } else if (TargetRegisterInfo::isVirtualRegister(Reg) && MO.readsReg()) {
913         addVRegUseDeps(SU, j);
914       }
915     }
916 
917     // If we haven't seen any uses in this scheduling region, create a
918     // dependence edge to ExitSU to model the live-out latency. This is required
919     // for vreg defs with no in-region use, and prefetches with no vreg def.
920     //
921     // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
922     // check currently relies on being called before adding chain deps.
923     if (SU->NumSuccs == 0 && SU->Latency > 1 && (HasVRegDef || MI.mayLoad())) {
924       SDep Dep(SU, SDep::Artificial);
925       Dep.setLatency(SU->Latency - 1);
926       ExitSU.addPred(Dep);
927     }
928 
929     // Add memory dependencies (Note: isStoreToStackSlot and
930     // isLoadFromStackSLot are not usable after stack slots are lowered to
931     // actual addresses).
932 
933     // This is a barrier event that acts as a pivotal node in the DAG.
934     if (isGlobalMemoryObject(AA, &MI)) {
935 
936       // Become the barrier chain.
937       if (BarrierChain)
938         BarrierChain->addPredBarrier(SU);
939       BarrierChain = SU;
940 
941       DEBUG(dbgs() << "Global memory object and new barrier chain: SU("
942             << BarrierChain->NodeNum << ").\n";);
943 
944       // Add dependencies against everything below it and clear maps.
945       addBarrierChain(Stores);
946       addBarrierChain(Loads);
947       addBarrierChain(NonAliasStores);
948       addBarrierChain(NonAliasLoads);
949 
950       continue;
951     }
952 
953     // If it's not a store or a variant load, we're done.
954     if (!MI.mayStore() &&
955         !(MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA)))
956       continue;
957 
958     // Always add dependecy edge to BarrierChain if present.
959     if (BarrierChain)
960       BarrierChain->addPredBarrier(SU);
961 
962     // Find the underlying objects for MI. The Objs vector is either
963     // empty, or filled with the Values of memory locations which this
964     // SU depends on. An empty vector means the memory location is
965     // unknown, and may alias anything.
966     UnderlyingObjectsVector Objs;
967     getUnderlyingObjectsForInstr(&MI, MFI, Objs, MF.getDataLayout());
968 
969     if (MI.mayStore()) {
970       if (Objs.empty()) {
971         // An unknown store depends on all stores and loads.
972         addChainDependencies(SU, Stores);
973         addChainDependencies(SU, NonAliasStores);
974         addChainDependencies(SU, Loads);
975         addChainDependencies(SU, NonAliasLoads);
976 
977         // Map this store to 'UnknownValue'.
978         Stores.insert(SU, UnknownValue);
979       } else {
980         // Add precise dependencies against all previously seen memory
981         // accesses mapped to the same Value(s).
982         for (const UnderlyingObject &UnderlObj : Objs) {
983           ValueType V = UnderlObj.getValue();
984           bool ThisMayAlias = UnderlObj.mayAlias();
985 
986           // Add dependencies to previous stores and loads mapped to V.
987           addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
988           addChainDependencies(SU, (ThisMayAlias ? Loads : NonAliasLoads), V);
989         }
990         // Update the store map after all chains have been added to avoid adding
991         // self-loop edge if multiple underlying objects are present.
992         for (const UnderlyingObject &UnderlObj : Objs) {
993           ValueType V = UnderlObj.getValue();
994           bool ThisMayAlias = UnderlObj.mayAlias();
995 
996           // Map this store to V.
997           (ThisMayAlias ? Stores : NonAliasStores).insert(SU, V);
998         }
999         // The store may have dependencies to unanalyzable loads and
1000         // stores.
1001         addChainDependencies(SU, Loads, UnknownValue);
1002         addChainDependencies(SU, Stores, UnknownValue);
1003       }
1004     } else { // SU is a load.
1005       if (Objs.empty()) {
1006         // An unknown load depends on all stores.
1007         addChainDependencies(SU, Stores);
1008         addChainDependencies(SU, NonAliasStores);
1009 
1010         Loads.insert(SU, UnknownValue);
1011       } else {
1012         for (const UnderlyingObject &UnderlObj : Objs) {
1013           ValueType V = UnderlObj.getValue();
1014           bool ThisMayAlias = UnderlObj.mayAlias();
1015 
1016           // Add precise dependencies against all previously seen stores
1017           // mapping to the same Value(s).
1018           addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
1019 
1020           // Map this load to V.
1021           (ThisMayAlias ? Loads : NonAliasLoads).insert(SU, V);
1022         }
1023         // The load may have dependencies to unanalyzable stores.
1024         addChainDependencies(SU, Stores, UnknownValue);
1025       }
1026     }
1027 
1028     // Reduce maps if they grow huge.
1029     if (Stores.size() + Loads.size() >= HugeRegion) {
1030       DEBUG(dbgs() << "Reducing Stores and Loads maps.\n";);
1031       reduceHugeMemNodeMaps(Stores, Loads, getReductionSize());
1032     }
1033     if (NonAliasStores.size() + NonAliasLoads.size() >= HugeRegion) {
1034       DEBUG(dbgs() << "Reducing NonAliasStores and NonAliasLoads maps.\n";);
1035       reduceHugeMemNodeMaps(NonAliasStores, NonAliasLoads, getReductionSize());
1036     }
1037   }
1038 
1039   if (DbgMI)
1040     FirstDbgValue = DbgMI;
1041 
1042   Defs.clear();
1043   Uses.clear();
1044   CurrentVRegDefs.clear();
1045   CurrentVRegUses.clear();
1046 }
1047 
1048 raw_ostream &llvm::operator<<(raw_ostream &OS, const PseudoSourceValue* PSV) {
1049   PSV->printCustom(OS);
1050   return OS;
1051 }
1052 
1053 void ScheduleDAGInstrs::Value2SUsMap::dump() {
1054   for (auto &Itr : *this) {
1055     if (Itr.first.is<const Value*>()) {
1056       const Value *V = Itr.first.get<const Value*>();
1057       if (isa<UndefValue>(V))
1058         dbgs() << "Unknown";
1059       else
1060         V->printAsOperand(dbgs());
1061     }
1062     else if (Itr.first.is<const PseudoSourceValue*>())
1063       dbgs() <<  Itr.first.get<const PseudoSourceValue*>();
1064     else
1065       llvm_unreachable("Unknown Value type.");
1066 
1067     dbgs() << " : ";
1068     dumpSUList(Itr.second);
1069   }
1070 }
1071 
1072 void ScheduleDAGInstrs::reduceHugeMemNodeMaps(Value2SUsMap &stores,
1073                                               Value2SUsMap &loads, unsigned N) {
1074   DEBUG(dbgs() << "Before reduction:\nStoring SUnits:\n";
1075         stores.dump();
1076         dbgs() << "Loading SUnits:\n";
1077         loads.dump());
1078 
1079   // Insert all SU's NodeNums into a vector and sort it.
1080   std::vector<unsigned> NodeNums;
1081   NodeNums.reserve(stores.size() + loads.size());
1082   for (auto &I : stores)
1083     for (auto *SU : I.second)
1084       NodeNums.push_back(SU->NodeNum);
1085   for (auto &I : loads)
1086     for (auto *SU : I.second)
1087       NodeNums.push_back(SU->NodeNum);
1088   std::sort(NodeNums.begin(), NodeNums.end());
1089 
1090   // The N last elements in NodeNums will be removed, and the SU with
1091   // the lowest NodeNum of them will become the new BarrierChain to
1092   // let the not yet seen SUs have a dependency to the removed SUs.
1093   assert (N <= NodeNums.size());
1094   SUnit *newBarrierChain = &SUnits[*(NodeNums.end() - N)];
1095   if (BarrierChain) {
1096     // The aliasing and non-aliasing maps reduce independently of each
1097     // other, but share a common BarrierChain. Check if the
1098     // newBarrierChain is above the former one. If it is not, it may
1099     // introduce a loop to use newBarrierChain, so keep the old one.
1100     if (newBarrierChain->NodeNum < BarrierChain->NodeNum) {
1101       BarrierChain->addPredBarrier(newBarrierChain);
1102       BarrierChain = newBarrierChain;
1103       DEBUG(dbgs() << "Inserting new barrier chain: SU("
1104             << BarrierChain->NodeNum << ").\n";);
1105     }
1106     else
1107       DEBUG(dbgs() << "Keeping old barrier chain: SU("
1108             << BarrierChain->NodeNum << ").\n";);
1109   }
1110   else
1111     BarrierChain = newBarrierChain;
1112 
1113   insertBarrierChain(stores);
1114   insertBarrierChain(loads);
1115 
1116   DEBUG(dbgs() << "After reduction:\nStoring SUnits:\n";
1117         stores.dump();
1118         dbgs() << "Loading SUnits:\n";
1119         loads.dump());
1120 }
1121 
1122 void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) {
1123   // Start with no live registers.
1124   LiveRegs.reset();
1125 
1126   // Examine the live-in regs of all successors.
1127   for (const MachineBasicBlock *Succ : BB->successors()) {
1128     for (const auto &LI : Succ->liveins()) {
1129       // Repeat, for reg and all subregs.
1130       for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
1131            SubRegs.isValid(); ++SubRegs)
1132         LiveRegs.set(*SubRegs);
1133     }
1134   }
1135 }
1136 
1137 /// \brief If we change a kill flag on the bundle instruction implicit register
1138 /// operands, then we also need to propagate that to any instructions inside
1139 /// the bundle which had the same kill state.
1140 static void toggleBundleKillFlag(MachineInstr *MI, unsigned Reg,
1141                                  bool NewKillState,
1142                                  const TargetRegisterInfo *TRI) {
1143   if (MI->getOpcode() != TargetOpcode::BUNDLE)
1144     return;
1145 
1146   // Walk backwards from the last instruction in the bundle to the first.
1147   // Once we set a kill flag on an instruction, we bail out, as otherwise we
1148   // might set it on too many operands.  We will clear as many flags as we
1149   // can though.
1150   MachineBasicBlock::instr_iterator Begin = MI->getIterator();
1151   MachineBasicBlock::instr_iterator End = getBundleEnd(Begin);
1152   while (Begin != End) {
1153     if (NewKillState) {
1154       if ((--End)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
1155          return;
1156     } else
1157       (--End)->clearRegisterKills(Reg, TRI);
1158   }
1159 }
1160 
1161 void ScheduleDAGInstrs::toggleKillFlag(MachineInstr &MI, MachineOperand &MO) {
1162   if (MO.isDebug())
1163     return;
1164 
1165   // Setting kill flag...
1166   if (!MO.isKill()) {
1167     MO.setIsKill(true);
1168     toggleBundleKillFlag(&MI, MO.getReg(), true, TRI);
1169     return;
1170   }
1171 
1172   // If MO itself is live, clear the kill flag...
1173   if (LiveRegs.test(MO.getReg())) {
1174     MO.setIsKill(false);
1175     toggleBundleKillFlag(&MI, MO.getReg(), false, TRI);
1176     return;
1177   }
1178 
1179   // If any subreg of MO is live, then create an imp-def for that
1180   // subreg and keep MO marked as killed.
1181   MO.setIsKill(false);
1182   toggleBundleKillFlag(&MI, MO.getReg(), false, TRI);
1183   bool AllDead = true;
1184   const unsigned SuperReg = MO.getReg();
1185   MachineInstrBuilder MIB(MF, &MI);
1186   for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
1187     if (LiveRegs.test(*SubRegs)) {
1188       MIB.addReg(*SubRegs, RegState::ImplicitDefine);
1189       AllDead = false;
1190     }
1191   }
1192 
1193   if(AllDead) {
1194     MO.setIsKill(true);
1195     toggleBundleKillFlag(&MI, MO.getReg(), true, TRI);
1196   }
1197 }
1198 
1199 void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) {
1200   // FIXME: Reuse the LivePhysRegs utility for this.
1201   DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
1202 
1203   LiveRegs.resize(TRI->getNumRegs());
1204   BitVector killedRegs(TRI->getNumRegs());
1205 
1206   startBlockForKills(MBB);
1207 
1208   // Examine block from end to start...
1209   unsigned Count = MBB->size();
1210   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
1211        I != E; --Count) {
1212     MachineInstr &MI = *--I;
1213     if (MI.isDebugValue())
1214       continue;
1215 
1216     // Update liveness.  Registers that are defed but not used in this
1217     // instruction are now dead. Mark register and all subregs as they
1218     // are completely defined.
1219     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1220       MachineOperand &MO = MI.getOperand(i);
1221       if (MO.isRegMask())
1222         LiveRegs.clearBitsNotInMask(MO.getRegMask());
1223       if (!MO.isReg()) continue;
1224       unsigned Reg = MO.getReg();
1225       if (Reg == 0) continue;
1226       if (!MO.isDef()) continue;
1227       // Ignore two-addr defs.
1228       if (MI.isRegTiedToUseOperand(i)) continue;
1229 
1230       // Repeat for reg and all subregs.
1231       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1232            SubRegs.isValid(); ++SubRegs)
1233         LiveRegs.reset(*SubRegs);
1234     }
1235 
1236     // Examine all used registers and set/clear kill flag. When a
1237     // register is used multiple times we only set the kill flag on
1238     // the first use. Don't set kill flags on undef operands.
1239     killedRegs.reset();
1240 
1241     // toggleKillFlag can append new operands (implicit defs), so using
1242     // a range-based loop is not safe. The new operands will be appended
1243     // at the end of the operand list and they don't need to be visited,
1244     // so iterating until the currently last operand is ok.
1245     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1246       MachineOperand &MO = MI.getOperand(i);
1247       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1248       unsigned Reg = MO.getReg();
1249       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1250 
1251       bool kill = false;
1252       if (!killedRegs.test(Reg)) {
1253         kill = true;
1254         // A register is not killed if any subregs are live...
1255         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
1256           if (LiveRegs.test(*SubRegs)) {
1257             kill = false;
1258             break;
1259           }
1260         }
1261 
1262         // If subreg is not live, then register is killed if it became
1263         // live in this instruction
1264         if (kill)
1265           kill = !LiveRegs.test(Reg);
1266       }
1267 
1268       if (MO.isKill() != kill) {
1269         DEBUG(dbgs() << "Fixing " << MO << " in ");
1270         toggleKillFlag(MI, MO);
1271         DEBUG(MI.dump());
1272         DEBUG({
1273           if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1274             MachineBasicBlock::instr_iterator Begin = MI.getIterator();
1275             MachineBasicBlock::instr_iterator End = getBundleEnd(Begin);
1276             while (++Begin != End)
1277               DEBUG(Begin->dump());
1278           }
1279         });
1280       }
1281 
1282       killedRegs.set(Reg);
1283     }
1284 
1285     // Mark any used register (that is not using undef) and subregs as
1286     // now live...
1287     for (const MachineOperand &MO : MI.operands()) {
1288       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1289       unsigned Reg = MO.getReg();
1290       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1291 
1292       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1293            SubRegs.isValid(); ++SubRegs)
1294         LiveRegs.set(*SubRegs);
1295     }
1296   }
1297 }
1298 
1299 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
1300   // Cannot completely remove virtual function even in release mode.
1301 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1302   SU->getInstr()->dump();
1303 #endif
1304 }
1305 
1306 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1307   std::string s;
1308   raw_string_ostream oss(s);
1309   if (SU == &EntrySU)
1310     oss << "<entry>";
1311   else if (SU == &ExitSU)
1312     oss << "<exit>";
1313   else
1314     SU->getInstr()->print(oss, /*SkipOpers=*/true);
1315   return oss.str();
1316 }
1317 
1318 /// Return the basic block label. It is not necessarilly unique because a block
1319 /// contains multiple scheduling regions. But it is fine for visualization.
1320 std::string ScheduleDAGInstrs::getDAGName() const {
1321   return "dag." + BB->getFullName();
1322 }
1323 
1324 //===----------------------------------------------------------------------===//
1325 // SchedDFSResult Implementation
1326 //===----------------------------------------------------------------------===//
1327 
1328 namespace llvm {
1329 /// Internal state used to compute SchedDFSResult.
1330 class SchedDFSImpl {
1331   SchedDFSResult &R;
1332 
1333   /// Join DAG nodes into equivalence classes by their subtree.
1334   IntEqClasses SubtreeClasses;
1335   /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1336   std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1337 
1338   struct RootData {
1339     unsigned NodeID;
1340     unsigned ParentNodeID;  ///< Parent node (member of the parent subtree).
1341     unsigned SubInstrCount; ///< Instr count in this tree only, not children.
1342 
1343     RootData(unsigned id): NodeID(id),
1344                            ParentNodeID(SchedDFSResult::InvalidSubtreeID),
1345                            SubInstrCount(0) {}
1346 
1347     unsigned getSparseSetIndex() const { return NodeID; }
1348   };
1349 
1350   SparseSet<RootData> RootSet;
1351 
1352 public:
1353   SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1354     RootSet.setUniverse(R.DFSNodeData.size());
1355   }
1356 
1357   /// Returns true if this node been visited by the DFS traversal.
1358   ///
1359   /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1360   /// ID. Later, SubtreeID is updated but remains valid.
1361   bool isVisited(const SUnit *SU) const {
1362     return R.DFSNodeData[SU->NodeNum].SubtreeID
1363       != SchedDFSResult::InvalidSubtreeID;
1364   }
1365 
1366   /// Initializes this node's instruction count. We don't need to flag the node
1367   /// visited until visitPostorder because the DAG cannot have cycles.
1368   void visitPreorder(const SUnit *SU) {
1369     R.DFSNodeData[SU->NodeNum].InstrCount =
1370       SU->getInstr()->isTransient() ? 0 : 1;
1371   }
1372 
1373   /// Called once for each node after all predecessors are visited. Revisit this
1374   /// node's predecessors and potentially join them now that we know the ILP of
1375   /// the other predecessors.
1376   void visitPostorderNode(const SUnit *SU) {
1377     // Mark this node as the root of a subtree. It may be joined with its
1378     // successors later.
1379     R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1380     RootData RData(SU->NodeNum);
1381     RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
1382 
1383     // If any predecessors are still in their own subtree, they either cannot be
1384     // joined or are large enough to remain separate. If this parent node's
1385     // total instruction count is not greater than a child subtree by at least
1386     // the subtree limit, then try to join it now since splitting subtrees is
1387     // only useful if multiple high-pressure paths are possible.
1388     unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
1389     for (const SDep &PredDep : SU->Preds) {
1390       if (PredDep.getKind() != SDep::Data)
1391         continue;
1392       unsigned PredNum = PredDep.getSUnit()->NodeNum;
1393       if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
1394         joinPredSubtree(PredDep, SU, /*CheckLimit=*/false);
1395 
1396       // Either link or merge the TreeData entry from the child to the parent.
1397       if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1398         // If the predecessor's parent is invalid, this is a tree edge and the
1399         // current node is the parent.
1400         if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1401           RootSet[PredNum].ParentNodeID = SU->NodeNum;
1402       }
1403       else if (RootSet.count(PredNum)) {
1404         // The predecessor is not a root, but is still in the root set. This
1405         // must be the new parent that it was just joined to. Note that
1406         // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1407         // set to the original parent.
1408         RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1409         RootSet.erase(PredNum);
1410       }
1411     }
1412     RootSet[SU->NodeNum] = RData;
1413   }
1414 
1415   /// \brief Called once for each tree edge after calling visitPostOrderNode on
1416   /// the predecessor. Increment the parent node's instruction count and
1417   /// preemptively join this subtree to its parent's if it is small enough.
1418   void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1419     R.DFSNodeData[Succ->NodeNum].InstrCount
1420       += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1421     joinPredSubtree(PredDep, Succ);
1422   }
1423 
1424   /// Adds a connection for cross edges.
1425   void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
1426     ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1427   }
1428 
1429   /// Sets each node's subtree ID to the representative ID and record
1430   /// connections between trees.
1431   void finalize() {
1432     SubtreeClasses.compress();
1433     R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1434     assert(SubtreeClasses.getNumClasses() == RootSet.size()
1435            && "number of roots should match trees");
1436     for (const RootData &Root : RootSet) {
1437       unsigned TreeID = SubtreeClasses[Root.NodeID];
1438       if (Root.ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1439         R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[Root.ParentNodeID];
1440       R.DFSTreeData[TreeID].SubInstrCount = Root.SubInstrCount;
1441       // Note that SubInstrCount may be greater than InstrCount if we joined
1442       // subtrees across a cross edge. InstrCount will be attributed to the
1443       // original parent, while SubInstrCount will be attributed to the joined
1444       // parent.
1445     }
1446     R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1447     R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1448     DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
1449     for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1450       R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
1451       DEBUG(dbgs() << "  SU(" << Idx << ") in tree "
1452             << R.DFSNodeData[Idx].SubtreeID << '\n');
1453     }
1454     for (const std::pair<const SUnit*, const SUnit*> &P : ConnectionPairs) {
1455       unsigned PredTree = SubtreeClasses[P.first->NodeNum];
1456       unsigned SuccTree = SubtreeClasses[P.second->NodeNum];
1457       if (PredTree == SuccTree)
1458         continue;
1459       unsigned Depth = P.first->getDepth();
1460       addConnection(PredTree, SuccTree, Depth);
1461       addConnection(SuccTree, PredTree, Depth);
1462     }
1463   }
1464 
1465 protected:
1466   /// Joins the predecessor subtree with the successor that is its DFS parent.
1467   /// Applies some heuristics before joining.
1468   bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1469                        bool CheckLimit = true) {
1470     assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1471 
1472     // Check if the predecessor is already joined.
1473     const SUnit *PredSU = PredDep.getSUnit();
1474     unsigned PredNum = PredSU->NodeNum;
1475     if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
1476       return false;
1477 
1478     // Four is the magic number of successors before a node is considered a
1479     // pinch point.
1480     unsigned NumDataSucs = 0;
1481     for (const SDep &SuccDep : PredSU->Succs) {
1482       if (SuccDep.getKind() == SDep::Data) {
1483         if (++NumDataSucs >= 4)
1484           return false;
1485       }
1486     }
1487     if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
1488       return false;
1489     R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
1490     SubtreeClasses.join(Succ->NodeNum, PredNum);
1491     return true;
1492   }
1493 
1494   /// Called by finalize() to record a connection between trees.
1495   void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1496     if (!Depth)
1497       return;
1498 
1499     do {
1500       SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1501         R.SubtreeConnections[FromTree];
1502       for (SchedDFSResult::Connection &C : Connections) {
1503         if (C.TreeID == ToTree) {
1504           C.Level = std::max(C.Level, Depth);
1505           return;
1506         }
1507       }
1508       Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1509       FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1510     } while (FromTree != SchedDFSResult::InvalidSubtreeID);
1511   }
1512 };
1513 } // end namespace llvm
1514 
1515 namespace {
1516 /// Manage the stack used by a reverse depth-first search over the DAG.
1517 class SchedDAGReverseDFS {
1518   std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1519 public:
1520   bool isComplete() const { return DFSStack.empty(); }
1521 
1522   void follow(const SUnit *SU) {
1523     DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1524   }
1525   void advance() { ++DFSStack.back().second; }
1526 
1527   const SDep *backtrack() {
1528     DFSStack.pop_back();
1529     return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
1530   }
1531 
1532   const SUnit *getCurr() const { return DFSStack.back().first; }
1533 
1534   SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1535 
1536   SUnit::const_pred_iterator getPredEnd() const {
1537     return getCurr()->Preds.end();
1538   }
1539 };
1540 } // anonymous
1541 
1542 static bool hasDataSucc(const SUnit *SU) {
1543   for (const SDep &SuccDep : SU->Succs) {
1544     if (SuccDep.getKind() == SDep::Data &&
1545         !SuccDep.getSUnit()->isBoundaryNode())
1546       return true;
1547   }
1548   return false;
1549 }
1550 
1551 /// Computes an ILP metric for all nodes in the subDAG reachable via depth-first
1552 /// search from this root.
1553 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
1554   if (!IsBottomUp)
1555     llvm_unreachable("Top-down ILP metric is unimplemnted");
1556 
1557   SchedDFSImpl Impl(*this);
1558   for (const SUnit &SU : SUnits) {
1559     if (Impl.isVisited(&SU) || hasDataSucc(&SU))
1560       continue;
1561 
1562     SchedDAGReverseDFS DFS;
1563     Impl.visitPreorder(&SU);
1564     DFS.follow(&SU);
1565     for (;;) {
1566       // Traverse the leftmost path as far as possible.
1567       while (DFS.getPred() != DFS.getPredEnd()) {
1568         const SDep &PredDep = *DFS.getPred();
1569         DFS.advance();
1570         // Ignore non-data edges.
1571         if (PredDep.getKind() != SDep::Data
1572             || PredDep.getSUnit()->isBoundaryNode()) {
1573           continue;
1574         }
1575         // An already visited edge is a cross edge, assuming an acyclic DAG.
1576         if (Impl.isVisited(PredDep.getSUnit())) {
1577           Impl.visitCrossEdge(PredDep, DFS.getCurr());
1578           continue;
1579         }
1580         Impl.visitPreorder(PredDep.getSUnit());
1581         DFS.follow(PredDep.getSUnit());
1582       }
1583       // Visit the top of the stack in postorder and backtrack.
1584       const SUnit *Child = DFS.getCurr();
1585       const SDep *PredDep = DFS.backtrack();
1586       Impl.visitPostorderNode(Child);
1587       if (PredDep)
1588         Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
1589       if (DFS.isComplete())
1590         break;
1591     }
1592   }
1593   Impl.finalize();
1594 }
1595 
1596 /// The root of the given SubtreeID was just scheduled. For all subtrees
1597 /// connected to this tree, record the depth of the connection so that the
1598 /// nearest connected subtrees can be prioritized.
1599 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1600   for (const Connection &C : SubtreeConnections[SubtreeID]) {
1601     SubtreeConnectLevels[C.TreeID] =
1602       std::max(SubtreeConnectLevels[C.TreeID], C.Level);
1603     DEBUG(dbgs() << "  Tree: " << C.TreeID
1604           << " @" << SubtreeConnectLevels[C.TreeID] << '\n');
1605   }
1606 }
1607 
1608 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1609 LLVM_DUMP_METHOD void ILPValue::print(raw_ostream &OS) const {
1610   OS << InstrCount << " / " << Length << " = ";
1611   if (!Length)
1612     OS << "BADILP";
1613   else
1614     OS << format("%g", ((double)InstrCount / Length));
1615 }
1616 
1617 LLVM_DUMP_METHOD void ILPValue::dump() const {
1618   dbgs() << *this << '\n';
1619 }
1620 
1621 namespace llvm {
1622 
1623 LLVM_DUMP_METHOD
1624 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1625   Val.print(OS);
1626   return OS;
1627 }
1628 
1629 } // end namespace llvm
1630 #endif
1631