Cache basic block boundaries for faster RegMaskSlots access.
[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     /// For each basic block number, keep (begin, size) pairs indexing into the
86     /// RegMaskSlots and RegMaskBits arrays.
87     /// Note that basic block numbers may not be layout contiguous, that's why
88     /// we can't just keep track of the first register mask in each basic
89     /// block.
90     SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
91
92   public:
93     static char ID; // Pass identification, replacement for typeid
94     LiveIntervals() : MachineFunctionPass(ID) {
95       initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
96     }
97
98     // Calculate the spill weight to assign to a single instruction.
99     static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
100
101     typedef Reg2IntervalMap::iterator iterator;
102     typedef Reg2IntervalMap::const_iterator const_iterator;
103     const_iterator begin() const { return r2iMap_.begin(); }
104     const_iterator end() const { return r2iMap_.end(); }
105     iterator begin() { return r2iMap_.begin(); }
106     iterator end() { return r2iMap_.end(); }
107     unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
108
109     LiveInterval &getInterval(unsigned reg) {
110       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
111       assert(I != r2iMap_.end() && "Interval does not exist for register");
112       return *I->second;
113     }
114
115     const LiveInterval &getInterval(unsigned reg) const {
116       Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
117       assert(I != r2iMap_.end() && "Interval does not exist for register");
118       return *I->second;
119     }
120
121     bool hasInterval(unsigned reg) const {
122       return r2iMap_.count(reg);
123     }
124
125     /// isAllocatable - is the physical register reg allocatable in the current
126     /// function?
127     bool isAllocatable(unsigned reg) const {
128       return allocatableRegs_.test(reg);
129     }
130
131     /// getScaledIntervalSize - get the size of an interval in "units,"
132     /// where every function is composed of one thousand units.  This
133     /// measure scales properly with empty index slots in the function.
134     double getScaledIntervalSize(LiveInterval& I) {
135       return (1000.0 * I.getSize()) / indexes_->getIndexesLength();
136     }
137
138     /// getFuncInstructionCount - Return the number of instructions in the
139     /// current function.
140     unsigned getFuncInstructionCount() {
141       return indexes_->getFunctionSize();
142     }
143
144     /// getApproximateInstructionCount - computes an estimate of the number
145     /// of instructions in a given LiveInterval.
146     unsigned getApproximateInstructionCount(LiveInterval& I) {
147       double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
148       return (unsigned)(IntervalPercentage * indexes_->getFunctionSize());
149     }
150
151     // Interval creation
152     LiveInterval &getOrCreateInterval(unsigned reg) {
153       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
154       if (I == r2iMap_.end())
155         I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
156       return *I->second;
157     }
158
159     /// dupInterval - Duplicate a live interval. The caller is responsible for
160     /// managing the allocated memory.
161     LiveInterval *dupInterval(LiveInterval *li);
162
163     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
164     /// adds a live range from that instruction to the end of its MBB.
165     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
166                                        MachineInstr* startInst);
167
168     /// shrinkToUses - After removing some uses of a register, shrink its live
169     /// range to just the remaining uses. This method does not compute reaching
170     /// defs for new uses, and it doesn't remove dead defs.
171     /// Dead PHIDef values are marked as unused.
172     /// New dead machine instructions are added to the dead vector.
173     /// Return true if the interval may have been separated into multiple
174     /// connected components.
175     bool shrinkToUses(LiveInterval *li,
176                       SmallVectorImpl<MachineInstr*> *dead = 0);
177
178     // Interval removal
179
180     void removeInterval(unsigned Reg) {
181       DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
182       delete I->second;
183       r2iMap_.erase(I);
184     }
185
186     SlotIndexes *getSlotIndexes() const {
187       return indexes_;
188     }
189
190     /// isNotInMIMap - returns true if the specified machine instr has been
191     /// removed or was never entered in the map.
192     bool isNotInMIMap(const MachineInstr* Instr) const {
193       return !indexes_->hasIndex(Instr);
194     }
195
196     /// Returns the base index of the given instruction.
197     SlotIndex getInstructionIndex(const MachineInstr *instr) const {
198       return indexes_->getInstructionIndex(instr);
199     }
200
201     /// Returns the instruction associated with the given index.
202     MachineInstr* getInstructionFromIndex(SlotIndex index) const {
203       return indexes_->getInstructionFromIndex(index);
204     }
205
206     /// Return the first index in the given basic block.
207     SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
208       return indexes_->getMBBStartIdx(mbb);
209     }
210
211     /// Return the last index in the given basic block.
212     SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
213       return indexes_->getMBBEndIdx(mbb);
214     }
215
216     bool isLiveInToMBB(const LiveInterval &li,
217                        const MachineBasicBlock *mbb) const {
218       return li.liveAt(getMBBStartIdx(mbb));
219     }
220
221     bool isLiveOutOfMBB(const LiveInterval &li,
222                         const MachineBasicBlock *mbb) const {
223       return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
224     }
225
226     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
227       return indexes_->getMBBFromIndex(index);
228     }
229
230     SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
231       return indexes_->insertMachineInstrInMaps(MI);
232     }
233
234     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
235       indexes_->removeMachineInstrFromMaps(MI);
236     }
237
238     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
239       indexes_->replaceMachineInstrInMaps(MI, NewMI);
240     }
241
242     bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
243                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
244       return indexes_->findLiveInMBBs(Start, End, MBBs);
245     }
246
247     VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
248
249     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
250     virtual void releaseMemory();
251
252     /// runOnMachineFunction - pass entry point
253     virtual bool runOnMachineFunction(MachineFunction&);
254
255     /// print - Implement the dump method.
256     virtual void print(raw_ostream &O, const Module* = 0) const;
257
258     /// isReMaterializable - Returns true if every definition of MI of every
259     /// val# of the specified interval is re-materializable. Also returns true
260     /// by reference if all of the defs are load instructions.
261     bool isReMaterializable(const LiveInterval &li,
262                             const SmallVectorImpl<LiveInterval*> *SpillIs,
263                             bool &isLoad);
264
265     /// intervalIsInOneMBB - If LI is confined to a single basic block, return
266     /// a pointer to that block.  If LI is live in to or out of any block,
267     /// return NULL.
268     MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
269
270     /// addKillFlags - Add kill flags to any instruction that kills a virtual
271     /// register.
272     void addKillFlags();
273
274     /// moveInstr - Move MachineInstr mi to insertPt, updating the live
275     /// intervals of mi's operands to reflect the new position. The insertion
276     /// point can be above or below mi, but must be in the same basic block.
277     void moveInstr(MachineBasicBlock::iterator insertPt, MachineInstr* mi);
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, bool isAlias = false);
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 } // End llvm namespace
386
387 #endif