LLVM 24.0.0git
SlotIndexes.cpp
Go to the documentation of this file.
1//===-- SlotIndexes.cpp - Slot Indexes Pass ------------------------------===//
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
10#include "llvm/ADT/Statistic.h"
12#include "llvm/Config/llvm-config.h"
14#include "llvm/Support/Debug.h"
16
17using namespace llvm;
18
19#define DEBUG_TYPE "slot-indexes"
20
21AnalysisKey SlotIndexesAnalysis::Key;
22
28
32 OS << "Slot indexes in machine function: " << MF.getName() << '\n';
35}
37
39
41 // The indexList's nodes are all allocated in the BumpPtrAllocator.
42 indexList.clear();
43}
44
46 false, false)
47
48STATISTIC(NumLocalRenum, "Number of local renumberings");
49STATISTIC(NumDeadEntriesErased,
50 "Number of index list entries erased for deleted instructions");
51
56
57void SlotIndexes::clear() {
58 MIEntries.clear();
59 MBBRanges.clear();
60 idx2MBBMap.clear();
61 indexList.clear();
62 ileAllocator.Reset();
63}
64
65void SlotIndexes::analyze(MachineFunction &fn) {
66
67 // Compute numbering as follows:
68 // Grab an iterator to the start of the index list.
69 // Iterate over all MBBs, and within each MBB all MIs, keeping the MI
70 // iterator in lock-step (though skipping it over indexes which have
71 // null pointers in the instruction field).
72 // At each iteration assert that the instruction pointed to in the index
73 // is the same one pointed to by the MI iterator. This
74
75 // FIXME: This can be simplified. The mi2iMap_, Idx2MBBMap, etc. should
76 // only need to be set up once after the first numbering is computed.
77
78 mf = &fn;
79
80 // Check that the list contains only the sentinel.
81 assert(indexList.empty() && "Index list non-empty at initial numbering?");
82 assert(idx2MBBMap.empty() &&
83 "Index -> MBB mapping non-empty at initial numbering?");
84 assert(MBBRanges.empty() &&
85 "MBB -> Index mapping non-empty at initial numbering?");
86 assert(MIEntries.empty() &&
87 "MachineInstr -> Index mapping non-empty at initial numbering?");
88
89 unsigned index = 0;
90 MBBRanges.resize(mf->getMaxAnalysisBlockNumber());
91 idx2MBBMap.reserve(mf->size());
92
93 indexList.push_back(*createEntry(nullptr, index));
94
95 // Iterate over the function.
96 for (MachineBasicBlock &MBB : *mf) {
97 // Insert an index for the MBB start.
98 SlotIndex blockStartIndex(&indexList.back(), SlotIndex::Slot_Block);
99
100 for (MachineInstr &MI : MBB.instrs()) {
101 if (MI.isBundledWithPred() || MI.isDebugOrPseudoInstr()) {
102 MI.SlotIndexHandle = 0;
103 continue;
104 }
105
106 // Insert a store index for the instr.
107 indexList.push_back(*createEntry(&MI, index += SlotIndex::InstrDist));
108
109 // Save this base index in the maps.
110 setMIEntry(MI, &indexList.back());
111 }
112
113 // We insert one blank instructions between basic blocks.
114 indexList.push_back(*createEntry(nullptr, index += SlotIndex::InstrDist));
115
116 MBBRanges[MBB.getAnalysisNumber()].first = blockStartIndex;
117 MBBRanges[MBB.getAnalysisNumber()].second =
118 SlotIndex(&indexList.back(), SlotIndex::Slot_Block);
119 idx2MBBMap.push_back(IdxMBBPair(blockStartIndex, &MBB));
120 }
121
122 // Sort the Idx2MBBMap
123 llvm::sort(idx2MBBMap, less_first());
124
125 LLVM_DEBUG(mf->print(dbgs(), this));
126}
127
130 return false;
131
132 // Adjacent blocks share a boundary entry, so a boundary is either the start
133 // index of the block Idx falls in or the end index of the last block. A block
134 // dropped by removeMBBFromMaps() is gone from idx2MBBMap, so its start entry
135 // classifies as stale.
136 assert(!idx2MBBMap.empty() && "Index -> MBB mapping is empty");
137 SlotIndex Base = Idx.getBaseIndex();
139 return Base == I->first || Base == getMBBEndIdx(I->second);
140}
141
143 if (!isStaleIndex(Idx))
144 return Idx;
145
146 // The block start is a boundary entry, so it bounds the walk.
147 SlotIndex BlockStart = getMBBStartIdx(getMBBFromIndex(Idx));
148 IndexList::iterator I = Idx.listEntry()->getIterator();
149 while (&*I != BlockStart.listEntry()) {
150 --I;
151 if (I->getInstr())
152 return SlotIndex(&*I, SlotIndex::Slot_Register);
153 }
154 return BlockStart;
155}
156
158 bool AllowBundled) {
159 assert((AllowBundled || !MI.isBundledWithPred()) &&
160 "Use removeSingleMachineInstrFromMaps() instead");
161 IndexListEntry *MIEntry = getMIEntry(MI);
162 if (!MIEntry)
163 return;
164
165 // FIXME: Eventually we want to actually delete these indexes.
166 MIEntry->setInstr(nullptr);
167 MI.SlotIndexHandle = 0;
168}
169
171 IndexListEntry *MIEntryPtr = getMIEntry(MI);
172 if (!MIEntryPtr)
173 return;
174
175 IndexListEntry &MIEntry = *MIEntryPtr;
176
177 // When removing the first instruction of a bundle update mapping to next
178 // instruction.
179 if (MI.isBundledWithSucc()) {
180 // Only the first instruction of a bundle should have an index assigned.
181 assert(!MI.isBundledWithPred() && "Should be first bundle instruction");
182
183 MachineBasicBlock::instr_iterator Next = std::next(MI.getIterator());
184 MachineInstr &NextMI = *Next;
185 MIEntry.setInstr(&NextMI);
186 NextMI.SlotIndexHandle = MI.SlotIndexHandle;
187 MI.SlotIndexHandle = 0;
188 return;
189 } else {
190 // FIXME: Eventually we want to actually delete these indexes.
191 MIEntry.setInstr(nullptr);
192 MI.SlotIndexHandle = 0;
193 }
194}
195
197 assert(&MBB != &MBB.getParent()->front() &&
198 "Can't remove the first block of a function.");
199
200 unsigned Num = MBB.getAnalysisNumber();
201 SlotIndex StartIdx = MBBRanges[Num].first;
202 SlotIndex EndIdx = MBBRanges[Num].second;
203
204 // Give MBB's slot range to its layout predecessor so blocks stay contiguous.
205 auto PrevMBB = std::prev(MBB.getIterator());
206 MBBRanges[PrevMBB->getAnalysisNumber()].second = EndIdx;
207
208 // Drop MBB's index -> MBB entry, which would dangle once MBB is erased.
209 auto It = getMBBLowerBound(StartIdx);
210 assert(It != MBBIndexEnd() && It->first == StartIdx && It->second == &MBB &&
211 "MBB not found in index -> MBB map");
212 idx2MBBMap.erase(It);
213
214 // Clear the block-start boundary entry. MBBRanges is never renumbered, so
215 // MBB's now-stale slot is simply left in place.
216 StartIdx.listEntry()->setInstr(nullptr);
217}
218
219// Renumber indexes locally after curItr was inserted, but failed to get a new
220// index.
221void SlotIndexes::renumberIndexes(IndexList::iterator curItr) {
222 // Number indexes with half the default spacing so we can catch up quickly.
223 const unsigned Space = SlotIndex::InstrDist/2;
224 static_assert((Space & 3) == 0, "InstrDist must be a multiple of 2*NUM");
225
226 IndexList::iterator startItr = std::prev(curItr);
227 unsigned index = startItr->getIndex();
228 unsigned BeginIndex = index;
229 do {
230 curItr->setIndex(index += Space);
231 ++curItr;
232 // If the next index is bigger, we have caught up.
233 } while (curItr != indexList.end() && curItr->getIndex() <= index);
234
235 LLVM_DEBUG(dbgs() << "\n*** Renumbered SlotIndexes " << startItr->getIndex()
236 << '-' << index << " ***\n");
237
238 // If we repack more than 20% of a function, add spacing in between the
239 // instructions so that future renumberings are able to catch up
240 // without also renumbering so much.
241 if (index - BeginIndex >
242 (getLastIndex().getIndex() - getZeroIndex().getIndex()) / 5)
243 packIndexes();
244
245 ++NumLocalRenum;
246}
247
248// Repair indexes after adding and removing instructions.
252 bool includeStart = (Begin == MBB->begin());
253 SlotIndex startIdx;
254 if (includeStart)
255 startIdx = getMBBStartIdx(MBB);
256 else
257 startIdx = getInstructionIndex(*--Begin);
258
259 SlotIndex endIdx;
260 if (End == MBB->end())
261 endIdx = getMBBEndIdx(MBB);
262 else
263 endIdx = getInstructionIndex(*End);
264
265 // FIXME: Conceptually, this code is implementing an iterator on MBB that
266 // optionally includes an additional position prior to MBB->begin(), indicated
267 // by the includeStart flag. This is done so that we can iterate MIs in a MBB
268 // in parallel with SlotIndexes, but there should be a better way to do this.
269 IndexList::iterator ListB = startIdx.listEntry()->getIterator();
270 IndexList::iterator ListI = endIdx.listEntry()->getIterator();
272 bool pastStart = false;
273 bool OldIndexesRemoved = false;
274 while (ListI != ListB || MBBI != Begin || (includeStart && !pastStart)) {
275 assert(ListI->getIndex() >= startIdx.getIndex() &&
276 (includeStart || !pastStart) &&
277 "Decremented past the beginning of region to repair.");
278
279 MachineInstr *SlotMI = ListI->getInstr();
280 MachineInstr *MI = (MBBI != MBB->end() && !pastStart) ? &*MBBI : nullptr;
281 bool MBBIAtBegin = MBBI == Begin && (!includeStart || pastStart);
282 bool MIIndexNotFound = MI && !hasIndex(*MI);
283 bool SlotMIRemoved = false;
284
285 if (SlotMI == MI && !MBBIAtBegin) {
286 --ListI;
287 if (MBBI != Begin)
288 --MBBI;
289 else
290 pastStart = true;
291 } else if (MIIndexNotFound || OldIndexesRemoved) {
292 if (MBBI != Begin)
293 --MBBI;
294 else
295 pastStart = true;
296 } else {
297 // We ran through all the indexes on the interval
298 // -> The only thing left is to go through all the
299 // remaining MBB instructions and update their indexes
300 if (ListI == ListB)
301 OldIndexesRemoved = true;
302 else
303 --ListI;
304 if (SlotMI) {
306 SlotMIRemoved = true;
307 }
308 }
309
310 MachineInstr *InstrToInsert = SlotMIRemoved ? SlotMI : MI;
311
312 // Insert instruction back into the maps after passing it/removing the index
313 if ((MIIndexNotFound || SlotMIRemoved) && InstrToInsert->getParent() &&
314 !InstrToInsert->isDebugOrPseudoInstr())
315 insertMachineInstrInMaps(*InstrToInsert);
316 }
317}
318
320 for (auto [Index, Entry] : enumerate(indexList))
321 Entry.setIndex(Index * SlotIndex::InstrDist);
322}
323
325 if (indexList.empty())
326 return 0;
327
329
330 // The first and last entries anchor getZeroIndex() and getLastIndex().
331 Keep.insert(&indexList.front());
332 Keep.insert(&indexList.back());
333
334 for (const auto &Range : MBBRanges) {
335 if (Range.first.isValid())
336 Keep.insert(Range.first.listEntry());
337 if (Range.second.isValid())
338 Keep.insert(Range.second.listEntry());
339 }
340
341 // Entries must be unlinked, not zero-width: that would break getNextSlot().
343 unsigned Index = 0;
344 for (auto It = indexList.begin(), E = indexList.end(); It != E;) {
345 IndexListEntry &Entry = *It++;
346 if (Entry.getInstr() || Keep.contains(&Entry)) {
347 Entry.setIndex(Index);
348 Index += SlotIndex::InstrDist;
349 continue;
350 }
351 // Take the surviving entry behind, so a stale index stays in program order.
352 assert(Index != 0 && "First entry is always kept");
353 Entry.setIndex(Index - SlotIndex::InstrDist);
354 Erased.push_back(&Entry);
355 indexList.remove(Entry);
356 }
357
358 for (IndexListEntry *Entry : Erased)
359 Entry->setErased();
360
361 NumDeadEntriesErased += Erased.size();
362 return Erased.size();
363}
364
366 for (const IndexListEntry &ILE : indexList) {
367 OS << ILE.getIndex() << ' ';
368
369 if (ILE.getInstr())
370 OS << *ILE.getInstr();
371 else
372 OS << '\n';
373 }
374
375 for (const MachineBasicBlock &MBB : *mf)
376 OS << printMBBReference(MBB) << "\t[" << getMBBStartIdx(&MBB) << ';'
377 << getMBBEndIdx(&MBB) << ")\n";
378}
379
380#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
382#endif
383
384// Print a SlotIndex to a raw_ostream.
386 if (isValid())
387 os << listEntry()->getIndex() << "Berd"[getSlot()];
388 else
389 os << "invalid";
390}
391
392#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
393// Dump a SlotIndex to stderr.
395 print(dbgs());
396 dbgs() << "\n";
397}
398#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
#define DEBUG_TYPE
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
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
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
This class represents an entry in the slot index list held in the SlotIndexes pass.
Definition SlotIndexes.h:47
void setInstr(MachineInstr *mi)
Definition SlotIndexes.h:59
int getAnalysisNumber() const
For analyses, blocks have a more stable number.
Instructions::iterator instr_iterator
MachineInstrBundleIterator< MachineInstr > iterator
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
unsigned getMaxAnalysisBlockNumber() const
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
bool isDebugOrPseudoInstr() const
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
@ InstrDist
The default distance between instructions as returned by distance().
bool isValid() const
Returns true if this is a valid index.
LLVM_ABI void dump() const
Dump this index to stderr.
LLVM_ABI void print(raw_ostream &os) const
Print this index to the given raw_ostream.
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
void getAnalysisUsage(AnalysisUsage &au) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
LLVM_ABI bool isBlockBoundaryIndex(SlotIndex Idx) const
Returns true if Idx refers to an entry created to mark a basic block boundary.
SlotIndex getLastIndex()
Returns the base index of the last slot in this analysis.
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
LLVM_ABI void removeMachineInstrFromMaps(MachineInstr &MI, bool AllowBundled=false)
Removes machine instruction (bundle) MI from the mapping.
LLVM_ABI SlotIndex canonicalizeIndex(SlotIndex Idx) const
Returns the register slot of the closest instruction preceding a stale Idx, or the start index of its...
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
Returns the basic block which the given index falls in.
LLVM_ABI void dump() const
Dump the indexes.
LLVM_ABI void repairIndexesInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End)
Repair indexes after adding and removing instructions.
LLVM_ABI unsigned compactIndexes()
Erase index list entries left behind by deleted instructions, then renumber.
MBBIndexIterator getMBBLowerBound(MBBIndexIterator Start, SlotIndex Idx) const
Get an iterator pointing to the first IdxMBBPair with SlotIndex greater than or equal to Idx.
LLVM_ABI void removeSingleMachineInstrFromMaps(MachineInstr &MI)
Removes a single machine instruction MI from the mapping.
MBBIndexIterator MBBIndexEnd() const
Return an iterator for the end of the idx2MBBMap.
SmallVectorImpl< IdxMBBPair >::const_iterator MBBIndexIterator
Iterator over the idx2MBBMap (sorted pairs of slot index of basic block begin and basic block)
MBBIndexIterator getMBBUpperBound(SlotIndex Idx) const
Get an iterator pointing to the first IdxMBBPair with SlotIndex greater than Idx.
SlotIndex getInstructionIndex(const MachineInstr &MI, bool IgnoreBundle=false) const
Returns the base index for the given instruction.
LLVM_ABI ~SlotIndexes()
bool isStaleIndex(SlotIndex Idx) const
Returns true if Idx refers to an instruction that has been erased.
LLVM_ABI void packIndexes()
Renumber all indexes using the default instruction distance.
LLVM_ABI void removeMBBFromMaps(MachineBasicBlock &MBB)
Inverse of insertMBBInMaps: merge MBB's slot range into its layout predecessor and drop it from the m...
bool hasIndex(const MachineInstr &instr) const
Returns true if the given machine instr is mapped to an index, otherwise returns false.
LLVM_ABI void print(raw_ostream &OS) const
SlotIndex getZeroIndex()
Returns the zero index for this analysis.
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Returns the index past the last valid index in the given basic block.
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Returns the first index in the given basic block.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction for the given index, or null if the given index has no instruction associated...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
void clear()
Clear the list; never deletes.
bool empty() const
Check if the list is empty in constant time.
ilist_select_iterator_type< OptionsT, false, false > iterator
void push_back(reference Node)
Insert a node at the back; never copies.
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
std::pair< SlotIndex, MachineBasicBlock * > IdxMBBPair
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
@ Keep
No function return thunk.
Definition CodeGen.h:370
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29