Remove includes of Support/Compiler.h that are no longer needed after the
[llvm.git] / lib / CodeGen / StrongPHIElimination.cpp
blob5658a65abc879733123c66d0a1beca040e6f0dcd
1 //===- StrongPhiElimination.cpp - Eliminate PHI nodes by inserting copies -===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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:
13 //
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/Debug.h"
36 using namespace llvm;
38 namespace {
39 struct StrongPHIElimination : public MachineFunctionPass {
40 static char ID; // Pass identification, replacement for typeid
41 StrongPHIElimination() : MachineFunctionPass(&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::multimap<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.setPreservesCFG();
74 AU.addRequired<MachineDominatorTree>();
75 AU.addRequired<LiveIntervals>();
77 // TODO: Actually make this true.
78 AU.addPreserved<LiveIntervals>();
79 AU.addPreserved<RegisterCoalescer>();
80 MachineFunctionPass::getAnalysisUsage(AU);
83 virtual void releaseMemory() {
84 preorder.clear();
85 maxpreorder.clear();
87 Waiting.clear();
88 Stacks.clear();
89 UsedByAnother.clear();
90 RenameSets.clear();
93 private:
95 /// DomForestNode - Represents a node in the "dominator forest". This is
96 /// a forest in which the nodes represent registers and the edges
97 /// represent a dominance relation in the block defining those registers.
98 struct DomForestNode {
99 private:
100 // Store references to our children
101 std::vector<DomForestNode*> children;
102 // The register we represent
103 unsigned reg;
105 // Add another node as our child
106 void addChild(DomForestNode* DFN) { children.push_back(DFN); }
108 public:
109 typedef std::vector<DomForestNode*>::iterator iterator;
111 // Create a DomForestNode by providing the register it represents, and
112 // the node to be its parent. The virtual root node has register 0
113 // and a null parent.
114 DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
115 if (parent)
116 parent->addChild(this);
119 ~DomForestNode() {
120 for (iterator I = begin(), E = end(); I != E; ++I)
121 delete *I;
124 /// getReg - Return the regiser that this node represents
125 inline unsigned getReg() { return reg; }
127 // Provide iterator access to our children
128 inline DomForestNode::iterator begin() { return children.begin(); }
129 inline DomForestNode::iterator end() { return children.end(); }
132 void computeDFS(MachineFunction& MF);
133 void processBlock(MachineBasicBlock* MBB);
135 std::vector<DomForestNode*> computeDomForest(
136 std::map<unsigned, MachineBasicBlock*>& instrs,
137 MachineRegisterInfo& MRI);
138 void processPHIUnion(MachineInstr* Inst,
139 std::map<unsigned, MachineBasicBlock*>& PHIUnion,
140 std::vector<StrongPHIElimination::DomForestNode*>& DF,
141 std::vector<std::pair<unsigned, unsigned> >& locals);
142 void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
143 void InsertCopies(MachineDomTreeNode* MBB,
144 SmallPtrSet<MachineBasicBlock*, 16>& v);
145 bool mergeLiveIntervals(unsigned primary, unsigned secondary);
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;
163 unsigned time = 0;
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);
177 ++time;
178 preorder.insert(std::make_pair(currNode->getBlock(), time));
181 bool inserted = false;
182 for (MachineDomTreeNode::iterator I = currNode->begin(), E = currNode->end();
183 I != E; ++I)
184 if (!frontier.count(*I) && !visited.count(*I)) {
185 worklist.push_back(*I);
186 inserted = true;
187 break;
190 if (!inserted) {
191 frontier.erase(currNode);
192 visited.insert(currNode);
193 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
195 worklist.pop_back();
200 namespace {
202 /// PreorderSorter - a helper class that is used to sort registers
203 /// according to the preorder number of their defining blocks
204 class PreorderSorter {
205 private:
206 DenseMap<MachineBasicBlock*, unsigned>& preorder;
207 MachineRegisterInfo& MRI;
209 public:
210 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
211 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
213 bool operator()(unsigned A, unsigned B) {
214 if (A == B)
215 return false;
217 MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
218 MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
220 if (preorder[ABlock] < preorder[BBlock])
221 return true;
222 else if (preorder[ABlock] > preorder[BBlock])
223 return false;
225 return false;
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();
260 I != E; ++I) {
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]) {
269 stack.pop_back();
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());
289 return ret;
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,
295 LiveIntervals& LI) {
296 LiveInterval& I = LI.getOrCreateInterval(r);
297 LiveIndex idx = LI.getMBBStartIdx(MBB);
298 return I.liveAt(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,
304 LiveIntervals& LI) {
305 for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
306 E = MBB->succ_end(); PI != E; ++PI)
307 if (isLiveIn(r, *PI, LI))
308 return true;
310 return false;
313 /// interferes - checks for local interferences by scanning a block. The only
314 /// trick parameter is 'mode' which tells it the relationship of the two
315 /// registers. 0 - defined in the same block, 1 - first properly dominates
316 /// second, 2 - second properly dominates first
317 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
318 LiveIntervals& LV, unsigned mode) {
319 MachineInstr* def = 0;
320 MachineInstr* kill = 0;
322 // The code is still in SSA form at this point, so there is only one
323 // definition per VReg. Thus we can safely use MRI->getVRegDef().
324 const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
326 bool interference = false;
328 // Wallk the block, checking for interferences
329 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
330 MBI != MBE; ++MBI) {
331 MachineInstr* curr = MBI;
333 // Same defining block...
334 if (mode == 0) {
335 if (curr == MRI->getVRegDef(a)) {
336 // If we find our first definition, save it
337 if (!def) {
338 def = curr;
339 // If there's already an unkilled definition, then
340 // this is an interference
341 } else if (!kill) {
342 interference = true;
343 break;
344 // If there's a definition followed by a KillInst, then
345 // they can't interfere
346 } else {
347 interference = false;
348 break;
350 // Symmetric with the above
351 } else if (curr == MRI->getVRegDef(b)) {
352 if (!def) {
353 def = curr;
354 } else if (!kill) {
355 interference = true;
356 break;
357 } else {
358 interference = false;
359 break;
361 // Store KillInsts if they match up with the definition
362 } else if (curr->killsRegister(a)) {
363 if (def == MRI->getVRegDef(a)) {
364 kill = curr;
365 } else if (curr->killsRegister(b)) {
366 if (def == MRI->getVRegDef(b)) {
367 kill = curr;
371 // First properly dominates second...
372 } else if (mode == 1) {
373 if (curr == MRI->getVRegDef(b)) {
374 // Definition of second without kill of first is an interference
375 if (!kill) {
376 interference = true;
377 break;
378 // Definition after a kill is a non-interference
379 } else {
380 interference = false;
381 break;
383 // Save KillInsts of First
384 } else if (curr->killsRegister(a)) {
385 kill = curr;
387 // Symmetric with the above
388 } else if (mode == 2) {
389 if (curr == MRI->getVRegDef(a)) {
390 if (!kill) {
391 interference = true;
392 break;
393 } else {
394 interference = false;
395 break;
397 } else if (curr->killsRegister(b)) {
398 kill = curr;
403 return interference;
406 /// processBlock - Determine how to break up PHIs in the current block. Each
407 /// PHI is broken up by some combination of renaming its operands and inserting
408 /// copies. This method is responsible for determining which operands receive
409 /// which treatment.
410 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
411 LiveIntervals& LI = getAnalysis<LiveIntervals>();
412 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
414 // Holds names that have been added to a set in any PHI within this block
415 // before the current one.
416 std::set<unsigned> ProcessedNames;
418 // Iterate over all the PHI nodes in this block
419 MachineBasicBlock::iterator P = MBB->begin();
420 while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
421 unsigned DestReg = P->getOperand(0).getReg();
423 // Don't both doing PHI elimination for dead PHI's.
424 if (P->registerDefIsDead(DestReg)) {
425 ++P;
426 continue;
429 LiveInterval& PI = LI.getOrCreateInterval(DestReg);
430 LiveIndex pIdx = LI.getDefIndex(LI.getInstructionIndex(P));
431 VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
432 PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
434 // PHIUnion is the set of incoming registers to the PHI node that
435 // are going to be renames rather than having copies inserted. This set
436 // is refinded over the course of this function. UnionedBlocks is the set
437 // of corresponding MBBs.
438 std::map<unsigned, MachineBasicBlock*> PHIUnion;
439 SmallPtrSet<MachineBasicBlock*, 8> UnionedBlocks;
441 // Iterate over the operands of the PHI node
442 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
443 unsigned SrcReg = P->getOperand(i-1).getReg();
445 // Don't need to try to coalesce a register with itself.
446 if (SrcReg == DestReg) {
447 ProcessedNames.insert(SrcReg);
448 continue;
451 // We don't need to insert copies for implicit_defs.
452 MachineInstr* DefMI = MRI.getVRegDef(SrcReg);
453 if (DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
454 ProcessedNames.insert(SrcReg);
456 // Check for trivial interferences via liveness information, allowing us
457 // to avoid extra work later. Any registers that interfere cannot both
458 // be in the renaming set, so choose one and add copies for it instead.
459 // The conditions are:
460 // 1) if the operand is live into the PHI node's block OR
461 // 2) if the PHI node is live out of the operand's defining block OR
462 // 3) if the operand is itself a PHI node and the original PHI is
463 // live into the operand's defining block OR
464 // 4) if the operand is already being renamed for another PHI node
465 // in this block OR
466 // 5) if any two operands are defined in the same block, insert copies
467 // for one of them
468 if (isLiveIn(SrcReg, P->getParent(), LI) ||
469 isLiveOut(P->getOperand(0).getReg(),
470 MRI.getVRegDef(SrcReg)->getParent(), LI) ||
471 ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
472 isLiveIn(P->getOperand(0).getReg(),
473 MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
474 ProcessedNames.count(SrcReg) ||
475 UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
477 // Add a copy for the selected register
478 MachineBasicBlock* From = P->getOperand(i).getMBB();
479 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
480 UsedByAnother.insert(SrcReg);
481 } else {
482 // Otherwise, add it to the renaming set
483 PHIUnion.insert(std::make_pair(SrcReg,P->getOperand(i).getMBB()));
484 UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
488 // Compute the dominator forest for the renaming set. This is a forest
489 // where the nodes are the registers and the edges represent dominance
490 // relations between the defining blocks of the registers
491 std::vector<StrongPHIElimination::DomForestNode*> DF =
492 computeDomForest(PHIUnion, MRI);
494 // Walk DomForest to resolve interferences at an inter-block level. This
495 // will remove registers from the renaming set (and insert copies for them)
496 // if interferences are found.
497 std::vector<std::pair<unsigned, unsigned> > localInterferences;
498 processPHIUnion(P, PHIUnion, DF, localInterferences);
500 // If one of the inputs is defined in the same block as the current PHI
501 // then we need to check for a local interference between that input and
502 // the PHI.
503 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
504 E = PHIUnion.end(); I != E; ++I)
505 if (MRI.getVRegDef(I->first)->getParent() == P->getParent())
506 localInterferences.push_back(std::make_pair(I->first,
507 P->getOperand(0).getReg()));
509 // The dominator forest walk may have returned some register pairs whose
510 // interference cannot be determined from dominator analysis. We now
511 // examine these pairs for local interferences.
512 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
513 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
514 std::pair<unsigned, unsigned> p = *I;
516 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
518 // Determine the block we need to scan and the relationship between
519 // the two registers
520 MachineBasicBlock* scan = 0;
521 unsigned mode = 0;
522 if (MRI.getVRegDef(p.first)->getParent() ==
523 MRI.getVRegDef(p.second)->getParent()) {
524 scan = MRI.getVRegDef(p.first)->getParent();
525 mode = 0; // Same block
526 } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
527 MRI.getVRegDef(p.second)->getParent())) {
528 scan = MRI.getVRegDef(p.second)->getParent();
529 mode = 1; // First dominates second
530 } else {
531 scan = MRI.getVRegDef(p.first)->getParent();
532 mode = 2; // Second dominates first
535 // If there's an interference, we need to insert copies
536 if (interferes(p.first, p.second, scan, LI, mode)) {
537 // Insert copies for First
538 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
539 if (P->getOperand(i-1).getReg() == p.first) {
540 unsigned SrcReg = p.first;
541 MachineBasicBlock* From = P->getOperand(i).getMBB();
543 Waiting[From].insert(std::make_pair(SrcReg,
544 P->getOperand(0).getReg()));
545 UsedByAnother.insert(SrcReg);
547 PHIUnion.erase(SrcReg);
553 // Add the renaming set for this PHI node to our overall renaming information
554 for (std::map<unsigned, MachineBasicBlock*>::iterator QI = PHIUnion.begin(),
555 QE = PHIUnion.end(); QI != QE; ++QI) {
556 DEBUG(errs() << "Adding Renaming: " << QI->first << " -> "
557 << P->getOperand(0).getReg() << "\n");
560 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
562 // Remember which registers are already renamed, so that we don't try to
563 // rename them for another PHI node in this block
564 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
565 E = PHIUnion.end(); I != E; ++I)
566 ProcessedNames.insert(I->first);
568 ++P;
572 /// processPHIUnion - Take a set of candidate registers to be coalesced when
573 /// decomposing the PHI instruction. Use the DominanceForest to remove the ones
574 /// that are known to interfere, and flag others that need to be checked for
575 /// local interferences.
576 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
577 std::map<unsigned, MachineBasicBlock*>& PHIUnion,
578 std::vector<StrongPHIElimination::DomForestNode*>& DF,
579 std::vector<std::pair<unsigned, unsigned> >& locals) {
581 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
582 SmallPtrSet<DomForestNode*, 4> visited;
584 // Code is still in SSA form, so we can use MRI::getVRegDef()
585 MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
587 LiveIntervals& LI = getAnalysis<LiveIntervals>();
588 unsigned DestReg = Inst->getOperand(0).getReg();
590 // DF walk on the DomForest
591 while (!worklist.empty()) {
592 DomForestNode* DFNode = worklist.back();
594 visited.insert(DFNode);
596 bool inserted = false;
597 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
598 CI != CE; ++CI) {
599 DomForestNode* child = *CI;
601 // If the current node is live-out of the defining block of one of its
602 // children, insert a copy for it. NOTE: The paper actually calls for
603 // a more elaborate heuristic for determining whether to insert copies
604 // for the child or the parent. In the interest of simplicity, we're
605 // just always choosing the parent.
606 if (isLiveOut(DFNode->getReg(),
607 MRI.getVRegDef(child->getReg())->getParent(), LI)) {
608 // Insert copies for parent
609 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
610 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
611 unsigned SrcReg = DFNode->getReg();
612 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
614 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
615 UsedByAnother.insert(SrcReg);
617 PHIUnion.erase(SrcReg);
621 // If a node is live-in to the defining block of one of its children, but
622 // not live-out, then we need to scan that block for local interferences.
623 } else if (isLiveIn(DFNode->getReg(),
624 MRI.getVRegDef(child->getReg())->getParent(), LI) ||
625 MRI.getVRegDef(DFNode->getReg())->getParent() ==
626 MRI.getVRegDef(child->getReg())->getParent()) {
627 // Add (p, c) to possible local interferences
628 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
631 if (!visited.count(child)) {
632 worklist.push_back(child);
633 inserted = true;
637 if (!inserted) worklist.pop_back();
641 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
642 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
643 /// problems.
645 /// Based on "Practical Improvements to the Construction and Destruction
646 /// of Static Single Assignment Form" by Briggs, et al.
647 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
648 std::set<unsigned>& pushed) {
649 // FIXME: This function needs to update LiveIntervals
650 std::multimap<unsigned, unsigned>& copy_set= Waiting[MBB];
652 std::multimap<unsigned, unsigned> worklist;
653 std::map<unsigned, unsigned> map;
655 // Setup worklist of initial copies
656 for (std::multimap<unsigned, unsigned>::iterator I = copy_set.begin(),
657 E = copy_set.end(); I != E; ) {
658 map.insert(std::make_pair(I->first, I->first));
659 map.insert(std::make_pair(I->second, I->second));
661 if (!UsedByAnother.count(I->second)) {
662 worklist.insert(*I);
664 // Avoid iterator invalidation
665 std::multimap<unsigned, unsigned>::iterator OI = I;
666 ++I;
667 copy_set.erase(OI);
668 } else {
669 ++I;
673 LiveIntervals& LI = getAnalysis<LiveIntervals>();
674 MachineFunction* MF = MBB->getParent();
675 MachineRegisterInfo& MRI = MF->getRegInfo();
676 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
678 SmallVector<std::pair<unsigned, MachineInstr*>, 4> InsertedPHIDests;
680 // Iterate over the worklist, inserting copies
681 while (!worklist.empty() || !copy_set.empty()) {
682 while (!worklist.empty()) {
683 std::multimap<unsigned, unsigned>::iterator WI = worklist.begin();
684 std::pair<unsigned, unsigned> curr = *WI;
685 worklist.erase(WI);
687 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
689 if (isLiveOut(curr.second, MBB, LI)) {
690 // Create a temporary
691 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
693 // Insert copy from curr.second to a temporary at
694 // the Phi defining curr.second
695 MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
696 TII->copyRegToReg(*PI->getParent(), PI, t,
697 curr.second, RC, RC);
699 DEBUG(errs() << "Inserted copy from " << curr.second << " to " << t
700 << "\n");
702 // Push temporary on Stacks
703 Stacks[curr.second].push_back(t);
705 // Insert curr.second in pushed
706 pushed.insert(curr.second);
708 // Create a live interval for this temporary
709 InsertedPHIDests.push_back(std::make_pair(t, --PI));
712 // Insert copy from map[curr.first] to curr.second
713 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
714 map[curr.first], RC, RC);
715 map[curr.first] = curr.second;
716 DEBUG(errs() << "Inserted copy from " << curr.first << " to "
717 << curr.second << "\n");
719 // Push this copy onto InsertedPHICopies so we can
720 // update LiveIntervals with it.
721 MachineBasicBlock::iterator MI = MBB->getFirstTerminator();
722 InsertedPHIDests.push_back(std::make_pair(curr.second, --MI));
724 // If curr.first is a destination in copy_set...
725 for (std::multimap<unsigned, unsigned>::iterator I = copy_set.begin(),
726 E = copy_set.end(); I != E; )
727 if (curr.first == I->second) {
728 std::pair<unsigned, unsigned> temp = *I;
729 worklist.insert(temp);
731 // Avoid iterator invalidation
732 std::multimap<unsigned, unsigned>::iterator OI = I;
733 ++I;
734 copy_set.erase(OI);
736 break;
737 } else {
738 ++I;
742 if (!copy_set.empty()) {
743 std::multimap<unsigned, unsigned>::iterator CI = copy_set.begin();
744 std::pair<unsigned, unsigned> curr = *CI;
745 worklist.insert(curr);
746 copy_set.erase(CI);
748 LiveInterval& I = LI.getInterval(curr.second);
749 MachineBasicBlock::iterator term = MBB->getFirstTerminator();
750 LiveIndex endIdx = LiveIndex();
751 if (term != MBB->end())
752 endIdx = LI.getInstructionIndex(term);
753 else
754 endIdx = LI.getMBBEndIdx(MBB);
756 if (I.liveAt(endIdx)) {
757 const TargetRegisterClass *RC =
758 MF->getRegInfo().getRegClass(curr.first);
760 // Insert a copy from dest to a new temporary t at the end of b
761 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
762 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
763 curr.second, RC, RC);
764 map[curr.second] = t;
766 MachineBasicBlock::iterator TI = MBB->getFirstTerminator();
767 InsertedPHIDests.push_back(std::make_pair(t, --TI));
772 // Renumber the instructions so that we can perform the index computations
773 // needed to create new live intervals.
774 LI.computeNumbering();
776 // For copies that we inserted at the ends of predecessors, we construct
777 // live intervals. This is pretty easy, since we know that the destination
778 // register cannot have be in live at that point previously. We just have
779 // to make sure that, for registers that serve as inputs to more than one
780 // PHI, we don't create multiple overlapping live intervals.
781 std::set<unsigned> RegHandled;
782 for (SmallVector<std::pair<unsigned, MachineInstr*>, 4>::iterator I =
783 InsertedPHIDests.begin(), E = InsertedPHIDests.end(); I != E; ++I) {
784 if (RegHandled.insert(I->first).second) {
785 LiveInterval& Int = LI.getOrCreateInterval(I->first);
786 LiveIndex instrIdx = LI.getInstructionIndex(I->second);
787 if (Int.liveAt(LI.getDefIndex(instrIdx)))
788 Int.removeRange(LI.getDefIndex(instrIdx),
789 LI.getNextSlot(LI.getMBBEndIdx(I->second->getParent())),
790 true);
792 LiveRange R = LI.addLiveRangeToEndOfBlock(I->first, I->second);
793 R.valno->setCopy(I->second);
794 R.valno->def = LI.getDefIndex(LI.getInstructionIndex(I->second));
799 /// InsertCopies - insert copies into MBB and all of its successors
800 void StrongPHIElimination::InsertCopies(MachineDomTreeNode* MDTN,
801 SmallPtrSet<MachineBasicBlock*, 16>& visited) {
802 MachineBasicBlock* MBB = MDTN->getBlock();
803 visited.insert(MBB);
805 std::set<unsigned> pushed;
807 LiveIntervals& LI = getAnalysis<LiveIntervals>();
808 // Rewrite register uses from Stacks
809 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
810 I != E; ++I) {
811 if (I->getOpcode() == TargetInstrInfo::PHI)
812 continue;
814 for (unsigned i = 0; i < I->getNumOperands(); ++i)
815 if (I->getOperand(i).isReg() &&
816 Stacks[I->getOperand(i).getReg()].size()) {
817 // Remove the live range for the old vreg.
818 LiveInterval& OldInt = LI.getInterval(I->getOperand(i).getReg());
819 LiveInterval::iterator OldLR = OldInt.FindLiveRangeContaining(
820 LI.getUseIndex(LI.getInstructionIndex(I)));
821 if (OldLR != OldInt.end())
822 OldInt.removeRange(*OldLR, true);
824 // Change the register
825 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
827 // Add a live range for the new vreg
828 LiveInterval& Int = LI.getInterval(I->getOperand(i).getReg());
829 VNInfo* FirstVN = *Int.vni_begin();
830 FirstVN->setHasPHIKill(false);
831 if (I->getOperand(i).isKill())
832 FirstVN->addKill(
833 LI.getUseIndex(LI.getInstructionIndex(I)));
835 LiveRange LR (LI.getMBBStartIdx(I->getParent()),
836 LI.getNextSlot(LI.getUseIndex(LI.getInstructionIndex(I))),
837 FirstVN);
839 Int.addRange(LR);
843 // Schedule the copies for this block
844 ScheduleCopies(MBB, pushed);
846 // Recur down the dominator tree.
847 for (MachineDomTreeNode::iterator I = MDTN->begin(),
848 E = MDTN->end(); I != E; ++I)
849 if (!visited.count((*I)->getBlock()))
850 InsertCopies(*I, visited);
852 // As we exit this block, pop the names we pushed while processing it
853 for (std::set<unsigned>::iterator I = pushed.begin(),
854 E = pushed.end(); I != E; ++I)
855 Stacks[*I].pop_back();
858 bool StrongPHIElimination::mergeLiveIntervals(unsigned primary,
859 unsigned secondary) {
861 LiveIntervals& LI = getAnalysis<LiveIntervals>();
862 LiveInterval& LHS = LI.getOrCreateInterval(primary);
863 LiveInterval& RHS = LI.getOrCreateInterval(secondary);
865 LI.computeNumbering();
867 DenseMap<VNInfo*, VNInfo*> VNMap;
868 for (LiveInterval::iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
869 LiveRange R = *I;
871 LiveIndex Start = R.start;
872 LiveIndex End = R.end;
873 if (LHS.getLiveRangeContaining(Start))
874 return false;
876 if (LHS.getLiveRangeContaining(End))
877 return false;
879 LiveInterval::iterator RI = std::upper_bound(LHS.begin(), LHS.end(), R);
880 if (RI != LHS.end() && RI->start < End)
881 return false;
884 for (LiveInterval::iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
885 LiveRange R = *I;
886 VNInfo* OldVN = R.valno;
887 VNInfo*& NewVN = VNMap[OldVN];
888 if (!NewVN) {
889 NewVN = LHS.createValueCopy(OldVN, LI.getVNInfoAllocator());
892 LiveRange LR (R.start, R.end, NewVN);
893 LHS.addRange(LR);
896 LI.removeInterval(RHS.reg);
898 return true;
901 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
902 LiveIntervals& LI = getAnalysis<LiveIntervals>();
904 // Compute DFS numbers of each block
905 computeDFS(Fn);
907 // Determine which phi node operands need copies
908 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
909 if (!I->empty() &&
910 I->begin()->getOpcode() == TargetInstrInfo::PHI)
911 processBlock(I);
913 // Break interferences where two different phis want to coalesce
914 // in the same register.
915 std::set<unsigned> seen;
916 typedef std::map<unsigned, std::map<unsigned, MachineBasicBlock*> >
917 RenameSetType;
918 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
919 I != E; ++I) {
920 for (std::map<unsigned, MachineBasicBlock*>::iterator
921 OI = I->second.begin(), OE = I->second.end(); OI != OE; ) {
922 if (!seen.count(OI->first)) {
923 seen.insert(OI->first);
924 ++OI;
925 } else {
926 Waiting[OI->second].insert(std::make_pair(OI->first, I->first));
927 unsigned reg = OI->first;
928 ++OI;
929 I->second.erase(reg);
930 DEBUG(errs() << "Removing Renaming: " << reg << " -> " << I->first
931 << "\n");
936 // Insert copies
937 // FIXME: This process should probably preserve LiveIntervals
938 SmallPtrSet<MachineBasicBlock*, 16> visited;
939 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
940 InsertCopies(MDT.getRootNode(), visited);
942 // Perform renaming
943 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
944 I != E; ++I)
945 while (I->second.size()) {
946 std::map<unsigned, MachineBasicBlock*>::iterator SI = I->second.begin();
948 DEBUG(errs() << "Renaming: " << SI->first << " -> " << I->first << "\n");
950 if (SI->first != I->first) {
951 if (mergeLiveIntervals(I->first, SI->first)) {
952 Fn.getRegInfo().replaceRegWith(SI->first, I->first);
954 if (RenameSets.count(SI->first)) {
955 I->second.insert(RenameSets[SI->first].begin(),
956 RenameSets[SI->first].end());
957 RenameSets.erase(SI->first);
959 } else {
960 // Insert a last-minute copy if a conflict was detected.
961 const TargetInstrInfo *TII = Fn.getTarget().getInstrInfo();
962 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(I->first);
963 TII->copyRegToReg(*SI->second, SI->second->getFirstTerminator(),
964 I->first, SI->first, RC, RC);
966 LI.computeNumbering();
968 LiveInterval& Int = LI.getOrCreateInterval(I->first);
969 LiveIndex instrIdx =
970 LI.getInstructionIndex(--SI->second->getFirstTerminator());
971 if (Int.liveAt(LI.getDefIndex(instrIdx)))
972 Int.removeRange(LI.getDefIndex(instrIdx),
973 LI.getNextSlot(LI.getMBBEndIdx(SI->second)), true);
975 LiveRange R = LI.addLiveRangeToEndOfBlock(I->first,
976 --SI->second->getFirstTerminator());
977 R.valno->setCopy(--SI->second->getFirstTerminator());
978 R.valno->def = LI.getDefIndex(instrIdx);
980 DEBUG(errs() << "Renaming failed: " << SI->first << " -> "
981 << I->first << "\n");
985 LiveInterval& Int = LI.getOrCreateInterval(I->first);
986 const LiveRange* LR =
987 Int.getLiveRangeContaining(LI.getMBBEndIdx(SI->second));
988 LR->valno->setHasPHIKill(true);
990 I->second.erase(SI->first);
993 // Remove PHIs
994 std::vector<MachineInstr*> phis;
995 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
996 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
997 BI != BE; ++BI)
998 if (BI->getOpcode() == TargetInstrInfo::PHI)
999 phis.push_back(BI);
1002 for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
1003 I != E; ) {
1004 MachineInstr* PInstr = *(I++);
1006 // If this is a dead PHI node, then remove it from LiveIntervals.
1007 unsigned DestReg = PInstr->getOperand(0).getReg();
1008 LiveInterval& PI = LI.getInterval(DestReg);
1009 if (PInstr->registerDefIsDead(DestReg)) {
1010 if (PI.containsOneValue()) {
1011 LI.removeInterval(DestReg);
1012 } else {
1013 LiveIndex idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
1014 PI.removeRange(*PI.getLiveRangeContaining(idx), true);
1016 } else {
1017 // Trim live intervals of input registers. They are no longer live into
1018 // this block if they died after the PHI. If they lived after it, don't
1019 // trim them because they might have other legitimate uses.
1020 for (unsigned i = 1; i < PInstr->getNumOperands(); i += 2) {
1021 unsigned reg = PInstr->getOperand(i).getReg();
1023 MachineBasicBlock* MBB = PInstr->getOperand(i+1).getMBB();
1024 LiveInterval& InputI = LI.getInterval(reg);
1025 if (MBB != PInstr->getParent() &&
1026 InputI.liveAt(LI.getMBBStartIdx(PInstr->getParent())) &&
1027 InputI.expiredAt(LI.getNextIndex(LI.getInstructionIndex(PInstr))))
1028 InputI.removeRange(LI.getMBBStartIdx(PInstr->getParent()),
1029 LI.getInstructionIndex(PInstr),
1030 true);
1033 // If the PHI is not dead, then the valno defined by the PHI
1034 // now has an unknown def.
1035 LiveIndex idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
1036 const LiveRange* PLR = PI.getLiveRangeContaining(idx);
1037 PLR->valno->setIsPHIDef(true);
1038 LiveRange R (LI.getMBBStartIdx(PInstr->getParent()),
1039 PLR->start, PLR->valno);
1040 PI.addRange(R);
1043 LI.RemoveMachineInstrFromMaps(PInstr);
1044 PInstr->eraseFromParent();
1047 LI.computeNumbering();
1049 return true;