LiveIntervalAnalysis.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  1. //===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
  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. // This file implements the LiveInterval analysis pass which is used
  11. // by the Linear Scan Register allocator. This pass linearizes the
  12. // basic blocks of the function in DFS order and uses the
  13. // LiveVariables pass to conservatively compute live intervals for
  14. // each virtual and physical register.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  18. #include "LiveRangeCalc.h"
  19. #include "llvm/ADT/DenseSet.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/Analysis/AliasAnalysis.h"
  22. #include "llvm/CodeGen/LiveVariables.h"
  23. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  24. #include "llvm/CodeGen/MachineDominators.h"
  25. #include "llvm/CodeGen/MachineInstr.h"
  26. #include "llvm/CodeGen/MachineRegisterInfo.h"
  27. #include "llvm/CodeGen/Passes.h"
  28. #include "llvm/CodeGen/VirtRegMap.h"
  29. #include "llvm/IR/Value.h"
  30. #include "llvm/Support/BlockFrequency.h"
  31. #include "llvm/Support/CommandLine.h"
  32. #include "llvm/Support/Debug.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/Format.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/Target/TargetInstrInfo.h"
  37. #include "llvm/Target/TargetRegisterInfo.h"
  38. #include "llvm/Target/TargetSubtargetInfo.h"
  39. #include <algorithm>
  40. #include <cmath>
  41. #include <limits>
  42. using namespace llvm;
  43. #define DEBUG_TYPE "regalloc"
  44. char LiveIntervals::ID = 0;
  45. char &llvm::LiveIntervalsID = LiveIntervals::ID;
  46. INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
  47. "Live Interval Analysis", false, false)
  48. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  49. INITIALIZE_PASS_DEPENDENCY(LiveVariables)
  50. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  51. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  52. INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
  53. "Live Interval Analysis", false, false)
  54. #ifndef NDEBUG
  55. static cl::opt<bool> EnablePrecomputePhysRegs(
  56. "precompute-phys-liveness", cl::Hidden,
  57. cl::desc("Eagerly compute live intervals for all physreg units."));
  58. #else
  59. static bool EnablePrecomputePhysRegs = false;
  60. #endif // NDEBUG
  61. static cl::opt<bool> EnableSubRegLiveness(
  62. "enable-subreg-liveness", cl::Hidden, cl::init(true),
  63. cl::desc("Enable subregister liveness tracking."));
  64. namespace llvm {
  65. cl::opt<bool> UseSegmentSetForPhysRegs(
  66. "use-segment-set-for-physregs", cl::Hidden, cl::init(true),
  67. cl::desc(
  68. "Use segment set for the computation of the live ranges of physregs."));
  69. }
  70. void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
  71. AU.setPreservesCFG();
  72. AU.addRequired<AliasAnalysis>();
  73. AU.addPreserved<AliasAnalysis>();
  74. // LiveVariables isn't really required by this analysis, it is only required
  75. // here to make sure it is live during TwoAddressInstructionPass and
  76. // PHIElimination. This is temporary.
  77. AU.addRequired<LiveVariables>();
  78. AU.addPreserved<LiveVariables>();
  79. AU.addPreservedID(MachineLoopInfoID);
  80. AU.addRequiredTransitiveID(MachineDominatorsID);
  81. AU.addPreservedID(MachineDominatorsID);
  82. AU.addPreserved<SlotIndexes>();
  83. AU.addRequiredTransitive<SlotIndexes>();
  84. MachineFunctionPass::getAnalysisUsage(AU);
  85. }
  86. LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
  87. DomTree(nullptr), LRCalc(nullptr) {
  88. initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
  89. }
  90. LiveIntervals::~LiveIntervals() {
  91. delete LRCalc;
  92. }
  93. void LiveIntervals::releaseMemory() {
  94. // Free the live intervals themselves.
  95. for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
  96. delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
  97. VirtRegIntervals.clear();
  98. RegMaskSlots.clear();
  99. RegMaskBits.clear();
  100. RegMaskBlocks.clear();
  101. for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
  102. delete RegUnitRanges[i];
  103. RegUnitRanges.clear();
  104. // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
  105. VNInfoAllocator.Reset();
  106. }
  107. /// runOnMachineFunction - calculates LiveIntervals
  108. ///
  109. bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
  110. MF = &fn;
  111. MRI = &MF->getRegInfo();
  112. TRI = MF->getSubtarget().getRegisterInfo();
  113. TII = MF->getSubtarget().getInstrInfo();
  114. AA = &getAnalysis<AliasAnalysis>();
  115. Indexes = &getAnalysis<SlotIndexes>();
  116. DomTree = &getAnalysis<MachineDominatorTree>();
  117. if (EnableSubRegLiveness && MF->getSubtarget().enableSubRegLiveness())
  118. MRI->enableSubRegLiveness(true);
  119. if (!LRCalc)
  120. LRCalc = new LiveRangeCalc();
  121. // Allocate space for all virtual registers.
  122. VirtRegIntervals.resize(MRI->getNumVirtRegs());
  123. computeVirtRegs();
  124. computeRegMasks();
  125. computeLiveInRegUnits();
  126. if (EnablePrecomputePhysRegs) {
  127. // For stress testing, precompute live ranges of all physical register
  128. // units, including reserved registers.
  129. for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
  130. getRegUnit(i);
  131. }
  132. DEBUG(dump());
  133. return true;
  134. }
  135. /// print - Implement the dump method.
  136. void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
  137. OS << "********** INTERVALS **********\n";
  138. // Dump the regunits.
  139. for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
  140. if (LiveRange *LR = RegUnitRanges[i])
  141. OS << PrintRegUnit(i, TRI) << ' ' << *LR << '\n';
  142. // Dump the virtregs.
  143. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  144. unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  145. if (hasInterval(Reg))
  146. OS << getInterval(Reg) << '\n';
  147. }
  148. OS << "RegMasks:";
  149. for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
  150. OS << ' ' << RegMaskSlots[i];
  151. OS << '\n';
  152. printInstrs(OS);
  153. }
  154. void LiveIntervals::printInstrs(raw_ostream &OS) const {
  155. OS << "********** MACHINEINSTRS **********\n";
  156. MF->print(OS, Indexes);
  157. }
  158. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  159. void LiveIntervals::dumpInstrs() const {
  160. printInstrs(dbgs());
  161. }
  162. #endif
  163. LiveInterval* LiveIntervals::createInterval(unsigned reg) {
  164. float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
  165. llvm::huge_valf : 0.0F;
  166. return new LiveInterval(reg, Weight);
  167. }
  168. /// computeVirtRegInterval - Compute the live interval of a virtual register,
  169. /// based on defs and uses.
  170. void LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
  171. assert(LRCalc && "LRCalc not initialized.");
  172. assert(LI.empty() && "Should only compute empty intervals.");
  173. LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
  174. LRCalc->calculate(LI, MRI->shouldTrackSubRegLiveness(LI.reg));
  175. computeDeadValues(LI, nullptr);
  176. }
  177. void LiveIntervals::computeVirtRegs() {
  178. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  179. unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  180. if (MRI->reg_nodbg_empty(Reg))
  181. continue;
  182. createAndComputeVirtRegInterval(Reg);
  183. }
  184. }
  185. void LiveIntervals::computeRegMasks() {
  186. RegMaskBlocks.resize(MF->getNumBlockIDs());
  187. // Find all instructions with regmask operands.
  188. for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
  189. MBBI != E; ++MBBI) {
  190. MachineBasicBlock *MBB = MBBI;
  191. std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
  192. RMB.first = RegMaskSlots.size();
  193. for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
  194. MI != ME; ++MI)
  195. for (const MachineOperand &MO : MI->operands()) {
  196. if (!MO.isRegMask())
  197. continue;
  198. RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
  199. RegMaskBits.push_back(MO.getRegMask());
  200. }
  201. // Compute the number of register mask instructions in this block.
  202. RMB.second = RegMaskSlots.size() - RMB.first;
  203. }
  204. }
  205. //===----------------------------------------------------------------------===//
  206. // Register Unit Liveness
  207. //===----------------------------------------------------------------------===//
  208. //
  209. // Fixed interference typically comes from ABI boundaries: Function arguments
  210. // and return values are passed in fixed registers, and so are exception
  211. // pointers entering landing pads. Certain instructions require values to be
  212. // present in specific registers. That is also represented through fixed
  213. // interference.
  214. //
  215. /// computeRegUnitInterval - Compute the live range of a register unit, based
  216. /// on the uses and defs of aliasing registers. The range should be empty,
  217. /// or contain only dead phi-defs from ABI blocks.
  218. void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
  219. assert(LRCalc && "LRCalc not initialized.");
  220. LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
  221. // The physregs aliasing Unit are the roots and their super-registers.
  222. // Create all values as dead defs before extending to uses. Note that roots
  223. // may share super-registers. That's OK because createDeadDefs() is
  224. // idempotent. It is very rare for a register unit to have multiple roots, so
  225. // uniquing super-registers is probably not worthwhile.
  226. for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
  227. for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
  228. Supers.isValid(); ++Supers) {
  229. if (!MRI->reg_empty(*Supers))
  230. LRCalc->createDeadDefs(LR, *Supers);
  231. }
  232. }
  233. // Now extend LR to reach all uses.
  234. // Ignore uses of reserved registers. We only track defs of those.
  235. for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
  236. for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
  237. Supers.isValid(); ++Supers) {
  238. unsigned Reg = *Supers;
  239. if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
  240. LRCalc->extendToUses(LR, Reg);
  241. }
  242. }
  243. // Flush the segment set to the segment vector.
  244. if (UseSegmentSetForPhysRegs)
  245. LR.flushSegmentSet();
  246. }
  247. /// computeLiveInRegUnits - Precompute the live ranges of any register units
  248. /// that are live-in to an ABI block somewhere. Register values can appear
  249. /// without a corresponding def when entering the entry block or a landing pad.
  250. ///
  251. void LiveIntervals::computeLiveInRegUnits() {
  252. RegUnitRanges.resize(TRI->getNumRegUnits());
  253. DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
  254. // Keep track of the live range sets allocated.
  255. SmallVector<unsigned, 8> NewRanges;
  256. // Check all basic blocks for live-ins.
  257. for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
  258. MFI != MFE; ++MFI) {
  259. const MachineBasicBlock *MBB = MFI;
  260. // We only care about ABI blocks: Entry + landing pads.
  261. if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
  262. continue;
  263. // Create phi-defs at Begin for all live-in registers.
  264. SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
  265. DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
  266. for (MachineBasicBlock::livein_iterator LII = MBB->livein_begin(),
  267. LIE = MBB->livein_end(); LII != LIE; ++LII) {
  268. for (MCRegUnitIterator Units(*LII, TRI); Units.isValid(); ++Units) {
  269. unsigned Unit = *Units;
  270. LiveRange *LR = RegUnitRanges[Unit];
  271. if (!LR) {
  272. // Use segment set to speed-up initial computation of the live range.
  273. LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs);
  274. NewRanges.push_back(Unit);
  275. }
  276. VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
  277. (void)VNI;
  278. DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
  279. }
  280. }
  281. DEBUG(dbgs() << '\n');
  282. }
  283. DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
  284. // Compute the 'normal' part of the ranges.
  285. for (unsigned i = 0, e = NewRanges.size(); i != e; ++i) {
  286. unsigned Unit = NewRanges[i];
  287. computeRegUnitRange(*RegUnitRanges[Unit], Unit);
  288. }
  289. }
  290. static void createSegmentsForValues(LiveRange &LR,
  291. iterator_range<LiveInterval::vni_iterator> VNIs) {
  292. for (auto VNI : VNIs) {
  293. if (VNI->isUnused())
  294. continue;
  295. SlotIndex Def = VNI->def;
  296. LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
  297. }
  298. }
  299. typedef SmallVector<std::pair<SlotIndex, VNInfo*>, 16> ShrinkToUsesWorkList;
  300. static void extendSegmentsToUses(LiveRange &LR, const SlotIndexes &Indexes,
  301. ShrinkToUsesWorkList &WorkList,
  302. const LiveRange &OldRange) {
  303. // Keep track of the PHIs that are in use.
  304. SmallPtrSet<VNInfo*, 8> UsedPHIs;
  305. // Blocks that have already been added to WorkList as live-out.
  306. SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
  307. // Extend intervals to reach all uses in WorkList.
  308. while (!WorkList.empty()) {
  309. SlotIndex Idx = WorkList.back().first;
  310. VNInfo *VNI = WorkList.back().second;
  311. WorkList.pop_back();
  312. const MachineBasicBlock *MBB = Indexes.getMBBFromIndex(Idx.getPrevSlot());
  313. SlotIndex BlockStart = Indexes.getMBBStartIdx(MBB);
  314. // Extend the live range for VNI to be live at Idx.
  315. if (VNInfo *ExtVNI = LR.extendInBlock(BlockStart, Idx)) {
  316. assert(ExtVNI == VNI && "Unexpected existing value number");
  317. (void)ExtVNI;
  318. // Is this a PHIDef we haven't seen before?
  319. if (!VNI->isPHIDef() || VNI->def != BlockStart ||
  320. !UsedPHIs.insert(VNI).second)
  321. continue;
  322. // The PHI is live, make sure the predecessors are live-out.
  323. for (auto &Pred : MBB->predecessors()) {
  324. if (!LiveOut.insert(Pred).second)
  325. continue;
  326. SlotIndex Stop = Indexes.getMBBEndIdx(Pred);
  327. // A predecessor is not required to have a live-out value for a PHI.
  328. if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
  329. WorkList.push_back(std::make_pair(Stop, PVNI));
  330. }
  331. continue;
  332. }
  333. // VNI is live-in to MBB.
  334. DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
  335. LR.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
  336. // Make sure VNI is live-out from the predecessors.
  337. for (auto &Pred : MBB->predecessors()) {
  338. if (!LiveOut.insert(Pred).second)
  339. continue;
  340. SlotIndex Stop = Indexes.getMBBEndIdx(Pred);
  341. assert(OldRange.getVNInfoBefore(Stop) == VNI &&
  342. "Wrong value out of predecessor");
  343. WorkList.push_back(std::make_pair(Stop, VNI));
  344. }
  345. }
  346. }
  347. /// shrinkToUses - After removing some uses of a register, shrink its live
  348. /// range to just the remaining uses. This method does not compute reaching
  349. /// defs for new uses, and it doesn't remove dead defs.
  350. bool LiveIntervals::shrinkToUses(LiveInterval *li,
  351. SmallVectorImpl<MachineInstr*> *dead) {
  352. DEBUG(dbgs() << "Shrink: " << *li << '\n');
  353. assert(TargetRegisterInfo::isVirtualRegister(li->reg)
  354. && "Can only shrink virtual registers");
  355. // Shrink subregister live ranges.
  356. for (LiveInterval::SubRange &S : li->subranges()) {
  357. shrinkToUses(S, li->reg);
  358. }
  359. // Find all the values used, including PHI kills.
  360. ShrinkToUsesWorkList WorkList;
  361. // Visit all instructions reading li->reg.
  362. for (MachineRegisterInfo::reg_instr_iterator
  363. I = MRI->reg_instr_begin(li->reg), E = MRI->reg_instr_end();
  364. I != E; ) {
  365. MachineInstr *UseMI = &*(I++);
  366. if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
  367. continue;
  368. SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
  369. LiveQueryResult LRQ = li->Query(Idx);
  370. VNInfo *VNI = LRQ.valueIn();
  371. if (!VNI) {
  372. // This shouldn't happen: readsVirtualRegister returns true, but there is
  373. // no live value. It is likely caused by a target getting <undef> flags
  374. // wrong.
  375. DEBUG(dbgs() << Idx << '\t' << *UseMI
  376. << "Warning: Instr claims to read non-existent value in "
  377. << *li << '\n');
  378. continue;
  379. }
  380. // Special case: An early-clobber tied operand reads and writes the
  381. // register one slot early.
  382. if (VNInfo *DefVNI = LRQ.valueDefined())
  383. Idx = DefVNI->def;
  384. WorkList.push_back(std::make_pair(Idx, VNI));
  385. }
  386. // Create new live ranges with only minimal live segments per def.
  387. LiveRange NewLR;
  388. createSegmentsForValues(NewLR, make_range(li->vni_begin(), li->vni_end()));
  389. extendSegmentsToUses(NewLR, *Indexes, WorkList, *li);
  390. // Move the trimmed segments back.
  391. li->segments.swap(NewLR.segments);
  392. // Handle dead values.
  393. bool CanSeparate = computeDeadValues(*li, dead);
  394. DEBUG(dbgs() << "Shrunk: " << *li << '\n');
  395. return CanSeparate;
  396. }
  397. bool LiveIntervals::computeDeadValues(LiveInterval &LI,
  398. SmallVectorImpl<MachineInstr*> *dead) {
  399. bool PHIRemoved = false;
  400. for (auto VNI : LI.valnos) {
  401. if (VNI->isUnused())
  402. continue;
  403. SlotIndex Def = VNI->def;
  404. LiveRange::iterator I = LI.FindSegmentContaining(Def);
  405. assert(I != LI.end() && "Missing segment for VNI");
  406. // Is the register live before? Otherwise we may have to add a read-undef
  407. // flag for subregister defs.
  408. if (MRI->shouldTrackSubRegLiveness(LI.reg)) {
  409. if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
  410. MachineInstr *MI = getInstructionFromIndex(Def);
  411. MI->addRegisterDefReadUndef(LI.reg);
  412. }
  413. }
  414. if (I->end != Def.getDeadSlot())
  415. continue;
  416. if (VNI->isPHIDef()) {
  417. // This is a dead PHI. Remove it.
  418. VNI->markUnused();
  419. LI.removeSegment(I);
  420. DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
  421. PHIRemoved = true;
  422. } else {
  423. // This is a dead def. Make sure the instruction knows.
  424. MachineInstr *MI = getInstructionFromIndex(Def);
  425. assert(MI && "No instruction defining live value");
  426. MI->addRegisterDead(LI.reg, TRI);
  427. if (dead && MI->allDefsAreDead()) {
  428. DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
  429. dead->push_back(MI);
  430. }
  431. }
  432. }
  433. return PHIRemoved;
  434. }
  435. void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, unsigned Reg)
  436. {
  437. DEBUG(dbgs() << "Shrink: " << SR << '\n');
  438. assert(TargetRegisterInfo::isVirtualRegister(Reg)
  439. && "Can only shrink virtual registers");
  440. // Find all the values used, including PHI kills.
  441. ShrinkToUsesWorkList WorkList;
  442. // Visit all instructions reading Reg.
  443. SlotIndex LastIdx;
  444. for (MachineOperand &MO : MRI->reg_operands(Reg)) {
  445. MachineInstr *UseMI = MO.getParent();
  446. if (UseMI->isDebugValue())
  447. continue;
  448. // Maybe the operand is for a subregister we don't care about.
  449. unsigned SubReg = MO.getSubReg();
  450. if (SubReg != 0) {
  451. unsigned SubRegMask = TRI->getSubRegIndexLaneMask(SubReg);
  452. if ((SubRegMask & SR.LaneMask) == 0)
  453. continue;
  454. }
  455. // We only need to visit each instruction once.
  456. SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
  457. if (Idx == LastIdx)
  458. continue;
  459. LastIdx = Idx;
  460. LiveQueryResult LRQ = SR.Query(Idx);
  461. VNInfo *VNI = LRQ.valueIn();
  462. // For Subranges it is possible that only undef values are left in that
  463. // part of the subregister, so there is no real liverange at the use
  464. if (!VNI)
  465. continue;
  466. // Special case: An early-clobber tied operand reads and writes the
  467. // register one slot early.
  468. if (VNInfo *DefVNI = LRQ.valueDefined())
  469. Idx = DefVNI->def;
  470. WorkList.push_back(std::make_pair(Idx, VNI));
  471. }
  472. // Create a new live ranges with only minimal live segments per def.
  473. LiveRange NewLR;
  474. createSegmentsForValues(NewLR, make_range(SR.vni_begin(), SR.vni_end()));
  475. extendSegmentsToUses(NewLR, *Indexes, WorkList, SR);
  476. // Move the trimmed ranges back.
  477. SR.segments.swap(NewLR.segments);
  478. // Remove dead PHI value numbers
  479. for (auto VNI : SR.valnos) {
  480. if (VNI->isUnused())
  481. continue;
  482. const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
  483. assert(Segment != nullptr && "Missing segment for VNI");
  484. if (Segment->end != VNI->def.getDeadSlot())
  485. continue;
  486. if (VNI->isPHIDef()) {
  487. // This is a dead PHI. Remove it.
  488. VNI->markUnused();
  489. SR.removeSegment(*Segment);
  490. DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
  491. }
  492. }
  493. DEBUG(dbgs() << "Shrunk: " << SR << '\n');
  494. }
  495. void LiveIntervals::extendToIndices(LiveRange &LR,
  496. ArrayRef<SlotIndex> Indices) {
  497. assert(LRCalc && "LRCalc not initialized.");
  498. LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
  499. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  500. LRCalc->extend(LR, Indices[i]);
  501. }
  502. void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill,
  503. SmallVectorImpl<SlotIndex> *EndPoints) {
  504. LiveQueryResult LRQ = LR.Query(Kill);
  505. VNInfo *VNI = LRQ.valueOutOrDead();
  506. if (!VNI)
  507. return;
  508. MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
  509. SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
  510. // If VNI isn't live out from KillMBB, the value is trivially pruned.
  511. if (LRQ.endPoint() < MBBEnd) {
  512. LR.removeSegment(Kill, LRQ.endPoint());
  513. if (EndPoints) EndPoints->push_back(LRQ.endPoint());
  514. return;
  515. }
  516. // VNI is live out of KillMBB.
  517. LR.removeSegment(Kill, MBBEnd);
  518. if (EndPoints) EndPoints->push_back(MBBEnd);
  519. // Find all blocks that are reachable from KillMBB without leaving VNI's live
  520. // range. It is possible that KillMBB itself is reachable, so start a DFS
  521. // from each successor.
  522. typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
  523. VisitedTy Visited;
  524. for (MachineBasicBlock::succ_iterator
  525. SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
  526. SuccI != SuccE; ++SuccI) {
  527. for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
  528. I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
  529. I != E;) {
  530. MachineBasicBlock *MBB = *I;
  531. // Check if VNI is live in to MBB.
  532. SlotIndex MBBStart, MBBEnd;
  533. std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
  534. LiveQueryResult LRQ = LR.Query(MBBStart);
  535. if (LRQ.valueIn() != VNI) {
  536. // This block isn't part of the VNI segment. Prune the search.
  537. I.skipChildren();
  538. continue;
  539. }
  540. // Prune the search if VNI is killed in MBB.
  541. if (LRQ.endPoint() < MBBEnd) {
  542. LR.removeSegment(MBBStart, LRQ.endPoint());
  543. if (EndPoints) EndPoints->push_back(LRQ.endPoint());
  544. I.skipChildren();
  545. continue;
  546. }
  547. // VNI is live through MBB.
  548. LR.removeSegment(MBBStart, MBBEnd);
  549. if (EndPoints) EndPoints->push_back(MBBEnd);
  550. ++I;
  551. }
  552. }
  553. }
  554. //===----------------------------------------------------------------------===//
  555. // Register allocator hooks.
  556. //
  557. void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
  558. // Keep track of regunit ranges.
  559. SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU;
  560. // Keep track of subregister ranges.
  561. SmallVector<std::pair<const LiveInterval::SubRange*,
  562. LiveRange::const_iterator>, 4> SRs;
  563. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  564. unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  565. if (MRI->reg_nodbg_empty(Reg))
  566. continue;
  567. const LiveInterval &LI = getInterval(Reg);
  568. if (LI.empty())
  569. continue;
  570. // Find the regunit intervals for the assigned register. They may overlap
  571. // the virtual register live range, cancelling any kills.
  572. RU.clear();
  573. for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
  574. ++Units) {
  575. const LiveRange &RURange = getRegUnit(*Units);
  576. if (RURange.empty())
  577. continue;
  578. RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
  579. }
  580. if (MRI->subRegLivenessEnabled()) {
  581. SRs.clear();
  582. for (const LiveInterval::SubRange &SR : LI.subranges()) {
  583. SRs.push_back(std::make_pair(&SR, SR.find(LI.begin()->end)));
  584. }
  585. }
  586. // Every instruction that kills Reg corresponds to a segment range end
  587. // point.
  588. for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
  589. ++RI) {
  590. // A block index indicates an MBB edge.
  591. if (RI->end.isBlock())
  592. continue;
  593. MachineInstr *MI = getInstructionFromIndex(RI->end);
  594. if (!MI)
  595. continue;
  596. // Check if any of the regunits are live beyond the end of RI. That could
  597. // happen when a physreg is defined as a copy of a virtreg:
  598. //
  599. // %EAX = COPY %vreg5
  600. // FOO %vreg5 <--- MI, cancel kill because %EAX is live.
  601. // BAR %EAX<kill>
  602. //
  603. // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
  604. for (auto &RUP : RU) {
  605. const LiveRange &RURange = *RUP.first;
  606. LiveRange::const_iterator &I = RUP.second;
  607. if (I == RURange.end())
  608. continue;
  609. I = RURange.advanceTo(I, RI->end);
  610. if (I == RURange.end() || I->start >= RI->end)
  611. continue;
  612. // I is overlapping RI.
  613. goto CancelKill;
  614. }
  615. if (MRI->subRegLivenessEnabled()) {
  616. // When reading a partial undefined value we must not add a kill flag.
  617. // The regalloc might have used the undef lane for something else.
  618. // Example:
  619. // %vreg1 = ... ; R32: %vreg1
  620. // %vreg2:high16 = ... ; R64: %vreg2
  621. // = read %vreg2<kill> ; R64: %vreg2
  622. // = read %vreg1 ; R32: %vreg1
  623. // The <kill> flag is correct for %vreg2, but the register allocator may
  624. // assign R0L to %vreg1, and R0 to %vreg2 because the low 32bits of R0
  625. // are actually never written by %vreg2. After assignment the <kill>
  626. // flag at the read instruction is invalid.
  627. unsigned DefinedLanesMask;
  628. if (!SRs.empty()) {
  629. // Compute a mask of lanes that are defined.
  630. DefinedLanesMask = 0;
  631. for (auto &SRP : SRs) {
  632. const LiveInterval::SubRange &SR = *SRP.first;
  633. LiveRange::const_iterator &I = SRP.second;
  634. if (I == SR.end())
  635. continue;
  636. I = SR.advanceTo(I, RI->end);
  637. if (I == SR.end() || I->start >= RI->end)
  638. continue;
  639. // I is overlapping RI
  640. DefinedLanesMask |= SR.LaneMask;
  641. }
  642. } else
  643. DefinedLanesMask = ~0u;
  644. bool IsFullWrite = false;
  645. for (const MachineOperand &MO : MI->operands()) {
  646. if (!MO.isReg() || MO.getReg() != Reg)
  647. continue;
  648. if (MO.isUse()) {
  649. // Reading any undefined lanes?
  650. unsigned UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
  651. if ((UseMask & ~DefinedLanesMask) != 0)
  652. goto CancelKill;
  653. } else if (MO.getSubReg() == 0) {
  654. // Writing to the full register?
  655. assert(MO.isDef());
  656. IsFullWrite = true;
  657. }
  658. }
  659. // If an instruction writes to a subregister, a new segment starts in
  660. // the LiveInterval. But as this is only overriding part of the register
  661. // adding kill-flags is not correct here after registers have been
  662. // assigned.
  663. if (!IsFullWrite) {
  664. // Next segment has to be adjacent in the subregister write case.
  665. LiveRange::const_iterator N = std::next(RI);
  666. if (N != LI.end() && N->start == RI->end)
  667. goto CancelKill;
  668. }
  669. }
  670. MI->addRegisterKilled(Reg, nullptr);
  671. continue;
  672. CancelKill:
  673. MI->clearRegisterKills(Reg, nullptr);
  674. }
  675. }
  676. }
  677. MachineBasicBlock*
  678. LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
  679. // A local live range must be fully contained inside the block, meaning it is
  680. // defined and killed at instructions, not at block boundaries. It is not
  681. // live in or or out of any block.
  682. //
  683. // It is technically possible to have a PHI-defined live range identical to a
  684. // single block, but we are going to return false in that case.
  685. SlotIndex Start = LI.beginIndex();
  686. if (Start.isBlock())
  687. return nullptr;
  688. SlotIndex Stop = LI.endIndex();
  689. if (Stop.isBlock())
  690. return nullptr;
  691. // getMBBFromIndex doesn't need to search the MBB table when both indexes
  692. // belong to proper instructions.
  693. MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
  694. MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
  695. return MBB1 == MBB2 ? MBB1 : nullptr;
  696. }
  697. bool
  698. LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
  699. for (const VNInfo *PHI : LI.valnos) {
  700. if (PHI->isUnused() || !PHI->isPHIDef())
  701. continue;
  702. const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
  703. // Conservatively return true instead of scanning huge predecessor lists.
  704. if (PHIMBB->pred_size() > 100)
  705. return true;
  706. for (MachineBasicBlock::const_pred_iterator
  707. PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
  708. if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
  709. return true;
  710. }
  711. return false;
  712. }
  713. float
  714. LiveIntervals::getSpillWeight(bool isDef, bool isUse,
  715. const MachineBlockFrequencyInfo *MBFI,
  716. const MachineInstr *MI) {
  717. BlockFrequency Freq = MBFI->getBlockFreq(MI->getParent());
  718. const float Scale = 1.0f / MBFI->getEntryFreq();
  719. return (isDef + isUse) * (Freq.getFrequency() * Scale);
  720. }
  721. LiveRange::Segment
  722. LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr* startInst) {
  723. LiveInterval& Interval = createEmptyInterval(reg);
  724. VNInfo* VN = Interval.getNextValue(
  725. SlotIndex(getInstructionIndex(startInst).getRegSlot()),
  726. getVNInfoAllocator());
  727. LiveRange::Segment S(
  728. SlotIndex(getInstructionIndex(startInst).getRegSlot()),
  729. getMBBEndIdx(startInst->getParent()), VN);
  730. Interval.addSegment(S);
  731. return S;
  732. }
  733. //===----------------------------------------------------------------------===//
  734. // Register mask functions
  735. //===----------------------------------------------------------------------===//
  736. bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
  737. BitVector &UsableRegs) {
  738. if (LI.empty())
  739. return false;
  740. LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
  741. // Use a smaller arrays for local live ranges.
  742. ArrayRef<SlotIndex> Slots;
  743. ArrayRef<const uint32_t*> Bits;
  744. if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
  745. Slots = getRegMaskSlotsInBlock(MBB->getNumber());
  746. Bits = getRegMaskBitsInBlock(MBB->getNumber());
  747. } else {
  748. Slots = getRegMaskSlots();
  749. Bits = getRegMaskBits();
  750. }
  751. // We are going to enumerate all the register mask slots contained in LI.
  752. // Start with a binary search of RegMaskSlots to find a starting point.
  753. ArrayRef<SlotIndex>::iterator SlotI =
  754. std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
  755. ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
  756. // No slots in range, LI begins after the last call.
  757. if (SlotI == SlotE)
  758. return false;
  759. bool Found = false;
  760. for (;;) {
  761. assert(*SlotI >= LiveI->start);
  762. // Loop over all slots overlapping this segment.
  763. while (*SlotI < LiveI->end) {
  764. // *SlotI overlaps LI. Collect mask bits.
  765. if (!Found) {
  766. // This is the first overlap. Initialize UsableRegs to all ones.
  767. UsableRegs.clear();
  768. UsableRegs.resize(TRI->getNumRegs(), true);
  769. Found = true;
  770. }
  771. // Remove usable registers clobbered by this mask.
  772. UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
  773. if (++SlotI == SlotE)
  774. return Found;
  775. }
  776. // *SlotI is beyond the current LI segment.
  777. LiveI = LI.advanceTo(LiveI, *SlotI);
  778. if (LiveI == LiveE)
  779. return Found;
  780. // Advance SlotI until it overlaps.
  781. while (*SlotI < LiveI->start)
  782. if (++SlotI == SlotE)
  783. return Found;
  784. }
  785. }
  786. //===----------------------------------------------------------------------===//
  787. // IntervalUpdate class.
  788. //===----------------------------------------------------------------------===//
  789. // HMEditor is a toolkit used by handleMove to trim or extend live intervals.
  790. class LiveIntervals::HMEditor {
  791. private:
  792. LiveIntervals& LIS;
  793. const MachineRegisterInfo& MRI;
  794. const TargetRegisterInfo& TRI;
  795. SlotIndex OldIdx;
  796. SlotIndex NewIdx;
  797. SmallPtrSet<LiveRange*, 8> Updated;
  798. bool UpdateFlags;
  799. public:
  800. HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
  801. const TargetRegisterInfo& TRI,
  802. SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
  803. : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
  804. UpdateFlags(UpdateFlags) {}
  805. // FIXME: UpdateFlags is a workaround that creates live intervals for all
  806. // physregs, even those that aren't needed for regalloc, in order to update
  807. // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
  808. // flags, and postRA passes will use a live register utility instead.
  809. LiveRange *getRegUnitLI(unsigned Unit) {
  810. if (UpdateFlags)
  811. return &LIS.getRegUnit(Unit);
  812. return LIS.getCachedRegUnit(Unit);
  813. }
  814. /// Update all live ranges touched by MI, assuming a move from OldIdx to
  815. /// NewIdx.
  816. void updateAllRanges(MachineInstr *MI) {
  817. DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
  818. bool hasRegMask = false;
  819. for (MachineOperand &MO : MI->operands()) {
  820. if (MO.isRegMask())
  821. hasRegMask = true;
  822. if (!MO.isReg())
  823. continue;
  824. // Aggressively clear all kill flags.
  825. // They are reinserted by VirtRegRewriter.
  826. if (MO.isUse())
  827. MO.setIsKill(false);
  828. unsigned Reg = MO.getReg();
  829. if (!Reg)
  830. continue;
  831. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  832. LiveInterval &LI = LIS.getInterval(Reg);
  833. if (LI.hasSubRanges()) {
  834. unsigned SubReg = MO.getSubReg();
  835. unsigned LaneMask = TRI.getSubRegIndexLaneMask(SubReg);
  836. for (LiveInterval::SubRange &S : LI.subranges()) {
  837. if ((S.LaneMask & LaneMask) == 0)
  838. continue;
  839. updateRange(S, Reg, S.LaneMask);
  840. }
  841. }
  842. updateRange(LI, Reg, 0);
  843. continue;
  844. }
  845. // For physregs, only update the regunits that actually have a
  846. // precomputed live range.
  847. for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
  848. if (LiveRange *LR = getRegUnitLI(*Units))
  849. updateRange(*LR, *Units, 0);
  850. }
  851. if (hasRegMask)
  852. updateRegMaskSlots();
  853. }
  854. private:
  855. /// Update a single live range, assuming an instruction has been moved from
  856. /// OldIdx to NewIdx.
  857. void updateRange(LiveRange &LR, unsigned Reg, unsigned LaneMask) {
  858. if (!Updated.insert(&LR).second)
  859. return;
  860. DEBUG({
  861. dbgs() << " ";
  862. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  863. dbgs() << PrintReg(Reg);
  864. if (LaneMask != 0)
  865. dbgs() << format(" L%04X", LaneMask);
  866. } else {
  867. dbgs() << PrintRegUnit(Reg, &TRI);
  868. }
  869. dbgs() << ":\t" << LR << '\n';
  870. });
  871. if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
  872. handleMoveDown(LR);
  873. else
  874. handleMoveUp(LR, Reg, LaneMask);
  875. DEBUG(dbgs() << " -->\t" << LR << '\n');
  876. LR.verify();
  877. }
  878. /// Update LR to reflect an instruction has been moved downwards from OldIdx
  879. /// to NewIdx.
  880. ///
  881. /// 1. Live def at OldIdx:
  882. /// Move def to NewIdx, assert endpoint after NewIdx.
  883. ///
  884. /// 2. Live def at OldIdx, killed at NewIdx:
  885. /// Change to dead def at NewIdx.
  886. /// (Happens when bundling def+kill together).
  887. ///
  888. /// 3. Dead def at OldIdx:
  889. /// Move def to NewIdx, possibly across another live value.
  890. ///
  891. /// 4. Def at OldIdx AND at NewIdx:
  892. /// Remove segment [OldIdx;NewIdx) and value defined at OldIdx.
  893. /// (Happens when bundling multiple defs together).
  894. ///
  895. /// 5. Value read at OldIdx, killed before NewIdx:
  896. /// Extend kill to NewIdx.
  897. ///
  898. void handleMoveDown(LiveRange &LR) {
  899. // First look for a kill at OldIdx.
  900. LiveRange::iterator I = LR.find(OldIdx.getBaseIndex());
  901. LiveRange::iterator E = LR.end();
  902. // Is LR even live at OldIdx?
  903. if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
  904. return;
  905. // Handle a live-in value.
  906. if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
  907. bool isKill = SlotIndex::isSameInstr(OldIdx, I->end);
  908. // If the live-in value already extends to NewIdx, there is nothing to do.
  909. if (!SlotIndex::isEarlierInstr(I->end, NewIdx))
  910. return;
  911. // Aggressively remove all kill flags from the old kill point.
  912. // Kill flags shouldn't be used while live intervals exist, they will be
  913. // reinserted by VirtRegRewriter.
  914. if (MachineInstr *KillMI = LIS.getInstructionFromIndex(I->end))
  915. for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
  916. if (MO->isReg() && MO->isUse())
  917. MO->setIsKill(false);
  918. // Adjust I->end to reach NewIdx. This may temporarily make LR invalid by
  919. // overlapping ranges. Case 5 above.
  920. I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
  921. // If this was a kill, there may also be a def. Otherwise we're done.
  922. if (!isKill)
  923. return;
  924. ++I;
  925. }
  926. // Check for a def at OldIdx.
  927. if (I == E || !SlotIndex::isSameInstr(OldIdx, I->start))
  928. return;
  929. // We have a def at OldIdx.
  930. VNInfo *DefVNI = I->valno;
  931. assert(DefVNI->def == I->start && "Inconsistent def");
  932. DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
  933. // If the defined value extends beyond NewIdx, just move the def down.
  934. // This is case 1 above.
  935. if (SlotIndex::isEarlierInstr(NewIdx, I->end)) {
  936. I->start = DefVNI->def;
  937. return;
  938. }
  939. // The remaining possibilities are now:
  940. // 2. Live def at OldIdx, killed at NewIdx: isSameInstr(I->end, NewIdx).
  941. // 3. Dead def at OldIdx: I->end = OldIdx.getDeadSlot().
  942. // In either case, it is possible that there is an existing def at NewIdx.
  943. assert((I->end == OldIdx.getDeadSlot() ||
  944. SlotIndex::isSameInstr(I->end, NewIdx)) &&
  945. "Cannot move def below kill");
  946. LiveRange::iterator NewI = LR.advanceTo(I, NewIdx.getRegSlot());
  947. if (NewI != E && SlotIndex::isSameInstr(NewI->start, NewIdx)) {
  948. // There is an existing def at NewIdx, case 4 above. The def at OldIdx is
  949. // coalesced into that value.
  950. assert(NewI->valno != DefVNI && "Multiple defs of value?");
  951. LR.removeValNo(DefVNI);
  952. return;
  953. }
  954. // There was no existing def at NewIdx. Turn *I into a dead def at NewIdx.
  955. // If the def at OldIdx was dead, we allow it to be moved across other LR
  956. // values. The new range should be placed immediately before NewI, move any
  957. // intermediate ranges up.
  958. assert(NewI != I && "Inconsistent iterators");
  959. std::copy(std::next(I), NewI, I);
  960. *std::prev(NewI)
  961. = LiveRange::Segment(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
  962. }
  963. /// Update LR to reflect an instruction has been moved upwards from OldIdx
  964. /// to NewIdx.
  965. ///
  966. /// 1. Live def at OldIdx:
  967. /// Hoist def to NewIdx.
  968. ///
  969. /// 2. Dead def at OldIdx:
  970. /// Hoist def+end to NewIdx, possibly move across other values.
  971. ///
  972. /// 3. Dead def at OldIdx AND existing def at NewIdx:
  973. /// Remove value defined at OldIdx, coalescing it with existing value.
  974. ///
  975. /// 4. Live def at OldIdx AND existing def at NewIdx:
  976. /// Remove value defined at NewIdx, hoist OldIdx def to NewIdx.
  977. /// (Happens when bundling multiple defs together).
  978. ///
  979. /// 5. Value killed at OldIdx:
  980. /// Hoist kill to NewIdx, then scan for last kill between NewIdx and
  981. /// OldIdx.
  982. ///
  983. void handleMoveUp(LiveRange &LR, unsigned Reg, unsigned LaneMask) {
  984. // First look for a kill at OldIdx.
  985. LiveRange::iterator I = LR.find(OldIdx.getBaseIndex());
  986. LiveRange::iterator E = LR.end();
  987. // Is LR even live at OldIdx?
  988. if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
  989. return;
  990. // Handle a live-in value.
  991. if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
  992. // If the live-in value isn't killed here, there is nothing to do.
  993. if (!SlotIndex::isSameInstr(OldIdx, I->end))
  994. return;
  995. // Adjust I->end to end at NewIdx. If we are hoisting a kill above
  996. // another use, we need to search for that use. Case 5 above.
  997. I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
  998. ++I;
  999. // If OldIdx also defines a value, there couldn't have been another use.
  1000. if (I == E || !SlotIndex::isSameInstr(I->start, OldIdx)) {
  1001. // No def, search for the new kill.
  1002. // This can never be an early clobber kill since there is no def.
  1003. std::prev(I)->end = findLastUseBefore(Reg, LaneMask).getRegSlot();
  1004. return;
  1005. }
  1006. }
  1007. // Now deal with the def at OldIdx.
  1008. assert(I != E && SlotIndex::isSameInstr(I->start, OldIdx) && "No def?");
  1009. VNInfo *DefVNI = I->valno;
  1010. assert(DefVNI->def == I->start && "Inconsistent def");
  1011. DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
  1012. // Check for an existing def at NewIdx.
  1013. LiveRange::iterator NewI = LR.find(NewIdx.getRegSlot());
  1014. if (SlotIndex::isSameInstr(NewI->start, NewIdx)) {
  1015. assert(NewI->valno != DefVNI && "Same value defined more than once?");
  1016. // There is an existing def at NewIdx.
  1017. if (I->end.isDead()) {
  1018. // Case 3: Remove the dead def at OldIdx.
  1019. LR.removeValNo(DefVNI);
  1020. return;
  1021. }
  1022. // Case 4: Replace def at NewIdx with live def at OldIdx.
  1023. I->start = DefVNI->def;
  1024. LR.removeValNo(NewI->valno);
  1025. return;
  1026. }
  1027. // There is no existing def at NewIdx. Hoist DefVNI.
  1028. if (!I->end.isDead()) {
  1029. // Leave the end point of a live def.
  1030. I->start = DefVNI->def;
  1031. return;
  1032. }
  1033. // DefVNI is a dead def. It may have been moved across other values in LR,
  1034. // so move I up to NewI. Slide [NewI;I) down one position.
  1035. std::copy_backward(NewI, I, std::next(I));
  1036. *NewI = LiveRange::Segment(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
  1037. }
  1038. void updateRegMaskSlots() {
  1039. SmallVectorImpl<SlotIndex>::iterator RI =
  1040. std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
  1041. OldIdx);
  1042. assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
  1043. "No RegMask at OldIdx.");
  1044. *RI = NewIdx.getRegSlot();
  1045. assert((RI == LIS.RegMaskSlots.begin() ||
  1046. SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
  1047. "Cannot move regmask instruction above another call");
  1048. assert((std::next(RI) == LIS.RegMaskSlots.end() ||
  1049. SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
  1050. "Cannot move regmask instruction below another call");
  1051. }
  1052. // Return the last use of reg between NewIdx and OldIdx.
  1053. SlotIndex findLastUseBefore(unsigned Reg, unsigned LaneMask) {
  1054. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  1055. SlotIndex LastUse = NewIdx;
  1056. for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
  1057. unsigned SubReg = MO.getSubReg();
  1058. if (SubReg != 0 && LaneMask != 0
  1059. && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask) == 0)
  1060. continue;
  1061. const MachineInstr *MI = MO.getParent();
  1062. SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
  1063. if (InstSlot > LastUse && InstSlot < OldIdx)
  1064. LastUse = InstSlot;
  1065. }
  1066. return LastUse;
  1067. }
  1068. // This is a regunit interval, so scanning the use list could be very
  1069. // expensive. Scan upwards from OldIdx instead.
  1070. assert(NewIdx < OldIdx && "Expected upwards move");
  1071. SlotIndexes *Indexes = LIS.getSlotIndexes();
  1072. MachineBasicBlock *MBB = Indexes->getMBBFromIndex(NewIdx);
  1073. // OldIdx may not correspond to an instruction any longer, so set MII to
  1074. // point to the next instruction after OldIdx, or MBB->end().
  1075. MachineBasicBlock::iterator MII = MBB->end();
  1076. if (MachineInstr *MI = Indexes->getInstructionFromIndex(
  1077. Indexes->getNextNonNullIndex(OldIdx)))
  1078. if (MI->getParent() == MBB)
  1079. MII = MI;
  1080. MachineBasicBlock::iterator Begin = MBB->begin();
  1081. while (MII != Begin) {
  1082. if ((--MII)->isDebugValue())
  1083. continue;
  1084. SlotIndex Idx = Indexes->getInstructionIndex(MII);
  1085. // Stop searching when NewIdx is reached.
  1086. if (!SlotIndex::isEarlierInstr(NewIdx, Idx))
  1087. return NewIdx;
  1088. // Check if MII uses Reg.
  1089. for (MIBundleOperands MO(MII); MO.isValid(); ++MO)
  1090. if (MO->isReg() &&
  1091. TargetRegisterInfo::isPhysicalRegister(MO->getReg()) &&
  1092. TRI.hasRegUnit(MO->getReg(), Reg))
  1093. return Idx;
  1094. }
  1095. // Didn't reach NewIdx. It must be the first instruction in the block.
  1096. return NewIdx;
  1097. }
  1098. };
  1099. void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
  1100. assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
  1101. SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
  1102. Indexes->removeMachineInstrFromMaps(MI);
  1103. SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
  1104. assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
  1105. OldIndex < getMBBEndIdx(MI->getParent()) &&
  1106. "Cannot handle moves across basic block boundaries.");
  1107. HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
  1108. HME.updateAllRanges(MI);
  1109. }
  1110. void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
  1111. MachineInstr* BundleStart,
  1112. bool UpdateFlags) {
  1113. SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
  1114. SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
  1115. HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
  1116. HME.updateAllRanges(MI);
  1117. }
  1118. void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
  1119. const MachineBasicBlock::iterator End,
  1120. const SlotIndex endIdx,
  1121. LiveRange &LR, const unsigned Reg,
  1122. const unsigned LaneMask) {
  1123. LiveInterval::iterator LII = LR.find(endIdx);
  1124. SlotIndex lastUseIdx;
  1125. if (LII != LR.end() && LII->start < endIdx)
  1126. lastUseIdx = LII->end;
  1127. else
  1128. --LII;
  1129. for (MachineBasicBlock::iterator I = End; I != Begin;) {
  1130. --I;
  1131. MachineInstr *MI = I;
  1132. if (MI->isDebugValue())
  1133. continue;
  1134. SlotIndex instrIdx = getInstructionIndex(MI);
  1135. bool isStartValid = getInstructionFromIndex(LII->start);
  1136. bool isEndValid = getInstructionFromIndex(LII->end);
  1137. // FIXME: This doesn't currently handle early-clobber or multiple removed
  1138. // defs inside of the region to repair.
  1139. for (MachineInstr::mop_iterator OI = MI->operands_begin(),
  1140. OE = MI->operands_end(); OI != OE; ++OI) {
  1141. const MachineOperand &MO = *OI;
  1142. if (!MO.isReg() || MO.getReg() != Reg)
  1143. continue;
  1144. unsigned SubReg = MO.getSubReg();
  1145. unsigned Mask = TRI->getSubRegIndexLaneMask(SubReg);
  1146. if ((Mask & LaneMask) == 0)
  1147. continue;
  1148. if (MO.isDef()) {
  1149. if (!isStartValid) {
  1150. if (LII->end.isDead()) {
  1151. SlotIndex prevStart;
  1152. if (LII != LR.begin())
  1153. prevStart = std::prev(LII)->start;
  1154. // FIXME: This could be more efficient if there was a
  1155. // removeSegment method that returned an iterator.
  1156. LR.removeSegment(*LII, true);
  1157. if (prevStart.isValid())
  1158. LII = LR.find(prevStart);
  1159. else
  1160. LII = LR.begin();
  1161. } else {
  1162. LII->start = instrIdx.getRegSlot();
  1163. LII->valno->def = instrIdx.getRegSlot();
  1164. if (MO.getSubReg() && !MO.isUndef())
  1165. lastUseIdx = instrIdx.getRegSlot();
  1166. else
  1167. lastUseIdx = SlotIndex();
  1168. continue;
  1169. }
  1170. }
  1171. if (!lastUseIdx.isValid()) {
  1172. VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
  1173. LiveRange::Segment S(instrIdx.getRegSlot(),
  1174. instrIdx.getDeadSlot(), VNI);
  1175. LII = LR.addSegment(S);
  1176. } else if (LII->start != instrIdx.getRegSlot()) {
  1177. VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
  1178. LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
  1179. LII = LR.addSegment(S);
  1180. }
  1181. if (MO.getSubReg() && !MO.isUndef())
  1182. lastUseIdx = instrIdx.getRegSlot();
  1183. else
  1184. lastUseIdx = SlotIndex();
  1185. } else if (MO.isUse()) {
  1186. // FIXME: This should probably be handled outside of this branch,
  1187. // either as part of the def case (for defs inside of the region) or
  1188. // after the loop over the region.
  1189. if (!isEndValid && !LII->end.isBlock())
  1190. LII->end = instrIdx.getRegSlot();
  1191. if (!lastUseIdx.isValid())
  1192. lastUseIdx = instrIdx.getRegSlot();
  1193. }
  1194. }
  1195. }
  1196. }
  1197. void
  1198. LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
  1199. MachineBasicBlock::iterator Begin,
  1200. MachineBasicBlock::iterator End,
  1201. ArrayRef<unsigned> OrigRegs) {
  1202. // Find anchor points, which are at the beginning/end of blocks or at
  1203. // instructions that already have indexes.
  1204. while (Begin != MBB->begin() && !Indexes->hasIndex(Begin))
  1205. --Begin;
  1206. while (End != MBB->end() && !Indexes->hasIndex(End))
  1207. ++End;
  1208. SlotIndex endIdx;
  1209. if (End == MBB->end())
  1210. endIdx = getMBBEndIdx(MBB).getPrevSlot();
  1211. else
  1212. endIdx = getInstructionIndex(End);
  1213. Indexes->repairIndexesInRange(MBB, Begin, End);
  1214. for (MachineBasicBlock::iterator I = End; I != Begin;) {
  1215. --I;
  1216. MachineInstr *MI = I;
  1217. if (MI->isDebugValue())
  1218. continue;
  1219. for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
  1220. MOE = MI->operands_end(); MOI != MOE; ++MOI) {
  1221. if (MOI->isReg() &&
  1222. TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
  1223. !hasInterval(MOI->getReg())) {
  1224. createAndComputeVirtRegInterval(MOI->getReg());
  1225. }
  1226. }
  1227. }
  1228. for (unsigned i = 0, e = OrigRegs.size(); i != e; ++i) {
  1229. unsigned Reg = OrigRegs[i];
  1230. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  1231. continue;
  1232. LiveInterval &LI = getInterval(Reg);
  1233. // FIXME: Should we support undefs that gain defs?
  1234. if (!LI.hasAtLeastOneValue())
  1235. continue;
  1236. for (LiveInterval::SubRange &S : LI.subranges()) {
  1237. repairOldRegInRange(Begin, End, endIdx, S, Reg, S.LaneMask);
  1238. }
  1239. repairOldRegInRange(Begin, End, endIdx, LI, Reg);
  1240. }
  1241. }
  1242. void LiveIntervals::removePhysRegDefAt(unsigned Reg, SlotIndex Pos) {
  1243. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
  1244. if (LiveRange *LR = getCachedRegUnit(*Units))
  1245. if (VNInfo *VNI = LR->getVNInfoAt(Pos))
  1246. LR->removeValNo(VNI);
  1247. }
  1248. }
  1249. void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) {
  1250. VNInfo *VNI = LI.getVNInfoAt(Pos);
  1251. if (VNI == nullptr)
  1252. return;
  1253. LI.removeValNo(VNI);
  1254. // Also remove the value in subranges.
  1255. for (LiveInterval::SubRange &S : LI.subranges()) {
  1256. if (VNInfo *SVNI = S.getVNInfoAt(Pos))
  1257. S.removeValNo(SVNI);
  1258. }
  1259. LI.removeEmptySubRanges();
  1260. }