LiveVariables.cpp 30 KB

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