• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- LiveIntervalAnalysis.h - Live Interval Analysis ---------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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).
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #ifndef LLVM_CODEGEN_LIVEINTERVALANALYSIS_H
21 #define LLVM_CODEGEN_LIVEINTERVALANALYSIS_H
22 
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"
33 #include <cmath>
34 
35 namespace llvm {
36 
37 extern cl::opt<bool> UseSegmentSetForPhysRegs;
38 
39   class BitVector;
40   class BlockFrequency;
41   class LiveRangeCalc;
42   class LiveVariables;
43   class MachineDominatorTree;
44   class MachineLoopInfo;
45   class TargetRegisterInfo;
46   class MachineRegisterInfo;
47   class TargetInstrInfo;
48   class TargetRegisterClass;
49   class VirtRegMap;
50   class MachineBlockFrequencyInfo;
51 
52   class LiveIntervals : public MachineFunctionPass {
53     MachineFunction* MF;
54     MachineRegisterInfo* MRI;
55     const TargetRegisterInfo* TRI;
56     const TargetInstrInfo* TII;
57     AliasAnalysis *AA;
58     SlotIndexes* Indexes;
59     MachineDominatorTree *DomTree;
60     LiveRangeCalc *LRCalc;
61 
62     /// Special pool allocator for VNInfo's (LiveInterval val#).
63     ///
64     VNInfo::Allocator VNInfoAllocator;
65 
66     /// Live interval pointers for all the virtual registers.
67     IndexedMap<LiveInterval*, VirtReg2IndexFunctor> VirtRegIntervals;
68 
69     /// RegMaskSlots - Sorted list of instructions with register mask operands.
70     /// Always use the 'r' slot, RegMasks are normal clobbers, not early
71     /// clobbers.
72     SmallVector<SlotIndex, 8> RegMaskSlots;
73 
74     /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
75     /// pointer to the corresponding register mask.  This pointer can be
76     /// recomputed as:
77     ///
78     ///   MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
79     ///   unsigned OpNum = findRegMaskOperand(MI);
80     ///   RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
81     ///
82     /// This is kept in a separate vector partly because some standard
83     /// libraries don't support lower_bound() with mixed objects, partly to
84     /// improve locality when searching in RegMaskSlots.
85     /// Also see the comment in LiveInterval::find().
86     SmallVector<const uint32_t*, 8> RegMaskBits;
87 
88     /// For each basic block number, keep (begin, size) pairs indexing into the
89     /// RegMaskSlots and RegMaskBits arrays.
90     /// Note that basic block numbers may not be layout contiguous, that's why
91     /// we can't just keep track of the first register mask in each basic
92     /// block.
93     SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
94 
95     /// Keeps a live range set for each register unit to track fixed physreg
96     /// interference.
97     SmallVector<LiveRange*, 0> RegUnitRanges;
98 
99   public:
100     static char ID; // Pass identification, replacement for typeid
101     LiveIntervals();
102     ~LiveIntervals() override;
103 
104     // Calculate the spill weight to assign to a single instruction.
105     static float getSpillWeight(bool isDef, bool isUse,
106                                 const MachineBlockFrequencyInfo *MBFI,
107                                 const MachineInstr &Instr);
108 
getInterval(unsigned Reg)109     LiveInterval &getInterval(unsigned Reg) {
110       if (hasInterval(Reg))
111         return *VirtRegIntervals[Reg];
112       else
113         return createAndComputeVirtRegInterval(Reg);
114     }
115 
getInterval(unsigned Reg)116     const LiveInterval &getInterval(unsigned Reg) const {
117       return const_cast<LiveIntervals*>(this)->getInterval(Reg);
118     }
119 
hasInterval(unsigned Reg)120     bool hasInterval(unsigned Reg) const {
121       return VirtRegIntervals.inBounds(Reg) && VirtRegIntervals[Reg];
122     }
123 
124     // Interval creation.
createEmptyInterval(unsigned Reg)125     LiveInterval &createEmptyInterval(unsigned Reg) {
126       assert(!hasInterval(Reg) && "Interval already exists!");
127       VirtRegIntervals.grow(Reg);
128       VirtRegIntervals[Reg] = createInterval(Reg);
129       return *VirtRegIntervals[Reg];
130     }
131 
createAndComputeVirtRegInterval(unsigned Reg)132     LiveInterval &createAndComputeVirtRegInterval(unsigned Reg) {
133       LiveInterval &LI = createEmptyInterval(Reg);
134       computeVirtRegInterval(LI);
135       return LI;
136     }
137 
138     // Interval removal.
removeInterval(unsigned Reg)139     void removeInterval(unsigned Reg) {
140       delete VirtRegIntervals[Reg];
141       VirtRegIntervals[Reg] = nullptr;
142     }
143 
144     /// Given a register and an instruction, adds a live segment from that
145     /// instruction to the end of its MBB.
146     LiveInterval::Segment addSegmentToEndOfBlock(unsigned reg,
147                                                  MachineInstr &startInst);
148 
149     /// After removing some uses of a register, shrink its live range to just
150     /// the remaining uses. This method does not compute reaching defs for new
151     /// uses, and it doesn't remove dead defs.
152     /// Dead PHIDef values are marked as unused. New dead machine instructions
153     /// are added to the dead vector. Returns true if the interval may have been
154     /// separated into multiple connected components.
155     bool shrinkToUses(LiveInterval *li,
156                       SmallVectorImpl<MachineInstr*> *dead = nullptr);
157 
158     /// Specialized version of
159     /// shrinkToUses(LiveInterval *li, SmallVectorImpl<MachineInstr*> *dead)
160     /// that works on a subregister live range and only looks at uses matching
161     /// the lane mask of the subregister range.
162     /// This may leave the subrange empty which needs to be cleaned up with
163     /// LiveInterval::removeEmptySubranges() afterwards.
164     void shrinkToUses(LiveInterval::SubRange &SR, unsigned Reg);
165 
166     /// extendToIndices - Extend the live range of LI to reach all points in
167     /// Indices. The points in the Indices array must be jointly dominated by
168     /// existing defs in LI. PHI-defs are added as needed to maintain SSA form.
169     ///
170     /// If a SlotIndex in Indices is the end index of a basic block, LI will be
171     /// extended to be live out of the basic block.
172     ///
173     /// See also LiveRangeCalc::extend().
174     void extendToIndices(LiveRange &LR, ArrayRef<SlotIndex> Indices);
175 
176 
177     /// If @p LR has a live value at @p Kill, prune its live range by removing
178     /// any liveness reachable from Kill. Add live range end points to
179     /// EndPoints such that extendToIndices(LI, EndPoints) will reconstruct the
180     /// value's live range.
181     ///
182     /// Calling pruneValue() and extendToIndices() can be used to reconstruct
183     /// SSA form after adding defs to a virtual register.
184     void pruneValue(LiveRange &LR, SlotIndex Kill,
185                     SmallVectorImpl<SlotIndex> *EndPoints);
186 
getSlotIndexes()187     SlotIndexes *getSlotIndexes() const {
188       return Indexes;
189     }
190 
getAliasAnalysis()191     AliasAnalysis *getAliasAnalysis() const {
192       return AA;
193     }
194 
195     /// isNotInMIMap - returns true if the specified machine instr has been
196     /// removed or was never entered in the map.
isNotInMIMap(const MachineInstr & Instr)197     bool isNotInMIMap(const MachineInstr &Instr) const {
198       return !Indexes->hasIndex(Instr);
199     }
200 
201     /// Returns the base index of the given instruction.
getInstructionIndex(const MachineInstr & Instr)202     SlotIndex getInstructionIndex(const MachineInstr &Instr) const {
203       return Indexes->getInstructionIndex(Instr);
204     }
205 
206     /// Returns the instruction associated with the given index.
getInstructionFromIndex(SlotIndex index)207     MachineInstr* getInstructionFromIndex(SlotIndex index) const {
208       return Indexes->getInstructionFromIndex(index);
209     }
210 
211     /// Return the first index in the given basic block.
getMBBStartIdx(const MachineBasicBlock * mbb)212     SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
213       return Indexes->getMBBStartIdx(mbb);
214     }
215 
216     /// Return the last index in the given basic block.
getMBBEndIdx(const MachineBasicBlock * mbb)217     SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
218       return Indexes->getMBBEndIdx(mbb);
219     }
220 
isLiveInToMBB(const LiveRange & LR,const MachineBasicBlock * mbb)221     bool isLiveInToMBB(const LiveRange &LR,
222                        const MachineBasicBlock *mbb) const {
223       return LR.liveAt(getMBBStartIdx(mbb));
224     }
225 
isLiveOutOfMBB(const LiveRange & LR,const MachineBasicBlock * mbb)226     bool isLiveOutOfMBB(const LiveRange &LR,
227                         const MachineBasicBlock *mbb) const {
228       return LR.liveAt(getMBBEndIdx(mbb).getPrevSlot());
229     }
230 
getMBBFromIndex(SlotIndex index)231     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
232       return Indexes->getMBBFromIndex(index);
233     }
234 
insertMBBInMaps(MachineBasicBlock * MBB)235     void insertMBBInMaps(MachineBasicBlock *MBB) {
236       Indexes->insertMBBInMaps(MBB);
237       assert(unsigned(MBB->getNumber()) == RegMaskBlocks.size() &&
238              "Blocks must be added in order.");
239       RegMaskBlocks.push_back(std::make_pair(RegMaskSlots.size(), 0));
240     }
241 
InsertMachineInstrInMaps(MachineInstr & MI)242     SlotIndex InsertMachineInstrInMaps(MachineInstr &MI) {
243       return Indexes->insertMachineInstrInMaps(MI);
244     }
245 
InsertMachineInstrRangeInMaps(MachineBasicBlock::iterator B,MachineBasicBlock::iterator E)246     void InsertMachineInstrRangeInMaps(MachineBasicBlock::iterator B,
247                                        MachineBasicBlock::iterator E) {
248       for (MachineBasicBlock::iterator I = B; I != E; ++I)
249         Indexes->insertMachineInstrInMaps(*I);
250     }
251 
RemoveMachineInstrFromMaps(MachineInstr & MI)252     void RemoveMachineInstrFromMaps(MachineInstr &MI) {
253       Indexes->removeMachineInstrFromMaps(MI);
254     }
255 
ReplaceMachineInstrInMaps(MachineInstr & MI,MachineInstr & NewMI)256     void ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI) {
257       Indexes->replaceMachineInstrInMaps(MI, NewMI);
258     }
259 
getVNInfoAllocator()260     VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
261 
262     void getAnalysisUsage(AnalysisUsage &AU) const override;
263     void releaseMemory() override;
264 
265     /// runOnMachineFunction - pass entry point
266     bool runOnMachineFunction(MachineFunction&) override;
267 
268     /// print - Implement the dump method.
269     void print(raw_ostream &O, const Module* = nullptr) const override;
270 
271     /// intervalIsInOneMBB - If LI is confined to a single basic block, return
272     /// a pointer to that block.  If LI is live in to or out of any block,
273     /// return NULL.
274     MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
275 
276     /// Returns true if VNI is killed by any PHI-def values in LI.
277     /// This may conservatively return true to avoid expensive computations.
278     bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const;
279 
280     /// addKillFlags - Add kill flags to any instruction that kills a virtual
281     /// register.
282     void addKillFlags(const VirtRegMap*);
283 
284     /// handleMove - call this method to notify LiveIntervals that
285     /// instruction 'mi' has been moved within a basic block. This will update
286     /// the live intervals for all operands of mi. Moves between basic blocks
287     /// are not supported.
288     ///
289     /// \param UpdateFlags Update live intervals for nonallocatable physregs.
290     void handleMove(MachineInstr &MI, bool UpdateFlags = false);
291 
292     /// moveIntoBundle - Update intervals for operands of MI so that they
293     /// begin/end on the SlotIndex for BundleStart.
294     ///
295     /// \param UpdateFlags Update live intervals for nonallocatable physregs.
296     ///
297     /// Requires MI and BundleStart to have SlotIndexes, and assumes
298     /// existing liveness is accurate. BundleStart should be the first
299     /// instruction in the Bundle.
300     void handleMoveIntoBundle(MachineInstr &MI, MachineInstr &BundleStart,
301                               bool UpdateFlags = false);
302 
303     /// repairIntervalsInRange - Update live intervals for instructions in a
304     /// range of iterators. It is intended for use after target hooks that may
305     /// insert or remove instructions, and is only efficient for a small number
306     /// of instructions.
307     ///
308     /// OrigRegs is a vector of registers that were originally used by the
309     /// instructions in the range between the two iterators.
310     ///
311     /// Currently, the only only changes that are supported are simple removal
312     /// and addition of uses.
313     void repairIntervalsInRange(MachineBasicBlock *MBB,
314                                 MachineBasicBlock::iterator Begin,
315                                 MachineBasicBlock::iterator End,
316                                 ArrayRef<unsigned> OrigRegs);
317 
318     // Register mask functions.
319     //
320     // Machine instructions may use a register mask operand to indicate that a
321     // large number of registers are clobbered by the instruction.  This is
322     // typically used for calls.
323     //
324     // For compile time performance reasons, these clobbers are not recorded in
325     // the live intervals for individual physical registers.  Instead,
326     // LiveIntervalAnalysis maintains a sorted list of instructions with
327     // register mask operands.
328 
329     /// getRegMaskSlots - Returns a sorted array of slot indices of all
330     /// instructions with register mask operands.
getRegMaskSlots()331     ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
332 
333     /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
334     /// instructions with register mask operands in the basic block numbered
335     /// MBBNum.
getRegMaskSlotsInBlock(unsigned MBBNum)336     ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
337       std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
338       return getRegMaskSlots().slice(P.first, P.second);
339     }
340 
341     /// getRegMaskBits() - Returns an array of register mask pointers
342     /// corresponding to getRegMaskSlots().
getRegMaskBits()343     ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
344 
345     /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
346     /// to getRegMaskSlotsInBlock(MBBNum).
getRegMaskBitsInBlock(unsigned MBBNum)347     ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
348       std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
349       return getRegMaskBits().slice(P.first, P.second);
350     }
351 
352     /// checkRegMaskInterference - Test if LI is live across any register mask
353     /// instructions, and compute a bit mask of physical registers that are not
354     /// clobbered by any of them.
355     ///
356     /// Returns false if LI doesn't cross any register mask instructions. In
357     /// that case, the bit vector is not filled in.
358     bool checkRegMaskInterference(LiveInterval &LI,
359                                   BitVector &UsableRegs);
360 
361     // Register unit functions.
362     //
363     // Fixed interference occurs when MachineInstrs use physregs directly
364     // instead of virtual registers. This typically happens when passing
365     // arguments to a function call, or when instructions require operands in
366     // fixed registers.
367     //
368     // Each physreg has one or more register units, see MCRegisterInfo. We
369     // track liveness per register unit to handle aliasing registers more
370     // efficiently.
371 
372     /// getRegUnit - Return the live range for Unit.
373     /// It will be computed if it doesn't exist.
getRegUnit(unsigned Unit)374     LiveRange &getRegUnit(unsigned Unit) {
375       LiveRange *LR = RegUnitRanges[Unit];
376       if (!LR) {
377         // Compute missing ranges on demand.
378         // Use segment set to speed-up initial computation of the live range.
379         RegUnitRanges[Unit] = LR = new LiveRange(UseSegmentSetForPhysRegs);
380         computeRegUnitRange(*LR, Unit);
381       }
382       return *LR;
383     }
384 
385     /// getCachedRegUnit - Return the live range for Unit if it has already
386     /// been computed, or NULL if it hasn't been computed yet.
getCachedRegUnit(unsigned Unit)387     LiveRange *getCachedRegUnit(unsigned Unit) {
388       return RegUnitRanges[Unit];
389     }
390 
getCachedRegUnit(unsigned Unit)391     const LiveRange *getCachedRegUnit(unsigned Unit) const {
392       return RegUnitRanges[Unit];
393     }
394 
395     /// Remove value numbers and related live segments starting at position
396     /// @p Pos that are part of any liverange of physical register @p Reg or one
397     /// of its subregisters.
398     void removePhysRegDefAt(unsigned Reg, SlotIndex Pos);
399 
400     /// Remove value number and related live segments of @p LI and its subranges
401     /// that start at position @p Pos.
402     void removeVRegDefAt(LiveInterval &LI, SlotIndex Pos);
403 
404     /// Split separate components in LiveInterval \p LI into separate intervals.
405     void splitSeparateComponents(LiveInterval &LI,
406                                  SmallVectorImpl<LiveInterval*> &SplitLIs);
407 
408     /// For live interval \p LI with correct SubRanges construct matching
409     /// information for the main live range. Expects the main live range to not
410     /// have any segments or value numbers.
411     void constructMainRangeFromSubranges(LiveInterval &LI);
412 
413   private:
414     /// Compute live intervals for all virtual registers.
415     void computeVirtRegs();
416 
417     /// Compute RegMaskSlots and RegMaskBits.
418     void computeRegMasks();
419 
420     /// Walk the values in @p LI and check for dead values:
421     /// - Dead PHIDef values are marked as unused.
422     /// - Dead operands are marked as such.
423     /// - Completely dead machine instructions are added to the @p dead vector
424     ///   if it is not nullptr.
425     /// Returns true if any PHI value numbers have been removed which may
426     /// have separated the interval into multiple connected components.
427     bool computeDeadValues(LiveInterval &LI,
428                            SmallVectorImpl<MachineInstr*> *dead);
429 
430     static LiveInterval* createInterval(unsigned Reg);
431 
432     void printInstrs(raw_ostream &O) const;
433     void dumpInstrs() const;
434 
435     void computeLiveInRegUnits();
436     void computeRegUnitRange(LiveRange&, unsigned Unit);
437     void computeVirtRegInterval(LiveInterval&);
438 
439 
440     /// Helper function for repairIntervalsInRange(), walks backwards and
441     /// creates/modifies live segments in @p LR to match the operands found.
442     /// Only full operands or operands with subregisters matching @p LaneMask
443     /// are considered.
444     void repairOldRegInRange(MachineBasicBlock::iterator Begin,
445                              MachineBasicBlock::iterator End,
446                              const SlotIndex endIdx, LiveRange &LR,
447                              unsigned Reg, LaneBitmask LaneMask = ~0u);
448 
449     class HMEditor;
450   };
451 } // End llvm namespace
452 
453 #endif
454