37#include "llvm/Config/llvm-config.h"
46#define DEBUG_TYPE "post-RA-sched"
50STATISTIC(NumFixedAnti,
"Number of fixed anti-dependencies");
55class PostRAScheduler {
66 :
TII(MF.getSubtarget().getInstrInfo()), MLI(MLI),
AA(
AA), TM(TM),
67 RegClassInfo(RegClassInfo) {}
74 PostRASchedulerLegacy() : MachineFunctionPass(ID) {}
76 void getAnalysisUsage(AnalysisUsage &AU)
const override {
81 AU.
addRequired<MachineRegisterClassInfoWrapperPass>();
85 MachineFunctionProperties getRequiredProperties()
const override {
86 return MachineFunctionProperties().setNoVRegs();
91char PostRASchedulerLegacy::ID = 0;
96 LatencyPriorityQueue AvailableQueue;
102 std::vector<SUnit *> PendingQueue;
105 ScheduleHazardRecognizer *HazardRec;
108 AntiDepBreaker *AntiDepBreak;
114 std::vector<SUnit *> Sequence;
117 std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
123 unsigned EndIndex = 0;
126 SchedulePostRATDList(
128 const RegisterClassInfo &,
130 SmallVectorImpl<const TargetRegisterClass *> &CriticalPathRCs);
132 ~SchedulePostRATDList()
override;
137 void startBlock(MachineBasicBlock *BB)
override;
140 void setEndIndex(
unsigned EndIdx) { EndIndex = EndIdx; }
145 unsigned regioninstrs)
override;
148 void exitRegion()
override;
152 void schedule()
override;
159 void Observe(MachineInstr &
MI,
unsigned Count);
163 void finishBlock()
override;
167 void postProcessDAG();
169 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
170 void ReleaseSuccessors(SUnit *SU);
171 void ScheduleNodeTopDown(SUnit *SU,
unsigned CurCycle);
172 void ListScheduleTopDown();
174 void dumpSchedule()
const;
175 void emitNoop(
unsigned CurCycle);
182 "Post RA top-down list latency scheduler",
false,
false)
187SchedulePostRATDList::SchedulePostRATDList(
195 MF.getSubtarget().getInstrItineraryData();
197 MF.getSubtarget().getInstrInfo()->CreateTargetPostRAHazardRecognizer(
199 MF.getSubtarget().getPostRAMutations(Mutations);
201 assert((AntiDepMode == TargetSubtargetInfo::ANTIDEP_NONE ||
202 MRI.tracksLiveness()) &&
203 "Live-ins must be accurate for anti-dependency breaking");
204 AntiDepBreak = ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_ALL)
206 : ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_CRITICAL)
211SchedulePostRATDList::~SchedulePostRATDList() {
217void SchedulePostRATDList::enterRegion(MachineBasicBlock *bb,
220 unsigned regioninstrs) {
226void SchedulePostRATDList::exitRegion() {
228 dbgs() <<
"*** Final schedule ***\n";
235#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
238 for (
const SUnit *SU : Sequence) {
242 dbgs() <<
"**** NOOP ****\n";
251 return valueOr(Opts.post_RA_scheduler,
252 ST.enablePostRAScheduler() &&
253 OptLevel >= ST.getOptLevelToEnablePostRAScheduler());
265 if (
auto Mode = Opts.break_anti_dependencies) {
268 ? TargetSubtargetInfo::ANTIDEP_ALL
269 : ((*
Mode ==
"critical") ? TargetSubtargetInfo::ANTIDEP_CRITICAL
270 : TargetSubtargetInfo::ANTIDEP_NONE);
273 Subtarget.getCriticalPathRCs(CriticalPathRCs);
277 SchedulePostRATDList
Scheduler(MF, *MLI, AA, *RegClassInfo, AntiDepMode,
281 for (
auto &
MBB : MF) {
285 if (Opts.postra_sched_debugdiv > 0) {
286 static int bbcnt = 0;
287 if (bbcnt++ % Opts.postra_sched_debugdiv != Opts.postra_sched_debugmod)
289 dbgs() <<
"*** DEBUG scheduling " << MF.getName() <<
":"
302 MachineInstr &
MI = *std::prev(
I);
314 CurrentCount =
Count;
321 assert(
Count == 0 &&
"Instruction count mismatch!");
323 "Instruction count mismatch!");
344 MachineLoopInfo *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
345 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
346 const TargetMachine *TM =
347 &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
348 RegisterClassInfo *RegClassInfo =
349 &getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
350 PostRAScheduler Impl(MF, MLI, AA, TM, RegClassInfo);
365 PostRAScheduler Impl(MF, MLI,
AA, TM, &RegClassInfo);
390void SchedulePostRATDList::schedule() {
397 EndIndex, DbgValues);
409 NumFixedAnti += Broken;
419 ListScheduleTopDown();
426void SchedulePostRATDList::Observe(MachineInstr &
MI,
unsigned Count) {
433void SchedulePostRATDList::finishBlock() {
442void SchedulePostRATDList::postProcessDAG() {
443 for (
auto &M : Mutations)
453void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
454 SUnit *SuccSU = SuccEdge->
getSUnit();
462 dbgs() <<
"*** Scheduling failed! ***\n";
464 dbgs() <<
" has been released too many times!\n";
484 PendingQueue.push_back(SuccSU);
488void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
491 ReleaseSucc(SU, &*
I);
498void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU,
unsigned CurCycle) {
504 "Node scheduled above its depth!");
507 ReleaseSuccessors(SU);
513void SchedulePostRATDList::emitNoop(
unsigned CurCycle) {
514 LLVM_DEBUG(
dbgs() <<
"*** Emitting noop in cycle " << CurCycle <<
'\n');
522void SchedulePostRATDList::ListScheduleTopDown() {
523 unsigned CurCycle = 0;
532 ReleaseSuccessors(&EntrySU);
535 for (SUnit &SUnit : SUnits) {
537 if (!SUnit.NumPredsLeft && !SUnit.isAvailable) {
538 AvailableQueue.
push(&SUnit);
539 SUnit.isAvailable =
true;
545 bool CycleHasInsts =
false;
549 std::vector<SUnit*> NotReady;
551 while (!AvailableQueue.
empty() || !PendingQueue.empty()) {
554 unsigned MinDepth = ~0
u;
555 for (
unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
556 if (PendingQueue[i]->getDepth() <= CurCycle) {
557 AvailableQueue.
push(PendingQueue[i]);
558 PendingQueue[i]->isAvailable =
true;
559 PendingQueue[i] = PendingQueue.back();
560 PendingQueue.pop_back();
562 }
else if (PendingQueue[i]->getDepth() < MinDepth)
563 MinDepth = PendingQueue[i]->getDepth();
567 AvailableQueue.
dump(
this));
569 SUnit *FoundSUnit =
nullptr, *NotPreferredSUnit =
nullptr;
570 bool HasNoopHazards =
false;
571 while (!AvailableQueue.
empty()) {
572 SUnit *CurSUnit = AvailableQueue.
pop();
578 if (!NotPreferredSUnit) {
583 NotPreferredSUnit = CurSUnit;
587 FoundSUnit = CurSUnit;
595 NotReady.push_back(CurSUnit);
601 if (NotPreferredSUnit) {
604 dbgs() <<
"*** Will schedule a non-preferred instruction...\n");
605 FoundSUnit = NotPreferredSUnit;
607 AvailableQueue.
push(NotPreferredSUnit);
610 NotPreferredSUnit =
nullptr;
614 if (!NotReady.empty()) {
622 unsigned NumPreNoops = HazardRec->
PreEmitNoops(FoundSUnit);
623 for (
unsigned i = 0; i != NumPreNoops; ++i)
627 ScheduleNodeTopDown(FoundSUnit, CurCycle);
629 CycleHasInsts =
true;
631 LLVM_DEBUG(
dbgs() <<
"*** Max instructions per cycle " << CurCycle
635 CycleHasInsts =
false;
641 }
else if (!HasNoopHazards) {
655 CycleHasInsts =
false;
660 unsigned ScheduledNodes = VerifyScheduledDAG(
false);
663 "The number of nodes scheduled doesn't match the expected number!");
668void SchedulePostRATDList::EmitSchedule() {
669 RegionBegin = RegionEnd;
673 BB->
splice(RegionEnd, BB, FirstDbgValue);
676 for (
unsigned i = 0, e =
Sequence.size(); i != e; i++) {
677 if (SUnit *SU = Sequence[i])
686 RegionBegin = std::prev(RegionEnd);
690 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
691 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
692 std::pair<MachineInstr *, MachineInstr *>
P = *std::prev(DI);
693 MachineInstr *DbgValue =
P.first;
695 BB->
splice(++OrigPrivMI, BB, DbgValue);
698 FirstDbgValue =
nullptr;
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
const HexagonInstrInfo * TII
PostRA Machine Instruction Scheduler
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static bool enablePostRAScheduler(const CodeGenOptions &Opts, const TargetSubtargetInfo &ST, CodeGenOptLevel OptLevel)
MachineRegisterInfo & MRI
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Target-Independent Code Generator Pass Configuration Options pass.
A manager for alias analyses.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
virtual void FinishBlock()=0
Finish anti-dep breaking for a basic block.
virtual unsigned BreakAntiDependencies(const std::vector< SUnit > &SUnits, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, unsigned InsertPosIndex, DbgValueVector &DbgValues)=0
Identifiy anti-dependencies within a basic-block region and break them by renaming registers.
virtual void Observe(MachineInstr &MI, unsigned Count, unsigned InsertPosIndex)=0
Update liveness information to account for the current instruction, which will not be scheduled.
virtual ~AntiDepBreaker()
virtual void StartBlock(MachineBasicBlock *BB)=0
Initialize anti-dep breaking for a new basic block.
Represents analyses that only rely on functions' control flow.
void insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
Insert a noop into the instruction stream at the specified point.
bool isSchedulingBoundary(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const override
Test if the given instruction should be considered a scheduling boundary.
Itinerary data supplied by a subtarget to be used by a target.
void releaseState() override
void push(SUnit *U) override
LLVM_DUMP_METHOD void dump(ScheduleDAG *DAG) const override
void scheduledNode(SUnit *SU) override
As each node is scheduled, this method is invoked.
void initNodes(std::vector< SUnit > &sunits) override
bool empty() const override
An RAII based helper class to modify MachineFunctionProperties when running pass.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Function & getFunction()
Return the LLVM function that this machine code represents.
Analysis pass that exposes the MachineLoopInfo for a machine function.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
bool isWeak() const
Tests if this a weak dependence.
unsigned getDepth() const
Returns the depth of this node, which is the length of the maximum path up to any node which has no p...
bool isScheduled
True once scheduled.
SmallVector< SDep, 4 > Succs
All sunit successors.
SmallVectorImpl< SDep >::iterator succ_iterator
LLVM_ABI void setDepthToAtLeast(unsigned NewDepth)
If NewDepth is greater than this node's depth value, sets it to be the new depth value.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
A ScheduleDAG for scheduling lists of MachineInstr.
virtual void finishBlock()
Cleans up after scheduling in the given block.
virtual void startBlock(MachineBasicBlock *BB)
Prepares to perform scheduling in the given block.
virtual void exitRegion()
Called when the scheduler has finished scheduling the current region.
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 clearDAG()
Clears the DAG state (between regions).
virtual void Reset()
Reset - This callback is invoked when a new block of instructions is about to be schedule.
virtual void EmitInstruction(SUnit *)
EmitInstruction - This callback is invoked when an instruction is emitted, to advance the hazard stat...
virtual bool atIssueLimit() const
atIssueLimit - Return true if no more instructions may be issued in this cycle.
virtual bool ShouldPreferAnother(SUnit *) const
ShouldPreferAnother - This callback may be invoked if getHazardType returns NoHazard.
virtual void EmitNoop()
EmitNoop - This callback is invoked when a noop was added to the instruction stream.
virtual void AdvanceCycle()
AdvanceCycle - This callback is invoked whenever the next top-down instruction to be scheduled cannot...
virtual HazardType getHazardType(SUnit *, int Stalls=0)
getHazardType - Return the hazard type of emitting this node.
virtual unsigned PreEmitNoops(SUnit *)
PreEmitNoops - This callback is invoked prior to emitting an instruction.
void push_all(const std::vector< SUnit * > &Nodes)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
TargetInstrInfo - Interface to description of machine instruction set.
Primary interface to the complete machine description for the target machine.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
TargetSubtargetInfo - Generic base class for all target subtargets.
enum { ANTIDEP_NONE, ANTIDEP_CRITICAL, ANTIDEP_ALL } AntiDepBreakMode
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
Sequence
A sequence of states that a pointer may go through in which an objc_retain and objc_release are actua...
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
LLVM_ABI AntiDepBreaker * createAggressiveAntiDepBreaker(MachineFunction &MFi, const RegisterClassInfo &RCI, TargetSubtargetInfo::RegClassVector &CriticalPathRCs)
LLVM_ABI char & PostRASchedulerID
PostRAScheduler - This pass performs post register allocation scheduling.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
CodeGenOptLevel
Code generation optimization level.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
LLVM_ABI AntiDepBreaker * createCriticalAntiDepBreaker(MachineFunction &MFi, const RegisterClassInfo &RCI)
constexpr bool valueOr(BoolOrDefault X, bool Default)
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
MCRegisterClass TargetRegisterClass