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 purpose 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/MachineInstrBundle.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/ADT/PointerIntPair.h"
26 #include "llvm/ADT/ilist.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/Support/Allocator.h"
33 /// This class represents an entry in the slot index list held in the
34 /// SlotIndexes pass. It should not be used directly. See the
35 /// SlotIndex & SlotIndexes classes for the public interface to this
37 class IndexListEntry : public ilist_node<IndexListEntry> {
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) {
58 struct ilist_traits<IndexListEntry> : public ilist_default_traits<IndexListEntry> {
60 mutable ilist_half_node<IndexListEntry> Sentinel;
62 IndexListEntry *createSentinel() const {
63 return static_cast<IndexListEntry*>(&Sentinel);
65 void destroySentinel(IndexListEntry *) const {}
67 IndexListEntry *provideInitialHead() const { return createSentinel(); }
68 IndexListEntry *ensureHead(IndexListEntry*) const { return createSentinel(); }
69 static void noteHead(IndexListEntry*, IndexListEntry*) {}
70 void deleteNode(IndexListEntry *N) {}
73 void createNode(const IndexListEntry &);
76 /// SlotIndex - An opaque wrapper around machine indexes.
78 friend class SlotIndexes;
79 friend struct DenseMapInfo<SlotIndex>;
82 /// Basic block boundary. Used for live ranges entering and leaving a
83 /// block without being live in the layout neighbor. Also used as the
84 /// def slot of PHI-defs.
87 /// Early-clobber register use/def slot. A live range defined at
88 /// Slot_EarlyCLobber interferes with normal live ranges killed at
89 /// Slot_Register. Also used as the kill slot for live ranges tied to an
90 /// early-clobber def.
93 /// Normal register use/def slot. Normal instructions kill and define
94 /// register live ranges at this slot.
97 /// Dead def kill point. Kill slot for a live range that is defined by
98 /// the same instruction (Slot_Register or Slot_EarlyClobber), but isn't
105 PointerIntPair<IndexListEntry*, 2, unsigned> lie;
107 SlotIndex(IndexListEntry *entry, unsigned slot)
108 : lie(entry, slot) {}
110 IndexListEntry* listEntry() const {
111 assert(isValid() && "Attempt to compare reserved index.");
112 return lie.getPointer();
115 int getIndex() const {
116 return listEntry()->getIndex() | getSlot();
119 /// Returns the slot for this SlotIndex.
120 Slot getSlot() const {
121 return static_cast<Slot>(lie.getInt());
124 static inline unsigned getHashValue(const SlotIndex &v) {
125 void *ptrVal = v.lie.getOpaqueValue();
126 return (unsigned((intptr_t)ptrVal)) ^ (unsigned((intptr_t)ptrVal) >> 9);
131 /// The default distance between instructions as returned by distance().
132 /// This may vary as instructions are inserted and removed.
133 InstrDist = 4 * Slot_Count
136 static inline SlotIndex getEmptyKey() {
137 return SlotIndex(0, 1);
140 static inline SlotIndex getTombstoneKey() {
141 return SlotIndex(0, 2);
144 /// Construct an invalid index.
145 SlotIndex() : lie(0, 0) {}
147 // Construct a new slot index from the given one, and set the slot.
148 SlotIndex(const SlotIndex &li, Slot s) : lie(li.listEntry(), unsigned(s)) {
149 assert(lie.getPointer() != 0 &&
150 "Attempt to construct index with 0 pointer.");
153 /// Returns true if this is a valid index. Invalid indicies do
154 /// not point into an index table, and cannot be compared.
155 bool isValid() const {
156 return lie.getPointer();
159 /// Return true for a valid index.
160 operator bool() const { return isValid(); }
162 /// Print this index to the given raw_ostream.
163 void print(raw_ostream &os) const;
165 /// Dump this index to stderr.
168 /// Compare two SlotIndex objects for equality.
169 bool operator==(SlotIndex other) const {
170 return lie == other.lie;
172 /// Compare two SlotIndex objects for inequality.
173 bool operator!=(SlotIndex other) const {
174 return lie != other.lie;
177 /// Compare two SlotIndex objects. Return true if the first index
178 /// is strictly lower than the second.
179 bool operator<(SlotIndex other) const {
180 return getIndex() < other.getIndex();
182 /// Compare two SlotIndex objects. Return true if the first index
183 /// is lower than, or equal to, the second.
184 bool operator<=(SlotIndex other) const {
185 return getIndex() <= other.getIndex();
188 /// Compare two SlotIndex objects. Return true if the first index
189 /// is greater than the second.
190 bool operator>(SlotIndex other) const {
191 return getIndex() > other.getIndex();
194 /// Compare two SlotIndex objects. Return true if the first index
195 /// is greater than, or equal to, the second.
196 bool operator>=(SlotIndex other) const {
197 return getIndex() >= other.getIndex();
200 /// isSameInstr - Return true if A and B refer to the same instruction.
201 static bool isSameInstr(SlotIndex A, SlotIndex B) {
202 return A.lie.getPointer() == B.lie.getPointer();
205 /// isEarlierInstr - Return true if A refers to an instruction earlier than
206 /// B. This is equivalent to A < B && !isSameInstr(A, B).
207 static bool isEarlierInstr(SlotIndex A, SlotIndex B) {
208 return A.listEntry()->getIndex() < B.listEntry()->getIndex();
211 /// Return the distance from this index to the given one.
212 int distance(SlotIndex other) const {
213 return other.getIndex() - getIndex();
216 /// isBlock - Returns true if this is a block boundary slot.
217 bool isBlock() const { return getSlot() == Slot_Block; }
219 /// isEarlyClobber - Returns true if this is an early-clobber slot.
220 bool isEarlyClobber() const { return getSlot() == Slot_EarlyClobber; }
222 /// isRegister - Returns true if this is a normal register use/def slot.
223 /// Note that early-clobber slots may also be used for uses and defs.
224 bool isRegister() const { return getSlot() == Slot_Register; }
226 /// isDead - Returns true if this is a dead def kill slot.
227 bool isDead() const { return getSlot() == Slot_Dead; }
229 /// Returns the base index for associated with this index. The base index
230 /// is the one associated with the Slot_Block slot for the instruction
231 /// pointed to by this index.
232 SlotIndex getBaseIndex() const {
233 return SlotIndex(listEntry(), Slot_Block);
236 /// Returns the boundary index for associated with this index. The boundary
237 /// index is the one associated with the Slot_Block slot for the instruction
238 /// pointed to by this index.
239 SlotIndex getBoundaryIndex() const {
240 return SlotIndex(listEntry(), Slot_Dead);
243 /// Returns the register use/def slot in the current instruction for a
244 /// normal or early-clobber def.
245 SlotIndex getRegSlot(bool EC = false) const {
246 return SlotIndex(listEntry(), EC ? Slot_EarlyClobber : Slot_Register);
249 /// Returns the dead def kill slot for the current instruction.
250 SlotIndex getDeadSlot() const {
251 return SlotIndex(listEntry(), Slot_Dead);
254 /// Returns the next slot in the index list. This could be either the
255 /// next slot for the instruction pointed to by this index or, if this
256 /// index is a STORE, the first slot for the next instruction.
257 /// WARNING: This method is considerably more expensive than the methods
258 /// that return specific slots (getUseIndex(), etc). If you can - please
259 /// use one of those methods.
260 SlotIndex getNextSlot() const {
262 if (s == Slot_Dead) {
263 return SlotIndex(listEntry()->getNextNode(), Slot_Block);
265 return SlotIndex(listEntry(), s + 1);
268 /// Returns the next index. This is the index corresponding to the this
269 /// index's slot, but for the next instruction.
270 SlotIndex getNextIndex() const {
271 return SlotIndex(listEntry()->getNextNode(), getSlot());
274 /// Returns the previous slot in the index list. This could be either the
275 /// previous slot for the instruction pointed to by this index or, if this
276 /// index is a Slot_Block, the last slot for the previous instruction.
277 /// WARNING: This method is considerably more expensive than the methods
278 /// that return specific slots (getUseIndex(), etc). If you can - please
279 /// use one of those methods.
280 SlotIndex getPrevSlot() const {
282 if (s == Slot_Block) {
283 return SlotIndex(listEntry()->getPrevNode(), Slot_Dead);
285 return SlotIndex(listEntry(), s - 1);
288 /// Returns the previous index. This is the index corresponding to this
289 /// index's slot, but for the previous instruction.
290 SlotIndex getPrevIndex() const {
291 return SlotIndex(listEntry()->getPrevNode(), getSlot());
296 /// DenseMapInfo specialization for SlotIndex.
298 struct DenseMapInfo<SlotIndex> {
299 static inline SlotIndex getEmptyKey() {
300 return SlotIndex::getEmptyKey();
302 static inline SlotIndex getTombstoneKey() {
303 return SlotIndex::getTombstoneKey();
305 static inline unsigned getHashValue(const SlotIndex &v) {
306 return SlotIndex::getHashValue(v);
308 static inline bool isEqual(const SlotIndex &LHS, const SlotIndex &RHS) {
313 template <> struct isPodLike<SlotIndex> { static const bool value = true; };
316 inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
321 typedef std::pair<SlotIndex, MachineBasicBlock*> IdxMBBPair;
323 inline bool operator<(SlotIndex V, const IdxMBBPair &IM) {
327 inline bool operator<(const IdxMBBPair &IM, SlotIndex V) {
331 struct Idx2MBBCompare {
332 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
333 return LHS.first < RHS.first;
337 /// SlotIndexes pass.
339 /// This pass assigns indexes to each instruction.
340 class SlotIndexes : public MachineFunctionPass {
343 typedef ilist<IndexListEntry> IndexList;
348 typedef DenseMap<const MachineInstr*, SlotIndex> Mi2IndexMap;
351 /// MBBRanges - Map MBB number to (start, stop) indexes.
352 SmallVector<std::pair<SlotIndex, SlotIndex>, 8> MBBRanges;
354 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
356 SmallVector<IdxMBBPair, 8> idx2MBBMap;
358 // IndexListEntry allocator.
359 BumpPtrAllocator ileAllocator;
361 IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
362 IndexListEntry *entry =
363 static_cast<IndexListEntry*>(
364 ileAllocator.Allocate(sizeof(IndexListEntry),
365 alignOf<IndexListEntry>()));
367 new (entry) IndexListEntry(mi, index);
372 /// Renumber locally after inserting curItr.
373 void renumberIndexes(IndexList::iterator curItr);
378 SlotIndexes() : MachineFunctionPass(ID) {
379 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
382 virtual void getAnalysisUsage(AnalysisUsage &au) const;
383 virtual void releaseMemory();
385 virtual bool runOnMachineFunction(MachineFunction &fn);
387 /// Dump the indexes.
390 /// Renumber the index list, providing space for new instructions.
391 void renumberIndexes();
393 /// Returns the zero index for this analysis.
394 SlotIndex getZeroIndex() {
395 assert(indexList.front().getIndex() == 0 && "First index is not 0?");
396 return SlotIndex(&indexList.front(), 0);
399 /// Returns the base index of the last slot in this analysis.
400 SlotIndex getLastIndex() {
401 return SlotIndex(&indexList.back(), 0);
404 /// Returns true if the given machine instr is mapped to an index,
405 /// otherwise returns false.
406 bool hasIndex(const MachineInstr *instr) const {
407 return mi2iMap.count(instr);
410 /// Returns the base index for the given instruction.
411 SlotIndex getInstructionIndex(const MachineInstr *MI) const {
412 // Instructions inside a bundle have the same number as the bundle itself.
413 Mi2IndexMap::const_iterator itr = mi2iMap.find(getBundleStart(MI));
414 assert(itr != mi2iMap.end() && "Instruction not found in maps.");
418 /// Returns the instruction for the given index, or null if the given
419 /// index has no instruction associated with it.
420 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
421 return index.isValid() ? index.listEntry()->getInstr() : 0;
424 /// Returns the next non-null index.
425 SlotIndex getNextNonNullIndex(SlotIndex index) {
426 IndexList::iterator itr(index.listEntry());
428 while (itr != indexList.end() && itr->getInstr() == 0) { ++itr; }
429 return SlotIndex(itr, index.getSlot());
432 /// getIndexBefore - Returns the index of the last indexed instruction
433 /// before MI, or the the start index of its basic block.
434 /// MI is not required to have an index.
435 SlotIndex getIndexBefore(const MachineInstr *MI) const {
436 const MachineBasicBlock *MBB = MI->getParent();
437 assert(MBB && "MI must be inserted inna basic block");
438 MachineBasicBlock::const_iterator I = MI, B = MBB->begin();
441 return getMBBStartIdx(MBB);
443 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
444 if (MapItr != mi2iMap.end())
445 return MapItr->second;
449 /// getIndexAfter - Returns the index of the first indexed instruction
450 /// after MI, or the end index of its basic block.
451 /// MI is not required to have an index.
452 SlotIndex getIndexAfter(const MachineInstr *MI) const {
453 const MachineBasicBlock *MBB = MI->getParent();
454 assert(MBB && "MI must be inserted inna basic block");
455 MachineBasicBlock::const_iterator I = MI, E = MBB->end();
459 return getMBBEndIdx(MBB);
460 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
461 if (MapItr != mi2iMap.end())
462 return MapItr->second;
466 /// Return the (start,end) range of the given basic block number.
467 const std::pair<SlotIndex, SlotIndex> &
468 getMBBRange(unsigned Num) const {
469 return MBBRanges[Num];
472 /// Return the (start,end) range of the given basic block.
473 const std::pair<SlotIndex, SlotIndex> &
474 getMBBRange(const MachineBasicBlock *MBB) const {
475 return getMBBRange(MBB->getNumber());
478 /// Returns the first index in the given basic block number.
479 SlotIndex getMBBStartIdx(unsigned Num) const {
480 return getMBBRange(Num).first;
483 /// Returns the first index in the given basic block.
484 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
485 return getMBBRange(mbb).first;
488 /// Returns the last index in the given basic block number.
489 SlotIndex getMBBEndIdx(unsigned Num) const {
490 return getMBBRange(Num).second;
493 /// Returns the last index in the given basic block.
494 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
495 return getMBBRange(mbb).second;
498 /// Returns the basic block which the given index falls in.
499 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
500 if (MachineInstr *MI = getInstructionFromIndex(index))
501 return MI->getParent();
502 SmallVectorImpl<IdxMBBPair>::const_iterator I =
503 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), index);
504 // Take the pair containing the index
505 SmallVectorImpl<IdxMBBPair>::const_iterator J =
506 ((I != idx2MBBMap.end() && I->first > index) ||
507 (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
509 assert(J != idx2MBBMap.end() && J->first <= index &&
510 index < getMBBEndIdx(J->second) &&
511 "index does not correspond to an MBB");
515 bool findLiveInMBBs(SlotIndex start, SlotIndex end,
516 SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
517 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
518 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
521 while (itr != idx2MBBMap.end()) {
522 if (itr->first >= end)
524 mbbs.push_back(itr->second);
531 /// Returns the MBB covering the given range, or null if the range covers
532 /// more than one basic block.
533 MachineBasicBlock* getMBBCoveringRange(SlotIndex start, SlotIndex end) const {
535 assert(start < end && "Backwards ranges not allowed.");
537 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
538 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
540 if (itr == idx2MBBMap.end()) {
545 // Check that we don't cross the boundary into this block.
546 if (itr->first < end)
551 if (itr->first <= start)
557 /// Insert the given machine instruction into the mapping. Returns the
559 /// If Late is set and there are null indexes between mi's neighboring
560 /// instructions, create the new index after the null indexes instead of
562 SlotIndex insertMachineInstrInMaps(MachineInstr *mi, bool Late = false) {
563 assert(!mi->isInsideBundle() &&
564 "Instructions inside bundles should use bundle start's slot.");
565 assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
566 // Numbering DBG_VALUE instructions could cause code generation to be
567 // affected by debug information.
568 assert(!mi->isDebugValue() && "Cannot number DBG_VALUE instructions.");
570 assert(mi->getParent() != 0 && "Instr must be added to function.");
572 // Get the entries where mi should be inserted.
573 IndexList::iterator prevItr, nextItr;
575 // Insert mi's index immediately before the following instruction.
576 nextItr = getIndexAfter(mi).listEntry();
577 prevItr = prior(nextItr);
579 // Insert mi's index immediately after the preceeding instruction.
580 prevItr = getIndexBefore(mi).listEntry();
581 nextItr = llvm::next(prevItr);
584 // Get a number for the new instr, or 0 if there's no room currently.
585 // In the latter case we'll force a renumber later.
586 unsigned dist = ((nextItr->getIndex() - prevItr->getIndex())/2) & ~3u;
587 unsigned newNumber = prevItr->getIndex() + dist;
589 // Insert a new list entry for mi.
590 IndexList::iterator newItr =
591 indexList.insert(nextItr, createEntry(mi, newNumber));
593 // Renumber locally if we need to.
595 renumberIndexes(newItr);
597 SlotIndex newIndex(&*newItr, SlotIndex::Slot_Block);
598 mi2iMap.insert(std::make_pair(mi, newIndex));
602 /// Remove the given machine instruction from the mapping.
603 void removeMachineInstrFromMaps(MachineInstr *mi) {
604 // remove index -> MachineInstr and
605 // MachineInstr -> index mappings
606 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
607 if (mi2iItr != mi2iMap.end()) {
608 IndexListEntry *miEntry(mi2iItr->second.listEntry());
609 assert(miEntry->getInstr() == mi && "Instruction indexes broken.");
610 // FIXME: Eventually we want to actually delete these indexes.
611 miEntry->setInstr(0);
612 mi2iMap.erase(mi2iItr);
616 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
617 /// maps used by register allocator.
618 void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI) {
619 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
620 if (mi2iItr == mi2iMap.end())
622 SlotIndex replaceBaseIndex = mi2iItr->second;
623 IndexListEntry *miEntry(replaceBaseIndex.listEntry());
624 assert(miEntry->getInstr() == mi &&
625 "Mismatched instruction in index tables.");
626 miEntry->setInstr(newMI);
627 mi2iMap.erase(mi2iItr);
628 mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
631 /// Add the given MachineBasicBlock into the maps.
632 void insertMBBInMaps(MachineBasicBlock *mbb) {
633 MachineFunction::iterator nextMBB =
634 llvm::next(MachineFunction::iterator(mbb));
635 IndexListEntry *startEntry = createEntry(0, 0);
636 IndexListEntry *stopEntry = createEntry(0, 0);
637 IndexListEntry *nextEntry = 0;
639 if (nextMBB == mbb->getParent()->end()) {
640 nextEntry = indexList.end();
642 nextEntry = getMBBStartIdx(nextMBB).listEntry();
645 indexList.insert(nextEntry, startEntry);
646 indexList.insert(nextEntry, stopEntry);
648 SlotIndex startIdx(startEntry, SlotIndex::Slot_Block);
649 SlotIndex endIdx(nextEntry, SlotIndex::Slot_Block);
651 assert(unsigned(mbb->getNumber()) == MBBRanges.size() &&
652 "Blocks must be added in order");
653 MBBRanges.push_back(std::make_pair(startIdx, endIdx));
655 idx2MBBMap.push_back(IdxMBBPair(startIdx, mbb));
658 std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());
664 // Specialize IntervalMapInfo for half-open slot index intervals.
665 template <typename> struct IntervalMapInfo;
666 template <> struct IntervalMapInfo<SlotIndex> {
667 static inline bool startLess(const SlotIndex &x, const SlotIndex &a) {
670 static inline bool stopLess(const SlotIndex &b, const SlotIndex &x) {
673 static inline bool adjacent(const SlotIndex &a, const SlotIndex &b) {
680 #endif // LLVM_CODEGEN_SLOTINDEXES_H