LLVM 22.0.0git
MacroFusion.cpp
Go to the documentation of this file.
1//===- MacroFusion.cpp - Macro Fusion -------------------------------------===//
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 file contains the implementation of the DAG scheduling mutation
10/// to pair instructions back to back.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/Statistic.h"
22#include "llvm/Support/Debug.h"
24
25#define DEBUG_TYPE "machine-scheduler"
26
27STATISTIC(NumFused, "Number of instr pairs fused");
28
29using namespace llvm;
30
32 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
33
34static bool isHazard(const SDep &Dep) {
35 return Dep.getKind() == SDep::Anti || Dep.getKind() == SDep::Output;
36}
37
38static SUnit *getPredClusterSU(const SUnit &SU) {
39 for (const SDep &SI : SU.Preds)
40 if (SI.isCluster())
41 return SI.getSUnit();
42
43 return nullptr;
44}
45
46bool llvm::hasLessThanNumFused(const SUnit &SU, unsigned FuseLimit) {
47 unsigned Num = 1;
48 const SUnit *CurrentSU = &SU;
49 while ((CurrentSU = getPredClusterSU(*CurrentSU)) && Num < FuseLimit) Num ++;
50 return Num < FuseLimit;
51}
52
54 SUnit &SecondSU) {
55 // Check that neither instr is already paired with another along the edge
56 // between them.
57 for (SDep &SI : FirstSU.Succs)
58 if (SI.isCluster())
59 return false;
60
61 for (SDep &SI : SecondSU.Preds)
62 if (SI.isCluster())
63 return false;
64
67
68 // Though the reachability checks above could be made more generic,
69 // perhaps as part of ScheduleDAGInstrs::addEdge(), since such edges are valid,
70 // the extra computation cost makes it less interesting in general cases.
71
72 // Create a single weak edge between the adjacent instrs. The only effect is
73 // to cause bottom-up scheduling to heavily prioritize the clustered instrs.
74 if (!DAG.addEdge(&SecondSU, SDep(&FirstSU, SDep::Cluster)))
75 return false;
76
77 auto &Clusters = DAG.getClusters();
78
79 FirstSU.ParentClusterIdx = Clusters.size();
80 SecondSU.ParentClusterIdx = Clusters.size();
81
82 SmallPtrSet<SUnit *, 8> Cluster{{&FirstSU, &SecondSU}};
83 Clusters.push_back(Cluster);
84
85 // TODO - If we want to chain more than two instructions, we need to create
86 // artifical edges to make dependencies from the FirstSU also dependent
87 // on other chained instructions, and other chained instructions also
88 // dependent on the dependencies of the SecondSU, to prevent them from being
89 // scheduled into these chained instructions.
90 assert(hasLessThanNumFused(FirstSU, 2) &&
91 "Currently we only support chaining together two instructions");
92
93 // Adjust the latency between both instrs.
94 for (SDep &SI : FirstSU.Succs)
95 if (SI.getSUnit() == &SecondSU)
96 SI.setLatency(0);
97
98 for (SDep &SI : SecondSU.Preds)
99 if (SI.getSUnit() == &FirstSU)
100 SI.setLatency(0);
101
103 dbgs() << "Macro fuse: "; DAG.dumpNodeName(FirstSU); dbgs() << " - ";
104 DAG.dumpNodeName(SecondSU); dbgs() << " / ";
105 dbgs() << DAG.TII->getName(FirstSU.getInstr()->getOpcode()) << " - "
106 << DAG.TII->getName(SecondSU.getInstr()->getOpcode()) << '\n';);
107
108 // Make data dependencies from the FirstSU also dependent on the SecondSU to
109 // prevent them from being scheduled between the FirstSU and the SecondSU.
110 if (&SecondSU != &DAG.ExitSU)
111 for (const SDep &SI : FirstSU.Succs) {
112 SUnit *SU = SI.getSUnit();
113 if (SI.isWeak() || isHazard(SI) ||
114 SU == &DAG.ExitSU || SU == &SecondSU || SU->isPred(&SecondSU))
115 continue;
116 LLVM_DEBUG(dbgs() << " Bind "; DAG.dumpNodeName(SecondSU);
117 dbgs() << " - "; DAG.dumpNodeName(*SU); dbgs() << '\n';);
118 DAG.addEdge(SU, SDep(&SecondSU, SDep::Artificial));
119 }
120
121 // Make the FirstSU also dependent on the dependencies of the SecondSU to
122 // prevent them from being scheduled between the FirstSU and the SecondSU.
123 if (&FirstSU != &DAG.EntrySU) {
124 for (const SDep &SI : SecondSU.Preds) {
125 SUnit *SU = SI.getSUnit();
126 if (SI.isWeak() || isHazard(SI) || &FirstSU == SU || FirstSU.isSucc(SU))
127 continue;
128 LLVM_DEBUG(dbgs() << " Bind "; DAG.dumpNodeName(*SU); dbgs() << " - ";
129 DAG.dumpNodeName(FirstSU); dbgs() << '\n';);
130 DAG.addEdge(&FirstSU, SDep(SU, SDep::Artificial));
131 }
132 // ExitSU comes last by design, which acts like an implicit dependency
133 // between ExitSU and any bottom root in the graph. We should transfer
134 // this to FirstSU as well.
135 if (&SecondSU == &DAG.ExitSU) {
136 for (SUnit &SU : DAG.SUnits) {
137 if (SU.Succs.empty())
138 DAG.addEdge(&FirstSU, SDep(&SU, SDep::Artificial));
139 }
140 }
141 }
142
143 ++NumFused;
144 return true;
145}
146
147namespace {
148
149/// Post-process the DAG to create cluster edges between instrs that may
150/// be fused by the processor into a single operation.
151class MacroFusion : public ScheduleDAGMutation {
152 std::vector<MacroFusionPredTy> Predicates;
153 bool FuseBlock;
154 bool scheduleAdjacentImpl(ScheduleDAGInstrs &DAG, SUnit &AnchorSU);
155
156public:
157 MacroFusion(ArrayRef<MacroFusionPredTy> Predicates, bool FuseBlock)
158 : Predicates(Predicates.begin(), Predicates.end()), FuseBlock(FuseBlock) {
159 }
160
161 void apply(ScheduleDAGInstrs *DAGInstrs) override;
162
163 bool shouldScheduleAdjacent(const TargetInstrInfo &TII,
164 const TargetSubtargetInfo &STI,
165 const MachineInstr *FirstMI,
166 const MachineInstr &SecondMI);
167};
168
169} // end anonymous namespace
170
171bool MacroFusion::shouldScheduleAdjacent(const TargetInstrInfo &TII,
172 const TargetSubtargetInfo &STI,
173 const MachineInstr *FirstMI,
174 const MachineInstr &SecondMI) {
175 return llvm::any_of(Predicates, [&](MacroFusionPredTy Predicate) {
176 return Predicate(TII, STI, FirstMI, SecondMI);
177 });
178}
179
180void MacroFusion::apply(ScheduleDAGInstrs *DAG) {
181 if (FuseBlock)
182 // For each of the SUnits in the scheduling block, try to fuse the instr in
183 // it with one in its predecessors.
184 for (SUnit &ISU : DAG->SUnits)
185 scheduleAdjacentImpl(*DAG, ISU);
186
187 if (DAG->ExitSU.getInstr())
188 // Try to fuse the instr in the ExitSU with one in its predecessors.
189 scheduleAdjacentImpl(*DAG, DAG->ExitSU);
190}
191
192/// Implement the fusion of instr pairs in the scheduling DAG,
193/// anchored at the instr in AnchorSU..
194bool MacroFusion::scheduleAdjacentImpl(ScheduleDAGInstrs &DAG, SUnit &AnchorSU) {
195 const MachineInstr &AnchorMI = *AnchorSU.getInstr();
196 const TargetInstrInfo &TII = *DAG.TII;
197 const TargetSubtargetInfo &ST = DAG.MF.getSubtarget();
198
199 // Check if the anchor instr may be fused.
200 if (!shouldScheduleAdjacent(TII, ST, nullptr, AnchorMI))
201 return false;
202
203 // Explorer for fusion candidates among the dependencies of the anchor instr.
204 for (SDep &Dep : AnchorSU.Preds) {
205 // Ignore dependencies other than data or strong ordering.
206 if (Dep.isWeak() || isHazard(Dep))
207 continue;
208
209 SUnit &DepSU = *Dep.getSUnit();
210 if (DepSU.isBoundaryNode())
211 continue;
212
213 // Only chain two instructions together at most.
214 const MachineInstr *DepMI = DepSU.getInstr();
215 if (!hasLessThanNumFused(DepSU, 2) ||
216 !shouldScheduleAdjacent(TII, ST, DepMI, AnchorMI))
217 continue;
218
219 if (fuseInstructionPair(DAG, DepSU, AnchorSU))
220 return true;
221 }
222
223 return false;
224}
225
226std::unique_ptr<ScheduleDAGMutation>
228 bool BranchOnly) {
230 return std::make_unique<MacroFusion>(Predicates, !BranchOnly);
231 return nullptr;
232}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool shouldScheduleAdjacent(const TargetInstrInfo &TII, const TargetSubtargetInfo &TSI, const MachineInstr *FirstMI, const MachineInstr &SecondMI)
Check if the instr pair, FirstMI and SecondMI, should be fused together.
const HexagonInstrInfo * TII
static cl::opt< bool > EnableMacroFusion("misched-fusion", cl::Hidden, cl::desc("Enable scheduling for macro fusion."), cl::init(true))
static SUnit * getPredClusterSU(const SUnit &SU)
static bool isHazard(const SDep &Dep)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
StringRef getName(unsigned Opcode) const
Returns the name for the instructions with the given opcode.
Definition MCInstrInfo.h:97
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Scheduling dependency.
Definition ScheduleDAG.h:51
SUnit * getSUnit() const
Kind getKind() const
Returns an enum value representing the kind of the dependence.
@ Output
A register output-dependence (aka WAW).
Definition ScheduleDAG.h:57
@ Anti
A register anti-dependence (aka WAR).
Definition ScheduleDAG.h:56
bool isWeak() const
Tests if this a weak dependence.
@ Cluster
Weak DAG edge linking a chain of clustered instrs.
Definition ScheduleDAG.h:76
@ Artificial
Arbitrary strong DAG edge (no real dependence).
Definition ScheduleDAG.h:74
Scheduling unit. This is a node in the scheduling DAG.
bool isSucc(const SUnit *N) const
Tests if node N is a successor of this node.
bool isPred(const SUnit *N) const
Tests if node N is a predecessor of this node.
bool isBoundaryNode() const
Boundary nodes are placeholders for the boundary of the scheduling region.
unsigned ParentClusterIdx
The parent cluster id.
SmallVector< SDep, 4 > Succs
All sunit successors.
SmallVector< SDep, 4 > Preds
All sunit predecessors.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
A ScheduleDAG for scheduling lists of MachineInstr.
SmallVector< ClusterInfo > & getClusters()
Returns the array of the clusters.
bool addEdge(SUnit *SuccSU, const SDep &PredDep)
Add a DAG edge to the given SU with the given predecessor dependence data.
Mutate the DAG as a postpass after normal DAG building.
const TargetInstrInfo * TII
Target instruction information.
std::vector< SUnit > SUnits
The scheduling units.
SUnit EntrySU
Special node for the region entry.
MachineFunction & MF
Machine function.
void dumpNodeName(const SUnit &SU) const
SUnit ExitSU
Special node for the region exit.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
TargetInstrInfo - Interface to description of machine instruction set.
TargetSubtargetInfo - Generic base class for all target subtargets.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
void apply(Opt *O, const Mod &M, const Mods &... Ms)
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createMacroFusionDAGMutation(ArrayRef< MacroFusionPredTy > Predicates, bool BranchOnly=false)
Create a DAG scheduling mutation to pair instructions back to back for instructions that benefit acco...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1712
LLVM_ABI bool fuseInstructionPair(ScheduleDAGInstrs &DAG, SUnit &FirstSU, SUnit &SecondSU)
Create an artificial edge between FirstSU and SecondSU.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
constexpr unsigned InvalidClusterId
bool(*)(const TargetInstrInfo &TII, const TargetSubtargetInfo &STI, const MachineInstr *FirstMI, const MachineInstr &SecondMI) MacroFusionPredTy
Check if the instr pair, FirstMI and SecondMI, should be fused together.
Definition MacroFusion.h:33
static bool shouldScheduleAdjacent(const TargetInstrInfo &TII, const TargetSubtargetInfo &TSI, const MachineInstr *FirstMI, const MachineInstr &SecondMI)
Check if the instr pair, FirstMI and SecondMI, should be fused together.
LLVM_ABI bool hasLessThanNumFused(const SUnit &SU, unsigned FuseLimit)
Checks if the number of cluster edges between SU and its predecessors is less than FuseLimit.