2
0

LiveRangeCalc.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. //===---- LiveRangeCalc.cpp - Calculate live ranges -----------------------===//
  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. // Implementation of the LiveRangeCalc class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "LiveRangeCalc.h"
  14. #include "llvm/CodeGen/MachineDominators.h"
  15. #include "llvm/CodeGen/MachineRegisterInfo.h"
  16. using namespace llvm;
  17. #define DEBUG_TYPE "regalloc"
  18. void LiveRangeCalc::resetLiveOutMap() {
  19. unsigned NumBlocks = MF->getNumBlockIDs();
  20. Seen.clear();
  21. Seen.resize(NumBlocks);
  22. Map.resize(NumBlocks);
  23. }
  24. void LiveRangeCalc::reset(const MachineFunction *mf,
  25. SlotIndexes *SI,
  26. MachineDominatorTree *MDT,
  27. VNInfo::Allocator *VNIA) {
  28. MF = mf;
  29. MRI = &MF->getRegInfo();
  30. Indexes = SI;
  31. DomTree = MDT;
  32. Alloc = VNIA;
  33. resetLiveOutMap();
  34. LiveIn.clear();
  35. }
  36. static void createDeadDef(SlotIndexes &Indexes, VNInfo::Allocator &Alloc,
  37. LiveRange &LR, const MachineOperand &MO) {
  38. const MachineInstr *MI = MO.getParent();
  39. SlotIndex DefIdx =
  40. Indexes.getInstructionIndex(MI).getRegSlot(MO.isEarlyClobber());
  41. // Create the def in LR. This may find an existing def.
  42. LR.createDeadDef(DefIdx, Alloc);
  43. }
  44. void LiveRangeCalc::calculate(LiveInterval &LI, bool TrackSubRegs) {
  45. assert(MRI && Indexes && "call reset() first");
  46. // Step 1: Create minimal live segments for every definition of Reg.
  47. // Visit all def operands. If the same instruction has multiple defs of Reg,
  48. // createDeadDef() will deduplicate.
  49. const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
  50. unsigned Reg = LI.reg;
  51. for (const MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
  52. if (!MO.isDef() && !MO.readsReg())
  53. continue;
  54. unsigned SubReg = MO.getSubReg();
  55. if (LI.hasSubRanges() || (SubReg != 0 && TrackSubRegs)) {
  56. unsigned Mask = SubReg != 0 ? TRI.getSubRegIndexLaneMask(SubReg)
  57. : MRI->getMaxLaneMaskForVReg(Reg);
  58. // If this is the first time we see a subregister def, initialize
  59. // subranges by creating a copy of the main range.
  60. if (!LI.hasSubRanges() && !LI.empty()) {
  61. unsigned ClassMask = MRI->getMaxLaneMaskForVReg(Reg);
  62. LI.createSubRangeFrom(*Alloc, ClassMask, LI);
  63. }
  64. for (LiveInterval::SubRange &S : LI.subranges()) {
  65. // A Mask for subregs common to the existing subrange and current def.
  66. unsigned Common = S.LaneMask & Mask;
  67. if (Common == 0)
  68. continue;
  69. // A Mask for subregs covered by the subrange but not the current def.
  70. unsigned LRest = S.LaneMask & ~Mask;
  71. LiveInterval::SubRange *CommonRange;
  72. if (LRest != 0) {
  73. // Split current subrange into Common and LRest ranges.
  74. S.LaneMask = LRest;
  75. CommonRange = LI.createSubRangeFrom(*Alloc, Common, S);
  76. } else {
  77. assert(Common == S.LaneMask);
  78. CommonRange = &S;
  79. }
  80. if (MO.isDef())
  81. createDeadDef(*Indexes, *Alloc, *CommonRange, MO);
  82. Mask &= ~Common;
  83. }
  84. // Create a new SubRange for subregs we did not cover yet.
  85. if (Mask != 0) {
  86. LiveInterval::SubRange *NewRange = LI.createSubRange(*Alloc, Mask);
  87. if (MO.isDef())
  88. createDeadDef(*Indexes, *Alloc, *NewRange, MO);
  89. }
  90. }
  91. // Create the def in the main liverange. We do not have to do this if
  92. // subranges are tracked as we recreate the main range later in this case.
  93. if (MO.isDef() && !LI.hasSubRanges())
  94. createDeadDef(*Indexes, *Alloc, LI, MO);
  95. }
  96. // We may have created empty live ranges for partially undefined uses, we
  97. // can't keep them because we won't find defs in them later.
  98. LI.removeEmptySubRanges();
  99. // Step 2: Extend live segments to all uses, constructing SSA form as
  100. // necessary.
  101. if (LI.hasSubRanges()) {
  102. for (LiveInterval::SubRange &S : LI.subranges()) {
  103. resetLiveOutMap();
  104. extendToUses(S, Reg, S.LaneMask);
  105. }
  106. LI.clear();
  107. LI.constructMainRangeFromSubranges(*Indexes, *Alloc);
  108. } else {
  109. resetLiveOutMap();
  110. extendToUses(LI, Reg, ~0u);
  111. }
  112. }
  113. void LiveRangeCalc::createDeadDefs(LiveRange &LR, unsigned Reg) {
  114. assert(MRI && Indexes && "call reset() first");
  115. // Visit all def operands. If the same instruction has multiple defs of Reg,
  116. // LR.createDeadDef() will deduplicate.
  117. for (MachineOperand &MO : MRI->def_operands(Reg))
  118. createDeadDef(*Indexes, *Alloc, LR, MO);
  119. }
  120. void LiveRangeCalc::extendToUses(LiveRange &LR, unsigned Reg, unsigned Mask) {
  121. // Visit all operands that read Reg. This may include partial defs.
  122. const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
  123. for (MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
  124. // Clear all kill flags. They will be reinserted after register allocation
  125. // by LiveIntervalAnalysis::addKillFlags().
  126. if (MO.isUse())
  127. MO.setIsKill(false);
  128. else {
  129. // We only care about uses, but on the main range (mask ~0u) this includes
  130. // the "virtual" reads happening for subregister defs.
  131. if (Mask != ~0u)
  132. continue;
  133. }
  134. if (!MO.readsReg())
  135. continue;
  136. unsigned SubReg = MO.getSubReg();
  137. if (SubReg != 0) {
  138. unsigned SubRegMask = TRI.getSubRegIndexLaneMask(SubReg);
  139. // Ignore uses not covering the current subrange.
  140. if ((SubRegMask & Mask) == 0)
  141. continue;
  142. }
  143. // Determine the actual place of the use.
  144. const MachineInstr *MI = MO.getParent();
  145. unsigned OpNo = (&MO - &MI->getOperand(0));
  146. SlotIndex UseIdx;
  147. if (MI->isPHI()) {
  148. assert(!MO.isDef() && "Cannot handle PHI def of partial register.");
  149. // The actual place where a phi operand is used is the end of the pred
  150. // MBB. PHI operands are paired: (Reg, PredMBB).
  151. UseIdx = Indexes->getMBBEndIdx(MI->getOperand(OpNo+1).getMBB());
  152. } else {
  153. // Check for early-clobber redefs.
  154. bool isEarlyClobber = false;
  155. unsigned DefIdx;
  156. if (MO.isDef())
  157. isEarlyClobber = MO.isEarlyClobber();
  158. else if (MI->isRegTiedToDefOperand(OpNo, &DefIdx)) {
  159. // FIXME: This would be a lot easier if tied early-clobber uses also
  160. // had an early-clobber flag.
  161. isEarlyClobber = MI->getOperand(DefIdx).isEarlyClobber();
  162. }
  163. UseIdx = Indexes->getInstructionIndex(MI).getRegSlot(isEarlyClobber);
  164. }
  165. // MI is reading Reg. We may have visited MI before if it happens to be
  166. // reading Reg multiple times. That is OK, extend() is idempotent.
  167. extend(LR, UseIdx, Reg);
  168. }
  169. }
  170. void LiveRangeCalc::updateFromLiveIns() {
  171. LiveRangeUpdater Updater;
  172. for (const LiveInBlock &I : LiveIn) {
  173. if (!I.DomNode)
  174. continue;
  175. MachineBasicBlock *MBB = I.DomNode->getBlock();
  176. assert(I.Value && "No live-in value found");
  177. SlotIndex Start, End;
  178. std::tie(Start, End) = Indexes->getMBBRange(MBB);
  179. if (I.Kill.isValid())
  180. // Value is killed inside this block.
  181. End = I.Kill;
  182. else {
  183. // The value is live-through, update LiveOut as well.
  184. // Defer the Domtree lookup until it is needed.
  185. assert(Seen.test(MBB->getNumber()));
  186. Map[MBB] = LiveOutPair(I.Value, nullptr);
  187. }
  188. Updater.setDest(&I.LR);
  189. Updater.add(Start, End, I.Value);
  190. }
  191. LiveIn.clear();
  192. }
  193. void LiveRangeCalc::extend(LiveRange &LR, SlotIndex Use, unsigned PhysReg) {
  194. assert(Use.isValid() && "Invalid SlotIndex");
  195. assert(Indexes && "Missing SlotIndexes");
  196. assert(DomTree && "Missing dominator tree");
  197. MachineBasicBlock *UseMBB = Indexes->getMBBFromIndex(Use.getPrevSlot());
  198. assert(UseMBB && "No MBB at Use");
  199. // Is there a def in the same MBB we can extend?
  200. if (LR.extendInBlock(Indexes->getMBBStartIdx(UseMBB), Use))
  201. return;
  202. // Find the single reaching def, or determine if Use is jointly dominated by
  203. // multiple values, and we may need to create even more phi-defs to preserve
  204. // VNInfo SSA form. Perform a search for all predecessor blocks where we
  205. // know the dominating VNInfo.
  206. if (findReachingDefs(LR, *UseMBB, Use, PhysReg))
  207. return;
  208. // When there were multiple different values, we may need new PHIs.
  209. calculateValues();
  210. }
  211. // This function is called by a client after using the low-level API to add
  212. // live-out and live-in blocks. The unique value optimization is not
  213. // available, SplitEditor::transferValues handles that case directly anyway.
  214. void LiveRangeCalc::calculateValues() {
  215. assert(Indexes && "Missing SlotIndexes");
  216. assert(DomTree && "Missing dominator tree");
  217. updateSSA();
  218. updateFromLiveIns();
  219. }
  220. bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &UseMBB,
  221. SlotIndex Use, unsigned PhysReg) {
  222. unsigned UseMBBNum = UseMBB.getNumber();
  223. // Block numbers where LR should be live-in.
  224. SmallVector<unsigned, 16> WorkList(1, UseMBBNum);
  225. // Remember if we have seen more than one value.
  226. bool UniqueVNI = true;
  227. VNInfo *TheVNI = nullptr;
  228. // Using Seen as a visited set, perform a BFS for all reaching defs.
  229. for (unsigned i = 0; i != WorkList.size(); ++i) {
  230. MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]);
  231. #ifndef NDEBUG
  232. if (MBB->pred_empty()) {
  233. MBB->getParent()->verify();
  234. errs() << "Use of " << PrintReg(PhysReg)
  235. << " does not have a corresponding definition on every path:\n";
  236. const MachineInstr *MI = Indexes->getInstructionFromIndex(Use);
  237. if (MI != nullptr)
  238. errs() << Use << " " << *MI;
  239. llvm_unreachable("Use not jointly dominated by defs.");
  240. }
  241. if (TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
  242. !MBB->isLiveIn(PhysReg)) {
  243. MBB->getParent()->verify();
  244. errs() << "The register " << PrintReg(PhysReg)
  245. << " needs to be live in to BB#" << MBB->getNumber()
  246. << ", but is missing from the live-in list.\n";
  247. llvm_unreachable("Invalid global physical register");
  248. }
  249. #endif
  250. for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
  251. PE = MBB->pred_end(); PI != PE; ++PI) {
  252. MachineBasicBlock *Pred = *PI;
  253. // Is this a known live-out block?
  254. if (Seen.test(Pred->getNumber())) {
  255. if (VNInfo *VNI = Map[Pred].first) {
  256. if (TheVNI && TheVNI != VNI)
  257. UniqueVNI = false;
  258. TheVNI = VNI;
  259. }
  260. continue;
  261. }
  262. SlotIndex Start, End;
  263. std::tie(Start, End) = Indexes->getMBBRange(Pred);
  264. // First time we see Pred. Try to determine the live-out value, but set
  265. // it as null if Pred is live-through with an unknown value.
  266. VNInfo *VNI = LR.extendInBlock(Start, End);
  267. setLiveOutValue(Pred, VNI);
  268. if (VNI) {
  269. if (TheVNI && TheVNI != VNI)
  270. UniqueVNI = false;
  271. TheVNI = VNI;
  272. continue;
  273. }
  274. // No, we need a live-in value for Pred as well
  275. if (Pred != &UseMBB)
  276. WorkList.push_back(Pred->getNumber());
  277. else
  278. // Loopback to UseMBB, so value is really live through.
  279. Use = SlotIndex();
  280. }
  281. }
  282. LiveIn.clear();
  283. // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
  284. // neither require it. Skip the sorting overhead for small updates.
  285. if (WorkList.size() > 4)
  286. array_pod_sort(WorkList.begin(), WorkList.end());
  287. // If a unique reaching def was found, blit in the live ranges immediately.
  288. if (UniqueVNI) {
  289. LiveRangeUpdater Updater(&LR);
  290. for (SmallVectorImpl<unsigned>::const_iterator I = WorkList.begin(),
  291. E = WorkList.end(); I != E; ++I) {
  292. SlotIndex Start, End;
  293. std::tie(Start, End) = Indexes->getMBBRange(*I);
  294. // Trim the live range in UseMBB.
  295. if (*I == UseMBBNum && Use.isValid())
  296. End = Use;
  297. else
  298. Map[MF->getBlockNumbered(*I)] = LiveOutPair(TheVNI, nullptr);
  299. Updater.add(Start, End, TheVNI);
  300. }
  301. return true;
  302. }
  303. // Multiple values were found, so transfer the work list to the LiveIn array
  304. // where UpdateSSA will use it as a work list.
  305. LiveIn.reserve(WorkList.size());
  306. for (SmallVectorImpl<unsigned>::const_iterator
  307. I = WorkList.begin(), E = WorkList.end(); I != E; ++I) {
  308. MachineBasicBlock *MBB = MF->getBlockNumbered(*I);
  309. addLiveInBlock(LR, DomTree->getNode(MBB));
  310. if (MBB == &UseMBB)
  311. LiveIn.back().Kill = Use;
  312. }
  313. return false;
  314. }
  315. // This is essentially the same iterative algorithm that SSAUpdater uses,
  316. // except we already have a dominator tree, so we don't have to recompute it.
  317. void LiveRangeCalc::updateSSA() {
  318. assert(Indexes && "Missing SlotIndexes");
  319. assert(DomTree && "Missing dominator tree");
  320. // Interate until convergence.
  321. unsigned Changes;
  322. do {
  323. Changes = 0;
  324. // Propagate live-out values down the dominator tree, inserting phi-defs
  325. // when necessary.
  326. for (LiveInBlock &I : LiveIn) {
  327. MachineDomTreeNode *Node = I.DomNode;
  328. // Skip block if the live-in value has already been determined.
  329. if (!Node)
  330. continue;
  331. MachineBasicBlock *MBB = Node->getBlock();
  332. MachineDomTreeNode *IDom = Node->getIDom();
  333. LiveOutPair IDomValue;
  334. // We need a live-in value to a block with no immediate dominator?
  335. // This is probably an unreachable block that has survived somehow.
  336. bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
  337. // IDom dominates all of our predecessors, but it may not be their
  338. // immediate dominator. Check if any of them have live-out values that are
  339. // properly dominated by IDom. If so, we need a phi-def here.
  340. if (!needPHI) {
  341. IDomValue = Map[IDom->getBlock()];
  342. // Cache the DomTree node that defined the value.
  343. if (IDomValue.first && !IDomValue.second)
  344. Map[IDom->getBlock()].second = IDomValue.second =
  345. DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
  346. for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
  347. PE = MBB->pred_end(); PI != PE; ++PI) {
  348. LiveOutPair &Value = Map[*PI];
  349. if (!Value.first || Value.first == IDomValue.first)
  350. continue;
  351. // Cache the DomTree node that defined the value.
  352. if (!Value.second)
  353. Value.second =
  354. DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
  355. // This predecessor is carrying something other than IDomValue.
  356. // It could be because IDomValue hasn't propagated yet, or it could be
  357. // because MBB is in the dominance frontier of that value.
  358. if (DomTree->dominates(IDom, Value.second)) {
  359. needPHI = true;
  360. break;
  361. }
  362. }
  363. }
  364. // The value may be live-through even if Kill is set, as can happen when
  365. // we are called from extendRange. In that case LiveOutSeen is true, and
  366. // LiveOut indicates a foreign or missing value.
  367. LiveOutPair &LOP = Map[MBB];
  368. // Create a phi-def if required.
  369. if (needPHI) {
  370. ++Changes;
  371. assert(Alloc && "Need VNInfo allocator to create PHI-defs");
  372. SlotIndex Start, End;
  373. std::tie(Start, End) = Indexes->getMBBRange(MBB);
  374. LiveRange &LR = I.LR;
  375. VNInfo *VNI = LR.getNextValue(Start, *Alloc);
  376. I.Value = VNI;
  377. // This block is done, we know the final value.
  378. I.DomNode = nullptr;
  379. // Add liveness since updateFromLiveIns now skips this node.
  380. if (I.Kill.isValid())
  381. LR.addSegment(LiveInterval::Segment(Start, I.Kill, VNI));
  382. else {
  383. LR.addSegment(LiveInterval::Segment(Start, End, VNI));
  384. LOP = LiveOutPair(VNI, Node);
  385. }
  386. } else if (IDomValue.first) {
  387. // No phi-def here. Remember incoming value.
  388. I.Value = IDomValue.first;
  389. // If the IDomValue is killed in the block, don't propagate through.
  390. if (I.Kill.isValid())
  391. continue;
  392. // Propagate IDomValue if it isn't killed:
  393. // MBB is live-out and doesn't define its own value.
  394. if (LOP.first == IDomValue.first)
  395. continue;
  396. ++Changes;
  397. LOP = IDomValue;
  398. }
  399. }
  400. } while (Changes);
  401. }