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"
40 class MachineDominatorTree;
41 class MachineLoopInfo;
42 class TargetRegisterInfo;
43 class MachineRegisterInfo;
44 class TargetInstrInfo;
45 class TargetRegisterClass;
48 class LiveIntervals : public MachineFunctionPass {
50 MachineRegisterInfo* MRI;
51 const TargetMachine* TM;
52 const TargetRegisterInfo* TRI;
53 const TargetInstrInfo* TII;
57 MachineDominatorTree *DomTree;
58 LiveRangeCalc *LRCalc;
60 /// Special pool allocator for VNInfo's (LiveInterval val#).
62 VNInfo::Allocator VNInfoAllocator;
64 typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
65 Reg2IntervalMap R2IMap;
67 /// AllocatableRegs - A bit vector of allocatable registers.
68 BitVector AllocatableRegs;
70 /// ReservedRegs - A bit vector of reserved registers.
71 BitVector ReservedRegs;
73 /// RegMaskSlots - Sorted list of instructions with register mask operands.
74 /// Always use the 'r' slot, RegMasks are normal clobbers, not early
76 SmallVector<SlotIndex, 8> RegMaskSlots;
78 /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
79 /// pointer to the corresponding register mask. This pointer can be
82 /// MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
83 /// unsigned OpNum = findRegMaskOperand(MI);
84 /// RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
86 /// This is kept in a separate vector partly because some standard
87 /// libraries don't support lower_bound() with mixed objects, partly to
88 /// improve locality when searching in RegMaskSlots.
89 /// Also see the comment in LiveInterval::find().
90 SmallVector<const uint32_t*, 8> RegMaskBits;
92 /// For each basic block number, keep (begin, size) pairs indexing into the
93 /// RegMaskSlots and RegMaskBits arrays.
94 /// Note that basic block numbers may not be layout contiguous, that's why
95 /// we can't just keep track of the first register mask in each basic
97 SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
99 /// RegUnitIntervals - Keep a live interval for each register unit as a way
100 /// of tracking fixed physreg interference.
101 SmallVector<LiveInterval*, 0> RegUnitIntervals;
104 static char ID; // Pass identification, replacement for typeid
106 virtual ~LiveIntervals();
108 // Calculate the spill weight to assign to a single instruction.
109 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
111 typedef Reg2IntervalMap::iterator iterator;
112 typedef Reg2IntervalMap::const_iterator const_iterator;
113 const_iterator begin() const { return R2IMap.begin(); }
114 const_iterator end() const { return R2IMap.end(); }
115 iterator begin() { return R2IMap.begin(); }
116 iterator end() { return R2IMap.end(); }
117 unsigned getNumIntervals() const { return (unsigned)R2IMap.size(); }
119 LiveInterval &getInterval(unsigned reg) {
120 Reg2IntervalMap::iterator I = R2IMap.find(reg);
121 assert(I != R2IMap.end() && "Interval does not exist for register");
125 const LiveInterval &getInterval(unsigned reg) const {
126 Reg2IntervalMap::const_iterator I = R2IMap.find(reg);
127 assert(I != R2IMap.end() && "Interval does not exist for register");
131 bool hasInterval(unsigned reg) const {
132 return R2IMap.count(reg);
135 /// isAllocatable - is the physical register reg allocatable in the current
137 bool isAllocatable(unsigned reg) const {
138 return AllocatableRegs.test(reg);
141 /// isReserved - is the physical register reg reserved in the current
143 bool isReserved(unsigned reg) const {
144 return ReservedRegs.test(reg);
148 LiveInterval &getOrCreateInterval(unsigned reg) {
149 Reg2IntervalMap::iterator I = R2IMap.find(reg);
150 if (I == R2IMap.end())
151 I = R2IMap.insert(std::make_pair(reg, createInterval(reg))).first;
155 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
156 /// adds a live range from that instruction to the end of its MBB.
157 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
158 MachineInstr* startInst);
160 /// shrinkToUses - After removing some uses of a register, shrink its live
161 /// range to just the remaining uses. This method does not compute reaching
162 /// defs for new uses, and it doesn't remove dead defs.
163 /// Dead PHIDef values are marked as unused.
164 /// New dead machine instructions are added to the dead vector.
165 /// Return true if the interval may have been separated into multiple
166 /// connected components.
167 bool shrinkToUses(LiveInterval *li,
168 SmallVectorImpl<MachineInstr*> *dead = 0);
172 void removeInterval(unsigned Reg) {
173 DenseMap<unsigned, LiveInterval*>::iterator I = R2IMap.find(Reg);
178 SlotIndexes *getSlotIndexes() const {
182 AliasAnalysis *getAliasAnalysis() const {
186 /// isNotInMIMap - returns true if the specified machine instr has been
187 /// removed or was never entered in the map.
188 bool isNotInMIMap(const MachineInstr* Instr) const {
189 return !Indexes->hasIndex(Instr);
192 /// Returns the base index of the given instruction.
193 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
194 return Indexes->getInstructionIndex(instr);
197 /// Returns the instruction associated with the given index.
198 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
199 return Indexes->getInstructionFromIndex(index);
202 /// Return the first index in the given basic block.
203 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
204 return Indexes->getMBBStartIdx(mbb);
207 /// Return the last index in the given basic block.
208 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
209 return Indexes->getMBBEndIdx(mbb);
212 bool isLiveInToMBB(const LiveInterval &li,
213 const MachineBasicBlock *mbb) const {
214 return li.liveAt(getMBBStartIdx(mbb));
217 bool isLiveOutOfMBB(const LiveInterval &li,
218 const MachineBasicBlock *mbb) const {
219 return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
222 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
223 return Indexes->getMBBFromIndex(index);
226 SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
227 return Indexes->insertMachineInstrInMaps(MI);
230 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
231 Indexes->removeMachineInstrFromMaps(MI);
234 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
235 Indexes->replaceMachineInstrInMaps(MI, NewMI);
238 bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
239 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
240 return Indexes->findLiveInMBBs(Start, End, MBBs);
243 VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
245 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
246 virtual void releaseMemory();
248 /// runOnMachineFunction - pass entry point
249 virtual bool runOnMachineFunction(MachineFunction&);
251 /// print - Implement the dump method.
252 virtual void print(raw_ostream &O, const Module* = 0) const;
254 /// isReMaterializable - Returns true if every definition of MI of every
255 /// val# of the specified interval is re-materializable. Also returns true
256 /// by reference if all of the defs are load instructions.
257 bool isReMaterializable(const LiveInterval &li,
258 const SmallVectorImpl<LiveInterval*> *SpillIs,
261 /// intervalIsInOneMBB - If LI is confined to a single basic block, return
262 /// a pointer to that block. If LI is live in to or out of any block,
264 MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
266 /// addKillFlags - Add kill flags to any instruction that kills a virtual
270 /// handleMove - call this method to notify LiveIntervals that
271 /// instruction 'mi' has been moved within a basic block. This will update
272 /// the live intervals for all operands of mi. Moves between basic blocks
273 /// are not supported.
274 void handleMove(MachineInstr* MI);
276 /// moveIntoBundle - Update intervals for operands of MI so that they
277 /// begin/end on the SlotIndex for BundleStart.
279 /// Requires MI and BundleStart to have SlotIndexes, and assumes
280 /// existing liveness is accurate. BundleStart should be the first
281 /// instruction in the Bundle.
282 void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart);
284 // Register mask functions.
286 // Machine instructions may use a register mask operand to indicate that a
287 // large number of registers are clobbered by the instruction. This is
288 // typically used for calls.
290 // For compile time performance reasons, these clobbers are not recorded in
291 // the live intervals for individual physical registers. Instead,
292 // LiveIntervalAnalysis maintains a sorted list of instructions with
293 // register mask operands.
295 /// getRegMaskSlots - Returns a sorted array of slot indices of all
296 /// instructions with register mask operands.
297 ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
299 /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
300 /// instructions with register mask operands in the basic block numbered
302 ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
303 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
304 return getRegMaskSlots().slice(P.first, P.second);
307 /// getRegMaskBits() - Returns an array of register mask pointers
308 /// corresponding to getRegMaskSlots().
309 ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
311 /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
312 /// to getRegMaskSlotsInBlock(MBBNum).
313 ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
314 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
315 return getRegMaskBits().slice(P.first, P.second);
318 /// checkRegMaskInterference - Test if LI is live across any register mask
319 /// instructions, and compute a bit mask of physical registers that are not
320 /// clobbered by any of them.
322 /// Returns false if LI doesn't cross any register mask instructions. In
323 /// that case, the bit vector is not filled in.
324 bool checkRegMaskInterference(LiveInterval &LI,
325 BitVector &UsableRegs);
327 // Register unit functions.
329 // Fixed interference occurs when MachineInstrs use physregs directly
330 // instead of virtual registers. This typically happens when passing
331 // arguments to a function call, or when instructions require operands in
334 // Each physreg has one or more register units, see MCRegisterInfo. We
335 // track liveness per register unit to handle aliasing registers more
338 /// getRegUnit - Return the live range for Unit.
339 /// It will be computed if it doesn't exist.
340 LiveInterval &getRegUnit(unsigned Unit) {
341 LiveInterval *LI = RegUnitIntervals[Unit];
343 // Compute missing ranges on demand.
344 RegUnitIntervals[Unit] = LI = new LiveInterval(Unit, HUGE_VALF);
345 computeRegUnitInterval(LI);
350 /// getCachedRegUnit - Return the live range for Unit if it has already
351 /// been computed, or NULL if it hasn't been computed yet.
352 LiveInterval *getCachedRegUnit(unsigned Unit) {
353 return RegUnitIntervals[Unit];
356 /// trackingRegUnits - Does LiveIntervals curently track register units?
357 /// This function will be removed when regunit tracking is permanently
359 bool trackingRegUnits() const { return !RegUnitIntervals.empty(); }
362 /// computeIntervals - Compute live intervals.
363 void computeIntervals();
365 /// handleRegisterDef - update intervals for a register def
366 /// (calls handlePhysicalRegisterDef and
367 /// handleVirtualRegisterDef)
368 void handleRegisterDef(MachineBasicBlock *MBB,
369 MachineBasicBlock::iterator MI,
371 MachineOperand& MO, unsigned MOIdx);
373 /// isPartialRedef - Return true if the specified def at the specific index
374 /// is partially re-defining the specified live interval. A common case of
375 /// this is a definition of the sub-register.
376 bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
377 LiveInterval &interval);
379 /// handleVirtualRegisterDef - update intervals for a virtual
381 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
382 MachineBasicBlock::iterator MI,
383 SlotIndex MIIdx, MachineOperand& MO,
385 LiveInterval& interval);
387 /// handlePhysicalRegisterDef - update intervals for a physical register
389 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
390 MachineBasicBlock::iterator mi,
391 SlotIndex MIIdx, MachineOperand& MO,
392 LiveInterval &interval);
394 /// handleLiveInRegister - Create interval for a livein register.
395 void handleLiveInRegister(MachineBasicBlock* mbb,
397 LiveInterval &interval);
399 static LiveInterval* createInterval(unsigned Reg);
401 void printInstrs(raw_ostream &O) const;
402 void dumpInstrs() const;
404 void computeLiveInRegUnits();
405 void computeRegUnitInterval(LiveInterval*);
409 } // End llvm namespace