LLVM 19.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 "slotindexes"
20
21char SlotIndexes::ID = 0;
22
25}
26
28 // The indexList's nodes are all allocated in the BumpPtrAllocator.
29 indexList.clearAndLeakNodesUnsafely();
30}
31
33 "Slot index numbering", false, false)
34
35STATISTIC(NumLocalRenum, "Number of local renumberings");
36
37void SlotIndexes::getAnalysisUsage(AnalysisUsage &au) const {
38 au.setPreservesAll();
40}
41
43 mi2iMap.clear();
44 MBBRanges.clear();
45 idx2MBBMap.clear();
46 indexList.clear();
47 ileAllocator.Reset();
48}
49
51
52 // Compute numbering as follows:
53 // Grab an iterator to the start of the index list.
54 // Iterate over all MBBs, and within each MBB all MIs, keeping the MI
55 // iterator in lock-step (though skipping it over indexes which have
56 // null pointers in the instruction field).
57 // At each iteration assert that the instruction pointed to in the index
58 // is the same one pointed to by the MI iterator. This
59
60 // FIXME: This can be simplified. The mi2iMap_, Idx2MBBMap, etc. should
61 // only need to be set up once after the first numbering is computed.
62
63 mf = &fn;
64
65 // Check that the list contains only the sentinel.
66 assert(indexList.empty() && "Index list non-empty at initial numbering?");
67 assert(idx2MBBMap.empty() &&
68 "Index -> MBB mapping non-empty at initial numbering?");
69 assert(MBBRanges.empty() &&
70 "MBB -> Index mapping non-empty at initial numbering?");
71 assert(mi2iMap.empty() &&
72 "MachineInstr -> Index mapping non-empty at initial numbering?");
73
74 unsigned index = 0;
75 MBBRanges.resize(mf->getNumBlockIDs());
76 idx2MBBMap.reserve(mf->size());
77
78 indexList.push_back(createEntry(nullptr, index));
79
80 // Iterate over the function.
81 for (MachineBasicBlock &MBB : *mf) {
82 // Insert an index for the MBB start.
83 SlotIndex blockStartIndex(&indexList.back(), SlotIndex::Slot_Block);
84
85 for (MachineInstr &MI : MBB) {
86 if (MI.isDebugOrPseudoInstr())
87 continue;
88
89 // Insert a store index for the instr.
90 indexList.push_back(createEntry(&MI, index += SlotIndex::InstrDist));
91
92 // Save this base index in the maps.
93 mi2iMap.insert(std::make_pair(
94 &MI, SlotIndex(&indexList.back(), SlotIndex::Slot_Block)));
95 }
96
97 // We insert one blank instructions between basic blocks.
98 indexList.push_back(createEntry(nullptr, index += SlotIndex::InstrDist));
99
100 MBBRanges[MBB.getNumber()].first = blockStartIndex;
101 MBBRanges[MBB.getNumber()].second = SlotIndex(&indexList.back(),
102 SlotIndex::Slot_Block);
103 idx2MBBMap.push_back(IdxMBBPair(blockStartIndex, &MBB));
104 }
105
106 // Sort the Idx2MBBMap
107 llvm::sort(idx2MBBMap, less_first());
108
109 LLVM_DEBUG(mf->print(dbgs(), this));
110
111 // And we're done!
112 return false;
113}
114
116 bool AllowBundled) {
117 assert((AllowBundled || !MI.isBundledWithPred()) &&
118 "Use removeSingleMachineInstrFromMaps() instead");
119 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(&MI);
120 if (mi2iItr == mi2iMap.end())
121 return;
122
123 SlotIndex MIIndex = mi2iItr->second;
124 IndexListEntry &MIEntry = *MIIndex.listEntry();
125 assert(MIEntry.getInstr() == &MI && "Instruction indexes broken.");
126 mi2iMap.erase(mi2iItr);
127 // FIXME: Eventually we want to actually delete these indexes.
128 MIEntry.setInstr(nullptr);
129}
130
132 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(&MI);
133 if (mi2iItr == mi2iMap.end())
134 return;
135
136 SlotIndex MIIndex = mi2iItr->second;
137 IndexListEntry &MIEntry = *MIIndex.listEntry();
138 assert(MIEntry.getInstr() == &MI && "Instruction indexes broken.");
139 mi2iMap.erase(mi2iItr);
140
141 // When removing the first instruction of a bundle update mapping to next
142 // instruction.
143 if (MI.isBundledWithSucc()) {
144 // Only the first instruction of a bundle should have an index assigned.
145 assert(!MI.isBundledWithPred() && "Should be first bundle instruction");
146
147 MachineBasicBlock::instr_iterator Next = std::next(MI.getIterator());
148 MachineInstr &NextMI = *Next;
149 MIEntry.setInstr(&NextMI);
150 mi2iMap.insert(std::make_pair(&NextMI, MIIndex));
151 return;
152 } else {
153 // FIXME: Eventually we want to actually delete these indexes.
154 MIEntry.setInstr(nullptr);
155 }
156}
157
158// Renumber indexes locally after curItr was inserted, but failed to get a new
159// index.
160void SlotIndexes::renumberIndexes(IndexList::iterator curItr) {
161 // Number indexes with half the default spacing so we can catch up quickly.
162 const unsigned Space = SlotIndex::InstrDist/2;
163 static_assert((Space & 3) == 0, "InstrDist must be a multiple of 2*NUM");
164
165 IndexList::iterator startItr = std::prev(curItr);
166 unsigned index = startItr->getIndex();
167 do {
168 curItr->setIndex(index += Space);
169 ++curItr;
170 // If the next index is bigger, we have caught up.
171 } while (curItr != indexList.end() && curItr->getIndex() <= index);
172
173 LLVM_DEBUG(dbgs() << "\n*** Renumbered SlotIndexes " << startItr->getIndex()
174 << '-' << index << " ***\n");
175 ++NumLocalRenum;
176}
177
178// Repair indexes after adding and removing instructions.
182 bool includeStart = (Begin == MBB->begin());
183 SlotIndex startIdx;
184 if (includeStart)
185 startIdx = getMBBStartIdx(MBB);
186 else
187 startIdx = getInstructionIndex(*--Begin);
188
189 SlotIndex endIdx;
190 if (End == MBB->end())
191 endIdx = getMBBEndIdx(MBB);
192 else
193 endIdx = getInstructionIndex(*End);
194
195 // FIXME: Conceptually, this code is implementing an iterator on MBB that
196 // optionally includes an additional position prior to MBB->begin(), indicated
197 // by the includeStart flag. This is done so that we can iterate MIs in a MBB
198 // in parallel with SlotIndexes, but there should be a better way to do this.
199 IndexList::iterator ListB = startIdx.listEntry()->getIterator();
200 IndexList::iterator ListI = endIdx.listEntry()->getIterator();
202 bool pastStart = false;
203 while (ListI != ListB || MBBI != Begin || (includeStart && !pastStart)) {
204 assert(ListI->getIndex() >= startIdx.getIndex() &&
205 (includeStart || !pastStart) &&
206 "Decremented past the beginning of region to repair.");
207
208 MachineInstr *SlotMI = ListI->getInstr();
209 MachineInstr *MI = (MBBI != MBB->end() && !pastStart) ? &*MBBI : nullptr;
210 bool MBBIAtBegin = MBBI == Begin && (!includeStart || pastStart);
211
212 if (SlotMI == MI && !MBBIAtBegin) {
213 --ListI;
214 if (MBBI != Begin)
215 --MBBI;
216 else
217 pastStart = true;
218 } else if (MI && !mi2iMap.contains(MI)) {
219 if (MBBI != Begin)
220 --MBBI;
221 else
222 pastStart = true;
223 } else {
224 --ListI;
225 if (SlotMI)
227 }
228 }
229
230 // In theory this could be combined with the previous loop, but it is tricky
231 // to update the IndexList while we are iterating it.
232 for (MachineBasicBlock::iterator I = End; I != Begin;) {
233 --I;
234 MachineInstr &MI = *I;
235 if (!MI.isDebugOrPseudoInstr() && !mi2iMap.contains(&MI))
237 }
238}
239
241 for (auto [Index, Entry] : enumerate(indexList))
242 Entry.setIndex(Index * SlotIndex::InstrDist);
243}
244
245#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
247 for (const IndexListEntry &ILE : indexList) {
248 dbgs() << ILE.getIndex() << " ";
249
250 if (ILE.getInstr()) {
251 dbgs() << *ILE.getInstr();
252 } else {
253 dbgs() << "\n";
254 }
255 }
256
257 for (unsigned i = 0, e = MBBRanges.size(); i != e; ++i)
258 dbgs() << "%bb." << i << "\t[" << MBBRanges[i].first << ';'
259 << MBBRanges[i].second << ")\n";
260}
261#endif
262
263// Print a SlotIndex to a raw_ostream.
265 if (isValid())
266 os << listEntry()->getIndex() << "Berd"[getSlot()];
267 else
268 os << "invalid";
269}
270
271#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
272// Dump a SlotIndex to stderr.
274 print(dbgs());
275 dbgs() << "\n";
276}
277#endif
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:537
#define LLVM_DEBUG(X)
Definition: Debug.h:101
bool End
Definition: ELF_riscv.cpp:480
#define DEBUG_TYPE
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Number of renumberings
Definition: SlotIndexes.cpp:35
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:167
Represent the analysis usage information of a pass.
void Reset()
Deallocate all but the current slab and reset the current pointer to the beginning of it,...
Definition: Allocator.h:123
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
bool erase(const KeyT &Val)
Definition: DenseMap.h:345
bool empty() const
Definition: DenseMap.h:98
iterator end()
Definition: DenseMap.h:84
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:145
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:220
This class represents an entry in the slot index list held in the SlotIndexes pass.
Definition: SlotIndexes.h:45
void setInstr(MachineInstr *mi)
Definition: SlotIndexes.h:53
MachineInstr * getInstr() const
Definition: SlotIndexes.h:52
unsigned getIndex() const
Definition: SlotIndexes.h:57
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
Instructions::iterator instr_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.
unsigned size() const
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
Representation of each machine instruction.
Definition: MachineInstr.h:69
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:68
bool isValid() const
Returns true if this is a valid index.
Definition: SlotIndexes.h:133
@ InstrDist
The default distance between instructions as returned by distance().
Definition: SlotIndexes.h:115
void dump() const
Dump this index to stderr.
void print(raw_ostream &os) const
Print this index to the given raw_ostream.
SlotIndexes pass.
Definition: SlotIndexes.h:300
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
Definition: SlotIndexes.h:523
void removeMachineInstrFromMaps(MachineInstr &MI, bool AllowBundled=false)
Removes machine instruction (bundle) MI from the mapping.
void dump() const
Dump the indexes.
void repairIndexesInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End)
Repair indexes after adding and removing instructions.
bool runOnMachineFunction(MachineFunction &fn) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
Definition: SlotIndexes.cpp:50
SlotIndex getMBBEndIdx(unsigned Num) const
Returns the last index in the given basic block number.
Definition: SlotIndexes.h:462
void removeSingleMachineInstrFromMaps(MachineInstr &MI)
Removes a single machine instruction MI from the mapping.
static char ID
Definition: SlotIndexes.h:334
SlotIndex getInstructionIndex(const MachineInstr &MI, bool IgnoreBundle=false) const
Returns the base index for the given instruction.
Definition: SlotIndexes.h:371
SlotIndex getMBBStartIdx(unsigned Num) const
Returns the first index in the given basic block number.
Definition: SlotIndexes.h:452
~SlotIndexes() override
Definition: SlotIndexes.cpp:27
void packIndexes()
Renumber all indexes using the default instruction distance.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition: SlotIndexes.cpp:42
bool empty() const
Definition: SmallVector.h:94
void reserve(size_type N)
Definition: SmallVector.h:676
void push_back(const T &Elt)
Definition: SmallVector.h:426
self_iterator getIterator()
Definition: ilist_node.h:109
void push_back(pointer val)
Definition: ilist.h:250
void clearAndLeakNodesUnsafely()
Remove all nodes from the list like clear(), but do not call removeNodeFromList() or deleteNode().
Definition: ilist.h:217
void clear()
Definition: ilist.h:246
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are are tuples (A,...
Definition: STLExtras.h:2400
std::pair< SlotIndex, MachineBasicBlock * > IdxMBBPair
Definition: SlotIndexes.h:295
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void initializeSlotIndexesPass(PassRegistry &)
Function object to check whether the first component of a container supported by std::get (like std::...
Definition: STLExtras.h:1450