Store live intervals in an IndexedMap.
[oota-llvm.git] / include / llvm / CodeGen / LiveIntervalAnalysis.h
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
36 namespace 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     /// AllocatableRegs - A bit vector of allocatable registers.
69     BitVector AllocatableRegs;
70
71     /// ReservedRegs - A bit vector of reserved registers.
72     BitVector ReservedRegs;
73
74     /// RegMaskSlots - Sorted list of instructions with register mask operands.
75     /// Always use the 'r' slot, RegMasks are normal clobbers, not early
76     /// clobbers.
77     SmallVector<SlotIndex, 8> RegMaskSlots;
78
79     /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
80     /// pointer to the corresponding register mask.  This pointer can be
81     /// recomputed as:
82     ///
83     ///   MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
84     ///   unsigned OpNum = findRegMaskOperand(MI);
85     ///   RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
86     ///
87     /// This is kept in a separate vector partly because some standard
88     /// libraries don't support lower_bound() with mixed objects, partly to
89     /// improve locality when searching in RegMaskSlots.
90     /// Also see the comment in LiveInterval::find().
91     SmallVector<const uint32_t*, 8> RegMaskBits;
92
93     /// For each basic block number, keep (begin, size) pairs indexing into the
94     /// RegMaskSlots and RegMaskBits arrays.
95     /// Note that basic block numbers may not be layout contiguous, that's why
96     /// we can't just keep track of the first register mask in each basic
97     /// block.
98     SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
99
100     /// RegUnitIntervals - Keep a live interval for each register unit as a way
101     /// of tracking fixed physreg interference.
102     SmallVector<LiveInterval*, 0> RegUnitIntervals;
103
104   public:
105     static char ID; // Pass identification, replacement for typeid
106     LiveIntervals();
107     virtual ~LiveIntervals();
108
109     // Calculate the spill weight to assign to a single instruction.
110     static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
111
112     unsigned getNumIntervals() const { return (unsigned)VirtRegIntervals.size(); }
113
114     LiveInterval &getInterval(unsigned Reg) {
115       LiveInterval *LI = VirtRegIntervals[Reg];
116       assert(LI && "Interval does not exist for virtual register");
117       return *LI;
118     }
119
120     const LiveInterval &getInterval(unsigned Reg) const {
121       return const_cast<LiveIntervals*>(this)->getInterval(Reg);
122     }
123
124     bool hasInterval(unsigned Reg) const {
125       return VirtRegIntervals.inBounds(Reg) && VirtRegIntervals[Reg];
126     }
127
128     /// isAllocatable - is the physical register reg allocatable in the current
129     /// function?
130     bool isAllocatable(unsigned reg) const {
131       return AllocatableRegs.test(reg);
132     }
133
134     /// isReserved - is the physical register reg reserved in the current
135     /// function
136     bool isReserved(unsigned reg) const {
137       return ReservedRegs.test(reg);
138     }
139
140     // Interval creation.
141     LiveInterval &getOrCreateInterval(unsigned Reg) {
142       if (!hasInterval(Reg)) {
143         VirtRegIntervals.grow(Reg);
144         VirtRegIntervals[Reg] = createInterval(Reg);
145       }
146       return getInterval(Reg);
147     }
148
149     // Interval removal.
150     void removeInterval(unsigned Reg) {
151       delete VirtRegIntervals[Reg];
152       VirtRegIntervals[Reg] = 0;
153     }
154
155     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
156     /// adds a live range from that instruction to the end of its MBB.
157     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
158                                        MachineInstr* startInst);
159
160     /// shrinkToUses - After removing some uses of a register, shrink its live
161     /// range to just the remaining uses. This method does not compute reaching
162     /// defs for new uses, and it doesn't remove dead defs.
163     /// Dead PHIDef values are marked as unused.
164     /// New dead machine instructions are added to the dead vector.
165     /// Return true if the interval may have been separated into multiple
166     /// connected components.
167     bool shrinkToUses(LiveInterval *li,
168                       SmallVectorImpl<MachineInstr*> *dead = 0);
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     /// isReMaterializable - Returns true if every definition of MI of every
247     /// val# of the specified interval is re-materializable. Also returns true
248     /// by reference if all of the defs are load instructions.
249     bool isReMaterializable(const LiveInterval &li,
250                             const SmallVectorImpl<LiveInterval*> *SpillIs,
251                             bool &isLoad);
252
253     /// intervalIsInOneMBB - If LI is confined to a single basic block, return
254     /// a pointer to that block.  If LI is live in to or out of any block,
255     /// return NULL.
256     MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
257
258     /// addKillFlags - Add kill flags to any instruction that kills a virtual
259     /// register.
260     void addKillFlags();
261
262     /// handleMove - call this method to notify LiveIntervals that
263     /// instruction 'mi' has been moved within a basic block. This will update
264     /// the live intervals for all operands of mi. Moves between basic blocks
265     /// are not supported.
266     void handleMove(MachineInstr* MI);
267
268     /// moveIntoBundle - Update intervals for operands of MI so that they
269     /// begin/end on the SlotIndex for BundleStart.
270     ///
271     /// Requires MI and BundleStart to have SlotIndexes, and assumes
272     /// existing liveness is accurate. BundleStart should be the first
273     /// instruction in the Bundle.
274     void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart);
275
276     // Register mask functions.
277     //
278     // Machine instructions may use a register mask operand to indicate that a
279     // large number of registers are clobbered by the instruction.  This is
280     // typically used for calls.
281     //
282     // For compile time performance reasons, these clobbers are not recorded in
283     // the live intervals for individual physical registers.  Instead,
284     // LiveIntervalAnalysis maintains a sorted list of instructions with
285     // register mask operands.
286
287     /// getRegMaskSlots - Returns a sorted array of slot indices of all
288     /// instructions with register mask operands.
289     ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
290
291     /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
292     /// instructions with register mask operands in the basic block numbered
293     /// MBBNum.
294     ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
295       std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
296       return getRegMaskSlots().slice(P.first, P.second);
297     }
298
299     /// getRegMaskBits() - Returns an array of register mask pointers
300     /// corresponding to getRegMaskSlots().
301     ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
302
303     /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
304     /// to getRegMaskSlotsInBlock(MBBNum).
305     ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
306       std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
307       return getRegMaskBits().slice(P.first, P.second);
308     }
309
310     /// checkRegMaskInterference - Test if LI is live across any register mask
311     /// instructions, and compute a bit mask of physical registers that are not
312     /// clobbered by any of them.
313     ///
314     /// Returns false if LI doesn't cross any register mask instructions. In
315     /// that case, the bit vector is not filled in.
316     bool checkRegMaskInterference(LiveInterval &LI,
317                                   BitVector &UsableRegs);
318
319     // Register unit functions.
320     //
321     // Fixed interference occurs when MachineInstrs use physregs directly
322     // instead of virtual registers. This typically happens when passing
323     // arguments to a function call, or when instructions require operands in
324     // fixed registers.
325     //
326     // Each physreg has one or more register units, see MCRegisterInfo. We
327     // track liveness per register unit to handle aliasing registers more
328     // efficiently.
329
330     /// getRegUnit - Return the live range for Unit.
331     /// It will be computed if it doesn't exist.
332     LiveInterval &getRegUnit(unsigned Unit) {
333       LiveInterval *LI = RegUnitIntervals[Unit];
334       if (!LI) {
335         // Compute missing ranges on demand.
336         RegUnitIntervals[Unit] = LI = new LiveInterval(Unit, HUGE_VALF);
337         computeRegUnitInterval(LI);
338       }
339       return *LI;
340     }
341
342     /// getCachedRegUnit - Return the live range for Unit if it has already
343     /// been computed, or NULL if it hasn't been computed yet.
344     LiveInterval *getCachedRegUnit(unsigned Unit) {
345       return RegUnitIntervals[Unit];
346     }
347
348   private:
349     /// computeIntervals - Compute live intervals.
350     void computeIntervals();
351
352     /// handleRegisterDef - update intervals for a register def
353     /// (calls handleVirtualRegisterDef)
354     void handleRegisterDef(MachineBasicBlock *MBB,
355                            MachineBasicBlock::iterator MI,
356                            SlotIndex MIIdx,
357                            MachineOperand& MO, unsigned MOIdx);
358
359     /// isPartialRedef - Return true if the specified def at the specific index
360     /// is partially re-defining the specified live interval. A common case of
361     /// this is a definition of the sub-register.
362     bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
363                         LiveInterval &interval);
364
365     /// handleVirtualRegisterDef - update intervals for a virtual
366     /// register def
367     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
368                                   MachineBasicBlock::iterator MI,
369                                   SlotIndex MIIdx, MachineOperand& MO,
370                                   unsigned MOIdx,
371                                   LiveInterval& interval);
372
373     static LiveInterval* createInterval(unsigned Reg);
374
375     void printInstrs(raw_ostream &O) const;
376     void dumpInstrs() const;
377
378     void computeLiveInRegUnits();
379     void computeRegUnitInterval(LiveInterval*);
380
381     class HMEditor;
382   };
383 } // End llvm namespace
384
385 #endif