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/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/RegisterCoalescer.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/ADT/DepthFirstIterator.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Support/Compiler.h"
39 struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
40 static char ID; // Pass identification, replacement for typeid
41 StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
43 // Waiting stores, for each MBB, the set of copies that need to
44 // be inserted into that MBB
45 DenseMap<MachineBasicBlock*,
46 std::map<unsigned, unsigned> > Waiting;
48 // Stacks holds the renaming stack for each register
49 std::map<unsigned, std::vector<unsigned> > Stacks;
51 // Registers in UsedByAnother are PHI nodes that are themselves
52 // used as operands to another another PHI node
53 std::set<unsigned> UsedByAnother;
55 // RenameSets are the is a map from a PHI-defined register
56 // to the input registers to be coalesced along with the index
57 // of the input registers.
58 std::map<unsigned, std::map<unsigned, unsigned> > RenameSets;
60 // PhiValueNumber holds the ID numbers of the VNs for each phi that we're
61 // eliminating, indexed by the register defined by that phi.
62 std::map<unsigned, unsigned> PhiValueNumber;
64 // Store the DFS-in number of each block
65 DenseMap<MachineBasicBlock*, unsigned> preorder;
67 // Store the DFS-out number of each block
68 DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
70 bool runOnMachineFunction(MachineFunction &Fn);
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.addRequired<MachineDominatorTree>();
74 AU.addRequired<LiveIntervals>();
76 // TODO: Actually make this true.
77 AU.addPreserved<LiveIntervals>();
78 AU.addPreserved<RegisterCoalescer>();
79 MachineFunctionPass::getAnalysisUsage(AU);
82 virtual void releaseMemory() {
88 UsedByAnother.clear();
94 /// DomForestNode - Represents a node in the "dominator forest". This is
95 /// a forest in which the nodes represent registers and the edges
96 /// represent a dominance relation in the block defining those registers.
97 struct DomForestNode {
99 // Store references to our children
100 std::vector<DomForestNode*> children;
101 // The register we represent
104 // Add another node as our child
105 void addChild(DomForestNode* DFN) { children.push_back(DFN); }
108 typedef std::vector<DomForestNode*>::iterator iterator;
110 // Create a DomForestNode by providing the register it represents, and
111 // the node to be its parent. The virtual root node has register 0
112 // and a null parent.
113 DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
115 parent->addChild(this);
119 for (iterator I = begin(), E = end(); I != E; ++I)
123 /// getReg - Return the regiser that this node represents
124 inline unsigned getReg() { return reg; }
126 // Provide iterator access to our children
127 inline DomForestNode::iterator begin() { return children.begin(); }
128 inline DomForestNode::iterator end() { return children.end(); }
131 void computeDFS(MachineFunction& MF);
132 void processBlock(MachineBasicBlock* MBB);
134 std::vector<DomForestNode*> computeDomForest(std::map<unsigned, unsigned>& instrs,
135 MachineRegisterInfo& MRI);
136 void processPHIUnion(MachineInstr* Inst,
137 std::map<unsigned, unsigned>& PHIUnion,
138 std::vector<StrongPHIElimination::DomForestNode*>& DF,
139 std::vector<std::pair<unsigned, unsigned> >& locals);
140 void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
141 void InsertCopies(MachineBasicBlock* MBB,
142 SmallPtrSet<MachineBasicBlock*, 16>& v);
143 void mergeLiveIntervals(unsigned primary, unsigned secondary, unsigned VN);
147 char StrongPHIElimination::ID = 0;
148 static RegisterPass<StrongPHIElimination>
149 X("strong-phi-node-elimination",
150 "Eliminate PHI nodes for register allocation, intelligently");
152 const PassInfo *const llvm::StrongPHIEliminationID = &X;
154 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
155 /// of the given MachineFunction. These numbers are then used in other parts
156 /// of the PHI elimination process.
157 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
158 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
159 SmallPtrSet<MachineDomTreeNode*, 8> visited;
163 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
165 MachineDomTreeNode* node = DT.getRootNode();
167 std::vector<MachineDomTreeNode*> worklist;
168 worklist.push_back(node);
170 while (!worklist.empty()) {
171 MachineDomTreeNode* currNode = worklist.back();
173 if (!frontier.count(currNode)) {
174 frontier.insert(currNode);
176 preorder.insert(std::make_pair(currNode->getBlock(), time));
179 bool inserted = false;
180 for (MachineDomTreeNode::iterator I = currNode->begin(), E = currNode->end();
182 if (!frontier.count(*I) && !visited.count(*I)) {
183 worklist.push_back(*I);
189 frontier.erase(currNode);
190 visited.insert(currNode);
191 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
200 /// PreorderSorter - a helper class that is used to sort registers
201 /// according to the preorder number of their defining blocks
202 class PreorderSorter {
204 DenseMap<MachineBasicBlock*, unsigned>& preorder;
205 MachineRegisterInfo& MRI;
208 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
209 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
211 bool operator()(unsigned A, unsigned B) {
215 MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
216 MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
218 if (preorder[ABlock] < preorder[BBlock])
220 else if (preorder[ABlock] > preorder[BBlock])
229 /// computeDomForest - compute the subforest of the DomTree corresponding
230 /// to the defining blocks of the registers in question
231 std::vector<StrongPHIElimination::DomForestNode*>
232 StrongPHIElimination::computeDomForest(std::map<unsigned, unsigned>& regs,
233 MachineRegisterInfo& MRI) {
234 // Begin by creating a virtual root node, since the actual results
235 // may well be a forest. Assume this node has maximum DFS-out number.
236 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
237 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
239 // Populate a worklist with the registers
240 std::vector<unsigned> worklist;
241 worklist.reserve(regs.size());
242 for (std::map<unsigned, unsigned>::iterator I = regs.begin(), E = regs.end();
244 worklist.push_back(I->first);
246 // Sort the registers by the DFS-in number of their defining block
247 PreorderSorter PS(preorder, MRI);
248 std::sort(worklist.begin(), worklist.end(), PS);
250 // Create a "current parent" stack, and put the virtual root on top of it
251 DomForestNode* CurrentParent = VirtualRoot;
252 std::vector<DomForestNode*> stack;
253 stack.push_back(VirtualRoot);
255 // Iterate over all the registers in the previously computed order
256 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
258 unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
259 MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
260 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
263 // If the DFS-in number of the register is greater than the DFS-out number
264 // of the current parent, repeatedly pop the parent stack until it isn't.
265 while (pre > maxpreorder[parentBlock]) {
267 CurrentParent = stack.back();
269 parentBlock = CurrentParent->getReg() ?
270 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
274 // Now that we've found the appropriate parent, create a DomForestNode for
275 // this register and attach it to the forest
276 DomForestNode* child = new DomForestNode(*I, CurrentParent);
278 // Push this new node on the "current parent" stack
279 stack.push_back(child);
280 CurrentParent = child;
283 // Return a vector containing the children of the virtual root node
284 std::vector<DomForestNode*> ret;
285 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
289 /// isLiveIn - helper method that determines, from a regno, if a register
290 /// is live into a block
291 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
293 LiveInterval& I = LI.getOrCreateInterval(r);
294 unsigned idx = LI.getMBBStartIdx(MBB);
295 return I.liveBeforeAndAt(idx);
298 /// isLiveOut - help method that determines, from a regno, if a register is
299 /// live out of a block.
300 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
302 for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
303 E = MBB->succ_end(); PI != E; ++PI) {
304 if (isLiveIn(r, *PI, LI))
311 /// interferes - checks for local interferences by scanning a block. The only
312 /// trick parameter is 'mode' which tells it the relationship of the two
313 /// registers. 0 - defined in the same block, 1 - first properly dominates
314 /// second, 2 - second properly dominates first
315 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
316 LiveIntervals& LV, unsigned mode) {
317 MachineInstr* def = 0;
318 MachineInstr* kill = 0;
320 // The code is still in SSA form at this point, so there is only one
321 // definition per VReg. Thus we can safely use MRI->getVRegDef().
322 const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
324 bool interference = false;
326 // Wallk the block, checking for interferences
327 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
329 MachineInstr* curr = MBI;
331 // Same defining block...
333 if (curr == MRI->getVRegDef(a)) {
334 // If we find our first definition, save it
337 // If there's already an unkilled definition, then
338 // this is an interference
342 // If there's a definition followed by a KillInst, then
343 // they can't interfere
345 interference = false;
348 // Symmetric with the above
349 } else if (curr == MRI->getVRegDef(b)) {
356 interference = false;
359 // Store KillInsts if they match up with the definition
360 } else if (curr->killsRegister(a)) {
361 if (def == MRI->getVRegDef(a)) {
363 } else if (curr->killsRegister(b)) {
364 if (def == MRI->getVRegDef(b)) {
369 // First properly dominates second...
370 } else if (mode == 1) {
371 if (curr == MRI->getVRegDef(b)) {
372 // Definition of second without kill of first is an interference
376 // Definition after a kill is a non-interference
378 interference = false;
381 // Save KillInsts of First
382 } else if (curr->killsRegister(a)) {
385 // Symmetric with the above
386 } else if (mode == 2) {
387 if (curr == MRI->getVRegDef(a)) {
392 interference = false;
395 } else if (curr->killsRegister(b)) {
404 /// processBlock - Determine how to break up PHIs in the current block. Each
405 /// PHI is broken up by some combination of renaming its operands and inserting
406 /// copies. This method is responsible for determining which operands receive
408 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
409 LiveIntervals& LI = getAnalysis<LiveIntervals>();
410 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
412 // Holds names that have been added to a set in any PHI within this block
413 // before the current one.
414 std::set<unsigned> ProcessedNames;
416 // Iterate over all the PHI nodes in this block
417 MachineBasicBlock::iterator P = MBB->begin();
418 while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
419 unsigned DestReg = P->getOperand(0).getReg();
421 // Don't both doing PHI elimination for dead PHI's.
422 if (P->registerDefIsDead(DestReg)) {
427 LiveInterval& PI = LI.getOrCreateInterval(DestReg);
428 unsigned pIdx = LI.getDefIndex(LI.getInstructionIndex(P));
429 VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
430 PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
432 // PHIUnion is the set of incoming registers to the PHI node that
433 // are going to be renames rather than having copies inserted. This set
434 // is refinded over the course of this function. UnionedBlocks is the set
435 // of corresponding MBBs.
436 std::map<unsigned, unsigned> PHIUnion;
437 SmallPtrSet<MachineBasicBlock*, 8> UnionedBlocks;
439 // Iterate over the operands of the PHI node
440 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
441 unsigned SrcReg = P->getOperand(i-1).getReg();
443 // Check for trivial interferences via liveness information, allowing us
444 // to avoid extra work later. Any registers that interfere cannot both
445 // be in the renaming set, so choose one and add copies for it instead.
446 // The conditions are:
447 // 1) if the operand is live into the PHI node's block OR
448 // 2) if the PHI node is live out of the operand's defining block OR
449 // 3) if the operand is itself a PHI node and the original PHI is
450 // live into the operand's defining block OR
451 // 4) if the operand is already being renamed for another PHI node
453 // 5) if any two operands are defined in the same block, insert copies
455 if (isLiveIn(SrcReg, P->getParent(), LI) ||
456 isLiveOut(P->getOperand(0).getReg(),
457 MRI.getVRegDef(SrcReg)->getParent(), LI) ||
458 ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
459 isLiveIn(P->getOperand(0).getReg(),
460 MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
461 ProcessedNames.count(SrcReg) ||
462 UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
464 // Add a copy for the selected register
465 MachineBasicBlock* From = P->getOperand(i).getMBB();
466 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
467 UsedByAnother.insert(SrcReg);
469 // Otherwise, add it to the renaming set
470 // We need to subtract one from the index because live ranges are open
472 unsigned idx = LI.getMBBEndIdx(P->getOperand(i).getMBB()) - 1;
474 PHIUnion.insert(std::make_pair(SrcReg, idx));
475 UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
479 // Compute the dominator forest for the renaming set. This is a forest
480 // where the nodes are the registers and the edges represent dominance
481 // relations between the defining blocks of the registers
482 std::vector<StrongPHIElimination::DomForestNode*> DF =
483 computeDomForest(PHIUnion, MRI);
485 // Walk DomForest to resolve interferences at an inter-block level. This
486 // will remove registers from the renaming set (and insert copies for them)
487 // if interferences are found.
488 std::vector<std::pair<unsigned, unsigned> > localInterferences;
489 processPHIUnion(P, PHIUnion, DF, localInterferences);
491 // If one of the inputs is defined in the same block as the current PHI
492 // then we need to check for a local interference between that input and
494 for (std::map<unsigned, unsigned>::iterator I = PHIUnion.begin(),
495 E = PHIUnion.end(); I != E; ++I)
496 if (MRI.getVRegDef(I->first)->getParent() == P->getParent())
497 localInterferences.push_back(std::make_pair(I->first,
498 P->getOperand(0).getReg()));
500 // The dominator forest walk may have returned some register pairs whose
501 // interference cannot be determined from dominator analysis. We now
502 // examine these pairs for local interferences.
503 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
504 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
505 std::pair<unsigned, unsigned> p = *I;
507 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
509 // Determine the block we need to scan and the relationship between
511 MachineBasicBlock* scan = 0;
513 if (MRI.getVRegDef(p.first)->getParent() ==
514 MRI.getVRegDef(p.second)->getParent()) {
515 scan = MRI.getVRegDef(p.first)->getParent();
516 mode = 0; // Same block
517 } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
518 MRI.getVRegDef(p.second)->getParent())) {
519 scan = MRI.getVRegDef(p.second)->getParent();
520 mode = 1; // First dominates second
522 scan = MRI.getVRegDef(p.first)->getParent();
523 mode = 2; // Second dominates first
526 // If there's an interference, we need to insert copies
527 if (interferes(p.first, p.second, scan, LI, mode)) {
528 // Insert copies for First
529 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
530 if (P->getOperand(i-1).getReg() == p.first) {
531 unsigned SrcReg = p.first;
532 MachineBasicBlock* From = P->getOperand(i).getMBB();
534 Waiting[From].insert(std::make_pair(SrcReg,
535 P->getOperand(0).getReg()));
536 UsedByAnother.insert(SrcReg);
538 PHIUnion.erase(SrcReg);
544 // Add the renaming set for this PHI node to our overall renaming information
545 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
547 // Remember which registers are already renamed, so that we don't try to
548 // rename them for another PHI node in this block
549 for (std::map<unsigned, unsigned>::iterator I = PHIUnion.begin(),
550 E = PHIUnion.end(); I != E; ++I)
551 ProcessedNames.insert(I->first);
557 /// processPHIUnion - Take a set of candidate registers to be coalesced when
558 /// decomposing the PHI instruction. Use the DominanceForest to remove the ones
559 /// that are known to interfere, and flag others that need to be checked for
560 /// local interferences.
561 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
562 std::map<unsigned, unsigned>& PHIUnion,
563 std::vector<StrongPHIElimination::DomForestNode*>& DF,
564 std::vector<std::pair<unsigned, unsigned> >& locals) {
566 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
567 SmallPtrSet<DomForestNode*, 4> visited;
569 // Code is still in SSA form, so we can use MRI::getVRegDef()
570 MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
572 LiveIntervals& LI = getAnalysis<LiveIntervals>();
573 unsigned DestReg = Inst->getOperand(0).getReg();
575 // DF walk on the DomForest
576 while (!worklist.empty()) {
577 DomForestNode* DFNode = worklist.back();
579 visited.insert(DFNode);
581 bool inserted = false;
582 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
584 DomForestNode* child = *CI;
586 // If the current node is live-out of the defining block of one of its
587 // children, insert a copy for it. NOTE: The paper actually calls for
588 // a more elaborate heuristic for determining whether to insert copies
589 // for the child or the parent. In the interest of simplicity, we're
590 // just always choosing the parent.
591 if (isLiveOut(DFNode->getReg(),
592 MRI.getVRegDef(child->getReg())->getParent(), LI)) {
593 // Insert copies for parent
594 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
595 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
596 unsigned SrcReg = DFNode->getReg();
597 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
599 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
600 UsedByAnother.insert(SrcReg);
602 PHIUnion.erase(SrcReg);
606 // If a node is live-in to the defining block of one of its children, but
607 // not live-out, then we need to scan that block for local interferences.
608 } else if (isLiveIn(DFNode->getReg(),
609 MRI.getVRegDef(child->getReg())->getParent(), LI) ||
610 MRI.getVRegDef(DFNode->getReg())->getParent() ==
611 MRI.getVRegDef(child->getReg())->getParent()) {
612 // Add (p, c) to possible local interferences
613 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
616 if (!visited.count(child)) {
617 worklist.push_back(child);
622 if (!inserted) worklist.pop_back();
626 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
627 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
630 /// Based on "Practical Improvements to the Construction and Destruction
631 /// of Static Single Assignment Form" by Briggs, et al.
632 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
633 std::set<unsigned>& pushed) {
634 // FIXME: This function needs to update LiveIntervals
635 std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
637 std::map<unsigned, unsigned> worklist;
638 std::map<unsigned, unsigned> map;
640 // Setup worklist of initial copies
641 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
642 E = copy_set.end(); I != E; ) {
643 map.insert(std::make_pair(I->first, I->first));
644 map.insert(std::make_pair(I->second, I->second));
646 if (!UsedByAnother.count(I->second)) {
649 // Avoid iterator invalidation
650 unsigned first = I->first;
652 copy_set.erase(first);
658 LiveIntervals& LI = getAnalysis<LiveIntervals>();
659 MachineFunction* MF = MBB->getParent();
660 MachineRegisterInfo& MRI = MF->getRegInfo();
661 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
663 SmallVector<std::pair<unsigned, MachineInstr*>, 4> InsertedPHIDests;
665 // Iterate over the worklist, inserting copies
666 while (!worklist.empty() || !copy_set.empty()) {
667 while (!worklist.empty()) {
668 std::pair<unsigned, unsigned> curr = *worklist.begin();
669 worklist.erase(curr.first);
671 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
673 if (isLiveOut(curr.second, MBB, LI)) {
674 // Create a temporary
675 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
677 // Insert copy from curr.second to a temporary at
678 // the Phi defining curr.second
679 MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
680 TII->copyRegToReg(*PI->getParent(), PI, t,
681 curr.second, RC, RC);
683 // Push temporary on Stacks
684 Stacks[curr.second].push_back(t);
686 // Insert curr.second in pushed
687 pushed.insert(curr.second);
690 // Insert copy from map[curr.first] to curr.second
691 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
692 map[curr.first], RC, RC);
693 map[curr.first] = curr.second;
695 // Push this copy onto InsertedPHICopies so we can
696 // update LiveIntervals with it.
697 MachineBasicBlock::iterator MI = MBB->getFirstTerminator();
698 InsertedPHIDests.push_back(std::make_pair(curr.second, --MI));
700 // If curr.first is a destination in copy_set...
701 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
702 E = copy_set.end(); I != E; )
703 if (curr.first == I->second) {
704 std::pair<unsigned, unsigned> temp = *I;
706 // Avoid iterator invalidation
708 copy_set.erase(temp.first);
709 worklist.insert(temp);
717 if (!copy_set.empty()) {
718 std::pair<unsigned, unsigned> curr = *copy_set.begin();
719 copy_set.erase(curr.first);
721 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
723 // Insert a copy from dest to a new temporary t at the end of b
724 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
725 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
726 curr.second, RC, RC);
727 map[curr.second] = t;
729 worklist.insert(curr);
733 // Renumber the instructions so that we can perform the index computations
734 // needed to create new live intervals.
735 LI.computeNumbering();
737 // For copies that we inserted at the ends of predecessors, we construct
738 // live intervals. This is pretty easy, since we know that the destination
739 // register cannot have be in live at that point previously. We just have
740 // to make sure that, for registers that serve as inputs to more than one
741 // PHI, we don't create multiple overlapping live intervals.
742 std::set<unsigned> RegHandled;
743 for (SmallVector<std::pair<unsigned, MachineInstr*>, 4>::iterator I =
744 InsertedPHIDests.begin(), E = InsertedPHIDests.end(); I != E; ++I)
745 if (!RegHandled.count(I->first))
746 LI.addLiveRangeToEndOfBlock(I->first, I->second);
749 /// InsertCopies - insert copies into MBB and all of its successors
750 void StrongPHIElimination::InsertCopies(MachineBasicBlock* MBB,
751 SmallPtrSet<MachineBasicBlock*, 16>& visited) {
754 std::set<unsigned> pushed;
756 // Rewrite register uses from Stacks
757 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
759 for (unsigned i = 0; i < I->getNumOperands(); ++i)
760 if (I->getOperand(i).isRegister() &&
761 Stacks[I->getOperand(i).getReg()].size()) {
762 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
765 // Schedule the copies for this block
766 ScheduleCopies(MBB, pushed);
768 // Recur to our successors
769 for (GraphTraits<MachineBasicBlock*>::ChildIteratorType I =
770 GraphTraits<MachineBasicBlock*>::child_begin(MBB), E =
771 GraphTraits<MachineBasicBlock*>::child_end(MBB); I != E; ++I)
772 if (!visited.count(*I))
773 InsertCopies(*I, visited);
775 // As we exit this block, pop the names we pushed while processing it
776 for (std::set<unsigned>::iterator I = pushed.begin(),
777 E = pushed.end(); I != E; ++I)
778 Stacks[*I].pop_back();
781 void StrongPHIElimination::mergeLiveIntervals(unsigned primary,
783 unsigned secondaryIdx) {
785 LiveIntervals& LI = getAnalysis<LiveIntervals>();
786 LiveInterval& LHS = LI.getOrCreateInterval(primary);
787 LiveInterval& RHS = LI.getOrCreateInterval(secondary);
789 LI.computeNumbering();
791 const LiveRange* RangeMergingIn = RHS.getLiveRangeContaining(secondaryIdx);
792 VNInfo* NewVN = LHS.getNextValue(secondaryIdx, RangeMergingIn->valno->copy,
793 LI.getVNInfoAllocator());
794 NewVN->hasPHIKill = true;
795 LiveRange NewRange(RangeMergingIn->start, RangeMergingIn->end, NewVN);
796 LHS.addRange(NewRange);
797 RHS.removeRange(RangeMergingIn->start, RangeMergingIn->end, true);
800 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
801 LiveIntervals& LI = getAnalysis<LiveIntervals>();
803 // Compute DFS numbers of each block
806 // Determine which phi node operands need copies
807 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
809 I->begin()->getOpcode() == TargetInstrInfo::PHI)
813 // FIXME: This process should probably preserve LiveIntervals
814 SmallPtrSet<MachineBasicBlock*, 16> visited;
815 InsertCopies(Fn.begin(), visited);
818 typedef std::map<unsigned, std::map<unsigned, unsigned> > RenameSetType;
819 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
821 for (std::map<unsigned, unsigned>::iterator SI = I->second.begin(),
822 SE = I->second.end(); SI != SE; ++SI) {
823 mergeLiveIntervals(I->first, SI->first, SI->second);
824 Fn.getRegInfo().replaceRegWith(SI->first, I->first);
827 // FIXME: Insert last-minute copies
830 std::vector<MachineInstr*> phis;
831 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
832 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
834 if (BI->getOpcode() == TargetInstrInfo::PHI)
838 for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
840 MachineInstr* PInstr = *(I++);
842 // If this is a dead PHI node, then remove it from LiveIntervals.
843 unsigned DestReg = PInstr->getOperand(0).getReg();
844 LiveInterval& PI = LI.getInterval(DestReg);
845 if (PInstr->registerDefIsDead(DestReg)) {
846 if (PI.containsOneValue()) {
847 LI.removeInterval(DestReg);
849 unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
850 PI.removeRange(*PI.getLiveRangeContaining(idx), true);
853 // If the PHI is not dead, then the valno defined by the PHI
854 // now has an unknown def.
855 unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
856 PI.getLiveRangeContaining(idx)->valno->def = ~0U;
859 LI.RemoveMachineInstrFromMaps(PInstr);
860 PInstr->eraseFromParent();
863 LI.computeNumbering();