LiveVariables.cpp 29 KB

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