LLVM 24.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");
28STATISTIC(NumFusionConflicts,
29 "Number of conflicts between a fusion pair and an already existing "
30 "cluster (either fusion or non-fusion)");
31
32using namespace llvm;
33
35 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
36
37static bool isHazard(const SDep &Dep) {
38 return Dep.getKind() == SDep::Anti || Dep.getKind() == SDep::Output;
39}
40
41static SUnit *getPredClusterSU(const SUnit &SU) {
42 for (const SDep &SI : SU.Preds)
43 if (SI.isCluster())
44 return SI.getSUnit();
45
46 return nullptr;
47}
48
49bool llvm::hasLessThanNumFused(const SUnit &SU, unsigned FuseLimit) {
50 unsigned Num = 1;
51 const SUnit *CurrentSU = &SU;
52 while ((CurrentSU = getPredClusterSU(*CurrentSU)) && Num < FuseLimit) Num ++;
53 return Num < FuseLimit;
54}
55
56bool llvm::isNonDataDep(const SDep *Dep) {
57 return Dep && Dep->getKind() != SDep::Data;
58}
59
61 SUnit &SecondSU) {
62 // Check that neither instr is already associated with a cluster (either
63 // fusion or non-fusion)
64 if (FirstSU.isClustered() || SecondSU.isClustered()) {
65 ++NumFusionConflicts;
67 dbgs() << "Fusion conflict: cannot fuse " << FirstSU << " and ";
68 DAG.dumpNodeName(SecondSU);
69 dbgs() << "\n";
70 if (FirstSU.isClustered())
71 dbgs() << " " << FirstSU << " already clustered\n";
72 if (SecondSU.isClustered()) {
73 dbgs() << " ";
74 DAG.dumpNodeName(SecondSU);
75 dbgs() << " already clustered\n";
76 }
77 });
78 return false;
79 }
80
81 // Create a single weak edge between the adjacent instrs. The only effect is
82 // to cause bottom-up scheduling to heavily prioritize the clustered instrs.
83 if (!DAG.addEdge(&SecondSU, SDep(&FirstSU, SDep::Cluster)))
84 return false;
85
86 auto &Clusters = DAG.getClusters();
87
88 unsigned ClusterIdx = Clusters.size();
89 FirstSU.ParentClusterIdx = ClusterIdx;
90 SecondSU.ParentClusterIdx = ClusterIdx;
91
92 SmallPtrSet<SUnit *, 8> Cluster{{&FirstSU, &SecondSU}};
93 Clusters.push_back(Cluster);
94
95 // TODO - If we want to chain more than two instructions, we need to create
96 // artifical edges to make dependencies from the FirstSU also dependent
97 // on other chained instructions, and other chained instructions also
98 // dependent on the dependencies of the SecondSU, to prevent them from being
99 // scheduled into these chained instructions.
100 assert(hasLessThanNumFused(FirstSU, 2) &&
101 "Currently we only support chaining together two instructions");
102
103 // Adjust the latency between both instrs.
104 for (SDep &SI : FirstSU.Succs)
105 if (SI.getSUnit() == &SecondSU)
106 SI.setLatency(0);
107
108 for (SDep &SI : SecondSU.Preds)
109 if (SI.getSUnit() == &FirstSU)
110 SI.setLatency(0);
111
113 dbgs() << "Macro fuse: "; DAG.dumpNodeName(FirstSU); dbgs() << " - ";
114 DAG.dumpNodeName(SecondSU); dbgs() << " / ";
115 dbgs() << DAG.TII->getName(FirstSU.getInstr()->getOpcode()) << " - "
116 << DAG.TII->getName(SecondSU.getInstr()->getOpcode()) << '\n';);
117
118 // Make data dependencies from the FirstSU also dependent on the SecondSU to
119 // prevent them from being scheduled between the FirstSU and the SecondSU.
120 if (&SecondSU != &DAG.ExitSU)
121 for (const SDep &SI : FirstSU.Succs) {
122 SUnit *SU = SI.getSUnit();
123 if (SI.isWeak() || isHazard(SI) ||
124 SU == &DAG.ExitSU || SU == &SecondSU || SU->isPred(&SecondSU))
125 continue;
126 LLVM_DEBUG(dbgs() << " Bind "; DAG.dumpNodeName(SecondSU);
127 dbgs() << " - "; DAG.dumpNodeName(*SU); dbgs() << '\n';);
128 DAG.addEdge(SU, SDep(&SecondSU, SDep::Artificial));
129 }
130
131 // Make the FirstSU also dependent on the dependencies of the SecondSU to
132 // prevent them from being scheduled between the FirstSU and the SecondSU.
133 if (&FirstSU != &DAG.EntrySU) {
134 for (const SDep &SI : SecondSU.Preds) {
135 SUnit *SU = SI.getSUnit();
136 if (SI.isWeak() || isHazard(SI) || &FirstSU == SU || FirstSU.isSucc(SU))
137 continue;
138 LLVM_DEBUG(dbgs() << " Bind "; DAG.dumpNodeName(*SU); dbgs() << " - ";
139 DAG.dumpNodeName(FirstSU); dbgs() << '\n';);
140 DAG.addEdge(&FirstSU, SDep(SU, SDep::Artificial));
141 }
142 // ExitSU comes last by design, which acts like an implicit dependency
143 // between ExitSU and any bottom root in the graph. We should transfer
144 // this to FirstSU as well.
145 if (&SecondSU == &DAG.ExitSU) {
146 for (SUnit &SU : DAG.SUnits) {
147 if (SU.Succs.empty())
148 DAG.addEdge(&FirstSU, SDep(&SU, SDep::Artificial));
149 }
150 }
151 }
152
153 ++NumFused;
154 return true;
155}
156
157namespace {
158
159/// Post-process the DAG to create cluster edges between instrs that may
160/// be fused by the processor into a single operation.
161class MacroFusion : public ScheduleDAGMutation {
162 std::vector<MacroFusionPredTy> Predicates;
163 bool FuseBlock;
164 bool scheduleAdjacentImpl(ScheduleDAGInstrs &DAG, SUnit &AnchorSU);
165
166public:
167 MacroFusion(ArrayRef<MacroFusionPredTy> Predicates, bool FuseBlock)
168 : Predicates(Predicates.begin(), Predicates.end()), FuseBlock(FuseBlock) {
169 }
170
171 void apply(ScheduleDAGInstrs *DAGInstrs) override;
172
173 bool shouldScheduleAdjacent(const TargetInstrInfo &TII,
174 const TargetSubtargetInfo &STI,
175 const MachineInstr *FirstMI,
176 const MachineInstr &SecondMI, const SDep *Dep);
177};
178
179} // end anonymous namespace
180
181bool MacroFusion::shouldScheduleAdjacent(const TargetInstrInfo &TII,
182 const TargetSubtargetInfo &STI,
183 const MachineInstr *FirstMI,
184 const MachineInstr &SecondMI,
185 const SDep *Dep) {
186 return llvm::any_of(Predicates, [&](MacroFusionPredTy Predicate) {
187 return Predicate(TII, STI, FirstMI, SecondMI, Dep);
188 });
189}
190
191void MacroFusion::apply(ScheduleDAGInstrs *DAG) {
192 if (FuseBlock)
193 // For each of the SUnits in the scheduling block, try to fuse the instr in
194 // it with one in its predecessors.
195 for (SUnit &ISU : DAG->SUnits)
196 scheduleAdjacentImpl(*DAG, ISU);
197
198 if (DAG->ExitSU.getInstr())
199 // Try to fuse the instr in the ExitSU with one in its predecessors.
200 scheduleAdjacentImpl(*DAG, DAG->ExitSU);
201}
202
203/// Implement the fusion of instr pairs in the scheduling DAG,
204/// anchored at the instr in AnchorSU..
205bool MacroFusion::scheduleAdjacentImpl(ScheduleDAGInstrs &DAG, SUnit &AnchorSU) {
206 const MachineInstr &AnchorMI = *AnchorSU.getInstr();
207 const TargetInstrInfo &TII = *DAG.TII;
208 const TargetSubtargetInfo &ST = DAG.MF.getSubtarget();
209
210 // Check if the anchor instr may be fused.
211 if (!shouldScheduleAdjacent(TII, ST, nullptr, AnchorMI, nullptr))
212 return false;
213
214 // Explorer for fusion candidates among the dependencies of the anchor instr.
215 for (SDep &Dep : AnchorSU.Preds) {
216 SUnit &DepSU = *Dep.getSUnit();
217 if (DepSU.isBoundaryNode())
218 continue;
219
220 // Only chain two instructions together at most.
221 const MachineInstr *DepMI = DepSU.getInstr();
222 if (!hasLessThanNumFused(DepSU, 2) ||
223 !shouldScheduleAdjacent(TII, ST, DepMI, AnchorMI, &Dep))
224 continue;
225
226 if (fuseInstructionPair(DAG, DepSU, AnchorSU))
227 return true;
228 }
229
230 return false;
231}
232
233std::unique_ptr<ScheduleDAGMutation>
235 bool BranchOnly) {
237 return std::make_unique<MacroFusion>(Predicates, !BranchOnly);
238 return nullptr;
239}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool shouldScheduleAdjacent(const TargetInstrInfo &TII, const TargetSubtargetInfo &TSI, const MachineInstr *FirstMI, const MachineInstr &SecondMI, const SDep *Dep)
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:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
StringRef getName(unsigned Opcode) const
Returns the name for the instructions with the given opcode.
Definition MCInstrInfo.h:96
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:54
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:60
@ Anti
A register anti-dependence (aka WAR).
Definition ScheduleDAG.h:59
@ Data
Regular data dependence (aka true-dependence).
Definition ScheduleDAG.h:58
@ Cluster
Weak DAG edge linking a chain of clustered instrs.
Definition ScheduleDAG.h:79
@ Artificial
Arbitrary strong DAG edge (no real dependence).
Definition ScheduleDAG.h:77
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.
bool isClustered() const
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:1762
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:209
static bool shouldScheduleAdjacent(const TargetInstrInfo &TII, const TargetSubtargetInfo &TSI, const MachineInstr *FirstMI, const MachineInstr &SecondMI, const SDep *Dep)
Check if the instr pair, FirstMI and SecondMI, should be fused together.
LLVM_ABI bool isNonDataDep(const SDep *Dep)
Returns true if Dep is a non-null non-data dependency.
bool(*)(const TargetInstrInfo &TII, const TargetSubtargetInfo &STI, const MachineInstr *FirstMI, const MachineInstr &SecondMI, const SDep *Dep) MacroFusionPredTy
Check if the instr pair, FirstMI and SecondMI, should be fused together, based on the dependency betw...
Definition MacroFusion.h:35
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.