LiveIntervals.h 20 KB

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