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/MachineFunctionPass.h"
24 #include "llvm/CodeGen/LiveInterval.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/Allocator.h"
36 class MachineLoopInfo;
37 class TargetRegisterInfo;
38 class MachineRegisterInfo;
39 class TargetInstrInfo;
40 class TargetRegisterClass;
42 typedef std::pair<unsigned, MachineBasicBlock*> IdxMBBPair;
44 inline bool operator<(unsigned V, const IdxMBBPair &IM) {
48 inline bool operator<(const IdxMBBPair &IM, unsigned V) {
52 struct Idx2MBBCompare {
53 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
54 return LHS.first < RHS.first;
58 class LiveIntervals : public MachineFunctionPass {
60 MachineRegisterInfo* mri_;
61 const TargetMachine* tm_;
62 const TargetRegisterInfo* tri_;
63 const TargetInstrInfo* tii_;
67 /// Special pool allocator for VNInfo's (LiveInterval val#).
69 BumpPtrAllocator VNInfoAllocator;
71 /// MBB2IdxMap - The indexes of the first and last instructions in the
72 /// specified basic block.
73 std::vector<std::pair<unsigned, unsigned> > MBB2IdxMap;
75 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
77 std::vector<IdxMBBPair> Idx2MBBMap;
79 /// FunctionSize - The number of instructions present in the function
80 uint64_t FunctionSize;
82 typedef DenseMap<MachineInstr*, unsigned> Mi2IndexMap;
85 typedef std::vector<MachineInstr*> Index2MiMap;
88 typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
89 Reg2IntervalMap r2iMap_;
91 BitVector allocatableRegs_;
93 std::vector<MachineInstr*> ClonedMIs;
95 typedef LiveInterval::InstrSlots InstrSlots;
98 static char ID; // Pass identification, replacement for typeid
99 LiveIntervals() : MachineFunctionPass(&ID) {}
101 static unsigned getBaseIndex(unsigned index) {
102 return index - (index % InstrSlots::NUM);
104 static unsigned getBoundaryIndex(unsigned index) {
105 return getBaseIndex(index + InstrSlots::NUM - 1);
107 static unsigned getLoadIndex(unsigned index) {
108 return getBaseIndex(index) + InstrSlots::LOAD;
110 static unsigned getUseIndex(unsigned index) {
111 return getBaseIndex(index) + InstrSlots::USE;
113 static unsigned getDefIndex(unsigned index) {
114 return getBaseIndex(index) + InstrSlots::DEF;
116 static unsigned getStoreIndex(unsigned index) {
117 return getBaseIndex(index) + InstrSlots::STORE;
120 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
121 return (isDef + isUse) * powf(10.0F, (float)loopDepth);
124 typedef Reg2IntervalMap::iterator iterator;
125 typedef Reg2IntervalMap::const_iterator const_iterator;
126 const_iterator begin() const { return r2iMap_.begin(); }
127 const_iterator end() const { return r2iMap_.end(); }
128 iterator begin() { return r2iMap_.begin(); }
129 iterator end() { return r2iMap_.end(); }
130 unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
132 LiveInterval &getInterval(unsigned reg) {
133 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
134 assert(I != r2iMap_.end() && "Interval does not exist for register");
138 const LiveInterval &getInterval(unsigned reg) const {
139 Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
140 assert(I != r2iMap_.end() && "Interval does not exist for register");
144 bool hasInterval(unsigned reg) const {
145 return r2iMap_.count(reg);
148 /// getMBBStartIdx - Return the base index of the first instruction in the
149 /// specified MachineBasicBlock.
150 unsigned getMBBStartIdx(MachineBasicBlock *MBB) const {
151 return getMBBStartIdx(MBB->getNumber());
153 unsigned getMBBStartIdx(unsigned MBBNo) const {
154 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
155 return MBB2IdxMap[MBBNo].first;
158 /// getMBBEndIdx - Return the store index of the last instruction in the
159 /// specified MachineBasicBlock.
160 unsigned getMBBEndIdx(MachineBasicBlock *MBB) const {
161 return getMBBEndIdx(MBB->getNumber());
163 unsigned getMBBEndIdx(unsigned MBBNo) const {
164 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
165 return MBB2IdxMap[MBBNo].second;
168 /// getScaledIntervalSize - get the size of an interval in "units,"
169 /// where every function is composed of one thousand units. This
170 /// measure scales properly with empty index slots in the function.
171 double getScaledIntervalSize(LiveInterval& I) {
172 return (1000.0 / InstrSlots::NUM * I.getSize()) / i2miMap_.size();
175 /// getApproximateInstructionCount - computes an estimate of the number
176 /// of instructions in a given LiveInterval.
177 unsigned getApproximateInstructionCount(LiveInterval& I) {
178 double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
179 return (unsigned)(IntervalPercentage * FunctionSize);
182 /// getMBBFromIndex - given an index in any instruction of an
183 /// MBB return a pointer the MBB
184 MachineBasicBlock* getMBBFromIndex(unsigned index) const {
185 std::vector<IdxMBBPair>::const_iterator I =
186 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
187 // Take the pair containing the index
188 std::vector<IdxMBBPair>::const_iterator J =
189 ((I != Idx2MBBMap.end() && I->first > index) ||
190 (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
192 assert(J != Idx2MBBMap.end() && J->first < index+1 &&
193 index <= getMBBEndIdx(J->second) &&
194 "index does not correspond to an MBB");
198 /// getInstructionIndex - returns the base index of instr
199 unsigned getInstructionIndex(MachineInstr* instr) const {
200 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
201 assert(it != mi2iMap_.end() && "Invalid instruction!");
205 /// getInstructionFromIndex - given an index in any slot of an
206 /// instruction return a pointer the instruction
207 MachineInstr* getInstructionFromIndex(unsigned index) const {
208 index /= InstrSlots::NUM; // convert index to vector index
209 assert(index < i2miMap_.size() &&
210 "index does not correspond to an instruction");
211 return i2miMap_[index];
214 /// hasGapBeforeInstr - Return true if the previous instruction slot,
215 /// i.e. Index - InstrSlots::NUM, is not occupied.
216 bool hasGapBeforeInstr(unsigned Index) {
217 Index = getBaseIndex(Index - InstrSlots::NUM);
218 return getInstructionFromIndex(Index) == 0;
221 /// hasGapAfterInstr - Return true if the successive instruction slot,
222 /// i.e. Index + InstrSlots::Num, is not occupied.
223 bool hasGapAfterInstr(unsigned Index) {
224 Index = getBaseIndex(Index + InstrSlots::NUM);
225 return getInstructionFromIndex(Index) == 0;
228 /// findGapBeforeInstr - Find an empty instruction slot before the
229 /// specified index. If "Furthest" is true, find one that's furthest
230 /// away from the index (but before any index that's occupied).
231 unsigned findGapBeforeInstr(unsigned Index, bool Furthest = false) {
232 Index = getBaseIndex(Index - InstrSlots::NUM);
233 if (getInstructionFromIndex(Index))
237 unsigned PrevIndex = getBaseIndex(Index - InstrSlots::NUM);
238 while (getInstructionFromIndex(Index)) {
240 PrevIndex = getBaseIndex(Index - InstrSlots::NUM);
245 /// InsertMachineInstrInMaps - Insert the specified machine instruction
246 /// into the instruction index map at the given index.
247 void InsertMachineInstrInMaps(MachineInstr *MI, unsigned Index) {
248 i2miMap_[Index / InstrSlots::NUM] = MI;
249 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
250 assert(it == mi2iMap_.end() && "Already in map!");
251 mi2iMap_[MI] = Index;
254 /// conflictsWithPhysRegDef - Returns true if the specified register
255 /// is defined during the duration of the specified interval.
256 bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
259 /// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
260 /// it can check use as well.
261 bool conflictsWithPhysRegRef(LiveInterval &li, unsigned Reg,
263 SmallPtrSet<MachineInstr*,32> &JoinedCopies);
265 /// findLiveInMBBs - Given a live range, if the value of the range
266 /// is live in any MBB returns true as well as the list of basic blocks
267 /// in which the value is live.
268 bool findLiveInMBBs(unsigned Start, unsigned End,
269 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
271 /// findReachableMBBs - Return a list MBB that can be reached via any
272 /// branch or fallthroughs. Return true if the list is not empty.
273 bool findReachableMBBs(unsigned Start, unsigned End,
274 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
278 LiveInterval &getOrCreateInterval(unsigned reg) {
279 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
280 if (I == r2iMap_.end())
281 I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
285 /// dupInterval - Duplicate a live interval. The caller is responsible for
286 /// managing the allocated memory.
287 LiveInterval *dupInterval(LiveInterval *li);
289 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
290 /// adds a live range from that instruction to the end of its MBB.
291 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
292 MachineInstr* startInst);
296 void removeInterval(unsigned Reg) {
297 DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
302 /// isNotInMIMap - returns true if the specified machine instr has been
303 /// removed or was never entered in the map.
304 bool isNotInMIMap(MachineInstr* instr) const {
305 return !mi2iMap_.count(instr);
308 /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
310 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
311 // remove index -> MachineInstr and
312 // MachineInstr -> index mappings
313 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
314 if (mi2i != mi2iMap_.end()) {
315 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
316 mi2iMap_.erase(mi2i);
320 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
321 /// maps used by register allocator.
322 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
323 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
324 if (mi2i == mi2iMap_.end())
326 i2miMap_[mi2i->second/InstrSlots::NUM] = NewMI;
327 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
328 assert(it != mi2iMap_.end() && "Invalid instruction!");
329 unsigned Index = it->second;
331 mi2iMap_[NewMI] = Index;
334 BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
336 /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
337 /// copy field and returns the source register that defines it.
338 unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
340 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
341 virtual void releaseMemory();
343 /// runOnMachineFunction - pass entry point
344 virtual bool runOnMachineFunction(MachineFunction&);
346 /// print - Implement the dump method.
347 virtual void print(std::ostream &O, const Module* = 0) const;
348 void print(std::ostream *O, const Module* M = 0) const {
352 /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
353 /// the given interval. FIXME: It also returns the weight of the spill slot
354 /// (if any is created) by reference. This is temporary.
355 std::vector<LiveInterval*>
356 addIntervalsForSpills(const LiveInterval& i,
357 SmallVectorImpl<LiveInterval*> &SpillIs,
358 const MachineLoopInfo *loopInfo, VirtRegMap& vrm);
360 /// addIntervalsForSpillsFast - Quickly create new intervals for spilled
361 /// defs / uses without remat or splitting.
362 std::vector<LiveInterval*>
363 addIntervalsForSpillsFast(const LiveInterval &li,
364 const MachineLoopInfo *loopInfo, VirtRegMap &vrm);
366 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
367 /// around all defs and uses of the specified interval. Return true if it
368 /// was able to cut its interval.
369 bool spillPhysRegAroundRegDefsUses(const LiveInterval &li,
370 unsigned PhysReg, VirtRegMap &vrm);
372 /// isReMaterializable - Returns true if every definition of MI of every
373 /// val# of the specified interval is re-materializable. Also returns true
374 /// by reference if all of the defs are load instructions.
375 bool isReMaterializable(const LiveInterval &li,
376 SmallVectorImpl<LiveInterval*> &SpillIs,
379 /// isReMaterializable - Returns true if the definition MI of the specified
380 /// val# of the specified interval is re-materializable.
381 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
384 /// getRepresentativeReg - Find the largest super register of the specified
385 /// physical register.
386 unsigned getRepresentativeReg(unsigned Reg) const;
388 /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
389 /// specified interval that conflicts with the specified physical register.
390 unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
391 unsigned PhysReg) const;
393 /// processImplicitDefs - Process IMPLICIT_DEF instructions. Add isUndef
394 /// marker to implicit_def defs and their uses.
395 void processImplicitDefs();
397 /// computeNumbering - Compute the index numbering.
398 void computeNumbering();
400 /// scaleNumbering - Rescale interval numbers to introduce gaps for new
402 void scaleNumbering(int factor);
404 /// intervalIsInOneMBB - Returns true if the specified interval is entirely
405 /// within a single basic block.
406 bool intervalIsInOneMBB(const LiveInterval &li) const;
409 /// computeIntervals - Compute live intervals.
410 void computeIntervals();
412 /// handleRegisterDef - update intervals for a register def
413 /// (calls handlePhysicalRegisterDef and
414 /// handleVirtualRegisterDef)
415 void handleRegisterDef(MachineBasicBlock *MBB,
416 MachineBasicBlock::iterator MI, unsigned MIIdx,
417 MachineOperand& MO, unsigned MOIdx);
419 /// handleVirtualRegisterDef - update intervals for a virtual
421 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
422 MachineBasicBlock::iterator MI,
423 unsigned MIIdx, MachineOperand& MO,
424 unsigned MOIdx, LiveInterval& interval);
426 /// handlePhysicalRegisterDef - update intervals for a physical register
428 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
429 MachineBasicBlock::iterator mi,
430 unsigned MIIdx, MachineOperand& MO,
431 LiveInterval &interval,
432 MachineInstr *CopyMI);
434 /// handleLiveInRegister - Create interval for a livein register.
435 void handleLiveInRegister(MachineBasicBlock* mbb,
437 LiveInterval &interval, bool isAlias = false);
439 /// getReMatImplicitUse - If the remat definition MI has one (for now, we
440 /// only allow one) virtual register operand, then its uses are implicitly
441 /// using the register. Returns the virtual register.
442 unsigned getReMatImplicitUse(const LiveInterval &li,
443 MachineInstr *MI) const;
445 /// isValNoAvailableAt - Return true if the val# of the specified interval
446 /// which reaches the given instruction also reaches the specified use
448 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
449 unsigned UseIdx) const;
451 /// isReMaterializable - Returns true if the definition MI of the specified
452 /// val# of the specified interval is re-materializable. Also returns true
453 /// by reference if the def is a load.
454 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
456 SmallVectorImpl<LiveInterval*> &SpillIs,
459 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
460 /// slot / to reg or any rematerialized load into ith operand of specified
461 /// MI. If it is successul, MI is updated with the newly created MI and
463 bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
464 MachineInstr *DefMI, unsigned InstrIdx,
465 SmallVector<unsigned, 2> &Ops,
466 bool isSS, int Slot, unsigned Reg);
468 /// canFoldMemoryOperand - Return true if the specified load / store
469 /// folding is possible.
470 bool canFoldMemoryOperand(MachineInstr *MI,
471 SmallVector<unsigned, 2> &Ops,
472 bool ReMatLoadSS) const;
474 /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
475 /// VNInfo that's after the specified index but is within the basic block.
476 bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
477 MachineBasicBlock *MBB, unsigned Idx) const;
479 /// hasAllocatableSuperReg - Return true if the specified physical register
480 /// has any super register that's allocatable.
481 bool hasAllocatableSuperReg(unsigned Reg) const;
483 /// SRInfo - Spill / restore info.
488 SRInfo(int i, unsigned vr, bool f) : index(i), vreg(vr), canFold(f) {};
491 bool alsoFoldARestore(int Id, int index, unsigned vr,
492 BitVector &RestoreMBBs,
493 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
494 void eraseRestoreInfo(int Id, int index, unsigned vr,
495 BitVector &RestoreMBBs,
496 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
498 /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
499 /// spilled and create empty intervals for their uses.
500 void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
501 const TargetRegisterClass* rc,
502 std::vector<LiveInterval*> &NewLIs);
504 /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
505 /// interval on to-be re-materialized operands of MI) with new register.
506 void rewriteImplicitOps(const LiveInterval &li,
507 MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
509 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
510 /// functions for addIntervalsForSpills to rewrite uses / defs for the given
512 bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
513 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
514 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
515 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
516 VirtRegMap &vrm, const TargetRegisterClass* rc,
517 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
518 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
519 DenseMap<unsigned,unsigned> &MBBVRegsMap,
520 std::vector<LiveInterval*> &NewLIs);
521 void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
522 LiveInterval::Ranges::const_iterator &I,
523 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
524 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
525 VirtRegMap &vrm, const TargetRegisterClass* rc,
526 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
527 BitVector &SpillMBBs,
528 DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
529 BitVector &RestoreMBBs,
530 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
531 DenseMap<unsigned,unsigned> &MBBVRegsMap,
532 std::vector<LiveInterval*> &NewLIs);
534 static LiveInterval* createInterval(unsigned Reg);
536 void printRegName(unsigned reg) const;
539 } // End llvm namespace