LiveVariables.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
  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. // This file implements the LiveVariable analysis pass. For each machine
  10. // instruction in the function, this pass calculates the set of registers that
  11. // are immediately dead after the instruction (i.e., the instruction calculates
  12. // the value, but it is never used) and the set of registers that are used by
  13. // the instruction, but are never used after the instruction (i.e., they are
  14. // killed).
  15. //
  16. // This class computes live variables using a sparse implementation based on
  17. // the machine code SSA form. This class computes live variable information for
  18. // each virtual and _register allocatable_ physical register in a function. It
  19. // uses the dominance properties of SSA form to efficiently compute live
  20. // variables for virtual registers, and assumes that physical registers are only
  21. // live within a single basic block (allowing it to do a single local analysis
  22. // to resolve physical register lifetimes in each basic block). If a physical
  23. // register is not register allocatable, it is not tracked. This is useful for
  24. // things like the stack pointer and condition codes.
  25. //
  26. //===----------------------------------------------------------------------===//
  27. #include "llvm/CodeGen/LiveVariables.h"
  28. #include "llvm/ADT/DenseSet.h"
  29. #include "llvm/ADT/DepthFirstIterator.h"
  30. #include "llvm/ADT/STLExtras.h"
  31. #include "llvm/ADT/SmallPtrSet.h"
  32. #include "llvm/ADT/SmallSet.h"
  33. #include "llvm/CodeGen/MachineInstr.h"
  34. #include "llvm/CodeGen/MachineRegisterInfo.h"
  35. #include "llvm/CodeGen/Passes.h"
  36. #include "llvm/Config/llvm-config.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Support/ErrorHandling.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. #include <algorithm>
  41. using namespace llvm;
  42. char LiveVariables::ID = 0;
  43. char &llvm::LiveVariablesID = LiveVariables::ID;
  44. INITIALIZE_PASS_BEGIN(LiveVariables, "livevars",
  45. "Live Variable Analysis", false, false)
  46. INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim)
  47. INITIALIZE_PASS_END(LiveVariables, "livevars",
  48. "Live Variable Analysis", false, false)
  49. void LiveVariables::getAnalysisUsage(AnalysisUsage &AU) const {
  50. AU.addRequiredID(UnreachableMachineBlockElimID);
  51. AU.setPreservesAll();
  52. MachineFunctionPass::getAnalysisUsage(AU);
  53. }
  54. MachineInstr *
  55. LiveVariables::VarInfo::findKill(const MachineBasicBlock *MBB) const {
  56. for (MachineInstr *MI : Kills)
  57. if (MI->getParent() == MBB)
  58. return MI;
  59. return nullptr;
  60. }
  61. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  62. LLVM_DUMP_METHOD void LiveVariables::VarInfo::dump() const {
  63. dbgs() << " Alive in blocks: ";
  64. for (unsigned AB : AliveBlocks)
  65. dbgs() << AB << ", ";
  66. dbgs() << "\n Killed by:";
  67. if (Kills.empty())
  68. dbgs() << " No instructions.\n";
  69. else {
  70. for (unsigned i = 0, e = Kills.size(); i != e; ++i)
  71. dbgs() << "\n #" << i << ": " << *Kills[i];
  72. dbgs() << "\n";
  73. }
  74. }
  75. #endif
  76. /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
  77. LiveVariables::VarInfo &LiveVariables::getVarInfo(Register Reg) {
  78. assert(Reg.isVirtual() && "getVarInfo: not a virtual register!");
  79. VirtRegInfo.grow(Reg);
  80. return VirtRegInfo[Reg];
  81. }
  82. void LiveVariables::MarkVirtRegAliveInBlock(
  83. VarInfo &VRInfo, MachineBasicBlock *DefBlock, MachineBasicBlock *MBB,
  84. SmallVectorImpl<MachineBasicBlock *> &WorkList) {
  85. unsigned BBNum = MBB->getNumber();
  86. // Check to see if this basic block is one of the killing blocks. If so,
  87. // remove it.
  88. for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
  89. if (VRInfo.Kills[i]->getParent() == MBB) {
  90. VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
  91. break;
  92. }
  93. if (MBB == DefBlock) return; // Terminate recursion
  94. if (VRInfo.AliveBlocks.test(BBNum))
  95. return; // We already know the block is live
  96. // Mark the variable known alive in this bb
  97. VRInfo.AliveBlocks.set(BBNum);
  98. assert(MBB != &MF->front() && "Can't find reaching def for virtreg");
  99. WorkList.insert(WorkList.end(), MBB->pred_rbegin(), MBB->pred_rend());
  100. }
  101. void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
  102. MachineBasicBlock *DefBlock,
  103. MachineBasicBlock *MBB) {
  104. SmallVector<MachineBasicBlock *, 16> WorkList;
  105. MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
  106. while (!WorkList.empty()) {
  107. MachineBasicBlock *Pred = WorkList.pop_back_val();
  108. MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
  109. }
  110. }
  111. void LiveVariables::HandleVirtRegUse(Register Reg, MachineBasicBlock *MBB,
  112. MachineInstr &MI) {
  113. assert(MRI->getVRegDef(Reg) && "Register use before def!");
  114. unsigned BBNum = MBB->getNumber();
  115. VarInfo &VRInfo = getVarInfo(Reg);
  116. // Check to see if this basic block is already a kill block.
  117. if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
  118. // Yes, this register is killed in this basic block already. Increase the
  119. // live range by updating the kill instruction.
  120. VRInfo.Kills.back() = &MI;
  121. return;
  122. }
  123. #ifndef NDEBUG
  124. for (MachineInstr *Kill : VRInfo.Kills)
  125. assert(Kill->getParent() != MBB && "entry should be at end!");
  126. #endif
  127. // This situation can occur:
  128. //
  129. // ,------.
  130. // | |
  131. // | v
  132. // | t2 = phi ... t1 ...
  133. // | |
  134. // | v
  135. // | t1 = ...
  136. // | ... = ... t1 ...
  137. // | |
  138. // `------'
  139. //
  140. // where there is a use in a PHI node that's a predecessor to the defining
  141. // block. We don't want to mark all predecessors as having the value "alive"
  142. // in this case.
  143. if (MBB == MRI->getVRegDef(Reg)->getParent())
  144. return;
  145. // Add a new kill entry for this basic block. If this virtual register is
  146. // already marked as alive in this basic block, that means it is alive in at
  147. // least one of the successor blocks, it's not a kill.
  148. if (!VRInfo.AliveBlocks.test(BBNum))
  149. VRInfo.Kills.push_back(&MI);
  150. // Update all dominating blocks to mark them as "known live".
  151. for (MachineBasicBlock *Pred : MBB->predecessors())
  152. MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(Reg)->getParent(), Pred);
  153. }
  154. void LiveVariables::HandleVirtRegDef(Register Reg, MachineInstr &MI) {
  155. VarInfo &VRInfo = getVarInfo(Reg);
  156. if (VRInfo.AliveBlocks.empty())
  157. // If vr is not alive in any block, then defaults to dead.
  158. VRInfo.Kills.push_back(&MI);
  159. }
  160. /// FindLastPartialDef - Return the last partial def of the specified register.
  161. /// Also returns the sub-registers that're defined by the instruction.
  162. MachineInstr *
  163. LiveVariables::FindLastPartialDef(Register Reg,
  164. SmallSet<unsigned, 4> &PartDefRegs) {
  165. unsigned LastDefReg = 0;
  166. unsigned LastDefDist = 0;
  167. MachineInstr *LastDef = nullptr;
  168. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  169. unsigned SubReg = *SubRegs;
  170. MachineInstr *Def = PhysRegDef[SubReg];
  171. if (!Def)
  172. continue;
  173. unsigned Dist = DistanceMap[Def];
  174. if (Dist > LastDefDist) {
  175. LastDefReg = SubReg;
  176. LastDef = Def;
  177. LastDefDist = Dist;
  178. }
  179. }
  180. if (!LastDef)
  181. return nullptr;
  182. PartDefRegs.insert(LastDefReg);
  183. for (unsigned i = 0, e = LastDef->getNumOperands(); i != e; ++i) {
  184. MachineOperand &MO = LastDef->getOperand(i);
  185. if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
  186. continue;
  187. Register DefReg = MO.getReg();
  188. if (TRI->isSubRegister(Reg, DefReg)) {
  189. for (MCSubRegIterator SubRegs(DefReg, TRI, /*IncludeSelf=*/true);
  190. SubRegs.isValid(); ++SubRegs)
  191. PartDefRegs.insert(*SubRegs);
  192. }
  193. }
  194. return LastDef;
  195. }
  196. /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
  197. /// implicit defs to a machine instruction if there was an earlier def of its
  198. /// super-register.
  199. void LiveVariables::HandlePhysRegUse(Register Reg, MachineInstr &MI) {
  200. MachineInstr *LastDef = PhysRegDef[Reg];
  201. // If there was a previous use or a "full" def all is well.
  202. if (!LastDef && !PhysRegUse[Reg]) {
  203. // Otherwise, the last sub-register def implicitly defines this register.
  204. // e.g.
  205. // AH =
  206. // AL = ... implicit-def EAX, implicit killed AH
  207. // = AH
  208. // ...
  209. // = EAX
  210. // All of the sub-registers must have been defined before the use of Reg!
  211. SmallSet<unsigned, 4> PartDefRegs;
  212. MachineInstr *LastPartialDef = FindLastPartialDef(Reg, PartDefRegs);
  213. // If LastPartialDef is NULL, it must be using a livein register.
  214. if (LastPartialDef) {
  215. LastPartialDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
  216. true/*IsImp*/));
  217. PhysRegDef[Reg] = LastPartialDef;
  218. SmallSet<unsigned, 8> Processed;
  219. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  220. unsigned SubReg = *SubRegs;
  221. if (Processed.count(SubReg))
  222. continue;
  223. if (PartDefRegs.count(SubReg))
  224. continue;
  225. // This part of Reg was defined before the last partial def. It's killed
  226. // here.
  227. LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg,
  228. false/*IsDef*/,
  229. true/*IsImp*/));
  230. PhysRegDef[SubReg] = LastPartialDef;
  231. for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
  232. Processed.insert(*SS);
  233. }
  234. }
  235. } else if (LastDef && !PhysRegUse[Reg] &&
  236. !LastDef->findRegisterDefOperand(Reg))
  237. // Last def defines the super register, add an implicit def of reg.
  238. LastDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
  239. true/*IsImp*/));
  240. // Remember this use.
  241. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  242. SubRegs.isValid(); ++SubRegs)
  243. PhysRegUse[*SubRegs] = &MI;
  244. }
  245. /// FindLastRefOrPartRef - Return the last reference or partial reference of
  246. /// the specified register.
  247. MachineInstr *LiveVariables::FindLastRefOrPartRef(Register Reg) {
  248. MachineInstr *LastDef = PhysRegDef[Reg];
  249. MachineInstr *LastUse = PhysRegUse[Reg];
  250. if (!LastDef && !LastUse)
  251. return nullptr;
  252. MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
  253. unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
  254. unsigned LastPartDefDist = 0;
  255. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  256. unsigned SubReg = *SubRegs;
  257. MachineInstr *Def = PhysRegDef[SubReg];
  258. if (Def && Def != LastDef) {
  259. // There was a def of this sub-register in between. This is a partial
  260. // def, keep track of the last one.
  261. unsigned Dist = DistanceMap[Def];
  262. if (Dist > LastPartDefDist)
  263. LastPartDefDist = Dist;
  264. } else if (MachineInstr *Use = PhysRegUse[SubReg]) {
  265. unsigned Dist = DistanceMap[Use];
  266. if (Dist > LastRefOrPartRefDist) {
  267. LastRefOrPartRefDist = Dist;
  268. LastRefOrPartRef = Use;
  269. }
  270. }
  271. }
  272. return LastRefOrPartRef;
  273. }
  274. bool LiveVariables::HandlePhysRegKill(Register Reg, MachineInstr *MI) {
  275. MachineInstr *LastDef = PhysRegDef[Reg];
  276. MachineInstr *LastUse = PhysRegUse[Reg];
  277. if (!LastDef && !LastUse)
  278. return false;
  279. MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
  280. unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
  281. // The whole register is used.
  282. // AL =
  283. // AH =
  284. //
  285. // = AX
  286. // = AL, implicit killed AX
  287. // AX =
  288. //
  289. // Or whole register is defined, but not used at all.
  290. // dead AX =
  291. // ...
  292. // AX =
  293. //
  294. // Or whole register is defined, but only partly used.
  295. // dead AX = implicit-def AL
  296. // = killed AL
  297. // AX =
  298. MachineInstr *LastPartDef = nullptr;
  299. unsigned LastPartDefDist = 0;
  300. SmallSet<unsigned, 8> PartUses;
  301. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  302. unsigned SubReg = *SubRegs;
  303. MachineInstr *Def = PhysRegDef[SubReg];
  304. if (Def && Def != LastDef) {
  305. // There was a def of this sub-register in between. This is a partial
  306. // def, keep track of the last one.
  307. unsigned Dist = DistanceMap[Def];
  308. if (Dist > LastPartDefDist) {
  309. LastPartDefDist = Dist;
  310. LastPartDef = Def;
  311. }
  312. continue;
  313. }
  314. if (MachineInstr *Use = PhysRegUse[SubReg]) {
  315. for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true); SS.isValid();
  316. ++SS)
  317. PartUses.insert(*SS);
  318. unsigned Dist = DistanceMap[Use];
  319. if (Dist > LastRefOrPartRefDist) {
  320. LastRefOrPartRefDist = Dist;
  321. LastRefOrPartRef = Use;
  322. }
  323. }
  324. }
  325. if (!PhysRegUse[Reg]) {
  326. // Partial uses. Mark register def dead and add implicit def of
  327. // sub-registers which are used.
  328. // dead EAX = op implicit-def AL
  329. // That is, EAX def is dead but AL def extends pass it.
  330. PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true);
  331. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  332. unsigned SubReg = *SubRegs;
  333. if (!PartUses.count(SubReg))
  334. continue;
  335. bool NeedDef = true;
  336. if (PhysRegDef[Reg] == PhysRegDef[SubReg]) {
  337. MachineOperand *MO = PhysRegDef[Reg]->findRegisterDefOperand(SubReg);
  338. if (MO) {
  339. NeedDef = false;
  340. assert(!MO->isDead());
  341. }
  342. }
  343. if (NeedDef)
  344. PhysRegDef[Reg]->addOperand(MachineOperand::CreateReg(SubReg,
  345. true/*IsDef*/, true/*IsImp*/));
  346. MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg);
  347. if (LastSubRef)
  348. LastSubRef->addRegisterKilled(SubReg, TRI, true);
  349. else {
  350. LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
  351. for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true);
  352. SS.isValid(); ++SS)
  353. PhysRegUse[*SS] = LastRefOrPartRef;
  354. }
  355. for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
  356. PartUses.erase(*SS);
  357. }
  358. } else if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI) {
  359. if (LastPartDef)
  360. // The last partial def kills the register.
  361. LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
  362. true/*IsImp*/, true/*IsKill*/));
  363. else {
  364. MachineOperand *MO =
  365. LastRefOrPartRef->findRegisterDefOperand(Reg, false, false, TRI);
  366. bool NeedEC = MO->isEarlyClobber() && MO->getReg() != Reg;
  367. // If the last reference is the last def, then it's not used at all.
  368. // That is, unless we are currently processing the last reference itself.
  369. LastRefOrPartRef->addRegisterDead(Reg, TRI, true);
  370. if (NeedEC) {
  371. // If we are adding a subreg def and the superreg def is marked early
  372. // clobber, add an early clobber marker to the subreg def.
  373. MO = LastRefOrPartRef->findRegisterDefOperand(Reg);
  374. if (MO)
  375. MO->setIsEarlyClobber();
  376. }
  377. }
  378. } else
  379. LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
  380. return true;
  381. }
  382. void LiveVariables::HandleRegMask(const MachineOperand &MO) {
  383. // Call HandlePhysRegKill() for all live registers clobbered by Mask.
  384. // Clobbered registers are always dead, sp there is no need to use
  385. // HandlePhysRegDef().
  386. for (unsigned Reg = 1, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg) {
  387. // Skip dead regs.
  388. if (!PhysRegDef[Reg] && !PhysRegUse[Reg])
  389. continue;
  390. // Skip mask-preserved regs.
  391. if (!MO.clobbersPhysReg(Reg))
  392. continue;
  393. // Kill the largest clobbered super-register.
  394. // This avoids needless implicit operands.
  395. unsigned Super = Reg;
  396. for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
  397. if ((PhysRegDef[*SR] || PhysRegUse[*SR]) && MO.clobbersPhysReg(*SR))
  398. Super = *SR;
  399. HandlePhysRegKill(Super, nullptr);
  400. }
  401. }
  402. void LiveVariables::HandlePhysRegDef(Register Reg, MachineInstr *MI,
  403. SmallVectorImpl<unsigned> &Defs) {
  404. // What parts of the register are previously defined?
  405. SmallSet<unsigned, 32> Live;
  406. if (PhysRegDef[Reg] || PhysRegUse[Reg]) {
  407. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  408. SubRegs.isValid(); ++SubRegs)
  409. Live.insert(*SubRegs);
  410. } else {
  411. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  412. unsigned SubReg = *SubRegs;
  413. // If a register isn't itself defined, but all parts that make up of it
  414. // are defined, then consider it also defined.
  415. // e.g.
  416. // AL =
  417. // AH =
  418. // = AX
  419. if (Live.count(SubReg))
  420. continue;
  421. if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
  422. for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true);
  423. SS.isValid(); ++SS)
  424. Live.insert(*SS);
  425. }
  426. }
  427. }
  428. // Start from the largest piece, find the last time any part of the register
  429. // is referenced.
  430. HandlePhysRegKill(Reg, MI);
  431. // Only some of the sub-registers are used.
  432. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  433. unsigned SubReg = *SubRegs;
  434. if (!Live.count(SubReg))
  435. // Skip if this sub-register isn't defined.
  436. continue;
  437. HandlePhysRegKill(SubReg, MI);
  438. }
  439. if (MI)
  440. Defs.push_back(Reg); // Remember this def.
  441. }
  442. void LiveVariables::UpdatePhysRegDefs(MachineInstr &MI,
  443. SmallVectorImpl<unsigned> &Defs) {
  444. while (!Defs.empty()) {
  445. Register Reg = Defs.pop_back_val();
  446. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  447. SubRegs.isValid(); ++SubRegs) {
  448. unsigned SubReg = *SubRegs;
  449. PhysRegDef[SubReg] = &MI;
  450. PhysRegUse[SubReg] = nullptr;
  451. }
  452. }
  453. }
  454. void LiveVariables::runOnInstr(MachineInstr &MI,
  455. SmallVectorImpl<unsigned> &Defs) {
  456. assert(!MI.isDebugOrPseudoInstr());
  457. // Process all of the operands of the instruction...
  458. unsigned NumOperandsToProcess = MI.getNumOperands();
  459. // Unless it is a PHI node. In this case, ONLY process the DEF, not any
  460. // of the uses. They will be handled in other basic blocks.
  461. if (MI.isPHI())
  462. NumOperandsToProcess = 1;
  463. // Clear kill and dead markers. LV will recompute them.
  464. SmallVector<unsigned, 4> UseRegs;
  465. SmallVector<unsigned, 4> DefRegs;
  466. SmallVector<unsigned, 1> RegMasks;
  467. for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
  468. MachineOperand &MO = MI.getOperand(i);
  469. if (MO.isRegMask()) {
  470. RegMasks.push_back(i);
  471. continue;
  472. }
  473. if (!MO.isReg() || MO.getReg() == 0)
  474. continue;
  475. Register MOReg = MO.getReg();
  476. if (MO.isUse()) {
  477. if (!(Register::isPhysicalRegister(MOReg) && MRI->isReserved(MOReg)))
  478. MO.setIsKill(false);
  479. if (MO.readsReg())
  480. UseRegs.push_back(MOReg);
  481. } else {
  482. assert(MO.isDef());
  483. // FIXME: We should not remove any dead flags. However the MIPS RDDSP
  484. // instruction needs it at the moment: http://llvm.org/PR27116.
  485. if (Register::isPhysicalRegister(MOReg) && !MRI->isReserved(MOReg))
  486. MO.setIsDead(false);
  487. DefRegs.push_back(MOReg);
  488. }
  489. }
  490. MachineBasicBlock *MBB = MI.getParent();
  491. // Process all uses.
  492. for (unsigned MOReg : UseRegs) {
  493. if (Register::isVirtualRegister(MOReg))
  494. HandleVirtRegUse(MOReg, MBB, MI);
  495. else if (!MRI->isReserved(MOReg))
  496. HandlePhysRegUse(MOReg, MI);
  497. }
  498. // Process all masked registers. (Call clobbers).
  499. for (unsigned Mask : RegMasks)
  500. HandleRegMask(MI.getOperand(Mask));
  501. // Process all defs.
  502. for (unsigned MOReg : DefRegs) {
  503. if (Register::isVirtualRegister(MOReg))
  504. HandleVirtRegDef(MOReg, MI);
  505. else if (!MRI->isReserved(MOReg))
  506. HandlePhysRegDef(MOReg, &MI, Defs);
  507. }
  508. UpdatePhysRegDefs(MI, Defs);
  509. }
  510. void LiveVariables::runOnBlock(MachineBasicBlock *MBB, const unsigned NumRegs) {
  511. // Mark live-in registers as live-in.
  512. SmallVector<unsigned, 4> Defs;
  513. for (const auto &LI : MBB->liveins()) {
  514. assert(Register::isPhysicalRegister(LI.PhysReg) &&
  515. "Cannot have a live-in virtual register!");
  516. HandlePhysRegDef(LI.PhysReg, nullptr, Defs);
  517. }
  518. // Loop over all of the instructions, processing them.
  519. DistanceMap.clear();
  520. unsigned Dist = 0;
  521. for (MachineInstr &MI : *MBB) {
  522. if (MI.isDebugOrPseudoInstr())
  523. continue;
  524. DistanceMap.insert(std::make_pair(&MI, Dist++));
  525. runOnInstr(MI, Defs);
  526. }
  527. // Handle any virtual assignments from PHI nodes which might be at the
  528. // bottom of this basic block. We check all of our successor blocks to see
  529. // if they have PHI nodes, and if so, we simulate an assignment at the end
  530. // of the current block.
  531. if (!PHIVarInfo[MBB->getNumber()].empty()) {
  532. SmallVectorImpl<unsigned> &VarInfoVec = PHIVarInfo[MBB->getNumber()];
  533. for (unsigned I : VarInfoVec)
  534. // Mark it alive only in the block we are representing.
  535. MarkVirtRegAliveInBlock(getVarInfo(I), MRI->getVRegDef(I)->getParent(),
  536. MBB);
  537. }
  538. // MachineCSE may CSE instructions which write to non-allocatable physical
  539. // registers across MBBs. Remember if any reserved register is liveout.
  540. SmallSet<unsigned, 4> LiveOuts;
  541. for (const MachineBasicBlock *SuccMBB : MBB->successors()) {
  542. if (SuccMBB->isEHPad())
  543. continue;
  544. for (const auto &LI : SuccMBB->liveins()) {
  545. if (!TRI->isInAllocatableClass(LI.PhysReg))
  546. // Ignore other live-ins, e.g. those that are live into landing pads.
  547. LiveOuts.insert(LI.PhysReg);
  548. }
  549. }
  550. // Loop over PhysRegDef / PhysRegUse, killing any registers that are
  551. // available at the end of the basic block.
  552. for (unsigned i = 0; i != NumRegs; ++i)
  553. if ((PhysRegDef[i] || PhysRegUse[i]) && !LiveOuts.count(i))
  554. HandlePhysRegDef(i, nullptr, Defs);
  555. }
  556. bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
  557. MF = &mf;
  558. MRI = &mf.getRegInfo();
  559. TRI = MF->getSubtarget().getRegisterInfo();
  560. const unsigned NumRegs = TRI->getNumRegs();
  561. PhysRegDef.assign(NumRegs, nullptr);
  562. PhysRegUse.assign(NumRegs, nullptr);
  563. PHIVarInfo.resize(MF->getNumBlockIDs());
  564. PHIJoins.clear();
  565. // FIXME: LiveIntervals will be updated to remove its dependence on
  566. // LiveVariables to improve compilation time and eliminate bizarre pass
  567. // dependencies. Until then, we can't change much in -O0.
  568. if (!MRI->isSSA())
  569. report_fatal_error("regalloc=... not currently supported with -O0");
  570. analyzePHINodes(mf);
  571. // Calculate live variable information in depth first order on the CFG of the
  572. // function. This guarantees that we will see the definition of a virtual
  573. // register before its uses due to dominance properties of SSA (except for PHI
  574. // nodes, which are treated as a special case).
  575. MachineBasicBlock *Entry = &MF->front();
  576. df_iterator_default_set<MachineBasicBlock*,16> Visited;
  577. for (MachineBasicBlock *MBB : depth_first_ext(Entry, Visited)) {
  578. runOnBlock(MBB, NumRegs);
  579. PhysRegDef.assign(NumRegs, nullptr);
  580. PhysRegUse.assign(NumRegs, nullptr);
  581. }
  582. // Convert and transfer the dead / killed information we have gathered into
  583. // VirtRegInfo onto MI's.
  584. for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i) {
  585. const Register Reg = Register::index2VirtReg(i);
  586. for (unsigned j = 0, e2 = VirtRegInfo[Reg].Kills.size(); j != e2; ++j)
  587. if (VirtRegInfo[Reg].Kills[j] == MRI->getVRegDef(Reg))
  588. VirtRegInfo[Reg].Kills[j]->addRegisterDead(Reg, TRI);
  589. else
  590. VirtRegInfo[Reg].Kills[j]->addRegisterKilled(Reg, TRI);
  591. }
  592. // Check to make sure there are no unreachable blocks in the MC CFG for the
  593. // function. If so, it is due to a bug in the instruction selector or some
  594. // other part of the code generator if this happens.
  595. #ifndef NDEBUG
  596. for (const MachineBasicBlock &MBB : *MF)
  597. assert(Visited.contains(&MBB) && "unreachable basic block found");
  598. #endif
  599. PhysRegDef.clear();
  600. PhysRegUse.clear();
  601. PHIVarInfo.clear();
  602. return false;
  603. }
  604. void LiveVariables::recomputeForSingleDefVirtReg(Register Reg) {
  605. assert(Reg.isVirtual());
  606. VarInfo &VI = getVarInfo(Reg);
  607. VI.AliveBlocks.clear();
  608. VI.Kills.clear();
  609. MachineInstr &DefMI = *MRI->getUniqueVRegDef(Reg);
  610. MachineBasicBlock &DefBB = *DefMI.getParent();
  611. // Handle the case where all uses have been removed.
  612. if (MRI->use_nodbg_empty(Reg)) {
  613. VI.Kills.push_back(&DefMI);
  614. DefMI.addRegisterDead(Reg, nullptr);
  615. return;
  616. }
  617. DefMI.clearRegisterDeads(Reg);
  618. // Initialize a worklist of BBs that Reg is live-to-end of. (Here
  619. // "live-to-end" means Reg is live at the end of a block even if it is only
  620. // live because of phi uses in a successor. This is different from isLiveOut()
  621. // which does not consider phi uses.)
  622. SmallVector<MachineBasicBlock *> LiveToEndBlocks;
  623. SparseBitVector<> UseBlocks;
  624. for (auto &UseMO : MRI->use_nodbg_operands(Reg)) {
  625. UseMO.setIsKill(false);
  626. MachineInstr &UseMI = *UseMO.getParent();
  627. MachineBasicBlock &UseBB = *UseMI.getParent();
  628. UseBlocks.set(UseBB.getNumber());
  629. if (UseMI.isPHI()) {
  630. // If Reg is used in a phi then it is live-to-end of the corresponding
  631. // predecessor.
  632. unsigned Idx = UseMI.getOperandNo(&UseMO);
  633. LiveToEndBlocks.push_back(UseMI.getOperand(Idx + 1).getMBB());
  634. } else if (&UseBB == &DefBB) {
  635. // A non-phi use in the same BB as the single def must come after the def.
  636. } else {
  637. // Otherwise Reg must be live-to-end of all predecessors.
  638. LiveToEndBlocks.append(UseBB.pred_begin(), UseBB.pred_end());
  639. }
  640. }
  641. // Iterate over the worklist adding blocks to AliveBlocks.
  642. bool LiveToEndOfDefBB = false;
  643. while (!LiveToEndBlocks.empty()) {
  644. MachineBasicBlock &BB = *LiveToEndBlocks.pop_back_val();
  645. if (&BB == &DefBB) {
  646. LiveToEndOfDefBB = true;
  647. continue;
  648. }
  649. if (VI.AliveBlocks.test(BB.getNumber()))
  650. continue;
  651. VI.AliveBlocks.set(BB.getNumber());
  652. LiveToEndBlocks.append(BB.pred_begin(), BB.pred_end());
  653. }
  654. // Recompute kill flags. For each block in which Reg is used but is not
  655. // live-through, find the last instruction that uses Reg. Ignore phi nodes
  656. // because they should not be included in Kills.
  657. for (unsigned UseBBNum : UseBlocks) {
  658. if (VI.AliveBlocks.test(UseBBNum))
  659. continue;
  660. MachineBasicBlock &UseBB = *MF->getBlockNumbered(UseBBNum);
  661. if (&UseBB == &DefBB && LiveToEndOfDefBB)
  662. continue;
  663. for (auto &MI : reverse(UseBB)) {
  664. if (MI.isDebugOrPseudoInstr())
  665. continue;
  666. if (MI.isPHI())
  667. break;
  668. if (MI.readsRegister(Reg)) {
  669. assert(!MI.killsRegister(Reg));
  670. MI.addRegisterKilled(Reg, nullptr);
  671. VI.Kills.push_back(&MI);
  672. break;
  673. }
  674. }
  675. }
  676. }
  677. /// replaceKillInstruction - Update register kill info by replacing a kill
  678. /// instruction with a new one.
  679. void LiveVariables::replaceKillInstruction(Register Reg, MachineInstr &OldMI,
  680. MachineInstr &NewMI) {
  681. VarInfo &VI = getVarInfo(Reg);
  682. std::replace(VI.Kills.begin(), VI.Kills.end(), &OldMI, &NewMI);
  683. }
  684. /// removeVirtualRegistersKilled - Remove all killed info for the specified
  685. /// instruction.
  686. void LiveVariables::removeVirtualRegistersKilled(MachineInstr &MI) {
  687. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  688. MachineOperand &MO = MI.getOperand(i);
  689. if (MO.isReg() && MO.isKill()) {
  690. MO.setIsKill(false);
  691. Register Reg = MO.getReg();
  692. if (Register::isVirtualRegister(Reg)) {
  693. bool removed = getVarInfo(Reg).removeKill(MI);
  694. assert(removed && "kill not in register's VarInfo?");
  695. (void)removed;
  696. }
  697. }
  698. }
  699. }
  700. /// analyzePHINodes - Gather information about the PHI nodes in here. In
  701. /// particular, we want to map the variable information of a virtual register
  702. /// which is used in a PHI node. We map that to the BB the vreg is coming from.
  703. ///
  704. void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
  705. for (const auto &MBB : Fn)
  706. for (const auto &BBI : MBB) {
  707. if (!BBI.isPHI())
  708. break;
  709. for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2)
  710. if (BBI.getOperand(i).readsReg())
  711. PHIVarInfo[BBI.getOperand(i + 1).getMBB()->getNumber()]
  712. .push_back(BBI.getOperand(i).getReg());
  713. }
  714. }
  715. bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock &MBB,
  716. Register Reg, MachineRegisterInfo &MRI) {
  717. unsigned Num = MBB.getNumber();
  718. // Reg is live-through.
  719. if (AliveBlocks.test(Num))
  720. return true;
  721. // Registers defined in MBB cannot be live in.
  722. const MachineInstr *Def = MRI.getVRegDef(Reg);
  723. if (Def && Def->getParent() == &MBB)
  724. return false;
  725. // Reg was not defined in MBB, was it killed here?
  726. return findKill(&MBB);
  727. }
  728. bool LiveVariables::isLiveOut(Register Reg, const MachineBasicBlock &MBB) {
  729. LiveVariables::VarInfo &VI = getVarInfo(Reg);
  730. SmallPtrSet<const MachineBasicBlock *, 8> Kills;
  731. for (MachineInstr *MI : VI.Kills)
  732. Kills.insert(MI->getParent());
  733. // Loop over all of the successors of the basic block, checking to see if
  734. // the value is either live in the block, or if it is killed in the block.
  735. for (const MachineBasicBlock *SuccMBB : MBB.successors()) {
  736. // Is it alive in this successor?
  737. unsigned SuccIdx = SuccMBB->getNumber();
  738. if (VI.AliveBlocks.test(SuccIdx))
  739. return true;
  740. // Or is it live because there is a use in a successor that kills it?
  741. if (Kills.count(SuccMBB))
  742. return true;
  743. }
  744. return false;
  745. }
  746. /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
  747. /// variables that are live out of DomBB will be marked as passing live through
  748. /// BB.
  749. void LiveVariables::addNewBlock(MachineBasicBlock *BB,
  750. MachineBasicBlock *DomBB,
  751. MachineBasicBlock *SuccBB) {
  752. const unsigned NumNew = BB->getNumber();
  753. DenseSet<unsigned> Defs, Kills;
  754. MachineBasicBlock::iterator BBI = SuccBB->begin(), BBE = SuccBB->end();
  755. for (; BBI != BBE && BBI->isPHI(); ++BBI) {
  756. // Record the def of the PHI node.
  757. Defs.insert(BBI->getOperand(0).getReg());
  758. // All registers used by PHI nodes in SuccBB must be live through BB.
  759. for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
  760. if (BBI->getOperand(i+1).getMBB() == BB)
  761. getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew);
  762. }
  763. // Record all vreg defs and kills of all instructions in SuccBB.
  764. for (; BBI != BBE; ++BBI) {
  765. for (const MachineOperand &Op : BBI->operands()) {
  766. if (Op.isReg() && Register::isVirtualRegister(Op.getReg())) {
  767. if (Op.isDef())
  768. Defs.insert(Op.getReg());
  769. else if (Op.isKill())
  770. Kills.insert(Op.getReg());
  771. }
  772. }
  773. }
  774. // Update info for all live variables
  775. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  776. Register Reg = Register::index2VirtReg(i);
  777. // If the Defs is defined in the successor it can't be live in BB.
  778. if (Defs.count(Reg))
  779. continue;
  780. // If the register is either killed in or live through SuccBB it's also live
  781. // through BB.
  782. VarInfo &VI = getVarInfo(Reg);
  783. if (Kills.count(Reg) || VI.AliveBlocks.test(SuccBB->getNumber()))
  784. VI.AliveBlocks.set(NumNew);
  785. }
  786. }
  787. /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
  788. /// variables that are live out of DomBB will be marked as passing live through
  789. /// BB. LiveInSets[BB] is *not* updated (because it is not needed during
  790. /// PHIElimination).
  791. void LiveVariables::addNewBlock(MachineBasicBlock *BB,
  792. MachineBasicBlock *DomBB,
  793. MachineBasicBlock *SuccBB,
  794. std::vector<SparseBitVector<>> &LiveInSets) {
  795. const unsigned NumNew = BB->getNumber();
  796. SparseBitVector<> &BV = LiveInSets[SuccBB->getNumber()];
  797. for (unsigned R : BV) {
  798. Register VirtReg = Register::index2VirtReg(R);
  799. LiveVariables::VarInfo &VI = getVarInfo(VirtReg);
  800. VI.AliveBlocks.set(NumNew);
  801. }
  802. // All registers used by PHI nodes in SuccBB must be live through BB.
  803. for (MachineBasicBlock::iterator BBI = SuccBB->begin(),
  804. BBE = SuccBB->end();
  805. BBI != BBE && BBI->isPHI(); ++BBI) {
  806. for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
  807. if (BBI->getOperand(i + 1).getMBB() == BB &&
  808. BBI->getOperand(i).readsReg())
  809. getVarInfo(BBI->getOperand(i).getReg())
  810. .AliveBlocks.set(NumNew);
  811. }
  812. }