Keep track of register masks in LiveIntervalAnalysis.
[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     /// RegMaskSlots - Sorted list of instructions with register mask operands.
67     /// Always use the 'r' slot, RegMasks are normal clobbers, not early
68     /// clobbers.
69     SmallVector<SlotIndex, 8> RegMaskSlots;
70
71     /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
72     /// pointer to the corresponding register mask.  This pointer can be
73     /// recomputed as:
74     ///
75     ///   MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
76     ///   unsigned OpNum = findRegMaskOperand(MI);
77     ///   RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
78     ///
79     /// This is kept in a separate vector partly because some standard
80     /// libraries don't support lower_bound() with mixed objects, partly to
81     /// improve locality when searching in RegMaskSlots.
82     /// Also see the comment in LiveInterval::find().
83     SmallVector<const uint32_t*, 8> RegMaskBits;
84
85   public:
86     static char ID; // Pass identification, replacement for typeid
87     LiveIntervals() : MachineFunctionPass(ID) {
88       initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
89     }
90
91     // Calculate the spill weight to assign to a single instruction.
92     static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
93
94     typedef Reg2IntervalMap::iterator iterator;
95     typedef Reg2IntervalMap::const_iterator const_iterator;
96     const_iterator begin() const { return r2iMap_.begin(); }
97     const_iterator end() const { return r2iMap_.end(); }
98     iterator begin() { return r2iMap_.begin(); }
99     iterator end() { return r2iMap_.end(); }
100     unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
101
102     LiveInterval &getInterval(unsigned reg) {
103       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
104       assert(I != r2iMap_.end() && "Interval does not exist for register");
105       return *I->second;
106     }
107
108     const LiveInterval &getInterval(unsigned reg) const {
109       Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
110       assert(I != r2iMap_.end() && "Interval does not exist for register");
111       return *I->second;
112     }
113
114     bool hasInterval(unsigned reg) const {
115       return r2iMap_.count(reg);
116     }
117
118     /// isAllocatable - is the physical register reg allocatable in the current
119     /// function?
120     bool isAllocatable(unsigned reg) const {
121       return allocatableRegs_.test(reg);
122     }
123
124     /// getScaledIntervalSize - get the size of an interval in "units,"
125     /// where every function is composed of one thousand units.  This
126     /// measure scales properly with empty index slots in the function.
127     double getScaledIntervalSize(LiveInterval& I) {
128       return (1000.0 * I.getSize()) / indexes_->getIndexesLength();
129     }
130
131     /// getFuncInstructionCount - Return the number of instructions in the
132     /// current function.
133     unsigned getFuncInstructionCount() {
134       return indexes_->getFunctionSize();
135     }
136
137     /// getApproximateInstructionCount - computes an estimate of the number
138     /// of instructions in a given LiveInterval.
139     unsigned getApproximateInstructionCount(LiveInterval& I) {
140       double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
141       return (unsigned)(IntervalPercentage * indexes_->getFunctionSize());
142     }
143
144     // Interval creation
145     LiveInterval &getOrCreateInterval(unsigned reg) {
146       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
147       if (I == r2iMap_.end())
148         I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
149       return *I->second;
150     }
151
152     /// dupInterval - Duplicate a live interval. The caller is responsible for
153     /// managing the allocated memory.
154     LiveInterval *dupInterval(LiveInterval *li);
155
156     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
157     /// adds a live range from that instruction to the end of its MBB.
158     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
159                                        MachineInstr* startInst);
160
161     /// shrinkToUses - After removing some uses of a register, shrink its live
162     /// range to just the remaining uses. This method does not compute reaching
163     /// defs for new uses, and it doesn't remove dead defs.
164     /// Dead PHIDef values are marked as unused.
165     /// New dead machine instructions are added to the dead vector.
166     /// Return true if the interval may have been separated into multiple
167     /// connected components.
168     bool shrinkToUses(LiveInterval *li,
169                       SmallVectorImpl<MachineInstr*> *dead = 0);
170
171     // Interval removal
172
173     void removeInterval(unsigned Reg) {
174       DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
175       delete I->second;
176       r2iMap_.erase(I);
177     }
178
179     SlotIndexes *getSlotIndexes() const {
180       return indexes_;
181     }
182
183     /// isNotInMIMap - returns true if the specified machine instr has been
184     /// removed or was never entered in the map.
185     bool isNotInMIMap(const MachineInstr* Instr) const {
186       return !indexes_->hasIndex(Instr);
187     }
188
189     /// Returns the base index of the given instruction.
190     SlotIndex getInstructionIndex(const MachineInstr *instr) const {
191       return indexes_->getInstructionIndex(instr);
192     }
193
194     /// Returns the instruction associated with the given index.
195     MachineInstr* getInstructionFromIndex(SlotIndex index) const {
196       return indexes_->getInstructionFromIndex(index);
197     }
198
199     /// Return the first index in the given basic block.
200     SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
201       return indexes_->getMBBStartIdx(mbb);
202     }
203
204     /// Return the last index in the given basic block.
205     SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
206       return indexes_->getMBBEndIdx(mbb);
207     }
208
209     bool isLiveInToMBB(const LiveInterval &li,
210                        const MachineBasicBlock *mbb) const {
211       return li.liveAt(getMBBStartIdx(mbb));
212     }
213
214     bool isLiveOutOfMBB(const LiveInterval &li,
215                         const MachineBasicBlock *mbb) const {
216       return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
217     }
218
219     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
220       return indexes_->getMBBFromIndex(index);
221     }
222
223     SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
224       return indexes_->insertMachineInstrInMaps(MI);
225     }
226
227     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
228       indexes_->removeMachineInstrFromMaps(MI);
229     }
230
231     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
232       indexes_->replaceMachineInstrInMaps(MI, NewMI);
233     }
234
235     bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
236                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
237       return indexes_->findLiveInMBBs(Start, End, MBBs);
238     }
239
240     VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
241
242     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
243     virtual void releaseMemory();
244
245     /// runOnMachineFunction - pass entry point
246     virtual bool runOnMachineFunction(MachineFunction&);
247
248     /// print - Implement the dump method.
249     virtual void print(raw_ostream &O, const Module* = 0) const;
250
251     /// isReMaterializable - Returns true if every definition of MI of every
252     /// val# of the specified interval is re-materializable. Also returns true
253     /// by reference if all of the defs are load instructions.
254     bool isReMaterializable(const LiveInterval &li,
255                             const SmallVectorImpl<LiveInterval*> *SpillIs,
256                             bool &isLoad);
257
258     /// intervalIsInOneMBB - Returns true if the specified interval is entirely
259     /// within a single basic block.
260     bool intervalIsInOneMBB(const LiveInterval &li) const;
261
262     /// addKillFlags - Add kill flags to any instruction that kills a virtual
263     /// register.
264     void addKillFlags();
265
266     /// moveInstr - Move MachineInstr mi to insertPt, updating the live
267     /// intervals of mi's operands to reflect the new position. The insertion
268     /// point can be above or below mi, but must be in the same basic block.
269     void moveInstr(MachineBasicBlock::iterator insertPt, MachineInstr* mi);
270
271     // Register mask functions.
272     //
273     // Machine instructions may use a register mask operand to indicate that a
274     // large number of registers are clobbered by the instruction.  This is
275     // typically used for calls.
276     //
277     // For compile time performance reasons, these clobbers are not recorded in
278     // the live intervals for individual physical registers.  Instead,
279     // LiveIntervalAnalysis maintains a sorted list of instructions with
280     // register mask operands.
281
282     /// getRegMaskSlots - Returns asorted array of slot indices of all
283     /// instructions with register mask operands.
284     ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
285
286     /// checkRegMaskInterference - Test if LI is live across any register mask
287     /// instructions, and compute a bit mask of physical registers that are not
288     /// clobbered by any of them.
289     ///
290     /// Returns false if LI doesn't cross any register mask instructions. In
291     /// that case, the bit vector is not filled in.
292     bool checkRegMaskInterference(LiveInterval &LI,
293                                   BitVector &UsableRegs);
294
295   private:
296     /// computeIntervals - Compute live intervals.
297     void computeIntervals();
298
299     /// handleRegisterDef - update intervals for a register def
300     /// (calls handlePhysicalRegisterDef and
301     /// handleVirtualRegisterDef)
302     void handleRegisterDef(MachineBasicBlock *MBB,
303                            MachineBasicBlock::iterator MI,
304                            SlotIndex MIIdx,
305                            MachineOperand& MO, unsigned MOIdx);
306
307     /// isPartialRedef - Return true if the specified def at the specific index
308     /// is partially re-defining the specified live interval. A common case of
309     /// this is a definition of the sub-register.
310     bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
311                         LiveInterval &interval);
312
313     /// handleVirtualRegisterDef - update intervals for a virtual
314     /// register def
315     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
316                                   MachineBasicBlock::iterator MI,
317                                   SlotIndex MIIdx, MachineOperand& MO,
318                                   unsigned MOIdx,
319                                   LiveInterval& interval);
320
321     /// handlePhysicalRegisterDef - update intervals for a physical register
322     /// def.
323     void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
324                                    MachineBasicBlock::iterator mi,
325                                    SlotIndex MIIdx, MachineOperand& MO,
326                                    LiveInterval &interval);
327
328     /// handleLiveInRegister - Create interval for a livein register.
329     void handleLiveInRegister(MachineBasicBlock* mbb,
330                               SlotIndex MIIdx,
331                               LiveInterval &interval, bool isAlias = false);
332
333     /// getReMatImplicitUse - If the remat definition MI has one (for now, we
334     /// only allow one) virtual register operand, then its uses are implicitly
335     /// using the register. Returns the virtual register.
336     unsigned getReMatImplicitUse(const LiveInterval &li,
337                                  MachineInstr *MI) const;
338
339     /// isValNoAvailableAt - Return true if the val# of the specified interval
340     /// which reaches the given instruction also reaches the specified use
341     /// index.
342     bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
343                             SlotIndex UseIdx) const;
344
345     /// isReMaterializable - Returns true if the definition MI of the specified
346     /// val# of the specified interval is re-materializable. Also returns true
347     /// by reference if the def is a load.
348     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
349                             MachineInstr *MI,
350                             const SmallVectorImpl<LiveInterval*> *SpillIs,
351                             bool &isLoad);
352
353     static LiveInterval* createInterval(unsigned Reg);
354
355     void printInstrs(raw_ostream &O) const;
356     void dumpInstrs() const;
357   };
358 } // End llvm namespace
359
360 #endif