1//===-- LiveIntervalAnalysis.h - Live Interval Analysis ---------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LiveInterval analysis pass.  Given some numbering of
11// each the machine instructions (in this implemention depth-first order) an
12// interval [i, j) is said to be a live interval for register v if there is no
13// instruction with number j' > j such that v is live at j' and there is no
14// instruction with number i' < i such that v is live at i'. In this
15// implementation intervals can have holes, i.e. an interval might look like
16// [1,20), [50,65), [1000,1001).
17//
18//===----------------------------------------------------------------------===//
19
20#ifndef LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
21#define LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
22
23#include "llvm/Target/TargetRegisterInfo.h"
24#include "llvm/CodeGen/MachineBasicBlock.h"
25#include "llvm/CodeGen/MachineFunctionPass.h"
26#include "llvm/CodeGen/LiveInterval.h"
27#include "llvm/CodeGen/SlotIndexes.h"
28#include "llvm/ADT/BitVector.h"
29#include "llvm/ADT/IndexedMap.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/Support/Allocator.h"
33#include <cmath>
34#include <iterator>
35
36namespace llvm {
37
38  class AliasAnalysis;
39  class LiveRangeCalc;
40  class LiveVariables;
41  class MachineDominatorTree;
42  class MachineLoopInfo;
43  class TargetRegisterInfo;
44  class MachineRegisterInfo;
45  class TargetInstrInfo;
46  class TargetRegisterClass;
47  class VirtRegMap;
48
49  class LiveIntervals : public MachineFunctionPass {
50    MachineFunction* MF;
51    MachineRegisterInfo* MRI;
52    const TargetMachine* TM;
53    const TargetRegisterInfo* TRI;
54    const TargetInstrInfo* TII;
55    AliasAnalysis *AA;
56    LiveVariables* LV;
57    SlotIndexes* Indexes;
58    MachineDominatorTree *DomTree;
59    LiveRangeCalc *LRCalc;
60
61    /// Special pool allocator for VNInfo's (LiveInterval val#).
62    ///
63    VNInfo::Allocator VNInfoAllocator;
64
65    /// Live interval pointers for all the virtual registers.
66    IndexedMap<LiveInterval*, VirtReg2IndexFunctor> VirtRegIntervals;
67
68    /// RegMaskSlots - Sorted list of instructions with register mask operands.
69    /// Always use the 'r' slot, RegMasks are normal clobbers, not early
70    /// clobbers.
71    SmallVector<SlotIndex, 8> RegMaskSlots;
72
73    /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
74    /// pointer to the corresponding register mask.  This pointer can be
75    /// recomputed as:
76    ///
77    ///   MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
78    ///   unsigned OpNum = findRegMaskOperand(MI);
79    ///   RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
80    ///
81    /// This is kept in a separate vector partly because some standard
82    /// libraries don't support lower_bound() with mixed objects, partly to
83    /// improve locality when searching in RegMaskSlots.
84    /// Also see the comment in LiveInterval::find().
85    SmallVector<const uint32_t*, 8> RegMaskBits;
86
87    /// For each basic block number, keep (begin, size) pairs indexing into the
88    /// RegMaskSlots and RegMaskBits arrays.
89    /// Note that basic block numbers may not be layout contiguous, that's why
90    /// we can't just keep track of the first register mask in each basic
91    /// block.
92    SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
93
94    /// RegUnitIntervals - Keep a live interval for each register unit as a way
95    /// of tracking fixed physreg interference.
96    SmallVector<LiveInterval*, 0> RegUnitIntervals;
97
98  public:
99    static char ID; // Pass identification, replacement for typeid
100    LiveIntervals();
101    virtual ~LiveIntervals();
102
103    // Calculate the spill weight to assign to a single instruction.
104    static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
105
106    LiveInterval &getInterval(unsigned Reg) {
107      LiveInterval *LI = VirtRegIntervals[Reg];
108      assert(LI && "Interval does not exist for virtual register");
109      return *LI;
110    }
111
112    const LiveInterval &getInterval(unsigned Reg) const {
113      return const_cast<LiveIntervals*>(this)->getInterval(Reg);
114    }
115
116    bool hasInterval(unsigned Reg) const {
117      return VirtRegIntervals.inBounds(Reg) && VirtRegIntervals[Reg];
118    }
119
120    // Interval creation.
121    LiveInterval &getOrCreateInterval(unsigned Reg) {
122      if (!hasInterval(Reg)) {
123        VirtRegIntervals.grow(Reg);
124        VirtRegIntervals[Reg] = createInterval(Reg);
125      }
126      return getInterval(Reg);
127    }
128
129    // Interval removal.
130    void removeInterval(unsigned Reg) {
131      delete VirtRegIntervals[Reg];
132      VirtRegIntervals[Reg] = 0;
133    }
134
135    /// addLiveRangeToEndOfBlock - Given a register and an instruction,
136    /// adds a live range from that instruction to the end of its MBB.
137    LiveRange addLiveRangeToEndOfBlock(unsigned reg,
138                                       MachineInstr* startInst);
139
140    /// shrinkToUses - After removing some uses of a register, shrink its live
141    /// range to just the remaining uses. This method does not compute reaching
142    /// defs for new uses, and it doesn't remove dead defs.
143    /// Dead PHIDef values are marked as unused.
144    /// New dead machine instructions are added to the dead vector.
145    /// Return true if the interval may have been separated into multiple
146    /// connected components.
147    bool shrinkToUses(LiveInterval *li,
148                      SmallVectorImpl<MachineInstr*> *dead = 0);
149
150    /// extendToIndices - Extend the live range of LI to reach all points in
151    /// Indices. The points in the Indices array must be jointly dominated by
152    /// existing defs in LI. PHI-defs are added as needed to maintain SSA form.
153    ///
154    /// If a SlotIndex in Indices is the end index of a basic block, LI will be
155    /// extended to be live out of the basic block.
156    ///
157    /// See also LiveRangeCalc::extend().
158    void extendToIndices(LiveInterval *LI, ArrayRef<SlotIndex> Indices);
159
160    /// pruneValue - If an LI value is live at Kill, prune its live range by
161    /// removing any liveness reachable from Kill. Add live range end points to
162    /// EndPoints such that extendToIndices(LI, EndPoints) will reconstruct the
163    /// value's live range.
164    ///
165    /// Calling pruneValue() and extendToIndices() can be used to reconstruct
166    /// SSA form after adding defs to a virtual register.
167    void pruneValue(LiveInterval *LI, SlotIndex Kill,
168                    SmallVectorImpl<SlotIndex> *EndPoints);
169
170    SlotIndexes *getSlotIndexes() const {
171      return Indexes;
172    }
173
174    AliasAnalysis *getAliasAnalysis() const {
175      return AA;
176    }
177
178    /// isNotInMIMap - returns true if the specified machine instr has been
179    /// removed or was never entered in the map.
180    bool isNotInMIMap(const MachineInstr* Instr) const {
181      return !Indexes->hasIndex(Instr);
182    }
183
184    /// Returns the base index of the given instruction.
185    SlotIndex getInstructionIndex(const MachineInstr *instr) const {
186      return Indexes->getInstructionIndex(instr);
187    }
188
189    /// Returns the instruction associated with the given index.
190    MachineInstr* getInstructionFromIndex(SlotIndex index) const {
191      return Indexes->getInstructionFromIndex(index);
192    }
193
194    /// Return the first index in the given basic block.
195    SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
196      return Indexes->getMBBStartIdx(mbb);
197    }
198
199    /// Return the last index in the given basic block.
200    SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
201      return Indexes->getMBBEndIdx(mbb);
202    }
203
204    bool isLiveInToMBB(const LiveInterval &li,
205                       const MachineBasicBlock *mbb) const {
206      return li.liveAt(getMBBStartIdx(mbb));
207    }
208
209    bool isLiveOutOfMBB(const LiveInterval &li,
210                        const MachineBasicBlock *mbb) const {
211      return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
212    }
213
214    MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
215      return Indexes->getMBBFromIndex(index);
216    }
217
218    SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
219      return Indexes->insertMachineInstrInMaps(MI);
220    }
221
222    void RemoveMachineInstrFromMaps(MachineInstr *MI) {
223      Indexes->removeMachineInstrFromMaps(MI);
224    }
225
226    void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
227      Indexes->replaceMachineInstrInMaps(MI, NewMI);
228    }
229
230    bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
231                        SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
232      return Indexes->findLiveInMBBs(Start, End, MBBs);
233    }
234
235    VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
236
237    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
238    virtual void releaseMemory();
239
240    /// runOnMachineFunction - pass entry point
241    virtual bool runOnMachineFunction(MachineFunction&);
242
243    /// print - Implement the dump method.
244    virtual void print(raw_ostream &O, const Module* = 0) const;
245
246    /// intervalIsInOneMBB - If LI is confined to a single basic block, return
247    /// a pointer to that block.  If LI is live in to or out of any block,
248    /// return NULL.
249    MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
250
251    /// Returns true if VNI is killed by any PHI-def values in LI.
252    /// This may conservatively return true to avoid expensive computations.
253    bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const;
254
255    /// addKillFlags - Add kill flags to any instruction that kills a virtual
256    /// register.
257    void addKillFlags(const VirtRegMap*);
258
259    /// handleMove - call this method to notify LiveIntervals that
260    /// instruction 'mi' has been moved within a basic block. This will update
261    /// the live intervals for all operands of mi. Moves between basic blocks
262    /// are not supported.
263    void handleMove(MachineInstr* MI);
264
265    /// moveIntoBundle - Update intervals for operands of MI so that they
266    /// begin/end on the SlotIndex for BundleStart.
267    ///
268    /// Requires MI and BundleStart to have SlotIndexes, and assumes
269    /// existing liveness is accurate. BundleStart should be the first
270    /// instruction in the Bundle.
271    void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart);
272
273    // Register mask functions.
274    //
275    // Machine instructions may use a register mask operand to indicate that a
276    // large number of registers are clobbered by the instruction.  This is
277    // typically used for calls.
278    //
279    // For compile time performance reasons, these clobbers are not recorded in
280    // the live intervals for individual physical registers.  Instead,
281    // LiveIntervalAnalysis maintains a sorted list of instructions with
282    // register mask operands.
283
284    /// getRegMaskSlots - Returns a sorted array of slot indices of all
285    /// instructions with register mask operands.
286    ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
287
288    /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
289    /// instructions with register mask operands in the basic block numbered
290    /// MBBNum.
291    ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
292      std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
293      return getRegMaskSlots().slice(P.first, P.second);
294    }
295
296    /// getRegMaskBits() - Returns an array of register mask pointers
297    /// corresponding to getRegMaskSlots().
298    ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
299
300    /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
301    /// to getRegMaskSlotsInBlock(MBBNum).
302    ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
303      std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
304      return getRegMaskBits().slice(P.first, P.second);
305    }
306
307    /// checkRegMaskInterference - Test if LI is live across any register mask
308    /// instructions, and compute a bit mask of physical registers that are not
309    /// clobbered by any of them.
310    ///
311    /// Returns false if LI doesn't cross any register mask instructions. In
312    /// that case, the bit vector is not filled in.
313    bool checkRegMaskInterference(LiveInterval &LI,
314                                  BitVector &UsableRegs);
315
316    // Register unit functions.
317    //
318    // Fixed interference occurs when MachineInstrs use physregs directly
319    // instead of virtual registers. This typically happens when passing
320    // arguments to a function call, or when instructions require operands in
321    // fixed registers.
322    //
323    // Each physreg has one or more register units, see MCRegisterInfo. We
324    // track liveness per register unit to handle aliasing registers more
325    // efficiently.
326
327    /// getRegUnit - Return the live range for Unit.
328    /// It will be computed if it doesn't exist.
329    LiveInterval &getRegUnit(unsigned Unit) {
330      LiveInterval *LI = RegUnitIntervals[Unit];
331      if (!LI) {
332        // Compute missing ranges on demand.
333        RegUnitIntervals[Unit] = LI = new LiveInterval(Unit, HUGE_VALF);
334        computeRegUnitInterval(LI);
335      }
336      return *LI;
337    }
338
339    /// getCachedRegUnit - Return the live range for Unit if it has already
340    /// been computed, or NULL if it hasn't been computed yet.
341    LiveInterval *getCachedRegUnit(unsigned Unit) {
342      return RegUnitIntervals[Unit];
343    }
344
345  private:
346    /// computeIntervals - Compute live intervals.
347    void computeIntervals();
348
349    /// Compute live intervals for all virtual registers.
350    void computeVirtRegs();
351
352    /// Compute RegMaskSlots and RegMaskBits.
353    void computeRegMasks();
354
355    /// handleRegisterDef - update intervals for a register def
356    /// (calls handleVirtualRegisterDef)
357    void handleRegisterDef(MachineBasicBlock *MBB,
358                           MachineBasicBlock::iterator MI,
359                           SlotIndex MIIdx,
360                           MachineOperand& MO, unsigned MOIdx);
361
362    /// isPartialRedef - Return true if the specified def at the specific index
363    /// is partially re-defining the specified live interval. A common case of
364    /// this is a definition of the sub-register.
365    bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
366                        LiveInterval &interval);
367
368    /// handleVirtualRegisterDef - update intervals for a virtual
369    /// register def
370    void handleVirtualRegisterDef(MachineBasicBlock *MBB,
371                                  MachineBasicBlock::iterator MI,
372                                  SlotIndex MIIdx, MachineOperand& MO,
373                                  unsigned MOIdx,
374                                  LiveInterval& interval);
375
376    static LiveInterval* createInterval(unsigned Reg);
377
378    void printInstrs(raw_ostream &O) const;
379    void dumpInstrs() const;
380
381    void computeLiveInRegUnits();
382    void computeRegUnitInterval(LiveInterval*);
383    void computeVirtRegInterval(LiveInterval*);
384
385    class HMEditor;
386  };
387} // End llvm namespace
388
389#endif
390