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 BumpPtrAllocator 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) {}
73 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
74 return (isDef + isUse) * powf(10.0F, (float)loopDepth);
77 typedef Reg2IntervalMap::iterator iterator;
78 typedef Reg2IntervalMap::const_iterator const_iterator;
79 const_iterator begin() const { return r2iMap_.begin(); }
80 const_iterator end() const { return r2iMap_.end(); }
81 iterator begin() { return r2iMap_.begin(); }
82 iterator end() { return r2iMap_.end(); }
83 unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
85 LiveInterval &getInterval(unsigned reg) {
86 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
87 assert(I != r2iMap_.end() && "Interval does not exist for register");
91 const LiveInterval &getInterval(unsigned reg) const {
92 Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
93 assert(I != r2iMap_.end() && "Interval does not exist for register");
97 bool hasInterval(unsigned reg) const {
98 return r2iMap_.count(reg);
101 /// getScaledIntervalSize - get the size of an interval in "units,"
102 /// where every function is composed of one thousand units. This
103 /// measure scales properly with empty index slots in the function.
104 double getScaledIntervalSize(LiveInterval& I) {
105 return (1000.0 * I.getSize()) / indexes_->getIndexesLength();
108 /// getApproximateInstructionCount - computes an estimate of the number
109 /// of instructions in a given LiveInterval.
110 unsigned getApproximateInstructionCount(LiveInterval& I) {
111 double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
112 return (unsigned)(IntervalPercentage * indexes_->getFunctionSize());
115 /// conflictsWithPhysRegDef - Returns true if the specified register
116 /// is defined during the duration of the specified interval.
117 bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
120 /// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
121 /// it can check use as well.
122 bool conflictsWithPhysRegRef(LiveInterval &li, unsigned Reg,
124 SmallPtrSet<MachineInstr*,32> &JoinedCopies);
127 LiveInterval &getOrCreateInterval(unsigned reg) {
128 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
129 if (I == r2iMap_.end())
130 I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
134 /// dupInterval - Duplicate a live interval. The caller is responsible for
135 /// managing the allocated memory.
136 LiveInterval *dupInterval(LiveInterval *li);
138 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
139 /// adds a live range from that instruction to the end of its MBB.
140 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
141 MachineInstr* startInst);
145 void removeInterval(unsigned Reg) {
146 DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
151 SlotIndex getZeroIndex() const {
152 return indexes_->getZeroIndex();
155 SlotIndex getInvalidIndex() const {
156 return indexes_->getInvalidIndex();
159 /// isNotInMIMap - returns true if the specified machine instr has been
160 /// removed or was never entered in the map.
161 bool isNotInMIMap(const MachineInstr* Instr) const {
162 return !indexes_->hasIndex(Instr);
165 /// Returns the base index of the given instruction.
166 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
167 return indexes_->getInstructionIndex(instr);
170 /// Returns the instruction associated with the given index.
171 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
172 return indexes_->getInstructionFromIndex(index);
175 /// Return the first index in the given basic block.
176 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
177 return indexes_->getMBBStartIdx(mbb);
180 /// Return the last index in the given basic block.
181 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
182 return indexes_->getMBBEndIdx(mbb);
185 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
186 return indexes_->getMBBFromIndex(index);
189 SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
190 return indexes_->insertMachineInstrInMaps(MI);
193 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
194 indexes_->removeMachineInstrFromMaps(MI);
197 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
198 indexes_->replaceMachineInstrInMaps(MI, NewMI);
201 bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
202 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
203 return indexes_->findLiveInMBBs(Start, End, MBBs);
207 indexes_->renumberIndexes();
210 BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
212 /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
213 /// copy field and returns the source register that defines it.
214 unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
216 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
217 virtual void releaseMemory();
219 /// runOnMachineFunction - pass entry point
220 virtual bool runOnMachineFunction(MachineFunction&);
222 /// print - Implement the dump method.
223 virtual void print(raw_ostream &O, const Module* = 0) const;
225 /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
226 /// the given interval. FIXME: It also returns the weight of the spill slot
227 /// (if any is created) by reference. This is temporary.
228 std::vector<LiveInterval*>
229 addIntervalsForSpills(const LiveInterval& i,
230 SmallVectorImpl<LiveInterval*> &SpillIs,
231 const MachineLoopInfo *loopInfo, VirtRegMap& vrm);
233 /// addIntervalsForSpillsFast - Quickly create new intervals for spilled
234 /// defs / uses without remat or splitting.
235 std::vector<LiveInterval*>
236 addIntervalsForSpillsFast(const LiveInterval &li,
237 const MachineLoopInfo *loopInfo, VirtRegMap &vrm);
239 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
240 /// around all defs and uses of the specified interval. Return true if it
241 /// was able to cut its interval.
242 bool spillPhysRegAroundRegDefsUses(const LiveInterval &li,
243 unsigned PhysReg, VirtRegMap &vrm);
245 /// isReMaterializable - Returns true if every definition of MI of every
246 /// val# of the specified interval is re-materializable. Also returns true
247 /// by reference if all of the defs are load instructions.
248 bool isReMaterializable(const LiveInterval &li,
249 SmallVectorImpl<LiveInterval*> &SpillIs,
252 /// isReMaterializable - Returns true if the definition MI of the specified
253 /// val# of the specified interval is re-materializable.
254 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
257 /// getRepresentativeReg - Find the largest super register of the specified
258 /// physical register.
259 unsigned getRepresentativeReg(unsigned Reg) const;
261 /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
262 /// specified interval that conflicts with the specified physical register.
263 unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
264 unsigned PhysReg) const;
266 /// processImplicitDefs - Process IMPLICIT_DEF instructions. Add isUndef
267 /// marker to implicit_def defs and their uses.
268 void processImplicitDefs();
270 /// intervalIsInOneMBB - Returns true if the specified interval is entirely
271 /// within a single basic block.
272 bool intervalIsInOneMBB(const LiveInterval &li) const;
275 /// computeIntervals - Compute live intervals.
276 void computeIntervals();
278 /// handleRegisterDef - update intervals for a register def
279 /// (calls handlePhysicalRegisterDef and
280 /// handleVirtualRegisterDef)
281 void handleRegisterDef(MachineBasicBlock *MBB,
282 MachineBasicBlock::iterator MI,
284 MachineOperand& MO, unsigned MOIdx);
286 /// handleVirtualRegisterDef - update intervals for a virtual
288 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
289 MachineBasicBlock::iterator MI,
290 SlotIndex MIIdx, MachineOperand& MO,
292 LiveInterval& interval);
294 /// handlePhysicalRegisterDef - update intervals for a physical register
296 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
297 MachineBasicBlock::iterator mi,
298 SlotIndex MIIdx, MachineOperand& MO,
299 LiveInterval &interval,
300 MachineInstr *CopyMI);
302 /// handleLiveInRegister - Create interval for a livein register.
303 void handleLiveInRegister(MachineBasicBlock* mbb,
305 LiveInterval &interval, bool isAlias = false);
307 /// getReMatImplicitUse - If the remat definition MI has one (for now, we
308 /// only allow one) virtual register operand, then its uses are implicitly
309 /// using the register. Returns the virtual register.
310 unsigned getReMatImplicitUse(const LiveInterval &li,
311 MachineInstr *MI) const;
313 /// isValNoAvailableAt - Return true if the val# of the specified interval
314 /// which reaches the given instruction also reaches the specified use
316 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
317 SlotIndex UseIdx) const;
319 /// isReMaterializable - Returns true if the definition MI of the specified
320 /// val# of the specified interval is re-materializable. Also returns true
321 /// by reference if the def is a load.
322 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
324 SmallVectorImpl<LiveInterval*> &SpillIs,
327 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
328 /// slot / to reg or any rematerialized load into ith operand of specified
329 /// MI. If it is successul, MI is updated with the newly created MI and
331 bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
332 MachineInstr *DefMI, SlotIndex InstrIdx,
333 SmallVector<unsigned, 2> &Ops,
334 bool isSS, int FrameIndex, unsigned Reg);
336 /// canFoldMemoryOperand - Return true if the specified load / store
337 /// folding is possible.
338 bool canFoldMemoryOperand(MachineInstr *MI,
339 SmallVector<unsigned, 2> &Ops,
340 bool ReMatLoadSS) const;
342 /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
343 /// VNInfo that's after the specified index but is within the basic block.
344 bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
345 MachineBasicBlock *MBB,
346 SlotIndex Idx) const;
348 /// hasAllocatableSuperReg - Return true if the specified physical register
349 /// has any super register that's allocatable.
350 bool hasAllocatableSuperReg(unsigned Reg) const;
352 /// SRInfo - Spill / restore info.
357 SRInfo(SlotIndex i, unsigned vr, bool f)
358 : index(i), vreg(vr), canFold(f) {}
361 bool alsoFoldARestore(int Id, SlotIndex index, unsigned vr,
362 BitVector &RestoreMBBs,
363 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
364 void eraseRestoreInfo(int Id, SlotIndex index, unsigned vr,
365 BitVector &RestoreMBBs,
366 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
368 /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
369 /// spilled and create empty intervals for their uses.
370 void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
371 const TargetRegisterClass* rc,
372 std::vector<LiveInterval*> &NewLIs);
374 /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
375 /// interval on to-be re-materialized operands of MI) with new register.
376 void rewriteImplicitOps(const LiveInterval &li,
377 MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
379 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
380 /// functions for addIntervalsForSpills to rewrite uses / defs for the given
382 bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
383 bool TrySplit, SlotIndex index, SlotIndex end,
384 MachineInstr *MI, MachineInstr *OrigDefMI, MachineInstr *DefMI,
385 unsigned Slot, int LdSlot,
386 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
387 VirtRegMap &vrm, const TargetRegisterClass* rc,
388 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
389 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
390 DenseMap<unsigned,unsigned> &MBBVRegsMap,
391 std::vector<LiveInterval*> &NewLIs);
392 void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
393 LiveInterval::Ranges::const_iterator &I,
394 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
395 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
396 VirtRegMap &vrm, const TargetRegisterClass* rc,
397 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
398 BitVector &SpillMBBs,
399 DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
400 BitVector &RestoreMBBs,
401 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
402 DenseMap<unsigned,unsigned> &MBBVRegsMap,
403 std::vector<LiveInterval*> &NewLIs);
405 static LiveInterval* createInterval(unsigned Reg);
407 void printInstrs(raw_ostream &O) const;
408 void dumpInstrs() const;
410 } // End llvm namespace