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 /// Returns the zero index for this analysis.
364 SlotIndex getZeroIndex() {
365 assert(indexList.front().getIndex() == 0 && "First index is not 0?");
366 return SlotIndex(&indexList.front(), 0);
369 /// Returns the base index of the last slot in this analysis.
370 SlotIndex getLastIndex() {
371 return SlotIndex(&indexList.back(), 0);
374 /// Returns true if the given machine instr is mapped to an index,
375 /// otherwise returns false.
376 bool hasIndex(const MachineInstr *instr) const {
377 return mi2iMap.count(instr);
380 /// Returns the base index for the given instruction.
381 SlotIndex getInstructionIndex(const MachineInstr *MI) const {
382 // Instructions inside a bundle have the same number as the bundle itself.
383 Mi2IndexMap::const_iterator itr = mi2iMap.find(getBundleStart(MI));
384 assert(itr != mi2iMap.end() && "Instruction not found in maps.");
388 /// Returns the instruction for the given index, or null if the given
389 /// index has no instruction associated with it.
390 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
391 return index.isValid() ? index.listEntry()->getInstr() : 0;
394 /// Returns the next non-null index.
395 SlotIndex getNextNonNullIndex(SlotIndex index) {
396 IndexList::iterator itr(index.listEntry());
398 while (itr != indexList.end() && itr->getInstr() == 0) { ++itr; }
399 return SlotIndex(itr, index.getSlot());
402 /// getIndexBefore - Returns the index of the last indexed instruction
403 /// before MI, or the start index of its basic block.
404 /// MI is not required to have an index.
405 SlotIndex getIndexBefore(const MachineInstr *MI) const {
406 const MachineBasicBlock *MBB = MI->getParent();
407 assert(MBB && "MI must be inserted inna basic block");
408 MachineBasicBlock::const_iterator I = MI, B = MBB->begin();
411 return getMBBStartIdx(MBB);
413 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
414 if (MapItr != mi2iMap.end())
415 return MapItr->second;
419 /// getIndexAfter - Returns the index of the first indexed instruction
420 /// after MI, or the end index of its basic block.
421 /// MI is not required to have an index.
422 SlotIndex getIndexAfter(const MachineInstr *MI) const {
423 const MachineBasicBlock *MBB = MI->getParent();
424 assert(MBB && "MI must be inserted inna basic block");
425 MachineBasicBlock::const_iterator I = MI, E = MBB->end();
429 return getMBBEndIdx(MBB);
430 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
431 if (MapItr != mi2iMap.end())
432 return MapItr->second;
436 /// Return the (start,end) range of the given basic block number.
437 const std::pair<SlotIndex, SlotIndex> &
438 getMBBRange(unsigned Num) const {
439 return MBBRanges[Num];
442 /// Return the (start,end) range of the given basic block.
443 const std::pair<SlotIndex, SlotIndex> &
444 getMBBRange(const MachineBasicBlock *MBB) const {
445 return getMBBRange(MBB->getNumber());
448 /// Returns the first index in the given basic block number.
449 SlotIndex getMBBStartIdx(unsigned Num) const {
450 return getMBBRange(Num).first;
453 /// Returns the first index in the given basic block.
454 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
455 return getMBBRange(mbb).first;
458 /// Returns the last index in the given basic block number.
459 SlotIndex getMBBEndIdx(unsigned Num) const {
460 return getMBBRange(Num).second;
463 /// Returns the last index in the given basic block.
464 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
465 return getMBBRange(mbb).second;
468 /// Returns the basic block which the given index falls in.
469 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
470 if (MachineInstr *MI = getInstructionFromIndex(index))
471 return MI->getParent();
472 SmallVectorImpl<IdxMBBPair>::const_iterator I =
473 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), index);
474 // Take the pair containing the index
475 SmallVectorImpl<IdxMBBPair>::const_iterator J =
476 ((I != idx2MBBMap.end() && I->first > index) ||
477 (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
479 assert(J != idx2MBBMap.end() && J->first <= index &&
480 index < getMBBEndIdx(J->second) &&
481 "index does not correspond to an MBB");
485 bool findLiveInMBBs(SlotIndex start, SlotIndex end,
486 SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
487 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
488 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
491 while (itr != idx2MBBMap.end()) {
492 if (itr->first >= end)
494 mbbs.push_back(itr->second);
501 /// Returns the MBB covering the given range, or null if the range covers
502 /// more than one basic block.
503 MachineBasicBlock* getMBBCoveringRange(SlotIndex start, SlotIndex end) const {
505 assert(start < end && "Backwards ranges not allowed.");
507 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
508 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
510 if (itr == idx2MBBMap.end()) {
515 // Check that we don't cross the boundary into this block.
516 if (itr->first < end)
521 if (itr->first <= start)
527 /// Insert the given machine instruction into the mapping. Returns the
529 /// If Late is set and there are null indexes between mi's neighboring
530 /// instructions, create the new index after the null indexes instead of
532 SlotIndex insertMachineInstrInMaps(MachineInstr *mi, bool Late = false) {
533 assert(!mi->isInsideBundle() &&
534 "Instructions inside bundles should use bundle start's slot.");
535 assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
536 // Numbering DBG_VALUE instructions could cause code generation to be
537 // affected by debug information.
538 assert(!mi->isDebugValue() && "Cannot number DBG_VALUE instructions.");
540 assert(mi->getParent() != 0 && "Instr must be added to function.");
542 // Get the entries where mi should be inserted.
543 IndexList::iterator prevItr, nextItr;
545 // Insert mi's index immediately before the following instruction.
546 nextItr = getIndexAfter(mi).listEntry();
547 prevItr = prior(nextItr);
549 // Insert mi's index immediately after the preceding instruction.
550 prevItr = getIndexBefore(mi).listEntry();
551 nextItr = llvm::next(prevItr);
554 // Get a number for the new instr, or 0 if there's no room currently.
555 // In the latter case we'll force a renumber later.
556 unsigned dist = ((nextItr->getIndex() - prevItr->getIndex())/2) & ~3u;
557 unsigned newNumber = prevItr->getIndex() + dist;
559 // Insert a new list entry for mi.
560 IndexList::iterator newItr =
561 indexList.insert(nextItr, createEntry(mi, newNumber));
563 // Renumber locally if we need to.
565 renumberIndexes(newItr);
567 SlotIndex newIndex(&*newItr, SlotIndex::Slot_Block);
568 mi2iMap.insert(std::make_pair(mi, newIndex));
572 /// Remove the given machine instruction from the mapping.
573 void removeMachineInstrFromMaps(MachineInstr *mi) {
574 // remove index -> MachineInstr and
575 // MachineInstr -> index mappings
576 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
577 if (mi2iItr != mi2iMap.end()) {
578 IndexListEntry *miEntry(mi2iItr->second.listEntry());
579 assert(miEntry->getInstr() == mi && "Instruction indexes broken.");
580 // FIXME: Eventually we want to actually delete these indexes.
581 miEntry->setInstr(0);
582 mi2iMap.erase(mi2iItr);
586 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
587 /// maps used by register allocator.
588 void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI) {
589 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
590 if (mi2iItr == mi2iMap.end())
592 SlotIndex replaceBaseIndex = mi2iItr->second;
593 IndexListEntry *miEntry(replaceBaseIndex.listEntry());
594 assert(miEntry->getInstr() == mi &&
595 "Mismatched instruction in index tables.");
596 miEntry->setInstr(newMI);
597 mi2iMap.erase(mi2iItr);
598 mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
601 /// Add the given MachineBasicBlock into the maps.
602 void insertMBBInMaps(MachineBasicBlock *mbb) {
603 MachineFunction::iterator nextMBB =
604 llvm::next(MachineFunction::iterator(mbb));
606 IndexListEntry *startEntry = 0;
607 IndexListEntry *endEntry = 0;
608 IndexList::iterator newItr;
609 if (nextMBB == mbb->getParent()->end()) {
610 startEntry = &indexList.back();
611 endEntry = createEntry(0, 0);
612 newItr = indexList.insertAfter(startEntry, endEntry);
614 startEntry = createEntry(0, 0);
615 endEntry = getMBBStartIdx(nextMBB).listEntry();
616 newItr = indexList.insert(endEntry, startEntry);
619 SlotIndex startIdx(startEntry, SlotIndex::Slot_Block);
620 SlotIndex endIdx(endEntry, SlotIndex::Slot_Block);
622 MachineFunction::iterator prevMBB(mbb);
623 assert(prevMBB != mbb->getParent()->end() &&
624 "Can't insert a new block at the beginning of a function.");
626 MBBRanges[prevMBB->getNumber()].second = startIdx;
628 assert(unsigned(mbb->getNumber()) == MBBRanges.size() &&
629 "Blocks must be added in order");
630 MBBRanges.push_back(std::make_pair(startIdx, endIdx));
631 idx2MBBMap.push_back(IdxMBBPair(startIdx, mbb));
633 renumberIndexes(newItr);
634 std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());
640 // Specialize IntervalMapInfo for half-open slot index intervals.
642 struct IntervalMapInfo<SlotIndex> : IntervalMapHalfOpenInfo<SlotIndex> {
647 #endif // LLVM_CODEGEN_SLOTINDEXES_H