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/ADT/DenseMap.h"
23 #include "llvm/ADT/IntervalMap.h"
24 #include "llvm/ADT/PointerIntPair.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/ilist.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstrBundle.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 : public ilist_node<IndexListEntry> {
44 IndexListEntry(MachineInstr *mi, unsigned index) : mi(mi), index(index) {}
46 MachineInstr* getInstr() const { return mi; }
47 void setInstr(MachineInstr *mi) {
51 unsigned getIndex() const { return index; }
52 void setIndex(unsigned index) {
59 struct ilist_traits<IndexListEntry> : public ilist_default_traits<IndexListEntry> {
61 mutable ilist_half_node<IndexListEntry> Sentinel;
63 IndexListEntry *createSentinel() const {
64 return static_cast<IndexListEntry*>(&Sentinel);
66 void destroySentinel(IndexListEntry *) const {}
68 IndexListEntry *provideInitialHead() const { return createSentinel(); }
69 IndexListEntry *ensureHead(IndexListEntry*) const { return createSentinel(); }
70 static void noteHead(IndexListEntry*, IndexListEntry*) {}
71 void deleteNode(IndexListEntry *N) {}
74 void createNode(const IndexListEntry &);
77 /// SlotIndex - An opaque wrapper around machine indexes.
79 friend class SlotIndexes;
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 unsigned 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());
126 /// The default distance between instructions as returned by distance().
127 /// This may vary as instructions are inserted and removed.
128 InstrDist = 4 * Slot_Count
131 /// Construct an invalid index.
132 SlotIndex() : lie(0, 0) {}
134 // Construct a new slot index from the given one, and set the slot.
135 SlotIndex(const SlotIndex &li, Slot s) : lie(li.listEntry(), unsigned(s)) {
136 assert(lie.getPointer() != 0 &&
137 "Attempt to construct index with 0 pointer.");
140 /// Returns true if this is a valid index. Invalid indicies do
141 /// not point into an index table, and cannot be compared.
142 bool isValid() const {
143 return lie.getPointer();
146 /// Return true for a valid index.
147 operator bool() const { return isValid(); }
149 /// Print this index to the given raw_ostream.
150 void print(raw_ostream &os) const;
152 /// Dump this index to stderr.
155 /// Compare two SlotIndex objects for equality.
156 bool operator==(SlotIndex other) const {
157 return lie == other.lie;
159 /// Compare two SlotIndex objects for inequality.
160 bool operator!=(SlotIndex other) const {
161 return lie != other.lie;
164 /// Compare two SlotIndex objects. Return true if the first index
165 /// is strictly lower than the second.
166 bool operator<(SlotIndex other) const {
167 return getIndex() < other.getIndex();
169 /// Compare two SlotIndex objects. Return true if the first index
170 /// is lower than, or equal to, 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 the second.
177 bool operator>(SlotIndex other) const {
178 return getIndex() > other.getIndex();
181 /// Compare two SlotIndex objects. Return true if the first index
182 /// is greater than, or equal to, the second.
183 bool operator>=(SlotIndex other) const {
184 return getIndex() >= other.getIndex();
187 /// isSameInstr - Return true if A and B refer to the same instruction.
188 static bool isSameInstr(SlotIndex A, SlotIndex B) {
189 return A.lie.getPointer() == B.lie.getPointer();
192 /// isEarlierInstr - Return true if A refers to an instruction earlier than
193 /// B. This is equivalent to A < B && !isSameInstr(A, B).
194 static bool isEarlierInstr(SlotIndex A, SlotIndex B) {
195 return A.listEntry()->getIndex() < B.listEntry()->getIndex();
198 /// Return the distance from this index to the given one.
199 int distance(SlotIndex other) const {
200 return other.getIndex() - getIndex();
203 /// isBlock - Returns true if this is a block boundary slot.
204 bool isBlock() const { return getSlot() == Slot_Block; }
206 /// isEarlyClobber - Returns true if this is an early-clobber slot.
207 bool isEarlyClobber() const { return getSlot() == Slot_EarlyClobber; }
209 /// isRegister - Returns true if this is a normal register use/def slot.
210 /// Note that early-clobber slots may also be used for uses and defs.
211 bool isRegister() const { return getSlot() == Slot_Register; }
213 /// isDead - Returns true if this is a dead def kill slot.
214 bool isDead() const { return getSlot() == Slot_Dead; }
216 /// Returns the base index for associated with this index. The base index
217 /// is the one associated with the Slot_Block slot for the instruction
218 /// pointed to by this index.
219 SlotIndex getBaseIndex() const {
220 return SlotIndex(listEntry(), Slot_Block);
223 /// Returns the boundary index for associated with this index. The boundary
224 /// index is the one associated with the Slot_Block slot for the instruction
225 /// pointed to by this index.
226 SlotIndex getBoundaryIndex() const {
227 return SlotIndex(listEntry(), Slot_Dead);
230 /// Returns the register use/def slot in the current instruction for a
231 /// normal or early-clobber def.
232 SlotIndex getRegSlot(bool EC = false) const {
233 return SlotIndex(listEntry(), EC ? Slot_EarlyClobber : Slot_Register);
236 /// Returns the dead def kill slot for the current instruction.
237 SlotIndex getDeadSlot() const {
238 return SlotIndex(listEntry(), Slot_Dead);
241 /// Returns the next slot in the index list. This could be either the
242 /// next slot for the instruction pointed to by this index or, if this
243 /// index is a STORE, the first slot for the next instruction.
244 /// WARNING: This method is considerably more expensive than the methods
245 /// that return specific slots (getUseIndex(), etc). If you can - please
246 /// use one of those methods.
247 SlotIndex getNextSlot() const {
249 if (s == Slot_Dead) {
250 return SlotIndex(listEntry()->getNextNode(), Slot_Block);
252 return SlotIndex(listEntry(), s + 1);
255 /// Returns the next index. This is the index corresponding to the this
256 /// index's slot, but for the next instruction.
257 SlotIndex getNextIndex() const {
258 return SlotIndex(listEntry()->getNextNode(), getSlot());
261 /// Returns the previous slot in the index list. This could be either the
262 /// previous slot for the instruction pointed to by this index or, if this
263 /// index is a Slot_Block, the last slot for the previous instruction.
264 /// WARNING: This method is considerably more expensive than the methods
265 /// that return specific slots (getUseIndex(), etc). If you can - please
266 /// use one of those methods.
267 SlotIndex getPrevSlot() const {
269 if (s == Slot_Block) {
270 return SlotIndex(listEntry()->getPrevNode(), Slot_Dead);
272 return SlotIndex(listEntry(), s - 1);
275 /// Returns the previous index. This is the index corresponding to this
276 /// index's slot, but for the previous instruction.
277 SlotIndex getPrevIndex() const {
278 return SlotIndex(listEntry()->getPrevNode(), getSlot());
283 template <> struct isPodLike<SlotIndex> { static const bool value = true; };
286 inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
291 typedef std::pair<SlotIndex, MachineBasicBlock*> IdxMBBPair;
293 inline bool operator<(SlotIndex V, const IdxMBBPair &IM) {
297 inline bool operator<(const IdxMBBPair &IM, SlotIndex V) {
301 struct Idx2MBBCompare {
302 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
303 return LHS.first < RHS.first;
307 /// SlotIndexes pass.
309 /// This pass assigns indexes to each instruction.
310 class SlotIndexes : public MachineFunctionPass {
313 typedef ilist<IndexListEntry> IndexList;
318 typedef DenseMap<const MachineInstr*, SlotIndex> Mi2IndexMap;
321 /// MBBRanges - Map MBB number to (start, stop) indexes.
322 SmallVector<std::pair<SlotIndex, SlotIndex>, 8> MBBRanges;
324 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
326 SmallVector<IdxMBBPair, 8> idx2MBBMap;
328 // IndexListEntry allocator.
329 BumpPtrAllocator ileAllocator;
331 IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
332 IndexListEntry *entry =
333 static_cast<IndexListEntry*>(
334 ileAllocator.Allocate(sizeof(IndexListEntry),
335 alignOf<IndexListEntry>()));
337 new (entry) IndexListEntry(mi, index);
342 /// Renumber locally after inserting curItr.
343 void renumberIndexes(IndexList::iterator curItr);
348 SlotIndexes() : MachineFunctionPass(ID) {
349 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
352 virtual void getAnalysisUsage(AnalysisUsage &au) const;
353 virtual void releaseMemory();
355 virtual bool runOnMachineFunction(MachineFunction &fn);
357 /// Dump the indexes.
360 /// Renumber the index list, providing space for new instructions.
361 void renumberIndexes();
363 /// Repair indexes after adding and removing instructions.
364 void repairIndexesInRange(MachineBasicBlock *MBB,
365 MachineBasicBlock::iterator Begin,
366 MachineBasicBlock::iterator End);
368 /// Returns the zero index for this analysis.
369 SlotIndex getZeroIndex() {
370 assert(indexList.front().getIndex() == 0 && "First index is not 0?");
371 return SlotIndex(&indexList.front(), 0);
374 /// Returns the base index of the last slot in this analysis.
375 SlotIndex getLastIndex() {
376 return SlotIndex(&indexList.back(), 0);
379 /// Returns true if the given machine instr is mapped to an index,
380 /// otherwise returns false.
381 bool hasIndex(const MachineInstr *instr) const {
382 return mi2iMap.count(instr);
385 /// Returns the base index for the given instruction.
386 SlotIndex getInstructionIndex(const MachineInstr *MI) const {
387 // Instructions inside a bundle have the same number as the bundle itself.
388 Mi2IndexMap::const_iterator itr = mi2iMap.find(getBundleStart(MI));
389 assert(itr != mi2iMap.end() && "Instruction not found in maps.");
393 /// Returns the instruction for the given index, or null if the given
394 /// index has no instruction associated with it.
395 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
396 return index.isValid() ? index.listEntry()->getInstr() : 0;
399 /// Returns the next non-null index, if one exists.
400 /// Otherwise returns getLastIndex().
401 SlotIndex getNextNonNullIndex(SlotIndex Index) {
402 IndexList::iterator I = Index.listEntry();
403 IndexList::iterator E = indexList.end();
406 return SlotIndex(I, Index.getSlot());
407 // We reached the end of the function.
408 return getLastIndex();
411 /// getIndexBefore - Returns the index of the last indexed instruction
412 /// before MI, or the start index of its basic block.
413 /// MI is not required to have an index.
414 SlotIndex getIndexBefore(const MachineInstr *MI) const {
415 const MachineBasicBlock *MBB = MI->getParent();
416 assert(MBB && "MI must be inserted inna basic block");
417 MachineBasicBlock::const_iterator I = MI, B = MBB->begin();
420 return getMBBStartIdx(MBB);
422 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
423 if (MapItr != mi2iMap.end())
424 return MapItr->second;
428 /// getIndexAfter - Returns the index of the first indexed instruction
429 /// after MI, or the end index of its basic block.
430 /// MI is not required to have an index.
431 SlotIndex getIndexAfter(const MachineInstr *MI) const {
432 const MachineBasicBlock *MBB = MI->getParent();
433 assert(MBB && "MI must be inserted inna basic block");
434 MachineBasicBlock::const_iterator I = MI, E = MBB->end();
438 return getMBBEndIdx(MBB);
439 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
440 if (MapItr != mi2iMap.end())
441 return MapItr->second;
445 /// Return the (start,end) range of the given basic block number.
446 const std::pair<SlotIndex, SlotIndex> &
447 getMBBRange(unsigned Num) const {
448 return MBBRanges[Num];
451 /// Return the (start,end) range of the given basic block.
452 const std::pair<SlotIndex, SlotIndex> &
453 getMBBRange(const MachineBasicBlock *MBB) const {
454 return getMBBRange(MBB->getNumber());
457 /// Returns the first index in the given basic block number.
458 SlotIndex getMBBStartIdx(unsigned Num) const {
459 return getMBBRange(Num).first;
462 /// Returns the first index in the given basic block.
463 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
464 return getMBBRange(mbb).first;
467 /// Returns the last index in the given basic block number.
468 SlotIndex getMBBEndIdx(unsigned Num) const {
469 return getMBBRange(Num).second;
472 /// Returns the last index in the given basic block.
473 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
474 return getMBBRange(mbb).second;
477 /// Returns the basic block which the given index falls in.
478 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
479 if (MachineInstr *MI = getInstructionFromIndex(index))
480 return MI->getParent();
481 SmallVectorImpl<IdxMBBPair>::const_iterator I =
482 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), index);
483 // Take the pair containing the index
484 SmallVectorImpl<IdxMBBPair>::const_iterator J =
485 ((I != idx2MBBMap.end() && I->first > index) ||
486 (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
488 assert(J != idx2MBBMap.end() && J->first <= index &&
489 index < getMBBEndIdx(J->second) &&
490 "index does not correspond to an MBB");
494 bool findLiveInMBBs(SlotIndex start, SlotIndex end,
495 SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
496 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
497 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
500 while (itr != idx2MBBMap.end()) {
501 if (itr->first >= end)
503 mbbs.push_back(itr->second);
510 /// Returns the MBB covering the given range, or null if the range covers
511 /// more than one basic block.
512 MachineBasicBlock* getMBBCoveringRange(SlotIndex start, SlotIndex end) const {
514 assert(start < end && "Backwards ranges not allowed.");
516 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
517 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
519 if (itr == idx2MBBMap.end()) {
524 // Check that we don't cross the boundary into this block.
525 if (itr->first < end)
530 if (itr->first <= start)
536 /// Insert the given machine instruction into the mapping. Returns the
538 /// If Late is set and there are null indexes between mi's neighboring
539 /// instructions, create the new index after the null indexes instead of
541 SlotIndex insertMachineInstrInMaps(MachineInstr *mi, bool Late = false) {
542 assert(!mi->isInsideBundle() &&
543 "Instructions inside bundles should use bundle start's slot.");
544 assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
545 // Numbering DBG_VALUE instructions could cause code generation to be
546 // affected by debug information.
547 assert(!mi->isDebugValue() && "Cannot number DBG_VALUE instructions.");
549 assert(mi->getParent() != 0 && "Instr must be added to function.");
551 // Get the entries where mi should be inserted.
552 IndexList::iterator prevItr, nextItr;
554 // Insert mi's index immediately before the following instruction.
555 nextItr = getIndexAfter(mi).listEntry();
556 prevItr = prior(nextItr);
558 // Insert mi's index immediately after the preceding instruction.
559 prevItr = getIndexBefore(mi).listEntry();
560 nextItr = llvm::next(prevItr);
563 // Get a number for the new instr, or 0 if there's no room currently.
564 // In the latter case we'll force a renumber later.
565 unsigned dist = ((nextItr->getIndex() - prevItr->getIndex())/2) & ~3u;
566 unsigned newNumber = prevItr->getIndex() + dist;
568 // Insert a new list entry for mi.
569 IndexList::iterator newItr =
570 indexList.insert(nextItr, createEntry(mi, newNumber));
572 // Renumber locally if we need to.
574 renumberIndexes(newItr);
576 SlotIndex newIndex(&*newItr, SlotIndex::Slot_Block);
577 mi2iMap.insert(std::make_pair(mi, newIndex));
581 /// Remove the given machine instruction from the mapping.
582 void removeMachineInstrFromMaps(MachineInstr *mi) {
583 // remove index -> MachineInstr and
584 // MachineInstr -> index mappings
585 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
586 if (mi2iItr != mi2iMap.end()) {
587 IndexListEntry *miEntry(mi2iItr->second.listEntry());
588 assert(miEntry->getInstr() == mi && "Instruction indexes broken.");
589 // FIXME: Eventually we want to actually delete these indexes.
590 miEntry->setInstr(0);
591 mi2iMap.erase(mi2iItr);
595 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
596 /// maps used by register allocator.
597 void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI) {
598 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
599 if (mi2iItr == mi2iMap.end())
601 SlotIndex replaceBaseIndex = mi2iItr->second;
602 IndexListEntry *miEntry(replaceBaseIndex.listEntry());
603 assert(miEntry->getInstr() == mi &&
604 "Mismatched instruction in index tables.");
605 miEntry->setInstr(newMI);
606 mi2iMap.erase(mi2iItr);
607 mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
610 /// Add the given MachineBasicBlock into the maps.
611 void insertMBBInMaps(MachineBasicBlock *mbb) {
612 MachineFunction::iterator nextMBB =
613 llvm::next(MachineFunction::iterator(mbb));
615 IndexListEntry *startEntry = 0;
616 IndexListEntry *endEntry = 0;
617 IndexList::iterator newItr;
618 if (nextMBB == mbb->getParent()->end()) {
619 startEntry = &indexList.back();
620 endEntry = createEntry(0, 0);
621 newItr = indexList.insertAfter(startEntry, endEntry);
623 startEntry = createEntry(0, 0);
624 endEntry = getMBBStartIdx(nextMBB).listEntry();
625 newItr = indexList.insert(endEntry, startEntry);
628 SlotIndex startIdx(startEntry, SlotIndex::Slot_Block);
629 SlotIndex endIdx(endEntry, SlotIndex::Slot_Block);
631 MachineFunction::iterator prevMBB(mbb);
632 assert(prevMBB != mbb->getParent()->end() &&
633 "Can't insert a new block at the beginning of a function.");
635 MBBRanges[prevMBB->getNumber()].second = startIdx;
637 assert(unsigned(mbb->getNumber()) == MBBRanges.size() &&
638 "Blocks must be added in order");
639 MBBRanges.push_back(std::make_pair(startIdx, endIdx));
640 idx2MBBMap.push_back(IdxMBBPair(startIdx, mbb));
642 renumberIndexes(newItr);
643 std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());
649 // Specialize IntervalMapInfo for half-open slot index intervals.
651 struct IntervalMapInfo<SlotIndex> : IntervalMapHalfOpenInfo<SlotIndex> {
656 #endif // LLVM_CODEGEN_SLOTINDEXES_H