Use instruction itinerary to determine what instructions are 'cheap'.
[oota-llvm.git] / include / llvm / CodeGen / SlotIndexes.h
index 3f175a7241dd1af5fd2ad830e2d6e6d5428633fe..98426f019c194c7ccfdaf066b1b3d7dc78070b09 100644 (file)
 //
 // SlotIndex is mostly a proxy for entries of the SlotIndexList, a class which
 // is held is LiveIntervals and provides the real numbering. This allows
-// LiveIntervals to perform largely transparent renumbering. The SlotIndex
-// class does hold a PHI bit, which determines whether the index relates to a
-// PHI use or def point, or an actual instruction. See the SlotIndex class
-// description for futher information.
+// LiveIntervals to perform largely transparent renumbering.
 //===----------------------------------------------------------------------===//
 
 #ifndef LLVM_CODEGEN_SLOTINDEXES_H
 #define LLVM_CODEGEN_SLOTINDEXES_H
 
-#include "llvm/ADT/PointerIntPair.h"
-#include "llvm/ADT/SmallVector.h"
 #include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
-#include "llvm/CodeGen/MachineInstr.h"
+#include "llvm/ADT/PointerIntPair.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/Support/Allocator.h"
 
 namespace llvm {
@@ -36,30 +34,77 @@ namespace llvm {
   /// SlotIndex & SlotIndexes classes for the public interface to this
   /// information.
   class IndexListEntry {
-  private:
+    static const unsigned EMPTY_KEY_INDEX = ~0U & ~3U,
+                          TOMBSTONE_KEY_INDEX = ~0U & ~7U;
 
     IndexListEntry *next, *prev;
     MachineInstr *mi;
     unsigned index;
 
+  protected:
+
+    typedef enum { EMPTY_KEY, TOMBSTONE_KEY } ReservedEntryType;
+
+    // This constructor is only to be used by getEmptyKeyEntry
+    // & getTombstoneKeyEntry. It sets index to the given
+    // value and mi to zero.
+    IndexListEntry(ReservedEntryType r) : mi(0) {
+      switch(r) {
+        case EMPTY_KEY: index = EMPTY_KEY_INDEX; break;
+        case TOMBSTONE_KEY: index = TOMBSTONE_KEY_INDEX; break;
+        default: assert(false && "Invalid value for constructor."); 
+      }
+      next = this;
+      prev = this;
+    }
+
   public:
 
-    IndexListEntry(MachineInstr *mi, unsigned index)
-      : mi(mi), index(index) {}
+    IndexListEntry(MachineInstr *mi, unsigned index) : mi(mi), index(index) {
+      assert(index != EMPTY_KEY_INDEX && index != TOMBSTONE_KEY_INDEX &&
+             "Attempt to create invalid index. "
+             "Available indexes may have been exhausted?.");
+    }
+
+    bool isValid() const {
+      return (index != EMPTY_KEY_INDEX && index != TOMBSTONE_KEY_INDEX);
+    }
 
     MachineInstr* getInstr() const { return mi; }
-    void setInstr(MachineInstr *mi) { this->mi = mi; }
+    void setInstr(MachineInstr *mi) {
+      assert(isValid() && "Attempt to modify reserved index.");
+      this->mi = mi;
+    }
 
     unsigned getIndex() const { return index; }
-    void setIndex(unsigned index) { this->index = index; }
+    void setIndex(unsigned index) {
+      assert(index != EMPTY_KEY_INDEX && index != TOMBSTONE_KEY_INDEX &&
+             "Attempt to set index to invalid value.");
+      assert(isValid() && "Attempt to reset reserved index value.");
+      this->index = index;
+    }
     
     IndexListEntry* getNext() { return next; }
     const IndexListEntry* getNext() const { return next; }
-    void setNext(IndexListEntry *next) { this->next = next; }
+    void setNext(IndexListEntry *next) {
+      assert(isValid() && "Attempt to modify reserved index.");
+      this->next = next;
+    }
 
     IndexListEntry* getPrev() { return prev; }
     const IndexListEntry* getPrev() const { return prev; }
-    void setPrev(IndexListEntry *prev) { this->prev = prev; }
+    void setPrev(IndexListEntry *prev) {
+      assert(isValid() && "Attempt to modify reserved index.");
+      this->prev = prev;
+    }
+
+    // This function returns the index list entry that is to be used for empty
+    // SlotIndex keys.
+    static IndexListEntry* getEmptyKeyEntry();
+
+    // This function returns the index list entry that is to be used for
+    // tombstone SlotIndex keys.
+    static IndexListEntry* getTombstoneKeyEntry();
   };
 
   // Specialize PointerLikeTypeTraits for IndexListEntry.
@@ -78,24 +123,18 @@ namespace llvm {
   /// SlotIndex - An opaque wrapper around machine indexes.
   class SlotIndex {
     friend class SlotIndexes;
-    friend class DenseMapInfo<SlotIndex>;
+    friend struct DenseMapInfo<SlotIndex>;
 
-  private:
-
-    // FIXME: Is there any way to statically allocate these things and have
-    // them 8-byte aligned?
-    static std::auto_ptr<IndexListEntry> emptyKeyPtr, tombstoneKeyPtr;
-    static const unsigned PHI_BIT = 1 << 2;
+    enum Slot { LOAD, USE, DEF, STORE, NUM };
 
-    PointerIntPair<IndexListEntry*, 3, unsigned> lie;
+    PointerIntPair<IndexListEntry*, 2, unsigned> lie;
 
-    SlotIndex(IndexListEntry *entry, unsigned phiAndSlot)
-      : lie(entry, phiAndSlot) {
+    SlotIndex(IndexListEntry *entry, unsigned slot)
+      : lie(entry, slot) {
       assert(entry != 0 && "Attempt to construct index with 0 pointer.");
     }
 
     IndexListEntry& entry() const {
-      assert(lie.getPointer() != 0 && "Use of invalid index.");
       return *lie.getPointer();
     }
 
@@ -103,6 +142,11 @@ namespace llvm {
       return entry().getIndex() | getSlot();
     }
 
+    /// Returns the slot for this SlotIndex.
+    Slot getSlot() const {
+      return static_cast<Slot>(lie.getInt());
+    }
+
     static inline unsigned getHashValue(const SlotIndex &v) {
       IndexListEntry *ptrVal = &v.entry();
       return (unsigned((intptr_t)ptrVal) >> 4) ^
@@ -110,44 +154,20 @@ namespace llvm {
     }
 
   public:
-
-    // FIXME: Ugh. This is public because LiveIntervalAnalysis is still using it
-    // for some spill weight stuff. Fix that, then make this private.
-    enum Slot { LOAD, USE, DEF, STORE, NUM };
-
     static inline SlotIndex getEmptyKey() {
-      // FIXME: How do we guarantee these numbers don't get allocated to
-      // legit indexes?
-      if (emptyKeyPtr.get() == 0)
-        emptyKeyPtr.reset(new IndexListEntry(0, ~0U & ~3U));
-
-      return SlotIndex(emptyKeyPtr.get(), 0);
+      return SlotIndex(IndexListEntry::getEmptyKeyEntry(), 0);
     }
 
     static inline SlotIndex getTombstoneKey() {
-      // FIXME: How do we guarantee these numbers don't get allocated to
-      // legit indexes?
-      if (tombstoneKeyPtr.get() == 0)
-        tombstoneKeyPtr.reset(new IndexListEntry(0, ~0U & ~7U));
-
-      return SlotIndex(tombstoneKeyPtr.get(), 0);
+      return SlotIndex(IndexListEntry::getTombstoneKeyEntry(), 0);
     }
-    
-    /// Construct an invalid index.
-    SlotIndex() : lie(&getEmptyKey().entry(), 0) {}
 
-    // Construct a new slot index from the given one, set the phi flag on the
-    // new index to the value of the phi parameter.
-    SlotIndex(const SlotIndex &li, bool phi)
-      : lie(&li.entry(), phi ? PHI_BIT & li.getSlot() : (unsigned)li.getSlot()){
-      assert(lie.getPointer() != 0 &&
-             "Attempt to construct index with 0 pointer.");
-    }
+    /// Construct an invalid index.
+    SlotIndex() : lie(IndexListEntry::getEmptyKeyEntry(), 0) {}
 
-    // Construct a new slot index from the given one, set the phi flag on the
-    // new index to the value of the phi parameter, and the slot to the new slot.
-    SlotIndex(const SlotIndex &li, bool phi, Slot s)
-      : lie(&li.entry(), phi ? PHI_BIT & s : (unsigned)s) {
+    // Construct a new slot index from the given one, and set the slot.
+    SlotIndex(const SlotIndex &li, Slot s)
+      : lie(&li.entry(), unsigned(s)) {
       assert(lie.getPointer() != 0 &&
              "Attempt to construct index with 0 pointer.");
     }
@@ -155,7 +175,8 @@ namespace llvm {
     /// Returns true if this is a valid index. Invalid indicies do
     /// not point into an index table, and cannot be compared.
     bool isValid() const {
-      return (lie.getPointer() != 0) && (lie.getPointer()->getIndex() != 0);
+      IndexListEntry *entry = lie.getPointer();
+      return ((entry!= 0) && (entry->isValid()));
     }
 
     /// Print this index to the given raw_ostream.
@@ -201,14 +222,24 @@ namespace llvm {
       return other.getIndex() - getIndex();
     }
 
-    /// Returns the slot for this SlotIndex.
-    Slot getSlot() const {
-      return static_cast<Slot>(lie.getInt()  & ~PHI_BIT);
+    /// isLoad - Return true if this is a LOAD slot.
+    bool isLoad() const {
+      return getSlot() == LOAD;
     }
 
-    /// Returns the state of the PHI bit.
-    bool isPHI() const {
-      return lie.getInt() & PHI_BIT;
+    /// isDef - Return true if this is a DEF slot.
+    bool isDef() const {
+      return getSlot() == DEF;
+    }
+
+    /// isUse - Return true if this is a USE slot.
+    bool isUse() const {
+      return getSlot() == USE;
+    }
+
+    /// isStore - Return true if this is a STORE slot.
+    bool isStore() const {
+      return getSlot() == STORE;
     }
 
     /// Returns the base index for associated with this index. The base index
@@ -306,8 +337,10 @@ namespace llvm {
     static inline bool isEqual(const SlotIndex &LHS, const SlotIndex &RHS) {
       return (LHS == RHS);
     }
-    static inline bool isPod() { return false; }
   };
+  
+  template <> struct isPodLike<SlotIndex> { static const bool value = true; };
+
 
   inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
     li.print(os);
@@ -353,9 +386,6 @@ namespace llvm {
     /// and MBB id.
     std::vector<IdxMBBPair> idx2MBBMap;
 
-    typedef DenseMap<const MachineBasicBlock*, SlotIndex> TerminatorGapsMap;
-    TerminatorGapsMap terminatorGaps;
-
     // IndexListEntry allocator.
     BumpPtrAllocator ileAllocator;
 
@@ -439,7 +469,9 @@ namespace llvm {
   public:
     static char ID;
 
-    SlotIndexes() : MachineFunctionPass(&ID), indexListHead(0) {}
+    SlotIndexes() : MachineFunctionPass(ID), indexListHead(0) {
+      initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
+    }
 
     virtual void getAnalysisUsage(AnalysisUsage &au) const;
     virtual void releaseMemory(); 
@@ -450,7 +482,7 @@ namespace llvm {
     void dump() const;
 
     /// Renumber the index list, providing space for new instructions.
-    void renumber();
+    void renumberIndexes();
 
     /// Returns the zero index for this analysis.
     SlotIndex getZeroIndex() {
@@ -458,6 +490,11 @@ namespace llvm {
       return SlotIndex(front(), 0);
     }
 
+    /// Returns the base index of the last slot in this analysis.
+    SlotIndex getLastIndex() {
+      return SlotIndex(back(), 0);
+    }
+
     /// Returns the invalid index marker for this analysis.
     SlotIndex getInvalidIndex() {
       return getZeroIndex();
@@ -522,14 +559,6 @@ namespace llvm {
       return itr->second.second;
     }
 
-    /// Returns the terminator gap for the given index.
-    SlotIndex getTerminatorGap(const MachineBasicBlock *mbb) {
-      TerminatorGapsMap::iterator itr = terminatorGaps.find(mbb);
-      assert(itr != terminatorGaps.end() &&
-             "All MBBs should have terminator gaps in their indexes.");
-      return itr->second;
-    }
-
     /// Returns the basic block which the given index falls in.
     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
       std::vector<IdxMBBPair>::const_iterator I =
@@ -540,7 +569,7 @@ namespace llvm {
          (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
 
       assert(J != idx2MBBMap.end() && J->first <= index &&
-             index <= getMBBEndIdx(J->second) &&
+             index < getMBBEndIdx(J->second) &&
              "index does not correspond to an MBB");
       return J->second;
     }
@@ -610,99 +639,94 @@ namespace llvm {
       return 0;
     }
 
-    /// Returns true if there is a gap in the numbering before the given index.
-    bool hasGapBeforeInstr(SlotIndex index) {
-      index = index.getBaseIndex();
-      SlotIndex prevIndex = index.getPrevIndex();
-      
-      if (prevIndex == getZeroIndex())
-        return false;
-
-      if (getInstructionFromIndex(prevIndex) == 0)
-        return true;
-
-      if (prevIndex.distance(index) >= 2 * SlotIndex::NUM)
-        return true;
-
-      return false;
-    }
-
-    /// Returns true if there is a gap in the numbering after the given index.
-    bool hasGapAfterInstr(SlotIndex index) const {
-      // Not implemented yet.
-      assert(false &&
-             "SlotIndexes::hasGapAfterInstr(SlotIndex) not implemented yet.");
-      return false;
-    }
+    /// Insert the given machine instruction into the mapping. Returns the
+    /// assigned index.
+    SlotIndex insertMachineInstrInMaps(MachineInstr *mi,
+                                        bool *deferredRenumber = 0) {
+      assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
 
-    /// findGapBeforeInstr - Find an empty instruction slot before the
-    /// specified index. If "Furthest" is true, find one that's furthest
-    /// away from the index (but before any index that's occupied).
-    // FIXME: This whole method should go away in future. It should
-    // always be possible to insert code between existing indices.
-    SlotIndex findGapBeforeInstr(SlotIndex index, bool furthest = false) {
-      if (index == getZeroIndex())
-        return getInvalidIndex();
+      MachineBasicBlock *mbb = mi->getParent();
 
-      index = index.getBaseIndex();
-      SlotIndex prevIndex = index.getPrevIndex();
+      assert(mbb != 0 && "Instr must be added to function.");
 
-      if (prevIndex == getZeroIndex())
-        return getInvalidIndex();
+      MBB2IdxMap::iterator mbbRangeItr = mbb2IdxMap.find(mbb);
 
-      // Try to reuse existing index objects with null-instrs.
-      if (getInstructionFromIndex(prevIndex) == 0) {
-        if (furthest) {
-          while (getInstructionFromIndex(prevIndex) == 0 &&
-                 prevIndex != getZeroIndex()) {
-            prevIndex = prevIndex.getPrevIndex();
-          }
+      assert(mbbRangeItr != mbb2IdxMap.end() &&
+             "Instruction's parent MBB has not been added to SlotIndexes.");
 
-          prevIndex = prevIndex.getNextIndex();
+      MachineBasicBlock::iterator miItr(mi);
+      bool needRenumber = false;
+      IndexListEntry *newEntry;
+      // Get previous index, considering that not all instructions are indexed.
+      IndexListEntry *prevEntry;
+      for (;;) {
+        // If mi is at the mbb beginning, get the prev index from the mbb.
+        if (miItr == mbb->begin()) {
+          prevEntry = &mbbRangeItr->second.first.entry();
+          break;
+        }
+        // Otherwise rewind until we find a mapped instruction.
+        Mi2IndexMap::const_iterator itr = mi2iMap.find(--miItr);
+        if (itr != mi2iMap.end()) {
+          prevEntry = &itr->second.entry();
+          break;
         }
-        assert(getInstructionFromIndex(prevIndex) == 0 && "Index list is broken.");
-
-        return prevIndex;
       }
 
-      int dist = prevIndex.distance(index);
+      // Get next entry from previous entry.
+      IndexListEntry *nextEntry = prevEntry->getNext();
 
-      // Double check that the spacing between this instruction and
-      // the last is sane.
-      assert(dist >= SlotIndex::NUM &&
-             "Distance between indexes too small.");
+      // Get a number for the new instr, or 0 if there's no room currently.
+      // In the latter case we'll force a renumber later.
+      unsigned dist = nextEntry->getIndex() - prevEntry->getIndex();
+      unsigned newNumber = dist > SlotIndex::NUM ?
+        prevEntry->getIndex() + ((dist >> 1) & ~3U) : 0;
 
-      // If there's no gap return an invalid index.
-      if (dist < 2*SlotIndex::NUM) {
-        return getInvalidIndex();
+      if (newNumber == 0) {
+        needRenumber = true;
       }
 
-      // Otherwise insert new index entries into the list using the
-      // gap in the numbering.
-      IndexListEntry *newEntry =
-        createEntry(0, prevIndex.entry().getIndex() + SlotIndex::NUM);
+      // Insert a new list entry for mi.
+      newEntry = createEntry(mi, newNumber);
+      insert(nextEntry, newEntry);
+  
+      SlotIndex newIndex(newEntry, SlotIndex::LOAD);
+      mi2iMap.insert(std::make_pair(mi, newIndex));
+
+      if (miItr == mbb->end()) {
+        // If this is the last instr in the MBB then we need to fix up the bb
+        // range:
+        mbbRangeItr->second.second = SlotIndex(newEntry, SlotIndex::STORE);
+      }
 
-      insert(&index.entry(), newEntry);
+      // Renumber if we need to.
+      if (needRenumber) {
+        if (deferredRenumber == 0)
+          renumberIndexes();
+        else
+          *deferredRenumber = true;
+      }
 
-      // And return a pointer to the entry at the start of the gap.
-      return index.getPrevIndex();
+      return newIndex;
     }
 
-    /// Insert the given machine instruction into the mapping at the given
-    /// index.
-    void insertMachineInstrInMaps(MachineInstr *mi, SlotIndex index) {
-      index = index.getBaseIndex();
-      IndexListEntry *miEntry = &index.entry();
-      assert(miEntry->getInstr() == 0 && "Index already in use.");
-      miEntry->setInstr(mi);
+    /// Add all instructions in the vector to the index list. This method will
+    /// defer renumbering until all instrs have been added, and should be 
+    /// preferred when adding multiple instrs.
+    void insertMachineInstrsInMaps(SmallVectorImpl<MachineInstr*> &mis) {
+      bool renumber = false;
 
-      assert(mi2iMap.find(mi) == mi2iMap.end() &&
-             "MachineInstr already has an index.");
+      for (SmallVectorImpl<MachineInstr*>::iterator
+           miItr = mis.begin(), miEnd = mis.end();
+           miItr != miEnd; ++miItr) {
+        insertMachineInstrInMaps(*miItr, &renumber);
+      }
 
-      mi2iMap.insert(std::make_pair(mi, index));
+      if (renumber)
+        renumberIndexes();
     }
 
+
     /// Remove the given machine instruction from the mapping.
     void removeMachineInstrFromMaps(MachineInstr *mi) {
       // remove index -> MachineInstr and
@@ -732,6 +756,41 @@ namespace llvm {
       mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
     }
 
+    /// Add the given MachineBasicBlock into the maps.
+    void insertMBBInMaps(MachineBasicBlock *mbb) {
+      MachineFunction::iterator nextMBB =
+        llvm::next(MachineFunction::iterator(mbb));
+      IndexListEntry *startEntry = createEntry(0, 0);
+      IndexListEntry *nextEntry = 0;
+
+      if (nextMBB == mbb->getParent()->end()) {
+        nextEntry = getTail();
+      } else {
+        nextEntry = &getMBBStartIdx(nextMBB).entry();
+      }
+
+      insert(nextEntry, startEntry);
+
+      SlotIndex startIdx(startEntry, SlotIndex::LOAD);
+      SlotIndex endIdx(nextEntry, SlotIndex::LOAD);
+
+      mbb2IdxMap.insert(
+        std::make_pair(mbb, std::make_pair(startIdx, endIdx)));
+
+      idx2MBBMap.push_back(IdxMBBPair(startIdx, mbb));
+
+      if (MachineFunction::iterator(mbb) != mbb->getParent()->begin()) {
+        // Have to update the end index of the previous block.
+        MachineBasicBlock *priorMBB =
+          llvm::prior(MachineFunction::iterator(mbb));
+        mbb2IdxMap[priorMBB].second = startIdx;
+      }
+
+      renumberIndexes();
+      std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());
+
+    }
+
   };