1 //===- StrongPhiElimination.cpp - Eliminate PHI nodes by inserting copies -===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass eliminates machine instruction PHI nodes by inserting copy
11 // instructions, using an intelligent copy-folding technique based on
12 // dominator information. This is technique is derived from:
14 // Budimlic, et al. Fast copy coalescing and live-range identification.
15 // In Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language
16 // Design and Implementation (Berlin, Germany, June 17 - 19, 2002).
17 // PLDI '02. ACM, New York, NY, 25-32.
18 // DOI= http://doi.acm.org/10.1145/512529.512534
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "strongphielim"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/ADT/DepthFirstIterator.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Compiler.h"
38 struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
39 static char ID; // Pass identification, replacement for typeid
40 StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
42 // Waiting stores, for each MBB, the set of copies that need to
43 // be inserted into that MBB
44 DenseMap<MachineBasicBlock*,
45 std::map<unsigned, unsigned> > Waiting;
47 // Stacks holds the renaming stack for each register
48 std::map<unsigned, std::vector<unsigned> > Stacks;
50 // Registers in UsedByAnother are PHI nodes that are themselves
51 // used as operands to another another PHI node
52 std::set<unsigned> UsedByAnother;
54 // RenameSets are the sets of operands (and their VNInfo IDs) to a PHI
55 // (the defining instruction of the key) that can be renamed without copies.
56 std::map<unsigned, std::map<unsigned, unsigned> > RenameSets;
58 // PhiValueNumber holds the ID numbers of the VNs for each phi that we're
59 // eliminating, indexed by the register defined by that phi.
60 std::map<unsigned, unsigned> PhiValueNumber;
62 // Store the DFS-in number of each block
63 DenseMap<MachineBasicBlock*, unsigned> preorder;
65 // Store the DFS-out number of each block
66 DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
68 bool runOnMachineFunction(MachineFunction &Fn);
70 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
71 AU.addRequired<MachineDominatorTree>();
72 AU.addRequired<LiveIntervals>();
74 // TODO: Actually make this true.
75 AU.addPreserved<LiveIntervals>();
76 MachineFunctionPass::getAnalysisUsage(AU);
79 virtual void releaseMemory() {
85 UsedByAnother.clear();
91 /// DomForestNode - Represents a node in the "dominator forest". This is
92 /// a forest in which the nodes represent registers and the edges
93 /// represent a dominance relation in the block defining those registers.
94 struct DomForestNode {
96 // Store references to our children
97 std::vector<DomForestNode*> children;
98 // The register we represent
101 // Add another node as our child
102 void addChild(DomForestNode* DFN) { children.push_back(DFN); }
105 typedef std::vector<DomForestNode*>::iterator iterator;
107 // Create a DomForestNode by providing the register it represents, and
108 // the node to be its parent. The virtual root node has register 0
109 // and a null parent.
110 DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
112 parent->addChild(this);
116 for (iterator I = begin(), E = end(); I != E; ++I)
120 /// getReg - Return the regiser that this node represents
121 inline unsigned getReg() { return reg; }
123 // Provide iterator access to our children
124 inline DomForestNode::iterator begin() { return children.begin(); }
125 inline DomForestNode::iterator end() { return children.end(); }
128 void computeDFS(MachineFunction& MF);
129 void processBlock(MachineBasicBlock* MBB);
131 std::vector<DomForestNode*> computeDomForest(std::map<unsigned, unsigned>& instrs,
132 MachineRegisterInfo& MRI);
133 void processPHIUnion(MachineInstr* Inst,
134 std::map<unsigned, unsigned>& PHIUnion,
135 std::vector<StrongPHIElimination::DomForestNode*>& DF,
136 std::vector<std::pair<unsigned, unsigned> >& locals);
137 void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
138 void InsertCopies(MachineBasicBlock* MBB, std::set<MachineBasicBlock*>& v);
139 void mergeLiveIntervals(unsigned primary, unsigned secondary, unsigned VN);
142 char StrongPHIElimination::ID = 0;
143 RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
144 "Eliminate PHI nodes for register allocation, intelligently");
147 const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
149 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
150 /// of the given MachineFunction. These numbers are then used in other parts
151 /// of the PHI elimination process.
152 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
153 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
154 SmallPtrSet<MachineDomTreeNode*, 8> visited;
158 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
160 MachineDomTreeNode* node = DT.getRootNode();
162 std::vector<MachineDomTreeNode*> worklist;
163 worklist.push_back(node);
165 while (!worklist.empty()) {
166 MachineDomTreeNode* currNode = worklist.back();
168 if (!frontier.count(currNode)) {
169 frontier.insert(currNode);
171 preorder.insert(std::make_pair(currNode->getBlock(), time));
174 bool inserted = false;
175 for (MachineDomTreeNode::iterator I = node->begin(), E = node->end();
177 if (!frontier.count(*I) && !visited.count(*I)) {
178 worklist.push_back(*I);
184 frontier.erase(currNode);
185 visited.insert(currNode);
186 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
193 /// PreorderSorter - a helper class that is used to sort registers
194 /// according to the preorder number of their defining blocks
195 class PreorderSorter {
197 DenseMap<MachineBasicBlock*, unsigned>& preorder;
198 MachineRegisterInfo& MRI;
201 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
202 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
204 bool operator()(unsigned A, unsigned B) {
208 MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
209 MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
211 if (preorder[ABlock] < preorder[BBlock])
213 else if (preorder[ABlock] > preorder[BBlock])
220 /// computeDomForest - compute the subforest of the DomTree corresponding
221 /// to the defining blocks of the registers in question
222 std::vector<StrongPHIElimination::DomForestNode*>
223 StrongPHIElimination::computeDomForest(std::map<unsigned, unsigned>& regs,
224 MachineRegisterInfo& MRI) {
225 // Begin by creating a virtual root node, since the actual results
226 // may well be a forest. Assume this node has maximum DFS-out number.
227 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
228 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
230 // Populate a worklist with the registers
231 std::vector<unsigned> worklist;
232 worklist.reserve(regs.size());
233 for (std::map<unsigned, unsigned>::iterator I = regs.begin(), E = regs.end();
235 worklist.push_back(I->first);
237 // Sort the registers by the DFS-in number of their defining block
238 PreorderSorter PS(preorder, MRI);
239 std::sort(worklist.begin(), worklist.end(), PS);
241 // Create a "current parent" stack, and put the virtual root on top of it
242 DomForestNode* CurrentParent = VirtualRoot;
243 std::vector<DomForestNode*> stack;
244 stack.push_back(VirtualRoot);
246 // Iterate over all the registers in the previously computed order
247 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
249 unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
250 MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
251 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
254 // If the DFS-in number of the register is greater than the DFS-out number
255 // of the current parent, repeatedly pop the parent stack until it isn't.
256 while (pre > maxpreorder[parentBlock]) {
258 CurrentParent = stack.back();
260 parentBlock = CurrentParent->getReg() ?
261 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
265 // Now that we've found the appropriate parent, create a DomForestNode for
266 // this register and attach it to the forest
267 DomForestNode* child = new DomForestNode(*I, CurrentParent);
269 // Push this new node on the "current parent" stack
270 stack.push_back(child);
271 CurrentParent = child;
274 // Return a vector containing the children of the virtual root node
275 std::vector<DomForestNode*> ret;
276 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
280 /// isLiveIn - helper method that determines, from a regno, if a register
281 /// is live into a block
282 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
284 LiveInterval& I = LI.getOrCreateInterval(r);
285 unsigned idx = LI.getMBBStartIdx(MBB);
286 return I.liveBeforeAndAt(idx);
289 /// isLiveOut - help method that determines, from a regno, if a register is
290 /// live out of a block.
291 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
293 for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
294 E = MBB->succ_end(); PI != E; ++PI) {
295 if (isLiveIn(r, *PI, LI))
302 /// interferes - checks for local interferences by scanning a block. The only
303 /// trick parameter is 'mode' which tells it the relationship of the two
304 /// registers. 0 - defined in the same block, 1 - first properly dominates
305 /// second, 2 - second properly dominates first
306 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
307 LiveIntervals& LV, unsigned mode) {
308 MachineInstr* def = 0;
309 MachineInstr* kill = 0;
311 // The code is still in SSA form at this point, so there is only one
312 // definition per VReg. Thus we can safely use MRI->getVRegDef().
313 const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
315 bool interference = false;
317 // Wallk the block, checking for interferences
318 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
320 MachineInstr* curr = MBI;
322 // Same defining block...
324 if (curr == MRI->getVRegDef(a)) {
325 // If we find our first definition, save it
328 // If there's already an unkilled definition, then
329 // this is an interference
333 // If there's a definition followed by a KillInst, then
334 // they can't interfere
336 interference = false;
339 // Symmetric with the above
340 } else if (curr == MRI->getVRegDef(b)) {
347 interference = false;
350 // Store KillInsts if they match up with the definition
351 } else if (curr->killsRegister(a)) {
352 if (def == MRI->getVRegDef(a)) {
354 } else if (curr->killsRegister(b)) {
355 if (def == MRI->getVRegDef(b)) {
360 // First properly dominates second...
361 } else if (mode == 1) {
362 if (curr == MRI->getVRegDef(b)) {
363 // Definition of second without kill of first is an interference
367 // Definition after a kill is a non-interference
369 interference = false;
372 // Save KillInsts of First
373 } else if (curr->killsRegister(a)) {
376 // Symmetric with the above
377 } else if (mode == 2) {
378 if (curr == MRI->getVRegDef(a)) {
383 interference = false;
386 } else if (curr->killsRegister(b)) {
395 /// processBlock - Determine how to break up PHIs in the current block. Each
396 /// PHI is broken up by some combination of renaming its operands and inserting
397 /// copies. This method is responsible for determining which operands receive
399 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
400 LiveIntervals& LI = getAnalysis<LiveIntervals>();
401 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
403 // Holds names that have been added to a set in any PHI within this block
404 // before the current one.
405 std::set<unsigned> ProcessedNames;
407 // Iterate over all the PHI nodes in this block
408 MachineBasicBlock::iterator P = MBB->begin();
409 while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
410 unsigned DestReg = P->getOperand(0).getReg();
412 LiveInterval& PI = LI.getOrCreateInterval(DestReg);
413 unsigned pIdx = LI.getInstructionIndex(P);
414 VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
415 PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
417 // PHIUnion is the set of incoming registers to the PHI node that
418 // are going to be renames rather than having copies inserted. This set
419 // is refinded over the course of this function. UnionedBlocks is the set
420 // of corresponding MBBs.
421 std::map<unsigned, unsigned> PHIUnion;
422 std::set<MachineBasicBlock*> UnionedBlocks;
424 // Iterate over the operands of the PHI node
425 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
426 unsigned SrcReg = P->getOperand(i-1).getReg();
428 // Check for trivial interferences via liveness information, allowing us
429 // to avoid extra work later. Any registers that interfere cannot both
430 // be in the renaming set, so choose one and add copies for it instead.
431 // The conditions are:
432 // 1) if the operand is live into the PHI node's block OR
433 // 2) if the PHI node is live out of the operand's defining block OR
434 // 3) if the operand is itself a PHI node and the original PHI is
435 // live into the operand's defining block OR
436 // 4) if the operand is already being renamed for another PHI node
438 // 5) if any two operands are defined in the same block, insert copies
440 if (isLiveIn(SrcReg, P->getParent(), LI) ||
441 isLiveOut(P->getOperand(0).getReg(),
442 MRI.getVRegDef(SrcReg)->getParent(), LI) ||
443 ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
444 isLiveIn(P->getOperand(0).getReg(),
445 MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
446 ProcessedNames.count(SrcReg) ||
447 UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
449 // Add a copy for the selected register
450 MachineBasicBlock* From = P->getOperand(i).getMBB();
451 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
452 UsedByAnother.insert(SrcReg);
454 // Otherwise, add it to the renaming set
455 LiveInterval& I = LI.getOrCreateInterval(SrcReg);
456 unsigned idx = LI.getMBBEndIdx(P->getOperand(i).getMBB());
457 VNInfo* VN = I.getLiveRangeContaining(idx)->valno;
459 assert(VN && "No VNInfo for register?");
461 PHIUnion.insert(std::make_pair(SrcReg, VN->id));
462 UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
466 // Compute the dominator forest for the renaming set. This is a forest
467 // where the nodes are the registers and the edges represent dominance
468 // relations between the defining blocks of the registers
469 std::vector<StrongPHIElimination::DomForestNode*> DF =
470 computeDomForest(PHIUnion, MRI);
472 // Walk DomForest to resolve interferences at an inter-block level. This
473 // will remove registers from the renaming set (and insert copies for them)
474 // if interferences are found.
475 std::vector<std::pair<unsigned, unsigned> > localInterferences;
476 processPHIUnion(P, PHIUnion, DF, localInterferences);
478 // The dominator forest walk may have returned some register pairs whose
479 // interference cannot be determines from dominator analysis. We now
480 // examine these pairs for local interferences.
481 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
482 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
483 std::pair<unsigned, unsigned> p = *I;
485 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
487 // Determine the block we need to scan and the relationship between
489 MachineBasicBlock* scan = 0;
491 if (MRI.getVRegDef(p.first)->getParent() ==
492 MRI.getVRegDef(p.second)->getParent()) {
493 scan = MRI.getVRegDef(p.first)->getParent();
494 mode = 0; // Same block
495 } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
496 MRI.getVRegDef(p.second)->getParent())) {
497 scan = MRI.getVRegDef(p.second)->getParent();
498 mode = 1; // First dominates second
500 scan = MRI.getVRegDef(p.first)->getParent();
501 mode = 2; // Second dominates first
504 // If there's an interference, we need to insert copies
505 if (interferes(p.first, p.second, scan, LI, mode)) {
506 // Insert copies for First
507 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
508 if (P->getOperand(i-1).getReg() == p.first) {
509 unsigned SrcReg = p.first;
510 MachineBasicBlock* From = P->getOperand(i).getMBB();
512 Waiting[From].insert(std::make_pair(SrcReg,
513 P->getOperand(0).getReg()));
514 UsedByAnother.insert(SrcReg);
516 PHIUnion.erase(SrcReg);
522 // Add the renaming set for this PHI node to our overal renaming information
523 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
525 // Remember which registers are already renamed, so that we don't try to
526 // rename them for another PHI node in this block
527 for (std::map<unsigned, unsigned>::iterator I = PHIUnion.begin(),
528 E = PHIUnion.end(); I != E; ++I)
529 ProcessedNames.insert(I->first);
535 /// processPHIUnion - Take a set of candidate registers to be coalesced when
536 /// decomposing the PHI instruction. Use the DominanceForest to remove the ones
537 /// that are known to interfere, and flag others that need to be checked for
538 /// local interferences.
539 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
540 std::map<unsigned, unsigned>& PHIUnion,
541 std::vector<StrongPHIElimination::DomForestNode*>& DF,
542 std::vector<std::pair<unsigned, unsigned> >& locals) {
544 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
545 SmallPtrSet<DomForestNode*, 4> visited;
547 // Code is still in SSA form, so we can use MRI::getVRegDef()
548 MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
550 LiveIntervals& LI = getAnalysis<LiveIntervals>();
551 unsigned DestReg = Inst->getOperand(0).getReg();
553 // DF walk on the DomForest
554 while (!worklist.empty()) {
555 DomForestNode* DFNode = worklist.back();
557 visited.insert(DFNode);
559 bool inserted = false;
560 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
562 DomForestNode* child = *CI;
564 // If the current node is live-out of the defining block of one of its
565 // children, insert a copy for it. NOTE: The paper actually calls for
566 // a more elaborate heuristic for determining whether to insert copies
567 // for the child or the parent. In the interest of simplicity, we're
568 // just always choosing the parent.
569 if (isLiveOut(DFNode->getReg(),
570 MRI.getVRegDef(child->getReg())->getParent(), LI)) {
571 // Insert copies for parent
572 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
573 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
574 unsigned SrcReg = DFNode->getReg();
575 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
577 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
578 UsedByAnother.insert(SrcReg);
580 PHIUnion.erase(SrcReg);
584 // If a node is live-in to the defining block of one of its children, but
585 // not live-out, then we need to scan that block for local interferences.
586 } else if (isLiveIn(DFNode->getReg(),
587 MRI.getVRegDef(child->getReg())->getParent(), LI) ||
588 MRI.getVRegDef(DFNode->getReg())->getParent() ==
589 MRI.getVRegDef(child->getReg())->getParent()) {
590 // Add (p, c) to possible local interferences
591 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
594 if (!visited.count(child)) {
595 worklist.push_back(child);
600 if (!inserted) worklist.pop_back();
604 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
605 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
608 /// Based on "Practical Improvements to the Construction and Destruction
609 /// of Static Single Assignment Form" by Briggs, et al.
610 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
611 std::set<unsigned>& pushed) {
612 // FIXME: This function needs to update LiveVariables
613 std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
615 std::map<unsigned, unsigned> worklist;
616 std::map<unsigned, unsigned> map;
618 // Setup worklist of initial copies
619 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
620 E = copy_set.end(); I != E; ) {
621 map.insert(std::make_pair(I->first, I->first));
622 map.insert(std::make_pair(I->second, I->second));
624 if (!UsedByAnother.count(I->first)) {
627 // Avoid iterator invalidation
628 unsigned first = I->first;
630 copy_set.erase(first);
636 LiveIntervals& LI = getAnalysis<LiveIntervals>();
637 MachineFunction* MF = MBB->getParent();
638 MachineRegisterInfo& MRI = MF->getRegInfo();
639 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
641 // Iterate over the worklist, inserting copies
642 while (!worklist.empty() || !copy_set.empty()) {
643 while (!worklist.empty()) {
644 std::pair<unsigned, unsigned> curr = *worklist.begin();
645 worklist.erase(curr.first);
647 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
649 if (isLiveOut(curr.second, MBB, LI)) {
650 // Create a temporary
651 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
653 // Insert copy from curr.second to a temporary at
654 // the Phi defining curr.second
655 MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
656 TII->copyRegToReg(*PI->getParent(), PI, t,
657 curr.second, RC, RC);
659 // Push temporary on Stacks
660 Stacks[curr.second].push_back(t);
662 // Insert curr.second in pushed
663 pushed.insert(curr.second);
666 // Insert copy from map[curr.first] to curr.second
667 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
668 map[curr.first], RC, RC);
669 map[curr.first] = curr.second;
671 // If curr.first is a destination in copy_set...
672 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
673 E = copy_set.end(); I != E; )
674 if (curr.first == I->second) {
675 std::pair<unsigned, unsigned> temp = *I;
677 // Avoid iterator invalidation
679 copy_set.erase(temp.first);
680 worklist.insert(temp);
688 if (!copy_set.empty()) {
689 std::pair<unsigned, unsigned> curr = *copy_set.begin();
690 copy_set.erase(curr.first);
692 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
694 // Insert a copy from dest to a new temporary t at the end of b
695 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
696 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
697 curr.second, RC, RC);
698 map[curr.second] = t;
700 worklist.insert(curr);
705 /// InsertCopies - insert copies into MBB and all of its successors
706 void StrongPHIElimination::InsertCopies(MachineBasicBlock* MBB,
707 std::set<MachineBasicBlock*>& visited) {
710 std::set<unsigned> pushed;
712 // Rewrite register uses from Stacks
713 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
715 for (unsigned i = 0; i < I->getNumOperands(); ++i)
716 if (I->getOperand(i).isRegister() &&
717 Stacks[I->getOperand(i).getReg()].size()) {
718 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
721 // Schedule the copies for this block
722 ScheduleCopies(MBB, pushed);
724 // Recur to our successors
725 for (GraphTraits<MachineBasicBlock*>::ChildIteratorType I =
726 GraphTraits<MachineBasicBlock*>::child_begin(MBB), E =
727 GraphTraits<MachineBasicBlock*>::child_end(MBB); I != E; ++I)
728 if (!visited.count(*I))
729 InsertCopies(*I, visited);
731 // As we exit this block, pop the names we pushed while processing it
732 for (std::set<unsigned>::iterator I = pushed.begin(),
733 E = pushed.end(); I != E; ++I)
734 Stacks[*I].pop_back();
737 void StrongPHIElimination::mergeLiveIntervals(unsigned primary,
738 unsigned secondary, unsigned VN) {
739 // FIXME: Update LiveIntervals
742 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
743 // Compute DFS numbers of each block
746 // Determine which phi node operands need copies
747 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
749 I->begin()->getOpcode() == TargetInstrInfo::PHI)
753 // FIXME: This process should probably preserve LiveVariables
754 std::set<MachineBasicBlock*> visited;
755 InsertCopies(Fn.begin(), visited);
758 typedef std::map<unsigned, std::map<unsigned, unsigned> > RenameSetType;
759 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
761 for (std::map<unsigned, unsigned>::iterator SI = I->second.begin(),
762 SE = I->second.end(); SI != SE; ++SI) {
763 mergeLiveIntervals(I->first, SI->first, SI->second);
764 Fn.getRegInfo().replaceRegWith(SI->first, I->first);
767 // FIXME: Insert last-minute copies
770 std::vector<MachineInstr*> phis;
771 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
772 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
774 if (BI->getOpcode() == TargetInstrInfo::PHI)
778 for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
780 (*I)->eraseFromParent();