LLVM 24.0.0git
DFAPacketizer.cpp
Go to the documentation of this file.
1//=- llvm/CodeGen/DFAPacketizer.cpp - DFA Packetizer for VLIW -*- C++ -*-=====//
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// This class implements a deterministic finite automaton (DFA) based
9// packetizing mechanism for VLIW architectures. It provides APIs to
10// determine whether there exists a legal mapping of instructions to
11// functional unit assignments in a packet. The DFA is auto-generated from
12// the target's Schedule.td file.
13//
14// A DFA consists of 3 major elements: states, inputs, and transitions. For
15// the packetizing mechanism, the input is the set of instruction classes for
16// a target. The state models all possible combinations of functional unit
17// consumption for a given set of instructions in a packet. A transition
18// models the addition of an instruction to a packet. In the DFA constructed
19// by this class, if an instruction can be added to a packet, then a valid
20// transition exists from the corresponding state. Invalid transitions
21// indicate that the instruction cannot be added to the current packet.
22//
23//===----------------------------------------------------------------------===//
24
26#include "CodeGenOptions.h"
35#include "llvm/MC/MCInstrDesc.h"
36#include "llvm/Support/Debug.h"
38#include <algorithm>
39#include <cassert>
40#include <iterator>
41#include <memory>
42
43using namespace llvm;
44
45#define DEBUG_TYPE "packets"
46
47static unsigned InstrCount = 0;
48
49// Check if the resources occupied by a MCInstrDesc are available in the
50// current state.
52 unsigned Action = ItinActions[MID->getSchedClass()];
53 if (MID->getSchedClass() == 0 || Action == 0)
54 return false;
55 return A.canAdd(Action);
56}
57
58// Reserve the resources occupied by a MCInstrDesc and change the current
59// state to reflect that change.
61 unsigned Action = ItinActions[MID->getSchedClass()];
62 if (MID->getSchedClass() == 0 || Action == 0)
63 return;
64 A.add(Action);
65}
66
67// Check if the resources occupied by a machine instruction are available
68// in the current state.
70 const MCInstrDesc &MID = MI.getDesc();
71 return canReserveResources(&MID);
72}
73
74// Reserve the resources occupied by a machine instruction and change the
75// current state to reflect that change.
77 const MCInstrDesc &MID = MI.getDesc();
78 reserveResources(&MID);
79}
80
81unsigned DFAPacketizer::getUsedResources(unsigned InstIdx) {
82 ArrayRef<NfaPath> NfaPaths = A.getNfaPaths();
83 assert(!NfaPaths.empty() && "Invalid bundle!");
84 const NfaPath &RS = NfaPaths.front();
85
86 // RS stores the cumulative resources used up to and including the I'th
87 // instruction. The 0th instruction is the base case.
88 if (InstIdx == 0)
89 return RS[0];
90 // Return the difference between the cumulative resources used by InstIdx and
91 // its predecessor.
92 return RS[InstIdx] ^ RS[InstIdx - 1];
93}
94
101
102/// Apply each ScheduleDAGMutation step in order.
104 for (auto &M : Mutations)
105 M->apply(this);
106}
107
109 // Build the scheduling graph.
110 buildSchedGraph(AA);
112}
113
116 : MF(mf), TII(mf.getSubtarget().getInstrInfo()), AA(aa) {
117 ResourceTracker = TII->CreateTargetScheduleState(MF.getSubtarget());
118 ResourceTracker->setTrackResources(true);
120}
121
126
127// End the current packet, bundle packet instructions and reset DFA state.
130 LLVM_DEBUG({
131 if (!CurrentPacketMIs.empty()) {
132 dbgs() << "Finalizing packet:\n";
133 unsigned Idx = 0;
135 unsigned R = ResourceTracker->getUsedResources(Idx++);
136 dbgs() << " * [res:0x" << utohexstr(R) << "] " << *MI;
137 }
138 }
139 });
140 if (CurrentPacketMIs.size() > 1) {
141 MachineInstr &MIFirst = *CurrentPacketMIs.front();
142 finalizeBundle(*MBB, MIFirst.getIterator(), MI.getInstrIterator());
143 }
144 CurrentPacketMIs.clear();
145 ResourceTracker->clearResources();
146 LLVM_DEBUG(dbgs() << "End packet\n");
147}
148
149// Bundle machine instructions into packets.
153 assert(VLIWScheduler && "VLIW Scheduler is not initialized!");
154 VLIWScheduler->startBlock(MBB);
155 VLIWScheduler->enterRegion(MBB, BeginItr, EndItr,
156 std::distance(BeginItr, EndItr));
157 VLIWScheduler->schedule();
158
159 LLVM_DEBUG({
160 dbgs() << "Scheduling DAG of the packetize region\n";
161 VLIWScheduler->dump();
162 });
163
164 // Generate MI -> SU map.
165 MIToSUnit.clear();
166 for (SUnit &SU : VLIWScheduler->SUnits)
167 MIToSUnit[SU.getInstr()] = &SU;
168
169 std::optional<unsigned> InstrLimit = VLIWScheduler->Opts.dfa_instr_limit;
170
171 // The main packetizer loop.
172 for (; BeginItr != EndItr; ++BeginItr) {
173 if (InstrLimit) {
174 if (InstrCount >= *InstrLimit) {
175 EndItr = BeginItr;
176 break;
177 }
178 InstrCount++;
179 }
180 MachineInstr &MI = *BeginItr;
182
183 // End the current packet if needed.
184 if (isSoloInstruction(MI)) {
185 endPacket(MBB, MI);
186 continue;
187 }
188
189 // Ignore pseudo instructions.
191 continue;
192
193 SUnit *SUI = MIToSUnit[&MI];
194 assert(SUI && "Missing SUnit Info!");
195
196 // Ask DFA if machine resource is available for MI.
197 LLVM_DEBUG(dbgs() << "Checking resources for adding MI to packet " << MI);
198
199 bool ResourceAvail = ResourceTracker->canReserveResources(MI);
200 LLVM_DEBUG({
201 if (ResourceAvail)
202 dbgs() << " Resources are available for adding MI to packet\n";
203 else
204 dbgs() << " Resources NOT available\n";
205 });
206 if (ResourceAvail && shouldAddToPacket(MI)) {
207 // Dependency check for MI with instructions in CurrentPacketMIs.
208 for (auto *MJ : CurrentPacketMIs) {
209 SUnit *SUJ = MIToSUnit[MJ];
210 assert(SUJ && "Missing SUnit Info!");
211
212 LLVM_DEBUG(dbgs() << " Checking against MJ " << *MJ);
213 // Is it legal to packetize SUI and SUJ together.
214 if (!isLegalToPacketizeTogether(SUI, SUJ)) {
215 LLVM_DEBUG(dbgs() << " Not legal to add MI, try to prune\n");
216 // Allow packetization if dependency can be pruned.
217 if (!isLegalToPruneDependencies(SUI, SUJ)) {
218 // End the packet if dependency cannot be pruned.
220 << " Could not prune dependencies for adding MI\n");
221 endPacket(MBB, MI);
222 break;
223 }
224 LLVM_DEBUG(dbgs() << " Pruned dependence for adding MI\n");
225 }
226 }
227 } else {
228 LLVM_DEBUG(if (ResourceAvail) dbgs()
229 << "Resources are available, but instruction should not be "
230 "added to packet\n "
231 << MI);
232 // End the packet if resource is not available, or if the instruction
233 // should not be added to the current packet.
234 endPacket(MBB, MI);
235 }
236
237 // Add MI to the current packet.
238 LLVM_DEBUG(dbgs() << "* Adding MI to packet " << MI << '\n');
239 BeginItr = addToPacket(MI);
240 } // For all instructions in the packetization range.
241
242 // End any packet left behind.
243 endPacket(MBB, EndItr);
244 VLIWScheduler->exitRegion();
245 VLIWScheduler->finishBlock();
246}
247
249 const MachineMemOperand &Op2,
250 bool UseTBAA) const {
251 if (!Op1.getValue() || !Op2.getValue() || !Op1.getSize().hasValue() ||
252 !Op2.getSize().hasValue())
253 return true;
254
255 int64_t MinOffset = std::min(Op1.getOffset(), Op2.getOffset());
256 int64_t Overlapa = Op1.getSize().getValue() + Op1.getOffset() - MinOffset;
257 int64_t Overlapb = Op2.getSize().getValue() + Op2.getOffset() - MinOffset;
258
259 AliasResult AAResult =
260 AA->alias(MemoryLocation(Op1.getValue(), Overlapa,
261 UseTBAA ? Op1.getAAInfo() : AAMDNodes()),
262 MemoryLocation(Op2.getValue(), Overlapb,
263 UseTBAA ? Op2.getAAInfo() : AAMDNodes()));
264
265 return AAResult != AliasResult::NoAlias;
266}
267
269 const MachineInstr &MI2,
270 bool UseTBAA) const {
271 if (MI1.memoperands_empty() || MI2.memoperands_empty())
272 return true;
273
274 for (const MachineMemOperand *Op1 : MI1.memoperands())
275 for (const MachineMemOperand *Op2 : MI2.memoperands())
276 if (alias(*Op1, *Op2, UseTBAA))
277 return true;
278 return false;
279}
280
281// Add a DAG mutation object to the ordered list.
283 std::unique_ptr<ScheduleDAGMutation> Mutation) {
284 VLIWScheduler->addMutation(std::move(Mutation));
285}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static unsigned InstrCount
IRTranslator LLVM IR MI
PowerPC VSX FMA Mutation
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
The possible results of an alias query.
@ NoAlias
The two locations do not alias at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
LLVM_ABI unsigned getUsedResources(unsigned InstIdx)
LLVM_ABI bool canReserveResources(const MCInstrDesc *MID)
LLVM_ABI void reserveResources(const MCInstrDesc *MID)
void postProcessDAG()
Apply each ScheduleDAGMutation step in order.
void schedule() override
Orders nodes according to selected style.
DefaultVLIWScheduler(MachineFunction &MF, MachineLoopInfo &MLI, AAResults *AA)
bool hasValue() const
TypeSize getValue() const
Describe properties that are true of each instruction in the target description file.
unsigned getSchedClass() const
Return the scheduling class for this instruction.
MachineInstrBundleIterator< MachineInstr > iterator
Representation of each machine instruction.
bool memoperands_empty() const
Return true if we don't have any memory operands which described the memory access done by this instr...
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
A description of a memory reference used in the backend.
LocationSize getSize() const
Return the size in bytes of the memory reference.
AAMDNodes getAAInfo() const
Return the AA tags for the memory reference.
const Value * getValue() const
Return the base address of the memory access.
int64_t getOffset() const
For normal values, this is a byte offset added to the base address.
Representation for a specific memory location.
Scheduling unit. This is a node in the scheduling DAG.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
bool CanHandleTerminators
The standard DAG builder does not normally include terminators as DAG nodes because it does not creat...
ScheduleDAGInstrs(MachineFunction &mf, const MachineLoopInfo *mli, bool RemoveKillFlags=false)
void buildSchedGraph(AAResults *AA, RegPressureTracker *RPTracker=nullptr, PressureDiffs *PDiffs=nullptr, LiveIntervals *LIS=nullptr, bool TrackLaneMasks=false)
Builds SUnits for the current region.
const MachineLoopInfo * MLI
MachineFunction & MF
Machine function.
VLIWPacketizerList(MachineFunction &MF, MachineLoopInfo &MLI, AAResults *AA)
virtual bool isSoloInstruction(const MachineInstr &MI)
void addMutation(std::unique_ptr< ScheduleDAGMutation > Mutation)
virtual bool isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ)
const TargetInstrInfo * TII
bool alias(const MachineInstr &MI1, const MachineInstr &MI2, bool UseTBAA=true) const
std::vector< MachineInstr * > CurrentPacketMIs
std::map< MachineInstr *, SUnit * > MIToSUnit
DefaultVLIWScheduler * VLIWScheduler
virtual bool isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ)
DFAPacketizer * ResourceTracker
virtual void initPacketizerState()
virtual void endPacket(MachineBasicBlock *MBB, MachineBasicBlock::iterator MI)
virtual bool ignorePseudoInstruction(const MachineInstr &I, const MachineBasicBlock *MBB)
void PacketizeMIs(MachineBasicBlock *MBB, MachineBasicBlock::iterator BeginItr, MachineBasicBlock::iterator EndItr)
virtual MachineBasicBlock::iterator addToPacket(MachineInstr &MI)
virtual bool shouldAddToPacket(const MachineInstr &MI)
self_iterator getIterator()
Definition ilist_node.h:123
Abstract Attribute helper functions.
Definition Attributor.h:166
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void finalizeBundle(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
finalizeBundle - Finalize a machine instruction bundle which includes a sequence of instructions star...
std::string utohexstr(uint64_t X, bool LowerCase=false, unsigned Width=0)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
SmallVector< uint64_t, 4 > NfaPath
Definition Automaton.h:39
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:775