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
57 // predecessor block for those input registers.
58 std::map<unsigned, std::map<unsigned, MachineBasicBlock*> > 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(
135 std::map<unsigned, MachineBasicBlock*>& instrs,
136 MachineRegisterInfo& MRI);
137 void processPHIUnion(MachineInstr* Inst,
138 std::map<unsigned, MachineBasicBlock*>& PHIUnion,
139 std::vector<StrongPHIElimination::DomForestNode*>& DF,
140 std::vector<std::pair<unsigned, unsigned> >& locals);
141 void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
142 void InsertCopies(MachineBasicBlock* MBB,
143 SmallPtrSet<MachineBasicBlock*, 16>& v);
144 void mergeLiveIntervals(unsigned primary, unsigned secondary,
145 MachineBasicBlock* pred);
149 char StrongPHIElimination::ID = 0;
150 static RegisterPass<StrongPHIElimination>
151 X("strong-phi-node-elimination",
152 "Eliminate PHI nodes for register allocation, intelligently");
154 const PassInfo *const llvm::StrongPHIEliminationID = &X;
156 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
157 /// of the given MachineFunction. These numbers are then used in other parts
158 /// of the PHI elimination process.
159 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
160 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
161 SmallPtrSet<MachineDomTreeNode*, 8> visited;
165 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
167 MachineDomTreeNode* node = DT.getRootNode();
169 std::vector<MachineDomTreeNode*> worklist;
170 worklist.push_back(node);
172 while (!worklist.empty()) {
173 MachineDomTreeNode* currNode = worklist.back();
175 if (!frontier.count(currNode)) {
176 frontier.insert(currNode);
178 preorder.insert(std::make_pair(currNode->getBlock(), time));
181 bool inserted = false;
182 for (MachineDomTreeNode::iterator I = currNode->begin(), E = currNode->end();
184 if (!frontier.count(*I) && !visited.count(*I)) {
185 worklist.push_back(*I);
191 frontier.erase(currNode);
192 visited.insert(currNode);
193 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
202 /// PreorderSorter - a helper class that is used to sort registers
203 /// according to the preorder number of their defining blocks
204 class PreorderSorter {
206 DenseMap<MachineBasicBlock*, unsigned>& preorder;
207 MachineRegisterInfo& MRI;
210 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
211 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
213 bool operator()(unsigned A, unsigned B) {
217 MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
218 MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
220 if (preorder[ABlock] < preorder[BBlock])
222 else if (preorder[ABlock] > preorder[BBlock])
231 /// computeDomForest - compute the subforest of the DomTree corresponding
232 /// to the defining blocks of the registers in question
233 std::vector<StrongPHIElimination::DomForestNode*>
234 StrongPHIElimination::computeDomForest(
235 std::map<unsigned, MachineBasicBlock*>& regs,
236 MachineRegisterInfo& MRI) {
237 // Begin by creating a virtual root node, since the actual results
238 // may well be a forest. Assume this node has maximum DFS-out number.
239 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
240 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
242 // Populate a worklist with the registers
243 std::vector<unsigned> worklist;
244 worklist.reserve(regs.size());
245 for (std::map<unsigned, MachineBasicBlock*>::iterator I = regs.begin(),
246 E = regs.end(); I != E; ++I)
247 worklist.push_back(I->first);
249 // Sort the registers by the DFS-in number of their defining block
250 PreorderSorter PS(preorder, MRI);
251 std::sort(worklist.begin(), worklist.end(), PS);
253 // Create a "current parent" stack, and put the virtual root on top of it
254 DomForestNode* CurrentParent = VirtualRoot;
255 std::vector<DomForestNode*> stack;
256 stack.push_back(VirtualRoot);
258 // Iterate over all the registers in the previously computed order
259 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
261 unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
262 MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
263 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
266 // If the DFS-in number of the register is greater than the DFS-out number
267 // of the current parent, repeatedly pop the parent stack until it isn't.
268 while (pre > maxpreorder[parentBlock]) {
270 CurrentParent = stack.back();
272 parentBlock = CurrentParent->getReg() ?
273 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
277 // Now that we've found the appropriate parent, create a DomForestNode for
278 // this register and attach it to the forest
279 DomForestNode* child = new DomForestNode(*I, CurrentParent);
281 // Push this new node on the "current parent" stack
282 stack.push_back(child);
283 CurrentParent = child;
286 // Return a vector containing the children of the virtual root node
287 std::vector<DomForestNode*> ret;
288 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
292 /// isLiveIn - helper method that determines, from a regno, if a register
293 /// is live into a block
294 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
296 LiveInterval& I = LI.getOrCreateInterval(r);
297 unsigned idx = LI.getMBBStartIdx(MBB);
298 return I.liveBeforeAndAt(idx);
301 /// isLiveOut - help method that determines, from a regno, if a register is
302 /// live out of a block.
303 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
305 for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
306 E = MBB->succ_end(); PI != E; ++PI) {
307 if (isLiveIn(r, *PI, LI))
314 /// interferes - checks for local interferences by scanning a block. The only
315 /// trick parameter is 'mode' which tells it the relationship of the two
316 /// registers. 0 - defined in the same block, 1 - first properly dominates
317 /// second, 2 - second properly dominates first
318 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
319 LiveIntervals& LV, unsigned mode) {
320 MachineInstr* def = 0;
321 MachineInstr* kill = 0;
323 // The code is still in SSA form at this point, so there is only one
324 // definition per VReg. Thus we can safely use MRI->getVRegDef().
325 const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
327 bool interference = false;
329 // Wallk the block, checking for interferences
330 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
332 MachineInstr* curr = MBI;
334 // Same defining block...
336 if (curr == MRI->getVRegDef(a)) {
337 // If we find our first definition, save it
340 // If there's already an unkilled definition, then
341 // this is an interference
345 // If there's a definition followed by a KillInst, then
346 // they can't interfere
348 interference = false;
351 // Symmetric with the above
352 } else if (curr == MRI->getVRegDef(b)) {
359 interference = false;
362 // Store KillInsts if they match up with the definition
363 } else if (curr->killsRegister(a)) {
364 if (def == MRI->getVRegDef(a)) {
366 } else if (curr->killsRegister(b)) {
367 if (def == MRI->getVRegDef(b)) {
372 // First properly dominates second...
373 } else if (mode == 1) {
374 if (curr == MRI->getVRegDef(b)) {
375 // Definition of second without kill of first is an interference
379 // Definition after a kill is a non-interference
381 interference = false;
384 // Save KillInsts of First
385 } else if (curr->killsRegister(a)) {
388 // Symmetric with the above
389 } else if (mode == 2) {
390 if (curr == MRI->getVRegDef(a)) {
395 interference = false;
398 } else if (curr->killsRegister(b)) {
407 /// processBlock - Determine how to break up PHIs in the current block. Each
408 /// PHI is broken up by some combination of renaming its operands and inserting
409 /// copies. This method is responsible for determining which operands receive
411 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
412 LiveIntervals& LI = getAnalysis<LiveIntervals>();
413 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
415 // Holds names that have been added to a set in any PHI within this block
416 // before the current one.
417 std::set<unsigned> ProcessedNames;
419 // Iterate over all the PHI nodes in this block
420 MachineBasicBlock::iterator P = MBB->begin();
421 while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
422 unsigned DestReg = P->getOperand(0).getReg();
425 // Don't both doing PHI elimination for dead PHI's.
426 if (P->registerDefIsDead(DestReg)) {
431 LiveInterval& PI = LI.getOrCreateInterval(DestReg);
432 unsigned pIdx = LI.getDefIndex(LI.getInstructionIndex(P));
433 VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
434 PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
436 // PHIUnion is the set of incoming registers to the PHI node that
437 // are going to be renames rather than having copies inserted. This set
438 // is refinded over the course of this function. UnionedBlocks is the set
439 // of corresponding MBBs.
440 std::map<unsigned, MachineBasicBlock*> PHIUnion;
441 SmallPtrSet<MachineBasicBlock*, 8> UnionedBlocks;
443 // Iterate over the operands of the PHI node
444 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
445 unsigned SrcReg = P->getOperand(i-1).getReg();
447 // Don't need to try to coalesce a register with itself.
448 if (SrcReg == DestReg) {
449 ProcessedNames.insert(SrcReg);
453 // Check for trivial interferences via liveness information, allowing us
454 // to avoid extra work later. Any registers that interfere cannot both
455 // be in the renaming set, so choose one and add copies for it instead.
456 // The conditions are:
457 // 1) if the operand is live into the PHI node's block OR
458 // 2) if the PHI node is live out of the operand's defining block OR
459 // 3) if the operand is itself a PHI node and the original PHI is
460 // live into the operand's defining block OR
461 // 4) if the operand is already being renamed for another PHI node
463 // 5) if any two operands are defined in the same block, insert copies
465 if (isLiveIn(SrcReg, P->getParent(), LI) ||
466 isLiveOut(P->getOperand(0).getReg(),
467 MRI.getVRegDef(SrcReg)->getParent(), LI) ||
468 ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
469 isLiveIn(P->getOperand(0).getReg(),
470 MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
471 ProcessedNames.count(SrcReg) ||
472 UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
474 // Add a copy for the selected register
475 MachineBasicBlock* From = P->getOperand(i).getMBB();
476 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
477 UsedByAnother.insert(SrcReg);
479 // Otherwise, add it to the renaming set
480 PHIUnion.insert(std::make_pair(SrcReg,P->getOperand(i).getMBB()));
481 UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
485 // Compute the dominator forest for the renaming set. This is a forest
486 // where the nodes are the registers and the edges represent dominance
487 // relations between the defining blocks of the registers
488 std::vector<StrongPHIElimination::DomForestNode*> DF =
489 computeDomForest(PHIUnion, MRI);
491 // Walk DomForest to resolve interferences at an inter-block level. This
492 // will remove registers from the renaming set (and insert copies for them)
493 // if interferences are found.
494 std::vector<std::pair<unsigned, unsigned> > localInterferences;
495 processPHIUnion(P, PHIUnion, DF, localInterferences);
497 // If one of the inputs is defined in the same block as the current PHI
498 // then we need to check for a local interference between that input and
500 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
501 E = PHIUnion.end(); I != E; ++I)
502 if (MRI.getVRegDef(I->first)->getParent() == P->getParent())
503 localInterferences.push_back(std::make_pair(I->first,
504 P->getOperand(0).getReg()));
506 // The dominator forest walk may have returned some register pairs whose
507 // interference cannot be determined from dominator analysis. We now
508 // examine these pairs for local interferences.
509 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
510 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
511 std::pair<unsigned, unsigned> p = *I;
513 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
515 // Determine the block we need to scan and the relationship between
517 MachineBasicBlock* scan = 0;
519 if (MRI.getVRegDef(p.first)->getParent() ==
520 MRI.getVRegDef(p.second)->getParent()) {
521 scan = MRI.getVRegDef(p.first)->getParent();
522 mode = 0; // Same block
523 } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
524 MRI.getVRegDef(p.second)->getParent())) {
525 scan = MRI.getVRegDef(p.second)->getParent();
526 mode = 1; // First dominates second
528 scan = MRI.getVRegDef(p.first)->getParent();
529 mode = 2; // Second dominates first
532 // If there's an interference, we need to insert copies
533 if (interferes(p.first, p.second, scan, LI, mode)) {
534 // Insert copies for First
535 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
536 if (P->getOperand(i-1).getReg() == p.first) {
537 unsigned SrcReg = p.first;
538 MachineBasicBlock* From = P->getOperand(i).getMBB();
540 Waiting[From].insert(std::make_pair(SrcReg,
541 P->getOperand(0).getReg()));
542 UsedByAnother.insert(SrcReg);
544 PHIUnion.erase(SrcReg);
550 // Add the renaming set for this PHI node to our overall renaming information
551 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
553 // Remember which registers are already renamed, so that we don't try to
554 // rename them for another PHI node in this block
555 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
556 E = PHIUnion.end(); I != E; ++I)
557 ProcessedNames.insert(I->first);
563 /// processPHIUnion - Take a set of candidate registers to be coalesced when
564 /// decomposing the PHI instruction. Use the DominanceForest to remove the ones
565 /// that are known to interfere, and flag others that need to be checked for
566 /// local interferences.
567 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
568 std::map<unsigned, MachineBasicBlock*>& PHIUnion,
569 std::vector<StrongPHIElimination::DomForestNode*>& DF,
570 std::vector<std::pair<unsigned, unsigned> >& locals) {
572 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
573 SmallPtrSet<DomForestNode*, 4> visited;
575 // Code is still in SSA form, so we can use MRI::getVRegDef()
576 MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
578 LiveIntervals& LI = getAnalysis<LiveIntervals>();
579 unsigned DestReg = Inst->getOperand(0).getReg();
581 // DF walk on the DomForest
582 while (!worklist.empty()) {
583 DomForestNode* DFNode = worklist.back();
585 visited.insert(DFNode);
587 bool inserted = false;
588 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
590 DomForestNode* child = *CI;
592 // If the current node is live-out of the defining block of one of its
593 // children, insert a copy for it. NOTE: The paper actually calls for
594 // a more elaborate heuristic for determining whether to insert copies
595 // for the child or the parent. In the interest of simplicity, we're
596 // just always choosing the parent.
597 if (isLiveOut(DFNode->getReg(),
598 MRI.getVRegDef(child->getReg())->getParent(), LI)) {
599 // Insert copies for parent
600 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
601 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
602 unsigned SrcReg = DFNode->getReg();
603 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
605 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
606 UsedByAnother.insert(SrcReg);
608 PHIUnion.erase(SrcReg);
612 // If a node is live-in to the defining block of one of its children, but
613 // not live-out, then we need to scan that block for local interferences.
614 } else if (isLiveIn(DFNode->getReg(),
615 MRI.getVRegDef(child->getReg())->getParent(), LI) ||
616 MRI.getVRegDef(DFNode->getReg())->getParent() ==
617 MRI.getVRegDef(child->getReg())->getParent()) {
618 // Add (p, c) to possible local interferences
619 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
622 if (!visited.count(child)) {
623 worklist.push_back(child);
628 if (!inserted) worklist.pop_back();
632 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
633 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
636 /// Based on "Practical Improvements to the Construction and Destruction
637 /// of Static Single Assignment Form" by Briggs, et al.
638 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
639 std::set<unsigned>& pushed) {
640 // FIXME: This function needs to update LiveIntervals
641 std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
643 std::map<unsigned, unsigned> worklist;
644 std::map<unsigned, unsigned> map;
646 // Setup worklist of initial copies
647 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
648 E = copy_set.end(); I != E; ) {
649 map.insert(std::make_pair(I->first, I->first));
650 map.insert(std::make_pair(I->second, I->second));
652 if (!UsedByAnother.count(I->second)) {
655 // Avoid iterator invalidation
656 unsigned first = I->first;
658 copy_set.erase(first);
664 LiveIntervals& LI = getAnalysis<LiveIntervals>();
665 MachineFunction* MF = MBB->getParent();
666 MachineRegisterInfo& MRI = MF->getRegInfo();
667 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
669 SmallVector<std::pair<unsigned, MachineInstr*>, 4> InsertedPHIDests;
671 // Iterate over the worklist, inserting copies
672 while (!worklist.empty() || !copy_set.empty()) {
673 while (!worklist.empty()) {
674 std::pair<unsigned, unsigned> curr = *worklist.begin();
675 worklist.erase(curr.first);
677 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
679 if (isLiveOut(curr.second, MBB, LI)) {
680 // Create a temporary
681 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
683 // Insert copy from curr.second to a temporary at
684 // the Phi defining curr.second
685 MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
686 TII->copyRegToReg(*PI->getParent(), PI, t,
687 curr.second, RC, RC);
689 // Push temporary on Stacks
690 Stacks[curr.second].push_back(t);
692 // Insert curr.second in pushed
693 pushed.insert(curr.second);
696 // Insert copy from map[curr.first] to curr.second
697 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
698 map[curr.first], RC, RC);
699 map[curr.first] = curr.second;
701 // Push this copy onto InsertedPHICopies so we can
702 // update LiveIntervals with it.
703 MachineBasicBlock::iterator MI = MBB->getFirstTerminator();
704 InsertedPHIDests.push_back(std::make_pair(curr.second, --MI));
706 // If curr.first is a destination in copy_set...
707 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
708 E = copy_set.end(); I != E; )
709 if (curr.first == I->second) {
710 std::pair<unsigned, unsigned> temp = *I;
712 // Avoid iterator invalidation
714 copy_set.erase(temp.first);
715 worklist.insert(temp);
723 if (!copy_set.empty()) {
724 std::pair<unsigned, unsigned> curr = *copy_set.begin();
725 copy_set.erase(curr.first);
727 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
729 // Insert a copy from dest to a new temporary t at the end of b
730 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
731 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
732 curr.second, RC, RC);
733 map[curr.second] = t;
735 worklist.insert(curr);
739 // Renumber the instructions so that we can perform the index computations
740 // needed to create new live intervals.
741 LI.computeNumbering();
743 // For copies that we inserted at the ends of predecessors, we construct
744 // live intervals. This is pretty easy, since we know that the destination
745 // register cannot have be in live at that point previously. We just have
746 // to make sure that, for registers that serve as inputs to more than one
747 // PHI, we don't create multiple overlapping live intervals.
748 std::set<unsigned> RegHandled;
749 for (SmallVector<std::pair<unsigned, MachineInstr*>, 4>::iterator I =
750 InsertedPHIDests.begin(), E = InsertedPHIDests.end(); I != E; ++I)
751 if (RegHandled.insert(I->first).second)
752 LI.addLiveRangeToEndOfBlock(I->first, I->second);
755 /// InsertCopies - insert copies into MBB and all of its successors
756 void StrongPHIElimination::InsertCopies(MachineBasicBlock* MBB,
757 SmallPtrSet<MachineBasicBlock*, 16>& visited) {
760 std::set<unsigned> pushed;
762 // Rewrite register uses from Stacks
763 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
765 for (unsigned i = 0; i < I->getNumOperands(); ++i)
766 if (I->getOperand(i).isRegister() &&
767 Stacks[I->getOperand(i).getReg()].size()) {
768 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
771 // Schedule the copies for this block
772 ScheduleCopies(MBB, pushed);
774 // Recur to our successors
775 for (GraphTraits<MachineBasicBlock*>::ChildIteratorType I =
776 GraphTraits<MachineBasicBlock*>::child_begin(MBB), E =
777 GraphTraits<MachineBasicBlock*>::child_end(MBB); I != E; ++I)
778 if (!visited.count(*I))
779 InsertCopies(*I, visited);
781 // As we exit this block, pop the names we pushed while processing it
782 for (std::set<unsigned>::iterator I = pushed.begin(),
783 E = pushed.end(); I != E; ++I)
784 Stacks[*I].pop_back();
787 void StrongPHIElimination::mergeLiveIntervals(unsigned primary,
789 MachineBasicBlock* pred) {
791 LiveIntervals& LI = getAnalysis<LiveIntervals>();
792 LiveInterval& LHS = LI.getOrCreateInterval(primary);
793 LiveInterval& RHS = LI.getOrCreateInterval(secondary);
795 LI.computeNumbering();
796 const LiveRange* RangeMergingIn =
797 RHS.getLiveRangeContaining(LI.getMBBEndIdx(pred));
798 VNInfo* RHSVN = RangeMergingIn->valno;
799 VNInfo* NewVN = LHS.getNextValue(RangeMergingIn->valno->def,
800 RangeMergingIn->valno->copy,
801 LI.getVNInfoAllocator());
803 // If we discover that a live range was defined by a two-addr
804 // instruction, we need to merge over the input as well, even if
805 // it has a different VNInfo.
806 SmallPtrSet<VNInfo*, 4> MergedVNs;
807 MergedVNs.insert(RHSVN);
809 DenseMap<VNInfo*, VNInfo*> VNMap;
810 VNMap.insert(std::make_pair(RangeMergingIn->valno, NewVN));
812 // Find all VNs that are the inputs to two-address instructiosn
813 // chaining upwards from the VN we're trying to merge.
817 unsigned defIndex = RHSVN->def;
819 if (defIndex != ~0U) {
820 MachineInstr* instr = LI.getInstructionFromIndex(defIndex);
822 for (unsigned i = 0; i < instr->getNumOperands(); ++i) {
823 if (instr->getOperand(i).isReg() &&
824 instr->getOperand(i).getReg() == secondary)
825 if (instr->isRegReDefinedByTwoAddr(secondary, i)) {
826 RHSVN = RHS.getLiveRangeContaining(defIndex-1)->valno;
829 VNInfo* NextVN = LHS.getNextValue(RHSVN->def,
831 LI.getVNInfoAllocator());
832 VNMap.insert(std::make_pair(RHSVN, NextVN));
840 // Merge VNs from RHS into LHS using the mapping we computed above.
841 for (DenseMap<VNInfo*, VNInfo*>::iterator VI = VNMap.begin(),
842 VE = VNMap.end(); VI != VE; ++VI) {
843 LHS.MergeValueInAsValue(RHS, VI->first, VI->second);
844 RHS.removeValNo(VI->first);
847 if (RHS.begin() == RHS.end())
848 LI.removeInterval(RHS.reg);
851 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
852 LiveIntervals& LI = getAnalysis<LiveIntervals>();
854 // Compute DFS numbers of each block
857 // Determine which phi node operands need copies
858 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
860 I->begin()->getOpcode() == TargetInstrInfo::PHI)
863 // Break interferences where two different phis want to coalesce
864 // in the same register.
865 std::set<unsigned> seen;
866 typedef std::map<unsigned, std::map<unsigned, MachineBasicBlock*> >
868 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
870 for (std::map<unsigned, MachineBasicBlock*>::iterator
871 OI = I->second.begin(), OE = I->second.end(); OI != OE; ) {
872 if (!seen.count(OI->first)) {
873 seen.insert(OI->first);
876 Waiting[OI->second].insert(std::make_pair(OI->first, I->first));
877 unsigned reg = OI->first;
879 I->second.erase(reg);
885 // FIXME: This process should probably preserve LiveIntervals
886 SmallPtrSet<MachineBasicBlock*, 16> visited;
887 InsertCopies(Fn.begin(), visited);
890 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
892 while (I->second.size()) {
893 std::map<unsigned, MachineBasicBlock*>::iterator SI = I->second.begin();
895 if (SI->first != I->first) {
896 mergeLiveIntervals(I->first, SI->first, SI->second);
897 Fn.getRegInfo().replaceRegWith(SI->first, I->first);
899 if (RenameSets.count(SI->first)) {
900 I->second.insert(RenameSets[SI->first].begin(),
901 RenameSets[SI->first].end());
902 RenameSets.erase(SI->first);
908 I->second.erase(SI->first);
911 // FIXME: Insert last-minute copies
914 std::vector<MachineInstr*> phis;
915 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
916 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
918 if (BI->getOpcode() == TargetInstrInfo::PHI)
922 for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
924 MachineInstr* PInstr = *(I++);
926 // If this is a dead PHI node, then remove it from LiveIntervals.
927 unsigned DestReg = PInstr->getOperand(0).getReg();
928 LiveInterval& PI = LI.getInterval(DestReg);
929 if (PInstr->registerDefIsDead(DestReg)) {
930 if (PI.containsOneValue()) {
931 LI.removeInterval(DestReg);
933 unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
934 PI.removeRange(*PI.getLiveRangeContaining(idx), true);
937 // Trim live intervals of input registers. They are no longer live into
938 // this block if they died after the PHI. If they lived after it, don't
939 // trim them because they might have other legitimate uses.
940 for (unsigned i = 1; i < PInstr->getNumOperands(); i += 2) {
941 unsigned reg = PInstr->getOperand(i).getReg();
943 MachineBasicBlock* MBB = PInstr->getOperand(i+1).getMBB();
944 LiveInterval& InputI = LI.getInterval(reg);
945 if (MBB != PInstr->getParent() &&
946 InputI.liveAt(LI.getMBBStartIdx(PInstr->getParent())) &&
947 InputI.expiredAt(LI.getInstructionIndex(PInstr) +
948 LiveIntervals::InstrSlots::NUM))
949 InputI.removeRange(LI.getMBBStartIdx(PInstr->getParent()),
950 LI.getInstructionIndex(PInstr),
954 // If the PHI is not dead, then the valno defined by the PHI
955 // now has an unknown def.
956 unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
957 const LiveRange* PLR = PI.getLiveRangeContaining(idx);
958 PLR->valno->def = ~0U;
959 LiveRange R (LI.getMBBStartIdx(PInstr->getParent()),
960 PLR->start, PLR->valno);
964 LI.RemoveMachineInstrFromMaps(PInstr);
965 PInstr->eraseFromParent();
968 LI.computeNumbering();