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_LIVEINTERVALANALYSIS_H
21 #define LLVM_CODEGEN_LIVEINTERVALANALYSIS_H
23 #include "llvm/ADT/IndexedMap.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/CodeGen/LiveInterval.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/SlotIndexes.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
38 extern cl::opt<bool> UseSegmentSetForPhysRegs;
44 class MachineDominatorTree;
45 class MachineLoopInfo;
46 class TargetRegisterInfo;
47 class MachineRegisterInfo;
48 class TargetInstrInfo;
49 class TargetRegisterClass;
51 class MachineBlockFrequencyInfo;
53 class LiveIntervals : public MachineFunctionPass {
55 MachineRegisterInfo* MRI;
56 const TargetRegisterInfo* TRI;
57 const TargetInstrInfo* TII;
60 MachineDominatorTree *DomTree;
61 LiveRangeCalc *LRCalc;
63 /// Special pool allocator for VNInfo's (LiveInterval val#).
65 VNInfo::Allocator VNInfoAllocator;
67 /// Live interval pointers for all the virtual registers.
68 IndexedMap<LiveInterval*, VirtReg2IndexFunctor> VirtRegIntervals;
70 /// RegMaskSlots - Sorted list of instructions with register mask operands.
71 /// Always use the 'r' slot, RegMasks are normal clobbers, not early
73 SmallVector<SlotIndex, 8> RegMaskSlots;
75 /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
76 /// pointer to the corresponding register mask. This pointer can be
79 /// MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
80 /// unsigned OpNum = findRegMaskOperand(MI);
81 /// RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
83 /// This is kept in a separate vector partly because some standard
84 /// libraries don't support lower_bound() with mixed objects, partly to
85 /// improve locality when searching in RegMaskSlots.
86 /// Also see the comment in LiveInterval::find().
87 SmallVector<const uint32_t*, 8> RegMaskBits;
89 /// For each basic block number, keep (begin, size) pairs indexing into the
90 /// RegMaskSlots and RegMaskBits arrays.
91 /// Note that basic block numbers may not be layout contiguous, that's why
92 /// we can't just keep track of the first register mask in each basic
94 SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
96 /// Keeps a live range set for each register unit to track fixed physreg
98 SmallVector<LiveRange*, 0> RegUnitRanges;
101 static char ID; // Pass identification, replacement for typeid
103 ~LiveIntervals() override;
105 // Calculate the spill weight to assign to a single instruction.
106 static float getSpillWeight(bool isDef, bool isUse,
107 const MachineBlockFrequencyInfo *MBFI,
108 const MachineInstr *Instr);
110 LiveInterval &getInterval(unsigned Reg) {
111 if (hasInterval(Reg))
112 return *VirtRegIntervals[Reg];
114 return createAndComputeVirtRegInterval(Reg);
117 const LiveInterval &getInterval(unsigned Reg) const {
118 return const_cast<LiveIntervals*>(this)->getInterval(Reg);
121 bool hasInterval(unsigned Reg) const {
122 return VirtRegIntervals.inBounds(Reg) && VirtRegIntervals[Reg];
125 // Interval creation.
126 LiveInterval &createEmptyInterval(unsigned Reg) {
127 assert(!hasInterval(Reg) && "Interval already exists!");
128 VirtRegIntervals.grow(Reg);
129 VirtRegIntervals[Reg] = createInterval(Reg);
130 return *VirtRegIntervals[Reg];
133 LiveInterval &createAndComputeVirtRegInterval(unsigned Reg) {
134 LiveInterval &LI = createEmptyInterval(Reg);
135 computeVirtRegInterval(LI);
140 void removeInterval(unsigned Reg) {
141 delete VirtRegIntervals[Reg];
142 VirtRegIntervals[Reg] = nullptr;
145 /// Given a register and an instruction, adds a live segment from that
146 /// instruction to the end of its MBB.
147 LiveInterval::Segment addSegmentToEndOfBlock(unsigned reg,
148 MachineInstr* startInst);
150 /// After removing some uses of a register, shrink its live range to just
151 /// the remaining uses. This method does not compute reaching defs for new
152 /// uses, and it doesn't remove dead defs.
153 /// Dead PHIDef values are marked as unused. New dead machine instructions
154 /// are added to the dead vector. Returns true if the interval may have been
155 /// separated into multiple connected components.
156 bool shrinkToUses(LiveInterval *li,
157 SmallVectorImpl<MachineInstr*> *dead = nullptr);
159 /// Specialized version of
160 /// shrinkToUses(LiveInterval *li, SmallVectorImpl<MachineInstr*> *dead)
161 /// that works on a subregister live range and only looks at uses matching
162 /// the lane mask of the subregister range.
163 /// This may leave the subrange empty which needs to be cleaned up with
164 /// LiveInterval::removeEmptySubranges() afterwards.
165 void shrinkToUses(LiveInterval::SubRange &SR, unsigned Reg);
167 /// extendToIndices - Extend the live range of LI to reach all points in
168 /// Indices. The points in the Indices array must be jointly dominated by
169 /// existing defs in LI. PHI-defs are added as needed to maintain SSA form.
171 /// If a SlotIndex in Indices is the end index of a basic block, LI will be
172 /// extended to be live out of the basic block.
174 /// See also LiveRangeCalc::extend().
175 void extendToIndices(LiveRange &LR, ArrayRef<SlotIndex> Indices);
178 /// If @p LR has a live value at @p Kill, prune its live range by removing
179 /// any liveness reachable from Kill. Add live range end points to
180 /// EndPoints such that extendToIndices(LI, EndPoints) will reconstruct the
181 /// value's live range.
183 /// Calling pruneValue() and extendToIndices() can be used to reconstruct
184 /// SSA form after adding defs to a virtual register.
185 void pruneValue(LiveRange &LR, SlotIndex Kill,
186 SmallVectorImpl<SlotIndex> *EndPoints);
188 SlotIndexes *getSlotIndexes() const {
192 AliasAnalysis *getAliasAnalysis() const {
196 /// isNotInMIMap - returns true if the specified machine instr has been
197 /// removed or was never entered in the map.
198 bool isNotInMIMap(const MachineInstr* Instr) const {
199 return !Indexes->hasIndex(Instr);
202 /// Returns the base index of the given instruction.
203 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
204 return Indexes->getInstructionIndex(instr);
207 /// Returns the instruction associated with the given index.
208 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
209 return Indexes->getInstructionFromIndex(index);
212 /// Return the first index in the given basic block.
213 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
214 return Indexes->getMBBStartIdx(mbb);
217 /// Return the last index in the given basic block.
218 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
219 return Indexes->getMBBEndIdx(mbb);
222 bool isLiveInToMBB(const LiveRange &LR,
223 const MachineBasicBlock *mbb) const {
224 return LR.liveAt(getMBBStartIdx(mbb));
227 bool isLiveOutOfMBB(const LiveRange &LR,
228 const MachineBasicBlock *mbb) const {
229 return LR.liveAt(getMBBEndIdx(mbb).getPrevSlot());
232 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
233 return Indexes->getMBBFromIndex(index);
236 void insertMBBInMaps(MachineBasicBlock *MBB) {
237 Indexes->insertMBBInMaps(MBB);
238 assert(unsigned(MBB->getNumber()) == RegMaskBlocks.size() &&
239 "Blocks must be added in order.");
240 RegMaskBlocks.push_back(std::make_pair(RegMaskSlots.size(), 0));
243 SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
244 return Indexes->insertMachineInstrInMaps(MI);
247 void InsertMachineInstrRangeInMaps(MachineBasicBlock::iterator B,
248 MachineBasicBlock::iterator E) {
249 for (MachineBasicBlock::iterator I = B; I != E; ++I)
250 Indexes->insertMachineInstrInMaps(I);
253 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
254 Indexes->removeMachineInstrFromMaps(MI);
257 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
258 Indexes->replaceMachineInstrInMaps(MI, NewMI);
261 VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
263 void getAnalysisUsage(AnalysisUsage &AU) const override;
264 void releaseMemory() override;
266 /// runOnMachineFunction - pass entry point
267 bool runOnMachineFunction(MachineFunction&) override;
269 /// print - Implement the dump method.
270 void print(raw_ostream &O, const Module* = nullptr) const override;
272 /// intervalIsInOneMBB - If LI is confined to a single basic block, return
273 /// a pointer to that block. If LI is live in to or out of any block,
275 MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
277 /// Returns true if VNI is killed by any PHI-def values in LI.
278 /// This may conservatively return true to avoid expensive computations.
279 bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const;
281 /// addKillFlags - Add kill flags to any instruction that kills a virtual
283 void addKillFlags(const VirtRegMap*);
285 /// handleMove - call this method to notify LiveIntervals that
286 /// instruction 'mi' has been moved within a basic block. This will update
287 /// the live intervals for all operands of mi. Moves between basic blocks
288 /// are not supported.
290 /// \param UpdateFlags Update live intervals for nonallocatable physregs.
291 void handleMove(MachineInstr* MI, bool UpdateFlags = false);
293 /// moveIntoBundle - Update intervals for operands of MI so that they
294 /// begin/end on the SlotIndex for BundleStart.
296 /// \param UpdateFlags Update live intervals for nonallocatable physregs.
298 /// Requires MI and BundleStart to have SlotIndexes, and assumes
299 /// existing liveness is accurate. BundleStart should be the first
300 /// instruction in the Bundle.
301 void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart,
302 bool UpdateFlags = false);
304 /// repairIntervalsInRange - Update live intervals for instructions in a
305 /// range of iterators. It is intended for use after target hooks that may
306 /// insert or remove instructions, and is only efficient for a small number
309 /// OrigRegs is a vector of registers that were originally used by the
310 /// instructions in the range between the two iterators.
312 /// Currently, the only only changes that are supported are simple removal
313 /// and addition of uses.
314 void repairIntervalsInRange(MachineBasicBlock *MBB,
315 MachineBasicBlock::iterator Begin,
316 MachineBasicBlock::iterator End,
317 ArrayRef<unsigned> OrigRegs);
319 // Register mask functions.
321 // Machine instructions may use a register mask operand to indicate that a
322 // large number of registers are clobbered by the instruction. This is
323 // typically used for calls.
325 // For compile time performance reasons, these clobbers are not recorded in
326 // the live intervals for individual physical registers. Instead,
327 // LiveIntervalAnalysis maintains a sorted list of instructions with
328 // register mask operands.
330 /// getRegMaskSlots - Returns a sorted array of slot indices of all
331 /// instructions with register mask operands.
332 ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
334 /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
335 /// instructions with register mask operands in the basic block numbered
337 ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
338 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
339 return getRegMaskSlots().slice(P.first, P.second);
342 /// getRegMaskBits() - Returns an array of register mask pointers
343 /// corresponding to getRegMaskSlots().
344 ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
346 /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
347 /// to getRegMaskSlotsInBlock(MBBNum).
348 ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
349 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
350 return getRegMaskBits().slice(P.first, P.second);
353 /// checkRegMaskInterference - Test if LI is live across any register mask
354 /// instructions, and compute a bit mask of physical registers that are not
355 /// clobbered by any of them.
357 /// Returns false if LI doesn't cross any register mask instructions. In
358 /// that case, the bit vector is not filled in.
359 bool checkRegMaskInterference(LiveInterval &LI,
360 BitVector &UsableRegs);
362 // Register unit functions.
364 // Fixed interference occurs when MachineInstrs use physregs directly
365 // instead of virtual registers. This typically happens when passing
366 // arguments to a function call, or when instructions require operands in
369 // Each physreg has one or more register units, see MCRegisterInfo. We
370 // track liveness per register unit to handle aliasing registers more
373 /// getRegUnit - Return the live range for Unit.
374 /// It will be computed if it doesn't exist.
375 LiveRange &getRegUnit(unsigned Unit) {
376 LiveRange *LR = RegUnitRanges[Unit];
378 // Compute missing ranges on demand.
379 // Use segment set to speed-up initial computation of the live range.
380 RegUnitRanges[Unit] = LR = new LiveRange(UseSegmentSetForPhysRegs);
381 computeRegUnitRange(*LR, Unit);
386 /// getCachedRegUnit - Return the live range for Unit if it has already
387 /// been computed, or NULL if it hasn't been computed yet.
388 LiveRange *getCachedRegUnit(unsigned Unit) {
389 return RegUnitRanges[Unit];
392 const LiveRange *getCachedRegUnit(unsigned Unit) const {
393 return RegUnitRanges[Unit];
396 /// Remove value numbers and related live segments starting at position
397 /// @p Pos that are part of any liverange of physical register @p Reg or one
398 /// of its subregisters.
399 void removePhysRegDefAt(unsigned Reg, SlotIndex Pos);
401 /// Remove value number and related live segments of @p LI and its subranges
402 /// that start at position @p Pos.
403 void removeVRegDefAt(LiveInterval &LI, SlotIndex Pos);
405 /// Split separate components in LiveInterval \p LI into separate intervals.
406 void splitSeparateComponents(LiveInterval &LI,
407 SmallVectorImpl<LiveInterval*> &SplitLIs);
410 /// Compute live intervals for all virtual registers.
411 void computeVirtRegs();
413 /// Compute RegMaskSlots and RegMaskBits.
414 void computeRegMasks();
416 /// Walk the values in @p LI and check for dead values:
417 /// - Dead PHIDef values are marked as unused.
418 /// - Dead operands are marked as such.
419 /// - Completely dead machine instructions are added to the @p dead vector
420 /// if it is not nullptr.
421 /// Returns true if any PHI value numbers have been removed which may
422 /// have separated the interval into multiple connected components.
423 bool computeDeadValues(LiveInterval &LI,
424 SmallVectorImpl<MachineInstr*> *dead);
426 static LiveInterval* createInterval(unsigned Reg);
428 void printInstrs(raw_ostream &O) const;
429 void dumpInstrs() const;
431 void computeLiveInRegUnits();
432 void computeRegUnitRange(LiveRange&, unsigned Unit);
433 void computeVirtRegInterval(LiveInterval&);
436 /// Helper function for repairIntervalsInRange(), walks backwards and
437 /// creates/modifies live segments in @p LR to match the operands found.
438 /// Only full operands or operands with subregisters matching @p LaneMask
440 void repairOldRegInRange(MachineBasicBlock::iterator Begin,
441 MachineBasicBlock::iterator End,
442 const SlotIndex endIdx, LiveRange &LR,
443 unsigned Reg, LaneBitmask LaneMask = ~0u);
447 } // End llvm namespace