Delete dead code.
[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/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/LiveInterval.h"
26 #include "llvm/CodeGen/SlotIndexes.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/Support/Allocator.h"
32 #include <cmath>
33 #include <iterator>
34
35 namespace llvm {
36
37   class AliasAnalysis;
38   class LiveVariables;
39   class MachineLoopInfo;
40   class TargetRegisterInfo;
41   class MachineRegisterInfo;
42   class TargetInstrInfo;
43   class TargetRegisterClass;
44   class VirtRegMap;
45
46   class LiveIntervals : public MachineFunctionPass {
47     MachineFunction* MF;
48     MachineRegisterInfo* MRI;
49     const TargetMachine* TM;
50     const TargetRegisterInfo* TRI;
51     const TargetInstrInfo* TII;
52     AliasAnalysis *AA;
53     LiveVariables* LV;
54     SlotIndexes* Indexes;
55
56     /// Special pool allocator for VNInfo's (LiveInterval val#).
57     ///
58     VNInfo::Allocator VNInfoAllocator;
59
60     typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
61     Reg2IntervalMap R2IMap;
62
63     /// AllocatableRegs - A bit vector of allocatable registers.
64     BitVector AllocatableRegs;
65
66     /// ReservedRegs - A bit vector of reserved registers.
67     BitVector ReservedRegs;
68
69     /// RegMaskSlots - Sorted list of instructions with register mask operands.
70     /// Always use the 'r' slot, RegMasks are normal clobbers, not early
71     /// clobbers.
72     SmallVector<SlotIndex, 8> RegMaskSlots;
73
74     /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
75     /// pointer to the corresponding register mask.  This pointer can be
76     /// recomputed as:
77     ///
78     ///   MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
79     ///   unsigned OpNum = findRegMaskOperand(MI);
80     ///   RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
81     ///
82     /// This is kept in a separate vector partly because some standard
83     /// libraries don't support lower_bound() with mixed objects, partly to
84     /// improve locality when searching in RegMaskSlots.
85     /// Also see the comment in LiveInterval::find().
86     SmallVector<const uint32_t*, 8> RegMaskBits;
87
88     /// For each basic block number, keep (begin, size) pairs indexing into the
89     /// RegMaskSlots and RegMaskBits arrays.
90     /// Note that basic block numbers may not be layout contiguous, that's why
91     /// we can't just keep track of the first register mask in each basic
92     /// block.
93     SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
94
95   public:
96     static char ID; // Pass identification, replacement for typeid
97     LiveIntervals() : MachineFunctionPass(ID) {
98       initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
99     }
100
101     // Calculate the spill weight to assign to a single instruction.
102     static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
103
104     typedef Reg2IntervalMap::iterator iterator;
105     typedef Reg2IntervalMap::const_iterator const_iterator;
106     const_iterator begin() const { return R2IMap.begin(); }
107     const_iterator end() const { return R2IMap.end(); }
108     iterator begin() { return R2IMap.begin(); }
109     iterator end() { return R2IMap.end(); }
110     unsigned getNumIntervals() const { return (unsigned)R2IMap.size(); }
111
112     LiveInterval &getInterval(unsigned reg) {
113       Reg2IntervalMap::iterator I = R2IMap.find(reg);
114       assert(I != R2IMap.end() && "Interval does not exist for register");
115       return *I->second;
116     }
117
118     const LiveInterval &getInterval(unsigned reg) const {
119       Reg2IntervalMap::const_iterator I = R2IMap.find(reg);
120       assert(I != R2IMap.end() && "Interval does not exist for register");
121       return *I->second;
122     }
123
124     bool hasInterval(unsigned reg) const {
125       return R2IMap.count(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     /// getApproximateInstructionCount - computes an estimate of the number
141     /// of instructions in a given LiveInterval.
142     unsigned getApproximateInstructionCount(LiveInterval& I) {
143       return I.getSize()/SlotIndex::InstrDist;
144     }
145
146     // Interval creation
147     LiveInterval &getOrCreateInterval(unsigned reg) {
148       Reg2IntervalMap::iterator I = R2IMap.find(reg);
149       if (I == R2IMap.end())
150         I = R2IMap.insert(std::make_pair(reg, createInterval(reg))).first;
151       return *I->second;
152     }
153
154     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
155     /// adds a live range from that instruction to the end of its MBB.
156     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
157                                        MachineInstr* startInst);
158
159     /// shrinkToUses - After removing some uses of a register, shrink its live
160     /// range to just the remaining uses. This method does not compute reaching
161     /// defs for new uses, and it doesn't remove dead defs.
162     /// Dead PHIDef values are marked as unused.
163     /// New dead machine instructions are added to the dead vector.
164     /// Return true if the interval may have been separated into multiple
165     /// connected components.
166     bool shrinkToUses(LiveInterval *li,
167                       SmallVectorImpl<MachineInstr*> *dead = 0);
168
169     // Interval removal
170
171     void removeInterval(unsigned Reg) {
172       DenseMap<unsigned, LiveInterval*>::iterator I = R2IMap.find(Reg);
173       delete I->second;
174       R2IMap.erase(I);
175     }
176
177     SlotIndexes *getSlotIndexes() const {
178       return Indexes;
179     }
180
181     /// isNotInMIMap - returns true if the specified machine instr has been
182     /// removed or was never entered in the map.
183     bool isNotInMIMap(const MachineInstr* Instr) const {
184       return !Indexes->hasIndex(Instr);
185     }
186
187     /// Returns the base index of the given instruction.
188     SlotIndex getInstructionIndex(const MachineInstr *instr) const {
189       return Indexes->getInstructionIndex(instr);
190     }
191
192     /// Returns the instruction associated with the given index.
193     MachineInstr* getInstructionFromIndex(SlotIndex index) const {
194       return Indexes->getInstructionFromIndex(index);
195     }
196
197     /// Return the first index in the given basic block.
198     SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
199       return Indexes->getMBBStartIdx(mbb);
200     }
201
202     /// Return the last index in the given basic block.
203     SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
204       return Indexes->getMBBEndIdx(mbb);
205     }
206
207     bool isLiveInToMBB(const LiveInterval &li,
208                        const MachineBasicBlock *mbb) const {
209       return li.liveAt(getMBBStartIdx(mbb));
210     }
211
212     bool isLiveOutOfMBB(const LiveInterval &li,
213                         const MachineBasicBlock *mbb) const {
214       return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
215     }
216
217     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
218       return Indexes->getMBBFromIndex(index);
219     }
220
221     SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
222       return Indexes->insertMachineInstrInMaps(MI);
223     }
224
225     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
226       Indexes->removeMachineInstrFromMaps(MI);
227     }
228
229     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
230       Indexes->replaceMachineInstrInMaps(MI, NewMI);
231     }
232
233     bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
234                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
235       return Indexes->findLiveInMBBs(Start, End, MBBs);
236     }
237
238     VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
239
240     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
241     virtual void releaseMemory();
242
243     /// runOnMachineFunction - pass entry point
244     virtual bool runOnMachineFunction(MachineFunction&);
245
246     /// print - Implement the dump method.
247     virtual void print(raw_ostream &O, const Module* = 0) const;
248
249     /// isReMaterializable - Returns true if every definition of MI of every
250     /// val# of the specified interval is re-materializable. Also returns true
251     /// by reference if all of the defs are load instructions.
252     bool isReMaterializable(const LiveInterval &li,
253                             const SmallVectorImpl<LiveInterval*> *SpillIs,
254                             bool &isLoad);
255
256     /// intervalIsInOneMBB - If LI is confined to a single basic block, return
257     /// a pointer to that block.  If LI is live in to or out of any block,
258     /// return NULL.
259     MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
260
261     /// addKillFlags - Add kill flags to any instruction that kills a virtual
262     /// register.
263     void addKillFlags();
264
265     /// handleMove - call this method to notify LiveIntervals that
266     /// instruction 'mi' has been moved within a basic block. This will update
267     /// the live intervals for all operands of mi. Moves between basic blocks
268     /// are not supported.
269     void handleMove(MachineInstr* MI);
270
271     /// moveIntoBundle - Update intervals for operands of MI so that they
272     /// begin/end on the SlotIndex for BundleStart.
273     ///
274     /// Requires MI and BundleStart to have SlotIndexes, and assumes
275     /// existing liveness is accurate. BundleStart should be the first
276     /// instruction in the Bundle.
277     void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart);
278
279     // Register mask functions.
280     //
281     // Machine instructions may use a register mask operand to indicate that a
282     // large number of registers are clobbered by the instruction.  This is
283     // typically used for calls.
284     //
285     // For compile time performance reasons, these clobbers are not recorded in
286     // the live intervals for individual physical registers.  Instead,
287     // LiveIntervalAnalysis maintains a sorted list of instructions with
288     // register mask operands.
289
290     /// getRegMaskSlots - Returns a sorted array of slot indices of all
291     /// instructions with register mask operands.
292     ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
293
294     /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
295     /// instructions with register mask operands in the basic block numbered
296     /// MBBNum.
297     ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
298       std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
299       return getRegMaskSlots().slice(P.first, P.second);
300     }
301
302     /// getRegMaskBits() - Returns an array of register mask pointers
303     /// corresponding to getRegMaskSlots().
304     ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
305
306     /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
307     /// to getRegMaskSlotsInBlock(MBBNum).
308     ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
309       std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
310       return getRegMaskBits().slice(P.first, P.second);
311     }
312
313     /// checkRegMaskInterference - Test if LI is live across any register mask
314     /// instructions, and compute a bit mask of physical registers that are not
315     /// clobbered by any of them.
316     ///
317     /// Returns false if LI doesn't cross any register mask instructions. In
318     /// that case, the bit vector is not filled in.
319     bool checkRegMaskInterference(LiveInterval &LI,
320                                   BitVector &UsableRegs);
321
322   private:
323     /// computeIntervals - Compute live intervals.
324     void computeIntervals();
325
326     /// handleRegisterDef - update intervals for a register def
327     /// (calls handlePhysicalRegisterDef and
328     /// handleVirtualRegisterDef)
329     void handleRegisterDef(MachineBasicBlock *MBB,
330                            MachineBasicBlock::iterator MI,
331                            SlotIndex MIIdx,
332                            MachineOperand& MO, unsigned MOIdx);
333
334     /// isPartialRedef - Return true if the specified def at the specific index
335     /// is partially re-defining the specified live interval. A common case of
336     /// this is a definition of the sub-register.
337     bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
338                         LiveInterval &interval);
339
340     /// handleVirtualRegisterDef - update intervals for a virtual
341     /// register def
342     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
343                                   MachineBasicBlock::iterator MI,
344                                   SlotIndex MIIdx, MachineOperand& MO,
345                                   unsigned MOIdx,
346                                   LiveInterval& interval);
347
348     /// handlePhysicalRegisterDef - update intervals for a physical register
349     /// def.
350     void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
351                                    MachineBasicBlock::iterator mi,
352                                    SlotIndex MIIdx, MachineOperand& MO,
353                                    LiveInterval &interval);
354
355     /// handleLiveInRegister - Create interval for a livein register.
356     void handleLiveInRegister(MachineBasicBlock* mbb,
357                               SlotIndex MIIdx,
358                               LiveInterval &interval);
359
360     /// getReMatImplicitUse - If the remat definition MI has one (for now, we
361     /// only allow one) virtual register operand, then its uses are implicitly
362     /// using the register. Returns the virtual register.
363     unsigned getReMatImplicitUse(const LiveInterval &li,
364                                  MachineInstr *MI) const;
365
366     /// isValNoAvailableAt - Return true if the val# of the specified interval
367     /// which reaches the given instruction also reaches the specified use
368     /// index.
369     bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
370                             SlotIndex UseIdx) const;
371
372     /// isReMaterializable - Returns true if the definition MI of the specified
373     /// val# of the specified interval is re-materializable. Also returns true
374     /// by reference if the def is a load.
375     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
376                             MachineInstr *MI,
377                             const SmallVectorImpl<LiveInterval*> *SpillIs,
378                             bool &isLoad);
379
380     static LiveInterval* createInterval(unsigned Reg);
381
382     void printInstrs(raw_ostream &O) const;
383     void dumpInstrs() const;
384
385     class HMEditor;
386   };
387 } // End llvm namespace
388
389 #endif