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 // Recognize asm outputs and clobbers by their operand groups, excluding
208 // trailing register bookkeeping operands.
209 bool IsInlineAsmDef = SU->getInstr()->isInlineAsm() &&
210 SU->getInstr()->findInlineAsmFlagIdx(OperIdx) >= 0;
211 bool ImplicitPseudoDef = OperIdx >= DefMIDesc.getNumOperands() &&
212 !DefMIDesc.hasImplicitDefOfPhysReg(Reg) &&
213 !IsInlineAsmDef;
214 for (MCRegUnit Unit : TRI->regunits(Reg)) {
215 for (RegUnit2SUnitsMap::iterator I = Uses.find(Unit); I != Uses.end();
216 ++I) {
217 SUnit *UseSU = I->SU;
218 if (UseSU == SU)
219 continue;
220
221 // Adjust the dependence latency using operand def/use information,
222 // then allow the target to perform its own adjustments.
223 MachineInstr *UseInstr = nullptr;
224 int UseOpIdx = I->OpIdx;
225 bool ImplicitPseudoUse = false;
226 SDep Dep;
227 if (UseOpIdx < 0) {
228 Dep = SDep(SU, SDep::Artificial);
229 } else {
230 // Set the hasPhysRegDefs only for physreg defs that have a use within
231 // the scheduling region.
232 SU->hasPhysRegDefs = true;
233
234 UseInstr = UseSU->getInstr();
235 Register UseReg = UseInstr->getOperand(UseOpIdx).getReg();
236 const MCInstrDesc &UseMIDesc = UseInstr->getDesc();
237 // Recognize asm inputs by their operand groups, excluding trailing
238 // register bookkeeping operands.
239 bool IsInlineAsmUse = UseInstr->isInlineAsm() &&
240 UseInstr->findInlineAsmFlagIdx(UseOpIdx) >= 0;
241 ImplicitPseudoUse = UseOpIdx >= ((int)UseMIDesc.getNumOperands()) &&
242 !UseMIDesc.hasImplicitUseOfPhysReg(UseReg) &&
243 !IsInlineAsmUse;
244
245 Dep = SDep(SU, SDep::Data, UseReg);
246 }
247 if (!ImplicitPseudoDef && !ImplicitPseudoUse) {
248 Dep.setLatency(SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
249 UseInstr, UseOpIdx));
250 } else {
251 Dep.setLatency(0);
252 }
253 ST.adjustSchedDependency(SU, OperIdx, UseSU, UseOpIdx, Dep, &SchedModel);
254 UseSU->addPred(Dep);
255 }
256 }
257}
258
259/// Adds register dependencies (data, anti, and output) from this SUnit
260/// to following instructions in the same scheduling region that depend the
261/// physical register referenced at OperIdx.
262void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
263 MachineInstr *MI = SU->getInstr();
264 MachineOperand &MO = MI->getOperand(OperIdx);
265 Register Reg = MO.getReg();
266 // We do not need to track any dependencies for constant registers.
267 if (MRI.isConstantPhysReg(Reg))
268 return;
269
270 const TargetSubtargetInfo &ST = MF.getSubtarget();
271
272 // Optionally add output and anti dependencies. For anti
273 // dependencies we use a latency of 0 because for a multi-issue
274 // target we want to allow the defining instruction to issue
275 // in the same cycle as the using instruction.
276 // TODO: Using a latency of 1 here for output dependencies assumes
277 // there's no cost for reusing registers.
278 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
279 for (MCRegUnit Unit : TRI->regunits(Reg)) {
280 for (RegUnit2SUnitsMap::iterator I = Defs.find(Unit); I != Defs.end();
281 ++I) {
282 SUnit *DefSU = I->SU;
283 if (DefSU == &ExitSU)
284 continue;
285 MachineInstr *DefInstr = DefSU->getInstr();
286 MachineOperand &DefMO = DefInstr->getOperand(I->OpIdx);
287 if (DefSU != SU &&
288 (Kind != SDep::Output || !MO.isDead() || !DefMO.isDead())) {
289 SDep Dep(SU, Kind, DefMO.getReg());
290 if (Kind != SDep::Anti) {
291 Dep.setLatency(
292 SchedModel.computeOutputLatency(MI, OperIdx, DefInstr));
293 }
294 ST.adjustSchedDependency(SU, OperIdx, DefSU, I->OpIdx, Dep,
295 &SchedModel);
296 DefSU->addPred(Dep);
297 }
298 }
299 }
300
301 if (MO.isUse()) {
302 SU->hasPhysRegUses = true;
303 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
304 // retrieve the existing SUnits list for this register's uses.
305 // Push this SUnit on the use list.
306 for (MCRegUnit Unit : TRI->regunits(Reg))
307 Uses.insert(PhysRegSUOper(SU, OperIdx, Unit));
308 if (RemoveKillFlags)
309 MO.setIsKill(false);
310 } else {
311 addPhysRegDataDeps(SU, OperIdx);
312
313 // Clear previous uses and defs of this register and its subregisters.
314 for (MCRegUnit Unit : TRI->regunits(Reg)) {
315 Uses.eraseAll(Unit);
316 if (!MO.isDead())
317 Defs.eraseAll(Unit);
318 }
319
320 if (MO.isDead() && SU->isCall) {
321 // Calls will not be reordered because of chain dependencies (see
322 // below). Since call operands are dead, calls may continue to be added
323 // to the DefList making dependence checking quadratic in the size of
324 // the block. Instead, we leave only one call at the back of the
325 // DefList.
326 for (MCRegUnit Unit : TRI->regunits(Reg)) {
327 RegUnit2SUnitsMap::RangePair P = Defs.equal_range(Unit);
330 for (bool isBegin = I == B; !isBegin; /* empty */) {
331 isBegin = (--I) == B;
332 if (!I->SU->isCall)
333 break;
334 I = Defs.erase(I);
335 }
336 }
337 }
338
339 // Defs are pushed in the order they are visited and never reordered.
340 for (MCRegUnit Unit : TRI->regunits(Reg))
341 Defs.insert(PhysRegSUOper(SU, OperIdx, Unit));
342 }
343}
344
346{
347 Register Reg = MO.getReg();
348 // No point in tracking lanemasks if we don't have interesting subregisters.
349 const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
350 if (!RC.HasDisjunctSubRegs)
351 return LaneBitmask::getAll();
352
353 unsigned SubReg = MO.getSubReg();
354 if (SubReg == 0)
355 return RC.getLaneMask();
356 return TRI->getSubRegIndexLaneMask(SubReg);
357}
358
360 auto RegUse = CurrentVRegUses.find(MO.getReg());
361 if (RegUse == CurrentVRegUses.end())
362 return true;
363 return (RegUse->LaneMask & getLaneMaskForMO(MO)).none();
364}
365
366/// Adds register output and data dependencies from this SUnit to instructions
367/// that occur later in the same scheduling region if they read from or write to
368/// the virtual register defined at OperIdx.
369///
370/// TODO: Hoist loop induction variable increments. This has to be
371/// reevaluated. Generally, IV scheduling should be done before coalescing.
372void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
373 MachineInstr *MI = SU->getInstr();
374 MachineOperand &MO = MI->getOperand(OperIdx);
375 Register Reg = MO.getReg();
376
377 LaneBitmask DefLaneMask;
378 LaneBitmask KillLaneMask;
379 if (TrackLaneMasks) {
380 bool IsKill = MO.getSubReg() == 0 || MO.isUndef();
381 DefLaneMask = getLaneMaskForMO(MO);
382 // If we have a <read-undef> flag, none of the lane values comes from an
383 // earlier instruction.
384 KillLaneMask = IsKill ? LaneBitmask::getAll() : DefLaneMask;
385
386 if (MO.getSubReg() != 0 && MO.isUndef()) {
387 // There may be other subregister defs on the same instruction of the same
388 // register in later operands. The lanes of other defs will now be live
389 // after this instruction, so these should not be treated as killed by the
390 // instruction even though they appear to be killed in this one operand.
391 for (const MachineOperand &OtherMO :
392 llvm::drop_begin(MI->operands(), OperIdx + 1))
393 if (OtherMO.isReg() && OtherMO.isDef() && OtherMO.getReg() == Reg)
394 KillLaneMask &= ~getLaneMaskForMO(OtherMO);
395 }
396
397 // Clear undef flag, we'll re-add it later once we know which subregister
398 // Def is first.
399 MO.setIsUndef(false);
400 } else {
401 DefLaneMask = LaneBitmask::getAll();
402 KillLaneMask = LaneBitmask::getAll();
403 }
404
405 if (MO.isDead()) {
406 assert(deadDefHasNoUse(MO) && "Dead defs should have no uses");
407 } else {
408 // Add data dependence to all uses we found so far.
409 const TargetSubtargetInfo &ST = MF.getSubtarget();
411 E = CurrentVRegUses.end(); I != E; /*empty*/) {
412 LaneBitmask LaneMask = I->LaneMask;
413 // Ignore uses of other lanes.
414 if ((LaneMask & KillLaneMask).none()) {
415 ++I;
416 continue;
417 }
418
419 if ((LaneMask & DefLaneMask).any()) {
420 SUnit *UseSU = I->SU;
421 MachineInstr *Use = UseSU->getInstr();
422 SDep Dep(SU, SDep::Data, Reg);
423 Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use,
424 I->OperandIndex));
425 ST.adjustSchedDependency(SU, OperIdx, UseSU, I->OperandIndex, Dep,
426 &SchedModel);
427 UseSU->addPred(Dep);
428 }
429
430 LaneMask &= ~KillLaneMask;
431 // If we found a Def for all lanes of this use, remove it from the list.
432 if (LaneMask.any()) {
433 I->LaneMask = LaneMask;
434 ++I;
435 } else
436 I = CurrentVRegUses.erase(I);
437 }
438 }
439
440 // Shortcut: Singly defined vregs do not have output/anti dependencies.
441 if (MRI.hasOneDef(Reg))
442 return;
443
444 // Add output dependence to the next nearest defs of this vreg.
445 //
446 // Unless this definition is dead, the output dependence should be
447 // transitively redundant with antidependencies from this definition's
448 // uses. We're conservative for now until we have a way to guarantee the uses
449 // are not eliminated sometime during scheduling. The output dependence edge
450 // is also useful if output latency exceeds def-use latency.
451 LaneBitmask LaneMask = DefLaneMask;
452 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
453 CurrentVRegDefs.end())) {
454 // Ignore defs for other lanes.
455 if ((V2SU.LaneMask & LaneMask).none())
456 continue;
457 // Add an output dependence.
458 SUnit *DefSU = V2SU.SU;
459 // Ignore additional defs of the same lanes in one instruction. This can
460 // happen because lanemasks are shared for targets with too many
461 // subregisters. We also use some representration tricks/hacks where we
462 // add super-register defs/uses, to imply that although we only access parts
463 // of the reg we care about the full one.
464 if (DefSU == SU)
465 continue;
466 SDep Dep(SU, SDep::Output, Reg);
467 Dep.setLatency(
468 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
469 DefSU->addPred(Dep);
470
471 // Update current definition. This can get tricky if the def was about a
472 // bigger lanemask before. We then have to shrink it and create a new
473 // VReg2SUnit for the non-overlapping part.
474 LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
475 LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
476 V2SU.SU = SU;
477 V2SU.LaneMask = OverlapMask;
478 if (NonOverlapMask.any())
479 CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, DefSU));
480 }
481 // If there was no CurrentVRegDefs entry for some lanes yet, create one.
482 if (LaneMask.any())
483 CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU));
484}
485
486/// Adds a register data dependency if the instruction that defines the
487/// virtual register used at OperIdx is mapped to an SUnit. Add a register
488/// antidependency from this SUnit to instructions that occur later in the same
489/// scheduling region if they write the virtual register.
490///
491/// TODO: Handle ExitSU "uses" properly.
492void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
493 const MachineInstr *MI = SU->getInstr();
494 assert(!MI->isDebugOrPseudoInstr());
495
496 const MachineOperand &MO = MI->getOperand(OperIdx);
497 Register Reg = MO.getReg();
498
499 // Remember the use. Data dependencies will be added when we find the def.
502 CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU));
503
504 // Add antidependences to the following defs of the vreg.
505 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
506 CurrentVRegDefs.end())) {
507 // Ignore defs for unrelated lanes.
508 LaneBitmask PrevDefLaneMask = V2SU.LaneMask;
509 if ((PrevDefLaneMask & LaneMask).none())
510 continue;
511 if (V2SU.SU == SU)
512 continue;
513
514 V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg));
515 }
516}
517
518/// Creates an SUnit for each real instruction, numbered in top-down
519/// topological order. The instruction order A < B, implies that no edge exists
520/// from B to A.
521///
522/// Map each real instruction to its SUnit.
523///
524/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
525/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
526/// instead of pointers.
527///
528/// MachineScheduler relies on initSUnits numbering the nodes by their order in
529/// the original instruction list.
531 // We'll be allocating one SUnit for each real instruction in the region,
532 // which is contained within a basic block.
533 SUnits.reserve(NumRegionInstrs);
534
536 if (MI.isDebugOrPseudoInstr())
537 continue;
538
539 SUnit *SU = newSUnit(&MI);
540 MISUnitMap[&MI] = SU;
541
542 SU->isCall = MI.isCall();
543 SU->isCommutable = MI.isCommutable();
544
545 // Assign the Latency field of SU using target-provided information.
546 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
547
548 // If this SUnit uses a reserved or unbuffered resource, mark it as such.
549 //
550 // Reserved resources block an instruction from issuing and stall the
551 // entire pipeline. These are identified by BufferSize=0.
552 //
553 // Unbuffered resources prevent execution of subsequent instructions that
554 // require the same resources. This is used for in-order execution pipelines
555 // within an out-of-order core. These are identified by BufferSize=1.
556 if (SchedModel.hasInstrSchedModel()) {
557 const MCSchedClassDesc *SC = getSchedClass(SU);
558 for (const MCWriteProcResEntry &PRE :
559 make_range(SchedModel.getWriteProcResBegin(SC),
560 SchedModel.getWriteProcResEnd(SC))) {
561 switch (SchedModel.getResourceBufferSize(PRE.ProcResourceIdx)) {
562 case 0:
563 SU->hasReservedResource = true;
564 break;
565 case 1:
566 SU->isUnbuffered = true;
567 break;
568 default:
569 break;
570 }
571 }
572 }
573 }
574}
575
576namespace {
577/// A list of SUnits, used during DAG construction.
578/// FIXME: to gain speed it might be worth investigating an optimized
579/// implementation of this data structure, such as a singly linked list
580/// with a memory pool (SmallVector was tried but slow and SparseSet is not
581/// applicable).
582using SUList = std::list<SUnit *>;
583} // end anonymous namespace
584
585namespace llvm {
587private:
588 const CodeGenOptions &Opts;
590
591 BatchAAResults *AA;
592 RegPressureTracker *RPTracker;
593 PressureDiffs *PDiffs;
594 LiveIntervals *LIS;
595
596 // Track all instructions that may raise floating-point exceptions.
597 // These do not depend on one other (or normal loads or stores), but
598 // must not be rescheduled across global barriers.
599 SUList FPExceptions;
600
601 /// A frontier of unanalyzable memory operations.
602 ///
603 /// As we process memory operations (bottom to top), each new memory operation
604 /// needs to be checked for required control dependencies against later memory
605 /// operations. A naive implementation issues AA calls quadratically in the
606 /// number of memory operations and is therefore unacceptable.
607 ///
608 /// To bound the complexity, we only ever consider a frontier of memory
609 /// operations which we frequently clear, modeled by this struct. To ensure
610 /// that we are not missing any necessary control dependencies, we promote
611 /// certain store instructions to what we term 'sequencing stores'. These
612 /// sequencing stores are treated carefully to ensure that all previously seen
613 /// unanalyzable memory operations that do not belong to the frontier
614 /// necessarily transitively succeed the current sequencing store.
615 ///
616 /// By frequently updating the sequencing store, we bound the number of alias
617 /// analysis queries and transitively redundant control dependencies we
618 /// generate. However, doing so we necessarily overconstrain the DAG. Indeed,
619 /// if we were to update the sequencing store every time we see a store
620 /// instruction, the effect would be to linearize the stores.
621 struct MemopFrontier {
622 // The current sequencing store.
623 SUnit *SequencingStore = nullptr;
624 /// The memory operations in the frontier.
625 SUList Stores, Loads;
626
627 /// The number of memops in the frontier, excluding the sequencing store.
628 unsigned size() const;
629
630 /// Clears the frontier.
631 void clear();
632 };
633
634 // For memory operations that can be analyzed to an identified underlying
635 // object, we maintain one frontier per underlying object. Two SUs are
636 // trivially non-aliasing if they both depend on only identified Values and do
637 // not share any common Value. We expect the analyzable frontiers to remain
638 // small and benefit from alias analysis, so only clear when they grow too
639 // large.
640 MapVector<ValueType, MemopFrontier> AnalyzableFrontiers;
641
642 /// We maintain an additional frontier of unanalyzable memory operations,
643 /// equipped with some extra state designed to clear the frontier more
644 /// frequently. The conditions we choose to update the sequencing store are as
645 /// follows:
646 ///
647 /// The conditions we choose to update the sequencing store are as follows:
648 /// 1. If an incoming store instruction refers to an underlying object outside
649 /// of the set of underlying objects of the current sequencing store;
650 /// 2. If an incoming store instruction precedes an intervening load from an
651 /// underlying object outside of the set of underlying objects of the
652 /// current sequencing store (a 'sequencing load').
653 /// In these cases, a BasicAA query will (generally) already induce a
654 /// (transitive) edge from the incoming store to the current sequencing store.
655 /// However, this process introduces spurious (transitive) barrier edges in
656 /// the following cases:
657 /// 1. From all preceding loads to the new sequencing store;
658 /// 2. From the new sequencing store to all stores in the current frontier;
659 /// 3. From all preceding unanalyzable stores to (a subset of) the same base
660 /// objects, independent of AA results;
661 /// 4. From all preceding analyzable stores, independent of AA results.
662 struct UnanalyzableMemopFrontier {
663 /// The underlying memop frontier.
664 MemopFrontier Frontier;
665 /// The underlying objects of the current sequencing store.
666 UnderlyingObjectsVector BaseObjects;
667 /// `true` if the frontier contains a load whose underlying objects escape
668 /// #BaseObjects.
669 bool SeenSequencingLoad = false;
670
671 /// Returns true if any of \p Objs does not belong to #BaseObjects.
672 bool escapesBaseObjects(const UnderlyingObjectsVector &Objs) const;
673
674 /// Clears the frontier and resets the associated state.
675 void clear();
676 };
677
678 /// Track a frontier of unanalyzable memory operations.
679 ///
680 /// FIXME(@cofibrant): For some platforms, a single frontier is too coarse and
681 /// we should be maintaining one frontier per address space.
682 UnanalyzableMemopFrontier UnanalyzableFrontier;
683
684 /// Remember a generic side-effecting instruction as we proceed.
685 /// No other SU ever gets scheduled around it (except in the special
686 /// case of a huge region that gets reduced).
687 SUnit *BarrierChain = nullptr;
688
689 unsigned MemOpsProcessed = 0;
690
691 /// Tracks the total occupancy of all memop frontiers, including sequencing
692 /// stores.
693 unsigned MemopsInFlight = 0;
694
695public:
697 RegPressureTracker *RPTracker,
698 PressureDiffs *PDiffs, LiveIntervals *LIS)
699 : Opts(DAG.Opts), DAG(DAG), AA(AA), RPTracker(RPTracker), PDiffs(PDiffs),
700 LIS(LIS) {}
701
702private:
703 /// Adds a chain edge between SUa and SUb, but only if both
704 /// AAResults and Target fail to deny the dependency.
705 ///
706 /// Returns true if an edge was inserted.
707 bool addChainDependency(SUnit *SUa, SUnit *SUb, unsigned Latency = 0);
708
709 /// Adds dependencies as needed from all SUs in list to SU.
710 void addChainDependencies(SUnit *SU, SUList &SUs, unsigned Latency);
711 void addChainDependencies(SUnit *SU, MemopFrontier &F, bool IsStore);
712
713 void addBarrierChain(SUList &SUs);
714 void addBarrierChain(MemopFrontier &F);
715
716 /// Add dependencies from the barrier chain to all in flight memory operations
717 /// and clear the memop frontiers.
718 void addBarrierMemoryDeps();
719
720 /// Returns true if the next store should be promoted to a sequencing store
721 /// in the frontier \p F and false otherwise.
722 bool shouldUpdate(const MemopFrontier &F) const;
723
724 /// Given a store instruction with underlying objects \p Objs, returns true
725 /// if the store should be promoted to a sequencing store in the frontier
726 /// \p UF and false otherwise.
727 bool shouldUpdate(const UnanalyzableMemopFrontier &UF,
728 const UnderlyingObjectsVector &Objs) const;
729
730 /// Promote the store \p SU to be a new sequencing store in the frontier \p F.
731 /// If \p PreserveNoAliasLoads is true, loads in the frontier that do not
732 /// alias with \p SU will be retained after promotion.
733 void updateSequencingStore(MemopFrontier &F, SUnit *SU,
734 bool PreserveNoAliasLoads = false);
735
736 /// Promote the store \p SU with underlying objects \p Objs to be a new
737 /// sequencing store in the frontier \p UF.
738 void updateSequencingStore(UnanalyzableMemopFrontier &UF, SUnit *SU,
740
741public:
742 void buildDeps();
743};
744} // end namespace llvm
745
746unsigned ScheduleDAGDependencyBuilder::MemopFrontier::size() const {
747 return Loads.size() + Stores.size();
748}
749
750void ScheduleDAGDependencyBuilder::MemopFrontier::clear() {
751 SequencingStore = nullptr;
752 Stores.clear();
753 Loads.clear();
754}
755
756bool ScheduleDAGDependencyBuilder::shouldUpdate(const MemopFrontier &F) const {
757 if (!Opts.store_sequencing)
758 return false;
759 return F.size() >= Opts.store_sequencing_max_frontier_size;
760}
761
762bool ScheduleDAGDependencyBuilder::shouldUpdate(
763 const UnanalyzableMemopFrontier &UF,
764 const UnderlyingObjectsVector &Objs) const {
765 if (!Opts.store_sequencing)
766 return false;
767 return shouldUpdate(UF.Frontier) || !UF.Frontier.SequencingStore ||
768 UF.SeenSequencingLoad || UF.escapesBaseObjects(Objs);
769}
770
771bool ScheduleDAGDependencyBuilder::UnanalyzableMemopFrontier::
772 escapesBaseObjects(const UnderlyingObjectsVector &Objs) const {
773 for (const ValueType V : Objs) {
774 if (!is_contained(BaseObjects, V))
775 return true;
776 }
777
778 return false;
779}
780
781void ScheduleDAGDependencyBuilder::UnanalyzableMemopFrontier::clear() {
782 Frontier.clear();
783 SeenSequencingLoad = false;
784 BaseObjects.clear();
785}
786
787bool ScheduleDAGDependencyBuilder::addChainDependency(SUnit *SUa, SUnit *SUb,
788 unsigned Latency) {
789 if (!SUa->getInstr()->mayAlias(AA, *SUb->getInstr(), Opts.sched_mi_tbaa))
790 return false;
791
792 SDep Dep(SUa, SDep::MayAliasMem);
793 Dep.setLatency(Latency);
794 SUb->addPred(Dep);
795 return true;
796}
797
798void ScheduleDAGDependencyBuilder::addChainDependencies(SUnit *SU, SUList &SUs,
799 unsigned Latency) {
800 for (SUnit *Entry : SUs)
801 addChainDependency(SU, Entry, Latency);
802}
803
804void ScheduleDAGDependencyBuilder::addChainDependencies(SUnit *SU,
805 MemopFrontier &F,
806 bool IsStore) {
807 if (F.SequencingStore)
808 F.SequencingStore->addPredBarrier(SU);
809
810 addChainDependencies(SU, F.Stores, /*Latency=*/0);
811 if (IsStore)
812 addChainDependencies(SU, F.Loads, /*Latency=*/1);
813}
814
815void ScheduleDAGDependencyBuilder::addBarrierChain(SUList &SUs) {
816 assert(BarrierChain != nullptr);
817
818 for (auto *SU : SUs)
819 SU->addPredBarrier(BarrierChain);
820
821 SUs.clear();
822}
823
824void ScheduleDAGDependencyBuilder::addBarrierChain(MemopFrontier &F) {
825 assert(BarrierChain != nullptr);
826
827 addBarrierChain(F.Stores);
828 addBarrierChain(F.Loads);
829
830 if (F.SequencingStore)
831 F.SequencingStore->addPredBarrier(BarrierChain);
832
833 F.clear();
834}
835
836void ScheduleDAGDependencyBuilder::addBarrierMemoryDeps() {
837 assert(BarrierChain != nullptr);
838
839 addBarrierChain(UnanalyzableFrontier.Frontier);
840 UnanalyzableFrontier.clear();
841
842 for (auto &[_, AF] : AnalyzableFrontiers)
843 addBarrierChain(AF);
844 AnalyzableFrontiers.clear();
845
846 MemopsInFlight = 0;
847}
848
849void ScheduleDAGDependencyBuilder::updateSequencingStore(
850 MemopFrontier &F, SUnit *SU, bool PreserveNoAliasLoads) {
851 assert(SU->getInstr()->mayStore() &&
852 "Only store instructions should be used as sequencing stores");
853 LLVM_DEBUG(dbgs() << "Promoting " << *SU << " to sequencing store\n");
854
855 // Discount the memops we plan to clear.
856 MemopsInFlight -= F.size();
857
858 if (F.SequencingStore) {
859 F.SequencingStore->addPredBarrier(SU);
860 } else {
861 // Account for the new sequencing store.
862 ++MemopsInFlight;
863 }
864
865 // Sequence all stores against the sequencing store and clear the map.
866 for (SUnit *S : F.Stores)
867 S->addPredBarrier(SU);
868
869 F.Stores.clear();
870
871 if (PreserveNoAliasLoads) {
872 // If asked, for loads, we can do slightly better. Rather than naively
873 // adding pred barriers and clearing the map, we check whether each load
874 // genuinely needs to sequence against the new sequencing store. Wherever an
875 // edge is not required, we retain the load and avoid the spurious control
876 // dependency.
877 for (auto It = F.Loads.begin(); It != F.Loads.end();) {
878 if (addChainDependency(SU, *It, /*TrueMemOrderLatency=*/1)) {
879 It = F.Loads.erase(It);
880 } else {
881 ++It;
882 }
883 }
884
885 // Re-account for the potentially remaining loads.
886 MemopsInFlight += F.Loads.size();
887 } else {
888 // Sequence all loads against the sequencing store and clear the map.
889 for (SUnit *S : F.Loads)
890 S->addPredBarrier(SU);
891
892 F.Loads.clear();
893 }
894
895 F.SequencingStore = SU;
896}
897
898void ScheduleDAGDependencyBuilder::updateSequencingStore(
899 UnanalyzableMemopFrontier &UF, SUnit *SU, UnderlyingObjectsVector &&Objs) {
900 assert(SU->getInstr()->mayStore() &&
901 "Only store instructions should be used as sequencing stores");
902 // If the underlying MemopFrontier wants updating, we're over size and
903 // therefore shouldn't try to preserve no alias loads.
904 bool ShouldPreserveNoAliasLoads = !shouldUpdate(UF.Frontier);
905 updateSequencingStore(UF.Frontier, SU,
906 /*PreserveNoAliasLoads=*/ShouldPreserveNoAliasLoads);
907 UF.BaseObjects = std::move(Objs);
908 UF.SeenSequencingLoad = false;
909}
910
912 const TargetSubtargetInfo &ST = DAG.MF.getSubtarget();
913
914 // We build scheduling units by walking a block's instruction list
915 // from bottom to top.
916
917 // Model data dependencies between instructions being scheduled and the
918 // ExitSU.
919 DAG.addSchedBarrierDeps();
920
921 // Walk the list of instructions, from bottom moving up.
922 MachineInstr *DbgMI = nullptr;
923 for (MachineBasicBlock::iterator MII = DAG.RegionEnd, MIE = DAG.RegionBegin;
924 MII != MIE; --MII) {
925 MachineInstr &MI = *std::prev(MII);
926 if (DbgMI) {
927 DAG.DbgValues.emplace_back(DbgMI, &MI);
928 DbgMI = nullptr;
929 }
930
931 if (MI.isDebugValue() || MI.isDebugPHI()) {
932 DbgMI = &MI;
933 continue;
934 }
935
936 if (MI.isDebugLabel() || MI.isDebugRef() || MI.isPseudoProbe())
937 continue;
938
939 SUnit *SU = DAG.MISUnitMap[&MI];
940 assert(SU && "No SUnit mapped to this MI");
941
942 if (RPTracker) {
943 RegisterOperands RegOpers;
944 RegOpers.collect(MI, *DAG.TRI, DAG.MRI, DAG.TrackLaneMasks, false);
945 if (DAG.TrackLaneMasks) {
946 SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
947 RegOpers.adjustLaneLiveness(*LIS, DAG.MRI, SlotIdx);
948 } else if (LIS) {
949 // Detect dead defs from LiveIntervals instead of trusting operand dead
950 // flags.
951 RegOpers.detectDeadDefs(MI, *LIS, DAG.MRI);
952 }
953 if (PDiffs != nullptr)
954 PDiffs->addInstruction(SU->NodeNum, RegOpers, DAG.MRI);
955
956 if (RPTracker->getPos() == DAG.RegionEnd || &*RPTracker->getPos() != &MI)
957 RPTracker->recedeSkipDebugValues();
958 assert(&*RPTracker->getPos() == &MI && "RPTracker in sync");
959 RPTracker->recede(RegOpers);
960 }
961
962 assert((DAG.CanHandleTerminators ||
963 (!MI.isTerminator() && !MI.isPosition())) &&
964 "Cannot schedule terminators or labels!");
965
966 // Add register-based dependencies (data, anti, and output).
967 // For some instructions (calls, returns, inline-asm, etc.) there can
968 // be explicit uses and implicit defs, in which case the use will appear
969 // on the operand list before the def. Do two passes over the operand
970 // list to make sure that defs are processed before any uses.
971 bool HasVRegDef = false;
972 for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
973 const MachineOperand &MO = MI.getOperand(j);
974 if (!MO.isReg() || !MO.isDef())
975 continue;
976 Register Reg = MO.getReg();
977 if (Reg.isPhysical()) {
978 DAG.addPhysRegDeps(SU, j);
979 } else if (Reg.isVirtual()) {
980 HasVRegDef = true;
981 DAG.addVRegDefDeps(SU, j);
982 }
983 }
984 // Now process all uses.
985 for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
986 const MachineOperand &MO = MI.getOperand(j);
987 // Only look at use operands.
988 // We do not need to check for MO.readsReg() here because subsequent
989 // subregister defs will get output dependence edges and need no
990 // additional use dependencies.
991 if (!MO.isReg() || !MO.isUse())
992 continue;
993 Register Reg = MO.getReg();
994 if (Reg.isPhysical()) {
995 DAG.addPhysRegDeps(SU, j);
996 } else if (Reg.isVirtual() && MO.readsReg()) {
997 DAG.addVRegUseDeps(SU, j);
998 }
999 }
1000
1001 // If we haven't seen any uses in this scheduling region, create a
1002 // dependence edge to ExitSU to model the live-out latency. This is required
1003 // for vreg defs with no in-region use, and prefetches with no vreg def.
1004 //
1005 // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
1006 // check currently relies on being called before adding chain deps.
1007 if (SU->NumSuccs == 0 && SU->Latency > 1 && (HasVRegDef || MI.mayLoad())) {
1008 SDep Dep(SU, SDep::Artificial);
1009 Dep.setLatency(SU->Latency - 1);
1010 DAG.ExitSU.addPred(Dep);
1011 }
1012
1013 // Add memory dependencies (Note: isStoreToStackSlot and
1014 // isLoadFromStackSLot are not usable after stack slots are lowered to
1015 // actual addresses).
1016
1017 const TargetInstrInfo *TII = ST.getInstrInfo();
1018 // This is a barrier event that acts as a pivotal node in the DAG.
1019 if (TII->isGlobalMemoryObject(&MI)) {
1020
1021 // Become the barrier chain.
1022 if (BarrierChain)
1023 BarrierChain->addPredBarrier(SU);
1024 BarrierChain = SU;
1025
1026 LLVM_DEBUG(dbgs() << "Global memory object and new barrier chain: "
1027 << *BarrierChain << ".\n");
1028
1029 // Add dependencies against everything below it and clear maps.
1030 addBarrierChain(FPExceptions);
1031 addBarrierMemoryDeps();
1032
1033 continue;
1034 }
1035
1036 // Instructions that may raise FP exceptions may not be moved
1037 // across any global barriers.
1038 if (MI.mayRaiseFPException()) {
1039 if (BarrierChain)
1040 BarrierChain->addPredBarrier(SU);
1041
1042 if (!Opts.store_sequencing &&
1043 FPExceptions.size() + 1 >= Opts.dag_maps_huge_region) {
1044 LLVM_DEBUG(
1045 dbgs()
1046 << "Creating barrier chain and clearing FPExceptions map.\n");
1047 BarrierChain = SU;
1048 addBarrierChain(FPExceptions);
1049 } else {
1050 FPExceptions.push_back(SU);
1051 }
1052 }
1053
1054 // If it's not a store or a variant load, we're done.
1055 if (!MI.mayStore() &&
1056 !(MI.mayLoad() && !MI.isDereferenceableInvariantLoad()))
1057 continue;
1058
1059 MemOpsProcessed++;
1060
1061 // Always add dependecy edge to BarrierChain if present.
1062 if (BarrierChain && BarrierChain != SU)
1063 BarrierChain->addPredBarrier(SU);
1064
1065 // Reduce maps if they grow huge.
1066 if (!Opts.store_sequencing &&
1067 MemOpsProcessed >= Opts.dag_maps_huge_region) {
1068 LLVM_DEBUG(dbgs() << "Creating barrier chain and clearing maps.\n");
1069
1070 BarrierChain = SU;
1071 addBarrierMemoryDeps();
1072
1073 MemOpsProcessed = 0;
1074 continue;
1075 }
1076
1077 // If the frontier occupancy exceeds the maximum threshold, promote SU to a
1078 // global memory barrier and clear the frontiers.
1079 if (Opts.store_sequencing &&
1080 MemopsInFlight >= Opts.store_sequencing_max_memops_in_flight) {
1081 LLVM_DEBUG(dbgs() << "Number of in-flight memory operations reached "
1082 << Opts.store_sequencing_max_memops_in_flight
1083 << ", promoting " << *SU
1084 << " to barrier chain and clearing maps.\n");
1085
1086 BarrierChain = SU;
1087 addBarrierMemoryDeps();
1088 continue;
1089 }
1090
1091 // Find the underlying objects for MI. The Objs vector is either
1092 // empty, or filled with the Values of memory locations which this
1093 // SU depends on.
1095 bool ObjsIdentified = getUnderlyingObjectsForInstr(&MI, DAG.MFI, Objs,
1096 DAG.MF.getDataLayout());
1097 bool IsStore = MI.mayStore();
1098
1099 if (!ObjsIdentified) {
1100 // An unanalyzable memory operation depends on all analyzable frontiers.
1101 for (auto &[_, AF] : AnalyzableFrontiers)
1102 addChainDependencies(SU, AF, IsStore);
1103
1104 if (IsStore && shouldUpdate(UnanalyzableFrontier, Objs)) {
1105 updateSequencingStore(UnanalyzableFrontier, SU, std::move(Objs));
1106 } else {
1107 if (!IsStore && UnanalyzableFrontier.escapesBaseObjects(Objs))
1108 UnanalyzableFrontier.SeenSequencingLoad = true;
1109 addChainDependencies(SU, UnanalyzableFrontier.Frontier, IsStore);
1110 (IsStore ? UnanalyzableFrontier.Frontier.Stores
1111 : UnanalyzableFrontier.Frontier.Loads)
1112 .push_back(SU);
1113 ++MemopsInFlight;
1114 }
1115 } else {
1116 // Add precise dependencies against all previously seen memory
1117 // accesses mapped to the same Value(s).
1118 SmallSet<ValueType, 2> SeenValues;
1119 for (const ValueType V : Objs) {
1120 // Deduplicate values to avoid adding self loops.
1121 if (!SeenValues.insert(V).second)
1122 continue;
1123
1124 MemopFrontier &Frontier = AnalyzableFrontiers[V];
1125
1126 if (IsStore && shouldUpdate(Frontier)) {
1127 updateSequencingStore(Frontier, SU);
1128 } else {
1129 addChainDependencies(SU, Frontier, IsStore);
1130 (IsStore ? Frontier.Stores : Frontier.Loads).push_back(SU);
1131 ++MemopsInFlight;
1132 }
1133 }
1134
1135 // The memop may have dependencies to unanalyzable stores.
1136 addChainDependencies(SU, UnanalyzableFrontier.Frontier, IsStore);
1137 }
1138 }
1139
1140 if (DbgMI)
1141 DAG.FirstDbgValue = DbgMI;
1142}
1143
1145 RegPressureTracker *RPTracker,
1146 PressureDiffs *PDiffs,
1147 LiveIntervals *LIS,
1148 bool TrackLaneMasks) {
1149 const TargetSubtargetInfo &ST = MF.getSubtarget();
1150 bool UseAA = valueOr(Opts.sched_mi_aa, ST.useAA());
1151 this->TrackLaneMasks = TrackLaneMasks;
1152 MISUnitMap.clear();
1154
1155 // Create an SUnit for each real instruction.
1156 initSUnits();
1157
1158 if (PDiffs)
1159 PDiffs->init(SUnits.size());
1160
1161 // Remove any stale debug info; sometimes BuildSchedGraph is called again
1162 // without emitting the info from the previous call.
1163 DbgValues.clear();
1164 FirstDbgValue = nullptr;
1165
1166 assert(Defs.empty() && Uses.empty() &&
1167 "Only BuildGraph should update Defs/Uses");
1168 Defs.setUniverse(TRI->getNumRegs());
1169 Uses.setUniverse(TRI->getNumRegs());
1170
1171 assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
1172 assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
1173 unsigned NumVirtRegs = MRI.getNumVirtRegs();
1174 CurrentVRegDefs.setUniverse(NumVirtRegs);
1175 CurrentVRegUses.setUniverse(NumVirtRegs);
1176
1177 std::optional<BatchAAResults> BatchAA;
1178 if (UseAA && AA)
1179 BatchAA.emplace(*AA);
1180
1182 *this, BatchAA.has_value() ? &BatchAA.value() : nullptr, RPTracker,
1183 PDiffs, LIS);
1184 DepBuilder.buildDeps();
1185
1186 Defs.clear();
1187 Uses.clear();
1188 CurrentVRegDefs.clear();
1189 CurrentVRegUses.clear();
1190
1191 Topo.MarkDirty();
1192}
1193
1195 PSV->printCustom(OS);
1196 return OS;
1197}
1198
1200 MachineInstr &MI, bool addToLiveRegs) {
1201 for (MachineOperand &MO : MI.operands()) {
1202 if (!MO.isReg() || !MO.readsReg())
1203 continue;
1204 Register Reg = MO.getReg();
1205 if (!Reg)
1206 continue;
1207
1208 // Things that are available after the instruction are killed by it.
1209 bool IsKill = LiveRegs.available(Reg);
1210
1211 // Exception: Do not kill reserved registers
1212 MO.setIsKill(IsKill && !MRI.isReserved(Reg));
1213 if (addToLiveRegs)
1214 LiveRegs.addReg(Reg);
1215 }
1216}
1217
1219 LLVM_DEBUG(dbgs() << "Fixup kills for " << printMBBReference(MBB) << '\n');
1220
1221 LiveRegs.init(*TRI);
1222 LiveRegs.addLiveOuts(MBB);
1223
1224 // Examine block from end to start...
1225 for (MachineInstr &MI : llvm::reverse(MBB)) {
1226 if (MI.isDebugOrPseudoInstr())
1227 continue;
1228
1229 // Update liveness. Registers that are defed but not used in this
1230 // instruction are now dead. Mark register and all subregs as they
1231 // are completely defined.
1232 for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
1233 const MachineOperand &MO = *O;
1234 if (MO.isReg()) {
1235 if (!MO.isDef())
1236 continue;
1237 Register Reg = MO.getReg();
1238 if (!Reg)
1239 continue;
1240 LiveRegs.removeReg(Reg);
1241 } else if (MO.isRegMask()) {
1242 LiveRegs.removeRegsNotPreserved(MO.getRegMask());
1243 }
1244 }
1245
1246 // If there is a bundle header fix it up first.
1247 if (!MI.isBundled()) {
1248 toggleKills(MRI, LiveRegs, MI, true);
1249 } else {
1250 MachineBasicBlock::instr_iterator Bundle = MI.getIterator();
1251 if (MI.isBundle())
1252 toggleKills(MRI, LiveRegs, MI, false);
1253
1254 // Some targets make the (questionable) assumtion that the instructions
1255 // inside the bundle are ordered and consequently only the last use of
1256 // a register inside the bundle can kill it.
1257 MachineBasicBlock::instr_iterator I = std::next(Bundle);
1258 while (I->isBundledWithSucc())
1259 ++I;
1260 do {
1261 if (!I->isDebugOrPseudoInstr())
1262 toggleKills(MRI, LiveRegs, *I, true);
1263 --I;
1264 } while (I != Bundle);
1265 }
1266 }
1267}
1268
1269void ScheduleDAGInstrs::dumpNode(const SUnit &SU) const {
1270#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1271 dumpNodeName(SU);
1272#ifndef NDEBUG
1273 if (Opts.sched_print_cycles)
1274 dbgs() << " [TopReadyCycle = " << SU.TopReadyCycle
1275 << ", BottomReadyCycle = " << SU.BotReadyCycle << "]";
1276#endif
1277 dbgs() << ": ";
1278 SU.getInstr()->dump();
1279#endif
1280}
1281
1283#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1284 if (EntrySU.getInstr() != nullptr)
1286 for (const SUnit &SU : SUnits)
1287 dumpNodeAll(SU);
1288 if (ExitSU.getInstr() != nullptr)
1290#endif
1291}
1292
1293#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1294std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1295 std::string s;
1296 raw_string_ostream oss(s);
1297 if (SU == &EntrySU)
1298 oss << "<entry>";
1299 else if (SU == &ExitSU)
1300 oss << "<exit>";
1301 else
1302 SU->getInstr()->print(oss, /*IsStandalone=*/true);
1303 return s;
1304}
1305#endif
1306
1307/// Return the basic block label. It is not necessarily unique because a block
1308/// contains multiple scheduling regions. But it is fine for visualization.
1310 return "dag." + BB->getFullName();
1311}
1312
1314 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
1315}
1316
1317bool ScheduleDAGInstrs::addEdge(SUnit *SuccSU, const SDep &PredDep) {
1318 if (SuccSU != &ExitSU) {
1319 // Do not use WillCreateCycle, it assumes SD scheduling.
1320 // If Pred is reachable from Succ, then the edge creates a cycle.
1321 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
1322 return false;
1323 Topo.AddPredQueued(SuccSU, PredDep.getSUnit());
1324 }
1325 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
1326 // Return true regardless of whether a new edge needed to be inserted.
1327 return true;
1328}
1329
1330//===----------------------------------------------------------------------===//
1331// SchedDFSResult Implementation
1332//===----------------------------------------------------------------------===//
1333
1334namespace llvm {
1335
1336/// Internal state used to compute SchedDFSResult.
1338 SchedDFSResult &R;
1339
1340 /// Join DAG nodes into equivalence classes by their subtree.
1341 IntEqClasses SubtreeClasses;
1342 /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1343 std::vector<std::pair<const SUnit *, const SUnit*>> ConnectionPairs;
1344
1345 struct RootData {
1346 unsigned NodeID;
1347 unsigned ParentNodeID; ///< Parent node (member of the parent subtree).
1348 unsigned SubInstrCount = 0; ///< Instr count in this tree only, not
1349 /// children.
1350
1351 RootData(unsigned id): NodeID(id),
1352 ParentNodeID(SchedDFSResult::InvalidSubtreeID) {}
1353
1354 unsigned getSparseSetIndex() const { return NodeID; }
1355 };
1356
1357 SparseSet<RootData> RootSet;
1358
1359public:
1360 SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1361 RootSet.setUniverse(R.DFSNodeData.size());
1362 }
1363
1364 /// Returns true if this node been visited by the DFS traversal.
1365 ///
1366 /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1367 /// ID. Later, SubtreeID is updated but remains valid.
1368 bool isVisited(const SUnit *SU) const {
1369 return R.DFSNodeData[SU->NodeNum].SubtreeID
1370 != SchedDFSResult::InvalidSubtreeID;
1371 }
1372
1373 /// Initializes this node's instruction count. We don't need to flag the node
1374 /// visited until visitPostorder because the DAG cannot have cycles.
1375 void visitPreorder(const SUnit *SU) {
1376 R.DFSNodeData[SU->NodeNum].InstrCount =
1377 SU->getInstr()->isTransient() ? 0 : 1;
1378 }
1379
1380 /// Called once for each node after all predecessors are visited. Revisit this
1381 /// node's predecessors and potentially join them now that we know the ILP of
1382 /// the other predecessors.
1383 void visitPostorderNode(const SUnit *SU) {
1384 // Mark this node as the root of a subtree. It may be joined with its
1385 // successors later.
1386 R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1387 RootData RData(SU->NodeNum);
1388 RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
1389
1390 // If any predecessors are still in their own subtree, they either cannot be
1391 // joined or are large enough to remain separate. If this parent node's
1392 // total instruction count is not greater than a child subtree by at least
1393 // the subtree limit, then try to join it now since splitting subtrees is
1394 // only useful if multiple high-pressure paths are possible.
1395 unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
1396 for (const SDep &PredDep : SU->Preds) {
1397 if (PredDep.getKind() != SDep::Data)
1398 continue;
1399 unsigned PredNum = PredDep.getSUnit()->NodeNum;
1400 if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
1401 joinPredSubtree(PredDep, SU, /*CheckLimit=*/false);
1402
1403 // Either link or merge the TreeData entry from the child to the parent.
1404 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1405 // If the predecessor's parent is invalid, this is a tree edge and the
1406 // current node is the parent.
1407 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1408 RootSet[PredNum].ParentNodeID = SU->NodeNum;
1409 }
1410 else if (RootSet.count(PredNum)) {
1411 // The predecessor is not a root, but is still in the root set. This
1412 // must be the new parent that it was just joined to. Note that
1413 // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1414 // set to the original parent.
1415 RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1416 RootSet.erase(PredNum);
1417 }
1418 }
1419 RootSet[SU->NodeNum] = RData;
1420 }
1421
1422 /// Called once for each tree edge after calling visitPostOrderNode on
1423 /// the predecessor. Increment the parent node's instruction count and
1424 /// preemptively join this subtree to its parent's if it is small enough.
1425 void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1426 R.DFSNodeData[Succ->NodeNum].InstrCount
1427 += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1428 joinPredSubtree(PredDep, Succ);
1429 }
1430
1431 /// Adds a connection for cross edges.
1432 void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
1433 ConnectionPairs.emplace_back(PredDep.getSUnit(), Succ);
1434 }
1435
1436 /// Sets each node's subtree ID to the representative ID and record
1437 /// connections between trees.
1439 SubtreeClasses.compress();
1440 R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1441 assert(SubtreeClasses.getNumClasses() == RootSet.size()
1442 && "number of roots should match trees");
1443 for (const RootData &Root : RootSet) {
1444 unsigned TreeID = SubtreeClasses[Root.NodeID];
1445 if (Root.ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1446 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[Root.ParentNodeID];
1447 R.DFSTreeData[TreeID].SubInstrCount = Root.SubInstrCount;
1448 // Note that SubInstrCount may be greater than InstrCount if we joined
1449 // subtrees across a cross edge. InstrCount will be attributed to the
1450 // original parent, while SubInstrCount will be attributed to the joined
1451 // parent.
1452 }
1453 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1454 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1455 LLVM_DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
1456 for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1457 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
1458 LLVM_DEBUG(dbgs() << " " << SUnits[Idx] << " in tree "
1459 << R.DFSNodeData[Idx].SubtreeID << '\n');
1460 }
1461 for (const auto &[Pred, Succ] : ConnectionPairs) {
1462 unsigned PredTree = SubtreeClasses[Pred->NodeNum];
1463 unsigned SuccTree = SubtreeClasses[Succ->NodeNum];
1464 if (PredTree == SuccTree)
1465 continue;
1466 unsigned Depth = Pred->getDepth();
1467 addConnection(PredTree, SuccTree, Depth);
1468 addConnection(SuccTree, PredTree, Depth);
1469 }
1470 }
1471
1472protected:
1473 /// Joins the predecessor subtree with the successor that is its DFS parent.
1474 /// Applies some heuristics before joining.
1475 bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1476 bool CheckLimit = true) {
1477 assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1478
1479 // Check if the predecessor is already joined.
1480 const SUnit *PredSU = PredDep.getSUnit();
1481 unsigned PredNum = PredSU->NodeNum;
1482 if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
1483 return false;
1484
1485 // Four is the magic number of successors before a node is considered a
1486 // pinch point.
1487 unsigned NumDataSucs = 0;
1488 for (const SDep &SuccDep : PredSU->Succs) {
1489 if (SuccDep.getKind() == SDep::Data) {
1490 if (++NumDataSucs >= 4)
1491 return false;
1492 }
1493 }
1494 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
1495 return false;
1496 R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
1497 SubtreeClasses.join(Succ->NodeNum, PredNum);
1498 return true;
1499 }
1500
1501 /// Called by finalize() to record a connection between trees.
1502 void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1503 if (!Depth)
1504 return;
1505
1506 do {
1508 R.SubtreeConnections[FromTree];
1509 for (SchedDFSResult::Connection &C : Connections) {
1510 if (C.TreeID == ToTree) {
1511 C.Level = std::max(C.Level, Depth);
1512 return;
1513 }
1514 }
1515 Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1516 FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1517 } while (FromTree != SchedDFSResult::InvalidSubtreeID);
1518 }
1519};
1520
1521} // end namespace llvm
1522
1523namespace {
1524
1525/// Manage the stack used by a reverse depth-first search over the DAG.
1526class SchedDAGReverseDFS {
1527 std::vector<std::pair<const SUnit *, SUnit::const_pred_iterator>> DFSStack;
1528
1529public:
1530 bool isComplete() const { return DFSStack.empty(); }
1531
1532 void follow(const SUnit *SU) {
1533 DFSStack.emplace_back(SU, SU->Preds.begin());
1534 }
1535 void advance() { ++DFSStack.back().second; }
1536
1537 const SDep *backtrack() {
1538 DFSStack.pop_back();
1539 return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
1540 }
1541
1542 const SUnit *getCurr() const { return DFSStack.back().first; }
1543
1544 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1545
1546 SUnit::const_pred_iterator getPredEnd() const {
1547 return getCurr()->Preds.end();
1548 }
1549};
1550
1551} // end anonymous namespace
1552
1553static bool hasDataSucc(const SUnit *SU) {
1554 for (const SDep &SuccDep : SU->Succs) {
1555 if (SuccDep.getKind() == SDep::Data &&
1556 !SuccDep.getSUnit()->isBoundaryNode())
1557 return true;
1558 }
1559 return false;
1560}
1561
1562/// Computes an ILP metric for all nodes in the subDAG reachable via depth-first
1563/// search from this root.
1565 if (!IsBottomUp)
1566 llvm_unreachable("Top-down ILP metric is unimplemented");
1567
1568 SchedDFSImpl Impl(*this);
1569 for (const SUnit &SU : SUnits) {
1570 if (Impl.isVisited(&SU) || hasDataSucc(&SU))
1571 continue;
1572
1573 SchedDAGReverseDFS DFS;
1574 Impl.visitPreorder(&SU);
1575 DFS.follow(&SU);
1576 while (true) {
1577 // Traverse the leftmost path as far as possible.
1578 while (DFS.getPred() != DFS.getPredEnd()) {
1579 const SDep &PredDep = *DFS.getPred();
1580 DFS.advance();
1581 // Ignore non-data edges.
1582 if (PredDep.getKind() != SDep::Data
1583 || PredDep.getSUnit()->isBoundaryNode()) {
1584 continue;
1585 }
1586 // An already visited edge is a cross edge, assuming an acyclic DAG.
1587 if (Impl.isVisited(PredDep.getSUnit())) {
1588 Impl.visitCrossEdge(PredDep, DFS.getCurr());
1589 continue;
1590 }
1591 Impl.visitPreorder(PredDep.getSUnit());
1592 DFS.follow(PredDep.getSUnit());
1593 }
1594 // Visit the top of the stack in postorder and backtrack.
1595 const SUnit *Child = DFS.getCurr();
1596 const SDep *PredDep = DFS.backtrack();
1597 Impl.visitPostorderNode(Child);
1598 if (PredDep)
1599 Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
1600 if (DFS.isComplete())
1601 break;
1602 }
1603 }
1604 Impl.finalize(SUnits);
1605}
1606
1607/// The root of the given SubtreeID was just scheduled. For all subtrees
1608/// connected to this tree, record the depth of the connection so that the
1609/// nearest connected subtrees can be prioritized.
1610void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1611 for (const Connection &C : SubtreeConnections[SubtreeID]) {
1612 SubtreeConnectLevels[C.TreeID] =
1613 std::max(SubtreeConnectLevels[C.TreeID], C.Level);
1614 LLVM_DEBUG(dbgs() << " Tree: " << C.TreeID << " @"
1615 << SubtreeConnectLevels[C.TreeID] << '\n');
1616 }
1617}
1618
1619#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1621 OS << InstrCount << " / " << Length << " = ";
1622 if (!Length)
1623 OS << "BADILP";
1624 else
1625 OS << format("%g", ((double)InstrCount / Length));
1626}
1627
1629 dbgs() << *this << '\n';
1630}
1631
1632[[maybe_unused]]
1634 Val.print(OS);
1635 return OS;
1636}
1637
1638#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
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)
#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:63
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.