1 //===- llvm/CodeGen/SlotIndexes.h - Slot indexes representation -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements SlotIndex and related classes. The purpuse of SlotIndex
11 // is to describe a position at which a register can become live, or cease to
14 // SlotIndex is mostly a proxy for entries of the SlotIndexList, a class which
15 // is held is LiveIntervals and provides the real numbering. This allows
16 // LiveIntervals to perform largely transparent renumbering.
17 //===----------------------------------------------------------------------===//
19 #ifndef LLVM_CODEGEN_SLOTINDEXES_H
20 #define LLVM_CODEGEN_SLOTINDEXES_H
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/ADT/PointerIntPair.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/Support/Allocator.h"
32 /// This class represents an entry in the slot index list held in the
33 /// SlotIndexes pass. It should not be used directly. See the
34 /// SlotIndex & SlotIndexes classes for the public interface to this
36 class IndexListEntry {
37 IndexListEntry *next, *prev;
43 IndexListEntry(MachineInstr *mi, unsigned index) : mi(mi), index(index) {}
45 MachineInstr* getInstr() const { return mi; }
46 void setInstr(MachineInstr *mi) {
50 unsigned getIndex() const { return index; }
51 void setIndex(unsigned index) {
55 IndexListEntry* getNext() { return next; }
56 const IndexListEntry* getNext() const { return next; }
57 void setNext(IndexListEntry *next) {
61 IndexListEntry* getPrev() { return prev; }
62 const IndexListEntry* getPrev() const { return prev; }
63 void setPrev(IndexListEntry *prev) {
68 // Specialize PointerLikeTypeTraits for IndexListEntry.
70 class PointerLikeTypeTraits<IndexListEntry*> {
72 static inline void* getAsVoidPointer(IndexListEntry *p) {
75 static inline IndexListEntry* getFromVoidPointer(void *p) {
76 return static_cast<IndexListEntry*>(p);
78 enum { NumLowBitsAvailable = 3 };
81 /// SlotIndex - An opaque wrapper around machine indexes.
83 friend class SlotIndexes;
84 friend struct DenseMapInfo<SlotIndex>;
86 enum Slot { LOAD, USE, DEF, STORE, NUM };
88 PointerIntPair<IndexListEntry*, 2, unsigned> lie;
90 SlotIndex(IndexListEntry *entry, unsigned slot)
93 IndexListEntry& entry() const {
94 assert(isValid() && "Attempt to compare reserved index.");
95 return *lie.getPointer();
98 int getIndex() const {
99 return entry().getIndex() | getSlot();
102 /// Returns the slot for this SlotIndex.
103 Slot getSlot() const {
104 return static_cast<Slot>(lie.getInt());
107 static inline unsigned getHashValue(const SlotIndex &v) {
108 void *ptrVal = v.lie.getOpaqueValue();
109 return (unsigned((intptr_t)ptrVal)) ^ (unsigned((intptr_t)ptrVal) >> 9);
114 /// The default distance between instructions as returned by distance().
115 /// This may vary as instructions are inserted and removed.
119 static inline SlotIndex getEmptyKey() {
120 return SlotIndex(0, 1);
123 static inline SlotIndex getTombstoneKey() {
124 return SlotIndex(0, 2);
127 /// Construct an invalid index.
128 SlotIndex() : lie(0, 0) {}
130 // Construct a new slot index from the given one, and set the slot.
131 SlotIndex(const SlotIndex &li, Slot s)
132 : lie(&li.entry(), unsigned(s)) {
133 assert(lie.getPointer() != 0 &&
134 "Attempt to construct index with 0 pointer.");
137 /// Returns true if this is a valid index. Invalid indicies do
138 /// not point into an index table, and cannot be compared.
139 bool isValid() const {
140 return lie.getPointer();
143 /// Print this index to the given raw_ostream.
144 void print(raw_ostream &os) const;
146 /// Dump this index to stderr.
149 /// Compare two SlotIndex objects for equality.
150 bool operator==(SlotIndex other) const {
151 return lie == other.lie;
153 /// Compare two SlotIndex objects for inequality.
154 bool operator!=(SlotIndex other) const {
155 return lie != other.lie;
158 /// Compare two SlotIndex objects. Return true if the first index
159 /// is strictly lower than the second.
160 bool operator<(SlotIndex other) const {
161 return getIndex() < other.getIndex();
163 /// Compare two SlotIndex objects. Return true if the first index
164 /// is lower than, or equal to, the second.
165 bool operator<=(SlotIndex other) const {
166 return getIndex() <= other.getIndex();
169 /// Compare two SlotIndex objects. Return true if the first index
170 /// is greater than the second.
171 bool operator>(SlotIndex other) const {
172 return getIndex() > other.getIndex();
175 /// Compare two SlotIndex objects. Return true if the first index
176 /// is greater than, or equal to, the second.
177 bool operator>=(SlotIndex other) const {
178 return getIndex() >= other.getIndex();
181 /// Return the distance from this index to the given one.
182 int distance(SlotIndex other) const {
183 return other.getIndex() - getIndex();
186 /// isLoad - Return true if this is a LOAD slot.
187 bool isLoad() const {
188 return getSlot() == LOAD;
191 /// isDef - Return true if this is a DEF slot.
193 return getSlot() == DEF;
196 /// isUse - Return true if this is a USE slot.
198 return getSlot() == USE;
201 /// isStore - Return true if this is a STORE slot.
202 bool isStore() const {
203 return getSlot() == STORE;
206 /// Returns the base index for associated with this index. The base index
207 /// is the one associated with the LOAD slot for the instruction pointed to
209 SlotIndex getBaseIndex() const {
210 return getLoadIndex();
213 /// Returns the boundary index for associated with this index. The boundary
214 /// index is the one associated with the LOAD slot for the instruction
215 /// pointed to by this index.
216 SlotIndex getBoundaryIndex() const {
217 return getStoreIndex();
220 /// Returns the index of the LOAD slot for the instruction pointed to by
222 SlotIndex getLoadIndex() const {
223 return SlotIndex(&entry(), SlotIndex::LOAD);
226 /// Returns the index of the USE slot for the instruction pointed to by
228 SlotIndex getUseIndex() const {
229 return SlotIndex(&entry(), SlotIndex::USE);
232 /// Returns the index of the DEF slot for the instruction pointed to by
234 SlotIndex getDefIndex() const {
235 return SlotIndex(&entry(), SlotIndex::DEF);
238 /// Returns the index of the STORE slot for the instruction pointed to by
240 SlotIndex getStoreIndex() const {
241 return SlotIndex(&entry(), SlotIndex::STORE);
244 /// Returns the next slot in the index list. This could be either the
245 /// next slot for the instruction pointed to by this index or, if this
246 /// index is a STORE, the first slot for the next instruction.
247 /// WARNING: This method is considerably more expensive than the methods
248 /// that return specific slots (getUseIndex(), etc). If you can - please
249 /// use one of those methods.
250 SlotIndex getNextSlot() const {
252 if (s == SlotIndex::STORE) {
253 return SlotIndex(entry().getNext(), SlotIndex::LOAD);
255 return SlotIndex(&entry(), s + 1);
258 /// Returns the next index. This is the index corresponding to the this
259 /// index's slot, but for the next instruction.
260 SlotIndex getNextIndex() const {
261 return SlotIndex(entry().getNext(), getSlot());
264 /// Returns the previous slot in the index list. This could be either the
265 /// previous slot for the instruction pointed to by this index or, if this
266 /// index is a LOAD, the last slot for the previous instruction.
267 /// WARNING: This method is considerably more expensive than the methods
268 /// that return specific slots (getUseIndex(), etc). If you can - please
269 /// use one of those methods.
270 SlotIndex getPrevSlot() const {
272 if (s == SlotIndex::LOAD) {
273 return SlotIndex(entry().getPrev(), SlotIndex::STORE);
275 return SlotIndex(&entry(), s - 1);
278 /// Returns the previous index. This is the index corresponding to this
279 /// index's slot, but for the previous instruction.
280 SlotIndex getPrevIndex() const {
281 return SlotIndex(entry().getPrev(), getSlot());
286 /// DenseMapInfo specialization for SlotIndex.
288 struct DenseMapInfo<SlotIndex> {
289 static inline SlotIndex getEmptyKey() {
290 return SlotIndex::getEmptyKey();
292 static inline SlotIndex getTombstoneKey() {
293 return SlotIndex::getTombstoneKey();
295 static inline unsigned getHashValue(const SlotIndex &v) {
296 return SlotIndex::getHashValue(v);
298 static inline bool isEqual(const SlotIndex &LHS, const SlotIndex &RHS) {
303 template <> struct isPodLike<SlotIndex> { static const bool value = true; };
306 inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
311 typedef std::pair<SlotIndex, MachineBasicBlock*> IdxMBBPair;
313 inline bool operator<(SlotIndex V, const IdxMBBPair &IM) {
317 inline bool operator<(const IdxMBBPair &IM, SlotIndex V) {
321 struct Idx2MBBCompare {
322 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
323 return LHS.first < RHS.first;
327 /// SlotIndexes pass.
329 /// This pass assigns indexes to each instruction.
330 class SlotIndexes : public MachineFunctionPass {
334 IndexListEntry *indexListHead;
335 unsigned functionSize;
337 typedef DenseMap<const MachineInstr*, SlotIndex> Mi2IndexMap;
340 /// MBB2IdxMap - The indexes of the first and last instructions in the
341 /// specified basic block.
342 typedef DenseMap<const MachineBasicBlock*,
343 std::pair<SlotIndex, SlotIndex> > MBB2IdxMap;
344 MBB2IdxMap mbb2IdxMap;
346 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
348 std::vector<IdxMBBPair> idx2MBBMap;
350 // IndexListEntry allocator.
351 BumpPtrAllocator ileAllocator;
353 IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
354 IndexListEntry *entry =
355 static_cast<IndexListEntry*>(
356 ileAllocator.Allocate(sizeof(IndexListEntry),
357 alignOf<IndexListEntry>()));
359 new (entry) IndexListEntry(mi, index);
365 assert(indexListHead == 0 && "Zero entry non-null at initialisation.");
366 indexListHead = createEntry(0, ~0U);
367 indexListHead->setNext(0);
368 indexListHead->setPrev(indexListHead);
373 ileAllocator.Reset();
376 IndexListEntry* getTail() {
377 assert(indexListHead != 0 && "Call to getTail on uninitialized list.");
378 return indexListHead->getPrev();
381 const IndexListEntry* getTail() const {
382 assert(indexListHead != 0 && "Call to getTail on uninitialized list.");
383 return indexListHead->getPrev();
386 // Returns true if the index list is empty.
387 bool empty() const { return (indexListHead == getTail()); }
389 IndexListEntry* front() {
390 assert(!empty() && "front() called on empty index list.");
391 return indexListHead;
394 const IndexListEntry* front() const {
395 assert(!empty() && "front() called on empty index list.");
396 return indexListHead;
399 IndexListEntry* back() {
400 assert(!empty() && "back() called on empty index list.");
401 return getTail()->getPrev();
404 const IndexListEntry* back() const {
405 assert(!empty() && "back() called on empty index list.");
406 return getTail()->getPrev();
409 /// Insert a new entry before itr.
410 void insert(IndexListEntry *itr, IndexListEntry *val) {
411 assert(itr != 0 && "itr should not be null.");
412 IndexListEntry *prev = itr->getPrev();
416 if (itr != indexListHead) {
425 /// Push a new entry on to the end of the list.
426 void push_back(IndexListEntry *val) {
427 insert(getTail(), val);
433 SlotIndexes() : MachineFunctionPass(ID), indexListHead(0) {
434 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
437 virtual void getAnalysisUsage(AnalysisUsage &au) const;
438 virtual void releaseMemory();
440 virtual bool runOnMachineFunction(MachineFunction &fn);
442 /// Dump the indexes.
445 /// Renumber the index list, providing space for new instructions.
446 void renumberIndexes();
448 /// Returns the zero index for this analysis.
449 SlotIndex getZeroIndex() {
450 assert(front()->getIndex() == 0 && "First index is not 0?");
451 return SlotIndex(front(), 0);
454 /// Returns the base index of the last slot in this analysis.
455 SlotIndex getLastIndex() {
456 return SlotIndex(back(), 0);
459 /// Returns the invalid index marker for this analysis.
460 SlotIndex getInvalidIndex() {
461 return getZeroIndex();
464 /// Returns the distance between the highest and lowest indexes allocated
466 unsigned getIndexesLength() const {
467 assert(front()->getIndex() == 0 &&
468 "Initial index isn't zero?");
470 return back()->getIndex();
473 /// Returns the number of instructions in the function.
474 unsigned getFunctionSize() const {
478 /// Returns true if the given machine instr is mapped to an index,
479 /// otherwise returns false.
480 bool hasIndex(const MachineInstr *instr) const {
481 return (mi2iMap.find(instr) != mi2iMap.end());
484 /// Returns the base index for the given instruction.
485 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
486 Mi2IndexMap::const_iterator itr = mi2iMap.find(instr);
487 assert(itr != mi2iMap.end() && "Instruction not found in maps.");
491 /// Returns the instruction for the given index, or null if the given
492 /// index has no instruction associated with it.
493 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
494 return index.isValid() ? index.entry().getInstr() : 0;
497 /// Returns the next non-null index.
498 SlotIndex getNextNonNullIndex(SlotIndex index) {
499 SlotIndex nextNonNull = index.getNextIndex();
501 while (&nextNonNull.entry() != getTail() &&
502 getInstructionFromIndex(nextNonNull) == 0) {
503 nextNonNull = nextNonNull.getNextIndex();
509 /// Return the (start,end) range of the given basic block.
510 const std::pair<SlotIndex, SlotIndex> &
511 getMBBRange(const MachineBasicBlock *mbb) const {
512 MBB2IdxMap::const_iterator itr = mbb2IdxMap.find(mbb);
513 assert(itr != mbb2IdxMap.end() && "MBB not found in maps.");
517 /// Returns the first index in the given basic block.
518 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
519 return getMBBRange(mbb).first;
522 /// Returns the last index in the given basic block.
523 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
524 return getMBBRange(mbb).second;
527 /// Returns the basic block which the given index falls in.
528 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
529 std::vector<IdxMBBPair>::const_iterator I =
530 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), index);
531 // Take the pair containing the index
532 std::vector<IdxMBBPair>::const_iterator J =
533 ((I != idx2MBBMap.end() && I->first > index) ||
534 (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
536 assert(J != idx2MBBMap.end() && J->first <= index &&
537 index < getMBBEndIdx(J->second) &&
538 "index does not correspond to an MBB");
542 bool findLiveInMBBs(SlotIndex start, SlotIndex end,
543 SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
544 std::vector<IdxMBBPair>::const_iterator itr =
545 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
548 while (itr != idx2MBBMap.end()) {
549 if (itr->first >= end)
551 mbbs.push_back(itr->second);
558 /// Returns the MBB covering the given range, or null if the range covers
559 /// more than one basic block.
560 MachineBasicBlock* getMBBCoveringRange(SlotIndex start, SlotIndex end) const {
562 assert(start < end && "Backwards ranges not allowed.");
564 std::vector<IdxMBBPair>::const_iterator itr =
565 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
567 if (itr == idx2MBBMap.end()) {
572 // Check that we don't cross the boundary into this block.
573 if (itr->first < end)
578 if (itr->first <= start)
584 /// Insert the given machine instruction into the mapping. Returns the
586 SlotIndex insertMachineInstrInMaps(MachineInstr *mi) {
587 assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
588 // Numbering DBG_VALUE instructions could cause code generation to be
589 // affected by debug information.
590 assert(!mi->isDebugValue() && "Cannot number DBG_VALUE instructions.");
592 MachineBasicBlock *mbb = mi->getParent();
594 assert(mbb != 0 && "Instr must be added to function.");
596 MBB2IdxMap::iterator mbbRangeItr = mbb2IdxMap.find(mbb);
598 assert(mbbRangeItr != mbb2IdxMap.end() &&
599 "Instruction's parent MBB has not been added to SlotIndexes.");
601 MachineBasicBlock::iterator miItr(mi);
602 bool needRenumber = false;
603 IndexListEntry *newEntry;
604 // Get previous index, considering that not all instructions are indexed.
605 IndexListEntry *prevEntry;
607 // If mi is at the mbb beginning, get the prev index from the mbb.
608 if (miItr == mbb->begin()) {
609 prevEntry = &mbbRangeItr->second.first.entry();
612 // Otherwise rewind until we find a mapped instruction.
613 Mi2IndexMap::const_iterator itr = mi2iMap.find(--miItr);
614 if (itr != mi2iMap.end()) {
615 prevEntry = &itr->second.entry();
620 // Get next entry from previous entry.
621 IndexListEntry *nextEntry = prevEntry->getNext();
623 // Get a number for the new instr, or 0 if there's no room currently.
624 // In the latter case we'll force a renumber later.
625 unsigned dist = nextEntry->getIndex() - prevEntry->getIndex();
626 unsigned newNumber = dist > SlotIndex::NUM ?
627 prevEntry->getIndex() + ((dist >> 1) & ~3U) : 0;
629 if (newNumber == 0) {
633 // Insert a new list entry for mi.
634 newEntry = createEntry(mi, newNumber);
635 insert(nextEntry, newEntry);
637 SlotIndex newIndex(newEntry, SlotIndex::LOAD);
638 mi2iMap.insert(std::make_pair(mi, newIndex));
640 if (miItr == mbb->end()) {
641 // If this is the last instr in the MBB then we need to fix up the bb
643 mbbRangeItr->second.second = SlotIndex(newEntry, SlotIndex::STORE);
646 // Renumber if we need to.
653 /// Remove the given machine instruction from the mapping.
654 void removeMachineInstrFromMaps(MachineInstr *mi) {
655 // remove index -> MachineInstr and
656 // MachineInstr -> index mappings
657 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
658 if (mi2iItr != mi2iMap.end()) {
659 IndexListEntry *miEntry(&mi2iItr->second.entry());
660 assert(miEntry->getInstr() == mi && "Instruction indexes broken.");
661 // FIXME: Eventually we want to actually delete these indexes.
662 miEntry->setInstr(0);
663 mi2iMap.erase(mi2iItr);
667 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
668 /// maps used by register allocator.
669 void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI) {
670 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
671 if (mi2iItr == mi2iMap.end())
673 SlotIndex replaceBaseIndex = mi2iItr->second;
674 IndexListEntry *miEntry(&replaceBaseIndex.entry());
675 assert(miEntry->getInstr() == mi &&
676 "Mismatched instruction in index tables.");
677 miEntry->setInstr(newMI);
678 mi2iMap.erase(mi2iItr);
679 mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
682 /// Add the given MachineBasicBlock into the maps.
683 void insertMBBInMaps(MachineBasicBlock *mbb) {
684 MachineFunction::iterator nextMBB =
685 llvm::next(MachineFunction::iterator(mbb));
686 IndexListEntry *startEntry = createEntry(0, 0);
687 IndexListEntry *stopEntry = createEntry(0, 0);
688 IndexListEntry *nextEntry = 0;
690 if (nextMBB == mbb->getParent()->end()) {
691 nextEntry = getTail();
693 nextEntry = &getMBBStartIdx(nextMBB).entry();
696 insert(nextEntry, startEntry);
697 insert(nextEntry, stopEntry);
699 SlotIndex startIdx(startEntry, SlotIndex::LOAD);
700 SlotIndex endIdx(nextEntry, SlotIndex::LOAD);
703 std::make_pair(mbb, std::make_pair(startIdx, endIdx)));
705 idx2MBBMap.push_back(IdxMBBPair(startIdx, mbb));
707 if (MachineFunction::iterator(mbb) != mbb->getParent()->begin()) {
708 // Have to update the end index of the previous block.
709 MachineBasicBlock *priorMBB =
710 llvm::prior(MachineFunction::iterator(mbb));
711 mbb2IdxMap[priorMBB].second = startIdx;
715 std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());
722 // Specialize IntervalMapInfo for half-open slot index intervals.
723 template <typename> struct IntervalMapInfo;
724 template <> struct IntervalMapInfo<SlotIndex> {
725 static inline bool startLess(const SlotIndex &x, const SlotIndex &a) {
728 static inline bool stopLess(const SlotIndex &b, const SlotIndex &x) {
731 static inline bool adjacent(const SlotIndex &a, const SlotIndex &b) {
738 #endif // LLVM_CODEGEN_LIVEINDEX_H