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"
36 #include "llvm/Support/Debug.h"
40 struct VISIBILITY_HIDDEN StrongPHIElimination
: public MachineFunctionPass
{
41 static char ID
; // Pass identification, replacement for typeid
42 StrongPHIElimination() : MachineFunctionPass(&ID
) {}
44 // Waiting stores, for each MBB, the set of copies that need to
45 // be inserted into that MBB
46 DenseMap
<MachineBasicBlock
*,
47 std::multimap
<unsigned, unsigned> > Waiting
;
49 // Stacks holds the renaming stack for each register
50 std::map
<unsigned, std::vector
<unsigned> > Stacks
;
52 // Registers in UsedByAnother are PHI nodes that are themselves
53 // used as operands to another another PHI node
54 std::set
<unsigned> UsedByAnother
;
56 // RenameSets are the is a map from a PHI-defined register
57 // to the input registers to be coalesced along with the
58 // predecessor block for those input registers.
59 std::map
<unsigned, std::map
<unsigned, MachineBasicBlock
*> > RenameSets
;
61 // PhiValueNumber holds the ID numbers of the VNs for each phi that we're
62 // eliminating, indexed by the register defined by that phi.
63 std::map
<unsigned, unsigned> PhiValueNumber
;
65 // Store the DFS-in number of each block
66 DenseMap
<MachineBasicBlock
*, unsigned> preorder
;
68 // Store the DFS-out number of each block
69 DenseMap
<MachineBasicBlock
*, unsigned> maxpreorder
;
71 bool runOnMachineFunction(MachineFunction
&Fn
);
73 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
75 AU
.addRequired
<MachineDominatorTree
>();
76 AU
.addRequired
<LiveIntervals
>();
78 // TODO: Actually make this true.
79 AU
.addPreserved
<LiveIntervals
>();
80 AU
.addPreserved
<RegisterCoalescer
>();
81 MachineFunctionPass::getAnalysisUsage(AU
);
84 virtual void releaseMemory() {
90 UsedByAnother
.clear();
96 /// DomForestNode - Represents a node in the "dominator forest". This is
97 /// a forest in which the nodes represent registers and the edges
98 /// represent a dominance relation in the block defining those registers.
99 struct DomForestNode
{
101 // Store references to our children
102 std::vector
<DomForestNode
*> children
;
103 // The register we represent
106 // Add another node as our child
107 void addChild(DomForestNode
* DFN
) { children
.push_back(DFN
); }
110 typedef std::vector
<DomForestNode
*>::iterator iterator
;
112 // Create a DomForestNode by providing the register it represents, and
113 // the node to be its parent. The virtual root node has register 0
114 // and a null parent.
115 DomForestNode(unsigned r
, DomForestNode
* parent
) : reg(r
) {
117 parent
->addChild(this);
121 for (iterator I
= begin(), E
= end(); I
!= E
; ++I
)
125 /// getReg - Return the regiser that this node represents
126 inline unsigned getReg() { return reg
; }
128 // Provide iterator access to our children
129 inline DomForestNode::iterator
begin() { return children
.begin(); }
130 inline DomForestNode::iterator
end() { return children
.end(); }
133 void computeDFS(MachineFunction
& MF
);
134 void processBlock(MachineBasicBlock
* MBB
);
136 std::vector
<DomForestNode
*> computeDomForest(
137 std::map
<unsigned, MachineBasicBlock
*>& instrs
,
138 MachineRegisterInfo
& MRI
);
139 void processPHIUnion(MachineInstr
* Inst
,
140 std::map
<unsigned, MachineBasicBlock
*>& PHIUnion
,
141 std::vector
<StrongPHIElimination::DomForestNode
*>& DF
,
142 std::vector
<std::pair
<unsigned, unsigned> >& locals
);
143 void ScheduleCopies(MachineBasicBlock
* MBB
, std::set
<unsigned>& pushed
);
144 void InsertCopies(MachineDomTreeNode
* MBB
,
145 SmallPtrSet
<MachineBasicBlock
*, 16>& v
);
146 bool mergeLiveIntervals(unsigned primary
, unsigned secondary
);
150 char StrongPHIElimination::ID
= 0;
151 static RegisterPass
<StrongPHIElimination
>
152 X("strong-phi-node-elimination",
153 "Eliminate PHI nodes for register allocation, intelligently");
155 const PassInfo
*const llvm::StrongPHIEliminationID
= &X
;
157 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
158 /// of the given MachineFunction. These numbers are then used in other parts
159 /// of the PHI elimination process.
160 void StrongPHIElimination::computeDFS(MachineFunction
& MF
) {
161 SmallPtrSet
<MachineDomTreeNode
*, 8> frontier
;
162 SmallPtrSet
<MachineDomTreeNode
*, 8> visited
;
166 MachineDominatorTree
& DT
= getAnalysis
<MachineDominatorTree
>();
168 MachineDomTreeNode
* node
= DT
.getRootNode();
170 std::vector
<MachineDomTreeNode
*> worklist
;
171 worklist
.push_back(node
);
173 while (!worklist
.empty()) {
174 MachineDomTreeNode
* currNode
= worklist
.back();
176 if (!frontier
.count(currNode
)) {
177 frontier
.insert(currNode
);
179 preorder
.insert(std::make_pair(currNode
->getBlock(), time
));
182 bool inserted
= false;
183 for (MachineDomTreeNode::iterator I
= currNode
->begin(), E
= currNode
->end();
185 if (!frontier
.count(*I
) && !visited
.count(*I
)) {
186 worklist
.push_back(*I
);
192 frontier
.erase(currNode
);
193 visited
.insert(currNode
);
194 maxpreorder
.insert(std::make_pair(currNode
->getBlock(), time
));
203 /// PreorderSorter - a helper class that is used to sort registers
204 /// according to the preorder number of their defining blocks
205 class PreorderSorter
{
207 DenseMap
<MachineBasicBlock
*, unsigned>& preorder
;
208 MachineRegisterInfo
& MRI
;
211 PreorderSorter(DenseMap
<MachineBasicBlock
*, unsigned>& p
,
212 MachineRegisterInfo
& M
) : preorder(p
), MRI(M
) { }
214 bool operator()(unsigned A
, unsigned B
) {
218 MachineBasicBlock
* ABlock
= MRI
.getVRegDef(A
)->getParent();
219 MachineBasicBlock
* BBlock
= MRI
.getVRegDef(B
)->getParent();
221 if (preorder
[ABlock
] < preorder
[BBlock
])
223 else if (preorder
[ABlock
] > preorder
[BBlock
])
232 /// computeDomForest - compute the subforest of the DomTree corresponding
233 /// to the defining blocks of the registers in question
234 std::vector
<StrongPHIElimination::DomForestNode
*>
235 StrongPHIElimination::computeDomForest(
236 std::map
<unsigned, MachineBasicBlock
*>& regs
,
237 MachineRegisterInfo
& MRI
) {
238 // Begin by creating a virtual root node, since the actual results
239 // may well be a forest. Assume this node has maximum DFS-out number.
240 DomForestNode
* VirtualRoot
= new DomForestNode(0, 0);
241 maxpreorder
.insert(std::make_pair((MachineBasicBlock
*)0, ~0UL));
243 // Populate a worklist with the registers
244 std::vector
<unsigned> worklist
;
245 worklist
.reserve(regs
.size());
246 for (std::map
<unsigned, MachineBasicBlock
*>::iterator I
= regs
.begin(),
247 E
= regs
.end(); I
!= E
; ++I
)
248 worklist
.push_back(I
->first
);
250 // Sort the registers by the DFS-in number of their defining block
251 PreorderSorter
PS(preorder
, MRI
);
252 std::sort(worklist
.begin(), worklist
.end(), PS
);
254 // Create a "current parent" stack, and put the virtual root on top of it
255 DomForestNode
* CurrentParent
= VirtualRoot
;
256 std::vector
<DomForestNode
*> stack
;
257 stack
.push_back(VirtualRoot
);
259 // Iterate over all the registers in the previously computed order
260 for (std::vector
<unsigned>::iterator I
= worklist
.begin(), E
= worklist
.end();
262 unsigned pre
= preorder
[MRI
.getVRegDef(*I
)->getParent()];
263 MachineBasicBlock
* parentBlock
= CurrentParent
->getReg() ?
264 MRI
.getVRegDef(CurrentParent
->getReg())->getParent() :
267 // If the DFS-in number of the register is greater than the DFS-out number
268 // of the current parent, repeatedly pop the parent stack until it isn't.
269 while (pre
> maxpreorder
[parentBlock
]) {
271 CurrentParent
= stack
.back();
273 parentBlock
= CurrentParent
->getReg() ?
274 MRI
.getVRegDef(CurrentParent
->getReg())->getParent() :
278 // Now that we've found the appropriate parent, create a DomForestNode for
279 // this register and attach it to the forest
280 DomForestNode
* child
= new DomForestNode(*I
, CurrentParent
);
282 // Push this new node on the "current parent" stack
283 stack
.push_back(child
);
284 CurrentParent
= child
;
287 // Return a vector containing the children of the virtual root node
288 std::vector
<DomForestNode
*> ret
;
289 ret
.insert(ret
.end(), VirtualRoot
->begin(), VirtualRoot
->end());
293 /// isLiveIn - helper method that determines, from a regno, if a register
294 /// is live into a block
295 static bool isLiveIn(unsigned r
, MachineBasicBlock
* MBB
,
297 LiveInterval
& I
= LI
.getOrCreateInterval(r
);
298 unsigned idx
= LI
.getMBBStartIdx(MBB
);
299 return I
.liveAt(idx
);
302 /// isLiveOut - help method that determines, from a regno, if a register is
303 /// live out of a block.
304 static bool isLiveOut(unsigned r
, MachineBasicBlock
* MBB
,
306 for (MachineBasicBlock::succ_iterator PI
= MBB
->succ_begin(),
307 E
= MBB
->succ_end(); PI
!= E
; ++PI
)
308 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();
424 // Don't both doing PHI elimination for dead PHI's.
425 if (P
->registerDefIsDead(DestReg
)) {
430 LiveInterval
& PI
= LI
.getOrCreateInterval(DestReg
);
431 unsigned pIdx
= LI
.getDefIndex(LI
.getInstructionIndex(P
));
432 VNInfo
* PVN
= PI
.getLiveRangeContaining(pIdx
)->valno
;
433 PhiValueNumber
.insert(std::make_pair(DestReg
, PVN
->id
));
435 // PHIUnion is the set of incoming registers to the PHI node that
436 // are going to be renames rather than having copies inserted. This set
437 // is refinded over the course of this function. UnionedBlocks is the set
438 // of corresponding MBBs.
439 std::map
<unsigned, MachineBasicBlock
*> PHIUnion
;
440 SmallPtrSet
<MachineBasicBlock
*, 8> UnionedBlocks
;
442 // Iterate over the operands of the PHI node
443 for (int i
= P
->getNumOperands() - 1; i
>= 2; i
-=2) {
444 unsigned SrcReg
= P
->getOperand(i
-1).getReg();
446 // Don't need to try to coalesce a register with itself.
447 if (SrcReg
== DestReg
) {
448 ProcessedNames
.insert(SrcReg
);
452 // We don't need to insert copies for implicit_defs.
453 MachineInstr
* DefMI
= MRI
.getVRegDef(SrcReg
);
454 if (DefMI
->getOpcode() == TargetInstrInfo::IMPLICIT_DEF
)
455 ProcessedNames
.insert(SrcReg
);
457 // Check for trivial interferences via liveness information, allowing us
458 // to avoid extra work later. Any registers that interfere cannot both
459 // be in the renaming set, so choose one and add copies for it instead.
460 // The conditions are:
461 // 1) if the operand is live into the PHI node's block OR
462 // 2) if the PHI node is live out of the operand's defining block OR
463 // 3) if the operand is itself a PHI node and the original PHI is
464 // live into the operand's defining block OR
465 // 4) if the operand is already being renamed for another PHI node
467 // 5) if any two operands are defined in the same block, insert copies
469 if (isLiveIn(SrcReg
, P
->getParent(), LI
) ||
470 isLiveOut(P
->getOperand(0).getReg(),
471 MRI
.getVRegDef(SrcReg
)->getParent(), LI
) ||
472 ( MRI
.getVRegDef(SrcReg
)->getOpcode() == TargetInstrInfo::PHI
&&
473 isLiveIn(P
->getOperand(0).getReg(),
474 MRI
.getVRegDef(SrcReg
)->getParent(), LI
) ) ||
475 ProcessedNames
.count(SrcReg
) ||
476 UnionedBlocks
.count(MRI
.getVRegDef(SrcReg
)->getParent())) {
478 // Add a copy for the selected register
479 MachineBasicBlock
* From
= P
->getOperand(i
).getMBB();
480 Waiting
[From
].insert(std::make_pair(SrcReg
, DestReg
));
481 UsedByAnother
.insert(SrcReg
);
483 // Otherwise, add it to the renaming set
484 PHIUnion
.insert(std::make_pair(SrcReg
,P
->getOperand(i
).getMBB()));
485 UnionedBlocks
.insert(MRI
.getVRegDef(SrcReg
)->getParent());
489 // Compute the dominator forest for the renaming set. This is a forest
490 // where the nodes are the registers and the edges represent dominance
491 // relations between the defining blocks of the registers
492 std::vector
<StrongPHIElimination::DomForestNode
*> DF
=
493 computeDomForest(PHIUnion
, MRI
);
495 // Walk DomForest to resolve interferences at an inter-block level. This
496 // will remove registers from the renaming set (and insert copies for them)
497 // if interferences are found.
498 std::vector
<std::pair
<unsigned, unsigned> > localInterferences
;
499 processPHIUnion(P
, PHIUnion
, DF
, localInterferences
);
501 // If one of the inputs is defined in the same block as the current PHI
502 // then we need to check for a local interference between that input and
504 for (std::map
<unsigned, MachineBasicBlock
*>::iterator I
= PHIUnion
.begin(),
505 E
= PHIUnion
.end(); I
!= E
; ++I
)
506 if (MRI
.getVRegDef(I
->first
)->getParent() == P
->getParent())
507 localInterferences
.push_back(std::make_pair(I
->first
,
508 P
->getOperand(0).getReg()));
510 // The dominator forest walk may have returned some register pairs whose
511 // interference cannot be determined from dominator analysis. We now
512 // examine these pairs for local interferences.
513 for (std::vector
<std::pair
<unsigned, unsigned> >::iterator I
=
514 localInterferences
.begin(), E
= localInterferences
.end(); I
!= E
; ++I
) {
515 std::pair
<unsigned, unsigned> p
= *I
;
517 MachineDominatorTree
& MDT
= getAnalysis
<MachineDominatorTree
>();
519 // Determine the block we need to scan and the relationship between
521 MachineBasicBlock
* scan
= 0;
523 if (MRI
.getVRegDef(p
.first
)->getParent() ==
524 MRI
.getVRegDef(p
.second
)->getParent()) {
525 scan
= MRI
.getVRegDef(p
.first
)->getParent();
526 mode
= 0; // Same block
527 } else if (MDT
.dominates(MRI
.getVRegDef(p
.first
)->getParent(),
528 MRI
.getVRegDef(p
.second
)->getParent())) {
529 scan
= MRI
.getVRegDef(p
.second
)->getParent();
530 mode
= 1; // First dominates second
532 scan
= MRI
.getVRegDef(p
.first
)->getParent();
533 mode
= 2; // Second dominates first
536 // If there's an interference, we need to insert copies
537 if (interferes(p
.first
, p
.second
, scan
, LI
, mode
)) {
538 // Insert copies for First
539 for (int i
= P
->getNumOperands() - 1; i
>= 2; i
-=2) {
540 if (P
->getOperand(i
-1).getReg() == p
.first
) {
541 unsigned SrcReg
= p
.first
;
542 MachineBasicBlock
* From
= P
->getOperand(i
).getMBB();
544 Waiting
[From
].insert(std::make_pair(SrcReg
,
545 P
->getOperand(0).getReg()));
546 UsedByAnother
.insert(SrcReg
);
548 PHIUnion
.erase(SrcReg
);
554 // Add the renaming set for this PHI node to our overall renaming information
555 for (std::map
<unsigned, MachineBasicBlock
*>::iterator QI
= PHIUnion
.begin(),
556 QE
= PHIUnion
.end(); QI
!= QE
; ++QI
) {
557 DOUT
<< "Adding Renaming: " << QI
->first
<< " -> "
558 << P
->getOperand(0).getReg() << "\n";
561 RenameSets
.insert(std::make_pair(P
->getOperand(0).getReg(), PHIUnion
));
563 // Remember which registers are already renamed, so that we don't try to
564 // rename them for another PHI node in this block
565 for (std::map
<unsigned, MachineBasicBlock
*>::iterator I
= PHIUnion
.begin(),
566 E
= PHIUnion
.end(); I
!= E
; ++I
)
567 ProcessedNames
.insert(I
->first
);
573 /// processPHIUnion - Take a set of candidate registers to be coalesced when
574 /// decomposing the PHI instruction. Use the DominanceForest to remove the ones
575 /// that are known to interfere, and flag others that need to be checked for
576 /// local interferences.
577 void StrongPHIElimination::processPHIUnion(MachineInstr
* Inst
,
578 std::map
<unsigned, MachineBasicBlock
*>& PHIUnion
,
579 std::vector
<StrongPHIElimination::DomForestNode
*>& DF
,
580 std::vector
<std::pair
<unsigned, unsigned> >& locals
) {
582 std::vector
<DomForestNode
*> worklist(DF
.begin(), DF
.end());
583 SmallPtrSet
<DomForestNode
*, 4> visited
;
585 // Code is still in SSA form, so we can use MRI::getVRegDef()
586 MachineRegisterInfo
& MRI
= Inst
->getParent()->getParent()->getRegInfo();
588 LiveIntervals
& LI
= getAnalysis
<LiveIntervals
>();
589 unsigned DestReg
= Inst
->getOperand(0).getReg();
591 // DF walk on the DomForest
592 while (!worklist
.empty()) {
593 DomForestNode
* DFNode
= worklist
.back();
595 visited
.insert(DFNode
);
597 bool inserted
= false;
598 for (DomForestNode::iterator CI
= DFNode
->begin(), CE
= DFNode
->end();
600 DomForestNode
* child
= *CI
;
602 // If the current node is live-out of the defining block of one of its
603 // children, insert a copy for it. NOTE: The paper actually calls for
604 // a more elaborate heuristic for determining whether to insert copies
605 // for the child or the parent. In the interest of simplicity, we're
606 // just always choosing the parent.
607 if (isLiveOut(DFNode
->getReg(),
608 MRI
.getVRegDef(child
->getReg())->getParent(), LI
)) {
609 // Insert copies for parent
610 for (int i
= Inst
->getNumOperands() - 1; i
>= 2; i
-=2) {
611 if (Inst
->getOperand(i
-1).getReg() == DFNode
->getReg()) {
612 unsigned SrcReg
= DFNode
->getReg();
613 MachineBasicBlock
* From
= Inst
->getOperand(i
).getMBB();
615 Waiting
[From
].insert(std::make_pair(SrcReg
, DestReg
));
616 UsedByAnother
.insert(SrcReg
);
618 PHIUnion
.erase(SrcReg
);
622 // If a node is live-in to the defining block of one of its children, but
623 // not live-out, then we need to scan that block for local interferences.
624 } else if (isLiveIn(DFNode
->getReg(),
625 MRI
.getVRegDef(child
->getReg())->getParent(), LI
) ||
626 MRI
.getVRegDef(DFNode
->getReg())->getParent() ==
627 MRI
.getVRegDef(child
->getReg())->getParent()) {
628 // Add (p, c) to possible local interferences
629 locals
.push_back(std::make_pair(DFNode
->getReg(), child
->getReg()));
632 if (!visited
.count(child
)) {
633 worklist
.push_back(child
);
638 if (!inserted
) worklist
.pop_back();
642 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
643 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
646 /// Based on "Practical Improvements to the Construction and Destruction
647 /// of Static Single Assignment Form" by Briggs, et al.
648 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock
* MBB
,
649 std::set
<unsigned>& pushed
) {
650 // FIXME: This function needs to update LiveIntervals
651 std::multimap
<unsigned, unsigned>& copy_set
= Waiting
[MBB
];
653 std::multimap
<unsigned, unsigned> worklist
;
654 std::map
<unsigned, unsigned> map
;
656 // Setup worklist of initial copies
657 for (std::multimap
<unsigned, unsigned>::iterator I
= copy_set
.begin(),
658 E
= copy_set
.end(); I
!= E
; ) {
659 map
.insert(std::make_pair(I
->first
, I
->first
));
660 map
.insert(std::make_pair(I
->second
, I
->second
));
662 if (!UsedByAnother
.count(I
->second
)) {
665 // Avoid iterator invalidation
666 std::multimap
<unsigned, unsigned>::iterator OI
= I
;
674 LiveIntervals
& LI
= getAnalysis
<LiveIntervals
>();
675 MachineFunction
* MF
= MBB
->getParent();
676 MachineRegisterInfo
& MRI
= MF
->getRegInfo();
677 const TargetInstrInfo
*TII
= MF
->getTarget().getInstrInfo();
679 SmallVector
<std::pair
<unsigned, MachineInstr
*>, 4> InsertedPHIDests
;
681 // Iterate over the worklist, inserting copies
682 while (!worklist
.empty() || !copy_set
.empty()) {
683 while (!worklist
.empty()) {
684 std::multimap
<unsigned, unsigned>::iterator WI
= worklist
.begin();
685 std::pair
<unsigned, unsigned> curr
= *WI
;
688 const TargetRegisterClass
*RC
= MF
->getRegInfo().getRegClass(curr
.first
);
690 if (isLiveOut(curr
.second
, MBB
, LI
)) {
691 // Create a temporary
692 unsigned t
= MF
->getRegInfo().createVirtualRegister(RC
);
694 // Insert copy from curr.second to a temporary at
695 // the Phi defining curr.second
696 MachineBasicBlock::iterator PI
= MRI
.getVRegDef(curr
.second
);
697 TII
->copyRegToReg(*PI
->getParent(), PI
, t
,
698 curr
.second
, RC
, RC
);
700 DOUT
<< "Inserted copy from " << curr
.second
<< " to " << t
<< "\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 DOUT
<< "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
;
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
);
748 LiveInterval
& I
= LI
.getInterval(curr
.second
);
749 MachineBasicBlock::iterator term
= MBB
->getFirstTerminator();
751 if (term
!= MBB
->end())
752 endIdx
= LI
.getInstructionIndex(term
);
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 unsigned instrIdx
= LI
.getInstructionIndex(I
->second
);
787 if (Int
.liveAt(LiveIntervals::getDefIndex(instrIdx
)))
788 Int
.removeRange(LiveIntervals::getDefIndex(instrIdx
),
789 LI
.getMBBEndIdx(I
->second
->getParent())+1,
792 LiveRange R
= LI
.addLiveRangeToEndOfBlock(I
->first
, I
->second
);
793 R
.valno
->copy
= I
->second
;
795 LiveIntervals::getDefIndex(LI
.getInstructionIndex(I
->second
));
800 /// InsertCopies - insert copies into MBB and all of its successors
801 void StrongPHIElimination::InsertCopies(MachineDomTreeNode
* MDTN
,
802 SmallPtrSet
<MachineBasicBlock
*, 16>& visited
) {
803 MachineBasicBlock
* MBB
= MDTN
->getBlock();
806 std::set
<unsigned> pushed
;
808 LiveIntervals
& LI
= getAnalysis
<LiveIntervals
>();
809 // Rewrite register uses from Stacks
810 for (MachineBasicBlock::iterator I
= MBB
->begin(), E
= MBB
->end();
812 if (I
->getOpcode() == TargetInstrInfo::PHI
)
815 for (unsigned i
= 0; i
< I
->getNumOperands(); ++i
)
816 if (I
->getOperand(i
).isReg() &&
817 Stacks
[I
->getOperand(i
).getReg()].size()) {
818 // Remove the live range for the old vreg.
819 LiveInterval
& OldInt
= LI
.getInterval(I
->getOperand(i
).getReg());
820 LiveInterval::iterator OldLR
= OldInt
.FindLiveRangeContaining(
821 LiveIntervals::getUseIndex(LI
.getInstructionIndex(I
)));
822 if (OldLR
!= OldInt
.end())
823 OldInt
.removeRange(*OldLR
, true);
825 // Change the register
826 I
->getOperand(i
).setReg(Stacks
[I
->getOperand(i
).getReg()].back());
828 // Add a live range for the new vreg
829 LiveInterval
& Int
= LI
.getInterval(I
->getOperand(i
).getReg());
830 VNInfo
* FirstVN
= *Int
.vni_begin();
831 FirstVN
->setHasPHIKill(false);
832 if (I
->getOperand(i
).isKill())
834 LiveIntervals::getUseIndex(LI
.getInstructionIndex(I
)), false);
836 LiveRange
LR (LI
.getMBBStartIdx(I
->getParent()),
837 LiveIntervals::getUseIndex(LI
.getInstructionIndex(I
))+1,
844 // Schedule the copies for this block
845 ScheduleCopies(MBB
, pushed
);
847 // Recur down the dominator tree.
848 for (MachineDomTreeNode::iterator I
= MDTN
->begin(),
849 E
= MDTN
->end(); I
!= E
; ++I
)
850 if (!visited
.count((*I
)->getBlock()))
851 InsertCopies(*I
, visited
);
853 // As we exit this block, pop the names we pushed while processing it
854 for (std::set
<unsigned>::iterator I
= pushed
.begin(),
855 E
= pushed
.end(); I
!= E
; ++I
)
856 Stacks
[*I
].pop_back();
859 bool StrongPHIElimination::mergeLiveIntervals(unsigned primary
,
860 unsigned secondary
) {
862 LiveIntervals
& LI
= getAnalysis
<LiveIntervals
>();
863 LiveInterval
& LHS
= LI
.getOrCreateInterval(primary
);
864 LiveInterval
& RHS
= LI
.getOrCreateInterval(secondary
);
866 LI
.computeNumbering();
868 DenseMap
<VNInfo
*, VNInfo
*> VNMap
;
869 for (LiveInterval::iterator I
= RHS
.begin(), E
= RHS
.end(); I
!= E
; ++I
) {
872 unsigned Start
= R
.start
;
873 unsigned End
= R
.end
;
874 if (LHS
.getLiveRangeContaining(Start
))
877 if (LHS
.getLiveRangeContaining(End
))
880 LiveInterval::iterator RI
= std::upper_bound(LHS
.begin(), LHS
.end(), R
);
881 if (RI
!= LHS
.end() && RI
->start
< End
)
885 for (LiveInterval::iterator I
= RHS
.begin(), E
= RHS
.end(); I
!= E
; ++I
) {
887 VNInfo
* OldVN
= R
.valno
;
888 VNInfo
*& NewVN
= VNMap
[OldVN
];
890 NewVN
= LHS
.createValueCopy(OldVN
, LI
.getVNInfoAllocator());
893 LiveRange
LR (R
.start
, R
.end
, NewVN
);
897 LI
.removeInterval(RHS
.reg
);
902 bool StrongPHIElimination::runOnMachineFunction(MachineFunction
&Fn
) {
903 LiveIntervals
& LI
= getAnalysis
<LiveIntervals
>();
905 // Compute DFS numbers of each block
908 // Determine which phi node operands need copies
909 for (MachineFunction::iterator I
= Fn
.begin(), E
= Fn
.end(); I
!= E
; ++I
)
911 I
->begin()->getOpcode() == TargetInstrInfo::PHI
)
914 // Break interferences where two different phis want to coalesce
915 // in the same register.
916 std::set
<unsigned> seen
;
917 typedef std::map
<unsigned, std::map
<unsigned, MachineBasicBlock
*> >
919 for (RenameSetType::iterator I
= RenameSets
.begin(), E
= RenameSets
.end();
921 for (std::map
<unsigned, MachineBasicBlock
*>::iterator
922 OI
= I
->second
.begin(), OE
= I
->second
.end(); OI
!= OE
; ) {
923 if (!seen
.count(OI
->first
)) {
924 seen
.insert(OI
->first
);
927 Waiting
[OI
->second
].insert(std::make_pair(OI
->first
, I
->first
));
928 unsigned reg
= OI
->first
;
930 I
->second
.erase(reg
);
931 DOUT
<< "Removing Renaming: " << reg
<< " -> " << I
->first
<< "\n";
937 // FIXME: This process should probably preserve LiveIntervals
938 SmallPtrSet
<MachineBasicBlock
*, 16> visited
;
939 MachineDominatorTree
& MDT
= getAnalysis
<MachineDominatorTree
>();
940 InsertCopies(MDT
.getRootNode(), visited
);
943 for (RenameSetType::iterator I
= RenameSets
.begin(), E
= RenameSets
.end();
945 while (I
->second
.size()) {
946 std::map
<unsigned, MachineBasicBlock
*>::iterator SI
= I
->second
.begin();
948 DOUT
<< "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
);
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
);
970 LI
.getInstructionIndex(--SI
->second
->getFirstTerminator());
971 if (Int
.liveAt(LiveIntervals::getDefIndex(instrIdx
)))
972 Int
.removeRange(LiveIntervals::getDefIndex(instrIdx
),
973 LI
.getMBBEndIdx(SI
->second
)+1, true);
975 LiveRange R
= LI
.addLiveRangeToEndOfBlock(I
->first
,
976 --SI
->second
->getFirstTerminator());
977 R
.valno
->copy
= --SI
->second
->getFirstTerminator();
978 R
.valno
->def
= LiveIntervals::getDefIndex(instrIdx
);
980 DOUT
<< "Renaming failed: " << SI
->first
<< " -> "
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
);
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();
998 if (BI
->getOpcode() == TargetInstrInfo::PHI
)
1002 for (std::vector
<MachineInstr
*>::iterator I
= phis
.begin(), E
= phis
.end();
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
);
1013 unsigned idx
= LI
.getDefIndex(LI
.getInstructionIndex(PInstr
));
1014 PI
.removeRange(*PI
.getLiveRangeContaining(idx
), true);
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
.getInstructionIndex(PInstr
) +
1028 LiveInterval::InstrSlots::NUM
))
1029 InputI
.removeRange(LI
.getMBBStartIdx(PInstr
->getParent()),
1030 LI
.getInstructionIndex(PInstr
),
1034 // If the PHI is not dead, then the valno defined by the PHI
1035 // now has an unknown def.
1036 unsigned idx
= LI
.getDefIndex(LI
.getInstructionIndex(PInstr
));
1037 const LiveRange
* PLR
= PI
.getLiveRangeContaining(idx
);
1038 PLR
->valno
->setIsPHIDef(true);
1039 LiveRange
R (LI
.getMBBStartIdx(PInstr
->getParent()),
1040 PLR
->start
, PLR
->valno
);
1044 LI
.RemoveMachineInstrFromMaps(PInstr
);
1045 PInstr
->eraseFromParent();
1048 LI
.computeNumbering();