2
0

LiveVariables.cpp 29 KB

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