LLVM API Documentation
00001 //===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This pass eliminates machine instruction PHI nodes by inserting copy 00011 // instructions. This destroys SSA information, but is the desired input for 00012 // some register allocators. 00013 // 00014 //===----------------------------------------------------------------------===// 00015 00016 #define DEBUG_TYPE "phielim" 00017 #include "llvm/CodeGen/LiveVariables.h" 00018 #include "llvm/CodeGen/Passes.h" 00019 #include "llvm/CodeGen/MachineFunctionPass.h" 00020 #include "llvm/CodeGen/MachineInstr.h" 00021 #include "llvm/CodeGen/MachineInstrBuilder.h" 00022 #include "llvm/CodeGen/MachineRegisterInfo.h" 00023 #include "llvm/Target/TargetInstrInfo.h" 00024 #include "llvm/Target/TargetMachine.h" 00025 #include "llvm/ADT/SmallPtrSet.h" 00026 #include "llvm/ADT/STLExtras.h" 00027 #include "llvm/ADT/Statistic.h" 00028 #include "llvm/Support/Compiler.h" 00029 #include <algorithm> 00030 #include <map> 00031 using namespace llvm; 00032 00033 STATISTIC(NumAtomic, "Number of atomic phis lowered"); 00034 00035 namespace { 00036 class VISIBILITY_HIDDEN PNE : public MachineFunctionPass { 00037 MachineRegisterInfo *MRI; // Machine register information 00038 00039 public: 00040 static char ID; // Pass identification, replacement for typeid 00041 PNE() : MachineFunctionPass(&ID) {} 00042 00043 virtual bool runOnMachineFunction(MachineFunction &Fn); 00044 00045 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 00046 AU.addPreserved<LiveVariables>(); 00047 AU.addPreservedID(MachineLoopInfoID); 00048 AU.addPreservedID(MachineDominatorsID); 00049 MachineFunctionPass::getAnalysisUsage(AU); 00050 } 00051 00052 private: 00053 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions 00054 /// in predecessor basic blocks. 00055 /// 00056 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB); 00057 void LowerAtomicPHINode(MachineBasicBlock &MBB, 00058 MachineBasicBlock::iterator AfterPHIsIt); 00059 00060 /// analyzePHINodes - Gather information about the PHI nodes in 00061 /// here. In particular, we want to map the number of uses of a virtual 00062 /// register which is used in a PHI node. We map that to the BB the 00063 /// vreg is coming from. This is used later to determine when the vreg 00064 /// is killed in the BB. 00065 /// 00066 void analyzePHINodes(const MachineFunction& Fn); 00067 00068 typedef std::pair<const MachineBasicBlock*, unsigned> BBVRegPair; 00069 typedef std::map<BBVRegPair, unsigned> VRegPHIUse; 00070 00071 VRegPHIUse VRegPHIUseCount; 00072 00073 // Defs of PHI sources which are implicit_def. 00074 SmallPtrSet<MachineInstr*, 4> ImpDefs; 00075 }; 00076 } 00077 00078 char PNE::ID = 0; 00079 static RegisterPass<PNE> 00080 X("phi-node-elimination", "Eliminate PHI nodes for register allocation"); 00081 00082 const PassInfo *const llvm::PHIEliminationID = &X; 00083 00084 bool PNE::runOnMachineFunction(MachineFunction &Fn) { 00085 MRI = &Fn.getRegInfo(); 00086 00087 analyzePHINodes(Fn); 00088 00089 bool Changed = false; 00090 00091 // Eliminate PHI instructions by inserting copies into predecessor blocks. 00092 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) 00093 Changed |= EliminatePHINodes(Fn, *I); 00094 00095 // Remove dead IMPLICIT_DEF instructions. 00096 for (SmallPtrSet<MachineInstr*,4>::iterator I = ImpDefs.begin(), 00097 E = ImpDefs.end(); I != E; ++I) { 00098 MachineInstr *DefMI = *I; 00099 unsigned DefReg = DefMI->getOperand(0).getReg(); 00100 if (MRI->use_empty(DefReg)) 00101 DefMI->eraseFromParent(); 00102 } 00103 00104 ImpDefs.clear(); 00105 VRegPHIUseCount.clear(); 00106 return Changed; 00107 } 00108 00109 00110 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in 00111 /// predecessor basic blocks. 00112 /// 00113 bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) { 00114 if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI) 00115 return false; // Quick exit for basic blocks without PHIs. 00116 00117 // Get an iterator to the first instruction after the last PHI node (this may 00118 // also be the end of the basic block). 00119 MachineBasicBlock::iterator AfterPHIsIt = MBB.begin(); 00120 while (AfterPHIsIt != MBB.end() && 00121 AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI) 00122 ++AfterPHIsIt; // Skip over all of the PHI nodes... 00123 00124 while (MBB.front().getOpcode() == TargetInstrInfo::PHI) 00125 LowerAtomicPHINode(MBB, AfterPHIsIt); 00126 00127 return true; 00128 } 00129 00130 /// isSourceDefinedByImplicitDef - Return true if all sources of the phi node 00131 /// are implicit_def's. 00132 static bool isSourceDefinedByImplicitDef(const MachineInstr *MPhi, 00133 const MachineRegisterInfo *MRI) { 00134 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) { 00135 unsigned SrcReg = MPhi->getOperand(i).getReg(); 00136 const MachineInstr *DefMI = MRI->getVRegDef(SrcReg); 00137 if (!DefMI || DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF) 00138 return false; 00139 } 00140 return true; 00141 } 00142 00143 /// LowerAtomicPHINode - Lower the PHI node at the top of the specified block, 00144 /// under the assuption that it needs to be lowered in a way that supports 00145 /// atomic execution of PHIs. This lowering method is always correct all of the 00146 /// time. 00147 /// 00148 void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB, 00149 MachineBasicBlock::iterator AfterPHIsIt) { 00150 // Unlink the PHI node from the basic block, but don't delete the PHI yet. 00151 MachineInstr *MPhi = MBB.remove(MBB.begin()); 00152 00153 unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2; 00154 unsigned DestReg = MPhi->getOperand(0).getReg(); 00155 bool isDead = MPhi->getOperand(0).isDead(); 00156 00157 // Create a new register for the incoming PHI arguments. 00158 MachineFunction &MF = *MBB.getParent(); 00159 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg); 00160 unsigned IncomingReg = 0; 00161 00162 // Insert a register to register copy at the top of the current block (but 00163 // after any remaining phi nodes) which copies the new incoming register 00164 // into the phi node destination. 00165 const TargetInstrInfo *TII = MF.getTarget().getInstrInfo(); 00166 if (isSourceDefinedByImplicitDef(MPhi, MRI)) 00167 // If all sources of a PHI node are implicit_def, just emit an 00168 // implicit_def instead of a copy. 00169 BuildMI(MBB, AfterPHIsIt, 00170 TII->get(TargetInstrInfo::IMPLICIT_DEF), DestReg); 00171 else { 00172 IncomingReg = MF.getRegInfo().createVirtualRegister(RC); 00173 TII->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC, RC); 00174 } 00175 00176 // Update live variable information if there is any. 00177 LiveVariables *LV = getAnalysisToUpdate<LiveVariables>(); 00178 if (LV) { 00179 MachineInstr *PHICopy = prior(AfterPHIsIt); 00180 00181 if (IncomingReg) { 00182 // Increment use count of the newly created virtual register. 00183 LV->getVarInfo(IncomingReg).NumUses++; 00184 00185 // Add information to LiveVariables to know that the incoming value is 00186 // killed. Note that because the value is defined in several places (once 00187 // each for each incoming block), the "def" block and instruction fields 00188 // for the VarInfo is not filled in. 00189 LV->addVirtualRegisterKilled(IncomingReg, PHICopy); 00190 00191 LV->getVarInfo(IncomingReg).UsedBlocks[MBB.getNumber()] = true; 00192 } 00193 00194 // Since we are going to be deleting the PHI node, if it is the last use of 00195 // any registers, or if the value itself is dead, we need to move this 00196 // information over to the new copy we just inserted. 00197 LV->removeVirtualRegistersKilled(MPhi); 00198 00199 // If the result is dead, update LV. 00200 if (isDead) { 00201 LV->addVirtualRegisterDead(DestReg, PHICopy); 00202 LV->removeVirtualRegisterDead(DestReg, MPhi); 00203 } 00204 } 00205 00206 // Adjust the VRegPHIUseCount map to account for the removal of this PHI node. 00207 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) 00208 --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i + 1).getMBB(), 00209 MPhi->getOperand(i).getReg())]; 00210 00211 // Now loop over all of the incoming arguments, changing them to copy into the 00212 // IncomingReg register in the corresponding predecessor basic block. 00213 SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto; 00214 for (int i = NumSrcs - 1; i >= 0; --i) { 00215 unsigned SrcReg = MPhi->getOperand(i*2+1).getReg(); 00216 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) && 00217 "Machine PHI Operands must all be virtual registers!"); 00218 00219 // If source is defined by an implicit def, there is no need to insert a 00220 // copy. 00221 MachineInstr *DefMI = MRI->getVRegDef(SrcReg); 00222 if (DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) { 00223 ImpDefs.insert(DefMI); 00224 continue; 00225 } 00226 00227 // Get the MachineBasicBlock equivalent of the BasicBlock that is the source 00228 // path the PHI. 00229 MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB(); 00230 00231 // Check to make sure we haven't already emitted the copy for this block. 00232 // This can happen because PHI nodes may have multiple entries for the same 00233 // basic block. 00234 if (!MBBsInsertedInto.insert(&opBlock)) 00235 continue; // If the copy has already been emitted, we're done. 00236 00237 // Find a safe location to insert the copy, this may be the first terminator 00238 // in the block (or end()). 00239 MachineBasicBlock::iterator InsertPos = opBlock.getFirstTerminator(); 00240 00241 // Insert the copy. 00242 TII->copyRegToReg(opBlock, InsertPos, IncomingReg, SrcReg, RC, RC); 00243 00244 // Now update live variable information if we have it. Otherwise we're done 00245 if (!LV) continue; 00246 00247 // We want to be able to insert a kill of the register if this PHI (aka, the 00248 // copy we just inserted) is the last use of the source value. Live 00249 // variable analysis conservatively handles this by saying that the value is 00250 // live until the end of the block the PHI entry lives in. If the value 00251 // really is dead at the PHI copy, there will be no successor blocks which 00252 // have the value live-in. 00253 // 00254 // Check to see if the copy is the last use, and if so, update the live 00255 // variables information so that it knows the copy source instruction kills 00256 // the incoming value. 00257 LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg); 00258 InRegVI.UsedBlocks[opBlock.getNumber()] = true; 00259 00260 // Loop over all of the successors of the basic block, checking to see if 00261 // the value is either live in the block, or if it is killed in the block. 00262 // Also check to see if this register is in use by another PHI node which 00263 // has not yet been eliminated. If so, it will be killed at an appropriate 00264 // point later. 00265 00266 // Is it used by any PHI instructions in this block? 00267 bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0; 00268 00269 std::vector<MachineBasicBlock*> OpSuccBlocks; 00270 00271 // Otherwise, scan successors, including the BB the PHI node lives in. 00272 for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(), 00273 E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) { 00274 MachineBasicBlock *SuccMBB = *SI; 00275 00276 // Is it alive in this successor? 00277 unsigned SuccIdx = SuccMBB->getNumber(); 00278 if (SuccIdx < InRegVI.AliveBlocks.size() && 00279 InRegVI.AliveBlocks[SuccIdx]) { 00280 ValueIsLive = true; 00281 break; 00282 } 00283 00284 OpSuccBlocks.push_back(SuccMBB); 00285 } 00286 00287 // Check to see if this value is live because there is a use in a successor 00288 // that kills it. 00289 if (!ValueIsLive) { 00290 switch (OpSuccBlocks.size()) { 00291 case 1: { 00292 MachineBasicBlock *MBB = OpSuccBlocks[0]; 00293 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i) 00294 if (InRegVI.Kills[i]->getParent() == MBB) { 00295 ValueIsLive = true; 00296 break; 00297 } 00298 break; 00299 } 00300 case 2: { 00301 MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1]; 00302 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i) 00303 if (InRegVI.Kills[i]->getParent() == MBB1 || 00304 InRegVI.Kills[i]->getParent() == MBB2) { 00305 ValueIsLive = true; 00306 break; 00307 } 00308 break; 00309 } 00310 default: 00311 std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end()); 00312 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i) 00313 if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(), 00314 InRegVI.Kills[i]->getParent())) { 00315 ValueIsLive = true; 00316 break; 00317 } 00318 } 00319 } 00320 00321 // Okay, if we now know that the value is not live out of the block, we can 00322 // add a kill marker in this block saying that it kills the incoming value! 00323 if (!ValueIsLive) { 00324 // In our final twist, we have to decide which instruction kills the 00325 // register. In most cases this is the copy, however, the first 00326 // terminator instruction at the end of the block may also use the value. 00327 // In this case, we should mark *it* as being the killing block, not the 00328 // copy. 00329 MachineBasicBlock::iterator KillInst = prior(InsertPos); 00330 MachineBasicBlock::iterator Term = opBlock.getFirstTerminator(); 00331 if (Term != opBlock.end()) { 00332 if (Term->readsRegister(SrcReg)) 00333 KillInst = Term; 00334 00335 // Check that no other terminators use values. 00336 #ifndef NDEBUG 00337 for (MachineBasicBlock::iterator TI = next(Term); TI != opBlock.end(); 00338 ++TI) { 00339 assert(!TI->readsRegister(SrcReg) && 00340 "Terminator instructions cannot use virtual registers unless" 00341 "they are the first terminator in a block!"); 00342 } 00343 #endif 00344 } 00345 00346 // Finally, mark it killed. 00347 LV->addVirtualRegisterKilled(SrcReg, KillInst); 00348 00349 // This vreg no longer lives all of the way through opBlock. 00350 unsigned opBlockNum = opBlock.getNumber(); 00351 if (opBlockNum < InRegVI.AliveBlocks.size()) 00352 InRegVI.AliveBlocks[opBlockNum] = false; 00353 } 00354 } 00355 00356 // Really delete the PHI instruction now! 00357 MF.DeleteMachineInstr(MPhi); 00358 ++NumAtomic; 00359 } 00360 00361 /// analyzePHINodes - Gather information about the PHI nodes in here. In 00362 /// particular, we want to map the number of uses of a virtual register which is 00363 /// used in a PHI node. We map that to the BB the vreg is coming from. This is 00364 /// used later to determine when the vreg is killed in the BB. 00365 /// 00366 void PNE::analyzePHINodes(const MachineFunction& Fn) { 00367 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end(); 00368 I != E; ++I) 00369 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end(); 00370 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI) 00371 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) 00372 ++VRegPHIUseCount[BBVRegPair(BBI->getOperand(i + 1).getMBB(), 00373 BBI->getOperand(i).getReg())]; 00374 }