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 /// isSameInstr - Return true if A and B refer to the same instruction.
182 static bool isSameInstr(SlotIndex A, SlotIndex B) {
183 return A.lie.getPointer() == B.lie.getPointer();
186 /// Return the distance from this index to the given one.
187 int distance(SlotIndex other) const {
188 return other.getIndex() - getIndex();
191 /// isLoad - Return true if this is a LOAD slot.
192 bool isLoad() const {
193 return getSlot() == LOAD;
196 /// isDef - Return true if this is a DEF slot.
198 return getSlot() == DEF;
201 /// isUse - Return true if this is a USE slot.
203 return getSlot() == USE;
206 /// isStore - Return true if this is a STORE slot.
207 bool isStore() const {
208 return getSlot() == STORE;
211 /// Returns the base index for associated with this index. The base index
212 /// is the one associated with the LOAD slot for the instruction pointed to
214 SlotIndex getBaseIndex() const {
215 return getLoadIndex();
218 /// Returns the boundary index for associated with this index. The boundary
219 /// index is the one associated with the LOAD slot for the instruction
220 /// pointed to by this index.
221 SlotIndex getBoundaryIndex() const {
222 return getStoreIndex();
225 /// Returns the index of the LOAD slot for the instruction pointed to by
227 SlotIndex getLoadIndex() const {
228 return SlotIndex(&entry(), SlotIndex::LOAD);
231 /// Returns the index of the USE slot for the instruction pointed to by
233 SlotIndex getUseIndex() const {
234 return SlotIndex(&entry(), SlotIndex::USE);
237 /// Returns the index of the DEF slot for the instruction pointed to by
239 SlotIndex getDefIndex() const {
240 return SlotIndex(&entry(), SlotIndex::DEF);
243 /// Returns the index of the STORE slot for the instruction pointed to by
245 SlotIndex getStoreIndex() const {
246 return SlotIndex(&entry(), SlotIndex::STORE);
249 /// Returns the next slot in the index list. This could be either the
250 /// next slot for the instruction pointed to by this index or, if this
251 /// index is a STORE, the first slot for the next instruction.
252 /// WARNING: This method is considerably more expensive than the methods
253 /// that return specific slots (getUseIndex(), etc). If you can - please
254 /// use one of those methods.
255 SlotIndex getNextSlot() const {
257 if (s == SlotIndex::STORE) {
258 return SlotIndex(entry().getNext(), SlotIndex::LOAD);
260 return SlotIndex(&entry(), s + 1);
263 /// Returns the next index. This is the index corresponding to the this
264 /// index's slot, but for the next instruction.
265 SlotIndex getNextIndex() const {
266 return SlotIndex(entry().getNext(), getSlot());
269 /// Returns the previous slot in the index list. This could be either the
270 /// previous slot for the instruction pointed to by this index or, if this
271 /// index is a LOAD, the last slot for the previous instruction.
272 /// WARNING: This method is considerably more expensive than the methods
273 /// that return specific slots (getUseIndex(), etc). If you can - please
274 /// use one of those methods.
275 SlotIndex getPrevSlot() const {
277 if (s == SlotIndex::LOAD) {
278 return SlotIndex(entry().getPrev(), SlotIndex::STORE);
280 return SlotIndex(&entry(), s - 1);
283 /// Returns the previous index. This is the index corresponding to this
284 /// index's slot, but for the previous instruction.
285 SlotIndex getPrevIndex() const {
286 return SlotIndex(entry().getPrev(), getSlot());
291 /// DenseMapInfo specialization for SlotIndex.
293 struct DenseMapInfo<SlotIndex> {
294 static inline SlotIndex getEmptyKey() {
295 return SlotIndex::getEmptyKey();
297 static inline SlotIndex getTombstoneKey() {
298 return SlotIndex::getTombstoneKey();
300 static inline unsigned getHashValue(const SlotIndex &v) {
301 return SlotIndex::getHashValue(v);
303 static inline bool isEqual(const SlotIndex &LHS, const SlotIndex &RHS) {
308 template <> struct isPodLike<SlotIndex> { static const bool value = true; };
311 inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
316 typedef std::pair<SlotIndex, MachineBasicBlock*> IdxMBBPair;
318 inline bool operator<(SlotIndex V, const IdxMBBPair &IM) {
322 inline bool operator<(const IdxMBBPair &IM, SlotIndex V) {
326 struct Idx2MBBCompare {
327 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
328 return LHS.first < RHS.first;
332 /// SlotIndexes pass.
334 /// This pass assigns indexes to each instruction.
335 class SlotIndexes : public MachineFunctionPass {
339 IndexListEntry *indexListHead;
340 unsigned functionSize;
342 typedef DenseMap<const MachineInstr*, SlotIndex> Mi2IndexMap;
345 /// MBBRanges - Map MBB number to (start, stop) indexes.
346 SmallVector<std::pair<SlotIndex, SlotIndex>, 8> MBBRanges;
348 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
350 SmallVector<IdxMBBPair, 8> idx2MBBMap;
352 // IndexListEntry allocator.
353 BumpPtrAllocator ileAllocator;
355 IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
356 IndexListEntry *entry =
357 static_cast<IndexListEntry*>(
358 ileAllocator.Allocate(sizeof(IndexListEntry),
359 alignOf<IndexListEntry>()));
361 new (entry) IndexListEntry(mi, index);
367 assert(indexListHead == 0 && "Zero entry non-null at initialisation.");
368 indexListHead = createEntry(0, ~0U);
369 indexListHead->setNext(0);
370 indexListHead->setPrev(indexListHead);
375 ileAllocator.Reset();
378 IndexListEntry* getTail() {
379 assert(indexListHead != 0 && "Call to getTail on uninitialized list.");
380 return indexListHead->getPrev();
383 const IndexListEntry* getTail() const {
384 assert(indexListHead != 0 && "Call to getTail on uninitialized list.");
385 return indexListHead->getPrev();
388 // Returns true if the index list is empty.
389 bool empty() const { return (indexListHead == getTail()); }
391 IndexListEntry* front() {
392 assert(!empty() && "front() called on empty index list.");
393 return indexListHead;
396 const IndexListEntry* front() const {
397 assert(!empty() && "front() called on empty index list.");
398 return indexListHead;
401 IndexListEntry* back() {
402 assert(!empty() && "back() called on empty index list.");
403 return getTail()->getPrev();
406 const IndexListEntry* back() const {
407 assert(!empty() && "back() called on empty index list.");
408 return getTail()->getPrev();
411 /// Insert a new entry before itr.
412 void insert(IndexListEntry *itr, IndexListEntry *val) {
413 assert(itr != 0 && "itr should not be null.");
414 IndexListEntry *prev = itr->getPrev();
418 if (itr != indexListHead) {
427 /// Push a new entry on to the end of the list.
428 void push_back(IndexListEntry *val) {
429 insert(getTail(), val);
432 /// Renumber locally after inserting newEntry.
433 void renumberIndexes(IndexListEntry *newEntry);
438 SlotIndexes() : MachineFunctionPass(ID), indexListHead(0) {
439 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
442 virtual void getAnalysisUsage(AnalysisUsage &au) const;
443 virtual void releaseMemory();
445 virtual bool runOnMachineFunction(MachineFunction &fn);
447 /// Dump the indexes.
450 /// Renumber the index list, providing space for new instructions.
451 void renumberIndexes();
453 /// Returns the zero index for this analysis.
454 SlotIndex getZeroIndex() {
455 assert(front()->getIndex() == 0 && "First index is not 0?");
456 return SlotIndex(front(), 0);
459 /// Returns the base index of the last slot in this analysis.
460 SlotIndex getLastIndex() {
461 return SlotIndex(back(), 0);
464 /// Returns the invalid index marker for this analysis.
465 SlotIndex getInvalidIndex() {
466 return getZeroIndex();
469 /// Returns the distance between the highest and lowest indexes allocated
471 unsigned getIndexesLength() const {
472 assert(front()->getIndex() == 0 &&
473 "Initial index isn't zero?");
475 return back()->getIndex();
478 /// Returns the number of instructions in the function.
479 unsigned getFunctionSize() const {
483 /// Returns true if the given machine instr is mapped to an index,
484 /// otherwise returns false.
485 bool hasIndex(const MachineInstr *instr) const {
486 return (mi2iMap.find(instr) != mi2iMap.end());
489 /// Returns the base index for the given instruction.
490 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
491 Mi2IndexMap::const_iterator itr = mi2iMap.find(instr);
492 assert(itr != mi2iMap.end() && "Instruction not found in maps.");
496 /// Returns the instruction for the given index, or null if the given
497 /// index has no instruction associated with it.
498 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
499 return index.isValid() ? index.entry().getInstr() : 0;
502 /// Returns the next non-null index.
503 SlotIndex getNextNonNullIndex(SlotIndex index) {
504 SlotIndex nextNonNull = index.getNextIndex();
506 while (&nextNonNull.entry() != getTail() &&
507 getInstructionFromIndex(nextNonNull) == 0) {
508 nextNonNull = nextNonNull.getNextIndex();
514 /// Return the (start,end) range of the given basic block number.
515 const std::pair<SlotIndex, SlotIndex> &
516 getMBBRange(unsigned Num) const {
517 return MBBRanges[Num];
520 /// Return the (start,end) range of the given basic block.
521 const std::pair<SlotIndex, SlotIndex> &
522 getMBBRange(const MachineBasicBlock *MBB) const {
523 return getMBBRange(MBB->getNumber());
526 /// Returns the first index in the given basic block number.
527 SlotIndex getMBBStartIdx(unsigned Num) const {
528 return getMBBRange(Num).first;
531 /// Returns the first index in the given basic block.
532 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
533 return getMBBRange(mbb).first;
536 /// Returns the last index in the given basic block number.
537 SlotIndex getMBBEndIdx(unsigned Num) const {
538 return getMBBRange(Num).second;
541 /// Returns the last index in the given basic block.
542 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
543 return getMBBRange(mbb).second;
546 /// Returns the basic block which the given index falls in.
547 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
548 if (MachineInstr *MI = getInstructionFromIndex(index))
549 return MI->getParent();
550 SmallVectorImpl<IdxMBBPair>::const_iterator I =
551 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), index);
552 // Take the pair containing the index
553 SmallVectorImpl<IdxMBBPair>::const_iterator J =
554 ((I != idx2MBBMap.end() && I->first > index) ||
555 (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
557 assert(J != idx2MBBMap.end() && J->first <= index &&
558 index < getMBBEndIdx(J->second) &&
559 "index does not correspond to an MBB");
563 bool findLiveInMBBs(SlotIndex start, SlotIndex end,
564 SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
565 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
566 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
569 while (itr != idx2MBBMap.end()) {
570 if (itr->first >= end)
572 mbbs.push_back(itr->second);
579 /// Returns the MBB covering the given range, or null if the range covers
580 /// more than one basic block.
581 MachineBasicBlock* getMBBCoveringRange(SlotIndex start, SlotIndex end) const {
583 assert(start < end && "Backwards ranges not allowed.");
585 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
586 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
588 if (itr == idx2MBBMap.end()) {
593 // Check that we don't cross the boundary into this block.
594 if (itr->first < end)
599 if (itr->first <= start)
605 /// Insert the given machine instruction into the mapping. Returns the
607 SlotIndex insertMachineInstrInMaps(MachineInstr *mi) {
608 assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
609 // Numbering DBG_VALUE instructions could cause code generation to be
610 // affected by debug information.
611 assert(!mi->isDebugValue() && "Cannot number DBG_VALUE instructions.");
613 MachineBasicBlock *mbb = mi->getParent();
615 assert(mbb != 0 && "Instr must be added to function.");
617 MachineBasicBlock::iterator miItr(mi);
618 IndexListEntry *newEntry;
619 // Get previous index, considering that not all instructions are indexed.
620 IndexListEntry *prevEntry;
622 // If mi is at the mbb beginning, get the prev index from the mbb.
623 if (miItr == mbb->begin()) {
624 prevEntry = &getMBBStartIdx(mbb).entry();
627 // Otherwise rewind until we find a mapped instruction.
628 Mi2IndexMap::const_iterator itr = mi2iMap.find(--miItr);
629 if (itr != mi2iMap.end()) {
630 prevEntry = &itr->second.entry();
635 // Get next entry from previous entry.
636 IndexListEntry *nextEntry = prevEntry->getNext();
638 // Get a number for the new instr, or 0 if there's no room currently.
639 // In the latter case we'll force a renumber later.
640 unsigned dist = ((nextEntry->getIndex() - prevEntry->getIndex())/2) & ~3u;
641 unsigned newNumber = prevEntry->getIndex() + dist;
643 // Insert a new list entry for mi.
644 newEntry = createEntry(mi, newNumber);
645 insert(nextEntry, newEntry);
647 // Renumber locally if we need to.
649 renumberIndexes(newEntry);
651 SlotIndex newIndex(newEntry, SlotIndex::LOAD);
652 mi2iMap.insert(std::make_pair(mi, newIndex));
656 /// Remove the given machine instruction from the mapping.
657 void removeMachineInstrFromMaps(MachineInstr *mi) {
658 // remove index -> MachineInstr and
659 // MachineInstr -> index mappings
660 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
661 if (mi2iItr != mi2iMap.end()) {
662 IndexListEntry *miEntry(&mi2iItr->second.entry());
663 assert(miEntry->getInstr() == mi && "Instruction indexes broken.");
664 // FIXME: Eventually we want to actually delete these indexes.
665 miEntry->setInstr(0);
666 mi2iMap.erase(mi2iItr);
670 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
671 /// maps used by register allocator.
672 void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI) {
673 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
674 if (mi2iItr == mi2iMap.end())
676 SlotIndex replaceBaseIndex = mi2iItr->second;
677 IndexListEntry *miEntry(&replaceBaseIndex.entry());
678 assert(miEntry->getInstr() == mi &&
679 "Mismatched instruction in index tables.");
680 miEntry->setInstr(newMI);
681 mi2iMap.erase(mi2iItr);
682 mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
685 /// Add the given MachineBasicBlock into the maps.
686 void insertMBBInMaps(MachineBasicBlock *mbb) {
687 MachineFunction::iterator nextMBB =
688 llvm::next(MachineFunction::iterator(mbb));
689 IndexListEntry *startEntry = createEntry(0, 0);
690 IndexListEntry *stopEntry = createEntry(0, 0);
691 IndexListEntry *nextEntry = 0;
693 if (nextMBB == mbb->getParent()->end()) {
694 nextEntry = getTail();
696 nextEntry = &getMBBStartIdx(nextMBB).entry();
699 insert(nextEntry, startEntry);
700 insert(nextEntry, stopEntry);
702 SlotIndex startIdx(startEntry, SlotIndex::LOAD);
703 SlotIndex endIdx(nextEntry, SlotIndex::LOAD);
705 assert(unsigned(mbb->getNumber()) == MBBRanges.size() &&
706 "Blocks must be added in order");
707 MBBRanges.push_back(std::make_pair(startIdx, endIdx));
709 idx2MBBMap.push_back(IdxMBBPair(startIdx, mbb));
712 std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());
718 // Specialize IntervalMapInfo for half-open slot index intervals.
719 template <typename> struct IntervalMapInfo;
720 template <> struct IntervalMapInfo<SlotIndex> {
721 static inline bool startLess(const SlotIndex &x, const SlotIndex &a) {
724 static inline bool stopLess(const SlotIndex &b, const SlotIndex &x) {
727 static inline bool adjacent(const SlotIndex &a, const SlotIndex &b) {
734 #endif // LLVM_CODEGEN_LIVEINDEX_H