LLVM API Documentation

StrongPHIElimination.cpp

Go to the documentation of this file.
00001 //===- StrongPhiElimination.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, using an intelligent copy-folding technique based on
00012 // dominator information.  This is technique is derived from:
00013 // 
00014 //    Budimlic, et al. Fast copy coalescing and live-range identification.
00015 //    In Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language
00016 //    Design and Implementation (Berlin, Germany, June 17 - 19, 2002).
00017 //    PLDI '02. ACM, New York, NY, 25-32.
00018 //    DOI= http://doi.acm.org/10.1145/512529.512534
00019 //
00020 //===----------------------------------------------------------------------===//
00021 
00022 #define DEBUG_TYPE "strongphielim"
00023 #include "llvm/CodeGen/Passes.h"
00024 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00025 #include "llvm/CodeGen/MachineDominators.h"
00026 #include "llvm/CodeGen/MachineFunctionPass.h"
00027 #include "llvm/CodeGen/MachineInstr.h"
00028 #include "llvm/CodeGen/MachineLoopInfo.h"
00029 #include "llvm/CodeGen/MachineRegisterInfo.h"
00030 #include "llvm/CodeGen/RegisterCoalescer.h"
00031 #include "llvm/Target/TargetInstrInfo.h"
00032 #include "llvm/Target/TargetMachine.h"
00033 #include "llvm/ADT/DepthFirstIterator.h"
00034 #include "llvm/ADT/Statistic.h"
00035 #include "llvm/Support/Compiler.h"
00036 #include "llvm/Support/Debug.h"
00037 using namespace llvm;
00038 
00039 namespace {
00040   struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
00041     static char ID; // Pass identification, replacement for typeid
00042     StrongPHIElimination() : MachineFunctionPass(&ID) {}
00043 
00044     // Waiting stores, for each MBB, the set of copies that need to
00045     // be inserted into that MBB
00046     DenseMap<MachineBasicBlock*,
00047              std::multimap<unsigned, unsigned> > Waiting;
00048     
00049     // Stacks holds the renaming stack for each register
00050     std::map<unsigned, std::vector<unsigned> > Stacks;
00051     
00052     // Registers in UsedByAnother are PHI nodes that are themselves
00053     // used as operands to another another PHI node
00054     std::set<unsigned> UsedByAnother;
00055     
00056     // RenameSets are the is a map from a PHI-defined register
00057     // to the input registers to be coalesced along with the 
00058     // predecessor block for those input registers.
00059     std::map<unsigned, std::map<unsigned, MachineBasicBlock*> > RenameSets;
00060     
00061     // PhiValueNumber holds the ID numbers of the VNs for each phi that we're
00062     // eliminating, indexed by the register defined by that phi.
00063     std::map<unsigned, unsigned> PhiValueNumber;
00064 
00065     // Store the DFS-in number of each block
00066     DenseMap<MachineBasicBlock*, unsigned> preorder;
00067     
00068     // Store the DFS-out number of each block
00069     DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
00070 
00071     bool runOnMachineFunction(MachineFunction &Fn);
00072     
00073     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00074       AU.addRequired<MachineDominatorTree>();
00075       AU.addRequired<LiveIntervals>();
00076       
00077       // TODO: Actually make this true.
00078       AU.addPreserved<LiveIntervals>();
00079       AU.addPreserved<RegisterCoalescer>();
00080       MachineFunctionPass::getAnalysisUsage(AU);
00081     }
00082     
00083     virtual void releaseMemory() {
00084       preorder.clear();
00085       maxpreorder.clear();
00086       
00087       Waiting.clear();
00088       Stacks.clear();
00089       UsedByAnother.clear();
00090       RenameSets.clear();
00091     }
00092 
00093   private:
00094     
00095     /// DomForestNode - Represents a node in the "dominator forest".  This is
00096     /// a forest in which the nodes represent registers and the edges
00097     /// represent a dominance relation in the block defining those registers.
00098     struct DomForestNode {
00099     private:
00100       // Store references to our children
00101       std::vector<DomForestNode*> children;
00102       // The register we represent
00103       unsigned reg;
00104       
00105       // Add another node as our child
00106       void addChild(DomForestNode* DFN) { children.push_back(DFN); }
00107       
00108     public:
00109       typedef std::vector<DomForestNode*>::iterator iterator;
00110       
00111       // Create a DomForestNode by providing the register it represents, and
00112       // the node to be its parent.  The virtual root node has register 0
00113       // and a null parent.
00114       DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
00115         if (parent)
00116           parent->addChild(this);
00117       }
00118       
00119       ~DomForestNode() {
00120         for (iterator I = begin(), E = end(); I != E; ++I)
00121           delete *I;
00122       }
00123       
00124       /// getReg - Return the regiser that this node represents
00125       inline unsigned getReg() { return reg; }
00126       
00127       // Provide iterator access to our children
00128       inline DomForestNode::iterator begin() { return children.begin(); }
00129       inline DomForestNode::iterator end() { return children.end(); }
00130     };
00131     
00132     void computeDFS(MachineFunction& MF);
00133     void processBlock(MachineBasicBlock* MBB);
00134     
00135     std::vector<DomForestNode*> computeDomForest(
00136                            std::map<unsigned, MachineBasicBlock*>& instrs,
00137                                                  MachineRegisterInfo& MRI);
00138     void processPHIUnion(MachineInstr* Inst,
00139                          std::map<unsigned, MachineBasicBlock*>& PHIUnion,
00140                          std::vector<StrongPHIElimination::DomForestNode*>& DF,
00141                          std::vector<std::pair<unsigned, unsigned> >& locals);
00142     void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
00143     void InsertCopies(MachineDomTreeNode* MBB,
00144                       SmallPtrSet<MachineBasicBlock*, 16>& v);
00145     bool mergeLiveIntervals(unsigned primary, unsigned secondary);
00146   };
00147 }
00148 
00149 char StrongPHIElimination::ID = 0;
00150 static RegisterPass<StrongPHIElimination>
00151 X("strong-phi-node-elimination",
00152   "Eliminate PHI nodes for register allocation, intelligently");
00153 
00154 const PassInfo *const llvm::StrongPHIEliminationID = &X;
00155 
00156 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
00157 /// of the given MachineFunction.  These numbers are then used in other parts
00158 /// of the PHI elimination process.
00159 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
00160   SmallPtrSet<MachineDomTreeNode*, 8> frontier;
00161   SmallPtrSet<MachineDomTreeNode*, 8> visited;
00162   
00163   unsigned time = 0;
00164   
00165   MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
00166   
00167   MachineDomTreeNode* node = DT.getRootNode();
00168   
00169   std::vector<MachineDomTreeNode*> worklist;
00170   worklist.push_back(node);
00171   
00172   while (!worklist.empty()) {
00173     MachineDomTreeNode* currNode = worklist.back();
00174     
00175     if (!frontier.count(currNode)) {
00176       frontier.insert(currNode);
00177       ++time;
00178       preorder.insert(std::make_pair(currNode->getBlock(), time));
00179     }
00180     
00181     bool inserted = false;
00182     for (MachineDomTreeNode::iterator I = currNode->begin(), E = currNode->end();
00183          I != E; ++I)
00184       if (!frontier.count(*I) && !visited.count(*I)) {
00185         worklist.push_back(*I);
00186         inserted = true;
00187         break;
00188       }
00189     
00190     if (!inserted) {
00191       frontier.erase(currNode);
00192       visited.insert(currNode);
00193       maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
00194       
00195       worklist.pop_back();
00196     }
00197   }
00198 }
00199 
00200 namespace {
00201 
00202 /// PreorderSorter - a helper class that is used to sort registers
00203 /// according to the preorder number of their defining blocks
00204 class PreorderSorter {
00205 private:
00206   DenseMap<MachineBasicBlock*, unsigned>& preorder;
00207   MachineRegisterInfo& MRI;
00208   
00209 public:
00210   PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
00211                 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
00212   
00213   bool operator()(unsigned A, unsigned B) {
00214     if (A == B)
00215       return false;
00216     
00217     MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
00218     MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
00219     
00220     if (preorder[ABlock] < preorder[BBlock])
00221       return true;
00222     else if (preorder[ABlock] > preorder[BBlock])
00223       return false;
00224     
00225     return false;
00226   }
00227 };
00228 
00229 }
00230 
00231 /// computeDomForest - compute the subforest of the DomTree corresponding
00232 /// to the defining blocks of the registers in question
00233 std::vector<StrongPHIElimination::DomForestNode*>
00234 StrongPHIElimination::computeDomForest(
00235                   std::map<unsigned, MachineBasicBlock*>& regs, 
00236                                        MachineRegisterInfo& MRI) {
00237   // Begin by creating a virtual root node, since the actual results
00238   // may well be a forest.  Assume this node has maximum DFS-out number.
00239   DomForestNode* VirtualRoot = new DomForestNode(0, 0);
00240   maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
00241   
00242   // Populate a worklist with the registers
00243   std::vector<unsigned> worklist;
00244   worklist.reserve(regs.size());
00245   for (std::map<unsigned, MachineBasicBlock*>::iterator I = regs.begin(),
00246        E = regs.end(); I != E; ++I)
00247     worklist.push_back(I->first);
00248   
00249   // Sort the registers by the DFS-in number of their defining block
00250   PreorderSorter PS(preorder, MRI);
00251   std::sort(worklist.begin(), worklist.end(), PS);
00252   
00253   // Create a "current parent" stack, and put the virtual root on top of it
00254   DomForestNode* CurrentParent = VirtualRoot;
00255   std::vector<DomForestNode*> stack;
00256   stack.push_back(VirtualRoot);
00257   
00258   // Iterate over all the registers in the previously computed order
00259   for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
00260        I != E; ++I) {
00261     unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
00262     MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
00263                  MRI.getVRegDef(CurrentParent->getReg())->getParent() :
00264                  0;
00265     
00266     // If the DFS-in number of the register is greater than the DFS-out number
00267     // of the current parent, repeatedly pop the parent stack until it isn't.
00268     while (pre > maxpreorder[parentBlock]) {
00269       stack.pop_back();
00270       CurrentParent = stack.back();
00271       
00272       parentBlock = CurrentParent->getReg() ?
00273                    MRI.getVRegDef(CurrentParent->getReg())->getParent() :
00274                    0;
00275     }
00276     
00277     // Now that we've found the appropriate parent, create a DomForestNode for
00278     // this register and attach it to the forest
00279     DomForestNode* child = new DomForestNode(*I, CurrentParent);
00280     
00281     // Push this new node on the "current parent" stack
00282     stack.push_back(child);
00283     CurrentParent = child;
00284   }
00285   
00286   // Return a vector containing the children of the virtual root node
00287   std::vector<DomForestNode*> ret;
00288   ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
00289   return ret;
00290 }
00291 
00292 /// isLiveIn - helper method that determines, from a regno, if a register
00293 /// is live into a block
00294 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
00295                      LiveIntervals& LI) {
00296   LiveInterval& I = LI.getOrCreateInterval(r);
00297   unsigned idx = LI.getMBBStartIdx(MBB);
00298   return I.liveAt(idx);
00299 }
00300 
00301 /// isLiveOut - help method that determines, from a regno, if a register is
00302 /// live out of a block.
00303 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
00304                       LiveIntervals& LI) {
00305   for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
00306        E = MBB->succ_end(); PI != E; ++PI)
00307     if (isLiveIn(r, *PI, LI))
00308       return true;
00309   
00310   return false;
00311 }
00312 
00313 /// interferes - checks for local interferences by scanning a block.  The only
00314 /// trick parameter is 'mode' which tells it the relationship of the two
00315 /// registers. 0 - defined in the same block, 1 - first properly dominates
00316 /// second, 2 - second properly dominates first 
00317 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
00318                        LiveIntervals& LV, unsigned mode) {
00319   MachineInstr* def = 0;
00320   MachineInstr* kill = 0;
00321   
00322   // The code is still in SSA form at this point, so there is only one
00323   // definition per VReg.  Thus we can safely use MRI->getVRegDef().
00324   const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
00325   
00326   bool interference = false;
00327   
00328   // Wallk the block, checking for interferences
00329   for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
00330        MBI != MBE; ++MBI) {
00331     MachineInstr* curr = MBI;
00332     
00333     // Same defining block...
00334     if (mode == 0) {
00335       if (curr == MRI->getVRegDef(a)) {
00336         // If we find our first definition, save it
00337         if (!def) {
00338           def = curr;
00339         // If there's already an unkilled definition, then 
00340         // this is an interference
00341         } else if (!kill) {
00342           interference = true;
00343           break;
00344         // If there's a definition followed by a KillInst, then
00345         // they can't interfere
00346         } else {
00347           interference = false;
00348           break;
00349         }
00350       // Symmetric with the above
00351       } else if (curr == MRI->getVRegDef(b)) {
00352         if (!def) {
00353           def = curr;
00354         } else if (!kill) {
00355           interference = true;
00356           break;
00357         } else {
00358           interference = false;
00359           break;
00360         }
00361       // Store KillInsts if they match up with the definition
00362       } else if (curr->killsRegister(a)) {
00363         if (def == MRI->getVRegDef(a)) {
00364           kill = curr;
00365         } else if (curr->killsRegister(b)) {
00366           if (def == MRI->getVRegDef(b)) {
00367             kill = curr;
00368           }
00369         }
00370       }
00371     // First properly dominates second...
00372     } else if (mode == 1) {
00373       if (curr == MRI->getVRegDef(b)) {
00374         // Definition of second without kill of first is an interference
00375         if (!kill) {
00376           interference = true;
00377           break;
00378         // Definition after a kill is a non-interference
00379         } else {
00380           interference = false;
00381           break;
00382         }
00383       // Save KillInsts of First
00384       } else if (curr->killsRegister(a)) {
00385         kill = curr;
00386       }
00387     // Symmetric with the above
00388     } else if (mode == 2) {
00389       if (curr == MRI->getVRegDef(a)) {
00390         if (!kill) {
00391           interference = true;
00392           break;
00393         } else {
00394           interference = false;
00395           break;
00396         }
00397       } else if (curr->killsRegister(b)) {
00398         kill = curr;
00399       }
00400     }
00401   }
00402   
00403   return interference;
00404 }
00405 
00406 /// processBlock - Determine how to break up PHIs in the current block.  Each
00407 /// PHI is broken up by some combination of renaming its operands and inserting
00408 /// copies.  This method is responsible for determining which operands receive
00409 /// which treatment.
00410 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
00411   LiveIntervals& LI = getAnalysis<LiveIntervals>();
00412   MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
00413   
00414   // Holds names that have been added to a set in any PHI within this block
00415   // before the current one.
00416   std::set<unsigned> ProcessedNames;
00417   
00418   // Iterate over all the PHI nodes in this block
00419   MachineBasicBlock::iterator P = MBB->begin();
00420   while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
00421     unsigned DestReg = P->getOperand(0).getReg();
00422     
00423     // Don't both doing PHI elimination for dead PHI's.
00424     if (P->registerDefIsDead(DestReg)) {
00425       ++P;
00426       continue;
00427     }
00428 
00429     LiveInterval& PI = LI.getOrCreateInterval(DestReg);
00430     unsigned pIdx = LI.getDefIndex(LI.getInstructionIndex(P));
00431     VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
00432     PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
00433 
00434     // PHIUnion is the set of incoming registers to the PHI node that
00435     // are going to be renames rather than having copies inserted.  This set
00436     // is refinded over the course of this function.  UnionedBlocks is the set
00437     // of corresponding MBBs.
00438     std::map<unsigned, MachineBasicBlock*> PHIUnion;
00439     SmallPtrSet<MachineBasicBlock*, 8> UnionedBlocks;
00440   
00441     // Iterate over the operands of the PHI node
00442     for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
00443       unsigned SrcReg = P->getOperand(i-1).getReg();
00444       
00445       // Don't need to try to coalesce a register with itself.
00446       if (SrcReg == DestReg) {
00447         ProcessedNames.insert(SrcReg);
00448         continue;
00449       }
00450       
00451       // We don't need to insert copies for implicit_defs.
00452       MachineInstr* DefMI = MRI.getVRegDef(SrcReg);
00453       if (DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
00454         ProcessedNames.insert(SrcReg);
00455     
00456       // Check for trivial interferences via liveness information, allowing us
00457       // to avoid extra work later.  Any registers that interfere cannot both
00458       // be in the renaming set, so choose one and add copies for it instead.
00459       // The conditions are:
00460       //   1) if the operand is live into the PHI node's block OR
00461       //   2) if the PHI node is live out of the operand's defining block OR
00462       //   3) if the operand is itself a PHI node and the original PHI is
00463       //      live into the operand's defining block OR
00464       //   4) if the operand is already being renamed for another PHI node
00465       //      in this block OR
00466       //   5) if any two operands are defined in the same block, insert copies
00467       //      for one of them
00468       if (isLiveIn(SrcReg, P->getParent(), LI) ||
00469           isLiveOut(P->getOperand(0).getReg(),
00470                     MRI.getVRegDef(SrcReg)->getParent(), LI) ||
00471           ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
00472             isLiveIn(P->getOperand(0).getReg(),
00473                      MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
00474           ProcessedNames.count(SrcReg) ||
00475           UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
00476         
00477         // Add a copy for the selected register
00478         MachineBasicBlock* From = P->getOperand(i).getMBB();
00479         Waiting[From].insert(std::make_pair(SrcReg, DestReg));
00480         UsedByAnother.insert(SrcReg);
00481       } else {
00482         // Otherwise, add it to the renaming set
00483         PHIUnion.insert(std::make_pair(SrcReg,P->getOperand(i).getMBB()));
00484         UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
00485       }
00486     }
00487     
00488     // Compute the dominator forest for the renaming set.  This is a forest
00489     // where the nodes are the registers and the edges represent dominance 
00490     // relations between the defining blocks of the registers
00491     std::vector<StrongPHIElimination::DomForestNode*> DF = 
00492                                                 computeDomForest(PHIUnion, MRI);
00493     
00494     // Walk DomForest to resolve interferences at an inter-block level.  This
00495     // will remove registers from the renaming set (and insert copies for them)
00496     // if interferences are found.
00497     std::vector<std::pair<unsigned, unsigned> > localInterferences;
00498     processPHIUnion(P, PHIUnion, DF, localInterferences);
00499     
00500     // If one of the inputs is defined in the same block as the current PHI
00501     // then we need to check for a local interference between that input and
00502     // the PHI.
00503     for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
00504          E = PHIUnion.end(); I != E; ++I)
00505       if (MRI.getVRegDef(I->first)->getParent() == P->getParent())
00506         localInterferences.push_back(std::make_pair(I->first,
00507                                                     P->getOperand(0).getReg()));
00508     
00509     // The dominator forest walk may have returned some register pairs whose
00510     // interference cannot be determined from dominator analysis.  We now 
00511     // examine these pairs for local interferences.
00512     for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
00513         localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
00514       std::pair<unsigned, unsigned> p = *I;
00515       
00516       MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
00517       
00518       // Determine the block we need to scan and the relationship between
00519       // the two registers
00520       MachineBasicBlock* scan = 0;
00521       unsigned mode = 0;
00522       if (MRI.getVRegDef(p.first)->getParent() ==
00523           MRI.getVRegDef(p.second)->getParent()) {
00524         scan = MRI.getVRegDef(p.first)->getParent();
00525         mode = 0; // Same block
00526       } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
00527                                MRI.getVRegDef(p.second)->getParent())) {
00528         scan = MRI.getVRegDef(p.second)->getParent();
00529         mode = 1; // First dominates second
00530       } else {
00531         scan = MRI.getVRegDef(p.first)->getParent();
00532         mode = 2; // Second dominates first
00533       }
00534       
00535       // If there's an interference, we need to insert  copies
00536       if (interferes(p.first, p.second, scan, LI, mode)) {
00537         // Insert copies for First
00538         for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
00539           if (P->getOperand(i-1).getReg() == p.first) {
00540             unsigned SrcReg = p.first;
00541             MachineBasicBlock* From = P->getOperand(i).getMBB();
00542             
00543             Waiting[From].insert(std::make_pair(SrcReg,
00544                                                 P->getOperand(0).getReg()));
00545             UsedByAnother.insert(SrcReg);
00546             
00547             PHIUnion.erase(SrcReg);
00548           }
00549         }
00550       }
00551     }
00552     
00553     // Add the renaming set for this PHI node to our overall renaming information
00554     for (std::map<unsigned, MachineBasicBlock*>::iterator QI = PHIUnion.begin(),
00555          QE = PHIUnion.end(); QI != QE; ++QI) {
00556       DOUT << "Adding Renaming: " << QI->first << " -> "
00557            << P->getOperand(0).getReg() << "\n";
00558     }
00559     
00560     RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
00561     
00562     // Remember which registers are already renamed, so that we don't try to 
00563     // rename them for another PHI node in this block
00564     for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
00565          E = PHIUnion.end(); I != E; ++I)
00566       ProcessedNames.insert(I->first);
00567     
00568     ++P;
00569   }
00570 }
00571 
00572 /// processPHIUnion - Take a set of candidate registers to be coalesced when
00573 /// decomposing the PHI instruction.  Use the DominanceForest to remove the ones
00574 /// that are known to interfere, and flag others that need to be checked for
00575 /// local interferences.
00576 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
00577                         std::map<unsigned, MachineBasicBlock*>& PHIUnion,
00578                         std::vector<StrongPHIElimination::DomForestNode*>& DF,
00579                         std::vector<std::pair<unsigned, unsigned> >& locals) {
00580   
00581   std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
00582   SmallPtrSet<DomForestNode*, 4> visited;
00583   
00584   // Code is still in SSA form, so we can use MRI::getVRegDef()
00585   MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
00586   
00587   LiveIntervals& LI = getAnalysis<LiveIntervals>();
00588   unsigned DestReg = Inst->getOperand(0).getReg();
00589   
00590   // DF walk on the DomForest
00591   while (!worklist.empty()) {
00592     DomForestNode* DFNode = worklist.back();
00593     
00594     visited.insert(DFNode);
00595     
00596     bool inserted = false;
00597     for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
00598          CI != CE; ++CI) {
00599       DomForestNode* child = *CI;   
00600       
00601       // If the current node is live-out of the defining block of one of its
00602       // children, insert a copy for it.  NOTE: The paper actually calls for
00603       // a more elaborate heuristic for determining whether to insert copies
00604       // for the child or the parent.  In the interest of simplicity, we're
00605       // just always choosing the parent.
00606       if (isLiveOut(DFNode->getReg(),
00607           MRI.getVRegDef(child->getReg())->getParent(), LI)) {
00608         // Insert copies for parent
00609         for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
00610           if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
00611             unsigned SrcReg = DFNode->getReg();
00612             MachineBasicBlock* From = Inst->getOperand(i).getMBB();
00613             
00614             Waiting[From].insert(std::make_pair(SrcReg, DestReg));
00615             UsedByAnother.insert(SrcReg);
00616             
00617             PHIUnion.erase(SrcReg);
00618           }
00619         }
00620       
00621       // If a node is live-in to the defining block of one of its children, but
00622       // not live-out, then we need to scan that block for local interferences.
00623       } else if (isLiveIn(DFNode->getReg(),
00624                           MRI.getVRegDef(child->getReg())->getParent(), LI) ||
00625                  MRI.getVRegDef(DFNode->getReg())->getParent() ==
00626                                  MRI.getVRegDef(child->getReg())->getParent()) {
00627         // Add (p, c) to possible local interferences
00628         locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
00629       }
00630       
00631       if (!visited.count(child)) {
00632         worklist.push_back(child);
00633         inserted = true;
00634       }
00635     }
00636     
00637     if (!inserted) worklist.pop_back();
00638   }
00639 }
00640 
00641 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
00642 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
00643 /// problems.
00644 ///
00645 /// Based on "Practical Improvements to the Construction and Destruction
00646 /// of Static Single Assignment Form" by Briggs, et al.
00647 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
00648                                           std::set<unsigned>& pushed) {
00649   // FIXME: This function needs to update LiveIntervals
00650   std::multimap<unsigned, unsigned>& copy_set= Waiting[MBB];
00651   
00652   std::multimap<unsigned, unsigned> worklist;
00653   std::map<unsigned, unsigned> map;
00654   
00655   // Setup worklist of initial copies
00656   for (std::multimap<unsigned, unsigned>::iterator I = copy_set.begin(),
00657        E = copy_set.end(); I != E; ) {
00658     map.insert(std::make_pair(I->first, I->first));
00659     map.insert(std::make_pair(I->second, I->second));
00660          
00661     if (!UsedByAnother.count(I->second)) {
00662       worklist.insert(*I);
00663       
00664       // Avoid iterator invalidation
00665       std::multimap<unsigned, unsigned>::iterator OI = I;
00666       ++I;
00667       copy_set.erase(OI);
00668     } else {
00669       ++I;
00670     }
00671   }
00672   
00673   LiveIntervals& LI = getAnalysis<LiveIntervals>();
00674   MachineFunction* MF = MBB->getParent();
00675   MachineRegisterInfo& MRI = MF->getRegInfo();
00676   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
00677   
00678   SmallVector<std::pair<unsigned, MachineInstr*>, 4> InsertedPHIDests;
00679   
00680   // Iterate over the worklist, inserting copies
00681   while (!worklist.empty() || !copy_set.empty()) {
00682     while (!worklist.empty()) {
00683       std::multimap<unsigned, unsigned>::iterator WI = worklist.begin();
00684       std::pair<unsigned, unsigned> curr = *WI;
00685       worklist.erase(WI);
00686       
00687       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
00688       
00689       if (isLiveOut(curr.second, MBB, LI)) {
00690         // Create a temporary
00691         unsigned t = MF->getRegInfo().createVirtualRegister(RC);
00692         
00693         // Insert copy from curr.second to a temporary at
00694         // the Phi defining curr.second
00695         MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
00696         TII->copyRegToReg(*PI->getParent(), PI, t,
00697                           curr.second, RC, RC);
00698         
00699         DOUT << "Inserted copy from " << curr.second << " to " << t << "\n";
00700         
00701         // Push temporary on Stacks
00702         Stacks[curr.second].push_back(t);
00703         
00704         // Insert curr.second in pushed
00705         pushed.insert(curr.second);
00706         
00707         // Create a live interval for this temporary
00708         InsertedPHIDests.push_back(std::make_pair(t, --PI));
00709       }
00710       
00711       // Insert copy from map[curr.first] to curr.second
00712       TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
00713                         map[curr.first], RC, RC);
00714       map[curr.first] = curr.second;
00715       DOUT << "Inserted copy from " << curr.first << " to "
00716            << curr.second << "\n";
00717       
00718       // Push this copy onto InsertedPHICopies so we can
00719       // update LiveIntervals with it.
00720       MachineBasicBlock::iterator MI = MBB->getFirstTerminator();
00721       InsertedPHIDests.push_back(std::make_pair(curr.second, --MI));
00722       
00723       // If curr.first is a destination in copy_set...
00724       for (std::multimap<unsigned, unsigned>::iterator I = copy_set.begin(),
00725            E = copy_set.end(); I != E; )
00726         if (curr.first == I->second) {
00727           std::pair<unsigned, unsigned> temp = *I;
00728           worklist.insert(temp);
00729           
00730           // Avoid iterator invalidation
00731           std::multimap<unsigned, unsigned>::iterator OI = I;
00732           ++I;
00733           copy_set.erase(OI);
00734           
00735           break;
00736         } else {
00737           ++I;
00738         }
00739     }
00740     
00741     if (!copy_set.empty()) {
00742       std::multimap<unsigned, unsigned>::iterator CI = copy_set.begin();
00743       std::pair<unsigned, unsigned> curr = *CI;
00744       worklist.insert(curr);
00745       copy_set.erase(CI);
00746       
00747       LiveInterval& I = LI.getInterval(curr.second);
00748       MachineBasicBlock::iterator term = MBB->getFirstTerminator();
00749       unsigned endIdx = 0;
00750       if (term != MBB->end())
00751         endIdx = LI.getInstructionIndex(term);
00752       else
00753         endIdx = LI.getMBBEndIdx(MBB);
00754       
00755       if (I.liveAt(endIdx)) {
00756         const TargetRegisterClass *RC =
00757                                        MF->getRegInfo().getRegClass(curr.first);
00758         
00759         // Insert a copy from dest to a new temporary t at the end of b
00760         unsigned t = MF->getRegInfo().createVirtualRegister(RC);
00761         TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
00762                           curr.second, RC, RC);
00763         map[curr.second] = t;
00764         
00765         MachineBasicBlock::iterator TI = MBB->getFirstTerminator();
00766         InsertedPHIDests.push_back(std::make_pair(t, --TI));
00767       }
00768     }
00769   }
00770   
00771   // Renumber the instructions so that we can perform the index computations
00772   // needed to create new live intervals.
00773   LI.computeNumbering();
00774   
00775   // For copies that we inserted at the ends of predecessors, we construct
00776   // live intervals.  This is pretty easy, since we know that the destination
00777   // register cannot have be in live at that point previously.  We just have
00778   // to make sure that, for registers that serve as inputs to more than one
00779   // PHI, we don't create multiple overlapping live intervals.
00780   std::set<unsigned> RegHandled;
00781   for (SmallVector<std::pair<unsigned, MachineInstr*>, 4>::iterator I =
00782        InsertedPHIDests.begin(), E = InsertedPHIDests.end(); I != E; ++I) {
00783     if (RegHandled.insert(I->first).second) {
00784       LiveInterval& Int = LI.getOrCreateInterval(I->first);
00785       unsigned instrIdx = LI.getInstructionIndex(I->second);
00786       if (Int.liveAt(LiveIntervals::getDefIndex(instrIdx)))
00787         Int.removeRange(LiveIntervals::getDefIndex(instrIdx),
00788                         LI.getMBBEndIdx(I->second->getParent())+1,
00789                         true);
00790       
00791       LiveRange R = LI.addLiveRangeToEndOfBlock(I->first, I->second);
00792       R.valno->copy = I->second;
00793       R.valno->def =
00794                   LiveIntervals::getDefIndex(LI.getInstructionIndex(I->second));
00795     }
00796   }
00797 }
00798 
00799 /// InsertCopies - insert copies into MBB and all of its successors
00800 void StrongPHIElimination::InsertCopies(MachineDomTreeNode* MDTN,
00801                                  SmallPtrSet<MachineBasicBlock*, 16>& visited) {
00802   MachineBasicBlock* MBB = MDTN->getBlock();
00803   visited.insert(MBB);
00804   
00805   std::set<unsigned> pushed;
00806   
00807   LiveIntervals& LI = getAnalysis<LiveIntervals>();
00808   // Rewrite register uses from Stacks
00809   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
00810       I != E; ++I) {
00811     if (I->getOpcode() == TargetInstrInfo::PHI)
00812       continue;
00813     
00814     for (unsigned i = 0; i < I->getNumOperands(); ++i)
00815       if (I->getOperand(i).isReg() &&
00816           Stacks[I->getOperand(i).getReg()].size()) {
00817         // Remove the live range for the old vreg.
00818         LiveInterval& OldInt = LI.getInterval(I->getOperand(i).getReg());
00819         LiveInterval::iterator OldLR = OldInt.FindLiveRangeContaining(
00820                   LiveIntervals::getUseIndex(LI.getInstructionIndex(I)));
00821         if (OldLR != OldInt.end())
00822           OldInt.removeRange(*OldLR, true);
00823         
00824         // Change the register
00825         I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
00826         
00827         // Add a live range for the new vreg
00828         LiveInterval& Int = LI.getInterval(I->getOperand(i).getReg());
00829         VNInfo* FirstVN = *Int.vni_begin();
00830         FirstVN->hasPHIKill = false;
00831         if (I->getOperand(i).isKill())
00832           FirstVN->kills.push_back(
00833                          LiveIntervals::getUseIndex(LI.getInstructionIndex(I)));
00834         
00835         LiveRange LR (LI.getMBBStartIdx(I->getParent()),
00836                       LiveIntervals::getUseIndex(LI.getInstructionIndex(I))+1,
00837                       FirstVN);
00838         
00839         Int.addRange(LR);
00840       }
00841   }    
00842   
00843   // Schedule the copies for this block
00844   ScheduleCopies(MBB, pushed);
00845   
00846   // Recur down the dominator tree.
00847   for (MachineDomTreeNode::iterator I = MDTN->begin(),
00848        E = MDTN->end(); I != E; ++I)
00849     if (!visited.count((*I)->getBlock()))
00850       InsertCopies(*I, visited);
00851   
00852   // As we exit this block, pop the names we pushed while processing it
00853   for (std::set<unsigned>::iterator I = pushed.begin(), 
00854        E = pushed.end(); I != E; ++I)
00855     Stacks[*I].pop_back();
00856 }
00857 
00858 bool StrongPHIElimination::mergeLiveIntervals(unsigned primary,
00859                                               unsigned secondary) {
00860   
00861   LiveIntervals& LI = getAnalysis<LiveIntervals>();
00862   LiveInterval& LHS = LI.getOrCreateInterval(primary);
00863   LiveInterval& RHS = LI.getOrCreateInterval(secondary);
00864   
00865   LI.computeNumbering();
00866   
00867   DenseMap<VNInfo*, VNInfo*> VNMap;
00868   for (LiveInterval::iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
00869     LiveRange R = *I;
00870  
00871     unsigned Start = R.start;
00872     unsigned End = R.end;
00873     if (LHS.getLiveRangeContaining(Start))
00874       return false;
00875     
00876     if (LHS.getLiveRangeContaining(End))
00877       return false;
00878     
00879     LiveInterval::iterator RI = std::upper_bound(LHS.begin(), LHS.end(), R);
00880     if (RI != LHS.end() && RI->start < End)
00881       return false;
00882   }
00883   
00884   for (LiveInterval::iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
00885     LiveRange R = *I;
00886     VNInfo* OldVN = R.valno;
00887     VNInfo*& NewVN = VNMap[OldVN];
00888     if (!NewVN) {
00889       NewVN = LHS.getNextValue(OldVN->def,
00890                                OldVN->copy,
00891                                LI.getVNInfoAllocator());
00892       NewVN->kills = OldVN->kills;
00893     }
00894     
00895     LiveRange LR (R.start, R.end, NewVN);
00896     LHS.addRange(LR);
00897   }
00898   
00899   LI.removeInterval(RHS.reg);
00900   
00901   return true;
00902 }
00903 
00904 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
00905   LiveIntervals& LI = getAnalysis<LiveIntervals>();
00906   
00907   // Compute DFS numbers of each block
00908   computeDFS(Fn);
00909   
00910   // Determine which phi node operands need copies
00911   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
00912     if (!I->empty() &&
00913         I->begin()->getOpcode() == TargetInstrInfo::PHI)
00914       processBlock(I);
00915   
00916   // Break interferences where two different phis want to coalesce
00917   // in the same register.
00918   std::set<unsigned> seen;
00919   typedef std::map<unsigned, std::map<unsigned, MachineBasicBlock*> >
00920           RenameSetType;
00921   for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
00922        I != E; ++I) {
00923     for (std::map<unsigned, MachineBasicBlock*>::iterator
00924          OI = I->second.begin(), OE = I->second.end(); OI != OE; ) {
00925       if (!seen.count(OI->first)) {
00926         seen.insert(OI->first);
00927         ++OI;
00928       } else {
00929         Waiting[OI->second].insert(std::make_pair(OI->first, I->first));
00930         unsigned reg = OI->first;
00931         ++OI;
00932         I->second.erase(reg);
00933         DOUT << "Removing Renaming: " << reg << " -> " << I->first << "\n";
00934       }
00935     }
00936   }
00937   
00938   // Insert copies
00939   // FIXME: This process should probably preserve LiveIntervals
00940   SmallPtrSet<MachineBasicBlock*, 16> visited;
00941   MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
00942   InsertCopies(MDT.getRootNode(), visited);
00943   
00944   // Perform renaming
00945   for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
00946        I != E; ++I)
00947     while (I->second.size()) {
00948       std::map<unsigned, MachineBasicBlock*>::iterator SI = I->second.begin();
00949       
00950       DOUT << "Renaming: " << SI->first << " -> " << I->first << "\n";
00951       
00952       if (SI->first != I->first) {
00953         if (mergeLiveIntervals(I->first, SI->first)) {
00954           Fn.getRegInfo().replaceRegWith(SI->first, I->first);
00955       
00956           if (RenameSets.count(SI->first)) {
00957             I->second.insert(RenameSets[SI->first].begin(),
00958                              RenameSets[SI->first].end());
00959             RenameSets.erase(SI->first);
00960           }
00961         } else {
00962           // Insert a last-minute copy if a conflict was detected.
00963           const TargetInstrInfo *TII = Fn.getTarget().getInstrInfo();
00964           const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(I->first);
00965           TII->copyRegToReg(*SI->second, SI->second->getFirstTerminator(),
00966                             I->first, SI->first, RC, RC);
00967           
00968           LI.computeNumbering();
00969           
00970           LiveInterval& Int = LI.getOrCreateInterval(I->first);
00971           unsigned instrIdx =
00972                      LI.getInstructionIndex(--SI->second->getFirstTerminator());
00973           if (Int.liveAt(LiveIntervals::getDefIndex(instrIdx)))
00974             Int.removeRange(LiveIntervals::getDefIndex(instrIdx),
00975                             LI.getMBBEndIdx(SI->second)+1, true);
00976 
00977           LiveRange R = LI.addLiveRangeToEndOfBlock(I->first,
00978                                             --SI->second->getFirstTerminator());
00979           R.valno->copy = --SI->second->getFirstTerminator();
00980           R.valno->def = LiveIntervals::getDefIndex(instrIdx);
00981           
00982           DOUT << "Renaming failed: " << SI->first << " -> "
00983                << I->first << "\n";
00984         }
00985       }
00986       
00987       LiveInterval& Int = LI.getOrCreateInterval(I->first);
00988       const LiveRange* LR =
00989                        Int.getLiveRangeContaining(LI.getMBBEndIdx(SI->second));
00990       LR->valno->hasPHIKill = true;
00991       
00992       I->second.erase(SI->first);
00993     }
00994   
00995   // Remove PHIs
00996   std::vector<MachineInstr*> phis;
00997   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
00998     for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
00999          BI != BE; ++BI)
01000       if (BI->getOpcode() == TargetInstrInfo::PHI)
01001         phis.push_back(BI);
01002   }
01003   
01004   for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
01005        I != E; ) {
01006     MachineInstr* PInstr = *(I++);
01007     
01008     // If this is a dead PHI node, then remove it from LiveIntervals.
01009     unsigned DestReg = PInstr->getOperand(0).getReg();
01010     LiveInterval& PI = LI.getInterval(DestReg);
01011     if (PInstr->registerDefIsDead(DestReg)) {
01012       if (PI.containsOneValue()) {
01013         LI.removeInterval(DestReg);
01014       } else {
01015         unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
01016         PI.removeRange(*PI.getLiveRangeContaining(idx), true);
01017       }
01018     } else {
01019       // Trim live intervals of input registers.  They are no longer live into
01020       // this block if they died after the PHI.  If they lived after it, don't
01021       // trim them because they might have other legitimate uses.
01022       for (unsigned i = 1; i < PInstr->getNumOperands(); i += 2) {
01023         unsigned reg = PInstr->getOperand(i).getReg();
01024         
01025         MachineBasicBlock* MBB = PInstr->getOperand(i+1).getMBB();
01026         LiveInterval& InputI = LI.getInterval(reg);
01027         if (MBB != PInstr->getParent() &&
01028             InputI.liveAt(LI.getMBBStartIdx(PInstr->getParent())) &&
01029             InputI.expiredAt(LI.getInstructionIndex(PInstr) + 
01030                              LiveIntervals::InstrSlots::NUM))
01031           InputI.removeRange(LI.getMBBStartIdx(PInstr->getParent()),
01032                              LI.getInstructionIndex(PInstr),
01033                              true);
01034       }
01035       
01036       // If the PHI is not dead, then the valno defined by the PHI
01037       // now has an unknown def.
01038       unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
01039       const LiveRange* PLR = PI.getLiveRangeContaining(idx);
01040       PLR->valno->def = ~0U;
01041       LiveRange R (LI.getMBBStartIdx(PInstr->getParent()),
01042                    PLR->start, PLR->valno);
01043       PI.addRange(R);
01044     }
01045     
01046     LI.RemoveMachineInstrFromMaps(PInstr);
01047     PInstr->eraseFromParent();
01048   }
01049   
01050   LI.computeNumbering();
01051   
01052   return true;
01053 }