LiveRangeEdit.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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(unsigned 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. unsigned LiveRangeEdit::createFrom(unsigned 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. AliasAnalysis *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(AliasAnalysis *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(AliasAnalysis *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 = UseIdx.getRegSlot(true);
  99. for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
  100. const MachineOperand &MO = OrigMI->getOperand(i);
  101. if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
  102. continue;
  103. // We can't remat physreg uses, unless it is a constant.
  104. if (Register::isPhysicalRegister(MO.getReg())) {
  105. if (MRI.isConstantPhysReg(MO.getReg()))
  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. }
  121. return true;
  122. }
  123. bool LiveRangeEdit::canRematerializeAt(Remat &RM, VNInfo *OrigVNI,
  124. SlotIndex UseIdx, bool cheapAsAMove) {
  125. assert(ScannedRemattable && "Call anyRematerializable first");
  126. // Use scanRemattable info.
  127. if (!Remattable.count(OrigVNI))
  128. return false;
  129. // No defining instruction provided.
  130. SlotIndex DefIdx;
  131. assert(RM.OrigMI && "No defining instruction for remattable value");
  132. DefIdx = LIS.getInstructionIndex(*RM.OrigMI);
  133. // If only cheap remats were requested, bail out early.
  134. if (cheapAsAMove && !TII.isAsCheapAsAMove(*RM.OrigMI))
  135. return false;
  136. // Verify that all used registers are available with the same values.
  137. if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
  138. return false;
  139. return true;
  140. }
  141. SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
  142. MachineBasicBlock::iterator MI,
  143. unsigned DestReg,
  144. const Remat &RM,
  145. const TargetRegisterInfo &tri,
  146. bool Late) {
  147. assert(RM.OrigMI && "Invalid remat");
  148. TII.reMaterialize(MBB, MI, DestReg, 0, *RM.OrigMI, tri);
  149. // DestReg of the cloned instruction cannot be Dead. Set isDead of DestReg
  150. // to false anyway in case the isDead flag of RM.OrigMI's dest register
  151. // is true.
  152. (*--MI).getOperand(0).setIsDead(false);
  153. Rematted.insert(RM.ParentVNI);
  154. return LIS.getSlotIndexes()->insertMachineInstrInMaps(*MI, Late).getRegSlot();
  155. }
  156. void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
  157. if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
  158. LIS.removeInterval(Reg);
  159. }
  160. bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
  161. SmallVectorImpl<MachineInstr*> &Dead) {
  162. MachineInstr *DefMI = nullptr, *UseMI = nullptr;
  163. // Check that there is a single def and a single use.
  164. for (MachineOperand &MO : MRI.reg_nodbg_operands(LI->reg)) {
  165. MachineInstr *MI = MO.getParent();
  166. if (MO.isDef()) {
  167. if (DefMI && DefMI != MI)
  168. return false;
  169. if (!MI->canFoldAsLoad())
  170. return false;
  171. DefMI = MI;
  172. } else if (!MO.isUndef()) {
  173. if (UseMI && UseMI != MI)
  174. return false;
  175. // FIXME: Targets don't know how to fold subreg uses.
  176. if (MO.getSubReg())
  177. return false;
  178. UseMI = MI;
  179. }
  180. }
  181. if (!DefMI || !UseMI)
  182. return false;
  183. // Since we're moving the DefMI load, make sure we're not extending any live
  184. // ranges.
  185. if (!allUsesAvailableAt(DefMI, LIS.getInstructionIndex(*DefMI),
  186. LIS.getInstructionIndex(*UseMI)))
  187. return false;
  188. // We also need to make sure it is safe to move the load.
  189. // Assume there are stores between DefMI and UseMI.
  190. bool SawStore = true;
  191. if (!DefMI->isSafeToMove(nullptr, SawStore))
  192. return false;
  193. LLVM_DEBUG(dbgs() << "Try to fold single def: " << *DefMI
  194. << " into single use: " << *UseMI);
  195. SmallVector<unsigned, 8> Ops;
  196. if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
  197. return false;
  198. MachineInstr *FoldMI = TII.foldMemoryOperand(*UseMI, Ops, *DefMI, &LIS);
  199. if (!FoldMI)
  200. return false;
  201. LLVM_DEBUG(dbgs() << " folded: " << *FoldMI);
  202. LIS.ReplaceMachineInstrInMaps(*UseMI, *FoldMI);
  203. if (UseMI->isCall())
  204. UseMI->getMF()->updateCallSiteInfo(UseMI, FoldMI);
  205. UseMI->eraseFromParent();
  206. DefMI->addRegisterDead(LI->reg, nullptr);
  207. Dead.push_back(DefMI);
  208. ++NumDCEFoldedLoads;
  209. return true;
  210. }
  211. bool LiveRangeEdit::useIsKill(const LiveInterval &LI,
  212. const MachineOperand &MO) const {
  213. const MachineInstr &MI = *MO.getParent();
  214. SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
  215. if (LI.Query(Idx).isKill())
  216. return true;
  217. const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
  218. unsigned SubReg = MO.getSubReg();
  219. LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubReg);
  220. for (const LiveInterval::SubRange &S : LI.subranges()) {
  221. if ((S.LaneMask & LaneMask).any() && S.Query(Idx).isKill())
  222. return true;
  223. }
  224. return false;
  225. }
  226. /// Find all live intervals that need to shrink, then remove the instruction.
  227. void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink,
  228. AliasAnalysis *AA) {
  229. assert(MI->allDefsAreDead() && "Def isn't really dead");
  230. SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
  231. // Never delete a bundled instruction.
  232. if (MI->isBundled()) {
  233. return;
  234. }
  235. // Never delete inline asm.
  236. if (MI->isInlineAsm()) {
  237. LLVM_DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
  238. return;
  239. }
  240. // Use the same criteria as DeadMachineInstructionElim.
  241. bool SawStore = false;
  242. if (!MI->isSafeToMove(nullptr, SawStore)) {
  243. LLVM_DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
  244. return;
  245. }
  246. LLVM_DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
  247. // Collect virtual registers to be erased after MI is gone.
  248. SmallVector<unsigned, 8> RegsToErase;
  249. bool ReadsPhysRegs = false;
  250. bool isOrigDef = false;
  251. unsigned Dest;
  252. // Only optimize rematerialize case when the instruction has one def, since
  253. // otherwise we could leave some dead defs in the code. This case is
  254. // extremely rare.
  255. if (VRM && MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
  256. MI->getDesc().getNumDefs() == 1) {
  257. Dest = MI->getOperand(0).getReg();
  258. unsigned Original = VRM->getOriginal(Dest);
  259. LiveInterval &OrigLI = LIS.getInterval(Original);
  260. VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
  261. // The original live-range may have been shrunk to
  262. // an empty live-range. It happens when it is dead, but
  263. // we still keep it around to be able to rematerialize
  264. // other values that depend on it.
  265. if (OrigVNI)
  266. isOrigDef = SlotIndex::isSameInstr(OrigVNI->def, Idx);
  267. }
  268. // Check for live intervals that may shrink
  269. for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
  270. MOE = MI->operands_end(); MOI != MOE; ++MOI) {
  271. if (!MOI->isReg())
  272. continue;
  273. Register Reg = MOI->getReg();
  274. if (!Register::isVirtualRegister(Reg)) {
  275. // Check if MI reads any unreserved physregs.
  276. if (Reg && MOI->readsReg() && !MRI.isReserved(Reg))
  277. ReadsPhysRegs = true;
  278. else if (MOI->isDef())
  279. LIS.removePhysRegDefAt(Reg, Idx);
  280. continue;
  281. }
  282. LiveInterval &LI = LIS.getInterval(Reg);
  283. // Shrink read registers, unless it is likely to be expensive and
  284. // unlikely to change anything. We typically don't want to shrink the
  285. // PIC base register that has lots of uses everywhere.
  286. // Always shrink COPY uses that probably come from live range splitting.
  287. if ((MI->readsVirtualRegister(Reg) && (MI->isCopy() || MOI->isDef())) ||
  288. (MOI->readsReg() && (MRI.hasOneNonDBGUse(Reg) || useIsKill(LI, *MOI))))
  289. ToShrink.insert(&LI);
  290. // Remove defined value.
  291. if (MOI->isDef()) {
  292. if (TheDelegate && LI.getVNInfoAt(Idx) != nullptr)
  293. TheDelegate->LRE_WillShrinkVirtReg(LI.reg);
  294. LIS.removeVRegDefAt(LI, Idx);
  295. if (LI.empty())
  296. RegsToErase.push_back(Reg);
  297. }
  298. }
  299. // Currently, we don't support DCE of physreg live ranges. If MI reads
  300. // any unreserved physregs, don't erase the instruction, but turn it into
  301. // a KILL instead. This way, the physreg live ranges don't end up
  302. // dangling.
  303. // FIXME: It would be better to have something like shrinkToUses() for
  304. // physregs. That could potentially enable more DCE and it would free up
  305. // the physreg. It would not happen often, though.
  306. if (ReadsPhysRegs) {
  307. MI->setDesc(TII.get(TargetOpcode::KILL));
  308. // Remove all operands that aren't physregs.
  309. for (unsigned i = MI->getNumOperands(); i; --i) {
  310. const MachineOperand &MO = MI->getOperand(i-1);
  311. if (MO.isReg() && Register::isPhysicalRegister(MO.getReg()))
  312. continue;
  313. MI->RemoveOperand(i-1);
  314. }
  315. LLVM_DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
  316. } else {
  317. // If the dest of MI is an original reg and MI is reMaterializable,
  318. // don't delete the inst. Replace the dest with a new reg, and keep
  319. // the inst for remat of other siblings. The inst is saved in
  320. // LiveRangeEdit::DeadRemats and will be deleted after all the
  321. // allocations of the func are done.
  322. if (isOrigDef && DeadRemats && TII.isTriviallyReMaterializable(*MI, AA)) {
  323. LiveInterval &NewLI = createEmptyIntervalFrom(Dest, false);
  324. VNInfo *VNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
  325. NewLI.addSegment(LiveInterval::Segment(Idx, Idx.getDeadSlot(), VNI));
  326. pop_back();
  327. DeadRemats->insert(MI);
  328. const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
  329. MI->substituteRegister(Dest, NewLI.reg, 0, TRI);
  330. MI->getOperand(0).setIsDead(true);
  331. } else {
  332. if (TheDelegate)
  333. TheDelegate->LRE_WillEraseInstruction(MI);
  334. LIS.RemoveMachineInstrFromMaps(*MI);
  335. MI->eraseFromParent();
  336. ++NumDCEDeleted;
  337. }
  338. }
  339. // Erase any virtregs that are now empty and unused. There may be <undef>
  340. // uses around. Keep the empty live range in that case.
  341. for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
  342. unsigned Reg = RegsToErase[i];
  343. if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
  344. ToShrink.remove(&LIS.getInterval(Reg));
  345. eraseVirtReg(Reg);
  346. }
  347. }
  348. }
  349. void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr *> &Dead,
  350. ArrayRef<unsigned> RegsBeingSpilled,
  351. AliasAnalysis *AA) {
  352. ToShrinkSet ToShrink;
  353. for (;;) {
  354. // Erase all dead defs.
  355. while (!Dead.empty())
  356. eliminateDeadDef(Dead.pop_back_val(), ToShrink, AA);
  357. if (ToShrink.empty())
  358. break;
  359. // Shrink just one live interval. Then delete new dead defs.
  360. LiveInterval *LI = ToShrink.back();
  361. ToShrink.pop_back();
  362. if (foldAsLoad(LI, Dead))
  363. continue;
  364. unsigned VReg = LI->reg;
  365. if (TheDelegate)
  366. TheDelegate->LRE_WillShrinkVirtReg(VReg);
  367. if (!LIS.shrinkToUses(LI, &Dead))
  368. continue;
  369. // Don't create new intervals for a register being spilled.
  370. // The new intervals would have to be spilled anyway so its not worth it.
  371. // Also they currently aren't spilled so creating them and not spilling
  372. // them results in incorrect code.
  373. bool BeingSpilled = false;
  374. for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
  375. if (VReg == RegsBeingSpilled[i]) {
  376. BeingSpilled = true;
  377. break;
  378. }
  379. }
  380. if (BeingSpilled) continue;
  381. // LI may have been separated, create new intervals.
  382. LI->RenumberValues();
  383. SmallVector<LiveInterval*, 8> SplitLIs;
  384. LIS.splitSeparateComponents(*LI, SplitLIs);
  385. if (!SplitLIs.empty())
  386. ++NumFracRanges;
  387. unsigned Original = VRM ? VRM->getOriginal(VReg) : 0;
  388. for (const LiveInterval *SplitLI : SplitLIs) {
  389. // If LI is an original interval that hasn't been split yet, make the new
  390. // intervals their own originals instead of referring to LI. The original
  391. // interval must contain all the split products, and LI doesn't.
  392. if (Original != VReg && Original != 0)
  393. VRM->setIsSplitFromReg(SplitLI->reg, Original);
  394. if (TheDelegate)
  395. TheDelegate->LRE_DidCloneVirtReg(SplitLI->reg, VReg);
  396. }
  397. }
  398. }
  399. // Keep track of new virtual registers created via
  400. // MachineRegisterInfo::createVirtualRegister.
  401. void
  402. LiveRangeEdit::MRI_NoteNewVirtualRegister(unsigned VReg)
  403. {
  404. if (VRM)
  405. VRM->grow();
  406. NewRegs.push_back(VReg);
  407. }
  408. void
  409. LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
  410. const MachineLoopInfo &Loops,
  411. const MachineBlockFrequencyInfo &MBFI) {
  412. VirtRegAuxInfo VRAI(MF, LIS, VRM, Loops, MBFI);
  413. for (unsigned I = 0, Size = size(); I < Size; ++I) {
  414. LiveInterval &LI = LIS.getInterval(get(I));
  415. if (MRI.recomputeRegClass(LI.reg))
  416. LLVM_DEBUG({
  417. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  418. dbgs() << "Inflated " << printReg(LI.reg) << " to "
  419. << TRI->getRegClassName(MRI.getRegClass(LI.reg)) << '\n';
  420. });
  421. VRAI.calculateSpillWeightAndHint(LI);
  422. }
  423. }