PHIElimination.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 "llvm/CodeGen/LiveVariables.h"
  17. #include "llvm/CodeGen/Passes.h"
  18. #include "llvm/CodeGen/MachineFunctionPass.h"
  19. #include "llvm/CodeGen/MachineInstr.h"
  20. #include "llvm/CodeGen/MachineRegisterInfo.h"
  21. #include "llvm/Target/TargetInstrInfo.h"
  22. #include "llvm/Target/TargetMachine.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/Statistic.h"
  25. #include "llvm/Support/Compiler.h"
  26. #include <set>
  27. #include <algorithm>
  28. using namespace llvm;
  29. STATISTIC(NumAtomic, "Number of atomic phis lowered");
  30. //STATISTIC(NumSimple, "Number of simple phis lowered");
  31. namespace {
  32. struct VISIBILITY_HIDDEN PNE : public MachineFunctionPass {
  33. static char ID; // Pass identification, replacement for typeid
  34. PNE() : MachineFunctionPass((intptr_t)&ID) {}
  35. bool runOnMachineFunction(MachineFunction &Fn) {
  36. analyzePHINodes(Fn);
  37. bool Changed = false;
  38. // Eliminate PHI instructions by inserting copies into predecessor blocks.
  39. for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
  40. Changed |= EliminatePHINodes(Fn, *I);
  41. VRegPHIUseCount.clear();
  42. return Changed;
  43. }
  44. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  45. AU.addPreserved<LiveVariables>();
  46. AU.addPreservedID(MachineLoopInfoID);
  47. AU.addPreservedID(MachineDominatorsID);
  48. MachineFunctionPass::getAnalysisUsage(AU);
  49. }
  50. private:
  51. /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
  52. /// in predecessor basic blocks.
  53. ///
  54. bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
  55. void LowerAtomicPHINode(MachineBasicBlock &MBB,
  56. MachineBasicBlock::iterator AfterPHIsIt);
  57. /// analyzePHINodes - Gather information about the PHI nodes in
  58. /// here. In particular, we want to map the number of uses of a virtual
  59. /// register which is used in a PHI node. We map that to the BB the
  60. /// vreg is coming from. This is used later to determine when the vreg
  61. /// is killed in the BB.
  62. ///
  63. void analyzePHINodes(const MachineFunction& Fn);
  64. typedef std::pair<const MachineBasicBlock*, unsigned> BBVRegPair;
  65. typedef std::map<BBVRegPair, unsigned> VRegPHIUse;
  66. VRegPHIUse VRegPHIUseCount;
  67. };
  68. char PNE::ID = 0;
  69. RegisterPass<PNE> X("phi-node-elimination",
  70. "Eliminate PHI nodes for register allocation");
  71. }
  72. const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
  73. /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
  74. /// predecessor basic blocks.
  75. ///
  76. bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
  77. if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
  78. return false; // Quick exit for basic blocks without PHIs.
  79. // Get an iterator to the first instruction after the last PHI node (this may
  80. // also be the end of the basic block).
  81. MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
  82. while (AfterPHIsIt != MBB.end() &&
  83. AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
  84. ++AfterPHIsIt; // Skip over all of the PHI nodes...
  85. while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
  86. LowerAtomicPHINode(MBB, AfterPHIsIt);
  87. return true;
  88. }
  89. /// InstructionUsesRegister - Return true if the specified machine instr has a
  90. /// use of the specified register.
  91. static bool InstructionUsesRegister(MachineInstr *MI, unsigned SrcReg) {
  92. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
  93. if (MI->getOperand(i).isRegister() &&
  94. MI->getOperand(i).getReg() == SrcReg &&
  95. MI->getOperand(i).isUse())
  96. return true;
  97. return false;
  98. }
  99. /// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
  100. /// under the assuption that it needs to be lowered in a way that supports
  101. /// atomic execution of PHIs. This lowering method is always correct all of the
  102. /// time.
  103. void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,
  104. MachineBasicBlock::iterator AfterPHIsIt) {
  105. // Unlink the PHI node from the basic block, but don't delete the PHI yet.
  106. MachineInstr *MPhi = MBB.remove(MBB.begin());
  107. unsigned DestReg = MPhi->getOperand(0).getReg();
  108. // Create a new register for the incoming PHI arguments.
  109. MachineFunction &MF = *MBB.getParent();
  110. const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
  111. unsigned IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
  112. // Insert a register to register copy in the top of the current block (but
  113. // after any remaining phi nodes) which copies the new incoming register
  114. // into the phi node destination.
  115. //
  116. const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
  117. TII->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC, RC);
  118. // Update live variable information if there is any...
  119. LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
  120. if (LV) {
  121. MachineInstr *PHICopy = prior(AfterPHIsIt);
  122. // Increment use count of the newly created virtual register.
  123. LV->getVarInfo(IncomingReg).NumUses++;
  124. // Add information to LiveVariables to know that the incoming value is
  125. // killed. Note that because the value is defined in several places (once
  126. // each for each incoming block), the "def" block and instruction fields
  127. // for the VarInfo is not filled in.
  128. //
  129. LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
  130. // Since we are going to be deleting the PHI node, if it is the last use
  131. // of any registers, or if the value itself is dead, we need to move this
  132. // information over to the new copy we just inserted.
  133. //
  134. LV->removeVirtualRegistersKilled(MPhi);
  135. // If the result is dead, update LV.
  136. if (LV->RegisterDefIsDead(MPhi, DestReg)) {
  137. LV->addVirtualRegisterDead(DestReg, PHICopy);
  138. LV->removeVirtualRegistersDead(MPhi);
  139. }
  140. // Realize that the destination register is defined by the PHI copy now, not
  141. // the PHI itself.
  142. LV->getVarInfo(DestReg).DefInst = PHICopy;
  143. LV->getVarInfo(IncomingReg).UsedBlocks[MBB.getNumber()] = true;
  144. }
  145. // Adjust the VRegPHIUseCount map to account for the removal of this PHI
  146. // node.
  147. for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
  148. --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i + 1).getMBB(),
  149. MPhi->getOperand(i).getReg())];
  150. // Now loop over all of the incoming arguments, changing them to copy into
  151. // the IncomingReg register in the corresponding predecessor basic block.
  152. //
  153. std::set<MachineBasicBlock*> MBBsInsertedInto;
  154. for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
  155. unsigned SrcReg = MPhi->getOperand(i-1).getReg();
  156. assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
  157. "Machine PHI Operands must all be virtual registers!");
  158. // Get the MachineBasicBlock equivalent of the BasicBlock that is the
  159. // source path the PHI.
  160. MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMBB();
  161. // Check to make sure we haven't already emitted the copy for this block.
  162. // This can happen because PHI nodes may have multiple entries for the
  163. // same basic block.
  164. if (!MBBsInsertedInto.insert(&opBlock).second)
  165. continue; // If the copy has already been emitted, we're done.
  166. // Get an iterator pointing to the first terminator in the block (or end()).
  167. // This is the point where we can insert a copy if we'd like to.
  168. MachineBasicBlock::iterator I = opBlock.getFirstTerminator();
  169. // Insert the copy.
  170. TII->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC, RC);
  171. // Now update live variable information if we have it. Otherwise we're done
  172. if (!LV) continue;
  173. // We want to be able to insert a kill of the register if this PHI
  174. // (aka, the copy we just inserted) is the last use of the source
  175. // value. Live variable analysis conservatively handles this by
  176. // saying that the value is live until the end of the block the PHI
  177. // entry lives in. If the value really is dead at the PHI copy, there
  178. // will be no successor blocks which have the value live-in.
  179. //
  180. // Check to see if the copy is the last use, and if so, update the
  181. // live variables information so that it knows the copy source
  182. // instruction kills the incoming value.
  183. //
  184. LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
  185. InRegVI.UsedBlocks[opBlock.getNumber()] = true;
  186. // Loop over all of the successors of the basic block, checking to see
  187. // if the value is either live in the block, or if it is killed in the
  188. // block. Also check to see if this register is in use by another PHI
  189. // node which has not yet been eliminated. If so, it will be killed
  190. // at an appropriate point later.
  191. //
  192. // Is it used by any PHI instructions in this block?
  193. bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
  194. std::vector<MachineBasicBlock*> OpSuccBlocks;
  195. // Otherwise, scan successors, including the BB the PHI node lives in.
  196. for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
  197. E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
  198. MachineBasicBlock *SuccMBB = *SI;
  199. // Is it alive in this successor?
  200. unsigned SuccIdx = SuccMBB->getNumber();
  201. if (SuccIdx < InRegVI.AliveBlocks.size() &&
  202. InRegVI.AliveBlocks[SuccIdx]) {
  203. ValueIsLive = true;
  204. break;
  205. }
  206. OpSuccBlocks.push_back(SuccMBB);
  207. }
  208. // Check to see if this value is live because there is a use in a successor
  209. // that kills it.
  210. if (!ValueIsLive) {
  211. switch (OpSuccBlocks.size()) {
  212. case 1: {
  213. MachineBasicBlock *MBB = OpSuccBlocks[0];
  214. for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
  215. if (InRegVI.Kills[i]->getParent() == MBB) {
  216. ValueIsLive = true;
  217. break;
  218. }
  219. break;
  220. }
  221. case 2: {
  222. MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
  223. for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
  224. if (InRegVI.Kills[i]->getParent() == MBB1 ||
  225. InRegVI.Kills[i]->getParent() == MBB2) {
  226. ValueIsLive = true;
  227. break;
  228. }
  229. break;
  230. }
  231. default:
  232. std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
  233. for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
  234. if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
  235. InRegVI.Kills[i]->getParent())) {
  236. ValueIsLive = true;
  237. break;
  238. }
  239. }
  240. }
  241. // Okay, if we now know that the value is not live out of the block,
  242. // we can add a kill marker in this block saying that it kills the incoming
  243. // value!
  244. if (!ValueIsLive) {
  245. // In our final twist, we have to decide which instruction kills the
  246. // register. In most cases this is the copy, however, the first
  247. // terminator instruction at the end of the block may also use the value.
  248. // In this case, we should mark *it* as being the killing block, not the
  249. // copy.
  250. bool FirstTerminatorUsesValue = false;
  251. if (I != opBlock.end()) {
  252. FirstTerminatorUsesValue = InstructionUsesRegister(I, SrcReg);
  253. // Check that no other terminators use values.
  254. #ifndef NDEBUG
  255. for (MachineBasicBlock::iterator TI = next(I); TI != opBlock.end();
  256. ++TI) {
  257. assert(!InstructionUsesRegister(TI, SrcReg) &&
  258. "Terminator instructions cannot use virtual registers unless"
  259. "they are the first terminator in a block!");
  260. }
  261. #endif
  262. }
  263. MachineBasicBlock::iterator KillInst;
  264. if (!FirstTerminatorUsesValue)
  265. KillInst = prior(I);
  266. else
  267. KillInst = I;
  268. // Finally, mark it killed.
  269. LV->addVirtualRegisterKilled(SrcReg, KillInst);
  270. // This vreg no longer lives all of the way through opBlock.
  271. unsigned opBlockNum = opBlock.getNumber();
  272. if (opBlockNum < InRegVI.AliveBlocks.size())
  273. InRegVI.AliveBlocks[opBlockNum] = false;
  274. }
  275. }
  276. // Really delete the PHI instruction now!
  277. delete MPhi;
  278. ++NumAtomic;
  279. }
  280. /// analyzePHINodes - Gather information about the PHI nodes in here. In
  281. /// particular, we want to map the number of uses of a virtual register which is
  282. /// used in a PHI node. We map that to the BB the vreg is coming from. This is
  283. /// used later to determine when the vreg is killed in the BB.
  284. ///
  285. void PNE::analyzePHINodes(const MachineFunction& Fn) {
  286. for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
  287. I != E; ++I)
  288. for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
  289. BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
  290. for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
  291. ++VRegPHIUseCount[BBVRegPair(BBI->getOperand(i + 1).getMBB(),
  292. BBI->getOperand(i).getReg())];
  293. }