LiveRangeCalc.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. //===- LiveRangeCalc.cpp - Calculate live ranges -------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Implementation of the LiveRangeCalc class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/CodeGen/LiveRangeCalc.h"
  13. #include "llvm/ADT/BitVector.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SetVector.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/CodeGen/LiveInterval.h"
  18. #include "llvm/CodeGen/MachineBasicBlock.h"
  19. #include "llvm/CodeGen/MachineDominators.h"
  20. #include "llvm/CodeGen/MachineFunction.h"
  21. #include "llvm/CodeGen/MachineInstr.h"
  22. #include "llvm/CodeGen/MachineRegisterInfo.h"
  23. #include "llvm/CodeGen/SlotIndexes.h"
  24. #include "llvm/CodeGen/TargetRegisterInfo.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <algorithm>
  28. #include <cassert>
  29. #include <iterator>
  30. #include <tuple>
  31. #include <utility>
  32. using namespace llvm;
  33. #define DEBUG_TYPE "regalloc"
  34. // Reserve an address that indicates a value that is known to be "undef".
  35. static VNInfo UndefVNI(0xbad, SlotIndex());
  36. void LiveRangeCalc::resetLiveOutMap() {
  37. unsigned NumBlocks = MF->getNumBlockIDs();
  38. Seen.clear();
  39. Seen.resize(NumBlocks);
  40. EntryInfos.clear();
  41. Map.resize(NumBlocks);
  42. }
  43. void LiveRangeCalc::reset(const MachineFunction *mf,
  44. SlotIndexes *SI,
  45. MachineDominatorTree *MDT,
  46. VNInfo::Allocator *VNIA) {
  47. MF = mf;
  48. MRI = &MF->getRegInfo();
  49. Indexes = SI;
  50. DomTree = MDT;
  51. Alloc = VNIA;
  52. resetLiveOutMap();
  53. LiveIn.clear();
  54. }
  55. void LiveRangeCalc::updateFromLiveIns() {
  56. LiveRangeUpdater Updater;
  57. for (const LiveInBlock &I : LiveIn) {
  58. if (!I.DomNode)
  59. continue;
  60. MachineBasicBlock *MBB = I.DomNode->getBlock();
  61. assert(I.Value && "No live-in value found");
  62. SlotIndex Start, End;
  63. std::tie(Start, End) = Indexes->getMBBRange(MBB);
  64. if (I.Kill.isValid())
  65. // Value is killed inside this block.
  66. End = I.Kill;
  67. else {
  68. // The value is live-through, update LiveOut as well.
  69. // Defer the Domtree lookup until it is needed.
  70. assert(Seen.test(MBB->getNumber()));
  71. Map[MBB] = LiveOutPair(I.Value, nullptr);
  72. }
  73. Updater.setDest(&I.LR);
  74. Updater.add(Start, End, I.Value);
  75. }
  76. LiveIn.clear();
  77. }
  78. void LiveRangeCalc::extend(LiveRange &LR, SlotIndex Use, unsigned PhysReg,
  79. ArrayRef<SlotIndex> Undefs) {
  80. assert(Use.isValid() && "Invalid SlotIndex");
  81. assert(Indexes && "Missing SlotIndexes");
  82. assert(DomTree && "Missing dominator tree");
  83. MachineBasicBlock *UseMBB = Indexes->getMBBFromIndex(Use.getPrevSlot());
  84. assert(UseMBB && "No MBB at Use");
  85. // Is there a def in the same MBB we can extend?
  86. auto EP = LR.extendInBlock(Undefs, Indexes->getMBBStartIdx(UseMBB), Use);
  87. if (EP.first != nullptr || EP.second)
  88. return;
  89. // Find the single reaching def, or determine if Use is jointly dominated by
  90. // multiple values, and we may need to create even more phi-defs to preserve
  91. // VNInfo SSA form. Perform a search for all predecessor blocks where we
  92. // know the dominating VNInfo.
  93. if (findReachingDefs(LR, *UseMBB, Use, PhysReg, Undefs))
  94. return;
  95. // When there were multiple different values, we may need new PHIs.
  96. calculateValues();
  97. }
  98. // This function is called by a client after using the low-level API to add
  99. // live-out and live-in blocks. The unique value optimization is not
  100. // available, SplitEditor::transferValues handles that case directly anyway.
  101. void LiveRangeCalc::calculateValues() {
  102. assert(Indexes && "Missing SlotIndexes");
  103. assert(DomTree && "Missing dominator tree");
  104. updateSSA();
  105. updateFromLiveIns();
  106. }
  107. bool LiveRangeCalc::isDefOnEntry(LiveRange &LR, ArrayRef<SlotIndex> Undefs,
  108. MachineBasicBlock &MBB, BitVector &DefOnEntry,
  109. BitVector &UndefOnEntry) {
  110. unsigned BN = MBB.getNumber();
  111. if (DefOnEntry[BN])
  112. return true;
  113. if (UndefOnEntry[BN])
  114. return false;
  115. auto MarkDefined = [BN, &DefOnEntry](MachineBasicBlock &B) -> bool {
  116. for (MachineBasicBlock *S : B.successors())
  117. DefOnEntry[S->getNumber()] = true;
  118. DefOnEntry[BN] = true;
  119. return true;
  120. };
  121. SetVector<unsigned> WorkList;
  122. // Checking if the entry of MBB is reached by some def: add all predecessors
  123. // that are potentially defined-on-exit to the work list.
  124. for (MachineBasicBlock *P : MBB.predecessors())
  125. WorkList.insert(P->getNumber());
  126. for (unsigned i = 0; i != WorkList.size(); ++i) {
  127. // Determine if the exit from the block is reached by some def.
  128. unsigned N = WorkList[i];
  129. MachineBasicBlock &B = *MF->getBlockNumbered(N);
  130. if (Seen[N]) {
  131. const LiveOutPair &LOB = Map[&B];
  132. if (LOB.first != nullptr && LOB.first != &UndefVNI)
  133. return MarkDefined(B);
  134. }
  135. SlotIndex Begin, End;
  136. std::tie(Begin, End) = Indexes->getMBBRange(&B);
  137. // Treat End as not belonging to B.
  138. // If LR has a segment S that starts at the next block, i.e. [End, ...),
  139. // std::upper_bound will return the segment following S. Instead,
  140. // S should be treated as the first segment that does not overlap B.
  141. LiveRange::iterator UB = upper_bound(LR, End.getPrevSlot());
  142. if (UB != LR.begin()) {
  143. LiveRange::Segment &Seg = *std::prev(UB);
  144. if (Seg.end > Begin) {
  145. // There is a segment that overlaps B. If the range is not explicitly
  146. // undefined between the end of the segment and the end of the block,
  147. // treat the block as defined on exit. If it is, go to the next block
  148. // on the work list.
  149. if (LR.isUndefIn(Undefs, Seg.end, End))
  150. continue;
  151. return MarkDefined(B);
  152. }
  153. }
  154. // No segment overlaps with this block. If this block is not defined on
  155. // entry, or it undefines the range, do not process its predecessors.
  156. if (UndefOnEntry[N] || LR.isUndefIn(Undefs, Begin, End)) {
  157. UndefOnEntry[N] = true;
  158. continue;
  159. }
  160. if (DefOnEntry[N])
  161. return MarkDefined(B);
  162. // Still don't know: add all predecessors to the work list.
  163. for (MachineBasicBlock *P : B.predecessors())
  164. WorkList.insert(P->getNumber());
  165. }
  166. UndefOnEntry[BN] = true;
  167. return false;
  168. }
  169. bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &UseMBB,
  170. SlotIndex Use, unsigned PhysReg,
  171. ArrayRef<SlotIndex> Undefs) {
  172. unsigned UseMBBNum = UseMBB.getNumber();
  173. // Block numbers where LR should be live-in.
  174. SmallVector<unsigned, 16> WorkList(1, UseMBBNum);
  175. // Remember if we have seen more than one value.
  176. bool UniqueVNI = true;
  177. VNInfo *TheVNI = nullptr;
  178. bool FoundUndef = false;
  179. // Using Seen as a visited set, perform a BFS for all reaching defs.
  180. for (unsigned i = 0; i != WorkList.size(); ++i) {
  181. MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]);
  182. #ifndef NDEBUG
  183. if (MBB->pred_empty()) {
  184. MBB->getParent()->verify();
  185. errs() << "Use of " << printReg(PhysReg, MRI->getTargetRegisterInfo())
  186. << " does not have a corresponding definition on every path:\n";
  187. const MachineInstr *MI = Indexes->getInstructionFromIndex(Use);
  188. if (MI != nullptr)
  189. errs() << Use << " " << *MI;
  190. report_fatal_error("Use not jointly dominated by defs.");
  191. }
  192. if (Register::isPhysicalRegister(PhysReg) && !MBB->isLiveIn(PhysReg)) {
  193. MBB->getParent()->verify();
  194. const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo();
  195. errs() << "The register " << printReg(PhysReg, TRI)
  196. << " needs to be live in to " << printMBBReference(*MBB)
  197. << ", but is missing from the live-in list.\n";
  198. report_fatal_error("Invalid global physical register");
  199. }
  200. #endif
  201. FoundUndef |= MBB->pred_empty();
  202. for (MachineBasicBlock *Pred : MBB->predecessors()) {
  203. // Is this a known live-out block?
  204. if (Seen.test(Pred->getNumber())) {
  205. if (VNInfo *VNI = Map[Pred].first) {
  206. if (TheVNI && TheVNI != VNI)
  207. UniqueVNI = false;
  208. TheVNI = VNI;
  209. }
  210. continue;
  211. }
  212. SlotIndex Start, End;
  213. std::tie(Start, End) = Indexes->getMBBRange(Pred);
  214. // First time we see Pred. Try to determine the live-out value, but set
  215. // it as null if Pred is live-through with an unknown value.
  216. auto EP = LR.extendInBlock(Undefs, Start, End);
  217. VNInfo *VNI = EP.first;
  218. FoundUndef |= EP.second;
  219. setLiveOutValue(Pred, EP.second ? &UndefVNI : VNI);
  220. if (VNI) {
  221. if (TheVNI && TheVNI != VNI)
  222. UniqueVNI = false;
  223. TheVNI = VNI;
  224. }
  225. if (VNI || EP.second)
  226. continue;
  227. // No, we need a live-in value for Pred as well
  228. if (Pred != &UseMBB)
  229. WorkList.push_back(Pred->getNumber());
  230. else
  231. // Loopback to UseMBB, so value is really live through.
  232. Use = SlotIndex();
  233. }
  234. }
  235. LiveIn.clear();
  236. FoundUndef |= (TheVNI == nullptr || TheVNI == &UndefVNI);
  237. if (!Undefs.empty() && FoundUndef)
  238. UniqueVNI = false;
  239. // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
  240. // neither require it. Skip the sorting overhead for small updates.
  241. if (WorkList.size() > 4)
  242. array_pod_sort(WorkList.begin(), WorkList.end());
  243. // If a unique reaching def was found, blit in the live ranges immediately.
  244. if (UniqueVNI) {
  245. assert(TheVNI != nullptr && TheVNI != &UndefVNI);
  246. LiveRangeUpdater Updater(&LR);
  247. for (unsigned BN : WorkList) {
  248. SlotIndex Start, End;
  249. std::tie(Start, End) = Indexes->getMBBRange(BN);
  250. // Trim the live range in UseMBB.
  251. if (BN == UseMBBNum && Use.isValid())
  252. End = Use;
  253. else
  254. Map[MF->getBlockNumbered(BN)] = LiveOutPair(TheVNI, nullptr);
  255. Updater.add(Start, End, TheVNI);
  256. }
  257. return true;
  258. }
  259. // Prepare the defined/undefined bit vectors.
  260. EntryInfoMap::iterator Entry;
  261. bool DidInsert;
  262. std::tie(Entry, DidInsert) = EntryInfos.insert(
  263. std::make_pair(&LR, std::make_pair(BitVector(), BitVector())));
  264. if (DidInsert) {
  265. // Initialize newly inserted entries.
  266. unsigned N = MF->getNumBlockIDs();
  267. Entry->second.first.resize(N);
  268. Entry->second.second.resize(N);
  269. }
  270. BitVector &DefOnEntry = Entry->second.first;
  271. BitVector &UndefOnEntry = Entry->second.second;
  272. // Multiple values were found, so transfer the work list to the LiveIn array
  273. // where UpdateSSA will use it as a work list.
  274. LiveIn.reserve(WorkList.size());
  275. for (unsigned BN : WorkList) {
  276. MachineBasicBlock *MBB = MF->getBlockNumbered(BN);
  277. if (!Undefs.empty() &&
  278. !isDefOnEntry(LR, Undefs, *MBB, DefOnEntry, UndefOnEntry))
  279. continue;
  280. addLiveInBlock(LR, DomTree->getNode(MBB));
  281. if (MBB == &UseMBB)
  282. LiveIn.back().Kill = Use;
  283. }
  284. return false;
  285. }
  286. // This is essentially the same iterative algorithm that SSAUpdater uses,
  287. // except we already have a dominator tree, so we don't have to recompute it.
  288. void LiveRangeCalc::updateSSA() {
  289. assert(Indexes && "Missing SlotIndexes");
  290. assert(DomTree && "Missing dominator tree");
  291. // Interate until convergence.
  292. bool Changed;
  293. do {
  294. Changed = false;
  295. // Propagate live-out values down the dominator tree, inserting phi-defs
  296. // when necessary.
  297. for (LiveInBlock &I : LiveIn) {
  298. MachineDomTreeNode *Node = I.DomNode;
  299. // Skip block if the live-in value has already been determined.
  300. if (!Node)
  301. continue;
  302. MachineBasicBlock *MBB = Node->getBlock();
  303. MachineDomTreeNode *IDom = Node->getIDom();
  304. LiveOutPair IDomValue;
  305. // We need a live-in value to a block with no immediate dominator?
  306. // This is probably an unreachable block that has survived somehow.
  307. bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
  308. // IDom dominates all of our predecessors, but it may not be their
  309. // immediate dominator. Check if any of them have live-out values that are
  310. // properly dominated by IDom. If so, we need a phi-def here.
  311. if (!needPHI) {
  312. IDomValue = Map[IDom->getBlock()];
  313. // Cache the DomTree node that defined the value.
  314. if (IDomValue.first && IDomValue.first != &UndefVNI &&
  315. !IDomValue.second) {
  316. Map[IDom->getBlock()].second = IDomValue.second =
  317. DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
  318. }
  319. for (MachineBasicBlock *Pred : MBB->predecessors()) {
  320. LiveOutPair &Value = Map[Pred];
  321. if (!Value.first || Value.first == IDomValue.first)
  322. continue;
  323. if (Value.first == &UndefVNI) {
  324. needPHI = true;
  325. break;
  326. }
  327. // Cache the DomTree node that defined the value.
  328. if (!Value.second)
  329. Value.second =
  330. DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
  331. // This predecessor is carrying something other than IDomValue.
  332. // It could be because IDomValue hasn't propagated yet, or it could be
  333. // because MBB is in the dominance frontier of that value.
  334. if (DomTree->dominates(IDom, Value.second)) {
  335. needPHI = true;
  336. break;
  337. }
  338. }
  339. }
  340. // The value may be live-through even if Kill is set, as can happen when
  341. // we are called from extendRange. In that case LiveOutSeen is true, and
  342. // LiveOut indicates a foreign or missing value.
  343. LiveOutPair &LOP = Map[MBB];
  344. // Create a phi-def if required.
  345. if (needPHI) {
  346. Changed = true;
  347. assert(Alloc && "Need VNInfo allocator to create PHI-defs");
  348. SlotIndex Start, End;
  349. std::tie(Start, End) = Indexes->getMBBRange(MBB);
  350. LiveRange &LR = I.LR;
  351. VNInfo *VNI = LR.getNextValue(Start, *Alloc);
  352. I.Value = VNI;
  353. // This block is done, we know the final value.
  354. I.DomNode = nullptr;
  355. // Add liveness since updateFromLiveIns now skips this node.
  356. if (I.Kill.isValid()) {
  357. if (VNI)
  358. LR.addSegment(LiveInterval::Segment(Start, I.Kill, VNI));
  359. } else {
  360. if (VNI)
  361. LR.addSegment(LiveInterval::Segment(Start, End, VNI));
  362. LOP = LiveOutPair(VNI, Node);
  363. }
  364. } else if (IDomValue.first && IDomValue.first != &UndefVNI) {
  365. // No phi-def here. Remember incoming value.
  366. I.Value = IDomValue.first;
  367. // If the IDomValue is killed in the block, don't propagate through.
  368. if (I.Kill.isValid())
  369. continue;
  370. // Propagate IDomValue if it isn't killed:
  371. // MBB is live-out and doesn't define its own value.
  372. if (LOP.first == IDomValue.first)
  373. continue;
  374. Changed = true;
  375. LOP = IDomValue;
  376. }
  377. }
  378. } while (Changed);
  379. }
  380. bool LiveRangeCalc::isJointlyDominated(const MachineBasicBlock *MBB,
  381. ArrayRef<SlotIndex> Defs,
  382. const SlotIndexes &Indexes) {
  383. const MachineFunction &MF = *MBB->getParent();
  384. BitVector DefBlocks(MF.getNumBlockIDs());
  385. for (SlotIndex I : Defs)
  386. DefBlocks.set(Indexes.getMBBFromIndex(I)->getNumber());
  387. SetVector<unsigned> PredQueue;
  388. PredQueue.insert(MBB->getNumber());
  389. for (unsigned i = 0; i != PredQueue.size(); ++i) {
  390. unsigned BN = PredQueue[i];
  391. if (DefBlocks[BN])
  392. return true;
  393. const MachineBasicBlock *B = MF.getBlockNumbered(BN);
  394. for (const MachineBasicBlock *P : B->predecessors())
  395. PredQueue.insert(P->getNumber());
  396. }
  397. return false;
  398. }