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,
140 SmallPtrSet<MachineBasicBlock*, 16>& v);
141 void mergeLiveIntervals(unsigned primary, unsigned secondary, unsigned VN);
144 char StrongPHIElimination::ID = 0;
145 RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
146 "Eliminate PHI nodes for register allocation, intelligently");
149 const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
151 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
152 /// of the given MachineFunction. These numbers are then used in other parts
153 /// of the PHI elimination process.
154 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
155 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
156 SmallPtrSet<MachineDomTreeNode*, 8> visited;
160 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
162 MachineDomTreeNode* node = DT.getRootNode();
164 std::vector<MachineDomTreeNode*> worklist;
165 worklist.push_back(node);
167 while (!worklist.empty()) {
168 MachineDomTreeNode* currNode = worklist.back();
170 if (!frontier.count(currNode)) {
171 frontier.insert(currNode);
173 preorder.insert(std::make_pair(currNode->getBlock(), time));
176 bool inserted = false;
177 for (MachineDomTreeNode::iterator I = node->begin(), E = node->end();
179 if (!frontier.count(*I) && !visited.count(*I)) {
180 worklist.push_back(*I);
186 frontier.erase(currNode);
187 visited.insert(currNode);
188 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
195 /// PreorderSorter - a helper class that is used to sort registers
196 /// according to the preorder number of their defining blocks
197 class PreorderSorter {
199 DenseMap<MachineBasicBlock*, unsigned>& preorder;
200 MachineRegisterInfo& MRI;
203 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
204 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
206 bool operator()(unsigned A, unsigned B) {
210 MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
211 MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
213 if (preorder[ABlock] < preorder[BBlock])
215 else if (preorder[ABlock] > preorder[BBlock])
222 /// computeDomForest - compute the subforest of the DomTree corresponding
223 /// to the defining blocks of the registers in question
224 std::vector<StrongPHIElimination::DomForestNode*>
225 StrongPHIElimination::computeDomForest(std::map<unsigned, unsigned>& regs,
226 MachineRegisterInfo& MRI) {
227 // Begin by creating a virtual root node, since the actual results
228 // may well be a forest. Assume this node has maximum DFS-out number.
229 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
230 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
232 // Populate a worklist with the registers
233 std::vector<unsigned> worklist;
234 worklist.reserve(regs.size());
235 for (std::map<unsigned, unsigned>::iterator I = regs.begin(), E = regs.end();
237 worklist.push_back(I->first);
239 // Sort the registers by the DFS-in number of their defining block
240 PreorderSorter PS(preorder, MRI);
241 std::sort(worklist.begin(), worklist.end(), PS);
243 // Create a "current parent" stack, and put the virtual root on top of it
244 DomForestNode* CurrentParent = VirtualRoot;
245 std::vector<DomForestNode*> stack;
246 stack.push_back(VirtualRoot);
248 // Iterate over all the registers in the previously computed order
249 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
251 unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
252 MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
253 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
256 // If the DFS-in number of the register is greater than the DFS-out number
257 // of the current parent, repeatedly pop the parent stack until it isn't.
258 while (pre > maxpreorder[parentBlock]) {
260 CurrentParent = stack.back();
262 parentBlock = CurrentParent->getReg() ?
263 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
267 // Now that we've found the appropriate parent, create a DomForestNode for
268 // this register and attach it to the forest
269 DomForestNode* child = new DomForestNode(*I, CurrentParent);
271 // Push this new node on the "current parent" stack
272 stack.push_back(child);
273 CurrentParent = child;
276 // Return a vector containing the children of the virtual root node
277 std::vector<DomForestNode*> ret;
278 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
282 /// isLiveIn - helper method that determines, from a regno, if a register
283 /// is live into a block
284 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
286 LiveInterval& I = LI.getOrCreateInterval(r);
287 unsigned idx = LI.getMBBStartIdx(MBB);
288 return I.liveBeforeAndAt(idx);
291 /// isLiveOut - help method that determines, from a regno, if a register is
292 /// live out of a block.
293 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
295 for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
296 E = MBB->succ_end(); PI != E; ++PI) {
297 if (isLiveIn(r, *PI, LI))
304 /// interferes - checks for local interferences by scanning a block. The only
305 /// trick parameter is 'mode' which tells it the relationship of the two
306 /// registers. 0 - defined in the same block, 1 - first properly dominates
307 /// second, 2 - second properly dominates first
308 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
309 LiveIntervals& LV, unsigned mode) {
310 MachineInstr* def = 0;
311 MachineInstr* kill = 0;
313 // The code is still in SSA form at this point, so there is only one
314 // definition per VReg. Thus we can safely use MRI->getVRegDef().
315 const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
317 bool interference = false;
319 // Wallk the block, checking for interferences
320 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
322 MachineInstr* curr = MBI;
324 // Same defining block...
326 if (curr == MRI->getVRegDef(a)) {
327 // If we find our first definition, save it
330 // If there's already an unkilled definition, then
331 // this is an interference
335 // If there's a definition followed by a KillInst, then
336 // they can't interfere
338 interference = false;
341 // Symmetric with the above
342 } else if (curr == MRI->getVRegDef(b)) {
349 interference = false;
352 // Store KillInsts if they match up with the definition
353 } else if (curr->killsRegister(a)) {
354 if (def == MRI->getVRegDef(a)) {
356 } else if (curr->killsRegister(b)) {
357 if (def == MRI->getVRegDef(b)) {
362 // First properly dominates second...
363 } else if (mode == 1) {
364 if (curr == MRI->getVRegDef(b)) {
365 // Definition of second without kill of first is an interference
369 // Definition after a kill is a non-interference
371 interference = false;
374 // Save KillInsts of First
375 } else if (curr->killsRegister(a)) {
378 // Symmetric with the above
379 } else if (mode == 2) {
380 if (curr == MRI->getVRegDef(a)) {
385 interference = false;
388 } else if (curr->killsRegister(b)) {
397 /// processBlock - Determine how to break up PHIs in the current block. Each
398 /// PHI is broken up by some combination of renaming its operands and inserting
399 /// copies. This method is responsible for determining which operands receive
401 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
402 LiveIntervals& LI = getAnalysis<LiveIntervals>();
403 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
405 // Holds names that have been added to a set in any PHI within this block
406 // before the current one.
407 std::set<unsigned> ProcessedNames;
409 MachineBasicBlock::iterator FirstNonPHI = MBB->begin();
410 while (FirstNonPHI->getOpcode() == TargetInstrInfo::PHI) FirstNonPHI++;
412 // Iterate over all the PHI nodes in this block
413 MachineBasicBlock::iterator P = MBB->begin();
414 while (P != FirstNonPHI && P->getOpcode() == TargetInstrInfo::PHI) {
415 unsigned DestReg = P->getOperand(0).getReg();
417 LiveInterval& PI = LI.getOrCreateInterval(DestReg);
418 unsigned pIdx = LI.getInstructionIndex(FirstNonPHI);
419 VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
420 PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
422 // PHIUnion is the set of incoming registers to the PHI node that
423 // are going to be renames rather than having copies inserted. This set
424 // is refinded over the course of this function. UnionedBlocks is the set
425 // of corresponding MBBs.
426 std::map<unsigned, unsigned> PHIUnion;
427 SmallPtrSet<MachineBasicBlock*, 8> UnionedBlocks;
429 // Iterate over the operands of the PHI node
430 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
431 unsigned SrcReg = P->getOperand(i-1).getReg();
433 // Check for trivial interferences via liveness information, allowing us
434 // to avoid extra work later. Any registers that interfere cannot both
435 // be in the renaming set, so choose one and add copies for it instead.
436 // The conditions are:
437 // 1) if the operand is live into the PHI node's block OR
438 // 2) if the PHI node is live out of the operand's defining block OR
439 // 3) if the operand is itself a PHI node and the original PHI is
440 // live into the operand's defining block OR
441 // 4) if the operand is already being renamed for another PHI node
443 // 5) if any two operands are defined in the same block, insert copies
445 if (isLiveIn(SrcReg, P->getParent(), LI) ||
446 isLiveOut(P->getOperand(0).getReg(),
447 MRI.getVRegDef(SrcReg)->getParent(), LI) ||
448 ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
449 isLiveIn(P->getOperand(0).getReg(),
450 MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
451 ProcessedNames.count(SrcReg) ||
452 UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
454 // Add a copy for the selected register
455 MachineBasicBlock* From = P->getOperand(i).getMBB();
456 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
457 UsedByAnother.insert(SrcReg);
459 // Otherwise, add it to the renaming set
460 LiveInterval& I = LI.getOrCreateInterval(SrcReg);
461 unsigned idx = LI.getMBBEndIdx(P->getOperand(i).getMBB());
462 VNInfo* VN = I.getLiveRangeContaining(idx)->valno;
464 assert(VN && "No VNInfo for register?");
466 PHIUnion.insert(std::make_pair(SrcReg, VN->id));
467 UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
471 // Compute the dominator forest for the renaming set. This is a forest
472 // where the nodes are the registers and the edges represent dominance
473 // relations between the defining blocks of the registers
474 std::vector<StrongPHIElimination::DomForestNode*> DF =
475 computeDomForest(PHIUnion, MRI);
477 // Walk DomForest to resolve interferences at an inter-block level. This
478 // will remove registers from the renaming set (and insert copies for them)
479 // if interferences are found.
480 std::vector<std::pair<unsigned, unsigned> > localInterferences;
481 processPHIUnion(P, PHIUnion, DF, localInterferences);
483 // The dominator forest walk may have returned some register pairs whose
484 // interference cannot be determines from dominator analysis. We now
485 // examine these pairs for local interferences.
486 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
487 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
488 std::pair<unsigned, unsigned> p = *I;
490 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
492 // Determine the block we need to scan and the relationship between
494 MachineBasicBlock* scan = 0;
496 if (MRI.getVRegDef(p.first)->getParent() ==
497 MRI.getVRegDef(p.second)->getParent()) {
498 scan = MRI.getVRegDef(p.first)->getParent();
499 mode = 0; // Same block
500 } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
501 MRI.getVRegDef(p.second)->getParent())) {
502 scan = MRI.getVRegDef(p.second)->getParent();
503 mode = 1; // First dominates second
505 scan = MRI.getVRegDef(p.first)->getParent();
506 mode = 2; // Second dominates first
509 // If there's an interference, we need to insert copies
510 if (interferes(p.first, p.second, scan, LI, mode)) {
511 // Insert copies for First
512 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
513 if (P->getOperand(i-1).getReg() == p.first) {
514 unsigned SrcReg = p.first;
515 MachineBasicBlock* From = P->getOperand(i).getMBB();
517 Waiting[From].insert(std::make_pair(SrcReg,
518 P->getOperand(0).getReg()));
519 UsedByAnother.insert(SrcReg);
521 PHIUnion.erase(SrcReg);
527 // Add the renaming set for this PHI node to our overal renaming information
528 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
530 // Remember which registers are already renamed, so that we don't try to
531 // rename them for another PHI node in this block
532 for (std::map<unsigned, unsigned>::iterator I = PHIUnion.begin(),
533 E = PHIUnion.end(); I != E; ++I)
534 ProcessedNames.insert(I->first);
540 /// processPHIUnion - Take a set of candidate registers to be coalesced when
541 /// decomposing the PHI instruction. Use the DominanceForest to remove the ones
542 /// that are known to interfere, and flag others that need to be checked for
543 /// local interferences.
544 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
545 std::map<unsigned, unsigned>& PHIUnion,
546 std::vector<StrongPHIElimination::DomForestNode*>& DF,
547 std::vector<std::pair<unsigned, unsigned> >& locals) {
549 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
550 SmallPtrSet<DomForestNode*, 4> visited;
552 // Code is still in SSA form, so we can use MRI::getVRegDef()
553 MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
555 LiveIntervals& LI = getAnalysis<LiveIntervals>();
556 unsigned DestReg = Inst->getOperand(0).getReg();
558 // DF walk on the DomForest
559 while (!worklist.empty()) {
560 DomForestNode* DFNode = worklist.back();
562 visited.insert(DFNode);
564 bool inserted = false;
565 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
567 DomForestNode* child = *CI;
569 // If the current node is live-out of the defining block of one of its
570 // children, insert a copy for it. NOTE: The paper actually calls for
571 // a more elaborate heuristic for determining whether to insert copies
572 // for the child or the parent. In the interest of simplicity, we're
573 // just always choosing the parent.
574 if (isLiveOut(DFNode->getReg(),
575 MRI.getVRegDef(child->getReg())->getParent(), LI)) {
576 // Insert copies for parent
577 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
578 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
579 unsigned SrcReg = DFNode->getReg();
580 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
582 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
583 UsedByAnother.insert(SrcReg);
585 PHIUnion.erase(SrcReg);
589 // If a node is live-in to the defining block of one of its children, but
590 // not live-out, then we need to scan that block for local interferences.
591 } else if (isLiveIn(DFNode->getReg(),
592 MRI.getVRegDef(child->getReg())->getParent(), LI) ||
593 MRI.getVRegDef(DFNode->getReg())->getParent() ==
594 MRI.getVRegDef(child->getReg())->getParent()) {
595 // Add (p, c) to possible local interferences
596 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
599 if (!visited.count(child)) {
600 worklist.push_back(child);
605 if (!inserted) worklist.pop_back();
609 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
610 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
613 /// Based on "Practical Improvements to the Construction and Destruction
614 /// of Static Single Assignment Form" by Briggs, et al.
615 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
616 std::set<unsigned>& pushed) {
617 // FIXME: This function needs to update LiveVariables
618 std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
620 std::map<unsigned, unsigned> worklist;
621 std::map<unsigned, unsigned> map;
623 // Setup worklist of initial copies
624 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
625 E = copy_set.end(); I != E; ) {
626 map.insert(std::make_pair(I->first, I->first));
627 map.insert(std::make_pair(I->second, I->second));
629 if (!UsedByAnother.count(I->first)) {
632 // Avoid iterator invalidation
633 unsigned first = I->first;
635 copy_set.erase(first);
641 LiveIntervals& LI = getAnalysis<LiveIntervals>();
642 MachineFunction* MF = MBB->getParent();
643 MachineRegisterInfo& MRI = MF->getRegInfo();
644 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
646 // Iterate over the worklist, inserting copies
647 while (!worklist.empty() || !copy_set.empty()) {
648 while (!worklist.empty()) {
649 std::pair<unsigned, unsigned> curr = *worklist.begin();
650 worklist.erase(curr.first);
652 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
654 if (isLiveOut(curr.second, MBB, LI)) {
655 // Create a temporary
656 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
658 // Insert copy from curr.second to a temporary at
659 // the Phi defining curr.second
660 MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
661 TII->copyRegToReg(*PI->getParent(), PI, t,
662 curr.second, RC, RC);
664 // Push temporary on Stacks
665 Stacks[curr.second].push_back(t);
667 // Insert curr.second in pushed
668 pushed.insert(curr.second);
671 // Insert copy from map[curr.first] to curr.second
672 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
673 map[curr.first], RC, RC);
674 map[curr.first] = curr.second;
676 // If curr.first is a destination in copy_set...
677 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
678 E = copy_set.end(); I != E; )
679 if (curr.first == I->second) {
680 std::pair<unsigned, unsigned> temp = *I;
682 // Avoid iterator invalidation
684 copy_set.erase(temp.first);
685 worklist.insert(temp);
693 if (!copy_set.empty()) {
694 std::pair<unsigned, unsigned> curr = *copy_set.begin();
695 copy_set.erase(curr.first);
697 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
699 // Insert a copy from dest to a new temporary t at the end of b
700 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
701 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
702 curr.second, RC, RC);
703 map[curr.second] = t;
705 worklist.insert(curr);
710 /// InsertCopies - insert copies into MBB and all of its successors
711 void StrongPHIElimination::InsertCopies(MachineBasicBlock* MBB,
712 SmallPtrSet<MachineBasicBlock*, 16>& visited) {
715 std::set<unsigned> pushed;
717 // Rewrite register uses from Stacks
718 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
720 for (unsigned i = 0; i < I->getNumOperands(); ++i)
721 if (I->getOperand(i).isRegister() &&
722 Stacks[I->getOperand(i).getReg()].size()) {
723 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
726 // Schedule the copies for this block
727 ScheduleCopies(MBB, pushed);
729 // Recur to our successors
730 for (GraphTraits<MachineBasicBlock*>::ChildIteratorType I =
731 GraphTraits<MachineBasicBlock*>::child_begin(MBB), E =
732 GraphTraits<MachineBasicBlock*>::child_end(MBB); I != E; ++I)
733 if (!visited.count(*I))
734 InsertCopies(*I, visited);
736 // As we exit this block, pop the names we pushed while processing it
737 for (std::set<unsigned>::iterator I = pushed.begin(),
738 E = pushed.end(); I != E; ++I)
739 Stacks[*I].pop_back();
742 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
743 /// compute what the resultant value numbers for each value in the input two
744 /// ranges will be. This is complicated by copies between the two which can
745 /// and will commonly cause multiple value numbers to be merged into one.
747 /// VN is the value number that we're trying to resolve. InstDefiningValue
748 /// keeps track of the new InstDefiningValue assignment for the result
749 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
750 /// whether a value in this or other is a copy from the opposite set.
751 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
752 /// already been assigned.
754 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
755 /// contains the value number the copy is from.
757 static unsigned ComputeUltimateVN(VNInfo *VNI,
758 SmallVector<VNInfo*, 16> &NewVNInfo,
759 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
760 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
761 SmallVector<int, 16> &ThisValNoAssignments,
762 SmallVector<int, 16> &OtherValNoAssignments) {
763 unsigned VN = VNI->id;
765 // If the VN has already been computed, just return it.
766 if (ThisValNoAssignments[VN] >= 0)
767 return ThisValNoAssignments[VN];
768 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
770 // If this val is not a copy from the other val, then it must be a new value
771 // number in the destination.
772 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
773 if (I == ThisFromOther.end()) {
774 NewVNInfo.push_back(VNI);
775 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
777 VNInfo *OtherValNo = I->second;
779 // Otherwise, this *is* a copy from the RHS. If the other side has already
780 // been computed, return it.
781 if (OtherValNoAssignments[OtherValNo->id] >= 0)
782 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
784 // Mark this value number as currently being computed, then ask what the
785 // ultimate value # of the other value is.
786 ThisValNoAssignments[VN] = -2;
787 unsigned UltimateVN =
788 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
789 OtherValNoAssignments, ThisValNoAssignments);
790 return ThisValNoAssignments[VN] = UltimateVN;
793 void StrongPHIElimination::mergeLiveIntervals(unsigned primary,
795 unsigned secondaryVN) {
797 LiveIntervals& LI = getAnalysis<LiveIntervals>();
798 LiveInterval& LHS = LI.getOrCreateInterval(primary);
799 LiveInterval& RHS = LI.getOrCreateInterval(secondary);
801 // Compute the final value assignment, assuming that the live ranges can be
803 SmallVector<int, 16> LHSValNoAssignments;
804 SmallVector<int, 16> RHSValNoAssignments;
805 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
806 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
807 SmallVector<VNInfo*, 16> NewVNInfo;
809 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
810 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
811 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
813 for (LiveInterval::vni_iterator I = LHS.vni_begin(), E = LHS.vni_end();
816 unsigned VN = VNI->id;
817 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
819 ComputeUltimateVN(VNI, NewVNInfo,
820 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
821 LHSValNoAssignments, RHSValNoAssignments);
824 for (LiveInterval::vni_iterator I = RHS.vni_begin(), E = RHS.vni_end();
827 unsigned VN = VNI->id;
828 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
830 // If this value number isn't a copy from the LHS, it's a new number.
831 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
832 NewVNInfo.push_back(VNI);
833 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
837 ComputeUltimateVN(VNI, NewVNInfo,
838 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
839 RHSValNoAssignments, LHSValNoAssignments);
842 // Update kill info. Some live ranges are extended due to copy coalescing.
843 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
844 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
845 VNInfo *VNI = I->first;
846 unsigned LHSValID = LHSValNoAssignments[VNI->id];
847 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
848 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
849 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
852 // Update kill info. Some live ranges are extended due to copy coalescing.
853 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
854 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
855 VNInfo *VNI = I->first;
856 unsigned RHSValID = RHSValNoAssignments[VNI->id];
857 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
858 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
859 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
862 // Use the VNInfo we collected earlier to ensure that the phi copy is
864 // FIXME: This is not working correctly yet.
865 // RHSValNoAssignments[secondaryVN] = primaryVN;
867 // If we get here, we know that we can coalesce the live ranges. Ask the
868 // intervals to coalesce themselves now.
870 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
871 LI.removeInterval(secondary);
874 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
875 // Compute DFS numbers of each block
878 // Determine which phi node operands need copies
879 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
881 I->begin()->getOpcode() == TargetInstrInfo::PHI)
885 // FIXME: This process should probably preserve LiveVariables
886 SmallPtrSet<MachineBasicBlock*, 16> visited;
887 InsertCopies(Fn.begin(), visited);
890 typedef std::map<unsigned, std::map<unsigned, unsigned> > RenameSetType;
891 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
893 for (std::map<unsigned, unsigned>::iterator SI = I->second.begin(),
894 SE = I->second.end(); SI != SE; ++SI) {
895 mergeLiveIntervals(I->first, SI->first, SI->second);
896 Fn.getRegInfo().replaceRegWith(SI->first, I->first);
899 // FIXME: Insert last-minute copies
902 std::vector<MachineInstr*> phis;
903 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
904 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
906 if (BI->getOpcode() == TargetInstrInfo::PHI)
910 LiveIntervals& LI = getAnalysis<LiveIntervals>();
912 for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
914 LI.RemoveMachineInstrFromMaps(*I);
915 (*I)->eraseFromParent();