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/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/ADT/DepthFirstIterator.h"
33 #include "llvm/ADT/Statistic.h"
34 #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 sets of operands (and their VNInfo IDs) to a PHI
56 // (the defining instruction of the key) that can be renamed without copies.
57 std::map<unsigned, std::map<unsigned, unsigned> > RenameSets;
59 // PhiValueNumber holds the ID numbers of the VNs for each phi that we're
60 // eliminating, indexed by the register defined by that phi.
61 std::map<unsigned, unsigned> PhiValueNumber;
63 // Store the DFS-in number of each block
64 DenseMap<MachineBasicBlock*, unsigned> preorder;
66 // Store the DFS-out number of each block
67 DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
69 bool runOnMachineFunction(MachineFunction &Fn);
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72 AU.addRequired<MachineDominatorTree>();
73 AU.addRequired<LiveIntervals>();
75 // TODO: Actually make this true.
76 AU.addPreserved<LiveIntervals>();
77 MachineFunctionPass::getAnalysisUsage(AU);
80 virtual void releaseMemory() {
86 UsedByAnother.clear();
92 /// DomForestNode - Represents a node in the "dominator forest". This is
93 /// a forest in which the nodes represent registers and the edges
94 /// represent a dominance relation in the block defining those registers.
95 struct DomForestNode {
97 // Store references to our children
98 std::vector<DomForestNode*> children;
99 // The register we represent
102 // Add another node as our child
103 void addChild(DomForestNode* DFN) { children.push_back(DFN); }
106 typedef std::vector<DomForestNode*>::iterator iterator;
108 // Create a DomForestNode by providing the register it represents, and
109 // the node to be its parent. The virtual root node has register 0
110 // and a null parent.
111 DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
113 parent->addChild(this);
117 for (iterator I = begin(), E = end(); I != E; ++I)
121 /// getReg - Return the regiser that this node represents
122 inline unsigned getReg() { return reg; }
124 // Provide iterator access to our children
125 inline DomForestNode::iterator begin() { return children.begin(); }
126 inline DomForestNode::iterator end() { return children.end(); }
129 void computeDFS(MachineFunction& MF);
130 void processBlock(MachineBasicBlock* MBB);
132 std::vector<DomForestNode*> computeDomForest(std::map<unsigned, unsigned>& instrs,
133 MachineRegisterInfo& MRI);
134 void processPHIUnion(MachineInstr* Inst,
135 std::map<unsigned, unsigned>& PHIUnion,
136 std::vector<StrongPHIElimination::DomForestNode*>& DF,
137 std::vector<std::pair<unsigned, unsigned> >& locals);
138 void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
139 void InsertCopies(MachineBasicBlock* MBB, std::set<MachineBasicBlock*>& v);
140 void mergeLiveIntervals(unsigned primary, unsigned secondary, unsigned VN);
143 char StrongPHIElimination::ID = 0;
144 RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
145 "Eliminate PHI nodes for register allocation, intelligently");
148 const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
150 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
151 /// of the given MachineFunction. These numbers are then used in other parts
152 /// of the PHI elimination process.
153 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
154 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
155 SmallPtrSet<MachineDomTreeNode*, 8> visited;
159 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
161 MachineDomTreeNode* node = DT.getRootNode();
163 std::vector<MachineDomTreeNode*> worklist;
164 worklist.push_back(node);
166 while (!worklist.empty()) {
167 MachineDomTreeNode* currNode = worklist.back();
169 if (!frontier.count(currNode)) {
170 frontier.insert(currNode);
172 preorder.insert(std::make_pair(currNode->getBlock(), time));
175 bool inserted = false;
176 for (MachineDomTreeNode::iterator I = node->begin(), E = node->end();
178 if (!frontier.count(*I) && !visited.count(*I)) {
179 worklist.push_back(*I);
185 frontier.erase(currNode);
186 visited.insert(currNode);
187 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
194 /// PreorderSorter - a helper class that is used to sort registers
195 /// according to the preorder number of their defining blocks
196 class PreorderSorter {
198 DenseMap<MachineBasicBlock*, unsigned>& preorder;
199 MachineRegisterInfo& MRI;
202 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
203 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
205 bool operator()(unsigned A, unsigned B) {
209 MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
210 MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
212 if (preorder[ABlock] < preorder[BBlock])
214 else if (preorder[ABlock] > preorder[BBlock])
221 /// computeDomForest - compute the subforest of the DomTree corresponding
222 /// to the defining blocks of the registers in question
223 std::vector<StrongPHIElimination::DomForestNode*>
224 StrongPHIElimination::computeDomForest(std::map<unsigned, unsigned>& regs,
225 MachineRegisterInfo& MRI) {
226 // Begin by creating a virtual root node, since the actual results
227 // may well be a forest. Assume this node has maximum DFS-out number.
228 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
229 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
231 // Populate a worklist with the registers
232 std::vector<unsigned> worklist;
233 worklist.reserve(regs.size());
234 for (std::map<unsigned, unsigned>::iterator I = regs.begin(), E = regs.end();
236 worklist.push_back(I->first);
238 // Sort the registers by the DFS-in number of their defining block
239 PreorderSorter PS(preorder, MRI);
240 std::sort(worklist.begin(), worklist.end(), PS);
242 // Create a "current parent" stack, and put the virtual root on top of it
243 DomForestNode* CurrentParent = VirtualRoot;
244 std::vector<DomForestNode*> stack;
245 stack.push_back(VirtualRoot);
247 // Iterate over all the registers in the previously computed order
248 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
250 unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
251 MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
252 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
255 // If the DFS-in number of the register is greater than the DFS-out number
256 // of the current parent, repeatedly pop the parent stack until it isn't.
257 while (pre > maxpreorder[parentBlock]) {
259 CurrentParent = stack.back();
261 parentBlock = CurrentParent->getReg() ?
262 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
266 // Now that we've found the appropriate parent, create a DomForestNode for
267 // this register and attach it to the forest
268 DomForestNode* child = new DomForestNode(*I, CurrentParent);
270 // Push this new node on the "current parent" stack
271 stack.push_back(child);
272 CurrentParent = child;
275 // Return a vector containing the children of the virtual root node
276 std::vector<DomForestNode*> ret;
277 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
281 /// isLiveIn - helper method that determines, from a regno, if a register
282 /// is live into a block
283 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
285 LiveInterval& I = LI.getOrCreateInterval(r);
286 unsigned idx = LI.getMBBStartIdx(MBB);
287 return I.liveBeforeAndAt(idx);
290 /// isLiveOut - help method that determines, from a regno, if a register is
291 /// live out of a block.
292 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
294 for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
295 E = MBB->succ_end(); PI != E; ++PI) {
296 if (isLiveIn(r, *PI, LI))
303 /// interferes - checks for local interferences by scanning a block. The only
304 /// trick parameter is 'mode' which tells it the relationship of the two
305 /// registers. 0 - defined in the same block, 1 - first properly dominates
306 /// second, 2 - second properly dominates first
307 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
308 LiveIntervals& LV, unsigned mode) {
309 MachineInstr* def = 0;
310 MachineInstr* kill = 0;
312 // The code is still in SSA form at this point, so there is only one
313 // definition per VReg. Thus we can safely use MRI->getVRegDef().
314 const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
316 bool interference = false;
318 // Wallk the block, checking for interferences
319 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
321 MachineInstr* curr = MBI;
323 // Same defining block...
325 if (curr == MRI->getVRegDef(a)) {
326 // If we find our first definition, save it
329 // If there's already an unkilled definition, then
330 // this is an interference
334 // If there's a definition followed by a KillInst, then
335 // they can't interfere
337 interference = false;
340 // Symmetric with the above
341 } else if (curr == MRI->getVRegDef(b)) {
348 interference = false;
351 // Store KillInsts if they match up with the definition
352 } else if (curr->killsRegister(a)) {
353 if (def == MRI->getVRegDef(a)) {
355 } else if (curr->killsRegister(b)) {
356 if (def == MRI->getVRegDef(b)) {
361 // First properly dominates second...
362 } else if (mode == 1) {
363 if (curr == MRI->getVRegDef(b)) {
364 // Definition of second without kill of first is an interference
368 // Definition after a kill is a non-interference
370 interference = false;
373 // Save KillInsts of First
374 } else if (curr->killsRegister(a)) {
377 // Symmetric with the above
378 } else if (mode == 2) {
379 if (curr == MRI->getVRegDef(a)) {
384 interference = false;
387 } else if (curr->killsRegister(b)) {
396 /// processBlock - Determine how to break up PHIs in the current block. Each
397 /// PHI is broken up by some combination of renaming its operands and inserting
398 /// copies. This method is responsible for determining which operands receive
400 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
401 LiveIntervals& LI = getAnalysis<LiveIntervals>();
402 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
404 // Holds names that have been added to a set in any PHI within this block
405 // before the current one.
406 std::set<unsigned> ProcessedNames;
408 MachineBasicBlock::iterator FirstNonPHI = MBB->begin();
409 while (FirstNonPHI->getOpcode() == TargetInstrInfo::PHI) FirstNonPHI++;
411 // Iterate over all the PHI nodes in this block
412 MachineBasicBlock::iterator P = MBB->begin();
413 while (P != FirstNonPHI && P->getOpcode() == TargetInstrInfo::PHI) {
414 unsigned DestReg = P->getOperand(0).getReg();
416 LiveInterval& PI = LI.getOrCreateInterval(DestReg);
417 unsigned pIdx = LI.getInstructionIndex(FirstNonPHI);
418 VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
419 PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
421 // PHIUnion is the set of incoming registers to the PHI node that
422 // are going to be renames rather than having copies inserted. This set
423 // is refinded over the course of this function. UnionedBlocks is the set
424 // of corresponding MBBs.
425 std::map<unsigned, unsigned> PHIUnion;
426 std::set<MachineBasicBlock*> UnionedBlocks;
428 // Iterate over the operands of the PHI node
429 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
430 unsigned SrcReg = P->getOperand(i-1).getReg();
432 // Check for trivial interferences via liveness information, allowing us
433 // to avoid extra work later. Any registers that interfere cannot both
434 // be in the renaming set, so choose one and add copies for it instead.
435 // The conditions are:
436 // 1) if the operand is live into the PHI node's block OR
437 // 2) if the PHI node is live out of the operand's defining block OR
438 // 3) if the operand is itself a PHI node and the original PHI is
439 // live into the operand's defining block OR
440 // 4) if the operand is already being renamed for another PHI node
442 // 5) if any two operands are defined in the same block, insert copies
444 if (isLiveIn(SrcReg, P->getParent(), LI) ||
445 isLiveOut(P->getOperand(0).getReg(),
446 MRI.getVRegDef(SrcReg)->getParent(), LI) ||
447 ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
448 isLiveIn(P->getOperand(0).getReg(),
449 MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
450 ProcessedNames.count(SrcReg) ||
451 UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
453 // Add a copy for the selected register
454 MachineBasicBlock* From = P->getOperand(i).getMBB();
455 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
456 UsedByAnother.insert(SrcReg);
458 // Otherwise, add it to the renaming set
459 LiveInterval& I = LI.getOrCreateInterval(SrcReg);
460 unsigned idx = LI.getMBBEndIdx(P->getOperand(i).getMBB());
461 VNInfo* VN = I.getLiveRangeContaining(idx)->valno;
463 assert(VN && "No VNInfo for register?");
465 PHIUnion.insert(std::make_pair(SrcReg, VN->id));
466 UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
470 // Compute the dominator forest for the renaming set. This is a forest
471 // where the nodes are the registers and the edges represent dominance
472 // relations between the defining blocks of the registers
473 std::vector<StrongPHIElimination::DomForestNode*> DF =
474 computeDomForest(PHIUnion, MRI);
476 // Walk DomForest to resolve interferences at an inter-block level. This
477 // will remove registers from the renaming set (and insert copies for them)
478 // if interferences are found.
479 std::vector<std::pair<unsigned, unsigned> > localInterferences;
480 processPHIUnion(P, PHIUnion, DF, localInterferences);
482 // The dominator forest walk may have returned some register pairs whose
483 // interference cannot be determines from dominator analysis. We now
484 // examine these pairs for local interferences.
485 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
486 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
487 std::pair<unsigned, unsigned> p = *I;
489 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
491 // Determine the block we need to scan and the relationship between
493 MachineBasicBlock* scan = 0;
495 if (MRI.getVRegDef(p.first)->getParent() ==
496 MRI.getVRegDef(p.second)->getParent()) {
497 scan = MRI.getVRegDef(p.first)->getParent();
498 mode = 0; // Same block
499 } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
500 MRI.getVRegDef(p.second)->getParent())) {
501 scan = MRI.getVRegDef(p.second)->getParent();
502 mode = 1; // First dominates second
504 scan = MRI.getVRegDef(p.first)->getParent();
505 mode = 2; // Second dominates first
508 // If there's an interference, we need to insert copies
509 if (interferes(p.first, p.second, scan, LI, mode)) {
510 // Insert copies for First
511 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
512 if (P->getOperand(i-1).getReg() == p.first) {
513 unsigned SrcReg = p.first;
514 MachineBasicBlock* From = P->getOperand(i).getMBB();
516 Waiting[From].insert(std::make_pair(SrcReg,
517 P->getOperand(0).getReg()));
518 UsedByAnother.insert(SrcReg);
520 PHIUnion.erase(SrcReg);
526 // Add the renaming set for this PHI node to our overal renaming information
527 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
529 // Remember which registers are already renamed, so that we don't try to
530 // rename them for another PHI node in this block
531 for (std::map<unsigned, unsigned>::iterator I = PHIUnion.begin(),
532 E = PHIUnion.end(); I != E; ++I)
533 ProcessedNames.insert(I->first);
539 /// processPHIUnion - Take a set of candidate registers to be coalesced when
540 /// decomposing the PHI instruction. Use the DominanceForest to remove the ones
541 /// that are known to interfere, and flag others that need to be checked for
542 /// local interferences.
543 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
544 std::map<unsigned, unsigned>& PHIUnion,
545 std::vector<StrongPHIElimination::DomForestNode*>& DF,
546 std::vector<std::pair<unsigned, unsigned> >& locals) {
548 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
549 SmallPtrSet<DomForestNode*, 4> visited;
551 // Code is still in SSA form, so we can use MRI::getVRegDef()
552 MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
554 LiveIntervals& LI = getAnalysis<LiveIntervals>();
555 unsigned DestReg = Inst->getOperand(0).getReg();
557 // DF walk on the DomForest
558 while (!worklist.empty()) {
559 DomForestNode* DFNode = worklist.back();
561 visited.insert(DFNode);
563 bool inserted = false;
564 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
566 DomForestNode* child = *CI;
568 // If the current node is live-out of the defining block of one of its
569 // children, insert a copy for it. NOTE: The paper actually calls for
570 // a more elaborate heuristic for determining whether to insert copies
571 // for the child or the parent. In the interest of simplicity, we're
572 // just always choosing the parent.
573 if (isLiveOut(DFNode->getReg(),
574 MRI.getVRegDef(child->getReg())->getParent(), LI)) {
575 // Insert copies for parent
576 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
577 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
578 unsigned SrcReg = DFNode->getReg();
579 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
581 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
582 UsedByAnother.insert(SrcReg);
584 PHIUnion.erase(SrcReg);
588 // If a node is live-in to the defining block of one of its children, but
589 // not live-out, then we need to scan that block for local interferences.
590 } else if (isLiveIn(DFNode->getReg(),
591 MRI.getVRegDef(child->getReg())->getParent(), LI) ||
592 MRI.getVRegDef(DFNode->getReg())->getParent() ==
593 MRI.getVRegDef(child->getReg())->getParent()) {
594 // Add (p, c) to possible local interferences
595 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
598 if (!visited.count(child)) {
599 worklist.push_back(child);
604 if (!inserted) worklist.pop_back();
608 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
609 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
612 /// Based on "Practical Improvements to the Construction and Destruction
613 /// of Static Single Assignment Form" by Briggs, et al.
614 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
615 std::set<unsigned>& pushed) {
616 // FIXME: This function needs to update LiveVariables
617 std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
619 std::map<unsigned, unsigned> worklist;
620 std::map<unsigned, unsigned> map;
622 // Setup worklist of initial copies
623 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
624 E = copy_set.end(); I != E; ) {
625 map.insert(std::make_pair(I->first, I->first));
626 map.insert(std::make_pair(I->second, I->second));
628 if (!UsedByAnother.count(I->first)) {
631 // Avoid iterator invalidation
632 unsigned first = I->first;
634 copy_set.erase(first);
640 LiveIntervals& LI = getAnalysis<LiveIntervals>();
641 MachineFunction* MF = MBB->getParent();
642 MachineRegisterInfo& MRI = MF->getRegInfo();
643 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
645 // Iterate over the worklist, inserting copies
646 while (!worklist.empty() || !copy_set.empty()) {
647 while (!worklist.empty()) {
648 std::pair<unsigned, unsigned> curr = *worklist.begin();
649 worklist.erase(curr.first);
651 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
653 if (isLiveOut(curr.second, MBB, LI)) {
654 // Create a temporary
655 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
657 // Insert copy from curr.second to a temporary at
658 // the Phi defining curr.second
659 MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
660 TII->copyRegToReg(*PI->getParent(), PI, t,
661 curr.second, RC, RC);
663 // Push temporary on Stacks
664 Stacks[curr.second].push_back(t);
666 // Insert curr.second in pushed
667 pushed.insert(curr.second);
670 // Insert copy from map[curr.first] to curr.second
671 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
672 map[curr.first], RC, RC);
673 map[curr.first] = curr.second;
675 // If curr.first is a destination in copy_set...
676 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
677 E = copy_set.end(); I != E; )
678 if (curr.first == I->second) {
679 std::pair<unsigned, unsigned> temp = *I;
681 // Avoid iterator invalidation
683 copy_set.erase(temp.first);
684 worklist.insert(temp);
692 if (!copy_set.empty()) {
693 std::pair<unsigned, unsigned> curr = *copy_set.begin();
694 copy_set.erase(curr.first);
696 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
698 // Insert a copy from dest to a new temporary t at the end of b
699 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
700 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
701 curr.second, RC, RC);
702 map[curr.second] = t;
704 worklist.insert(curr);
709 /// InsertCopies - insert copies into MBB and all of its successors
710 void StrongPHIElimination::InsertCopies(MachineBasicBlock* MBB,
711 std::set<MachineBasicBlock*>& visited) {
714 std::set<unsigned> pushed;
716 // Rewrite register uses from Stacks
717 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
719 for (unsigned i = 0; i < I->getNumOperands(); ++i)
720 if (I->getOperand(i).isRegister() &&
721 Stacks[I->getOperand(i).getReg()].size()) {
722 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
725 // Schedule the copies for this block
726 ScheduleCopies(MBB, pushed);
728 // Recur to our successors
729 for (GraphTraits<MachineBasicBlock*>::ChildIteratorType I =
730 GraphTraits<MachineBasicBlock*>::child_begin(MBB), E =
731 GraphTraits<MachineBasicBlock*>::child_end(MBB); I != E; ++I)
732 if (!visited.count(*I))
733 InsertCopies(*I, visited);
735 // As we exit this block, pop the names we pushed while processing it
736 for (std::set<unsigned>::iterator I = pushed.begin(),
737 E = pushed.end(); I != E; ++I)
738 Stacks[*I].pop_back();
741 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
742 /// compute what the resultant value numbers for each value in the input two
743 /// ranges will be. This is complicated by copies between the two which can
744 /// and will commonly cause multiple value numbers to be merged into one.
746 /// VN is the value number that we're trying to resolve. InstDefiningValue
747 /// keeps track of the new InstDefiningValue assignment for the result
748 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
749 /// whether a value in this or other is a copy from the opposite set.
750 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
751 /// already been assigned.
753 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
754 /// contains the value number the copy is from.
756 static unsigned ComputeUltimateVN(VNInfo *VNI,
757 SmallVector<VNInfo*, 16> &NewVNInfo,
758 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
759 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
760 SmallVector<int, 16> &ThisValNoAssignments,
761 SmallVector<int, 16> &OtherValNoAssignments) {
762 unsigned VN = VNI->id;
764 // If the VN has already been computed, just return it.
765 if (ThisValNoAssignments[VN] >= 0)
766 return ThisValNoAssignments[VN];
767 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
769 // If this val is not a copy from the other val, then it must be a new value
770 // number in the destination.
771 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
772 if (I == ThisFromOther.end()) {
773 NewVNInfo.push_back(VNI);
774 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
776 VNInfo *OtherValNo = I->second;
778 // Otherwise, this *is* a copy from the RHS. If the other side has already
779 // been computed, return it.
780 if (OtherValNoAssignments[OtherValNo->id] >= 0)
781 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
783 // Mark this value number as currently being computed, then ask what the
784 // ultimate value # of the other value is.
785 ThisValNoAssignments[VN] = -2;
786 unsigned UltimateVN =
787 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
788 OtherValNoAssignments, ThisValNoAssignments);
789 return ThisValNoAssignments[VN] = UltimateVN;
792 void StrongPHIElimination::mergeLiveIntervals(unsigned primary,
793 unsigned secondary, unsigned secondaryVN) {
794 unsigned primaryVN = PhiValueNumber[primary];
796 LiveIntervals& LI = getAnalysis<LiveIntervals>();
797 LiveInterval& LHS = LI.getOrCreateInterval(primary);
798 LiveInterval& RHS = LI.getOrCreateInterval(secondary);
800 // Compute the final value assignment, assuming that the live ranges can be
802 SmallVector<int, 16> LHSValNoAssignments;
803 SmallVector<int, 16> RHSValNoAssignments;
804 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
805 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
806 SmallVector<VNInfo*, 16> NewVNInfo;
808 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
809 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
810 NewVNInfo.resize(LHS.getNumValNums(), NULL);
812 // Loop over the value numbers of the LHS, seeing if any are defined from
814 for (LiveInterval::vni_iterator I = LHS.vni_begin(), E = LHS.vni_end();
817 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
820 // DstReg is known to be a register in the LHS interval. If the src is
821 // from the RHS interval, we can use its value #.
822 if (LI.getVNInfoSourceReg(VNI) != RHS.reg)
825 // Figure out the value # from the RHS.
826 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
829 // Loop over the value numbers of the RHS, seeing if any are defined from
831 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
834 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
837 // DstReg is known to be a register in the RHS interval. If the src is
838 // from the LHS interval, we can use its value #.
839 if (LI.getVNInfoSourceReg(VNI) != LHS.reg)
842 // Figure out the value # from the LHS.
843 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
846 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
847 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
848 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
850 for (LiveInterval::vni_iterator I = LHS.vni_begin(), E = LHS.vni_end();
853 unsigned VN = VNI->id;
854 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
856 ComputeUltimateVN(VNI, NewVNInfo,
857 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
858 LHSValNoAssignments, RHSValNoAssignments);
861 for (LiveInterval::vni_iterator I = RHS.vni_begin(), E = RHS.vni_end();
864 unsigned VN = VNI->id;
865 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
867 // If this value number isn't a copy from the LHS, it's a new number.
868 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
869 NewVNInfo.push_back(VNI);
870 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
874 ComputeUltimateVN(VNI, NewVNInfo,
875 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
876 RHSValNoAssignments, LHSValNoAssignments);
879 // Update kill info. Some live ranges are extended due to copy coalescing.
880 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
881 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
882 VNInfo *VNI = I->first;
883 unsigned LHSValID = LHSValNoAssignments[VNI->id];
884 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
885 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
886 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
889 // Update kill info. Some live ranges are extended due to copy coalescing.
890 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
891 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
892 VNInfo *VNI = I->first;
893 unsigned RHSValID = RHSValNoAssignments[VNI->id];
894 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
895 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
896 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
899 // Use the VNInfo we collected earlier to ensure that the phi copy is
901 RHSValNoAssignments[secondaryVN] = primaryVN;
903 // If we get here, we know that we can coalesce the live ranges. Ask the
904 // intervals to coalesce themselves now.
905 if ((RHS.ranges.size() > LHS.ranges.size() &&
906 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
907 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
908 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
910 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
914 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
915 // Compute DFS numbers of each block
918 // Determine which phi node operands need copies
919 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
921 I->begin()->getOpcode() == TargetInstrInfo::PHI)
925 // FIXME: This process should probably preserve LiveVariables
926 std::set<MachineBasicBlock*> visited;
927 InsertCopies(Fn.begin(), visited);
930 typedef std::map<unsigned, std::map<unsigned, unsigned> > RenameSetType;
931 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
933 for (std::map<unsigned, unsigned>::iterator SI = I->second.begin(),
934 SE = I->second.end(); SI != SE; ++SI) {
935 mergeLiveIntervals(I->first, SI->first, SI->second);
936 Fn.getRegInfo().replaceRegWith(SI->first, I->first);
939 // FIXME: Insert last-minute copies
942 std::vector<MachineInstr*> phis;
943 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
944 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
946 if (BI->getOpcode() == TargetInstrInfo::PHI)
950 for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
952 (*I)->eraseFromParent();