1 //===-- LiveIntervalAnalysis.h - Live Interval Analysis ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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).
18 //===----------------------------------------------------------------------===//
20 #ifndef LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
21 #define LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
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"
39 class MachineLoopInfo;
40 class TargetRegisterInfo;
41 class MachineRegisterInfo;
42 class TargetInstrInfo;
43 class TargetRegisterClass;
46 class LiveIntervals : public MachineFunctionPass {
48 MachineRegisterInfo* mri_;
49 const TargetMachine* tm_;
50 const TargetRegisterInfo* tri_;
51 const TargetInstrInfo* tii_;
54 SlotIndexes* indexes_;
56 /// Special pool allocator for VNInfo's (LiveInterval val#).
58 VNInfo::Allocator VNInfoAllocator;
60 typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
61 Reg2IntervalMap r2iMap_;
63 /// allocatableRegs_ - A bit vector of allocatable registers.
64 BitVector allocatableRegs_;
66 /// RegMaskSlots - Sorted list of instructions with register mask operands.
67 /// Always use the 'r' slot, RegMasks are normal clobbers, not early
69 SmallVector<SlotIndex, 8> RegMaskSlots;
71 /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
72 /// pointer to the corresponding register mask. This pointer can be
75 /// MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
76 /// unsigned OpNum = findRegMaskOperand(MI);
77 /// RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
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;
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
90 SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
93 static char ID; // Pass identification, replacement for typeid
94 LiveIntervals() : MachineFunctionPass(ID) {
95 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
98 // Calculate the spill weight to assign to a single instruction.
99 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
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(); }
109 LiveInterval &getInterval(unsigned reg) {
110 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
111 assert(I != r2iMap_.end() && "Interval does not exist for register");
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");
121 bool hasInterval(unsigned reg) const {
122 return r2iMap_.count(reg);
125 /// isAllocatable - is the physical register reg allocatable in the current
127 bool isAllocatable(unsigned reg) const {
128 return allocatableRegs_.test(reg);
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();
138 /// getFuncInstructionCount - Return the number of instructions in the
139 /// current function.
140 unsigned getFuncInstructionCount() {
141 return indexes_->getFunctionSize();
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());
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;
159 /// dupInterval - Duplicate a live interval. The caller is responsible for
160 /// managing the allocated memory.
161 LiveInterval *dupInterval(LiveInterval *li);
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);
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);
180 void removeInterval(unsigned Reg) {
181 DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
186 SlotIndexes *getSlotIndexes() const {
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);
196 /// Returns the base index of the given instruction.
197 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
198 return indexes_->getInstructionIndex(instr);
201 /// Returns the instruction associated with the given index.
202 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
203 return indexes_->getInstructionFromIndex(index);
206 /// Return the first index in the given basic block.
207 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
208 return indexes_->getMBBStartIdx(mbb);
211 /// Return the last index in the given basic block.
212 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
213 return indexes_->getMBBEndIdx(mbb);
216 bool isLiveInToMBB(const LiveInterval &li,
217 const MachineBasicBlock *mbb) const {
218 return li.liveAt(getMBBStartIdx(mbb));
221 bool isLiveOutOfMBB(const LiveInterval &li,
222 const MachineBasicBlock *mbb) const {
223 return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
226 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
227 return indexes_->getMBBFromIndex(index);
230 SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
231 return indexes_->insertMachineInstrInMaps(MI);
234 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
235 indexes_->removeMachineInstrFromMaps(MI);
238 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
239 indexes_->replaceMachineInstrInMaps(MI, NewMI);
242 bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
243 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
244 return indexes_->findLiveInMBBs(Start, End, MBBs);
247 VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
249 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
250 virtual void releaseMemory();
252 /// runOnMachineFunction - pass entry point
253 virtual bool runOnMachineFunction(MachineFunction&);
255 /// print - Implement the dump method.
256 virtual void print(raw_ostream &O, const Module* = 0) const;
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,
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,
268 MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
270 /// addKillFlags - Add kill flags to any instruction that kills a virtual
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);
279 // Register mask functions.
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.
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.
290 /// getRegMaskSlots - Returns a sorted array of slot indices of all
291 /// instructions with register mask operands.
292 ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
294 /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
295 /// instructions with register mask operands in the basic block numbered
297 ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
298 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
299 return getRegMaskSlots().slice(P.first, P.second);
302 /// getRegMaskBits() - Returns an array of register mask pointers
303 /// corresponding to getRegMaskSlots().
304 ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
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);
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.
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);
323 /// computeIntervals - Compute live intervals.
324 void computeIntervals();
326 /// handleRegisterDef - update intervals for a register def
327 /// (calls handlePhysicalRegisterDef and
328 /// handleVirtualRegisterDef)
329 void handleRegisterDef(MachineBasicBlock *MBB,
330 MachineBasicBlock::iterator MI,
332 MachineOperand& MO, unsigned MOIdx);
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);
340 /// handleVirtualRegisterDef - update intervals for a virtual
342 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
343 MachineBasicBlock::iterator MI,
344 SlotIndex MIIdx, MachineOperand& MO,
346 LiveInterval& interval);
348 /// handlePhysicalRegisterDef - update intervals for a physical register
350 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
351 MachineBasicBlock::iterator mi,
352 SlotIndex MIIdx, MachineOperand& MO,
353 LiveInterval &interval);
355 /// handleLiveInRegister - Create interval for a livein register.
356 void handleLiveInRegister(MachineBasicBlock* mbb,
358 LiveInterval &interval, bool isAlias = false);
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;
366 /// isValNoAvailableAt - Return true if the val# of the specified interval
367 /// which reaches the given instruction also reaches the specified use
369 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
370 SlotIndex UseIdx) const;
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,
377 const SmallVectorImpl<LiveInterval*> *SpillIs,
380 static LiveInterval* createInterval(unsigned Reg);
382 void printInstrs(raw_ostream &O) const;
383 void dumpInstrs() const;
385 } // End llvm namespace