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