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 #ifndef LLVM_CODEGEN_SPLITKIT_H
16 #define LLVM_CODEGEN_SPLITKIT_H
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/IndexedMap.h"
22 #include "llvm/ADT/IntervalMap.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/CodeGen/SlotIndexes.h"
28 class ConnectedVNInfoEqClasses;
33 class MachineLoopInfo;
34 class MachineRegisterInfo;
35 class TargetInstrInfo;
36 class TargetRegisterInfo;
41 /// At some point we should just include MachineDominators.h:
42 class MachineDominatorTree;
43 template <class NodeT> class DomTreeNodeBase;
44 typedef DomTreeNodeBase<MachineBasicBlock> MachineDomTreeNode;
47 /// SplitAnalysis - Analyze a LiveInterval, looking for live range splitting
51 const MachineFunction &MF;
52 const VirtRegMap &VRM;
53 const LiveIntervals &LIS;
54 const MachineLoopInfo &Loops;
55 const TargetInstrInfo &TII;
57 // Sorted slot indexes of using instructions.
58 SmallVector<SlotIndex, 8> UseSlots;
60 /// Additional information about basic blocks where the current variable is
61 /// live. Such a block will look like one of these templates:
63 /// 1. | o---x | Internal to block. Variable is only live in this block.
64 /// 2. |---x | Live-in, kill.
65 /// 3. | o---| Def, live-out.
66 /// 4. |---x o---| Live-in, kill, def, live-out. Counted by NumGapBlocks.
67 /// 5. |---o---o---| Live-through with uses or defs.
68 /// 6. |-----------| Live-through without uses. Counted by NumThroughBlocks.
70 /// Two BlockInfo entries are created for template 4. One for the live-in
71 /// segment, and one for the live-out segment. These entries look as if the
72 /// block were split in the middle where the live range isn't live.
74 /// Live-through blocks without any uses don't get BlockInfo entries. They
75 /// are simply listed in ThroughBlocks instead.
78 MachineBasicBlock *MBB;
79 SlotIndex FirstInstr; ///< First instr accessing current reg.
80 SlotIndex LastInstr; ///< Last instr accessing current reg.
81 SlotIndex FirstDef; ///< First non-phi valno->def, or SlotIndex().
82 bool LiveIn; ///< Current reg is live in.
83 bool LiveOut; ///< Current reg is live out.
85 /// isOneInstr - Returns true when this BlockInfo describes a single
87 bool isOneInstr() const {
88 return SlotIndex::isSameInstr(FirstInstr, LastInstr);
93 // Current live interval.
94 const LiveInterval *CurLI;
96 /// LastSplitPoint - Last legal split point in each basic block in the current
97 /// function. The first entry is the first terminator, the second entry is the
98 /// last valid split point for a variable that is live in to a landing pad
100 SmallVector<std::pair<SlotIndex, SlotIndex>, 8> LastSplitPoint;
102 /// UseBlocks - Blocks where CurLI has uses.
103 SmallVector<BlockInfo, 8> UseBlocks;
105 /// NumGapBlocks - Number of duplicate entries in UseBlocks for blocks where
106 /// the live range has a gap.
107 unsigned NumGapBlocks;
109 /// ThroughBlocks - Block numbers where CurLI is live through without uses.
110 BitVector ThroughBlocks;
112 /// NumThroughBlocks - Number of live-through blocks.
113 unsigned NumThroughBlocks;
115 /// DidRepairRange - analyze was forced to shrinkToUses().
118 SlotIndex computeLastSplitPoint(unsigned Num);
120 // Sumarize statistics by counting instructions using CurLI.
123 /// calcLiveBlockInfo - Compute per-block information about CurLI.
124 bool calcLiveBlockInfo();
127 SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
128 const MachineLoopInfo &mli);
130 /// analyze - set CurLI to the specified interval, and analyze how it may be
132 void analyze(const LiveInterval *li);
134 /// didRepairRange() - Returns true if CurLI was invalid and has been repaired
135 /// by analyze(). This really shouldn't happen, but sometimes the coalescer
136 /// can create live ranges that end in mid-air.
137 bool didRepairRange() const { return DidRepairRange; }
139 /// clear - clear all data structures so SplitAnalysis is ready to analyze a
143 /// getParent - Return the last analyzed interval.
144 const LiveInterval &getParent() const { return *CurLI; }
146 /// getLastSplitPoint - Return that base index of the last valid split point
147 /// in the basic block numbered Num.
148 SlotIndex getLastSplitPoint(unsigned Num) {
149 // Inline the common simple case.
150 if (LastSplitPoint[Num].first.isValid() &&
151 !LastSplitPoint[Num].second.isValid())
152 return LastSplitPoint[Num].first;
153 return computeLastSplitPoint(Num);
156 /// isOriginalEndpoint - Return true if the original live range was killed or
157 /// (re-)defined at Idx. Idx should be the 'def' slot for a normal kill/def,
158 /// and 'use' for an early-clobber def.
159 /// This can be used to recognize code inserted by earlier live range
161 bool isOriginalEndpoint(SlotIndex Idx) const;
163 /// getUseBlocks - Return an array of BlockInfo objects for the basic blocks
164 /// where CurLI has uses.
165 ArrayRef<BlockInfo> getUseBlocks() const { return UseBlocks; }
167 /// getNumThroughBlocks - Return the number of through blocks.
168 unsigned getNumThroughBlocks() const { return NumThroughBlocks; }
170 /// isThroughBlock - Return true if CurLI is live through MBB without uses.
171 bool isThroughBlock(unsigned MBB) const { return ThroughBlocks.test(MBB); }
173 /// getThroughBlocks - Return the set of through blocks.
174 const BitVector &getThroughBlocks() const { return ThroughBlocks; }
176 /// getNumLiveBlocks - Return the number of blocks where CurLI is live.
177 unsigned getNumLiveBlocks() const {
178 return getUseBlocks().size() - NumGapBlocks + getNumThroughBlocks();
181 /// countLiveBlocks - Return the number of blocks where li is live. This is
182 /// guaranteed to return the same number as getNumLiveBlocks() after calling
184 unsigned countLiveBlocks(const LiveInterval *li) const;
186 typedef SmallPtrSet<const MachineBasicBlock*, 16> BlockPtrSet;
188 /// shouldSplitSingleBlock - Returns true if it would help to create a local
189 /// live range for the instructions in BI. There is normally no benefit to
190 /// creating a live range for a single instruction, but it does enable
191 /// register class inflation if the instruction has a restricted register
194 /// @param BI The block to be isolated.
195 /// @param SingleInstrs True when single instructions should be isolated.
196 bool shouldSplitSingleBlock(const BlockInfo &BI, bool SingleInstrs) const;
198 /// getMultiUseBlocks - Add basic blocks to Blocks that may benefit from
199 /// having CurLI split to a new live interval. Return true if Blocks can be
200 /// passed to SplitEditor::splitSingleBlocks.
201 bool getMultiUseBlocks(BlockPtrSet &Blocks);
205 /// SplitEditor - Edit machine code and LiveIntervals for live range
208 /// - Create a SplitEditor from a SplitAnalysis.
209 /// - Start a new live interval with openIntv.
210 /// - Mark the places where the new interval is entered using enterIntv*
211 /// - Mark the ranges where the new interval is used with useIntv*
212 /// - Mark the places where the interval is exited with exitIntv*.
213 /// - Finish the current interval with closeIntv and repeat from 2.
214 /// - Rewrite instructions with finish().
220 MachineRegisterInfo &MRI;
221 MachineDominatorTree &MDT;
222 const TargetInstrInfo &TII;
223 const TargetRegisterInfo &TRI;
225 /// Edit - The current parent register and new intervals created.
228 /// Index into Edit of the currently open interval.
229 /// The index 0 is used for the complement, so the first interval started by
230 /// openIntv will be 1.
233 typedef IntervalMap<SlotIndex, unsigned> RegAssignMap;
235 /// Allocator for the interval map. This will eventually be shared with
236 /// SlotIndexes and LiveIntervals.
237 RegAssignMap::Allocator Allocator;
239 /// RegAssign - Map of the assigned register indexes.
240 /// Edit.get(RegAssign.lookup(Idx)) is the register that should be live at
242 RegAssignMap RegAssign;
244 typedef DenseMap<std::pair<unsigned, unsigned>, VNInfo*> ValueMap;
246 /// Values - keep track of the mapping from parent values to values in the new
247 /// intervals. Given a pair (RegIdx, ParentVNI->id), Values contains:
249 /// 1. No entry - the value is not mapped to Edit.get(RegIdx).
250 /// 2. Null - the value is mapped to multiple values in Edit.get(RegIdx).
251 /// Each value is represented by a minimal live range at its def.
252 /// 3. A non-null VNInfo - the value is mapped to a single new value.
253 /// The new value has no live ranges anywhere.
256 typedef std::pair<VNInfo*, MachineDomTreeNode*> LiveOutPair;
257 typedef IndexedMap<LiveOutPair, MBB2NumberFunctor> LiveOutMap;
259 // LiveOutCache - Map each basic block where a new register is live out to the
260 // live-out value and its defining block.
261 // One of these conditions shall be true:
263 // 1. !LiveOutCache.count(MBB)
264 // 2. LiveOutCache[MBB].second.getNode() == MBB
265 // 3. forall P in preds(MBB): LiveOutCache[P] == LiveOutCache[MBB]
267 // This is only a cache, the values can be computed as:
269 // VNI = Edit.get(RegIdx)->getVNInfoAt(LIS.getMBBEndIdx(MBB))
270 // Node = mbt_[LIS.getMBBFromIndex(VNI->def)]
272 // The cache is also used as a visited set by extendRange(). It can be shared
273 // by all the new registers because at most one is live out of each block.
274 LiveOutMap LiveOutCache;
276 // LiveOutSeen - Indexed by MBB->getNumber(), a bit is set for each valid
277 // entry in LiveOutCache.
278 BitVector LiveOutSeen;
280 /// LiveInBlock - Info for updateSSA() about a block where a register is
282 /// The updateSSA caller provides DomNode and Kill inside MBB, updateSSA()
283 /// adds the computed live-in value.
285 // Dominator tree node for the block.
286 // Cleared by updateSSA when the final value has been determined.
287 MachineDomTreeNode *DomNode;
289 // Live-in value filled in by updateSSA once it is known.
292 // Position in block where the live-in range ends, or SlotIndex() if the
293 // range passes through the block.
296 LiveInBlock(MachineDomTreeNode *node) : DomNode(node), Value(0) {}
299 /// LiveInBlocks - List of live-in blocks used by findReachingDefs() and
300 /// updateSSA(). This list is usually empty, it exists here to avoid frequent
302 SmallVector<LiveInBlock, 16> LiveInBlocks;
304 /// defValue - define a value in RegIdx from ParentVNI at Idx.
305 /// Idx does not have to be ParentVNI->def, but it must be contained within
306 /// ParentVNI's live range in ParentLI. The new value is added to the value
308 /// Return the new LI value.
309 VNInfo *defValue(unsigned RegIdx, const VNInfo *ParentVNI, SlotIndex Idx);
311 /// markComplexMapped - Mark ParentVNI as complex mapped in RegIdx regardless
312 /// of the number of defs.
313 void markComplexMapped(unsigned RegIdx, const VNInfo *ParentVNI);
315 /// defFromParent - Define Reg from ParentVNI at UseIdx using either
316 /// rematerialization or a COPY from parent. Return the new value.
317 VNInfo *defFromParent(unsigned RegIdx,
320 MachineBasicBlock &MBB,
321 MachineBasicBlock::iterator I);
323 /// extendRange - Extend the live range of Edit.get(RegIdx) so it reaches Idx.
324 /// Insert PHIDefs as needed to preserve SSA form.
325 void extendRange(unsigned RegIdx, SlotIndex Idx);
327 /// findReachingDefs - Starting from MBB, add blocks to LiveInBlocks until all
328 /// reaching defs for LI are found.
329 /// @param LI Live interval whose value is needed.
330 /// @param MBB Block where LI should be live-in.
331 /// @param Kill Kill point in MBB.
332 /// @return Unique value seen, or NULL.
333 VNInfo *findReachingDefs(LiveInterval *LI, MachineBasicBlock *MBB,
336 /// updateSSA - Compute and insert PHIDefs such that all blocks in
337 // LiveInBlocks get a known live-in value. Add live ranges to the blocks.
340 /// transferValues - Transfer values to the new ranges.
341 /// Return true if any ranges were skipped.
342 bool transferValues();
344 /// extendPHIKillRanges - Extend the ranges of all values killed by original
346 void extendPHIKillRanges();
348 /// rewriteAssigned - Rewrite all uses of Edit.getReg() to assigned registers.
349 void rewriteAssigned(bool ExtendRanges);
351 /// deleteRematVictims - Delete defs that are dead after rematerializing.
352 void deleteRematVictims();
355 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
356 /// Newly created intervals will be appended to newIntervals.
357 SplitEditor(SplitAnalysis &SA, LiveIntervals&, VirtRegMap&,
358 MachineDominatorTree&);
360 /// reset - Prepare for a new split.
361 void reset(LiveRangeEdit&);
363 /// Create a new virtual register and live interval.
364 /// Return the interval index, starting from 1. Interval index 0 is the
365 /// implicit complement interval.
368 /// currentIntv - Return the current interval index.
369 unsigned currentIntv() const { return OpenIdx; }
371 /// selectIntv - Select a previously opened interval index.
372 void selectIntv(unsigned Idx);
374 /// enterIntvBefore - Enter the open interval before the instruction at Idx.
375 /// If the parent interval is not live before Idx, a COPY is not inserted.
376 /// Return the beginning of the new live range.
377 SlotIndex enterIntvBefore(SlotIndex Idx);
379 /// enterIntvAfter - Enter the open interval after the instruction at Idx.
380 /// Return the beginning of the new live range.
381 SlotIndex enterIntvAfter(SlotIndex Idx);
383 /// enterIntvAtEnd - Enter the open interval at the end of MBB.
384 /// Use the open interval from he inserted copy to the MBB end.
385 /// Return the beginning of the new live range.
386 SlotIndex enterIntvAtEnd(MachineBasicBlock &MBB);
388 /// useIntv - indicate that all instructions in MBB should use OpenLI.
389 void useIntv(const MachineBasicBlock &MBB);
391 /// useIntv - indicate that all instructions in range should use OpenLI.
392 void useIntv(SlotIndex Start, SlotIndex End);
394 /// leaveIntvAfter - Leave the open interval after the instruction at Idx.
395 /// Return the end of the live range.
396 SlotIndex leaveIntvAfter(SlotIndex Idx);
398 /// leaveIntvBefore - Leave the open interval before the instruction at Idx.
399 /// Return the end of the live range.
400 SlotIndex leaveIntvBefore(SlotIndex Idx);
402 /// leaveIntvAtTop - Leave the interval at the top of MBB.
403 /// Add liveness from the MBB top to the copy.
404 /// Return the end of the live range.
405 SlotIndex leaveIntvAtTop(MachineBasicBlock &MBB);
407 /// overlapIntv - Indicate that all instructions in range should use the open
408 /// interval, but also let the complement interval be live.
410 /// This doubles the register pressure, but is sometimes required to deal with
411 /// register uses after the last valid split point.
413 /// The Start index should be a return value from a leaveIntv* call, and End
414 /// should be in the same basic block. The parent interval must have the same
415 /// value across the range.
417 void overlapIntv(SlotIndex Start, SlotIndex End);
419 /// finish - after all the new live ranges have been created, compute the
420 /// remaining live range, and rewrite instructions to use the new registers.
421 /// @param LRMap When not null, this vector will map each live range in Edit
422 /// back to the indices returned by openIntv.
423 /// There may be extra indices created by dead code elimination.
424 void finish(SmallVectorImpl<unsigned> *LRMap = 0);
426 /// dump - print the current interval maping to dbgs().
429 // ===--- High level methods ---===
431 /// splitSingleBlock - Split CurLI into a separate live interval around the
432 /// uses in a single block. This is intended to be used as part of a larger
433 /// split, and doesn't call finish().
434 void splitSingleBlock(const SplitAnalysis::BlockInfo &BI);
436 /// splitSingleBlocks - Split CurLI into a separate live interval inside each
437 /// basic block in Blocks.
438 void splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks);
440 /// splitLiveThroughBlock - Split CurLI in the given block such that it
441 /// enters the block in IntvIn and leaves it in IntvOut. There may be uses in
442 /// the block, but they will be ignored when placing split points.
444 /// @param MBBNum Block number.
445 /// @param IntvIn Interval index entering the block.
446 /// @param LeaveBefore When set, leave IntvIn before this point.
447 /// @param IntvOut Interval index leaving the block.
448 /// @param EnterAfter When set, enter IntvOut after this point.
449 void splitLiveThroughBlock(unsigned MBBNum,
450 unsigned IntvIn, SlotIndex LeaveBefore,
451 unsigned IntvOut, SlotIndex EnterAfter);
453 /// splitRegInBlock - Split CurLI in the given block such that it enters the
454 /// block in IntvIn and leaves it on the stack (or not at all). Split points
455 /// are placed in a way that avoids putting uses in the stack interval. This
456 /// may require creating a local interval when there is interference.
458 /// @param BI Block descriptor.
459 /// @param IntvIn Interval index entering the block. Not 0.
460 /// @param LeaveBefore When set, leave IntvIn before this point.
461 void splitRegInBlock(const SplitAnalysis::BlockInfo &BI,
462 unsigned IntvIn, SlotIndex LeaveBefore);
464 /// splitRegOutBlock - Split CurLI in the given block such that it enters the
465 /// block on the stack (or isn't live-in at all) and leaves it in IntvOut.
466 /// Split points are placed to avoid interference and such that the uses are
467 /// not in the stack interval. This may require creating a local interval
468 /// when there is interference.
470 /// @param BI Block descriptor.
471 /// @param IntvOut Interval index leaving the block.
472 /// @param EnterAfter When set, enter IntvOut after this point.
473 void splitRegOutBlock(const SplitAnalysis::BlockInfo &BI,
474 unsigned IntvOut, SlotIndex EnterAfter);