PHIElimination.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. //===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
  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 pass eliminates machine instruction PHI nodes by inserting copy
  11. // instructions. This destroys SSA information, but is the desired input for
  12. // some register allocators.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #define DEBUG_TYPE "phielim"
  16. #include "PHIElimination.h"
  17. #include "llvm/CodeGen/LiveVariables.h"
  18. #include "llvm/CodeGen/Passes.h"
  19. #include "llvm/CodeGen/MachineDominators.h"
  20. #include "llvm/CodeGen/MachineInstr.h"
  21. #include "llvm/CodeGen/MachineInstrBuilder.h"
  22. #include "llvm/CodeGen/MachineLoopInfo.h"
  23. #include "llvm/CodeGen/MachineRegisterInfo.h"
  24. #include "llvm/Target/TargetInstrInfo.h"
  25. #include "llvm/Function.h"
  26. #include "llvm/Target/TargetMachine.h"
  27. #include "llvm/ADT/SmallPtrSet.h"
  28. #include "llvm/ADT/STLExtras.h"
  29. #include "llvm/ADT/Statistic.h"
  30. #include "llvm/Support/Compiler.h"
  31. #include "llvm/Support/Debug.h"
  32. #include <algorithm>
  33. #include <map>
  34. using namespace llvm;
  35. STATISTIC(NumAtomic, "Number of atomic phis lowered");
  36. STATISTIC(NumReused, "Number of reused lowered phis");
  37. char PHIElimination::ID = 0;
  38. INITIALIZE_PASS(PHIElimination, "phi-node-elimination",
  39. "Eliminate PHI nodes for register allocation", false, false);
  40. char &llvm::PHIEliminationID = PHIElimination::ID;
  41. void llvm::PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
  42. AU.addPreserved<LiveVariables>();
  43. AU.addPreserved<MachineDominatorTree>();
  44. AU.addPreserved<MachineLoopInfo>();
  45. MachineFunctionPass::getAnalysisUsage(AU);
  46. }
  47. bool llvm::PHIElimination::runOnMachineFunction(MachineFunction &MF) {
  48. MRI = &MF.getRegInfo();
  49. bool Changed = false;
  50. // Split critical edges to help the coalescer
  51. if (LiveVariables *LV = getAnalysisIfAvailable<LiveVariables>()) {
  52. MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
  53. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
  54. Changed |= SplitPHIEdges(MF, *I, *LV, MLI);
  55. }
  56. // Populate VRegPHIUseCount
  57. analyzePHINodes(MF);
  58. // Eliminate PHI instructions by inserting copies into predecessor blocks.
  59. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
  60. Changed |= EliminatePHINodes(MF, *I);
  61. // Remove dead IMPLICIT_DEF instructions.
  62. for (SmallPtrSet<MachineInstr*, 4>::iterator I = ImpDefs.begin(),
  63. E = ImpDefs.end(); I != E; ++I) {
  64. MachineInstr *DefMI = *I;
  65. unsigned DefReg = DefMI->getOperand(0).getReg();
  66. if (MRI->use_nodbg_empty(DefReg))
  67. DefMI->eraseFromParent();
  68. }
  69. // Clean up the lowered PHI instructions.
  70. for (LoweredPHIMap::iterator I = LoweredPHIs.begin(), E = LoweredPHIs.end();
  71. I != E; ++I)
  72. MF.DeleteMachineInstr(I->first);
  73. LoweredPHIs.clear();
  74. ImpDefs.clear();
  75. VRegPHIUseCount.clear();
  76. return Changed;
  77. }
  78. /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
  79. /// predecessor basic blocks.
  80. ///
  81. bool llvm::PHIElimination::EliminatePHINodes(MachineFunction &MF,
  82. MachineBasicBlock &MBB) {
  83. if (MBB.empty() || !MBB.front().isPHI())
  84. return false; // Quick exit for basic blocks without PHIs.
  85. // Get an iterator to the first instruction after the last PHI node (this may
  86. // also be the end of the basic block).
  87. MachineBasicBlock::iterator AfterPHIsIt = SkipPHIsAndLabels(MBB, MBB.begin());
  88. while (MBB.front().isPHI())
  89. LowerAtomicPHINode(MBB, AfterPHIsIt);
  90. return true;
  91. }
  92. /// isSourceDefinedByImplicitDef - Return true if all sources of the phi node
  93. /// are implicit_def's.
  94. static bool isSourceDefinedByImplicitDef(const MachineInstr *MPhi,
  95. const MachineRegisterInfo *MRI) {
  96. for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
  97. unsigned SrcReg = MPhi->getOperand(i).getReg();
  98. const MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
  99. if (!DefMI || !DefMI->isImplicitDef())
  100. return false;
  101. }
  102. return true;
  103. }
  104. // FindCopyInsertPoint - Find a safe place in MBB to insert a copy from SrcReg
  105. // when following the CFG edge to SuccMBB. This needs to be after any def of
  106. // SrcReg, but before any subsequent point where control flow might jump out of
  107. // the basic block.
  108. MachineBasicBlock::iterator
  109. llvm::PHIElimination::FindCopyInsertPoint(MachineBasicBlock &MBB,
  110. MachineBasicBlock &SuccMBB,
  111. unsigned SrcReg) {
  112. // Handle the trivial case trivially.
  113. if (MBB.empty())
  114. return MBB.begin();
  115. // Usually, we just want to insert the copy before the first terminator
  116. // instruction. However, for the edge going to a landing pad, we must insert
  117. // the copy before the call/invoke instruction.
  118. if (!SuccMBB.isLandingPad())
  119. return MBB.getFirstTerminator();
  120. // Discover any defs/uses in this basic block.
  121. SmallPtrSet<MachineInstr*, 8> DefUsesInMBB;
  122. for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
  123. RE = MRI->reg_end(); RI != RE; ++RI) {
  124. MachineInstr *DefUseMI = &*RI;
  125. if (DefUseMI->getParent() == &MBB)
  126. DefUsesInMBB.insert(DefUseMI);
  127. }
  128. MachineBasicBlock::iterator InsertPoint;
  129. if (DefUsesInMBB.empty()) {
  130. // No defs. Insert the copy at the start of the basic block.
  131. InsertPoint = MBB.begin();
  132. } else if (DefUsesInMBB.size() == 1) {
  133. // Insert the copy immediately after the def/use.
  134. InsertPoint = *DefUsesInMBB.begin();
  135. ++InsertPoint;
  136. } else {
  137. // Insert the copy immediately after the last def/use.
  138. InsertPoint = MBB.end();
  139. while (!DefUsesInMBB.count(&*--InsertPoint)) {}
  140. ++InsertPoint;
  141. }
  142. // Make sure the copy goes after any phi nodes however.
  143. return SkipPHIsAndLabels(MBB, InsertPoint);
  144. }
  145. /// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
  146. /// under the assuption that it needs to be lowered in a way that supports
  147. /// atomic execution of PHIs. This lowering method is always correct all of the
  148. /// time.
  149. ///
  150. void llvm::PHIElimination::LowerAtomicPHINode(
  151. MachineBasicBlock &MBB,
  152. MachineBasicBlock::iterator AfterPHIsIt) {
  153. ++NumAtomic;
  154. // Unlink the PHI node from the basic block, but don't delete the PHI yet.
  155. MachineInstr *MPhi = MBB.remove(MBB.begin());
  156. unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
  157. unsigned DestReg = MPhi->getOperand(0).getReg();
  158. assert(MPhi->getOperand(0).getSubReg() == 0 && "Can't handle sub-reg PHIs");
  159. bool isDead = MPhi->getOperand(0).isDead();
  160. // Create a new register for the incoming PHI arguments.
  161. MachineFunction &MF = *MBB.getParent();
  162. unsigned IncomingReg = 0;
  163. bool reusedIncoming = false; // Is IncomingReg reused from an earlier PHI?
  164. // Insert a register to register copy at the top of the current block (but
  165. // after any remaining phi nodes) which copies the new incoming register
  166. // into the phi node destination.
  167. const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
  168. if (isSourceDefinedByImplicitDef(MPhi, MRI))
  169. // If all sources of a PHI node are implicit_def, just emit an
  170. // implicit_def instead of a copy.
  171. BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
  172. TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
  173. else {
  174. // Can we reuse an earlier PHI node? This only happens for critical edges,
  175. // typically those created by tail duplication.
  176. unsigned &entry = LoweredPHIs[MPhi];
  177. if (entry) {
  178. // An identical PHI node was already lowered. Reuse the incoming register.
  179. IncomingReg = entry;
  180. reusedIncoming = true;
  181. ++NumReused;
  182. DEBUG(dbgs() << "Reusing %reg" << IncomingReg << " for " << *MPhi);
  183. } else {
  184. const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
  185. entry = IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
  186. }
  187. BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
  188. TII->get(TargetOpcode::COPY), DestReg)
  189. .addReg(IncomingReg);
  190. }
  191. // Update live variable information if there is any.
  192. LiveVariables *LV = getAnalysisIfAvailable<LiveVariables>();
  193. if (LV) {
  194. MachineInstr *PHICopy = prior(AfterPHIsIt);
  195. if (IncomingReg) {
  196. LiveVariables::VarInfo &VI = LV->getVarInfo(IncomingReg);
  197. // Increment use count of the newly created virtual register.
  198. VI.NumUses++;
  199. LV->setPHIJoin(IncomingReg);
  200. // When we are reusing the incoming register, it may already have been
  201. // killed in this block. The old kill will also have been inserted at
  202. // AfterPHIsIt, so it appears before the current PHICopy.
  203. if (reusedIncoming)
  204. if (MachineInstr *OldKill = VI.findKill(&MBB)) {
  205. DEBUG(dbgs() << "Remove old kill from " << *OldKill);
  206. LV->removeVirtualRegisterKilled(IncomingReg, OldKill);
  207. DEBUG(MBB.dump());
  208. }
  209. // Add information to LiveVariables to know that the incoming value is
  210. // killed. Note that because the value is defined in several places (once
  211. // each for each incoming block), the "def" block and instruction fields
  212. // for the VarInfo is not filled in.
  213. LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
  214. }
  215. // Since we are going to be deleting the PHI node, if it is the last use of
  216. // any registers, or if the value itself is dead, we need to move this
  217. // information over to the new copy we just inserted.
  218. LV->removeVirtualRegistersKilled(MPhi);
  219. // If the result is dead, update LV.
  220. if (isDead) {
  221. LV->addVirtualRegisterDead(DestReg, PHICopy);
  222. LV->removeVirtualRegisterDead(DestReg, MPhi);
  223. }
  224. }
  225. // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
  226. for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
  227. --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i+1).getMBB()->getNumber(),
  228. MPhi->getOperand(i).getReg())];
  229. // Now loop over all of the incoming arguments, changing them to copy into the
  230. // IncomingReg register in the corresponding predecessor basic block.
  231. SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
  232. for (int i = NumSrcs - 1; i >= 0; --i) {
  233. unsigned SrcReg = MPhi->getOperand(i*2+1).getReg();
  234. unsigned SrcSubReg = MPhi->getOperand(i*2+1).getSubReg();
  235. assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
  236. "Machine PHI Operands must all be virtual registers!");
  237. // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
  238. // path the PHI.
  239. MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB();
  240. // If source is defined by an implicit def, there is no need to insert a
  241. // copy.
  242. MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
  243. if (DefMI->isImplicitDef()) {
  244. ImpDefs.insert(DefMI);
  245. continue;
  246. }
  247. // Check to make sure we haven't already emitted the copy for this block.
  248. // This can happen because PHI nodes may have multiple entries for the same
  249. // basic block.
  250. if (!MBBsInsertedInto.insert(&opBlock))
  251. continue; // If the copy has already been emitted, we're done.
  252. // Find a safe location to insert the copy, this may be the first terminator
  253. // in the block (or end()).
  254. MachineBasicBlock::iterator InsertPos =
  255. FindCopyInsertPoint(opBlock, MBB, SrcReg);
  256. // Insert the copy.
  257. if (!reusedIncoming && IncomingReg)
  258. BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(),
  259. TII->get(TargetOpcode::COPY), IncomingReg).addReg(SrcReg, 0, SrcSubReg);
  260. // Now update live variable information if we have it. Otherwise we're done
  261. if (!LV) continue;
  262. // We want to be able to insert a kill of the register if this PHI (aka, the
  263. // copy we just inserted) is the last use of the source value. Live
  264. // variable analysis conservatively handles this by saying that the value is
  265. // live until the end of the block the PHI entry lives in. If the value
  266. // really is dead at the PHI copy, there will be no successor blocks which
  267. // have the value live-in.
  268. // Also check to see if this register is in use by another PHI node which
  269. // has not yet been eliminated. If so, it will be killed at an appropriate
  270. // point later.
  271. // Is it used by any PHI instructions in this block?
  272. bool ValueIsUsed = VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)];
  273. // Okay, if we now know that the value is not live out of the block, we can
  274. // add a kill marker in this block saying that it kills the incoming value!
  275. if (!ValueIsUsed && !LV->isLiveOut(SrcReg, opBlock)) {
  276. // In our final twist, we have to decide which instruction kills the
  277. // register. In most cases this is the copy, however, the first
  278. // terminator instruction at the end of the block may also use the value.
  279. // In this case, we should mark *it* as being the killing block, not the
  280. // copy.
  281. MachineBasicBlock::iterator KillInst;
  282. MachineBasicBlock::iterator Term = opBlock.getFirstTerminator();
  283. if (Term != opBlock.end() && Term->readsRegister(SrcReg)) {
  284. KillInst = Term;
  285. // Check that no other terminators use values.
  286. #ifndef NDEBUG
  287. for (MachineBasicBlock::iterator TI = llvm::next(Term);
  288. TI != opBlock.end(); ++TI) {
  289. assert(!TI->readsRegister(SrcReg) &&
  290. "Terminator instructions cannot use virtual registers unless"
  291. "they are the first terminator in a block!");
  292. }
  293. #endif
  294. } else if (reusedIncoming || !IncomingReg) {
  295. // We may have to rewind a bit if we didn't insert a copy this time.
  296. KillInst = Term;
  297. while (KillInst != opBlock.begin())
  298. if ((--KillInst)->readsRegister(SrcReg))
  299. break;
  300. } else {
  301. // We just inserted this copy.
  302. KillInst = prior(InsertPos);
  303. }
  304. assert(KillInst->readsRegister(SrcReg) && "Cannot find kill instruction");
  305. // Finally, mark it killed.
  306. LV->addVirtualRegisterKilled(SrcReg, KillInst);
  307. // This vreg no longer lives all of the way through opBlock.
  308. unsigned opBlockNum = opBlock.getNumber();
  309. LV->getVarInfo(SrcReg).AliveBlocks.reset(opBlockNum);
  310. }
  311. }
  312. // Really delete the PHI instruction now, if it is not in the LoweredPHIs map.
  313. if (reusedIncoming || !IncomingReg)
  314. MF.DeleteMachineInstr(MPhi);
  315. }
  316. /// analyzePHINodes - Gather information about the PHI nodes in here. In
  317. /// particular, we want to map the number of uses of a virtual register which is
  318. /// used in a PHI node. We map that to the BB the vreg is coming from. This is
  319. /// used later to determine when the vreg is killed in the BB.
  320. ///
  321. void llvm::PHIElimination::analyzePHINodes(const MachineFunction& MF) {
  322. for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
  323. I != E; ++I)
  324. for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
  325. BBI != BBE && BBI->isPHI(); ++BBI)
  326. for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
  327. ++VRegPHIUseCount[BBVRegPair(BBI->getOperand(i+1).getMBB()->getNumber(),
  328. BBI->getOperand(i).getReg())];
  329. }
  330. bool llvm::PHIElimination::SplitPHIEdges(MachineFunction &MF,
  331. MachineBasicBlock &MBB,
  332. LiveVariables &LV,
  333. MachineLoopInfo *MLI) {
  334. if (MBB.empty() || !MBB.front().isPHI() || MBB.isLandingPad())
  335. return false; // Quick exit for basic blocks without PHIs.
  336. bool Changed = false;
  337. for (MachineBasicBlock::const_iterator BBI = MBB.begin(), BBE = MBB.end();
  338. BBI != BBE && BBI->isPHI(); ++BBI) {
  339. for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
  340. unsigned Reg = BBI->getOperand(i).getReg();
  341. MachineBasicBlock *PreMBB = BBI->getOperand(i+1).getMBB();
  342. // We break edges when registers are live out from the predecessor block
  343. // (not considering PHI nodes). If the register is live in to this block
  344. // anyway, we would gain nothing from splitting.
  345. // Avoid splitting backedges of loops. It would introduce small
  346. // out-of-line blocks into the loop which is very bad for code placement.
  347. if (PreMBB != &MBB &&
  348. !LV.isLiveIn(Reg, MBB) && LV.isLiveOut(Reg, *PreMBB)) {
  349. if (!MLI ||
  350. !(MLI->getLoopFor(PreMBB) == MLI->getLoopFor(&MBB) &&
  351. MLI->isLoopHeader(&MBB)))
  352. Changed |= PreMBB->SplitCriticalEdge(&MBB, this) != 0;
  353. }
  354. }
  355. }
  356. return true;
  357. }