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 /// CloneMIs - A list of clones as result of re-materialization.
67 std::vector<MachineInstr*> CloneMIs;
70 static char ID; // Pass identification, replacement for typeid
71 LiveIntervals() : MachineFunctionPass(ID) {
72 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
75 // Calculate the spill weight to assign to a single instruction.
76 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
78 // After summing the spill weights of all defs and uses, the final weight
79 // should be normalized, dividing the weight of the interval by its size.
80 // This encourages spilling of intervals that are large and have few uses,
81 // and discourages spilling of small intervals with many uses.
82 void normalizeSpillWeight(LiveInterval &li) {
83 li.weight /= getApproximateInstructionCount(li) + 25;
86 typedef Reg2IntervalMap::iterator iterator;
87 typedef Reg2IntervalMap::const_iterator const_iterator;
88 const_iterator begin() const { return r2iMap_.begin(); }
89 const_iterator end() const { return r2iMap_.end(); }
90 iterator begin() { return r2iMap_.begin(); }
91 iterator end() { return r2iMap_.end(); }
92 unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
94 LiveInterval &getInterval(unsigned reg) {
95 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
96 assert(I != r2iMap_.end() && "Interval does not exist for register");
100 const LiveInterval &getInterval(unsigned reg) const {
101 Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
102 assert(I != r2iMap_.end() && "Interval does not exist for register");
106 bool hasInterval(unsigned reg) const {
107 return r2iMap_.count(reg);
110 /// isAllocatable - is the physical register reg allocatable in the current
112 bool isAllocatable(unsigned reg) const {
113 return allocatableRegs_.test(reg);
116 /// getScaledIntervalSize - get the size of an interval in "units,"
117 /// where every function is composed of one thousand units. This
118 /// measure scales properly with empty index slots in the function.
119 double getScaledIntervalSize(LiveInterval& I) {
120 return (1000.0 * I.getSize()) / indexes_->getIndexesLength();
123 /// getFuncInstructionCount - Return the number of instructions in the
124 /// current function.
125 unsigned getFuncInstructionCount() {
126 return indexes_->getFunctionSize();
129 /// getApproximateInstructionCount - computes an estimate of the number
130 /// of instructions in a given LiveInterval.
131 unsigned getApproximateInstructionCount(LiveInterval& I) {
132 double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
133 return (unsigned)(IntervalPercentage * indexes_->getFunctionSize());
136 /// conflictsWithPhysReg - Returns true if the specified register is used or
137 /// defined during the duration of the specified interval. Copies to and
138 /// from li.reg are allowed. This method is only able to analyze simple
139 /// ranges that stay within a single basic block. Anything else is
140 /// considered a conflict.
141 bool conflictsWithPhysReg(const LiveInterval &li, VirtRegMap &vrm,
144 /// conflictsWithAliasRef - Similar to conflictsWithPhysRegRef except
145 /// it checks for alias uses and defs.
146 bool conflictsWithAliasRef(LiveInterval &li, unsigned Reg,
147 SmallPtrSet<MachineInstr*,32> &JoinedCopies);
150 LiveInterval &getOrCreateInterval(unsigned reg) {
151 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
152 if (I == r2iMap_.end())
153 I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
157 /// dupInterval - Duplicate a live interval. The caller is responsible for
158 /// managing the allocated memory.
159 LiveInterval *dupInterval(LiveInterval *li);
161 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
162 /// adds a live range from that instruction to the end of its MBB.
163 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
164 MachineInstr* startInst);
168 void removeInterval(unsigned Reg) {
169 DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
174 SlotIndex getZeroIndex() const {
175 return indexes_->getZeroIndex();
178 SlotIndex getInvalidIndex() const {
179 return indexes_->getInvalidIndex();
182 /// isNotInMIMap - returns true if the specified machine instr has been
183 /// removed or was never entered in the map.
184 bool isNotInMIMap(const MachineInstr* Instr) const {
185 return !indexes_->hasIndex(Instr);
188 /// Returns the base index of the given instruction.
189 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
190 return indexes_->getInstructionIndex(instr);
193 /// Returns the instruction associated with the given index.
194 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
195 return indexes_->getInstructionFromIndex(index);
198 /// Return the first index in the given basic block.
199 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
200 return indexes_->getMBBStartIdx(mbb);
203 /// Return the last index in the given basic block.
204 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
205 return indexes_->getMBBEndIdx(mbb);
208 bool isLiveInToMBB(const LiveInterval &li,
209 const MachineBasicBlock *mbb) const {
210 return li.liveAt(getMBBStartIdx(mbb));
213 LiveRange* findEnteringRange(LiveInterval &li,
214 const MachineBasicBlock *mbb) {
215 return li.getLiveRangeContaining(getMBBStartIdx(mbb));
218 bool isLiveOutOfMBB(const LiveInterval &li,
219 const MachineBasicBlock *mbb) const {
220 return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
223 LiveRange* findExitingRange(LiveInterval &li,
224 const MachineBasicBlock *mbb) {
225 return li.getLiveRangeContaining(getMBBEndIdx(mbb).getPrevSlot());
228 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
229 return indexes_->getMBBFromIndex(index);
232 SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
233 return indexes_->insertMachineInstrInMaps(MI);
236 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
237 indexes_->removeMachineInstrFromMaps(MI);
240 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
241 indexes_->replaceMachineInstrInMaps(MI, NewMI);
244 void InsertMBBInMaps(MachineBasicBlock *MBB) {
245 indexes_->insertMBBInMaps(MBB);
248 bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
249 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
250 return indexes_->findLiveInMBBs(Start, End, MBBs);
254 indexes_->renumberIndexes();
257 VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
259 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
260 virtual void releaseMemory();
262 /// runOnMachineFunction - pass entry point
263 virtual bool runOnMachineFunction(MachineFunction&);
265 /// print - Implement the dump method.
266 virtual void print(raw_ostream &O, const Module* = 0) const;
268 /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
269 /// the given interval. FIXME: It also returns the weight of the spill slot
270 /// (if any is created) by reference. This is temporary.
271 std::vector<LiveInterval*>
272 addIntervalsForSpills(const LiveInterval& i,
273 SmallVectorImpl<LiveInterval*> &SpillIs,
274 const MachineLoopInfo *loopInfo, VirtRegMap& vrm);
276 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
277 /// around all defs and uses of the specified interval. Return true if it
278 /// was able to cut its interval.
279 bool spillPhysRegAroundRegDefsUses(const LiveInterval &li,
280 unsigned PhysReg, VirtRegMap &vrm);
282 /// isReMaterializable - Returns true if every definition of MI of every
283 /// val# of the specified interval is re-materializable. Also returns true
284 /// by reference if all of the defs are load instructions.
285 bool isReMaterializable(const LiveInterval &li,
286 SmallVectorImpl<LiveInterval*> &SpillIs,
289 /// isReMaterializable - Returns true if the definition MI of the specified
290 /// val# of the specified interval is re-materializable.
291 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
294 /// getRepresentativeReg - Find the largest super register of the specified
295 /// physical register.
296 unsigned getRepresentativeReg(unsigned Reg) const;
298 /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
299 /// specified interval that conflicts with the specified physical register.
300 unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
301 unsigned PhysReg) const;
303 /// intervalIsInOneMBB - Returns true if the specified interval is entirely
304 /// within a single basic block.
305 bool intervalIsInOneMBB(const LiveInterval &li) const;
308 /// computeIntervals - Compute live intervals.
309 void computeIntervals();
311 /// handleRegisterDef - update intervals for a register def
312 /// (calls handlePhysicalRegisterDef and
313 /// handleVirtualRegisterDef)
314 void handleRegisterDef(MachineBasicBlock *MBB,
315 MachineBasicBlock::iterator MI,
317 MachineOperand& MO, unsigned MOIdx);
319 /// isPartialRedef - Return true if the specified def at the specific index
320 /// is partially re-defining the specified live interval. A common case of
321 /// this is a definition of the sub-register.
322 bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
323 LiveInterval &interval);
325 /// handleVirtualRegisterDef - update intervals for a virtual
327 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
328 MachineBasicBlock::iterator MI,
329 SlotIndex MIIdx, MachineOperand& MO,
331 LiveInterval& interval);
333 /// handlePhysicalRegisterDef - update intervals for a physical register
335 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
336 MachineBasicBlock::iterator mi,
337 SlotIndex MIIdx, MachineOperand& MO,
338 LiveInterval &interval,
339 MachineInstr *CopyMI);
341 /// handleLiveInRegister - Create interval for a livein register.
342 void handleLiveInRegister(MachineBasicBlock* mbb,
344 LiveInterval &interval, bool isAlias = false);
346 /// getReMatImplicitUse - If the remat definition MI has one (for now, we
347 /// only allow one) virtual register operand, then its uses are implicitly
348 /// using the register. Returns the virtual register.
349 unsigned getReMatImplicitUse(const LiveInterval &li,
350 MachineInstr *MI) const;
352 /// isValNoAvailableAt - Return true if the val# of the specified interval
353 /// which reaches the given instruction also reaches the specified use
355 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
356 SlotIndex UseIdx) const;
358 /// isReMaterializable - Returns true if the definition MI of the specified
359 /// val# of the specified interval is re-materializable. Also returns true
360 /// by reference if the def is a load.
361 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
363 SmallVectorImpl<LiveInterval*> &SpillIs,
366 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
367 /// slot / to reg or any rematerialized load into ith operand of specified
368 /// MI. If it is successul, MI is updated with the newly created MI and
370 bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
371 MachineInstr *DefMI, SlotIndex InstrIdx,
372 SmallVector<unsigned, 2> &Ops,
373 bool isSS, int FrameIndex, unsigned Reg);
375 /// canFoldMemoryOperand - Return true if the specified load / store
376 /// folding is possible.
377 bool canFoldMemoryOperand(MachineInstr *MI,
378 SmallVector<unsigned, 2> &Ops,
379 bool ReMatLoadSS) const;
381 /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
382 /// VNInfo that's after the specified index but is within the basic block.
383 bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
384 MachineBasicBlock *MBB,
385 SlotIndex Idx) const;
387 /// hasAllocatableSuperReg - Return true if the specified physical register
388 /// has any super register that's allocatable.
389 bool hasAllocatableSuperReg(unsigned Reg) const;
391 /// SRInfo - Spill / restore info.
396 SRInfo(SlotIndex i, unsigned vr, bool f)
397 : index(i), vreg(vr), canFold(f) {}
400 bool alsoFoldARestore(int Id, SlotIndex index, unsigned vr,
401 BitVector &RestoreMBBs,
402 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
403 void eraseRestoreInfo(int Id, SlotIndex index, unsigned vr,
404 BitVector &RestoreMBBs,
405 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
407 /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
408 /// spilled and create empty intervals for their uses.
409 void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
410 const TargetRegisterClass* rc,
411 std::vector<LiveInterval*> &NewLIs);
413 /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
414 /// interval on to-be re-materialized operands of MI) with new register.
415 void rewriteImplicitOps(const LiveInterval &li,
416 MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
418 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
419 /// functions for addIntervalsForSpills to rewrite uses / defs for the given
421 bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
422 bool TrySplit, SlotIndex index, SlotIndex end,
423 MachineInstr *MI, MachineInstr *OrigDefMI, MachineInstr *DefMI,
424 unsigned Slot, int LdSlot,
425 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
426 VirtRegMap &vrm, const TargetRegisterClass* rc,
427 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
428 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
429 DenseMap<unsigned,unsigned> &MBBVRegsMap,
430 std::vector<LiveInterval*> &NewLIs);
431 void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
432 LiveInterval::Ranges::const_iterator &I,
433 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
434 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
435 VirtRegMap &vrm, const TargetRegisterClass* rc,
436 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
437 BitVector &SpillMBBs,
438 DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
439 BitVector &RestoreMBBs,
440 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
441 DenseMap<unsigned,unsigned> &MBBVRegsMap,
442 std::vector<LiveInterval*> &NewLIs);
444 // Normalize the spill weight of all the intervals in NewLIs.
445 void normalizeSpillWeights(std::vector<LiveInterval*> &NewLIs);
447 static LiveInterval* createInterval(unsigned Reg);
449 void printInstrs(raw_ostream &O) const;
450 void dumpInstrs() const;
452 } // End llvm namespace