1 //===- StrongPhiElimination.cpp - Eliminate PHI nodes by inserting copies -===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Owen Anderson and is distributed under
6 // the University of Illinois Open Source 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/BreakCriticalMachineEdge.h"
25 #include "llvm/CodeGen/LiveVariables.h"
26 #include "llvm/CodeGen/MachineDominators.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/SSARegMap.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Compiler.h"
38 struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
39 static char ID; // Pass identification, replacement for typeid
40 StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
42 DenseMap<MachineBasicBlock*,
43 SmallVector<std::pair<unsigned, unsigned>, 2> > Waiting;
45 bool runOnMachineFunction(MachineFunction &Fn);
47 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48 AU.addPreserved<LiveVariables>();
49 AU.addPreservedID(PHIEliminationID);
50 AU.addRequired<MachineDominatorTree>();
51 AU.addRequired<LiveVariables>();
53 MachineFunctionPass::getAnalysisUsage(AU);
56 virtual void releaseMemory() {
64 struct DomForestNode {
66 std::vector<DomForestNode*> children;
69 void addChild(DomForestNode* DFN) { children.push_back(DFN); }
72 typedef std::vector<DomForestNode*>::iterator iterator;
74 DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
76 parent->addChild(this);
80 for (iterator I = begin(), E = end(); I != E; ++I)
84 inline unsigned getReg() { return reg; }
86 inline DomForestNode::iterator begin() { return children.begin(); }
87 inline DomForestNode::iterator end() { return children.end(); }
90 DenseMap<MachineBasicBlock*, unsigned> preorder;
91 DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
93 DenseMap<MachineBasicBlock*, std::vector<MachineInstr*> > waiting;
96 void computeDFS(MachineFunction& MF);
97 void processBlock(MachineBasicBlock* MBB);
99 std::vector<DomForestNode*> computeDomForest(std::set<unsigned>& instrs);
100 void processPHIUnion(MachineInstr* Inst,
101 std::set<unsigned>& PHIUnion,
102 std::vector<StrongPHIElimination::DomForestNode*>& DF,
103 std::vector<std::pair<unsigned, unsigned> >& locals);
104 void breakCriticalEdges(MachineFunction &Fn);
108 char StrongPHIElimination::ID = 0;
109 RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
110 "Eliminate PHI nodes for register allocation, intelligently");
113 const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
115 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
116 /// of the given MachineFunction. These numbers are then used in other parts
117 /// of the PHI elimination process.
118 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
119 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
120 SmallPtrSet<MachineDomTreeNode*, 8> visited;
124 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
126 MachineDomTreeNode* node = DT.getRootNode();
128 std::vector<MachineDomTreeNode*> worklist;
129 worklist.push_back(node);
131 while (!worklist.empty()) {
132 MachineDomTreeNode* currNode = worklist.back();
134 if (!frontier.count(currNode)) {
135 frontier.insert(currNode);
137 preorder.insert(std::make_pair(currNode->getBlock(), time));
140 bool inserted = false;
141 for (MachineDomTreeNode::iterator I = node->begin(), E = node->end();
143 if (!frontier.count(*I) && !visited.count(*I)) {
144 worklist.push_back(*I);
150 frontier.erase(currNode);
151 visited.insert(currNode);
152 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
159 /// PreorderSorter - a helper class that is used to sort registers
160 /// according to the preorder number of their defining blocks
161 class PreorderSorter {
163 DenseMap<MachineBasicBlock*, unsigned>& preorder;
167 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
168 LiveVariables& L) : preorder(p), LV(L) { }
170 bool operator()(unsigned A, unsigned B) {
174 MachineBasicBlock* ABlock = LV.getVarInfo(A).DefInst->getParent();
175 MachineBasicBlock* BBlock = LV.getVarInfo(A).DefInst->getParent();
177 if (preorder[ABlock] < preorder[BBlock])
179 else if (preorder[ABlock] > preorder[BBlock])
182 assert(0 && "Error sorting by dominance!");
187 /// computeDomForest - compute the subforest of the DomTree corresponding
188 /// to the defining blocks of the registers in question
189 std::vector<StrongPHIElimination::DomForestNode*>
190 StrongPHIElimination::computeDomForest(std::set<unsigned>& regs) {
191 LiveVariables& LV = getAnalysis<LiveVariables>();
193 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
194 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
196 std::vector<unsigned> worklist;
197 worklist.reserve(regs.size());
198 for (std::set<unsigned>::iterator I = regs.begin(), E = regs.end();
200 worklist.push_back(*I);
202 PreorderSorter PS(preorder, LV);
203 std::sort(worklist.begin(), worklist.end(), PS);
205 DomForestNode* CurrentParent = VirtualRoot;
206 std::vector<DomForestNode*> stack;
207 stack.push_back(VirtualRoot);
209 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
211 unsigned pre = preorder[LV.getVarInfo(*I).DefInst->getParent()];
212 MachineBasicBlock* parentBlock =
213 LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent();
215 while (pre > maxpreorder[parentBlock]) {
217 CurrentParent = stack.back();
219 parentBlock = LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent();
222 DomForestNode* child = new DomForestNode(*I, CurrentParent);
223 stack.push_back(child);
224 CurrentParent = child;
227 std::vector<DomForestNode*> ret;
228 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
232 /// isLiveIn - helper method that determines, from a VarInfo, if a register
233 /// is live into a block
234 bool isLiveIn(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
235 if (V.AliveBlocks.test(MBB->getNumber()))
238 if (V.DefInst->getParent() != MBB &&
239 V.UsedBlocks.test(MBB->getNumber()))
245 /// isLiveOut - help method that determines, from a VarInfo, if a register is
246 /// live out of a block.
247 bool isLiveOut(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
248 if (MBB == V.DefInst->getParent() ||
249 V.UsedBlocks.test(MBB->getNumber())) {
250 for (std::vector<MachineInstr*>::iterator I = V.Kills.begin(),
251 E = V.Kills.end(); I != E; ++I)
252 if ((*I)->getParent() == MBB)
261 /// isKillInst - helper method that determines, from a VarInfo, if an
262 /// instruction kills a given register
263 bool isKillInst(LiveVariables::VarInfo& V, MachineInstr* MI) {
264 return std::find(V.Kills.begin(), V.Kills.end(), MI) != V.Kills.end();
267 /// interferes - checks for local interferences by scanning a block. The only
268 /// trick parameter is 'mode' which tells it the relationship of the two
269 /// registers. 0 - defined in the same block, 1 - first properly dominates
270 /// second, 2 - second properly dominates first
271 bool interferes(LiveVariables::VarInfo& First, LiveVariables::VarInfo& Second,
272 MachineBasicBlock* scan, unsigned mode) {
273 MachineInstr* def = 0;
274 MachineInstr* kill = 0;
276 bool interference = false;
278 // Wallk the block, checking for interferences
279 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
281 MachineInstr* curr = MBI;
283 // Same defining block...
285 if (curr == First.DefInst) {
286 // If we find our first DefInst, save it
289 // If there's already an unkilled DefInst, then
290 // this is an interference
294 // If there's a DefInst followed by a KillInst, then
295 // they can't interfere
297 interference = false;
300 // Symmetric with the above
301 } else if (curr == Second.DefInst ) {
308 interference = false;
311 // Store KillInsts if they match up with the DefInst
312 } else if (isKillInst(First, curr)) {
313 if (def == First.DefInst) {
315 } else if (isKillInst(Second, curr)) {
316 if (def == Second.DefInst) {
321 // First properly dominates second...
322 } else if (mode == 1) {
323 if (curr == Second.DefInst) {
324 // DefInst of second without kill of first is an interference
328 // DefInst after a kill is a non-interference
330 interference = false;
333 // Save KillInsts of First
334 } else if (isKillInst(First, curr)) {
337 // Symmetric with the above
338 } else if (mode == 2) {
339 if (curr == First.DefInst) {
344 interference = false;
347 } else if (isKillInst(Second, curr)) {
356 /// processBlock - Eliminate PHIs in the given block
357 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
358 LiveVariables& LV = getAnalysis<LiveVariables>();
360 // Holds names that have been added to a set in any PHI within this block
361 // before the current one.
362 std::set<unsigned> ProcessedNames;
364 MachineBasicBlock::iterator P = MBB->begin();
365 while (P->getOpcode() == TargetInstrInfo::PHI) {
366 LiveVariables::VarInfo& PHIInfo = LV.getVarInfo(P->getOperand(0).getReg());
368 unsigned DestReg = P->getOperand(0).getReg();
370 // Hold the names that are currently in the candidate set.
371 std::set<unsigned> PHIUnion;
372 std::set<MachineBasicBlock*> UnionedBlocks;
374 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
375 unsigned SrcReg = P->getOperand(i-1).getReg();
376 LiveVariables::VarInfo& SrcInfo = LV.getVarInfo(SrcReg);
378 // Check for trivial interferences
379 if (isLiveIn(SrcInfo, P->getParent()) ||
380 isLiveOut(PHIInfo, SrcInfo.DefInst->getParent()) ||
381 ( PHIInfo.DefInst->getOpcode() == TargetInstrInfo::PHI &&
382 isLiveIn(PHIInfo, SrcInfo.DefInst->getParent()) ) ||
383 ProcessedNames.count(SrcReg) ||
384 UnionedBlocks.count(SrcInfo.DefInst->getParent())) {
386 // add a copy from a_i to p in Waiting[From[a_i]]
387 MachineBasicBlock* From = P->getOperand(i).getMachineBasicBlock();
388 Waiting[From].push_back(std::make_pair(SrcReg, DestReg));
390 PHIUnion.insert(SrcReg);
391 UnionedBlocks.insert(SrcInfo.DefInst->getParent());
395 std::vector<StrongPHIElimination::DomForestNode*> DF =
396 computeDomForest(PHIUnion);
398 // Walk DomForest to resolve interferences
399 std::vector<std::pair<unsigned, unsigned> > localInterferences;
400 processPHIUnion(P, PHIUnion, DF, localInterferences);
402 // FIXME: Check for local interferences
403 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
404 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
405 std::pair<unsigned, unsigned> p = *I;
407 LiveVariables::VarInfo& FirstInfo = LV.getVarInfo(p.first);
408 LiveVariables::VarInfo& SecondInfo = LV.getVarInfo(p.second);
410 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
412 // Determine the block we need to scan and the relationship between
414 MachineBasicBlock* scan = 0;
416 if (FirstInfo.DefInst->getParent() == SecondInfo.DefInst->getParent()) {
417 scan = FirstInfo.DefInst->getParent();
418 mode = 0; // Same block
419 } else if (MDT.dominates(FirstInfo.DefInst->getParent(),
420 SecondInfo.DefInst->getParent())) {
421 scan = SecondInfo.DefInst->getParent();
422 mode = 1; // First dominates second
424 scan = FirstInfo.DefInst->getParent();
425 mode = 2; // Second dominates first
428 // If there's an interference, we need to insert copies
429 if (interferes(FirstInfo, SecondInfo, scan, mode)) {
430 // Insert copies for First
431 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
432 if (P->getOperand(i-1).getReg() == p.first) {
433 unsigned SrcReg = p.first;
434 MachineBasicBlock* From = P->getOperand(i).getMBB();
436 Waiting[From].push_back(std::make_pair(SrcReg,
437 P->getOperand(0).getReg()));
438 PHIUnion.erase(SrcReg);
444 ProcessedNames.insert(PHIUnion.begin(), PHIUnion.end());
449 /// processPHIUnion - Take a set of candidate registers to be coallesced when
450 /// decomposing the PHI instruction. Use the DominanceForest to remove the ones
451 /// that are known to interfere, and flag others that need to be checked for
452 /// local interferences.
453 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
454 std::set<unsigned>& PHIUnion,
455 std::vector<StrongPHIElimination::DomForestNode*>& DF,
456 std::vector<std::pair<unsigned, unsigned> >& locals) {
458 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
459 SmallPtrSet<DomForestNode*, 4> visited;
461 LiveVariables& LV = getAnalysis<LiveVariables>();
462 unsigned DestReg = Inst->getOperand(0).getReg();
464 // DF walk on the DomForest
465 while (!worklist.empty()) {
466 DomForestNode* DFNode = worklist.back();
468 LiveVariables::VarInfo& Info = LV.getVarInfo(DFNode->getReg());
469 visited.insert(DFNode);
471 bool inserted = false;
472 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
474 DomForestNode* child = *CI;
475 LiveVariables::VarInfo& CInfo = LV.getVarInfo(child->getReg());
477 if (isLiveOut(Info, CInfo.DefInst->getParent())) {
478 // Insert copies for parent
479 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
480 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
481 unsigned SrcReg = DFNode->getReg();
482 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
484 Waiting[From].push_back(std::make_pair(SrcReg, DestReg));
485 PHIUnion.erase(SrcReg);
488 } else if (isLiveIn(Info, CInfo.DefInst->getParent()) ||
489 Info.DefInst->getParent() == CInfo.DefInst->getParent()) {
490 // Add (p, c) to possible local interferences
491 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
494 if (!visited.count(child)) {
495 worklist.push_back(child);
500 if (!inserted) worklist.pop_back();
504 /// breakCriticalEdges - Break critical edges coming into blocks with PHI
505 /// nodes, preserving dominator and livevariable info.
506 void StrongPHIElimination::breakCriticalEdges(MachineFunction &Fn) {
507 typedef std::pair<MachineBasicBlock*, MachineBasicBlock*> MBB_pair;
509 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
510 LiveVariables& LV = getAnalysis<LiveVariables>();
512 // Find critical edges
513 std::vector<MBB_pair> criticals;
514 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
516 I->begin()->getOpcode() == TargetInstrInfo::PHI &&
518 for (MachineBasicBlock::pred_iterator PI = I->pred_begin(),
519 PE = I->pred_end(); PI != PE; ++PI)
520 if ((*PI)->succ_size() > 1)
521 criticals.push_back(std::make_pair(*PI, I));
523 for (std::vector<MBB_pair>::iterator I = criticals.begin(),
524 E = criticals.end(); I != E; ++I) {
526 MachineBasicBlock* new_bb = SplitCriticalMachineEdge(I->first, I->second);
529 MDT.splitBlock(I->first);
531 // Update livevariables
532 for (unsigned var = 1024; var < Fn.getSSARegMap()->getLastVirtReg(); ++var)
533 if (isLiveOut(LV.getVarInfo(var), I->first))
534 LV.getVarInfo(var).AliveBlocks.set(new_bb->getNumber());
538 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
539 breakCriticalEdges(Fn);
542 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
544 I->begin()->getOpcode() == TargetInstrInfo::PHI)