LLVM 24.0.0git
ScheduleDAGInstrs.cpp
Go to the documentation of this file.
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
15#include "CodeGenOptions.h"
16
18#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/SparseSet.h"
42#include "llvm/Config/llvm-config.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/Type.h"
45#include "llvm/IR/Value.h"
46#include "llvm/MC/LaneBitmask.h"
49#include "llvm/Support/Debug.h"
51#include "llvm/Support/Format.h"
53#include <algorithm>
54#include <cassert>
55#include <iterator>
56#include <list>
57#include <utility>
58#include <vector>
59
60using namespace llvm;
61
62#define DEBUG_TYPE "machine-scheduler"
63
65 const MachineLoopInfo *mli,
66 bool RemoveKillFlags)
67 : ScheduleDAG(mf), Opts(getCodeGenOptions(mf)), MLI(mli),
68 MFI(mf.getFrameInfo()), RemoveKillFlags(RemoveKillFlags),
69 Topo(SUnits, &ExitSU) {
70 DbgValues.clear();
71
72 const TargetSubtargetInfo &ST = mf.getSubtarget();
73 SchedModel.init(&ST, Opts.schedmodel, Opts.scheditins);
74}
75
76/// If this machine instruction has memory reference information, collect the
77/// list of underlying objects in \p Objects. If any of these objects are
78/// unknown or may alias anything, return false. Atomic and volatile memory
79/// operands are skipped.
81 const MachineFrameInfo &MFI,
83 const DataLayout &DL) {
84 bool AllObjectsIdentified = true;
85
86 for (const MachineMemOperand *MMO : MI->memoperands()) {
87 // TODO: Figure out whether isAtomic is really necessary (see D57601).
88 if (MMO->isVolatile() || MMO->isAtomic()) {
89 AllObjectsIdentified = false;
90 continue;
91 }
92
93 if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) {
94 if (MFI.hasTailCall()) {
95 // Function that contain tail calls don't have unique PseudoSourceValue
96 // objects. Two PseudoSourceValues might refer to the same or
97 // overlapping locations. The client code calling this function assumes
98 // this is not the case. So return a conservative answer of no known
99 // object.
100 AllObjectsIdentified = false;
101 } else if (PSV->isAliased(&MFI)) {
102 // For now, ignore PseudoSourceValues which may alias LLVM IR values
103 // because the code that uses this function has no way to cope with such
104 // aliases.
105 AllObjectsIdentified = false;
106 }
107
108 Objects.push_back(PSV);
109 } else if (const Value *V = MMO->getValue()) {
111 bool ObjectsIdentified = getUnderlyingObjectsForCodeGen(V, Objs);
112 AllObjectsIdentified &= ObjectsIdentified;
113
114 for (Value *V : Objs) {
115 assert(!ObjectsIdentified || isIdentifiedObject(V));
116 Objects.push_back(V);
117 }
118 } else {
119 AllObjectsIdentified = false;
120 }
121 }
122
123 return AllObjectsIdentified;
124}
125
129
131 // Subclasses should no longer refer to the old block.
132 BB = nullptr;
133}
134
138 unsigned regioninstrs) {
139 assert(bb == BB && "startBlock should set BB");
141 RegionEnd = end;
142 NumRegionInstrs = regioninstrs;
143}
144
146 // Nothing to do.
147}
148
150 MachineInstr *ExitMI =
151 RegionEnd != BB->end()
153 : nullptr;
154 ExitSU.setInstr(ExitMI);
155 // Add dependencies on the defs and uses of the instruction.
156 if (ExitMI) {
157 const MCInstrDesc &MIDesc = ExitMI->getDesc();
158 for (const MachineOperand &MO : ExitMI->all_uses()) {
159 unsigned OpIdx = MO.getOperandNo();
160 Register Reg = MO.getReg();
161 if (Reg.isPhysical()) {
162 // addPhysRegDataDeps uses the provided operand index to retrieve
163 // the operand use cycle from the scheduling model. If the operand
164 // is "fake" (e.g., an operand of a call instruction used to pass
165 // an argument to the called function.), the scheduling model may not
166 // have an entry for it. If this is the case, pass -1 as operand index,
167 // which will cause addPhysRegDataDeps to add an artificial dependency.
168 // FIXME: Using hasImplicitUseOfPhysReg here is inaccurate as it misses
169 // aliases. When fixing, make sure to update addPhysRegDataDeps, too.
170 bool IsRealUse = OpIdx < MIDesc.getNumOperands() ||
171 MIDesc.hasImplicitUseOfPhysReg(Reg);
172 for (MCRegUnit Unit : TRI->regunits(Reg))
173 Uses.insert(PhysRegSUOper(&ExitSU, IsRealUse ? OpIdx : -1, Unit));
174 } else if (Reg.isVirtual() && MO.readsReg()) {
175 addVRegUseDeps(&ExitSU, OpIdx);
176 }
177 }
178 }
179 if (!ExitMI || (!ExitMI->isCall() && !ExitMI->isBarrier())) {
180 // For others, e.g. fallthrough, conditional branch, assume the exit
181 // uses all the registers that are livein to the successor blocks.
182 for (const MachineBasicBlock *Succ : BB->successors()) {
183 for (const auto &LI : Succ->liveins()) {
184 for (MCRegUnitMaskIterator U(LI.PhysReg, TRI); U.isValid(); ++U) {
185 auto [Unit, Mask] = *U;
186 if ((Mask & LI.LaneMask).any() && !Uses.contains(Unit))
187 Uses.insert(PhysRegSUOper(&ExitSU, -1, Unit));
188 }
189 }
190 }
191 }
192}
193
194/// MO is an operand of SU's instruction that defines a physical register. Adds
195/// data dependencies from SU to any uses of the physical register.
196void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
197 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
198 assert(MO.isDef() && "expect physreg def");
199 Register Reg = MO.getReg();
200
201 // Ask the target if address-backscheduling is desirable, and if so how much.
202 const TargetSubtargetInfo &ST = MF.getSubtarget();
203
204 // Only use any non-zero latency for real defs/uses, in contrast to
205 // "fake" operands added by regalloc.
206 const MCInstrDesc &DefMIDesc = SU->getInstr()->getDesc();
207 bool ImplicitPseudoDef = (OperIdx >= DefMIDesc.getNumOperands() &&
208 !DefMIDesc.hasImplicitDefOfPhysReg(Reg));
209 bool IsInlineAsmDef = SU->getInstr()->isInlineAsm() &&
210 SU->getInstr()->findInlineAsmFlagIdx(OperIdx) >= 0;
211 for (MCRegUnit Unit : TRI->regunits(Reg)) {
212 for (RegUnit2SUnitsMap::iterator I = Uses.find(Unit); I != Uses.end();
213 ++I) {
214 SUnit *UseSU = I->SU;
215 if (UseSU == SU)
216 continue;
217
218 // Adjust the dependence latency using operand def/use information,
219 // then allow the target to perform its own adjustments.
220 MachineInstr *UseInstr = nullptr;
221 int UseOpIdx = I->OpIdx;
222 bool ImplicitPseudoUse = false;
223 bool IsInlineAsmUse = false;
224 SDep Dep;
225 if (UseOpIdx < 0) {
226 Dep = SDep(SU, SDep::Artificial);
227 } else {
228 // Set the hasPhysRegDefs only for physreg defs that have a use within
229 // the scheduling region.
230 SU->hasPhysRegDefs = true;
231
232 UseInstr = UseSU->getInstr();
233 Register UseReg = UseInstr->getOperand(UseOpIdx).getReg();
234 const MCInstrDesc &UseMIDesc = UseInstr->getDesc();
235 // Recognize asm inputs by their operand groups, excluding trailing
236 // register bookkeeping operands.
237 IsInlineAsmUse = UseInstr->isInlineAsm() &&
238 UseInstr->findInlineAsmFlagIdx(UseOpIdx) >= 0;
239 ImplicitPseudoUse = UseOpIdx >= ((int)UseMIDesc.getNumOperands()) &&
240 !UseMIDesc.hasImplicitUseOfPhysReg(UseReg) &&
241 !IsInlineAsmUse;
242
243 Dep = SDep(SU, SDep::Data, UseReg);
244 }
245 if ((!ImplicitPseudoDef && !ImplicitPseudoUse) ||
246 (IsInlineAsmDef && IsInlineAsmUse)) {
247 Dep.setLatency(SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
248 UseInstr, UseOpIdx));
249 } else {
250 Dep.setLatency(0);
251 }
252 ST.adjustSchedDependency(SU, OperIdx, UseSU, UseOpIdx, Dep, &SchedModel);
253 UseSU->addPred(Dep);
254 }
255 }
256}
257
258/// Adds register dependencies (data, anti, and output) from this SUnit
259/// to following instructions in the same scheduling region that depend the
260/// physical register referenced at OperIdx.
261void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
262 MachineInstr *MI = SU->getInstr();
263 MachineOperand &MO = MI->getOperand(OperIdx);
264 Register Reg = MO.getReg();
265 // We do not need to track any dependencies for constant registers.
266 if (MRI.isConstantPhysReg(Reg))
267 return;
268
269 const TargetSubtargetInfo &ST = MF.getSubtarget();
270
271 // Optionally add output and anti dependencies. For anti
272 // dependencies we use a latency of 0 because for a multi-issue
273 // target we want to allow the defining instruction to issue
274 // in the same cycle as the using instruction.
275 // TODO: Using a latency of 1 here for output dependencies assumes
276 // there's no cost for reusing registers.
277 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
278 for (MCRegUnit Unit : TRI->regunits(Reg)) {
279 for (RegUnit2SUnitsMap::iterator I = Defs.find(Unit); I != Defs.end();
280 ++I) {
281 SUnit *DefSU = I->SU;
282 if (DefSU == &ExitSU)
283 continue;
284 MachineInstr *DefInstr = DefSU->getInstr();
285 MachineOperand &DefMO = DefInstr->getOperand(I->OpIdx);
286 if (DefSU != SU &&
287 (Kind != SDep::Output || !MO.isDead() || !DefMO.isDead())) {
288 SDep Dep(SU, Kind, DefMO.getReg());
289 if (Kind != SDep::Anti) {
290 Dep.setLatency(
291 SchedModel.computeOutputLatency(MI, OperIdx, DefInstr));
292 }
293 ST.adjustSchedDependency(SU, OperIdx, DefSU, I->OpIdx, Dep,
294 &SchedModel);
295 DefSU->addPred(Dep);
296 }
297 }
298 }
299
300 if (MO.isUse()) {
301 SU->hasPhysRegUses = true;
302 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
303 // retrieve the existing SUnits list for this register's uses.
304 // Push this SUnit on the use list.
305 for (MCRegUnit Unit : TRI->regunits(Reg))
306 Uses.insert(PhysRegSUOper(SU, OperIdx, Unit));
307 if (RemoveKillFlags)
308 MO.setIsKill(false);
309 } else {
310 addPhysRegDataDeps(SU, OperIdx);
311
312 // Clear previous uses and defs of this register and its subregisters.
313 for (MCRegUnit Unit : TRI->regunits(Reg)) {
314 Uses.eraseAll(Unit);
315 if (!MO.isDead())
316 Defs.eraseAll(Unit);
317 }
318
319 if (MO.isDead() && SU->isCall) {
320 // Calls will not be reordered because of chain dependencies (see
321 // below). Since call operands are dead, calls may continue to be added
322 // to the DefList making dependence checking quadratic in the size of
323 // the block. Instead, we leave only one call at the back of the
324 // DefList.
325 for (MCRegUnit Unit : TRI->regunits(Reg)) {
326 RegUnit2SUnitsMap::RangePair P = Defs.equal_range(Unit);
329 for (bool isBegin = I == B; !isBegin; /* empty */) {
330 isBegin = (--I) == B;
331 if (!I->SU->isCall)
332 break;
333 I = Defs.erase(I);
334 }
335 }
336 }
337
338 // Defs are pushed in the order they are visited and never reordered.
339 for (MCRegUnit Unit : TRI->regunits(Reg))
340 Defs.insert(PhysRegSUOper(SU, OperIdx, Unit));
341 }
342}
343
345{
346 Register Reg = MO.getReg();
347 // No point in tracking lanemasks if we don't have interesting subregisters.
348 const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
349 if (!RC.HasDisjunctSubRegs)
350 return LaneBitmask::getAll();
351
352 unsigned SubReg = MO.getSubReg();
353 if (SubReg == 0)
354 return RC.getLaneMask();
355 return TRI->getSubRegIndexLaneMask(SubReg);
356}
357
359 auto RegUse = CurrentVRegUses.find(MO.getReg());
360 if (RegUse == CurrentVRegUses.end())
361 return true;
362 return (RegUse->LaneMask & getLaneMaskForMO(MO)).none();
363}
364
365/// Adds register output and data dependencies from this SUnit to instructions
366/// that occur later in the same scheduling region if they read from or write to
367/// the virtual register defined at OperIdx.
368///
369/// TODO: Hoist loop induction variable increments. This has to be
370/// reevaluated. Generally, IV scheduling should be done before coalescing.
371void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
372 MachineInstr *MI = SU->getInstr();
373 MachineOperand &MO = MI->getOperand(OperIdx);
374 Register Reg = MO.getReg();
375
376 LaneBitmask DefLaneMask;
377 LaneBitmask KillLaneMask;
378 if (TrackLaneMasks) {
379 bool IsKill = MO.getSubReg() == 0 || MO.isUndef();
380 DefLaneMask = getLaneMaskForMO(MO);
381 // If we have a <read-undef> flag, none of the lane values comes from an
382 // earlier instruction.
383 KillLaneMask = IsKill ? LaneBitmask::getAll() : DefLaneMask;
384
385 if (MO.getSubReg() != 0 && MO.isUndef()) {
386 // There may be other subregister defs on the same instruction of the same
387 // register in later operands. The lanes of other defs will now be live
388 // after this instruction, so these should not be treated as killed by the
389 // instruction even though they appear to be killed in this one operand.
390 for (const MachineOperand &OtherMO :
391 llvm::drop_begin(MI->operands(), OperIdx + 1))
392 if (OtherMO.isReg() && OtherMO.isDef() && OtherMO.getReg() == Reg)
393 KillLaneMask &= ~getLaneMaskForMO(OtherMO);
394 }
395
396 // Clear undef flag, we'll re-add it later once we know which subregister
397 // Def is first.
398 MO.setIsUndef(false);
399 } else {
400 DefLaneMask = LaneBitmask::getAll();
401 KillLaneMask = LaneBitmask::getAll();
402 }
403
404 if (MO.isDead()) {
405 assert(deadDefHasNoUse(MO) && "Dead defs should have no uses");
406 } else {
407 // Add data dependence to all uses we found so far.
408 const TargetSubtargetInfo &ST = MF.getSubtarget();
410 E = CurrentVRegUses.end(); I != E; /*empty*/) {
411 LaneBitmask LaneMask = I->LaneMask;
412 // Ignore uses of other lanes.
413 if ((LaneMask & KillLaneMask).none()) {
414 ++I;
415 continue;
416 }
417
418 if ((LaneMask & DefLaneMask).any()) {
419 SUnit *UseSU = I->SU;
420 MachineInstr *Use = UseSU->getInstr();
421 SDep Dep(SU, SDep::Data, Reg);
422 Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use,
423 I->OperandIndex));
424 ST.adjustSchedDependency(SU, OperIdx, UseSU, I->OperandIndex, Dep,
425 &SchedModel);
426 UseSU->addPred(Dep);
427 }
428
429 LaneMask &= ~KillLaneMask;
430 // If we found a Def for all lanes of this use, remove it from the list.
431 if (LaneMask.any()) {
432 I->LaneMask = LaneMask;
433 ++I;
434 } else
435 I = CurrentVRegUses.erase(I);
436 }
437 }
438
439 // Shortcut: Singly defined vregs do not have output/anti dependencies.
440 if (MRI.hasOneDef(Reg))
441 return;
442
443 // Add output dependence to the next nearest defs of this vreg.
444 //
445 // Unless this definition is dead, the output dependence should be
446 // transitively redundant with antidependencies from this definition's
447 // uses. We're conservative for now until we have a way to guarantee the uses
448 // are not eliminated sometime during scheduling. The output dependence edge
449 // is also useful if output latency exceeds def-use latency.
450 LaneBitmask LaneMask = DefLaneMask;
451 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
452 CurrentVRegDefs.end())) {
453 // Ignore defs for other lanes.
454 if ((V2SU.LaneMask & LaneMask).none())
455 continue;
456 // Add an output dependence.
457 SUnit *DefSU = V2SU.SU;
458 // Ignore additional defs of the same lanes in one instruction. This can
459 // happen because lanemasks are shared for targets with too many
460 // subregisters. We also use some representration tricks/hacks where we
461 // add super-register defs/uses, to imply that although we only access parts
462 // of the reg we care about the full one.
463 if (DefSU == SU)
464 continue;
465 SDep Dep(SU, SDep::Output, Reg);
466 Dep.setLatency(
467 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
468 DefSU->addPred(Dep);
469
470 // Update current definition. This can get tricky if the def was about a
471 // bigger lanemask before. We then have to shrink it and create a new
472 // VReg2SUnit for the non-overlapping part.
473 LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
474 LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
475 V2SU.SU = SU;
476 V2SU.LaneMask = OverlapMask;
477 if (NonOverlapMask.any())
478 CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, DefSU));
479 }
480 // If there was no CurrentVRegDefs entry for some lanes yet, create one.
481 if (LaneMask.any())
482 CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU));
483}
484
485/// Adds a register data dependency if the instruction that defines the
486/// virtual register used at OperIdx is mapped to an SUnit. Add a register
487/// antidependency from this SUnit to instructions that occur later in the same
488/// scheduling region if they write the virtual register.
489///
490/// TODO: Handle ExitSU "uses" properly.
491void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
492 const MachineInstr *MI = SU->getInstr();
493 assert(!MI->isDebugOrPseudoInstr());
494
495 const MachineOperand &MO = MI->getOperand(OperIdx);
496 Register Reg = MO.getReg();
497
498 // Remember the use. Data dependencies will be added when we find the def.
501 CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU));
502
503 // Add antidependences to the following defs of the vreg.
504 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
505 CurrentVRegDefs.end())) {
506 // Ignore defs for unrelated lanes.
507 LaneBitmask PrevDefLaneMask = V2SU.LaneMask;
508 if ((PrevDefLaneMask & LaneMask).none())
509 continue;
510 if (V2SU.SU == SU)
511 continue;
512
513 V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg));
514 }
515}
516
517/// Creates an SUnit for each real instruction, numbered in top-down
518/// topological order. The instruction order A < B, implies that no edge exists
519/// from B to A.
520///
521/// Map each real instruction to its SUnit.
522///
523/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
524/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
525/// instead of pointers.
526///
527/// MachineScheduler relies on initSUnits numbering the nodes by their order in
528/// the original instruction list.
530 // We'll be allocating one SUnit for each real instruction in the region,
531 // which is contained within a basic block.
532 SUnits.reserve(NumRegionInstrs);
533
535 if (MI.isDebugOrPseudoInstr())
536 continue;
537
538 SUnit *SU = newSUnit(&MI);
539 MISUnitMap[&MI] = SU;
540
541 SU->isCall = MI.isCall();
542 SU->isCommutable = MI.isCommutable();
543
544 // Assign the Latency field of SU using target-provided information.
545 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
546
547 // If this SUnit uses a reserved or unbuffered resource, mark it as such.
548 //
549 // Reserved resources block an instruction from issuing and stall the
550 // entire pipeline. These are identified by BufferSize=0.
551 //
552 // Unbuffered resources prevent execution of subsequent instructions that
553 // require the same resources. This is used for in-order execution pipelines
554 // within an out-of-order core. These are identified by BufferSize=1.
555 if (SchedModel.hasInstrSchedModel()) {
556 const MCSchedClassDesc *SC = getSchedClass(SU);
557 for (const MCWriteProcResEntry &PRE :
558 make_range(SchedModel.getWriteProcResBegin(SC),
559 SchedModel.getWriteProcResEnd(SC))) {
560 switch (SchedModel.getResourceBufferSize(PRE.ProcResourceIdx)) {
561 case 0:
562 SU->hasReservedResource = true;
563 break;
564 case 1:
565 SU->isUnbuffered = true;
566 break;
567 default:
568 break;
569 }
570 }
571 }
572 }
573}
574
575namespace {
576/// A list of SUnits, used during DAG construction.
577/// FIXME: to gain speed it might be worth investigating an optimized
578/// implementation of this data structure, such as a singly linked list
579/// with a memory pool (SmallVector was tried but slow and SparseSet is not
580/// applicable).
581using SUList = std::list<SUnit *>;
582} // end anonymous namespace
583
584namespace llvm {
586private:
587 const CodeGenOptions &Opts;
589
590 BatchAAResults *AA;
591 RegPressureTracker *RPTracker;
592 PressureDiffs *PDiffs;
593 LiveIntervals *LIS;
594
595 // Track all instructions that may raise floating-point exceptions.
596 // These do not depend on one other (or normal loads or stores), but
597 // must not be rescheduled across global barriers.
598 SUList FPExceptions;
599
600 /// A frontier of unanalyzable memory operations.
601 ///
602 /// As we process memory operations (bottom to top), each new memory operation
603 /// needs to be checked for required control dependencies against later memory
604 /// operations. A naive implementation issues AA calls quadratically in the
605 /// number of memory operations and is therefore unacceptable.
606 ///
607 /// To bound the complexity, we only ever consider a frontier of memory
608 /// operations which we frequently clear, modeled by this struct. To ensure
609 /// that we are not missing any necessary control dependencies, we promote
610 /// certain store instructions to what we term 'sequencing stores'. These
611 /// sequencing stores are treated carefully to ensure that all previously seen
612 /// unanalyzable memory operations that do not belong to the frontier
613 /// necessarily transitively succeed the current sequencing store.
614 ///
615 /// By frequently updating the sequencing store, we bound the number of alias
616 /// analysis queries and transitively redundant control dependencies we
617 /// generate. However, doing so we necessarily overconstrain the DAG. Indeed,
618 /// if we were to update the sequencing store every time we see a store
619 /// instruction, the effect would be to linearize the stores.
620 struct MemopFrontier {
621 // The current sequencing store.
622 SUnit *SequencingStore = nullptr;
623 /// The memory operations in the frontier.
624 SUList Stores, Loads;
625
626 /// The number of memops in the frontier, excluding the sequencing store.
627 unsigned size() const;
628
629 /// Clears the frontier.
630 void clear();
631 };
632
633 // For memory operations that can be analyzed to an identified underlying
634 // object, we maintain one frontier per underlying object. Two SUs are
635 // trivially non-aliasing if they both depend on only identified Values and do
636 // not share any common Value. We expect the analyzable frontiers to remain
637 // small and benefit from alias analysis, so only clear when they grow too
638 // large.
639 MapVector<ValueType, MemopFrontier> AnalyzableFrontiers;
640
641 /// We maintain an additional frontier of unanalyzable memory operations,
642 /// equipped with some extra state designed to clear the frontier more
643 /// frequently. The conditions we choose to update the sequencing store are as
644 /// follows:
645 ///
646 /// The conditions we choose to update the sequencing store are as follows:
647 /// 1. If an incoming store instruction refers to an underlying object outside
648 /// of the set of underlying objects of the current sequencing store;
649 /// 2. If an incoming store instruction precedes an intervening load from an
650 /// underlying object outside of the set of underlying objects of the
651 /// current sequencing store (a 'sequencing load').
652 /// In these cases, a BasicAA query will (generally) already induce a
653 /// (transitive) edge from the incoming store to the current sequencing store.
654 /// However, this process introduces spurious (transitive) barrier edges in
655 /// the following cases:
656 /// 1. From all preceding loads to the new sequencing store;
657 /// 2. From the new sequencing store to all stores in the current frontier;
658 /// 3. From all preceding unanalyzable stores to (a subset of) the same base
659 /// objects, independent of AA results;
660 /// 4. From all preceding analyzable stores, independent of AA results.
661 struct UnanalyzableMemopFrontier {
662 /// The underlying memop frontier.
663 MemopFrontier Frontier;
664 /// The underlying objects of the current sequencing store.
665 UnderlyingObjectsVector BaseObjects;
666 /// `true` if the frontier contains a load whose underlying objects escape
667 /// #BaseObjects.
668 bool SeenSequencingLoad = false;
669
670 /// Returns true if any of \p Objs does not belong to #BaseObjects.
671 bool escapesBaseObjects(const UnderlyingObjectsVector &Objs) const;
672
673 /// Clears the frontier and resets the associated state.
674 void clear();
675 };
676
677 /// Track a frontier of unanalyzable memory operations.
678 ///
679 /// FIXME(@cofibrant): For some platforms, a single frontier is too coarse and
680 /// we should be maintaining one frontier per address space.
681 UnanalyzableMemopFrontier UnanalyzableFrontier;
682
683 /// Remember a generic side-effecting instruction as we proceed.
684 /// No other SU ever gets scheduled around it (except in the special
685 /// case of a huge region that gets reduced).
686 SUnit *BarrierChain = nullptr;
687
688 unsigned MemOpsProcessed = 0;
689
690 /// Tracks the total occupancy of all memop frontiers, including sequencing
691 /// stores.
692 unsigned MemopsInFlight = 0;
693
694public:
696 RegPressureTracker *RPTracker,
697 PressureDiffs *PDiffs, LiveIntervals *LIS)
698 : Opts(DAG.Opts), DAG(DAG), AA(AA), RPTracker(RPTracker), PDiffs(PDiffs),
699 LIS(LIS) {}
700
701private:
702 /// Adds a chain edge between SUa and SUb, but only if both
703 /// AAResults and Target fail to deny the dependency.
704 ///
705 /// Returns true if an edge was inserted.
706 bool addChainDependency(SUnit *SUa, SUnit *SUb, unsigned Latency = 0);
707
708 /// Adds dependencies as needed from all SUs in list to SU.
709 void addChainDependencies(SUnit *SU, SUList &SUs, unsigned Latency);
710 void addChainDependencies(SUnit *SU, MemopFrontier &F, bool IsStore);
711
712 void addBarrierChain(SUList &SUs);
713 void addBarrierChain(MemopFrontier &F);
714
715 /// Add dependencies from the barrier chain to all in flight memory operations
716 /// and clear the memop frontiers.
717 void addBarrierMemoryDeps();
718
719 /// Returns true if the next store should be promoted to a sequencing store
720 /// in the frontier \p F and false otherwise.
721 bool shouldUpdate(const MemopFrontier &F) const;
722
723 /// Given a store instruction with underlying objects \p Objs, returns true
724 /// if the store should be promoted to a sequencing store in the frontier
725 /// \p UF and false otherwise.
726 bool shouldUpdate(const UnanalyzableMemopFrontier &UF,
727 const UnderlyingObjectsVector &Objs) const;
728
729 /// Promote the store \p SU to be a new sequencing store in the frontier \p F.
730 /// If \p PreserveNoAliasLoads is true, loads in the frontier that do not
731 /// alias with \p SU will be retained after promotion.
732 void updateSequencingStore(MemopFrontier &F, SUnit *SU,
733 bool PreserveNoAliasLoads = false);
734
735 /// Promote the store \p SU with underlying objects \p Objs to be a new
736 /// sequencing store in the frontier \p UF.
737 void updateSequencingStore(UnanalyzableMemopFrontier &UF, SUnit *SU,
739
740public:
741 void buildDeps();
742};
743} // end namespace llvm
744
745unsigned ScheduleDAGDependencyBuilder::MemopFrontier::size() const {
746 return Loads.size() + Stores.size();
747}
748
749void ScheduleDAGDependencyBuilder::MemopFrontier::clear() {
750 SequencingStore = nullptr;
751 Stores.clear();
752 Loads.clear();
753}
754
755bool ScheduleDAGDependencyBuilder::shouldUpdate(const MemopFrontier &F) const {
756 if (!Opts.store_sequencing)
757 return false;
758 return F.size() >= Opts.store_sequencing_max_frontier_size;
759}
760
761bool ScheduleDAGDependencyBuilder::shouldUpdate(
762 const UnanalyzableMemopFrontier &UF,
763 const UnderlyingObjectsVector &Objs) const {
764 if (!Opts.store_sequencing)
765 return false;
766 return shouldUpdate(UF.Frontier) || !UF.Frontier.SequencingStore ||
767 UF.SeenSequencingLoad || UF.escapesBaseObjects(Objs);
768}
769
770bool ScheduleDAGDependencyBuilder::UnanalyzableMemopFrontier::
771 escapesBaseObjects(const UnderlyingObjectsVector &Objs) const {
772 for (const ValueType V : Objs) {
773 if (!is_contained(BaseObjects, V))
774 return true;
775 }
776
777 return false;
778}
779
780void ScheduleDAGDependencyBuilder::UnanalyzableMemopFrontier::clear() {
781 Frontier.clear();
782 SeenSequencingLoad = false;
783 BaseObjects.clear();
784}
785
786bool ScheduleDAGDependencyBuilder::addChainDependency(SUnit *SUa, SUnit *SUb,
787 unsigned Latency) {
788 if (!SUa->getInstr()->mayAlias(AA, *SUb->getInstr(), Opts.sched_mi_tbaa))
789 return false;
790
791 SDep Dep(SUa, SDep::MayAliasMem);
792 Dep.setLatency(Latency);
793 SUb->addPred(Dep);
794 return true;
795}
796
797void ScheduleDAGDependencyBuilder::addChainDependencies(SUnit *SU, SUList &SUs,
798 unsigned Latency) {
799 for (SUnit *Entry : SUs)
800 addChainDependency(SU, Entry, Latency);
801}
802
803void ScheduleDAGDependencyBuilder::addChainDependencies(SUnit *SU,
804 MemopFrontier &F,
805 bool IsStore) {
806 if (F.SequencingStore)
807 F.SequencingStore->addPredBarrier(SU);
808
809 addChainDependencies(SU, F.Stores, /*Latency=*/0);
810 if (IsStore)
811 addChainDependencies(SU, F.Loads, /*Latency=*/1);
812}
813
814void ScheduleDAGDependencyBuilder::addBarrierChain(SUList &SUs) {
815 assert(BarrierChain != nullptr);
816
817 for (auto *SU : SUs)
818 SU->addPredBarrier(BarrierChain);
819
820 SUs.clear();
821}
822
823void ScheduleDAGDependencyBuilder::addBarrierChain(MemopFrontier &F) {
824 assert(BarrierChain != nullptr);
825
826 addBarrierChain(F.Stores);
827 addBarrierChain(F.Loads);
828
829 if (F.SequencingStore)
830 F.SequencingStore->addPredBarrier(BarrierChain);
831
832 F.clear();
833}
834
835void ScheduleDAGDependencyBuilder::addBarrierMemoryDeps() {
836 assert(BarrierChain != nullptr);
837
838 addBarrierChain(UnanalyzableFrontier.Frontier);
839 UnanalyzableFrontier.clear();
840
841 for (auto &[_, AF] : AnalyzableFrontiers)
842 addBarrierChain(AF);
843 AnalyzableFrontiers.clear();
844
845 MemopsInFlight = 0;
846}
847
848void ScheduleDAGDependencyBuilder::updateSequencingStore(
849 MemopFrontier &F, SUnit *SU, bool PreserveNoAliasLoads) {
850 assert(SU->getInstr()->mayStore() &&
851 "Only store instructions should be used as sequencing stores");
852 LLVM_DEBUG(dbgs() << "Promoting " << *SU << " to sequencing store\n");
853
854 // Discount the memops we plan to clear.
855 MemopsInFlight -= F.size();
856
857 if (F.SequencingStore) {
858 F.SequencingStore->addPredBarrier(SU);
859 } else {
860 // Account for the new sequencing store.
861 ++MemopsInFlight;
862 }
863
864 // Sequence all stores against the sequencing store and clear the map.
865 for (SUnit *S : F.Stores)
866 S->addPredBarrier(SU);
867
868 F.Stores.clear();
869
870 if (PreserveNoAliasLoads) {
871 // If asked, for loads, we can do slightly better. Rather than naively
872 // adding pred barriers and clearing the map, we check whether each load
873 // genuinely needs to sequence against the new sequencing store. Wherever an
874 // edge is not required, we retain the load and avoid the spurious control
875 // dependency.
876 for (auto It = F.Loads.begin(); It != F.Loads.end();) {
877 if (addChainDependency(SU, *It, /*TrueMemOrderLatency=*/1)) {
878 It = F.Loads.erase(It);
879 } else {
880 ++It;
881 }
882 }
883
884 // Re-account for the potentially remaining loads.
885 MemopsInFlight += F.Loads.size();
886 } else {
887 // Sequence all loads against the sequencing store and clear the map.
888 for (SUnit *S : F.Loads)
889 S->addPredBarrier(SU);
890
891 F.Loads.clear();
892 }
893
894 F.SequencingStore = SU;
895}
896
897void ScheduleDAGDependencyBuilder::updateSequencingStore(
898 UnanalyzableMemopFrontier &UF, SUnit *SU, UnderlyingObjectsVector &&Objs) {
899 assert(SU->getInstr()->mayStore() &&
900 "Only store instructions should be used as sequencing stores");
901 // If the underlying MemopFrontier wants updating, we're over size and
902 // therefore shouldn't try to preserve no alias loads.
903 bool ShouldPreserveNoAliasLoads = !shouldUpdate(UF.Frontier);
904 updateSequencingStore(UF.Frontier, SU,
905 /*PreserveNoAliasLoads=*/ShouldPreserveNoAliasLoads);
906 UF.BaseObjects = std::move(Objs);
907 UF.SeenSequencingLoad = false;
908}
909
911 const TargetSubtargetInfo &ST = DAG.MF.getSubtarget();
912
913 // We build scheduling units by walking a block's instruction list
914 // from bottom to top.
915
916 // Model data dependencies between instructions being scheduled and the
917 // ExitSU.
918 DAG.addSchedBarrierDeps();
919
920 // Walk the list of instructions, from bottom moving up.
921 MachineInstr *DbgMI = nullptr;
922 for (MachineBasicBlock::iterator MII = DAG.RegionEnd, MIE = DAG.RegionBegin;
923 MII != MIE; --MII) {
924 MachineInstr &MI = *std::prev(MII);
925 if (DbgMI) {
926 DAG.DbgValues.emplace_back(DbgMI, &MI);
927 DbgMI = nullptr;
928 }
929
930 if (MI.isDebugValue() || MI.isDebugPHI()) {
931 DbgMI = &MI;
932 continue;
933 }
934
935 if (MI.isDebugLabel() || MI.isDebugRef() || MI.isPseudoProbe())
936 continue;
937
938 SUnit *SU = DAG.MISUnitMap[&MI];
939 assert(SU && "No SUnit mapped to this MI");
940
941 if (RPTracker) {
942 RegisterOperands RegOpers;
943 RegOpers.collect(MI, *DAG.TRI, DAG.MRI, DAG.TrackLaneMasks, false);
944 if (DAG.TrackLaneMasks) {
945 SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
946 RegOpers.adjustLaneLiveness(*LIS, DAG.MRI, SlotIdx);
947 } else if (LIS) {
948 // Detect dead defs from LiveIntervals instead of trusting operand dead
949 // flags.
950 RegOpers.detectDeadDefs(MI, *LIS, DAG.MRI);
951 }
952 if (PDiffs != nullptr)
953 PDiffs->addInstruction(SU->NodeNum, RegOpers, DAG.MRI);
954
955 if (RPTracker->getPos() == DAG.RegionEnd || &*RPTracker->getPos() != &MI)
956 RPTracker->recedeSkipDebugValues();
957 assert(&*RPTracker->getPos() == &MI && "RPTracker in sync");
958 RPTracker->recede(RegOpers);
959 }
960
961 assert((DAG.CanHandleTerminators ||
962 (!MI.isTerminator() && !MI.isPosition())) &&
963 "Cannot schedule terminators or labels!");
964
965 // Add register-based dependencies (data, anti, and output).
966 // For some instructions (calls, returns, inline-asm, etc.) there can
967 // be explicit uses and implicit defs, in which case the use will appear
968 // on the operand list before the def. Do two passes over the operand
969 // list to make sure that defs are processed before any uses.
970 bool HasVRegDef = false;
971 for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
972 const MachineOperand &MO = MI.getOperand(j);
973 if (!MO.isReg() || !MO.isDef())
974 continue;
975 Register Reg = MO.getReg();
976 if (Reg.isPhysical()) {
977 DAG.addPhysRegDeps(SU, j);
978 } else if (Reg.isVirtual()) {
979 HasVRegDef = true;
980 DAG.addVRegDefDeps(SU, j);
981 }
982 }
983 // Now process all uses.
984 for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
985 const MachineOperand &MO = MI.getOperand(j);
986 // Only look at use operands.
987 // We do not need to check for MO.readsReg() here because subsequent
988 // subregister defs will get output dependence edges and need no
989 // additional use dependencies.
990 if (!MO.isReg() || !MO.isUse())
991 continue;
992 Register Reg = MO.getReg();
993 if (Reg.isPhysical()) {
994 DAG.addPhysRegDeps(SU, j);
995 } else if (Reg.isVirtual() && MO.readsReg()) {
996 DAG.addVRegUseDeps(SU, j);
997 }
998 }
999
1000 // If we haven't seen any uses in this scheduling region, create a
1001 // dependence edge to ExitSU to model the live-out latency. This is required
1002 // for vreg defs with no in-region use, and prefetches with no vreg def.
1003 //
1004 // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
1005 // check currently relies on being called before adding chain deps.
1006 if (SU->NumSuccs == 0 && SU->Latency > 1 && (HasVRegDef || MI.mayLoad())) {
1007 SDep Dep(SU, SDep::Artificial);
1008 Dep.setLatency(SU->Latency - 1);
1009 DAG.ExitSU.addPred(Dep);
1010 }
1011
1012 // Add memory dependencies (Note: isStoreToStackSlot and
1013 // isLoadFromStackSLot are not usable after stack slots are lowered to
1014 // actual addresses).
1015
1016 const TargetInstrInfo *TII = ST.getInstrInfo();
1017 // This is a barrier event that acts as a pivotal node in the DAG.
1018 if (TII->isGlobalMemoryObject(&MI)) {
1019
1020 // Become the barrier chain.
1021 if (BarrierChain)
1022 BarrierChain->addPredBarrier(SU);
1023 BarrierChain = SU;
1024
1025 LLVM_DEBUG(dbgs() << "Global memory object and new barrier chain: "
1026 << *BarrierChain << ".\n");
1027
1028 // Add dependencies against everything below it and clear maps.
1029 addBarrierChain(FPExceptions);
1030 addBarrierMemoryDeps();
1031
1032 continue;
1033 }
1034
1035 // Instructions that may raise FP exceptions may not be moved
1036 // across any global barriers.
1037 if (MI.mayRaiseFPException()) {
1038 if (BarrierChain)
1039 BarrierChain->addPredBarrier(SU);
1040
1041 if (!Opts.store_sequencing &&
1042 FPExceptions.size() + 1 >= Opts.dag_maps_huge_region) {
1043 LLVM_DEBUG(
1044 dbgs()
1045 << "Creating barrier chain and clearing FPExceptions map.\n");
1046 BarrierChain = SU;
1047 addBarrierChain(FPExceptions);
1048 } else {
1049 FPExceptions.push_back(SU);
1050 }
1051 }
1052
1053 // If it's not a store or a variant load, we're done.
1054 if (!MI.mayStore() &&
1055 !(MI.mayLoad() && !MI.isDereferenceableInvariantLoad()))
1056 continue;
1057
1058 MemOpsProcessed++;
1059
1060 // Always add dependecy edge to BarrierChain if present.
1061 if (BarrierChain && BarrierChain != SU)
1062 BarrierChain->addPredBarrier(SU);
1063
1064 // Reduce maps if they grow huge.
1065 if (!Opts.store_sequencing &&
1066 MemOpsProcessed >= Opts.dag_maps_huge_region) {
1067 LLVM_DEBUG(dbgs() << "Creating barrier chain and clearing maps.\n");
1068
1069 BarrierChain = SU;
1070 addBarrierMemoryDeps();
1071
1072 MemOpsProcessed = 0;
1073 continue;
1074 }
1075
1076 // If the frontier occupancy exceeds the maximum threshold, promote SU to a
1077 // global memory barrier and clear the frontiers.
1078 if (Opts.store_sequencing &&
1079 MemopsInFlight >= Opts.store_sequencing_max_memops_in_flight) {
1080 LLVM_DEBUG(dbgs() << "Number of in-flight memory operations reached "
1081 << Opts.store_sequencing_max_memops_in_flight
1082 << ", promoting " << *SU
1083 << " to barrier chain and clearing maps.\n");
1084
1085 BarrierChain = SU;
1086 addBarrierMemoryDeps();
1087 continue;
1088 }
1089
1090 // Find the underlying objects for MI. The Objs vector is either
1091 // empty, or filled with the Values of memory locations which this
1092 // SU depends on.
1094 bool ObjsIdentified = getUnderlyingObjectsForInstr(&MI, DAG.MFI, Objs,
1095 DAG.MF.getDataLayout());
1096 bool IsStore = MI.mayStore();
1097
1098 if (!ObjsIdentified) {
1099 // An unanalyzable memory operation depends on all analyzable frontiers.
1100 for (auto &[_, AF] : AnalyzableFrontiers)
1101 addChainDependencies(SU, AF, IsStore);
1102
1103 if (IsStore && shouldUpdate(UnanalyzableFrontier, Objs)) {
1104 updateSequencingStore(UnanalyzableFrontier, SU, std::move(Objs));
1105 } else {
1106 if (!IsStore && UnanalyzableFrontier.escapesBaseObjects(Objs))
1107 UnanalyzableFrontier.SeenSequencingLoad = true;
1108 addChainDependencies(SU, UnanalyzableFrontier.Frontier, IsStore);
1109 (IsStore ? UnanalyzableFrontier.Frontier.Stores
1110 : UnanalyzableFrontier.Frontier.Loads)
1111 .push_back(SU);
1112 ++MemopsInFlight;
1113 }
1114 } else {
1115 // Add precise dependencies against all previously seen memory
1116 // accesses mapped to the same Value(s).
1117 SmallSet<ValueType, 2> SeenValues;
1118 for (const ValueType V : Objs) {
1119 // Deduplicate values to avoid adding self loops.
1120 if (!SeenValues.insert(V).second)
1121 continue;
1122
1123 MemopFrontier &Frontier = AnalyzableFrontiers[V];
1124
1125 if (IsStore && shouldUpdate(Frontier)) {
1126 updateSequencingStore(Frontier, SU);
1127 } else {
1128 addChainDependencies(SU, Frontier, IsStore);
1129 (IsStore ? Frontier.Stores : Frontier.Loads).push_back(SU);
1130 ++MemopsInFlight;
1131 }
1132 }
1133
1134 // The memop may have dependencies to unanalyzable stores.
1135 addChainDependencies(SU, UnanalyzableFrontier.Frontier, IsStore);
1136 }
1137 }
1138
1139 if (DbgMI)
1140 DAG.FirstDbgValue = DbgMI;
1141}
1142
1144 RegPressureTracker *RPTracker,
1145 PressureDiffs *PDiffs,
1146 LiveIntervals *LIS,
1147 bool TrackLaneMasks) {
1148 const TargetSubtargetInfo &ST = MF.getSubtarget();
1149 bool UseAA = valueOr(Opts.sched_mi_aa, ST.useAA());
1150 this->TrackLaneMasks = TrackLaneMasks;
1151 MISUnitMap.clear();
1153
1154 // Create an SUnit for each real instruction.
1155 initSUnits();
1156
1157 if (PDiffs)
1158 PDiffs->init(SUnits.size());
1159
1160 // Remove any stale debug info; sometimes BuildSchedGraph is called again
1161 // without emitting the info from the previous call.
1162 DbgValues.clear();
1163 FirstDbgValue = nullptr;
1164
1165 assert(Defs.empty() && Uses.empty() &&
1166 "Only BuildGraph should update Defs/Uses");
1167 Defs.setUniverse(TRI->getNumRegs());
1168 Uses.setUniverse(TRI->getNumRegs());
1169
1170 assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
1171 assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
1172 unsigned NumVirtRegs = MRI.getNumVirtRegs();
1173 CurrentVRegDefs.setUniverse(NumVirtRegs);
1174 CurrentVRegUses.setUniverse(NumVirtRegs);
1175
1176 std::optional<BatchAAResults> BatchAA;
1177 if (UseAA && AA)
1178 BatchAA.emplace(*AA);
1179
1181 *this, BatchAA.has_value() ? &BatchAA.value() : nullptr, RPTracker,
1182 PDiffs, LIS);
1183 DepBuilder.buildDeps();
1184
1185 Defs.clear();
1186 Uses.clear();
1187 CurrentVRegDefs.clear();
1188 CurrentVRegUses.clear();
1189
1190 Topo.MarkDirty();
1191}
1192
1194 PSV->printCustom(OS);
1195 return OS;
1196}
1197
1199 MachineInstr &MI, bool addToLiveRegs) {
1200 for (MachineOperand &MO : MI.operands()) {
1201 if (!MO.isReg() || !MO.readsReg())
1202 continue;
1203 Register Reg = MO.getReg();
1204 if (!Reg)
1205 continue;
1206
1207 // Things that are available after the instruction are killed by it.
1208 bool IsKill = LiveRegs.available(Reg);
1209
1210 // Exception: Do not kill reserved registers
1211 MO.setIsKill(IsKill && !MRI.isReserved(Reg));
1212 if (addToLiveRegs)
1213 LiveRegs.addReg(Reg);
1214 }
1215}
1216
1218 LLVM_DEBUG(dbgs() << "Fixup kills for " << printMBBReference(MBB) << '\n');
1219
1220 LiveRegs.init(*TRI);
1221 LiveRegs.addLiveOuts(MBB);
1222
1223 // Examine block from end to start...
1224 for (MachineInstr &MI : llvm::reverse(MBB)) {
1225 if (MI.isDebugOrPseudoInstr())
1226 continue;
1227
1228 // Update liveness. Registers that are defed but not used in this
1229 // instruction are now dead. Mark register and all subregs as they
1230 // are completely defined.
1231 for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
1232 const MachineOperand &MO = *O;
1233 if (MO.isReg()) {
1234 if (!MO.isDef())
1235 continue;
1236 Register Reg = MO.getReg();
1237 if (!Reg)
1238 continue;
1239 LiveRegs.removeReg(Reg);
1240 } else if (MO.isRegMask()) {
1241 LiveRegs.removeRegsNotPreserved(MO.getRegMask());
1242 }
1243 }
1244
1245 // If there is a bundle header fix it up first.
1246 if (!MI.isBundled()) {
1247 toggleKills(MRI, LiveRegs, MI, true);
1248 } else {
1249 MachineBasicBlock::instr_iterator Bundle = MI.getIterator();
1250 if (MI.isBundle())
1251 toggleKills(MRI, LiveRegs, MI, false);
1252
1253 // Some targets make the (questionable) assumtion that the instructions
1254 // inside the bundle are ordered and consequently only the last use of
1255 // a register inside the bundle can kill it.
1256 MachineBasicBlock::instr_iterator I = std::next(Bundle);
1257 while (I->isBundledWithSucc())
1258 ++I;
1259 do {
1260 if (!I->isDebugOrPseudoInstr())
1261 toggleKills(MRI, LiveRegs, *I, true);
1262 --I;
1263 } while (I != Bundle);
1264 }
1265 }
1266}
1267
1268void ScheduleDAGInstrs::dumpNode(const SUnit &SU) const {
1269#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1270 dumpNodeName(SU);
1271#ifndef NDEBUG
1272 if (Opts.sched_print_cycles)
1273 dbgs() << " [TopReadyCycle = " << SU.TopReadyCycle
1274 << ", BottomReadyCycle = " << SU.BotReadyCycle << "]";
1275#endif
1276 dbgs() << ": ";
1277 SU.getInstr()->dump();
1278#endif
1279}
1280
1282#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1283 if (EntrySU.getInstr() != nullptr)
1285 for (const SUnit &SU : SUnits)
1286 dumpNodeAll(SU);
1287 if (ExitSU.getInstr() != nullptr)
1289#endif
1290}
1291
1292#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1293std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1294 std::string s;
1295 raw_string_ostream oss(s);
1296 if (SU == &EntrySU)
1297 oss << "<entry>";
1298 else if (SU == &ExitSU)
1299 oss << "<exit>";
1300 else
1301 SU->getInstr()->print(oss, /*IsStandalone=*/true);
1302 return s;
1303}
1304#endif
1305
1306/// Return the basic block label. It is not necessarily unique because a block
1307/// contains multiple scheduling regions. But it is fine for visualization.
1309 return "dag." + BB->getFullName();
1310}
1311
1313 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
1314}
1315
1316bool ScheduleDAGInstrs::addEdge(SUnit *SuccSU, const SDep &PredDep) {
1317 if (SuccSU != &ExitSU) {
1318 // Do not use WillCreateCycle, it assumes SD scheduling.
1319 // If Pred is reachable from Succ, then the edge creates a cycle.
1320 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
1321 return false;
1322 Topo.AddPredQueued(SuccSU, PredDep.getSUnit());
1323 }
1324 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
1325 // Return true regardless of whether a new edge needed to be inserted.
1326 return true;
1327}
1328
1329//===----------------------------------------------------------------------===//
1330// SchedDFSResult Implementation
1331//===----------------------------------------------------------------------===//
1332
1333namespace llvm {
1334
1335/// Internal state used to compute SchedDFSResult.
1337 SchedDFSResult &R;
1338
1339 /// Join DAG nodes into equivalence classes by their subtree.
1340 IntEqClasses SubtreeClasses;
1341 /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1342 std::vector<std::pair<const SUnit *, const SUnit*>> ConnectionPairs;
1343
1344 struct RootData {
1345 unsigned NodeID;
1346 unsigned ParentNodeID; ///< Parent node (member of the parent subtree).
1347 unsigned SubInstrCount = 0; ///< Instr count in this tree only, not
1348 /// children.
1349
1350 RootData(unsigned id): NodeID(id),
1351 ParentNodeID(SchedDFSResult::InvalidSubtreeID) {}
1352
1353 unsigned getSparseSetIndex() const { return NodeID; }
1354 };
1355
1356 SparseSet<RootData> RootSet;
1357
1358public:
1359 SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1360 RootSet.setUniverse(R.DFSNodeData.size());
1361 }
1362
1363 /// Returns true if this node been visited by the DFS traversal.
1364 ///
1365 /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1366 /// ID. Later, SubtreeID is updated but remains valid.
1367 bool isVisited(const SUnit *SU) const {
1368 return R.DFSNodeData[SU->NodeNum].SubtreeID
1369 != SchedDFSResult::InvalidSubtreeID;
1370 }
1371
1372 /// Initializes this node's instruction count. We don't need to flag the node
1373 /// visited until visitPostorder because the DAG cannot have cycles.
1374 void visitPreorder(const SUnit *SU) {
1375 R.DFSNodeData[SU->NodeNum].InstrCount =
1376 SU->getInstr()->isTransient() ? 0 : 1;
1377 }
1378
1379 /// Called once for each node after all predecessors are visited. Revisit this
1380 /// node's predecessors and potentially join them now that we know the ILP of
1381 /// the other predecessors.
1382 void visitPostorderNode(const SUnit *SU) {
1383 // Mark this node as the root of a subtree. It may be joined with its
1384 // successors later.
1385 R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1386 RootData RData(SU->NodeNum);
1387 RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
1388
1389 // If any predecessors are still in their own subtree, they either cannot be
1390 // joined or are large enough to remain separate. If this parent node's
1391 // total instruction count is not greater than a child subtree by at least
1392 // the subtree limit, then try to join it now since splitting subtrees is
1393 // only useful if multiple high-pressure paths are possible.
1394 unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
1395 for (const SDep &PredDep : SU->Preds) {
1396 if (PredDep.getKind() != SDep::Data)
1397 continue;
1398 unsigned PredNum = PredDep.getSUnit()->NodeNum;
1399 if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
1400 joinPredSubtree(PredDep, SU, /*CheckLimit=*/false);
1401
1402 // Either link or merge the TreeData entry from the child to the parent.
1403 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1404 // If the predecessor's parent is invalid, this is a tree edge and the
1405 // current node is the parent.
1406 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1407 RootSet[PredNum].ParentNodeID = SU->NodeNum;
1408 }
1409 else if (RootSet.count(PredNum)) {
1410 // The predecessor is not a root, but is still in the root set. This
1411 // must be the new parent that it was just joined to. Note that
1412 // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1413 // set to the original parent.
1414 RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1415 RootSet.erase(PredNum);
1416 }
1417 }
1418 RootSet[SU->NodeNum] = RData;
1419 }
1420
1421 /// Called once for each tree edge after calling visitPostOrderNode on
1422 /// the predecessor. Increment the parent node's instruction count and
1423 /// preemptively join this subtree to its parent's if it is small enough.
1424 void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1425 R.DFSNodeData[Succ->NodeNum].InstrCount
1426 += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1427 joinPredSubtree(PredDep, Succ);
1428 }
1429
1430 /// Adds a connection for cross edges.
1431 void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
1432 ConnectionPairs.emplace_back(PredDep.getSUnit(), Succ);
1433 }
1434
1435 /// Sets each node's subtree ID to the representative ID and record
1436 /// connections between trees.
1438 SubtreeClasses.compress();
1439 R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1440 assert(SubtreeClasses.getNumClasses() == RootSet.size()
1441 && "number of roots should match trees");
1442 for (const RootData &Root : RootSet) {
1443 unsigned TreeID = SubtreeClasses[Root.NodeID];
1444 if (Root.ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1445 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[Root.ParentNodeID];
1446 R.DFSTreeData[TreeID].SubInstrCount = Root.SubInstrCount;
1447 // Note that SubInstrCount may be greater than InstrCount if we joined
1448 // subtrees across a cross edge. InstrCount will be attributed to the
1449 // original parent, while SubInstrCount will be attributed to the joined
1450 // parent.
1451 }
1452 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1453 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1454 LLVM_DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
1455 for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1456 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
1457 LLVM_DEBUG(dbgs() << " " << SUnits[Idx] << " in tree "
1458 << R.DFSNodeData[Idx].SubtreeID << '\n');
1459 }
1460 for (const auto &[Pred, Succ] : ConnectionPairs) {
1461 unsigned PredTree = SubtreeClasses[Pred->NodeNum];
1462 unsigned SuccTree = SubtreeClasses[Succ->NodeNum];
1463 if (PredTree == SuccTree)
1464 continue;
1465 unsigned Depth = Pred->getDepth();
1466 addConnection(PredTree, SuccTree, Depth);
1467 addConnection(SuccTree, PredTree, Depth);
1468 }
1469 }
1470
1471protected:
1472 /// Joins the predecessor subtree with the successor that is its DFS parent.
1473 /// Applies some heuristics before joining.
1474 bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1475 bool CheckLimit = true) {
1476 assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1477
1478 // Check if the predecessor is already joined.
1479 const SUnit *PredSU = PredDep.getSUnit();
1480 unsigned PredNum = PredSU->NodeNum;
1481 if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
1482 return false;
1483
1484 // Four is the magic number of successors before a node is considered a
1485 // pinch point.
1486 unsigned NumDataSucs = 0;
1487 for (const SDep &SuccDep : PredSU->Succs) {
1488 if (SuccDep.getKind() == SDep::Data) {
1489 if (++NumDataSucs >= 4)
1490 return false;
1491 }
1492 }
1493 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
1494 return false;
1495 R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
1496 SubtreeClasses.join(Succ->NodeNum, PredNum);
1497 return true;
1498 }
1499
1500 /// Called by finalize() to record a connection between trees.
1501 void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1502 if (!Depth)
1503 return;
1504
1505 do {
1507 R.SubtreeConnections[FromTree];
1508 for (SchedDFSResult::Connection &C : Connections) {
1509 if (C.TreeID == ToTree) {
1510 C.Level = std::max(C.Level, Depth);
1511 return;
1512 }
1513 }
1514 Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1515 FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1516 } while (FromTree != SchedDFSResult::InvalidSubtreeID);
1517 }
1518};
1519
1520} // end namespace llvm
1521
1522namespace {
1523
1524/// Manage the stack used by a reverse depth-first search over the DAG.
1525class SchedDAGReverseDFS {
1526 std::vector<std::pair<const SUnit *, SUnit::const_pred_iterator>> DFSStack;
1527
1528public:
1529 bool isComplete() const { return DFSStack.empty(); }
1530
1531 void follow(const SUnit *SU) {
1532 DFSStack.emplace_back(SU, SU->Preds.begin());
1533 }
1534 void advance() { ++DFSStack.back().second; }
1535
1536 const SDep *backtrack() {
1537 DFSStack.pop_back();
1538 return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
1539 }
1540
1541 const SUnit *getCurr() const { return DFSStack.back().first; }
1542
1543 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1544
1545 SUnit::const_pred_iterator getPredEnd() const {
1546 return getCurr()->Preds.end();
1547 }
1548};
1549
1550} // end anonymous namespace
1551
1552static bool hasDataSucc(const SUnit *SU) {
1553 for (const SDep &SuccDep : SU->Succs) {
1554 if (SuccDep.getKind() == SDep::Data &&
1555 !SuccDep.getSUnit()->isBoundaryNode())
1556 return true;
1557 }
1558 return false;
1559}
1560
1561/// Computes an ILP metric for all nodes in the subDAG reachable via depth-first
1562/// search from this root.
1564 if (!IsBottomUp)
1565 llvm_unreachable("Top-down ILP metric is unimplemented");
1566
1567 SchedDFSImpl Impl(*this);
1568 for (const SUnit &SU : SUnits) {
1569 if (Impl.isVisited(&SU) || hasDataSucc(&SU))
1570 continue;
1571
1572 SchedDAGReverseDFS DFS;
1573 Impl.visitPreorder(&SU);
1574 DFS.follow(&SU);
1575 while (true) {
1576 // Traverse the leftmost path as far as possible.
1577 while (DFS.getPred() != DFS.getPredEnd()) {
1578 const SDep &PredDep = *DFS.getPred();
1579 DFS.advance();
1580 // Ignore non-data edges.
1581 if (PredDep.getKind() != SDep::Data
1582 || PredDep.getSUnit()->isBoundaryNode()) {
1583 continue;
1584 }
1585 // An already visited edge is a cross edge, assuming an acyclic DAG.
1586 if (Impl.isVisited(PredDep.getSUnit())) {
1587 Impl.visitCrossEdge(PredDep, DFS.getCurr());
1588 continue;
1589 }
1590 Impl.visitPreorder(PredDep.getSUnit());
1591 DFS.follow(PredDep.getSUnit());
1592 }
1593 // Visit the top of the stack in postorder and backtrack.
1594 const SUnit *Child = DFS.getCurr();
1595 const SDep *PredDep = DFS.backtrack();
1596 Impl.visitPostorderNode(Child);
1597 if (PredDep)
1598 Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
1599 if (DFS.isComplete())
1600 break;
1601 }
1602 }
1603 Impl.finalize(SUnits);
1604}
1605
1606/// The root of the given SubtreeID was just scheduled. For all subtrees
1607/// connected to this tree, record the depth of the connection so that the
1608/// nearest connected subtrees can be prioritized.
1609void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1610 for (const Connection &C : SubtreeConnections[SubtreeID]) {
1611 SubtreeConnectLevels[C.TreeID] =
1612 std::max(SubtreeConnectLevels[C.TreeID], C.Level);
1613 LLVM_DEBUG(dbgs() << " Tree: " << C.TreeID << " @"
1614 << SubtreeConnectLevels[C.TreeID] << '\n');
1615 }
1616}
1617
1618#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1620 OS << InstrCount << " / " << Length << " = ";
1621 if (!Length)
1622 OS << "BADILP";
1623 else
1624 OS << format("%g", ((double)InstrCount / Length));
1625}
1626
1628 dbgs() << *this << '\n';
1629}
1630
1631[[maybe_unused]]
1633 Val.print(OS);
1634 return OS;
1635}
1636
1637#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
static unsigned InstrCount
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
Equivalence classes for small integers.
A common definition of LaneBitmask for use in TableGen and CodeGen.
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
static cl::opt< bool > UseAA("loongarch-use-aa", cl::init(true), cl::desc("Enable the use of AA during codegen."))
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
This file implements a map that provides insertion order iteration.
#define P(N)
MachineRegisterInfo & MRI
static void toggleKills(const MachineRegisterInfo &MRI, LiveRegUnits &LiveRegs, MachineInstr &MI, bool addToLiveRegs)
static bool getUnderlyingObjectsForInstr(const MachineInstr *MI, const MachineFrameInfo &MFI, UnderlyingObjectsVector &Objects, const DataLayout &DL)
If this machine instruction has memory reference information, collect the list of underlying objects ...
static bool hasDataSucc(const SUnit *SU)
This file defines the SmallVector class.
This file defines the SparseSet class derived from the version described in Briggs,...
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
ConstMIBundleOperands - Iterate over all operands in a const bundle of machine instructions.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A set of register units used to track register liveness.
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
bool hasImplicitUseOfPhysReg(MCRegister Reg) const
Return true if this instruction implicitly uses the specified physical register.
LLVM_ABI bool hasImplicitDefOfPhysReg(MCRegister Reg, const MCRegisterInfo *MRI=nullptr) const
Return true if this instruction implicitly defines the specified physical register.
MCRegUnitMaskIterator enumerates a list of register units and their associated lane masks for Reg.
bool isValid() const
Returns true if this iterator is not yet at the end.
LaneBitmask getLaneMask() const
Returns the combination of all lane masks of register in this class.
const bool HasDisjunctSubRegs
Whether the class supports two (or more) disjunct subregister indices.
Instructions::iterator instr_iterator
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasTailCall() const
Returns true if the function contains a tail call.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Representation of each machine instruction.
bool isBarrier(QueryType Type=AnyInBundle) const
Returns true if the specified instruction stops control flow from executing the instruction immediate...
bool isCall(QueryType Type=AnyInBundle) const
LLVM_ABI bool mayAlias(BatchAAResults *AA, const MachineInstr &Other, bool UseTBAA) const
Returns true if this instruction's memory access aliases the memory access of Other.
bool isInlineAsm() const
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
LLVM_ABI void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
filtered_mop_range all_uses()
Returns an iterator range over all operands that are (explicit or implicit) register uses.
bool isTransient() const
Return true if this is a transient instruction that is either very likely to be eliminated during reg...
LLVM_ABI void dump() const
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo=nullptr) const
Find the index of the flag word operand that corresponds to operand OpIdx on an inline asm instructio...
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
void setIsKill(bool Val=true)
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
Array of PressureDiffs.
LLVM_ABI void init(unsigned N)
Initialize an array of N PressureDiffs.
Special value supplied for machine level alias analysis.
Track the current register pressure at some position in the instruction stream, and remember the high...
List of registers defined and used by a machine instruction.
LLVM_ABI void detectDeadDefs(const MachineInstr &MI, LiveIntervals &LIS, const MachineRegisterInfo &MRI)
Use liveness information to find dead defs at MI's dead slot not marked with a dead flag and move the...
LLVM_ABI void adjustLaneLiveness(LiveIntervals &LIS, const MachineRegisterInfo &MRI, SlotIndex Pos)
Use liveness information to find out which uses/defs are partially undefined/dead at Pos and adjust t...
LLVM_ABI void collect(const MachineInstr &MI, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, bool TrackLaneMasks, bool IgnoreDead)
Analyze the given instruction MI and fill in the Uses, Defs and DeadDefs list based on the MachineOpe...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Scheduling dependency.
Definition ScheduleDAG.h:54
SUnit * getSUnit() const
Kind getKind() const
Returns an enum value representing the kind of the dependence.
Kind
These are the different kinds of scheduling dependencies.
Definition ScheduleDAG.h:57
@ Output
A register output-dependence (aka WAW).
Definition ScheduleDAG.h:60
@ Anti
A register anti-dependence (aka WAR).
Definition ScheduleDAG.h:59
@ Data
Regular data dependence (aka true-dependence).
Definition ScheduleDAG.h:58
void setLatency(unsigned Lat)
Sets the latency for this edge.
@ Artificial
Arbitrary strong DAG edge (no real dependence).
Definition ScheduleDAG.h:77
@ MayAliasMem
Nonvolatile load/Store instructions that may alias.
Definition ScheduleDAG.h:75
bool isArtificial() const
Tests if this is an Order dependence that is marked as "artificial", meaning it isn't necessary for c...
Scheduling unit. This is a node in the scheduling DAG.
bool isCall
Is a function call.
bool addPredBarrier(SUnit *SU)
Adds a barrier edge to SU by calling addPred(), with latency 0 generally or latency 1 for a store fol...
unsigned NumSuccs
unsigned TopReadyCycle
Cycle relative to start when node is ready.
unsigned NodeNum
Entry # of node in the node vector.
bool isUnbuffered
Uses an unbuffered resource.
SmallVectorImpl< SDep >::const_iterator const_pred_iterator
unsigned short Latency
Node latency.
bool isBoundaryNode() const
Boundary nodes are placeholders for the boundary of the scheduling region.
bool hasPhysRegDefs
Has physreg defs that are being used.
unsigned BotReadyCycle
Cycle relative to end when node is ready.
SmallVector< SDep, 4 > Succs
All sunit successors.
bool hasReservedResource
Uses a reserved resource.
bool isCommutable
Is a commutable instruction.
bool hasPhysRegUses
Has physreg uses.
SmallVector< SDep, 4 > Preds
All sunit predecessors.
LLVM_ABI bool addPred(const SDep &D, bool Required=true)
Adds the specified edge as a pred of the current node if not already.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
void visitPostorderNode(const SUnit *SU)
Called once for each node after all predecessors are visited.
bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ, bool CheckLimit=true)
Joins the predecessor subtree with the successor that is its DFS parent.
void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth)
Called by finalize() to record a connection between trees.
void visitCrossEdge(const SDep &PredDep, const SUnit *Succ)
Adds a connection for cross edges.
void finalize(ArrayRef< SUnit > SUnits)
Sets each node's subtree ID to the representative ID and record connections between trees.
void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ)
Called once for each tree edge after calling visitPostOrderNode on the predecessor.
void visitPreorder(const SUnit *SU)
Initializes this node's instruction count.
bool isVisited(const SUnit *SU) const
Returns true if this node been visited by the DFS traversal.
SchedDFSImpl(SchedDFSResult &r)
Compute the values of each DAG node for various metrics during DFS.
Definition ScheduleDFS.h:65
friend class SchedDFSImpl
Definition ScheduleDFS.h:66
LLVM_ABI void compute(ArrayRef< SUnit > SUnits)
Compute various metrics for the DAG with given roots.
LLVM_ABI void scheduleTree(unsigned SubtreeID)
Scheduler callback to update SubtreeConnectLevels when a tree is initially scheduled.
ScheduleDAGDependencyBuilder(ScheduleDAGInstrs &DAG, BatchAAResults *AA, RegPressureTracker *RPTracker, PressureDiffs *PDiffs, LiveIntervals *LIS)
A ScheduleDAG for scheduling lists of MachineInstr.
LiveRegUnits LiveRegs
Set of live physical registers for updating kill flags.
DenseMap< MachineInstr *, SUnit * > MISUnitMap
After calling BuildSchedGraph, each machine instruction in the current scheduling region is mapped to...
void addVRegUseDeps(SUnit *SU, unsigned OperIdx)
Adds a register data dependency if the instruction that defines the virtual register used at OperIdx ...
void addVRegDefDeps(SUnit *SU, unsigned OperIdx)
Adds register output and data dependencies from this SUnit to instructions that occur later in the sa...
virtual void finishBlock()
Cleans up after scheduling in the given block.
MachineBasicBlock::iterator end() const
Returns an iterator to the bottom of the current scheduling region.
std::string getDAGName() const override
Returns a label for the region of code covered by the DAG.
MachineBasicBlock * BB
The block in which to insert instructions.
virtual void startBlock(MachineBasicBlock *BB)
Prepares to perform scheduling in the given block.
void addPhysRegDeps(SUnit *SU, unsigned OperIdx)
Adds register dependencies (data, anti, and output) from this SUnit to following instructions in the ...
const CodeGenOptions & Opts
friend class ScheduleDAGDependencyBuilder
MachineBasicBlock::iterator RegionEnd
The end of the range to be scheduled.
VReg2SUnitOperIdxMultiMap CurrentVRegUses
Tracks the last instructions in this region using each virtual register.
const MCSchedClassDesc * getSchedClass(SUnit *SU) const
Resolves and cache a resolved scheduling class for an SUnit.
void fixupKills(MachineBasicBlock &MBB)
Fixes register kill flags that scheduling has made invalid.
void addPhysRegDataDeps(SUnit *SU, unsigned OperIdx)
MO is an operand of SU's instruction that defines a physical register.
ScheduleDAGInstrs(MachineFunction &mf, const MachineLoopInfo *mli, bool RemoveKillFlags=false)
LaneBitmask getLaneMaskForMO(const MachineOperand &MO) const
Returns a mask for which lanes get read/written by the given (register) machine operand.
DbgValueVector DbgValues
Remember instruction that precedes DBG_VALUE.
SUnit * newSUnit(MachineInstr *MI)
Creates a new SUnit and return a ptr to it.
void initSUnits()
Creates an SUnit for each real instruction, numbered in top-down topological order.
bool addEdge(SUnit *SuccSU, const SDep &PredDep)
Add a DAG edge to the given SU with the given predecessor dependence data.
ScheduleDAGTopologicalSort Topo
Topo - A topological ordering for SUnits which permits fast IsReachable and similar queries.
bool TrackLaneMasks
Whether lane masks should get tracked.
void dumpNode(const SUnit &SU) const override
RegUnit2SUnitsMap Defs
Defs, Uses - Remember where defs and uses of each register are as we iterate upward through the instr...
VReg2SUnitMultiMap CurrentVRegDefs
Tracks the last instruction(s) in this region defining each virtual register.
MachineBasicBlock::iterator begin() const
Returns an iterator to the top of the current scheduling region.
void buildSchedGraph(AAResults *AA, RegPressureTracker *RPTracker=nullptr, PressureDiffs *PDiffs=nullptr, LiveIntervals *LIS=nullptr, bool TrackLaneMasks=false)
Builds SUnits for the current region.
TargetSchedModel SchedModel
TargetSchedModel provides an interface to the machine model.
virtual void exitRegion()
Called when the scheduler has finished scheduling the current region.
bool canAddEdge(SUnit *SuccSU, SUnit *PredSU)
True if an edge can be added from PredSU to SuccSU without creating a cycle.
const MachineLoopInfo * MLI
bool RemoveKillFlags
True if the DAG builder should remove kill flags (in preparation for rescheduling).
MachineBasicBlock::iterator RegionBegin
The beginning of the range to be scheduled.
void addSchedBarrierDeps()
Adds dependencies from instructions in the current list of instructions being scheduled to scheduling...
virtual void enterRegion(MachineBasicBlock *bb, MachineBasicBlock::iterator begin, MachineBasicBlock::iterator end, unsigned regioninstrs)
Initialize the DAG and common scheduler state for a new scheduling region.
void dump() const override
unsigned NumRegionInstrs
Instructions in this region (distance(RegionBegin, RegionEnd)).
const MachineFrameInfo & MFI
bool deadDefHasNoUse(const MachineOperand &MO)
Returns true if the def register in MO has no uses.
MachineRegisterInfo & MRI
Virtual/real register map.
void clearDAG()
Clears the DAG state (between regions).
std::vector< SUnit > SUnits
The scheduling units.
const TargetRegisterInfo * TRI
Target processor register info.
SUnit EntrySU
Special node for the region entry.
MachineFunction & MF
Machine function.
ScheduleDAG(const ScheduleDAG &)=delete
void dumpNodeAll(const SUnit &SU) const
void dumpNodeName(const SUnit &SU) const
SUnit ExitSU
Special node for the region exit.
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
SparseSet - Fast set implementation for objects that can be identified by small unsigned keys.
Definition SparseSet.h:118
TargetInstrInfo - Interface to description of machine instruction set.
TargetSubtargetInfo - Generic base class for all target subtargets.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
SmallVector< ValueType, 4 > UnderlyingObjectsVector
LLVM_ABI bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IterT skipDebugInstructionsBackward(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It until it points to a non-debug instruction or to Begin and return the resulting iterator...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
constexpr bool valueOr(BoolOrDefault X, bool Default)
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
Represent the ILP of the subDAG rooted at a DAG node.
Definition ScheduleDFS.h:34
unsigned Length
Length may either correspond to depth or height, depending on direction, and cycles or nodes dependin...
Definition ScheduleDFS.h:38
LLVM_ABI void dump() const
LLVM_ABI void print(raw_ostream &OS) const
unsigned InstrCount
Definition ScheduleDFS.h:35
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82
constexpr bool any() const
Definition LaneBitmask.h:53
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Definition MCSchedule.h:124
Identify one of the processor resource kinds consumed by a particular scheduling class for the specif...
Definition MCSchedule.h:69
Record a physical register access.
Mapping from virtual register to SUnit including an operand index.
An individual mapping from virtual register number to SUnit.