Merge into undefined lanes under -new-coalescer.
[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     LiveInterval &getInterval(unsigned Reg) {
113       LiveInterval *LI = VirtRegIntervals[Reg];
114       assert(LI && "Interval does not exist for virtual register");
115       return *LI;
116     }
117
118     const LiveInterval &getInterval(unsigned Reg) const {
119       return const_cast<LiveIntervals*>(this)->getInterval(Reg);
120     }
121
122     bool hasInterval(unsigned Reg) const {
123       return VirtRegIntervals.inBounds(Reg) && VirtRegIntervals[Reg];
124     }
125
126     /// isAllocatable - is the physical register reg allocatable in the current
127     /// function?
128     bool isAllocatable(unsigned reg) const {
129       return AllocatableRegs.test(reg);
130     }
131
132     /// isReserved - is the physical register reg reserved in the current
133     /// function
134     bool isReserved(unsigned reg) const {
135       return ReservedRegs.test(reg);
136     }
137
138     // Interval creation.
139     LiveInterval &getOrCreateInterval(unsigned Reg) {
140       if (!hasInterval(Reg)) {
141         VirtRegIntervals.grow(Reg);
142         VirtRegIntervals[Reg] = createInterval(Reg);
143       }
144       return getInterval(Reg);
145     }
146
147     // Interval removal.
148     void removeInterval(unsigned Reg) {
149       delete VirtRegIntervals[Reg];
150       VirtRegIntervals[Reg] = 0;
151     }
152
153     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
154     /// adds a live range from that instruction to the end of its MBB.
155     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
156                                        MachineInstr* startInst);
157
158     /// shrinkToUses - After removing some uses of a register, shrink its live
159     /// range to just the remaining uses. This method does not compute reaching
160     /// defs for new uses, and it doesn't remove dead defs.
161     /// Dead PHIDef values are marked as unused.
162     /// New dead machine instructions are added to the dead vector.
163     /// Return true if the interval may have been separated into multiple
164     /// connected components.
165     bool shrinkToUses(LiveInterval *li,
166                       SmallVectorImpl<MachineInstr*> *dead = 0);
167
168     /// extendToIndices - Extend the live range of LI to reach all points in
169     /// Indices. The points in the Indices array must be jointly dominated by
170     /// existing defs in LI. PHI-defs are added as needed to maintain SSA form.
171     ///
172     /// If a SlotIndex in Indices is the end index of a basic block, LI will be
173     /// extended to be live out of the basic block.
174     ///
175     /// See also LiveRangeCalc::extend().
176     void extendToIndices(LiveInterval *LI, ArrayRef<SlotIndex> Indices);
177
178     /// pruneValue - If an LI value is live at Kill, prune its live range by
179     /// removing any liveness reachable from Kill. Add live range end points to
180     /// EndPoints such that extendToIndices(LI, EndPoints) will reconstruct the
181     /// value's live range.
182     ///
183     /// Calling pruneValue() and extendToIndices() can be used to reconstruct
184     /// SSA form after adding defs to a virtual register.
185     void pruneValue(LiveInterval *LI, SlotIndex Kill,
186                     SmallVectorImpl<SlotIndex> *EndPoints);
187
188     SlotIndexes *getSlotIndexes() const {
189       return Indexes;
190     }
191
192     AliasAnalysis *getAliasAnalysis() const {
193       return AA;
194     }
195
196     /// isNotInMIMap - returns true if the specified machine instr has been
197     /// removed or was never entered in the map.
198     bool isNotInMIMap(const MachineInstr* Instr) const {
199       return !Indexes->hasIndex(Instr);
200     }
201
202     /// Returns the base index of the given instruction.
203     SlotIndex getInstructionIndex(const MachineInstr *instr) const {
204       return Indexes->getInstructionIndex(instr);
205     }
206
207     /// Returns the instruction associated with the given index.
208     MachineInstr* getInstructionFromIndex(SlotIndex index) const {
209       return Indexes->getInstructionFromIndex(index);
210     }
211
212     /// Return the first index in the given basic block.
213     SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
214       return Indexes->getMBBStartIdx(mbb);
215     }
216
217     /// Return the last index in the given basic block.
218     SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
219       return Indexes->getMBBEndIdx(mbb);
220     }
221
222     bool isLiveInToMBB(const LiveInterval &li,
223                        const MachineBasicBlock *mbb) const {
224       return li.liveAt(getMBBStartIdx(mbb));
225     }
226
227     bool isLiveOutOfMBB(const LiveInterval &li,
228                         const MachineBasicBlock *mbb) const {
229       return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
230     }
231
232     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
233       return Indexes->getMBBFromIndex(index);
234     }
235
236     SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
237       return Indexes->insertMachineInstrInMaps(MI);
238     }
239
240     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
241       Indexes->removeMachineInstrFromMaps(MI);
242     }
243
244     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
245       Indexes->replaceMachineInstrInMaps(MI, NewMI);
246     }
247
248     bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
249                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
250       return Indexes->findLiveInMBBs(Start, End, MBBs);
251     }
252
253     VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
254
255     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
256     virtual void releaseMemory();
257
258     /// runOnMachineFunction - pass entry point
259     virtual bool runOnMachineFunction(MachineFunction&);
260
261     /// print - Implement the dump method.
262     virtual void print(raw_ostream &O, const Module* = 0) const;
263
264     /// intervalIsInOneMBB - If LI is confined to a single basic block, return
265     /// a pointer to that block.  If LI is live in to or out of any block,
266     /// return NULL.
267     MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
268
269     /// Returns true if VNI is killed by any PHI-def values in LI.
270     /// This may conservatively return true to avoid expensive computations.
271     bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const;
272
273     /// addKillFlags - Add kill flags to any instruction that kills a virtual
274     /// register.
275     void addKillFlags(const VirtRegMap*);
276
277     /// handleMove - call this method to notify LiveIntervals that
278     /// instruction 'mi' has been moved within a basic block. This will update
279     /// the live intervals for all operands of mi. Moves between basic blocks
280     /// are not supported.
281     void handleMove(MachineInstr* MI);
282
283     /// moveIntoBundle - Update intervals for operands of MI so that they
284     /// begin/end on the SlotIndex for BundleStart.
285     ///
286     /// Requires MI and BundleStart to have SlotIndexes, and assumes
287     /// existing liveness is accurate. BundleStart should be the first
288     /// instruction in the Bundle.
289     void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart);
290
291     // Register mask functions.
292     //
293     // Machine instructions may use a register mask operand to indicate that a
294     // large number of registers are clobbered by the instruction.  This is
295     // typically used for calls.
296     //
297     // For compile time performance reasons, these clobbers are not recorded in
298     // the live intervals for individual physical registers.  Instead,
299     // LiveIntervalAnalysis maintains a sorted list of instructions with
300     // register mask operands.
301
302     /// getRegMaskSlots - Returns a sorted array of slot indices of all
303     /// instructions with register mask operands.
304     ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
305
306     /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
307     /// instructions with register mask operands in the basic block numbered
308     /// MBBNum.
309     ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
310       std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
311       return getRegMaskSlots().slice(P.first, P.second);
312     }
313
314     /// getRegMaskBits() - Returns an array of register mask pointers
315     /// corresponding to getRegMaskSlots().
316     ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
317
318     /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
319     /// to getRegMaskSlotsInBlock(MBBNum).
320     ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
321       std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
322       return getRegMaskBits().slice(P.first, P.second);
323     }
324
325     /// checkRegMaskInterference - Test if LI is live across any register mask
326     /// instructions, and compute a bit mask of physical registers that are not
327     /// clobbered by any of them.
328     ///
329     /// Returns false if LI doesn't cross any register mask instructions. In
330     /// that case, the bit vector is not filled in.
331     bool checkRegMaskInterference(LiveInterval &LI,
332                                   BitVector &UsableRegs);
333
334     // Register unit functions.
335     //
336     // Fixed interference occurs when MachineInstrs use physregs directly
337     // instead of virtual registers. This typically happens when passing
338     // arguments to a function call, or when instructions require operands in
339     // fixed registers.
340     //
341     // Each physreg has one or more register units, see MCRegisterInfo. We
342     // track liveness per register unit to handle aliasing registers more
343     // efficiently.
344
345     /// getRegUnit - Return the live range for Unit.
346     /// It will be computed if it doesn't exist.
347     LiveInterval &getRegUnit(unsigned Unit) {
348       LiveInterval *LI = RegUnitIntervals[Unit];
349       if (!LI) {
350         // Compute missing ranges on demand.
351         RegUnitIntervals[Unit] = LI = new LiveInterval(Unit, HUGE_VALF);
352         computeRegUnitInterval(LI);
353       }
354       return *LI;
355     }
356
357     /// getCachedRegUnit - Return the live range for Unit if it has already
358     /// been computed, or NULL if it hasn't been computed yet.
359     LiveInterval *getCachedRegUnit(unsigned Unit) {
360       return RegUnitIntervals[Unit];
361     }
362
363   private:
364     /// computeIntervals - Compute live intervals.
365     void computeIntervals();
366
367     /// Compute live intervals for all virtual registers.
368     void computeVirtRegs();
369
370     /// Compute RegMaskSlots and RegMaskBits.
371     void computeRegMasks();
372
373     /// handleRegisterDef - update intervals for a register def
374     /// (calls handleVirtualRegisterDef)
375     void handleRegisterDef(MachineBasicBlock *MBB,
376                            MachineBasicBlock::iterator MI,
377                            SlotIndex MIIdx,
378                            MachineOperand& MO, unsigned MOIdx);
379
380     /// isPartialRedef - Return true if the specified def at the specific index
381     /// is partially re-defining the specified live interval. A common case of
382     /// this is a definition of the sub-register.
383     bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
384                         LiveInterval &interval);
385
386     /// handleVirtualRegisterDef - update intervals for a virtual
387     /// register def
388     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
389                                   MachineBasicBlock::iterator MI,
390                                   SlotIndex MIIdx, MachineOperand& MO,
391                                   unsigned MOIdx,
392                                   LiveInterval& interval);
393
394     static LiveInterval* createInterval(unsigned Reg);
395
396     void printInstrs(raw_ostream &O) const;
397     void dumpInstrs() const;
398
399     void computeLiveInRegUnits();
400     void computeRegUnitInterval(LiveInterval*);
401     void computeVirtRegInterval(LiveInterval*);
402
403     class HMEditor;
404   };
405 } // End llvm namespace
406
407 #endif