1 //===-------- SplitKit.h - Toolkit for splitting live ranges ----*- 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 contains the SplitAnalysis class as well as mutator functions for
11 // live range splitting.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/CodeGen/SlotIndexes.h"
26 class MachineLoopInfo;
27 class MachineRegisterInfo;
28 class TargetInstrInfo;
29 class TargetRegisterInfo;
34 /// At some point we should just include MachineDominators.h:
35 class MachineDominatorTree;
36 template <class NodeT> class DomTreeNodeBase;
37 typedef DomTreeNodeBase<MachineBasicBlock> MachineDomTreeNode;
40 /// SplitAnalysis - Analyze a LiveInterval, looking for live range splitting
44 const MachineFunction &MF;
45 const LiveIntervals &LIS;
46 const MachineLoopInfo &Loops;
47 const TargetInstrInfo &TII;
49 // Instructions using the the current register.
50 typedef SmallPtrSet<const MachineInstr*, 16> InstrPtrSet;
51 InstrPtrSet UsingInstrs;
53 // Sorted slot indexes of using instructions.
54 SmallVector<SlotIndex, 8> UseSlots;
56 // The number of instructions using CurLI in each basic block.
57 typedef DenseMap<const MachineBasicBlock*, unsigned> BlockCountMap;
58 BlockCountMap UsingBlocks;
60 // The number of basic block using CurLI in each loop.
61 typedef DenseMap<const MachineLoop*, unsigned> LoopCountMap;
62 LoopCountMap UsingLoops;
65 // Current live interval.
66 const LiveInterval *CurLI;
68 // Sumarize statistics by counting instructions using CurLI.
71 /// canAnalyzeBranch - Return true if MBB ends in a branch that can be
73 bool canAnalyzeBranch(const MachineBasicBlock *MBB);
76 SplitAnalysis(const MachineFunction &mf, const LiveIntervals &lis,
77 const MachineLoopInfo &mli);
79 /// analyze - set CurLI to the specified interval, and analyze how it may be
81 void analyze(const LiveInterval *li);
83 /// clear - clear all data structures so SplitAnalysis is ready to analyze a
87 /// hasUses - Return true if MBB has any uses of CurLI.
88 bool hasUses(const MachineBasicBlock *MBB) const {
89 return UsingBlocks.lookup(MBB);
92 typedef SmallPtrSet<const MachineBasicBlock*, 16> BlockPtrSet;
93 typedef SmallPtrSet<const MachineLoop*, 16> LoopPtrSet;
95 // Print a set of blocks with use counts.
96 void print(const BlockPtrSet&, raw_ostream&) const;
98 // Sets of basic blocks surrounding a machine loop.
100 BlockPtrSet Loop; // Blocks in the loop.
101 BlockPtrSet Preds; // Loop predecessor blocks.
102 BlockPtrSet Exits; // Loop exit blocks.
111 // Print loop blocks with use counts.
112 void print(const LoopBlocks&, raw_ostream&) const;
114 // Calculate the block sets surrounding the loop.
115 void getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks);
117 /// LoopPeripheralUse - how is a variable used in and around a loop?
118 /// Peripheral blocks are the loop predecessors and exit blocks.
119 enum LoopPeripheralUse {
120 ContainedInLoop, // All uses are inside the loop.
121 SinglePeripheral, // At most one instruction per peripheral block.
122 MultiPeripheral, // Multiple instructions in some peripheral blocks.
123 OutsideLoop // Uses outside loop periphery.
126 /// analyzeLoopPeripheralUse - Return an enum describing how CurLI is used in
127 /// and around the Loop.
128 LoopPeripheralUse analyzeLoopPeripheralUse(const LoopBlocks&);
130 /// getCriticalExits - It may be necessary to partially break critical edges
131 /// leaving the loop if an exit block has phi uses of CurLI. Collect the exit
132 /// blocks that need special treatment into CriticalExits.
133 void getCriticalExits(const LoopBlocks &Blocks, BlockPtrSet &CriticalExits);
135 /// canSplitCriticalExits - Return true if it is possible to insert new exit
136 /// blocks before the blocks in CriticalExits.
137 bool canSplitCriticalExits(const LoopBlocks &Blocks,
138 BlockPtrSet &CriticalExits);
140 /// getCriticalPreds - Get the set of loop predecessors with critical edges to
141 /// blocks outside the loop that have CurLI live in. We don't have to break
142 /// these edges, but they do require special treatment.
143 void getCriticalPreds(const LoopBlocks &Blocks, BlockPtrSet &CriticalPreds);
145 /// getSplitLoops - Get the set of loops that have CurLI uses and would be
146 /// profitable to split.
147 void getSplitLoops(LoopPtrSet&);
149 /// getBestSplitLoop - Return the loop where CurLI may best be split to a
150 /// separate register, or NULL.
151 const MachineLoop *getBestSplitLoop();
153 /// isBypassLoop - Return true if CurLI is live through Loop and has no uses
154 /// inside the loop. Bypass loops are candidates for splitting because it can
155 /// prevent interference inside the loop.
156 bool isBypassLoop(const MachineLoop *Loop);
158 /// getBypassLoops - Get all the maximal bypass loops. These are the bypass
159 /// loops whose parent is not a bypass loop.
160 void getBypassLoops(LoopPtrSet&);
162 /// getMultiUseBlocks - Add basic blocks to Blocks that may benefit from
163 /// having CurLI split to a new live interval. Return true if Blocks can be
164 /// passed to SplitEditor::splitSingleBlocks.
165 bool getMultiUseBlocks(BlockPtrSet &Blocks);
167 /// getBlockForInsideSplit - If CurLI is contained inside a single basic
168 /// block, and it would pay to subdivide the interval inside that block,
169 /// return it. Otherwise return NULL. The returned block can be passed to
170 /// SplitEditor::splitInsideBlock.
171 const MachineBasicBlock *getBlockForInsideSplit();
175 /// LiveIntervalMap - Map values from a large LiveInterval into a small
176 /// interval that is a subset. Insert phi-def values as needed. This class is
177 /// used by SplitEditor to create new smaller LiveIntervals.
179 /// ParentLI is the larger interval, LI is the subset interval. Every value
180 /// in LI corresponds to exactly one value in ParentLI, and the live range
181 /// of the value is contained within the live range of the ParentLI value.
182 /// Values in ParentLI may map to any number of OpenLI values, including 0.
183 class LiveIntervalMap {
185 MachineDominatorTree &MDT;
187 // The parent interval is never changed.
188 const LiveInterval &ParentLI;
190 // The child interval's values are fully contained inside ParentLI values.
193 typedef DenseMap<const VNInfo*, VNInfo*> ValueMap;
195 // Map ParentLI values to simple values in LI that are defined at the same
196 // SlotIndex, or NULL for ParentLI values that have complex LI defs.
197 // Note there is a difference between values mapping to NULL (complex), and
198 // values not present (unknown/unmapped).
201 typedef std::pair<VNInfo*, MachineDomTreeNode*> LiveOutPair;
202 typedef DenseMap<MachineBasicBlock*,LiveOutPair> LiveOutMap;
204 // LiveOutCache - Map each basic block where LI is live out to the live-out
205 // value and its defining block. One of these conditions shall be true:
207 // 1. !LiveOutCache.count(MBB)
208 // 2. LiveOutCache[MBB].second.getNode() == MBB
209 // 3. forall P in preds(MBB): LiveOutCache[P] == LiveOutCache[MBB]
211 // This is only a cache, the values can be computed as:
213 // VNI = LI->getVNInfoAt(LIS.getMBBEndIdx(MBB))
214 // Node = mbt_[LIS.getMBBFromIndex(VNI->def)]
216 // The cache is also used as a visiteed set by mapValue().
217 LiveOutMap LiveOutCache;
219 // Dump the live-out cache to dbgs().
223 LiveIntervalMap(LiveIntervals &lis,
224 MachineDominatorTree &mdt,
225 const LiveInterval &parentli)
226 : LIS(lis), MDT(mdt), ParentLI(parentli), LI(0) {}
228 /// reset - clear all data structures and start a new live interval.
229 void reset(LiveInterval *);
231 /// getLI - return the current live interval.
232 LiveInterval *getLI() const { return LI; }
234 /// defValue - define a value in LI from the ParentLI value VNI and Idx.
235 /// Idx does not have to be ParentVNI->def, but it must be contained within
236 /// ParentVNI's live range in ParentLI.
237 /// Return the new LI value.
238 VNInfo *defValue(const VNInfo *ParentVNI, SlotIndex Idx);
240 /// mapValue - map ParentVNI to the corresponding LI value at Idx. It is
241 /// assumed that ParentVNI is live at Idx.
242 /// If ParentVNI has not been defined by defValue, it is assumed that
243 /// ParentVNI->def dominates Idx.
244 /// If ParentVNI has been defined by defValue one or more times, a value that
245 /// dominates Idx will be returned. This may require creating extra phi-def
246 /// values and adding live ranges to LI.
247 /// If simple is not NULL, *simple will indicate if ParentVNI is a simply
249 VNInfo *mapValue(const VNInfo *ParentVNI, SlotIndex Idx, bool *simple = 0);
251 // extendTo - Find the last LI value defined in MBB at or before Idx. The
252 // parentli is assumed to be live at Idx. Extend the live range to include
253 // Idx. Return the found VNInfo, or NULL.
254 VNInfo *extendTo(const MachineBasicBlock *MBB, SlotIndex Idx);
256 /// isMapped - Return true is ParentVNI is a known mapped value. It may be a
257 /// simple 1-1 mapping or a complex mapping to later defs.
258 bool isMapped(const VNInfo *ParentVNI) const {
259 return Values.count(ParentVNI);
262 /// isComplexMapped - Return true if ParentVNI has received new definitions
264 bool isComplexMapped(const VNInfo *ParentVNI) const;
266 // addSimpleRange - Add a simple range from ParentLI to LI.
267 // ParentVNI must be live in the [Start;End) interval.
268 void addSimpleRange(SlotIndex Start, SlotIndex End, const VNInfo *ParentVNI);
270 /// addRange - Add live ranges to LI where [Start;End) intersects ParentLI.
271 /// All needed values whose def is not inside [Start;End) must be defined
272 /// beforehand so mapValue will work.
273 void addRange(SlotIndex Start, SlotIndex End);
277 /// SplitEditor - Edit machine code and LiveIntervals for live range
280 /// - Create a SplitEditor from a SplitAnalysis.
281 /// - Start a new live interval with openIntv.
282 /// - Mark the places where the new interval is entered using enterIntv*
283 /// - Mark the ranges where the new interval is used with useIntv*
284 /// - Mark the places where the interval is exited with exitIntv*.
285 /// - Finish the current interval with closeIntv and repeat from 2.
286 /// - Rewrite instructions with finish().
292 MachineRegisterInfo &MRI;
293 const TargetInstrInfo &TII;
294 const TargetRegisterInfo &TRI;
296 /// Edit - The current parent register and new intervals created.
299 /// DupLI - Created as a copy of CurLI, ranges are carved out as new
300 /// intervals get added through openIntv / closeIntv. This is used to avoid
302 LiveIntervalMap DupLI;
304 /// Currently open LiveInterval.
305 LiveIntervalMap OpenLI;
307 /// defFromParent - Define Reg from ParentVNI at UseIdx using either
308 /// rematerialization or a COPY from parent. Return the new value.
309 VNInfo *defFromParent(LiveIntervalMap &Reg,
312 MachineBasicBlock &MBB,
313 MachineBasicBlock::iterator I);
315 /// intervalsLiveAt - Return true if any member of intervals_ is live at Idx.
316 bool intervalsLiveAt(SlotIndex Idx) const;
318 /// Values in CurLI whose live range has been truncated when entering an open
320 SmallPtrSet<const VNInfo*, 8> truncatedValues;
322 /// addTruncSimpleRange - Add the given simple range to DupLI after
323 /// truncating any overlap with intervals_.
324 void addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI);
326 /// criticalPreds_ - Set of basic blocks where both dupli and OpenLI should be
327 /// live out because of a critical edge.
328 SplitAnalysis::BlockPtrSet criticalPreds_;
330 /// computeRemainder - Compute the dupli liveness as the complement of all the
332 void computeRemainder();
334 /// rewrite - Rewrite all uses of reg to use the new registers.
335 void rewrite(unsigned reg);
338 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
339 /// Newly created intervals will be appended to newIntervals.
340 SplitEditor(SplitAnalysis &SA, LiveIntervals&, VirtRegMap&,
341 MachineDominatorTree&, LiveRangeEdit&);
343 /// getAnalysis - Get the corresponding analysis.
344 SplitAnalysis &getAnalysis() { return sa_; }
346 /// Create a new virtual register and live interval.
349 /// enterIntvBefore - Enter OpenLI before the instruction at Idx. If CurLI is
350 /// not live before Idx, a COPY is not inserted.
351 void enterIntvBefore(SlotIndex Idx);
353 /// enterIntvAtEnd - Enter OpenLI at the end of MBB.
354 void enterIntvAtEnd(MachineBasicBlock &MBB);
356 /// useIntv - indicate that all instructions in MBB should use OpenLI.
357 void useIntv(const MachineBasicBlock &MBB);
359 /// useIntv - indicate that all instructions in range should use OpenLI.
360 void useIntv(SlotIndex Start, SlotIndex End);
362 /// leaveIntvAfter - Leave OpenLI after the instruction at Idx.
363 void leaveIntvAfter(SlotIndex Idx);
365 /// leaveIntvAtTop - Leave the interval at the top of MBB.
366 /// Currently, only one value can leave the interval.
367 void leaveIntvAtTop(MachineBasicBlock &MBB);
369 /// closeIntv - Indicate that we are done editing the currently open
370 /// LiveInterval, and ranges can be trimmed.
373 /// finish - after all the new live ranges have been created, compute the
374 /// remaining live range, and rewrite instructions to use the new registers.
377 // ===--- High level methods ---===
379 /// splitAroundLoop - Split CurLI into a separate live interval inside
381 void splitAroundLoop(const MachineLoop*);
383 /// splitSingleBlocks - Split CurLI into a separate live interval inside each
384 /// basic block in Blocks.
385 void splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks);
387 /// splitInsideBlock - Split CurLI into multiple intervals inside MBB.
388 void splitInsideBlock(const MachineBasicBlock *);