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. The SlotIndex
17 // class does hold a PHI bit, which determines whether the index relates to a
18 // PHI use or def point, or an actual instruction. See the SlotIndex class
19 // description for futher information.
20 //===----------------------------------------------------------------------===//
22 #ifndef LLVM_CODEGEN_SLOTINDEXES_H
23 #define LLVM_CODEGEN_SLOTINDEXES_H
25 #include "llvm/CodeGen/MachineBasicBlock.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/ADT/PointerIntPair.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/Support/Allocator.h"
34 /// This class represents an entry in the slot index list held in the
35 /// SlotIndexes pass. It should not be used directly. See the
36 /// SlotIndex & SlotIndexes classes for the public interface to this
38 class IndexListEntry {
39 static const unsigned EMPTY_KEY_INDEX = ~0U & ~3U,
40 TOMBSTONE_KEY_INDEX = ~0U & ~7U;
42 IndexListEntry *next, *prev;
48 typedef enum { EMPTY_KEY, TOMBSTONE_KEY } ReservedEntryType;
50 // This constructor is only to be used by getEmptyKeyEntry
51 // & getTombstoneKeyEntry. It sets index to the given
52 // value and mi to zero.
53 IndexListEntry(ReservedEntryType r) : mi(0) {
55 case EMPTY_KEY: index = EMPTY_KEY_INDEX; break;
56 case TOMBSTONE_KEY: index = TOMBSTONE_KEY_INDEX; break;
57 default: assert(false && "Invalid value for constructor.");
65 IndexListEntry(MachineInstr *mi, unsigned index) : mi(mi), index(index) {
66 assert(index != EMPTY_KEY_INDEX && index != TOMBSTONE_KEY_INDEX &&
67 "Attempt to create invalid index. "
68 "Available indexes may have been exhausted?.");
71 bool isValid() const {
72 return (index != EMPTY_KEY_INDEX && index != TOMBSTONE_KEY_INDEX);
75 MachineInstr* getInstr() const { return mi; }
76 void setInstr(MachineInstr *mi) {
77 assert(isValid() && "Attempt to modify reserved index.");
81 unsigned getIndex() const { return index; }
82 void setIndex(unsigned index) {
83 assert(index != EMPTY_KEY_INDEX && index != TOMBSTONE_KEY_INDEX &&
84 "Attempt to set index to invalid value.");
85 assert(isValid() && "Attempt to reset reserved index value.");
89 IndexListEntry* getNext() { return next; }
90 const IndexListEntry* getNext() const { return next; }
91 void setNext(IndexListEntry *next) {
92 assert(isValid() && "Attempt to modify reserved index.");
96 IndexListEntry* getPrev() { return prev; }
97 const IndexListEntry* getPrev() const { return prev; }
98 void setPrev(IndexListEntry *prev) {
99 assert(isValid() && "Attempt to modify reserved index.");
103 // This function returns the index list entry that is to be used for empty
105 static IndexListEntry* getEmptyKeyEntry();
107 // This function returns the index list entry that is to be used for
108 // tombstone SlotIndex keys.
109 static IndexListEntry* getTombstoneKeyEntry();
112 // Specialize PointerLikeTypeTraits for IndexListEntry.
114 class PointerLikeTypeTraits<IndexListEntry*> {
116 static inline void* getAsVoidPointer(IndexListEntry *p) {
119 static inline IndexListEntry* getFromVoidPointer(void *p) {
120 return static_cast<IndexListEntry*>(p);
122 enum { NumLowBitsAvailable = 3 };
125 /// SlotIndex - An opaque wrapper around machine indexes.
127 friend class SlotIndexes;
128 friend struct DenseMapInfo<SlotIndex>;
131 static const unsigned PHI_BIT = 1 << 2;
133 PointerIntPair<IndexListEntry*, 3, unsigned> lie;
135 SlotIndex(IndexListEntry *entry, unsigned phiAndSlot)
136 : lie(entry, phiAndSlot) {
137 assert(entry != 0 && "Attempt to construct index with 0 pointer.");
140 IndexListEntry& entry() const {
141 return *lie.getPointer();
144 int getIndex() const {
145 return entry().getIndex() | getSlot();
148 static inline unsigned getHashValue(const SlotIndex &v) {
149 IndexListEntry *ptrVal = &v.entry();
150 return (unsigned((intptr_t)ptrVal) >> 4) ^
151 (unsigned((intptr_t)ptrVal) >> 9);
156 // FIXME: Ugh. This is public because LiveIntervalAnalysis is still using it
157 // for some spill weight stuff. Fix that, then make this private.
158 enum Slot { LOAD, USE, DEF, STORE, NUM };
160 static inline SlotIndex getEmptyKey() {
161 return SlotIndex(IndexListEntry::getEmptyKeyEntry(), 0);
164 static inline SlotIndex getTombstoneKey() {
165 return SlotIndex(IndexListEntry::getTombstoneKeyEntry(), 0);
168 /// Construct an invalid index.
169 SlotIndex() : lie(IndexListEntry::getEmptyKeyEntry(), 0) {}
171 // Construct a new slot index from the given one, set the phi flag on the
172 // new index to the value of the phi parameter.
173 SlotIndex(const SlotIndex &li, bool phi)
174 : lie(&li.entry(), phi ? PHI_BIT | li.getSlot() : (unsigned)li.getSlot()){
175 assert(lie.getPointer() != 0 &&
176 "Attempt to construct index with 0 pointer.");
179 // Construct a new slot index from the given one, set the phi flag on the
180 // new index to the value of the phi parameter, and the slot to the new slot.
181 SlotIndex(const SlotIndex &li, bool phi, Slot s)
182 : lie(&li.entry(), phi ? PHI_BIT | s : (unsigned)s) {
183 assert(lie.getPointer() != 0 &&
184 "Attempt to construct index with 0 pointer.");
187 /// Returns true if this is a valid index. Invalid indicies do
188 /// not point into an index table, and cannot be compared.
189 bool isValid() const {
190 IndexListEntry *entry = lie.getPointer();
191 return ((entry!= 0) && (entry->isValid()));
194 /// Print this index to the given raw_ostream.
195 void print(raw_ostream &os) const;
197 /// Dump this index to stderr.
200 /// Compare two SlotIndex objects for equality.
201 bool operator==(SlotIndex other) const {
202 return getIndex() == other.getIndex();
204 /// Compare two SlotIndex objects for inequality.
205 bool operator!=(SlotIndex other) const {
206 return getIndex() != other.getIndex();
209 /// Compare two SlotIndex objects. Return true if the first index
210 /// is strictly lower than the second.
211 bool operator<(SlotIndex other) const {
212 return getIndex() < other.getIndex();
214 /// Compare two SlotIndex objects. Return true if the first index
215 /// is lower than, or equal to, the second.
216 bool operator<=(SlotIndex other) const {
217 return getIndex() <= other.getIndex();
220 /// Compare two SlotIndex objects. Return true if the first index
221 /// is greater than the second.
222 bool operator>(SlotIndex other) const {
223 return getIndex() > other.getIndex();
226 /// Compare two SlotIndex objects. Return true if the first index
227 /// is greater than, or equal to, the second.
228 bool operator>=(SlotIndex other) const {
229 return getIndex() >= other.getIndex();
232 /// Return the distance from this index to the given one.
233 int distance(SlotIndex other) const {
234 return other.getIndex() - getIndex();
237 /// Returns the slot for this SlotIndex.
238 Slot getSlot() const {
239 return static_cast<Slot>(lie.getInt() & ~PHI_BIT);
242 /// Returns the state of the PHI bit.
244 return lie.getInt() & PHI_BIT;
247 /// Returns the base index for associated with this index. The base index
248 /// is the one associated with the LOAD slot for the instruction pointed to
250 SlotIndex getBaseIndex() const {
251 return getLoadIndex();
254 /// Returns the boundary index for associated with this index. The boundary
255 /// index is the one associated with the LOAD slot for the instruction
256 /// pointed to by this index.
257 SlotIndex getBoundaryIndex() const {
258 return getStoreIndex();
261 /// Returns the index of the LOAD slot for the instruction pointed to by
263 SlotIndex getLoadIndex() const {
264 return SlotIndex(&entry(), SlotIndex::LOAD);
267 /// Returns the index of the USE slot for the instruction pointed to by
269 SlotIndex getUseIndex() const {
270 return SlotIndex(&entry(), SlotIndex::USE);
273 /// Returns the index of the DEF slot for the instruction pointed to by
275 SlotIndex getDefIndex() const {
276 return SlotIndex(&entry(), SlotIndex::DEF);
279 /// Returns the index of the STORE slot for the instruction pointed to by
281 SlotIndex getStoreIndex() const {
282 return SlotIndex(&entry(), SlotIndex::STORE);
285 /// Returns the next slot in the index list. This could be either the
286 /// next slot for the instruction pointed to by this index or, if this
287 /// index is a STORE, the first slot for the next instruction.
288 /// WARNING: This method is considerably more expensive than the methods
289 /// that return specific slots (getUseIndex(), etc). If you can - please
290 /// use one of those methods.
291 SlotIndex getNextSlot() const {
293 if (s == SlotIndex::STORE) {
294 return SlotIndex(entry().getNext(), SlotIndex::LOAD);
296 return SlotIndex(&entry(), s + 1);
299 /// Returns the next index. This is the index corresponding to the this
300 /// index's slot, but for the next instruction.
301 SlotIndex getNextIndex() const {
302 return SlotIndex(entry().getNext(), getSlot());
305 /// Returns the previous slot in the index list. This could be either the
306 /// previous slot for the instruction pointed to by this index or, if this
307 /// index is a LOAD, the last slot for the previous instruction.
308 /// WARNING: This method is considerably more expensive than the methods
309 /// that return specific slots (getUseIndex(), etc). If you can - please
310 /// use one of those methods.
311 SlotIndex getPrevSlot() const {
313 if (s == SlotIndex::LOAD) {
314 return SlotIndex(entry().getPrev(), SlotIndex::STORE);
316 return SlotIndex(&entry(), s - 1);
319 /// Returns the previous index. This is the index corresponding to this
320 /// index's slot, but for the previous instruction.
321 SlotIndex getPrevIndex() const {
322 return SlotIndex(entry().getPrev(), getSlot());
327 /// DenseMapInfo specialization for SlotIndex.
329 struct DenseMapInfo<SlotIndex> {
330 static inline SlotIndex getEmptyKey() {
331 return SlotIndex::getEmptyKey();
333 static inline SlotIndex getTombstoneKey() {
334 return SlotIndex::getTombstoneKey();
336 static inline unsigned getHashValue(const SlotIndex &v) {
337 return SlotIndex::getHashValue(v);
339 static inline bool isEqual(const SlotIndex &LHS, const SlotIndex &RHS) {
344 template <> struct isPodLike<SlotIndex> { static const bool value = true; };
347 inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
352 typedef std::pair<SlotIndex, MachineBasicBlock*> IdxMBBPair;
354 inline bool operator<(SlotIndex V, const IdxMBBPair &IM) {
358 inline bool operator<(const IdxMBBPair &IM, SlotIndex V) {
362 struct Idx2MBBCompare {
363 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
364 return LHS.first < RHS.first;
368 /// SlotIndexes pass.
370 /// This pass assigns indexes to each instruction.
371 class SlotIndexes : public MachineFunctionPass {
375 IndexListEntry *indexListHead;
376 unsigned functionSize;
378 typedef DenseMap<const MachineInstr*, SlotIndex> Mi2IndexMap;
381 /// MBB2IdxMap - The indexes of the first and last instructions in the
382 /// specified basic block.
383 typedef DenseMap<const MachineBasicBlock*,
384 std::pair<SlotIndex, SlotIndex> > MBB2IdxMap;
385 MBB2IdxMap mbb2IdxMap;
387 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
389 std::vector<IdxMBBPair> idx2MBBMap;
391 typedef DenseMap<const MachineBasicBlock*, SlotIndex> TerminatorGapsMap;
392 TerminatorGapsMap terminatorGaps;
394 // IndexListEntry allocator.
395 BumpPtrAllocator ileAllocator;
397 IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
398 IndexListEntry *entry =
399 static_cast<IndexListEntry*>(
400 ileAllocator.Allocate(sizeof(IndexListEntry),
401 alignof<IndexListEntry>()));
403 new (entry) IndexListEntry(mi, index);
409 assert(indexListHead == 0 && "Zero entry non-null at initialisation.");
410 indexListHead = createEntry(0, ~0U);
411 indexListHead->setNext(0);
412 indexListHead->setPrev(indexListHead);
417 ileAllocator.Reset();
420 IndexListEntry* getTail() {
421 assert(indexListHead != 0 && "Call to getTail on uninitialized list.");
422 return indexListHead->getPrev();
425 const IndexListEntry* getTail() const {
426 assert(indexListHead != 0 && "Call to getTail on uninitialized list.");
427 return indexListHead->getPrev();
430 // Returns true if the index list is empty.
431 bool empty() const { return (indexListHead == getTail()); }
433 IndexListEntry* front() {
434 assert(!empty() && "front() called on empty index list.");
435 return indexListHead;
438 const IndexListEntry* front() const {
439 assert(!empty() && "front() called on empty index list.");
440 return indexListHead;
443 IndexListEntry* back() {
444 assert(!empty() && "back() called on empty index list.");
445 return getTail()->getPrev();
448 const IndexListEntry* back() const {
449 assert(!empty() && "back() called on empty index list.");
450 return getTail()->getPrev();
453 /// Insert a new entry before itr.
454 void insert(IndexListEntry *itr, IndexListEntry *val) {
455 assert(itr != 0 && "itr should not be null.");
456 IndexListEntry *prev = itr->getPrev();
460 if (itr != indexListHead) {
469 /// Push a new entry on to the end of the list.
470 void push_back(IndexListEntry *val) {
471 insert(getTail(), val);
477 SlotIndexes() : MachineFunctionPass(&ID), indexListHead(0) {}
479 virtual void getAnalysisUsage(AnalysisUsage &au) const;
480 virtual void releaseMemory();
482 virtual bool runOnMachineFunction(MachineFunction &fn);
484 /// Dump the indexes.
487 /// Renumber the index list, providing space for new instructions.
488 void renumberIndexes();
490 /// Returns the zero index for this analysis.
491 SlotIndex getZeroIndex() {
492 assert(front()->getIndex() == 0 && "First index is not 0?");
493 return SlotIndex(front(), 0);
496 /// Returns the invalid index marker for this analysis.
497 SlotIndex getInvalidIndex() {
498 return getZeroIndex();
501 /// Returns the distance between the highest and lowest indexes allocated
503 unsigned getIndexesLength() const {
504 assert(front()->getIndex() == 0 &&
505 "Initial index isn't zero?");
507 return back()->getIndex();
510 /// Returns the number of instructions in the function.
511 unsigned getFunctionSize() const {
515 /// Returns true if the given machine instr is mapped to an index,
516 /// otherwise returns false.
517 bool hasIndex(const MachineInstr *instr) const {
518 return (mi2iMap.find(instr) != mi2iMap.end());
521 /// Returns the base index for the given instruction.
522 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
523 Mi2IndexMap::const_iterator itr = mi2iMap.find(instr);
524 assert(itr != mi2iMap.end() && "Instruction not found in maps.");
528 /// Returns the instruction for the given index, or null if the given
529 /// index has no instruction associated with it.
530 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
531 return index.entry().getInstr();
534 /// Returns the next non-null index.
535 SlotIndex getNextNonNullIndex(SlotIndex index) {
536 SlotIndex nextNonNull = index.getNextIndex();
538 while (&nextNonNull.entry() != getTail() &&
539 getInstructionFromIndex(nextNonNull) == 0) {
540 nextNonNull = nextNonNull.getNextIndex();
546 /// Returns the first index in the given basic block.
547 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
548 MBB2IdxMap::const_iterator itr = mbb2IdxMap.find(mbb);
549 assert(itr != mbb2IdxMap.end() && "MBB not found in maps.");
550 return itr->second.first;
553 /// Returns the last index in the given basic block.
554 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
555 MBB2IdxMap::const_iterator itr = mbb2IdxMap.find(mbb);
556 assert(itr != mbb2IdxMap.end() && "MBB not found in maps.");
557 return itr->second.second;
560 /// Returns the terminator gap for the given index.
561 SlotIndex getTerminatorGap(const MachineBasicBlock *mbb) {
562 TerminatorGapsMap::iterator itr = terminatorGaps.find(mbb);
563 assert(itr != terminatorGaps.end() &&
564 "All MBBs should have terminator gaps in their indexes.");
568 /// Returns the basic block which the given index falls in.
569 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
570 std::vector<IdxMBBPair>::const_iterator I =
571 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), index);
572 // Take the pair containing the index
573 std::vector<IdxMBBPair>::const_iterator J =
574 ((I != idx2MBBMap.end() && I->first > index) ||
575 (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
577 assert(J != idx2MBBMap.end() && J->first <= index &&
578 index < getMBBEndIdx(J->second) &&
579 "index does not correspond to an MBB");
583 bool findLiveInMBBs(SlotIndex start, SlotIndex end,
584 SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
585 std::vector<IdxMBBPair>::const_iterator itr =
586 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
589 while (itr != idx2MBBMap.end()) {
590 if (itr->first >= end)
592 mbbs.push_back(itr->second);
599 /// Return a list of MBBs that can be reach via any branches or
601 bool findReachableMBBs(SlotIndex start, SlotIndex end,
602 SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
603 std::vector<IdxMBBPair>::const_iterator itr =
604 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
607 while (itr != idx2MBBMap.end()) {
608 if (itr->first > end)
610 MachineBasicBlock *mbb = itr->second;
611 if (getMBBEndIdx(mbb) > end)
613 for (MachineBasicBlock::succ_iterator si = mbb->succ_begin(),
614 se = mbb->succ_end(); si != se; ++si)
622 /// Returns the MBB covering the given range, or null if the range covers
623 /// more than one basic block.
624 MachineBasicBlock* getMBBCoveringRange(SlotIndex start, SlotIndex end) const {
626 assert(start < end && "Backwards ranges not allowed.");
628 std::vector<IdxMBBPair>::const_iterator itr =
629 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
631 if (itr == idx2MBBMap.end()) {
636 // Check that we don't cross the boundary into this block.
637 if (itr->first < end)
642 if (itr->first <= start)
648 /// Insert the given machine instruction into the mapping. Returns the
650 SlotIndex insertMachineInstrInMaps(MachineInstr *mi,
651 bool *deferredRenumber = 0) {
652 assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
654 MachineBasicBlock *mbb = mi->getParent();
656 assert(mbb != 0 && "Instr must be added to function.");
658 MBB2IdxMap::iterator mbbRangeItr = mbb2IdxMap.find(mbb);
660 assert(mbbRangeItr != mbb2IdxMap.end() &&
661 "Instruction's parent MBB has not been added to SlotIndexes.");
663 MachineBasicBlock::iterator miItr(mi);
664 bool needRenumber = false;
665 IndexListEntry *newEntry;
667 IndexListEntry *prevEntry;
668 if (miItr == mbb->begin()) {
669 // If mi is at the mbb beginning, get the prev index from the mbb.
670 prevEntry = &mbbRangeItr->second.first.entry();
672 // Otherwise get it from the previous instr.
673 MachineBasicBlock::iterator pItr(prior(miItr));
674 prevEntry = &getInstructionIndex(pItr).entry();
677 // Get next entry from previous entry.
678 IndexListEntry *nextEntry = prevEntry->getNext();
680 // Get a number for the new instr, or 0 if there's no room currently.
681 // In the latter case we'll force a renumber later.
682 unsigned dist = nextEntry->getIndex() - prevEntry->getIndex();
683 unsigned newNumber = dist > SlotIndex::NUM ?
684 prevEntry->getIndex() + ((dist >> 1) & ~3U) : 0;
686 if (newNumber == 0) {
690 // Insert a new list entry for mi.
691 newEntry = createEntry(mi, newNumber);
692 insert(nextEntry, newEntry);
694 SlotIndex newIndex(newEntry, SlotIndex::LOAD);
695 mi2iMap.insert(std::make_pair(mi, newIndex));
697 if (miItr == mbb->end()) {
698 // If this is the last instr in the MBB then we need to fix up the bb
700 mbbRangeItr->second.second = SlotIndex(newEntry, SlotIndex::STORE);
703 // Renumber if we need to.
705 if (deferredRenumber == 0)
708 *deferredRenumber = true;
714 /// Add all instructions in the vector to the index list. This method will
715 /// defer renumbering until all instrs have been added, and should be
716 /// preferred when adding multiple instrs.
717 void insertMachineInstrsInMaps(SmallVectorImpl<MachineInstr*> &mis) {
718 bool renumber = false;
720 for (SmallVectorImpl<MachineInstr*>::iterator
721 miItr = mis.begin(), miEnd = mis.end();
722 miItr != miEnd; ++miItr) {
723 insertMachineInstrInMaps(*miItr, &renumber);
731 /// Remove the given machine instruction from the mapping.
732 void removeMachineInstrFromMaps(MachineInstr *mi) {
733 // remove index -> MachineInstr and
734 // MachineInstr -> index mappings
735 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
736 if (mi2iItr != mi2iMap.end()) {
737 IndexListEntry *miEntry(&mi2iItr->second.entry());
738 assert(miEntry->getInstr() == mi && "Instruction indexes broken.");
739 // FIXME: Eventually we want to actually delete these indexes.
740 miEntry->setInstr(0);
741 mi2iMap.erase(mi2iItr);
745 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
746 /// maps used by register allocator.
747 void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI) {
748 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
749 if (mi2iItr == mi2iMap.end())
751 SlotIndex replaceBaseIndex = mi2iItr->second;
752 IndexListEntry *miEntry(&replaceBaseIndex.entry());
753 assert(miEntry->getInstr() == mi &&
754 "Mismatched instruction in index tables.");
755 miEntry->setInstr(newMI);
756 mi2iMap.erase(mi2iItr);
757 mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
765 #endif // LLVM_CODEGEN_LIVEINDEX_H