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_;
66 /// Special pool allocator for VNInfo's (LiveInterval val#).
68 BumpPtrAllocator VNInfoAllocator;
70 /// MBB2IdxMap - The indexes of the first and last instructions in the
71 /// specified basic block.
72 std::vector<std::pair<unsigned, unsigned> > MBB2IdxMap;
74 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
76 std::vector<IdxMBBPair> Idx2MBBMap;
78 typedef std::map<MachineInstr*, unsigned> Mi2IndexMap;
81 typedef std::vector<MachineInstr*> Index2MiMap;
84 typedef std::map<unsigned, LiveInterval> Reg2IntervalMap;
85 Reg2IntervalMap r2iMap_;
87 BitVector allocatableRegs_;
89 std::vector<MachineInstr*> ClonedMIs;
92 static char ID; // Pass identification, replacement for typeid
93 LiveIntervals() : MachineFunctionPass((intptr_t)&ID) {}
105 static unsigned getBaseIndex(unsigned index) {
106 return index - (index % InstrSlots::NUM);
108 static unsigned getBoundaryIndex(unsigned index) {
109 return getBaseIndex(index + InstrSlots::NUM - 1);
111 static unsigned getLoadIndex(unsigned index) {
112 return getBaseIndex(index) + InstrSlots::LOAD;
114 static unsigned getUseIndex(unsigned index) {
115 return getBaseIndex(index) + InstrSlots::USE;
117 static unsigned getDefIndex(unsigned index) {
118 return getBaseIndex(index) + InstrSlots::DEF;
120 static unsigned getStoreIndex(unsigned index) {
121 return getBaseIndex(index) + InstrSlots::STORE;
124 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
125 return (isDef + isUse) * powf(10.0F, (float)loopDepth);
128 typedef Reg2IntervalMap::iterator iterator;
129 typedef Reg2IntervalMap::const_iterator const_iterator;
130 const_iterator begin() const { return r2iMap_.begin(); }
131 const_iterator end() const { return r2iMap_.end(); }
132 iterator begin() { return r2iMap_.begin(); }
133 iterator end() { return r2iMap_.end(); }
134 unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
136 LiveInterval &getInterval(unsigned reg) {
137 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
138 assert(I != r2iMap_.end() && "Interval does not exist for register");
142 const LiveInterval &getInterval(unsigned reg) const {
143 Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
144 assert(I != r2iMap_.end() && "Interval does not exist for register");
148 bool hasInterval(unsigned reg) const {
149 return r2iMap_.count(reg);
152 /// getMBBStartIdx - Return the base index of the first instruction in the
153 /// specified MachineBasicBlock.
154 unsigned getMBBStartIdx(MachineBasicBlock *MBB) const {
155 return getMBBStartIdx(MBB->getNumber());
157 unsigned getMBBStartIdx(unsigned MBBNo) const {
158 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
159 return MBB2IdxMap[MBBNo].first;
162 /// getMBBEndIdx - Return the store index of the last instruction in the
163 /// specified MachineBasicBlock.
164 unsigned getMBBEndIdx(MachineBasicBlock *MBB) const {
165 return getMBBEndIdx(MBB->getNumber());
167 unsigned getMBBEndIdx(unsigned MBBNo) const {
168 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
169 return MBB2IdxMap[MBBNo].second;
172 /// getMBBFromIndex - given an index in any instruction of an
173 /// MBB return a pointer the MBB
174 MachineBasicBlock* getMBBFromIndex(unsigned index) const {
175 std::vector<IdxMBBPair>::const_iterator I =
176 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
177 // Take the pair containing the index
178 std::vector<IdxMBBPair>::const_iterator J =
179 ((I != Idx2MBBMap.end() && I->first > index) ||
180 (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
182 assert(J != Idx2MBBMap.end() && J->first < index+1 &&
183 index <= getMBBEndIdx(J->second) &&
184 "index does not correspond to an MBB");
188 /// getInstructionIndex - returns the base index of instr
189 unsigned getInstructionIndex(MachineInstr* instr) const {
190 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
191 assert(it != mi2iMap_.end() && "Invalid instruction!");
195 /// getInstructionFromIndex - given an index in any slot of an
196 /// instruction return a pointer the instruction
197 MachineInstr* getInstructionFromIndex(unsigned index) const {
198 index /= InstrSlots::NUM; // convert index to vector index
199 assert(index < i2miMap_.size() &&
200 "index does not correspond to an instruction");
201 return i2miMap_[index];
204 /// conflictsWithPhysRegDef - Returns true if the specified register
205 /// is defined during the duration of the specified interval.
206 bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
209 /// findLiveInMBBs - Given a live range, if the value of the range
210 /// is live in any MBB returns true as well as the list of basic blocks
211 /// where the value is live in.
212 bool findLiveInMBBs(const LiveRange &LR,
213 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
217 LiveInterval &getOrCreateInterval(unsigned reg) {
218 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
219 if (I == r2iMap_.end())
220 I = r2iMap_.insert(I, std::make_pair(reg, createInterval(reg)));
224 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
225 /// adds a live range from that instruction to the end of its MBB.
226 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
227 MachineInstr* startInst);
231 void removeInterval(unsigned Reg) {
235 /// isRemoved - returns true if the specified machine instr has been
237 bool isRemoved(MachineInstr* instr) const {
238 return !mi2iMap_.count(instr);
241 /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
243 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
244 // remove index -> MachineInstr and
245 // MachineInstr -> index mappings
246 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
247 if (mi2i != mi2iMap_.end()) {
248 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
249 mi2iMap_.erase(mi2i);
253 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
254 /// maps used by register allocator.
255 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
256 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
257 if (mi2i == mi2iMap_.end())
259 i2miMap_[mi2i->second/InstrSlots::NUM] = NewMI;
260 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
261 assert(it != mi2iMap_.end() && "Invalid instruction!");
262 unsigned Index = it->second;
264 mi2iMap_[NewMI] = Index;
267 BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
269 /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
270 /// copy field and returns the source register that defines it.
271 unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
273 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
274 virtual void releaseMemory();
276 /// runOnMachineFunction - pass entry point
277 virtual bool runOnMachineFunction(MachineFunction&);
279 /// print - Implement the dump method.
280 virtual void print(std::ostream &O, const Module* = 0) const;
281 void print(std::ostream *O, const Module* M = 0) const {
285 /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
286 /// the given interval. FIXME: It also returns the weight of the spill slot
287 /// (if any is created) by reference. This is temporary.
288 std::vector<LiveInterval*>
289 addIntervalsForSpills(const LiveInterval& i,
290 const MachineLoopInfo *loopInfo, VirtRegMap& vrm,
293 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
294 /// around all defs and uses of the specified interval.
295 void spillPhysRegAroundRegDefsUses(const LiveInterval &li,
296 unsigned PhysReg, VirtRegMap &vrm);
298 /// isReMaterializable - Returns true if every definition of MI of every
299 /// val# of the specified interval is re-materializable. Also returns true
300 /// by reference if all of the defs are load instructions.
301 bool isReMaterializable(const LiveInterval &li, bool &isLoad);
303 /// getRepresentativeReg - Find the largest super register of the specified
304 /// physical register.
305 unsigned getRepresentativeReg(unsigned Reg) const;
307 /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
308 /// specified interval that conflicts with the specified physical register.
309 unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
310 unsigned PhysReg) const;
312 /// computeNumbering - Compute the index numbering.
313 void computeNumbering();
316 /// computeIntervals - Compute live intervals.
317 void computeIntervals();
319 /// handleRegisterDef - update intervals for a register def
320 /// (calls handlePhysicalRegisterDef and
321 /// handleVirtualRegisterDef)
322 void handleRegisterDef(MachineBasicBlock *MBB,
323 MachineBasicBlock::iterator MI, unsigned MIIdx,
326 /// handleVirtualRegisterDef - update intervals for a virtual
328 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
329 MachineBasicBlock::iterator MI,
331 LiveInterval& interval);
333 /// handlePhysicalRegisterDef - update intervals for a physical register
335 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
336 MachineBasicBlock::iterator mi,
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 unsigned 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,
362 MachineInstr *MI, bool &isLoad);
364 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
365 /// slot / to reg or any rematerialized load into ith operand of specified
366 /// MI. If it is successul, MI is updated with the newly created MI and
368 bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
369 MachineInstr *DefMI, unsigned InstrIdx,
370 SmallVector<unsigned, 2> &Ops,
371 bool isSS, int Slot, unsigned Reg);
373 /// canFoldMemoryOperand - Return true if the specified load / store
374 /// folding is possible.
375 bool canFoldMemoryOperand(MachineInstr *MI,
376 SmallVector<unsigned, 2> &Ops,
377 bool ReMatLoadSS) const;
379 /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
380 /// VNInfo that's after the specified index but is within the basic block.
381 bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
382 MachineBasicBlock *MBB, unsigned Idx) const;
384 /// intervalIsInOneMBB - Returns true if the specified interval is entirely
385 /// within a single basic block.
386 bool intervalIsInOneMBB(const LiveInterval &li) const;
388 /// hasAllocatableSuperReg - Return true if the specified physical register
389 /// has any super register that's allocatable.
390 bool hasAllocatableSuperReg(unsigned Reg) const;
392 /// SRInfo - Spill / restore info.
397 SRInfo(int i, unsigned vr, bool f) : index(i), vreg(vr), canFold(f) {};
400 bool alsoFoldARestore(int Id, int index, unsigned vr,
401 BitVector &RestoreMBBs,
402 std::map<unsigned,std::vector<SRInfo> >&RestoreIdxes);
403 void eraseRestoreInfo(int Id, int index, unsigned vr,
404 BitVector &RestoreMBBs,
405 std::map<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, unsigned index, unsigned end, MachineInstr *MI,
423 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
424 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
425 VirtRegMap &vrm, const TargetRegisterClass* rc,
426 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
427 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
428 std::map<unsigned,unsigned> &MBBVRegsMap,
429 std::vector<LiveInterval*> &NewLIs, float &SSWeight);
430 void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
431 LiveInterval::Ranges::const_iterator &I,
432 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
433 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
434 VirtRegMap &vrm, const TargetRegisterClass* rc,
435 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
436 BitVector &SpillMBBs,
437 std::map<unsigned,std::vector<SRInfo> > &SpillIdxes,
438 BitVector &RestoreMBBs,
439 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes,
440 std::map<unsigned,unsigned> &MBBVRegsMap,
441 std::vector<LiveInterval*> &NewLIs, float &SSWeight);
443 static LiveInterval createInterval(unsigned Reg);
445 void printRegName(unsigned reg) const;
448 } // End llvm namespace