LiveRangeEdit.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. //===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===//
  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. // The LiveRangeEdit class represents changes done to a virtual register when it
  10. // is spilled or split.
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/CodeGen/LiveRangeEdit.h"
  13. #include "llvm/ADT/Statistic.h"
  14. #include "llvm/CodeGen/CalcSpillWeights.h"
  15. #include "llvm/CodeGen/LiveIntervals.h"
  16. #include "llvm/CodeGen/MachineRegisterInfo.h"
  17. #include "llvm/CodeGen/TargetInstrInfo.h"
  18. #include "llvm/CodeGen/VirtRegMap.h"
  19. #include "llvm/Support/Debug.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. using namespace llvm;
  22. #define DEBUG_TYPE "regalloc"
  23. STATISTIC(NumDCEDeleted, "Number of instructions deleted by DCE");
  24. STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE");
  25. STATISTIC(NumFracRanges, "Number of live ranges fractured by DCE");
  26. void LiveRangeEdit::Delegate::anchor() { }
  27. LiveInterval &LiveRangeEdit::createEmptyIntervalFrom(Register OldReg,
  28. bool createSubRanges) {
  29. Register VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
  30. if (VRM)
  31. VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
  32. LiveInterval &LI = LIS.createEmptyInterval(VReg);
  33. if (Parent && !Parent->isSpillable())
  34. LI.markNotSpillable();
  35. if (createSubRanges) {
  36. // Create empty subranges if the OldReg's interval has them. Do not create
  37. // the main range here---it will be constructed later after the subranges
  38. // have been finalized.
  39. LiveInterval &OldLI = LIS.getInterval(OldReg);
  40. VNInfo::Allocator &Alloc = LIS.getVNInfoAllocator();
  41. for (LiveInterval::SubRange &S : OldLI.subranges())
  42. LI.createSubRange(Alloc, S.LaneMask);
  43. }
  44. return LI;
  45. }
  46. Register LiveRangeEdit::createFrom(Register OldReg) {
  47. Register VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
  48. if (VRM) {
  49. VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
  50. }
  51. // FIXME: Getting the interval here actually computes it.
  52. // In theory, this may not be what we want, but in practice
  53. // the createEmptyIntervalFrom API is used when this is not
  54. // the case. Generally speaking we just want to annotate the
  55. // LiveInterval when it gets created but we cannot do that at
  56. // the moment.
  57. if (Parent && !Parent->isSpillable())
  58. LIS.getInterval(VReg).markNotSpillable();
  59. return VReg;
  60. }
  61. bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
  62. const MachineInstr *DefMI,
  63. AAResults *aa) {
  64. assert(DefMI && "Missing instruction");
  65. ScannedRemattable = true;
  66. if (!TII.isTriviallyReMaterializable(*DefMI, aa))
  67. return false;
  68. Remattable.insert(VNI);
  69. return true;
  70. }
  71. void LiveRangeEdit::scanRemattable(AAResults *aa) {
  72. for (VNInfo *VNI : getParent().valnos) {
  73. if (VNI->isUnused())
  74. continue;
  75. unsigned Original = VRM->getOriginal(getReg());
  76. LiveInterval &OrigLI = LIS.getInterval(Original);
  77. VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
  78. if (!OrigVNI)
  79. continue;
  80. MachineInstr *DefMI = LIS.getInstructionFromIndex(OrigVNI->def);
  81. if (!DefMI)
  82. continue;
  83. checkRematerializable(OrigVNI, DefMI, aa);
  84. }
  85. ScannedRemattable = true;
  86. }
  87. bool LiveRangeEdit::anyRematerializable(AAResults *aa) {
  88. if (!ScannedRemattable)
  89. scanRemattable(aa);
  90. return !Remattable.empty();
  91. }
  92. /// allUsesAvailableAt - Return true if all registers used by OrigMI at
  93. /// OrigIdx are also available with the same value at UseIdx.
  94. bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
  95. SlotIndex OrigIdx,
  96. SlotIndex UseIdx) const {
  97. OrigIdx = OrigIdx.getRegSlot(true);
  98. UseIdx = std::max(UseIdx, UseIdx.getRegSlot(true));
  99. for (const MachineOperand &MO : OrigMI->operands()) {
  100. if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
  101. continue;
  102. // We can't remat physreg uses, unless it is a constant or target wants
  103. // to ignore this use.
  104. if (Register::isPhysicalRegister(MO.getReg())) {
  105. if (MRI.isConstantPhysReg(MO.getReg()) || TII.isIgnorableUse(MO))
  106. continue;
  107. return false;
  108. }
  109. LiveInterval &li = LIS.getInterval(MO.getReg());
  110. const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
  111. if (!OVNI)
  112. continue;
  113. // Don't allow rematerialization immediately after the original def.
  114. // It would be incorrect if OrigMI redefines the register.
  115. // See PR14098.
  116. if (SlotIndex::isSameInstr(OrigIdx, UseIdx))
  117. return false;
  118. if (OVNI != li.getVNInfoAt(UseIdx))
  119. return false;
  120. // Check that subrange is live at UseIdx.
  121. if (MO.getSubReg()) {
  122. const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
  123. LaneBitmask LM = TRI->getSubRegIndexLaneMask(MO.getSubReg());
  124. for (LiveInterval::SubRange &SR : li.subranges()) {
  125. if ((SR.LaneMask & LM).none())
  126. continue;
  127. if (!SR.liveAt(UseIdx))
  128. return false;
  129. // Early exit if all used lanes are checked. No need to continue.
  130. LM &= ~SR.LaneMask;
  131. if (LM.none())
  132. break;
  133. }
  134. }
  135. }
  136. return true;
  137. }
  138. bool LiveRangeEdit::canRematerializeAt(Remat &RM, VNInfo *OrigVNI,
  139. SlotIndex UseIdx, bool cheapAsAMove) {
  140. assert(ScannedRemattable && "Call anyRematerializable first");
  141. // Use scanRemattable info.
  142. if (!Remattable.count(OrigVNI))
  143. return false;
  144. // No defining instruction provided.
  145. SlotIndex DefIdx;
  146. assert(RM.OrigMI && "No defining instruction for remattable value");
  147. DefIdx = LIS.getInstructionIndex(*RM.OrigMI);
  148. // If only cheap remats were requested, bail out early.
  149. if (cheapAsAMove && !TII.isAsCheapAsAMove(*RM.OrigMI))
  150. return false;
  151. // Verify that all used registers are available with the same values.
  152. if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
  153. return false;
  154. return true;
  155. }
  156. SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
  157. MachineBasicBlock::iterator MI,
  158. unsigned DestReg,
  159. const Remat &RM,
  160. const TargetRegisterInfo &tri,
  161. bool Late) {
  162. assert(RM.OrigMI && "Invalid remat");
  163. TII.reMaterialize(MBB, MI, DestReg, 0, *RM.OrigMI, tri);
  164. // DestReg of the cloned instruction cannot be Dead. Set isDead of DestReg
  165. // to false anyway in case the isDead flag of RM.OrigMI's dest register
  166. // is true.
  167. (*--MI).getOperand(0).setIsDead(false);
  168. Rematted.insert(RM.ParentVNI);
  169. return LIS.getSlotIndexes()->insertMachineInstrInMaps(*MI, Late).getRegSlot();
  170. }
  171. void LiveRangeEdit::eraseVirtReg(Register Reg) {
  172. if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
  173. LIS.removeInterval(Reg);
  174. }
  175. bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
  176. SmallVectorImpl<MachineInstr*> &Dead) {
  177. MachineInstr *DefMI = nullptr, *UseMI = nullptr;
  178. // Check that there is a single def and a single use.
  179. for (MachineOperand &MO : MRI.reg_nodbg_operands(LI->reg())) {
  180. MachineInstr *MI = MO.getParent();
  181. if (MO.isDef()) {
  182. if (DefMI && DefMI != MI)
  183. return false;
  184. if (!MI->canFoldAsLoad())
  185. return false;
  186. DefMI = MI;
  187. } else if (!MO.isUndef()) {
  188. if (UseMI && UseMI != MI)
  189. return false;
  190. // FIXME: Targets don't know how to fold subreg uses.
  191. if (MO.getSubReg())
  192. return false;
  193. UseMI = MI;
  194. }
  195. }
  196. if (!DefMI || !UseMI)
  197. return false;
  198. // Since we're moving the DefMI load, make sure we're not extending any live
  199. // ranges.
  200. if (!allUsesAvailableAt(DefMI, LIS.getInstructionIndex(*DefMI),
  201. LIS.getInstructionIndex(*UseMI)))
  202. return false;
  203. // We also need to make sure it is safe to move the load.
  204. // Assume there are stores between DefMI and UseMI.
  205. bool SawStore = true;
  206. if (!DefMI->isSafeToMove(nullptr, SawStore))
  207. return false;
  208. LLVM_DEBUG(dbgs() << "Try to fold single def: " << *DefMI
  209. << " into single use: " << *UseMI);
  210. SmallVector<unsigned, 8> Ops;
  211. if (UseMI->readsWritesVirtualRegister(LI->reg(), &Ops).second)
  212. return false;
  213. MachineInstr *FoldMI = TII.foldMemoryOperand(*UseMI, Ops, *DefMI, &LIS);
  214. if (!FoldMI)
  215. return false;
  216. LLVM_DEBUG(dbgs() << " folded: " << *FoldMI);
  217. LIS.ReplaceMachineInstrInMaps(*UseMI, *FoldMI);
  218. // Update the call site info.
  219. if (UseMI->shouldUpdateCallSiteInfo())
  220. UseMI->getMF()->moveCallSiteInfo(UseMI, FoldMI);
  221. UseMI->eraseFromParent();
  222. DefMI->addRegisterDead(LI->reg(), nullptr);
  223. Dead.push_back(DefMI);
  224. ++NumDCEFoldedLoads;
  225. return true;
  226. }
  227. bool LiveRangeEdit::useIsKill(const LiveInterval &LI,
  228. const MachineOperand &MO) const {
  229. const MachineInstr &MI = *MO.getParent();
  230. SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
  231. if (LI.Query(Idx).isKill())
  232. return true;
  233. const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
  234. unsigned SubReg = MO.getSubReg();
  235. LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubReg);
  236. for (const LiveInterval::SubRange &S : LI.subranges()) {
  237. if ((S.LaneMask & LaneMask).any() && S.Query(Idx).isKill())
  238. return true;
  239. }
  240. return false;
  241. }
  242. /// Find all live intervals that need to shrink, then remove the instruction.
  243. void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink,
  244. AAResults *AA) {
  245. assert(MI->allDefsAreDead() && "Def isn't really dead");
  246. SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
  247. // Never delete a bundled instruction.
  248. if (MI->isBundled()) {
  249. return;
  250. }
  251. // Never delete inline asm.
  252. if (MI->isInlineAsm()) {
  253. LLVM_DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
  254. return;
  255. }
  256. // Use the same criteria as DeadMachineInstructionElim.
  257. bool SawStore = false;
  258. if (!MI->isSafeToMove(nullptr, SawStore)) {
  259. LLVM_DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
  260. return;
  261. }
  262. LLVM_DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
  263. // Collect virtual registers to be erased after MI is gone.
  264. SmallVector<unsigned, 8> RegsToErase;
  265. bool ReadsPhysRegs = false;
  266. bool isOrigDef = false;
  267. unsigned Dest;
  268. // Only optimize rematerialize case when the instruction has one def, since
  269. // otherwise we could leave some dead defs in the code. This case is
  270. // extremely rare.
  271. if (VRM && MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
  272. MI->getDesc().getNumDefs() == 1) {
  273. Dest = MI->getOperand(0).getReg();
  274. unsigned Original = VRM->getOriginal(Dest);
  275. LiveInterval &OrigLI = LIS.getInterval(Original);
  276. VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
  277. // The original live-range may have been shrunk to
  278. // an empty live-range. It happens when it is dead, but
  279. // we still keep it around to be able to rematerialize
  280. // other values that depend on it.
  281. if (OrigVNI)
  282. isOrigDef = SlotIndex::isSameInstr(OrigVNI->def, Idx);
  283. }
  284. bool HasLiveVRegUses = false;
  285. // Check for live intervals that may shrink
  286. for (const MachineOperand &MO : MI->operands()) {
  287. if (!MO.isReg())
  288. continue;
  289. Register Reg = MO.getReg();
  290. if (!Register::isVirtualRegister(Reg)) {
  291. // Check if MI reads any unreserved physregs.
  292. if (Reg && MO.readsReg() && !MRI.isReserved(Reg))
  293. ReadsPhysRegs = true;
  294. else if (MO.isDef())
  295. LIS.removePhysRegDefAt(Reg.asMCReg(), Idx);
  296. continue;
  297. }
  298. LiveInterval &LI = LIS.getInterval(Reg);
  299. // Shrink read registers, unless it is likely to be expensive and
  300. // unlikely to change anything. We typically don't want to shrink the
  301. // PIC base register that has lots of uses everywhere.
  302. // Always shrink COPY uses that probably come from live range splitting.
  303. if ((MI->readsVirtualRegister(Reg) && (MI->isCopy() || MO.isDef())) ||
  304. (MO.readsReg() && (MRI.hasOneNonDBGUse(Reg) || useIsKill(LI, MO))))
  305. ToShrink.insert(&LI);
  306. else if (MO.readsReg())
  307. HasLiveVRegUses = true;
  308. // Remove defined value.
  309. if (MO.isDef()) {
  310. if (TheDelegate && LI.getVNInfoAt(Idx) != nullptr)
  311. TheDelegate->LRE_WillShrinkVirtReg(LI.reg());
  312. LIS.removeVRegDefAt(LI, Idx);
  313. if (LI.empty())
  314. RegsToErase.push_back(Reg);
  315. }
  316. }
  317. // Currently, we don't support DCE of physreg live ranges. If MI reads
  318. // any unreserved physregs, don't erase the instruction, but turn it into
  319. // a KILL instead. This way, the physreg live ranges don't end up
  320. // dangling.
  321. // FIXME: It would be better to have something like shrinkToUses() for
  322. // physregs. That could potentially enable more DCE and it would free up
  323. // the physreg. It would not happen often, though.
  324. if (ReadsPhysRegs) {
  325. MI->setDesc(TII.get(TargetOpcode::KILL));
  326. // Remove all operands that aren't physregs.
  327. for (unsigned i = MI->getNumOperands(); i; --i) {
  328. const MachineOperand &MO = MI->getOperand(i-1);
  329. if (MO.isReg() && Register::isPhysicalRegister(MO.getReg()))
  330. continue;
  331. MI->RemoveOperand(i-1);
  332. }
  333. LLVM_DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
  334. } else {
  335. // If the dest of MI is an original reg and MI is reMaterializable,
  336. // don't delete the inst. Replace the dest with a new reg, and keep
  337. // the inst for remat of other siblings. The inst is saved in
  338. // LiveRangeEdit::DeadRemats and will be deleted after all the
  339. // allocations of the func are done.
  340. // However, immediately delete instructions which have unshrunk virtual
  341. // register uses. That may provoke RA to split an interval at the KILL
  342. // and later result in an invalid live segment end.
  343. if (isOrigDef && DeadRemats && !HasLiveVRegUses &&
  344. TII.isTriviallyReMaterializable(*MI, AA)) {
  345. LiveInterval &NewLI = createEmptyIntervalFrom(Dest, false);
  346. VNInfo *VNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
  347. NewLI.addSegment(LiveInterval::Segment(Idx, Idx.getDeadSlot(), VNI));
  348. pop_back();
  349. DeadRemats->insert(MI);
  350. const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
  351. MI->substituteRegister(Dest, NewLI.reg(), 0, TRI);
  352. MI->getOperand(0).setIsDead(true);
  353. } else {
  354. if (TheDelegate)
  355. TheDelegate->LRE_WillEraseInstruction(MI);
  356. LIS.RemoveMachineInstrFromMaps(*MI);
  357. MI->eraseFromParent();
  358. ++NumDCEDeleted;
  359. }
  360. }
  361. // Erase any virtregs that are now empty and unused. There may be <undef>
  362. // uses around. Keep the empty live range in that case.
  363. for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
  364. Register Reg = RegsToErase[i];
  365. if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
  366. ToShrink.remove(&LIS.getInterval(Reg));
  367. eraseVirtReg(Reg);
  368. }
  369. }
  370. }
  371. void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr *> &Dead,
  372. ArrayRef<Register> RegsBeingSpilled,
  373. AAResults *AA) {
  374. ToShrinkSet ToShrink;
  375. for (;;) {
  376. // Erase all dead defs.
  377. while (!Dead.empty())
  378. eliminateDeadDef(Dead.pop_back_val(), ToShrink, AA);
  379. if (ToShrink.empty())
  380. break;
  381. // Shrink just one live interval. Then delete new dead defs.
  382. LiveInterval *LI = ToShrink.pop_back_val();
  383. if (foldAsLoad(LI, Dead))
  384. continue;
  385. unsigned VReg = LI->reg();
  386. if (TheDelegate)
  387. TheDelegate->LRE_WillShrinkVirtReg(VReg);
  388. if (!LIS.shrinkToUses(LI, &Dead))
  389. continue;
  390. // Don't create new intervals for a register being spilled.
  391. // The new intervals would have to be spilled anyway so its not worth it.
  392. // Also they currently aren't spilled so creating them and not spilling
  393. // them results in incorrect code.
  394. if (llvm::is_contained(RegsBeingSpilled, VReg))
  395. continue;
  396. // LI may have been separated, create new intervals.
  397. LI->RenumberValues();
  398. SmallVector<LiveInterval*, 8> SplitLIs;
  399. LIS.splitSeparateComponents(*LI, SplitLIs);
  400. if (!SplitLIs.empty())
  401. ++NumFracRanges;
  402. Register Original = VRM ? VRM->getOriginal(VReg) : Register();
  403. for (const LiveInterval *SplitLI : SplitLIs) {
  404. // If LI is an original interval that hasn't been split yet, make the new
  405. // intervals their own originals instead of referring to LI. The original
  406. // interval must contain all the split products, and LI doesn't.
  407. if (Original != VReg && Original != 0)
  408. VRM->setIsSplitFromReg(SplitLI->reg(), Original);
  409. if (TheDelegate)
  410. TheDelegate->LRE_DidCloneVirtReg(SplitLI->reg(), VReg);
  411. }
  412. }
  413. }
  414. // Keep track of new virtual registers created via
  415. // MachineRegisterInfo::createVirtualRegister.
  416. void
  417. LiveRangeEdit::MRI_NoteNewVirtualRegister(Register VReg) {
  418. if (VRM)
  419. VRM->grow();
  420. NewRegs.push_back(VReg);
  421. }
  422. void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
  423. VirtRegAuxInfo &VRAI) {
  424. for (unsigned I = 0, Size = size(); I < Size; ++I) {
  425. LiveInterval &LI = LIS.getInterval(get(I));
  426. if (MRI.recomputeRegClass(LI.reg()))
  427. LLVM_DEBUG({
  428. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  429. dbgs() << "Inflated " << printReg(LI.reg()) << " to "
  430. << TRI->getRegClassName(MRI.getRegClass(LI.reg())) << '\n';
  431. });
  432. VRAI.calculateSpillWeightAndHint(LI);
  433. }
  434. }