LiveIntervalAnalysis.h 17 KB

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