b421753dd5368c2784e13f0e65fe7170a9b5af22
[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     /// 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     ///
264     /// \param UpdateFlags Update live intervals for nonallocatable physregs.
265     void handleMove(MachineInstr* MI, bool UpdateFlags = false);
266
267     /// moveIntoBundle - Update intervals for operands of MI so that they
268     /// begin/end on the SlotIndex for BundleStart.
269     ///
270     /// \param UpdateFlags Update live intervals for nonallocatable physregs.
271     ///
272     /// Requires MI and BundleStart to have SlotIndexes, and assumes
273     /// existing liveness is accurate. BundleStart should be the first
274     /// instruction in the Bundle.
275     void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart,
276                               bool UpdateFlags = false);
277
278     // Register mask functions.
279     //
280     // Machine instructions may use a register mask operand to indicate that a
281     // large number of registers are clobbered by the instruction.  This is
282     // typically used for calls.
283     //
284     // For compile time performance reasons, these clobbers are not recorded in
285     // the live intervals for individual physical registers.  Instead,
286     // LiveIntervalAnalysis maintains a sorted list of instructions with
287     // register mask operands.
288
289     /// getRegMaskSlots - Returns a sorted array of slot indices of all
290     /// instructions with register mask operands.
291     ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
292
293     /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
294     /// instructions with register mask operands in the basic block numbered
295     /// MBBNum.
296     ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
297       std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
298       return getRegMaskSlots().slice(P.first, P.second);
299     }
300
301     /// getRegMaskBits() - Returns an array of register mask pointers
302     /// corresponding to getRegMaskSlots().
303     ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
304
305     /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
306     /// to getRegMaskSlotsInBlock(MBBNum).
307     ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
308       std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
309       return getRegMaskBits().slice(P.first, P.second);
310     }
311
312     /// checkRegMaskInterference - Test if LI is live across any register mask
313     /// instructions, and compute a bit mask of physical registers that are not
314     /// clobbered by any of them.
315     ///
316     /// Returns false if LI doesn't cross any register mask instructions. In
317     /// that case, the bit vector is not filled in.
318     bool checkRegMaskInterference(LiveInterval &LI,
319                                   BitVector &UsableRegs);
320
321     // Register unit functions.
322     //
323     // Fixed interference occurs when MachineInstrs use physregs directly
324     // instead of virtual registers. This typically happens when passing
325     // arguments to a function call, or when instructions require operands in
326     // fixed registers.
327     //
328     // Each physreg has one or more register units, see MCRegisterInfo. We
329     // track liveness per register unit to handle aliasing registers more
330     // efficiently.
331
332     /// getRegUnit - Return the live range for Unit.
333     /// It will be computed if it doesn't exist.
334     LiveInterval &getRegUnit(unsigned Unit) {
335       LiveInterval *LI = RegUnitIntervals[Unit];
336       if (!LI) {
337         // Compute missing ranges on demand.
338         RegUnitIntervals[Unit] = LI = new LiveInterval(Unit, HUGE_VALF);
339         computeRegUnitInterval(LI);
340       }
341       return *LI;
342     }
343
344     /// getCachedRegUnit - Return the live range for Unit if it has already
345     /// been computed, or NULL if it hasn't been computed yet.
346     LiveInterval *getCachedRegUnit(unsigned Unit) {
347       return RegUnitIntervals[Unit];
348     }
349
350   private:
351     /// computeIntervals - Compute live intervals.
352     void computeIntervals();
353
354     /// Compute live intervals for all virtual registers.
355     void computeVirtRegs();
356
357     /// Compute RegMaskSlots and RegMaskBits.
358     void computeRegMasks();
359
360     /// handleRegisterDef - update intervals for a register def
361     /// (calls handleVirtualRegisterDef)
362     void handleRegisterDef(MachineBasicBlock *MBB,
363                            MachineBasicBlock::iterator MI,
364                            SlotIndex MIIdx,
365                            MachineOperand& MO, unsigned MOIdx);
366
367     /// isPartialRedef - Return true if the specified def at the specific index
368     /// is partially re-defining the specified live interval. A common case of
369     /// this is a definition of the sub-register.
370     bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
371                         LiveInterval &interval);
372
373     /// handleVirtualRegisterDef - update intervals for a virtual
374     /// register def
375     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
376                                   MachineBasicBlock::iterator MI,
377                                   SlotIndex MIIdx, MachineOperand& MO,
378                                   unsigned MOIdx,
379                                   LiveInterval& interval);
380
381     static LiveInterval* createInterval(unsigned Reg);
382
383     void printInstrs(raw_ostream &O) const;
384     void dumpInstrs() const;
385
386     void computeLiveInRegUnits();
387     void computeRegUnitInterval(LiveInterval*);
388     void computeVirtRegInterval(LiveInterval*);
389
390     class HMEditor;
391   };
392 } // End llvm namespace
393
394 #endif