blob: ee7228db7efe93a953139c1c0b957047e9c6eb07 [file] [log] [blame]
Owen Anderson0bda0e82007-10-31 03:37:57 +00001//===- StrongPhiElimination.cpp - Eliminate PHI nodes by inserting copies -===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Owen Anderson0bda0e82007-10-31 03:37:57 +00007//
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
19//
20//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "strongphielim"
23#include "llvm/CodeGen/Passes.h"
Owen Andersoneb37ecc2008-03-10 07:22:36 +000024#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Owen Anderson0bda0e82007-10-31 03:37:57 +000025#include "llvm/CodeGen/MachineDominators.h"
26#include "llvm/CodeGen/MachineFunctionPass.h"
27#include "llvm/CodeGen/MachineInstr.h"
Owen Anderson0d893b42008-01-08 05:16:15 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
Owen Anderson0bda0e82007-10-31 03:37:57 +000029#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetMachine.h"
Owen Andersonefbcebc2007-12-23 15:37:26 +000031#include "llvm/ADT/DepthFirstIterator.h"
Owen Anderson0bda0e82007-10-31 03:37:57 +000032#include "llvm/ADT/Statistic.h"
33#include "llvm/Support/Compiler.h"
34using namespace llvm;
35
36
37namespace {
38 struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
39 static char ID; // Pass identification, replacement for typeid
40 StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
41
Owen Andersonec1213f2008-01-09 22:40:54 +000042 // Waiting stores, for each MBB, the set of copies that need to
43 // be inserted into that MBB
Owen Andersonafc6de02007-12-10 08:07:09 +000044 DenseMap<MachineBasicBlock*,
Owen Andersonefbcebc2007-12-23 15:37:26 +000045 std::map<unsigned, unsigned> > Waiting;
46
Owen Andersonec1213f2008-01-09 22:40:54 +000047 // Stacks holds the renaming stack for each register
Owen Andersonefbcebc2007-12-23 15:37:26 +000048 std::map<unsigned, std::vector<unsigned> > Stacks;
Owen Andersonec1213f2008-01-09 22:40:54 +000049
50 // Registers in UsedByAnother are PHI nodes that are themselves
51 // used as operands to another another PHI node
Owen Andersonefbcebc2007-12-23 15:37:26 +000052 std::set<unsigned> UsedByAnother;
Owen Andersonec1213f2008-01-09 22:40:54 +000053
54 // RenameSets are the sets of operands to a PHI (the defining instruction
55 // of the key) that can be renamed without copies
Owen Anderson0c5714b2008-01-08 21:54:52 +000056 std::map<unsigned, std::set<unsigned> > RenameSets;
Owen Andersonafc6de02007-12-10 08:07:09 +000057
Owen Andersonec1213f2008-01-09 22:40:54 +000058 // Store the DFS-in number of each block
59 DenseMap<MachineBasicBlock*, unsigned> preorder;
60
61 // Store the DFS-out number of each block
62 DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
63
Owen Andersona4ad2e72007-11-06 04:49:43 +000064 bool runOnMachineFunction(MachineFunction &Fn);
65
Owen Anderson0bda0e82007-10-31 03:37:57 +000066 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67 AU.addRequired<MachineDominatorTree>();
Owen Andersoneb37ecc2008-03-10 07:22:36 +000068 AU.addRequired<LiveIntervals>();
69
70 // TODO: Actually make this true.
71 AU.addPreserved<LiveIntervals>();
Owen Anderson0bda0e82007-10-31 03:37:57 +000072 MachineFunctionPass::getAnalysisUsage(AU);
73 }
74
75 virtual void releaseMemory() {
76 preorder.clear();
77 maxpreorder.clear();
Owen Andersona4ad2e72007-11-06 04:49:43 +000078
Owen Andersonefbcebc2007-12-23 15:37:26 +000079 Waiting.clear();
Owen Andersonec1213f2008-01-09 22:40:54 +000080 Stacks.clear();
81 UsedByAnother.clear();
82 RenameSets.clear();
Owen Anderson0bda0e82007-10-31 03:37:57 +000083 }
84
85 private:
Owen Andersonec1213f2008-01-09 22:40:54 +000086
87 /// DomForestNode - Represents a node in the "dominator forest". This is
88 /// a forest in which the nodes represent registers and the edges
89 /// represent a dominance relation in the block defining those registers.
Owen Anderson83430bc2007-11-04 22:33:26 +000090 struct DomForestNode {
91 private:
Owen Andersonec1213f2008-01-09 22:40:54 +000092 // Store references to our children
Owen Anderson83430bc2007-11-04 22:33:26 +000093 std::vector<DomForestNode*> children;
Owen Andersonec1213f2008-01-09 22:40:54 +000094 // The register we represent
Owen Andersonee49b532007-11-06 05:22:43 +000095 unsigned reg;
Owen Anderson83430bc2007-11-04 22:33:26 +000096
Owen Andersonec1213f2008-01-09 22:40:54 +000097 // Add another node as our child
Owen Anderson83430bc2007-11-04 22:33:26 +000098 void addChild(DomForestNode* DFN) { children.push_back(DFN); }
99
100 public:
101 typedef std::vector<DomForestNode*>::iterator iterator;
102
Owen Andersonec1213f2008-01-09 22:40:54 +0000103 // Create a DomForestNode by providing the register it represents, and
104 // the node to be its parent. The virtual root node has register 0
105 // and a null parent.
Owen Andersonee49b532007-11-06 05:22:43 +0000106 DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
Owen Anderson83430bc2007-11-04 22:33:26 +0000107 if (parent)
108 parent->addChild(this);
109 }
110
Owen Andersona4ad2e72007-11-06 04:49:43 +0000111 ~DomForestNode() {
112 for (iterator I = begin(), E = end(); I != E; ++I)
113 delete *I;
114 }
Owen Anderson83430bc2007-11-04 22:33:26 +0000115
Owen Andersonec1213f2008-01-09 22:40:54 +0000116 /// getReg - Return the regiser that this node represents
Owen Andersonee49b532007-11-06 05:22:43 +0000117 inline unsigned getReg() { return reg; }
Owen Andersona4ad2e72007-11-06 04:49:43 +0000118
Owen Andersonec1213f2008-01-09 22:40:54 +0000119 // Provide iterator access to our children
Owen Andersona4ad2e72007-11-06 04:49:43 +0000120 inline DomForestNode::iterator begin() { return children.begin(); }
121 inline DomForestNode::iterator end() { return children.end(); }
Owen Anderson83430bc2007-11-04 22:33:26 +0000122 };
123
Owen Anderson0bda0e82007-10-31 03:37:57 +0000124 void computeDFS(MachineFunction& MF);
Owen Anderson60a877d2007-11-07 05:17:15 +0000125 void processBlock(MachineBasicBlock* MBB);
Owen Anderson83430bc2007-11-04 22:33:26 +0000126
Owen Andersonddd060f2008-01-10 01:36:43 +0000127 std::vector<DomForestNode*> computeDomForest(std::set<unsigned>& instrs,
128 MachineRegisterInfo& MRI);
Owen Andersond525f662007-12-11 20:12:11 +0000129 void processPHIUnion(MachineInstr* Inst,
130 std::set<unsigned>& PHIUnion,
Owen Anderson62d67dd2007-12-13 05:53:03 +0000131 std::vector<StrongPHIElimination::DomForestNode*>& DF,
132 std::vector<std::pair<unsigned, unsigned> >& locals);
Owen Andersonf1519e82007-12-24 22:12:23 +0000133 void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
Owen Anderson719fef62008-01-09 10:32:30 +0000134 void InsertCopies(MachineBasicBlock* MBB, std::set<MachineBasicBlock*>& v);
Owen Anderson0bda0e82007-10-31 03:37:57 +0000135 };
136
137 char StrongPHIElimination::ID = 0;
138 RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
139 "Eliminate PHI nodes for register allocation, intelligently");
140}
141
142const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
143
144/// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
145/// of the given MachineFunction. These numbers are then used in other parts
146/// of the PHI elimination process.
147void StrongPHIElimination::computeDFS(MachineFunction& MF) {
148 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
149 SmallPtrSet<MachineDomTreeNode*, 8> visited;
150
151 unsigned time = 0;
152
153 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
154
155 MachineDomTreeNode* node = DT.getRootNode();
156
157 std::vector<MachineDomTreeNode*> worklist;
158 worklist.push_back(node);
159
160 while (!worklist.empty()) {
161 MachineDomTreeNode* currNode = worklist.back();
162
163 if (!frontier.count(currNode)) {
164 frontier.insert(currNode);
165 ++time;
166 preorder.insert(std::make_pair(currNode->getBlock(), time));
167 }
168
169 bool inserted = false;
170 for (MachineDomTreeNode::iterator I = node->begin(), E = node->end();
171 I != E; ++I)
172 if (!frontier.count(*I) && !visited.count(*I)) {
173 worklist.push_back(*I);
174 inserted = true;
175 break;
176 }
177
178 if (!inserted) {
179 frontier.erase(currNode);
180 visited.insert(currNode);
181 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
182
183 worklist.pop_back();
184 }
185 }
Duncan Sands1bd32712007-10-31 08:49:24 +0000186}
Owen Anderson83430bc2007-11-04 22:33:26 +0000187
Owen Anderson8b96b9f2007-11-06 05:26:02 +0000188/// PreorderSorter - a helper class that is used to sort registers
189/// according to the preorder number of their defining blocks
Owen Anderson83430bc2007-11-04 22:33:26 +0000190class PreorderSorter {
191private:
192 DenseMap<MachineBasicBlock*, unsigned>& preorder;
Owen Andersonddd060f2008-01-10 01:36:43 +0000193 MachineRegisterInfo& MRI;
Owen Anderson83430bc2007-11-04 22:33:26 +0000194
195public:
Owen Andersonee49b532007-11-06 05:22:43 +0000196 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
Owen Andersonddd060f2008-01-10 01:36:43 +0000197 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
Owen Anderson83430bc2007-11-04 22:33:26 +0000198
Owen Andersonee49b532007-11-06 05:22:43 +0000199 bool operator()(unsigned A, unsigned B) {
Owen Anderson83430bc2007-11-04 22:33:26 +0000200 if (A == B)
201 return false;
202
Owen Andersonddd060f2008-01-10 01:36:43 +0000203 MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
204 MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
Owen Andersonee49b532007-11-06 05:22:43 +0000205
206 if (preorder[ABlock] < preorder[BBlock])
Owen Anderson83430bc2007-11-04 22:33:26 +0000207 return true;
Owen Andersonee49b532007-11-06 05:22:43 +0000208 else if (preorder[ABlock] > preorder[BBlock])
Owen Anderson83430bc2007-11-04 22:33:26 +0000209 return false;
210
Owen Andersonee49b532007-11-06 05:22:43 +0000211 return false;
Owen Anderson83430bc2007-11-04 22:33:26 +0000212 }
213};
214
Owen Anderson8b96b9f2007-11-06 05:26:02 +0000215/// computeDomForest - compute the subforest of the DomTree corresponding
216/// to the defining blocks of the registers in question
Owen Anderson83430bc2007-11-04 22:33:26 +0000217std::vector<StrongPHIElimination::DomForestNode*>
Owen Andersonddd060f2008-01-10 01:36:43 +0000218StrongPHIElimination::computeDomForest(std::set<unsigned>& regs,
219 MachineRegisterInfo& MRI) {
Owen Andersonec1213f2008-01-09 22:40:54 +0000220 // Begin by creating a virtual root node, since the actual results
221 // may well be a forest. Assume this node has maximum DFS-out number.
Owen Anderson83430bc2007-11-04 22:33:26 +0000222 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
223 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
224
Owen Andersonec1213f2008-01-09 22:40:54 +0000225 // Populate a worklist with the registers
Owen Andersonee49b532007-11-06 05:22:43 +0000226 std::vector<unsigned> worklist;
227 worklist.reserve(regs.size());
228 for (std::set<unsigned>::iterator I = regs.begin(), E = regs.end();
229 I != E; ++I)
Owen Anderson83430bc2007-11-04 22:33:26 +0000230 worklist.push_back(*I);
Owen Andersonee49b532007-11-06 05:22:43 +0000231
Owen Andersonec1213f2008-01-09 22:40:54 +0000232 // Sort the registers by the DFS-in number of their defining block
Owen Andersonddd060f2008-01-10 01:36:43 +0000233 PreorderSorter PS(preorder, MRI);
Owen Anderson83430bc2007-11-04 22:33:26 +0000234 std::sort(worklist.begin(), worklist.end(), PS);
235
Owen Andersonec1213f2008-01-09 22:40:54 +0000236 // Create a "current parent" stack, and put the virtual root on top of it
Owen Anderson83430bc2007-11-04 22:33:26 +0000237 DomForestNode* CurrentParent = VirtualRoot;
238 std::vector<DomForestNode*> stack;
239 stack.push_back(VirtualRoot);
240
Owen Andersonec1213f2008-01-09 22:40:54 +0000241 // Iterate over all the registers in the previously computed order
Owen Andersonee49b532007-11-06 05:22:43 +0000242 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
243 I != E; ++I) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000244 unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
Owen Andersoncb7d9492008-01-09 06:19:05 +0000245 MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
Owen Andersonddd060f2008-01-10 01:36:43 +0000246 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
Owen Andersoncb7d9492008-01-09 06:19:05 +0000247 0;
Owen Andersonee49b532007-11-06 05:22:43 +0000248
Owen Andersonec1213f2008-01-09 22:40:54 +0000249 // If the DFS-in number of the register is greater than the DFS-out number
250 // of the current parent, repeatedly pop the parent stack until it isn't.
Owen Andersonee49b532007-11-06 05:22:43 +0000251 while (pre > maxpreorder[parentBlock]) {
Owen Anderson83430bc2007-11-04 22:33:26 +0000252 stack.pop_back();
253 CurrentParent = stack.back();
Owen Andersonee49b532007-11-06 05:22:43 +0000254
Owen Anderson864e3a32008-01-09 10:41:39 +0000255 parentBlock = CurrentParent->getReg() ?
Owen Andersonddd060f2008-01-10 01:36:43 +0000256 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
Owen Anderson864e3a32008-01-09 10:41:39 +0000257 0;
Owen Anderson83430bc2007-11-04 22:33:26 +0000258 }
259
Owen Andersonec1213f2008-01-09 22:40:54 +0000260 // Now that we've found the appropriate parent, create a DomForestNode for
261 // this register and attach it to the forest
Owen Anderson83430bc2007-11-04 22:33:26 +0000262 DomForestNode* child = new DomForestNode(*I, CurrentParent);
Owen Andersonec1213f2008-01-09 22:40:54 +0000263
264 // Push this new node on the "current parent" stack
Owen Anderson83430bc2007-11-04 22:33:26 +0000265 stack.push_back(child);
266 CurrentParent = child;
267 }
268
Owen Andersonec1213f2008-01-09 22:40:54 +0000269 // Return a vector containing the children of the virtual root node
Owen Anderson83430bc2007-11-04 22:33:26 +0000270 std::vector<DomForestNode*> ret;
271 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
272 return ret;
273}
Owen Andersona4ad2e72007-11-06 04:49:43 +0000274
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000275/// isLiveIn - helper method that determines, from a regno, if a register
Owen Anderson60a877d2007-11-07 05:17:15 +0000276/// is live into a block
Owen Andersonddd060f2008-01-10 01:36:43 +0000277static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000278 LiveIntervals& LI) {
279 LiveInterval& I = LI.getOrCreateInterval(r);
280 unsigned idx = LI.getMBBStartIdx(MBB);
281 return I.liveBeforeAndAt(idx);
Owen Anderson60a877d2007-11-07 05:17:15 +0000282}
283
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000284/// isLiveOut - help method that determines, from a regno, if a register is
Owen Anderson60a877d2007-11-07 05:17:15 +0000285/// live out of a block.
Owen Andersonddd060f2008-01-10 01:36:43 +0000286static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000287 LiveIntervals& LI) {
288 for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
289 E = MBB->succ_end(); PI != E; ++PI) {
290 if (isLiveIn(r, *PI, LI))
291 return true;
Owen Anderson14b3fb72007-11-08 01:32:45 +0000292 }
Owen Anderson60a877d2007-11-07 05:17:15 +0000293
294 return false;
295}
296
Owen Anderson87a702b2007-12-16 05:44:27 +0000297/// interferes - checks for local interferences by scanning a block. The only
298/// trick parameter is 'mode' which tells it the relationship of the two
299/// registers. 0 - defined in the same block, 1 - first properly dominates
300/// second, 2 - second properly dominates first
Owen Andersonb199cbe2008-01-10 00:33:11 +0000301static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000302 LiveIntervals& LV, unsigned mode) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000303 MachineInstr* def = 0;
304 MachineInstr* kill = 0;
305
Owen Andersonddd060f2008-01-10 01:36:43 +0000306 // The code is still in SSA form at this point, so there is only one
307 // definition per VReg. Thus we can safely use MRI->getVRegDef().
308 const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
Owen Andersonb199cbe2008-01-10 00:33:11 +0000309
Owen Anderson87a702b2007-12-16 05:44:27 +0000310 bool interference = false;
311
312 // Wallk the block, checking for interferences
313 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
314 MBI != MBE; ++MBI) {
315 MachineInstr* curr = MBI;
316
317 // Same defining block...
318 if (mode == 0) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000319 if (curr == MRI->getVRegDef(a)) {
320 // If we find our first definition, save it
Owen Anderson87a702b2007-12-16 05:44:27 +0000321 if (!def) {
322 def = curr;
Owen Andersonddd060f2008-01-10 01:36:43 +0000323 // If there's already an unkilled definition, then
Owen Anderson87a702b2007-12-16 05:44:27 +0000324 // this is an interference
325 } else if (!kill) {
326 interference = true;
327 break;
Owen Andersonddd060f2008-01-10 01:36:43 +0000328 // If there's a definition followed by a KillInst, then
Owen Anderson87a702b2007-12-16 05:44:27 +0000329 // they can't interfere
330 } else {
331 interference = false;
332 break;
333 }
334 // Symmetric with the above
Owen Andersonddd060f2008-01-10 01:36:43 +0000335 } else if (curr == MRI->getVRegDef(b)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000336 if (!def) {
337 def = curr;
338 } else if (!kill) {
339 interference = true;
340 break;
341 } else {
342 interference = false;
343 break;
344 }
Owen Andersonddd060f2008-01-10 01:36:43 +0000345 // Store KillInsts if they match up with the definition
Evan Cheng6130f662008-03-05 00:59:57 +0000346 } else if (curr->killsRegister(a)) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000347 if (def == MRI->getVRegDef(a)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000348 kill = curr;
Evan Cheng6130f662008-03-05 00:59:57 +0000349 } else if (curr->killsRegister(b)) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000350 if (def == MRI->getVRegDef(b)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000351 kill = curr;
352 }
353 }
354 }
355 // First properly dominates second...
356 } else if (mode == 1) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000357 if (curr == MRI->getVRegDef(b)) {
358 // Definition of second without kill of first is an interference
Owen Anderson87a702b2007-12-16 05:44:27 +0000359 if (!kill) {
360 interference = true;
361 break;
Owen Andersonddd060f2008-01-10 01:36:43 +0000362 // Definition after a kill is a non-interference
Owen Anderson87a702b2007-12-16 05:44:27 +0000363 } else {
364 interference = false;
365 break;
366 }
367 // Save KillInsts of First
Evan Cheng6130f662008-03-05 00:59:57 +0000368 } else if (curr->killsRegister(a)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000369 kill = curr;
370 }
371 // Symmetric with the above
372 } else if (mode == 2) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000373 if (curr == MRI->getVRegDef(a)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000374 if (!kill) {
375 interference = true;
376 break;
377 } else {
378 interference = false;
379 break;
380 }
Evan Cheng6130f662008-03-05 00:59:57 +0000381 } else if (curr->killsRegister(b)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000382 kill = curr;
383 }
384 }
385 }
386
387 return interference;
388}
389
Owen Andersondc4d6552008-01-10 00:47:01 +0000390/// processBlock - Determine how to break up PHIs in the current block. Each
391/// PHI is broken up by some combination of renaming its operands and inserting
392/// copies. This method is responsible for determining which operands receive
393/// which treatment.
Owen Anderson60a877d2007-11-07 05:17:15 +0000394void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000395 LiveIntervals& LI = getAnalysis<LiveIntervals>();
Owen Andersonddd060f2008-01-10 01:36:43 +0000396 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
Owen Anderson60a877d2007-11-07 05:17:15 +0000397
398 // Holds names that have been added to a set in any PHI within this block
399 // before the current one.
400 std::set<unsigned> ProcessedNames;
401
Owen Andersondc4d6552008-01-10 00:47:01 +0000402 // Iterate over all the PHI nodes in this block
Owen Anderson60a877d2007-11-07 05:17:15 +0000403 MachineBasicBlock::iterator P = MBB->begin();
Owen Anderson864e3a32008-01-09 10:41:39 +0000404 while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
Owen Andersonafc6de02007-12-10 08:07:09 +0000405 unsigned DestReg = P->getOperand(0).getReg();
406
Owen Andersondc4d6552008-01-10 00:47:01 +0000407 // PHIUnion is the set of incoming registers to the PHI node that
408 // are going to be renames rather than having copies inserted. This set
409 // is refinded over the course of this function. UnionedBlocks is the set
410 // of corresponding MBBs.
Owen Anderson60a877d2007-11-07 05:17:15 +0000411 std::set<unsigned> PHIUnion;
412 std::set<MachineBasicBlock*> UnionedBlocks;
413
Owen Andersondc4d6552008-01-10 00:47:01 +0000414 // Iterate over the operands of the PHI node
Owen Anderson60a877d2007-11-07 05:17:15 +0000415 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
416 unsigned SrcReg = P->getOperand(i-1).getReg();
Owen Anderson60a877d2007-11-07 05:17:15 +0000417
Owen Andersondc4d6552008-01-10 00:47:01 +0000418 // Check for trivial interferences via liveness information, allowing us
419 // to avoid extra work later. Any registers that interfere cannot both
420 // be in the renaming set, so choose one and add copies for it instead.
421 // The conditions are:
422 // 1) if the operand is live into the PHI node's block OR
423 // 2) if the PHI node is live out of the operand's defining block OR
424 // 3) if the operand is itself a PHI node and the original PHI is
425 // live into the operand's defining block OR
426 // 4) if the operand is already being renamed for another PHI node
427 // in this block OR
428 // 5) if any two operands are defined in the same block, insert copies
429 // for one of them
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000430 if (isLiveIn(SrcReg, P->getParent(), LI) ||
Owen Andersonddd060f2008-01-10 01:36:43 +0000431 isLiveOut(P->getOperand(0).getReg(),
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000432 MRI.getVRegDef(SrcReg)->getParent(), LI) ||
Owen Andersonddd060f2008-01-10 01:36:43 +0000433 ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
434 isLiveIn(P->getOperand(0).getReg(),
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000435 MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
Owen Andersonafc6de02007-12-10 08:07:09 +0000436 ProcessedNames.count(SrcReg) ||
Owen Andersonddd060f2008-01-10 01:36:43 +0000437 UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
Owen Andersonafc6de02007-12-10 08:07:09 +0000438
Owen Andersondc4d6552008-01-10 00:47:01 +0000439 // Add a copy for the selected register
Chris Lattner8aa797a2007-12-30 23:10:15 +0000440 MachineBasicBlock* From = P->getOperand(i).getMBB();
Owen Andersonefbcebc2007-12-23 15:37:26 +0000441 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
442 UsedByAnother.insert(SrcReg);
Owen Anderson60a877d2007-11-07 05:17:15 +0000443 } else {
Owen Andersondc4d6552008-01-10 00:47:01 +0000444 // Otherwise, add it to the renaming set
Owen Anderson60a877d2007-11-07 05:17:15 +0000445 PHIUnion.insert(SrcReg);
Owen Andersonddd060f2008-01-10 01:36:43 +0000446 UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
Owen Anderson60a877d2007-11-07 05:17:15 +0000447 }
Owen Anderson60a877d2007-11-07 05:17:15 +0000448 }
449
Owen Andersondc4d6552008-01-10 00:47:01 +0000450 // Compute the dominator forest for the renaming set. This is a forest
451 // where the nodes are the registers and the edges represent dominance
452 // relations between the defining blocks of the registers
Owen Anderson42f9e962007-11-13 20:13:24 +0000453 std::vector<StrongPHIElimination::DomForestNode*> DF =
Owen Andersonddd060f2008-01-10 01:36:43 +0000454 computeDomForest(PHIUnion, MRI);
Owen Anderson42f9e962007-11-13 20:13:24 +0000455
Owen Andersondc4d6552008-01-10 00:47:01 +0000456 // Walk DomForest to resolve interferences at an inter-block level. This
457 // will remove registers from the renaming set (and insert copies for them)
458 // if interferences are found.
Owen Anderson62d67dd2007-12-13 05:53:03 +0000459 std::vector<std::pair<unsigned, unsigned> > localInterferences;
460 processPHIUnion(P, PHIUnion, DF, localInterferences);
461
Owen Andersondc4d6552008-01-10 00:47:01 +0000462 // The dominator forest walk may have returned some register pairs whose
463 // interference cannot be determines from dominator analysis. We now
464 // examine these pairs for local interferences.
Owen Anderson87a702b2007-12-16 05:44:27 +0000465 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
466 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
467 std::pair<unsigned, unsigned> p = *I;
468
Owen Anderson87a702b2007-12-16 05:44:27 +0000469 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
470
471 // Determine the block we need to scan and the relationship between
472 // the two registers
473 MachineBasicBlock* scan = 0;
474 unsigned mode = 0;
Owen Andersonddd060f2008-01-10 01:36:43 +0000475 if (MRI.getVRegDef(p.first)->getParent() ==
476 MRI.getVRegDef(p.second)->getParent()) {
477 scan = MRI.getVRegDef(p.first)->getParent();
Owen Anderson87a702b2007-12-16 05:44:27 +0000478 mode = 0; // Same block
Owen Andersonddd060f2008-01-10 01:36:43 +0000479 } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
480 MRI.getVRegDef(p.second)->getParent())) {
481 scan = MRI.getVRegDef(p.second)->getParent();
Owen Anderson87a702b2007-12-16 05:44:27 +0000482 mode = 1; // First dominates second
483 } else {
Owen Andersonddd060f2008-01-10 01:36:43 +0000484 scan = MRI.getVRegDef(p.first)->getParent();
Owen Anderson87a702b2007-12-16 05:44:27 +0000485 mode = 2; // Second dominates first
486 }
487
488 // If there's an interference, we need to insert copies
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000489 if (interferes(p.first, p.second, scan, LI, mode)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000490 // Insert copies for First
491 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
492 if (P->getOperand(i-1).getReg() == p.first) {
493 unsigned SrcReg = p.first;
494 MachineBasicBlock* From = P->getOperand(i).getMBB();
495
Owen Andersonefbcebc2007-12-23 15:37:26 +0000496 Waiting[From].insert(std::make_pair(SrcReg,
497 P->getOperand(0).getReg()));
498 UsedByAnother.insert(SrcReg);
499
Owen Anderson87a702b2007-12-16 05:44:27 +0000500 PHIUnion.erase(SrcReg);
501 }
502 }
503 }
504 }
Owen Anderson42f9e962007-11-13 20:13:24 +0000505
Owen Andersondc4d6552008-01-10 00:47:01 +0000506 // Add the renaming set for this PHI node to our overal renaming information
Owen Anderson0c5714b2008-01-08 21:54:52 +0000507 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
Owen Andersoncae8d8d2007-12-22 04:59:10 +0000508
Owen Andersondc4d6552008-01-10 00:47:01 +0000509 // Remember which registers are already renamed, so that we don't try to
510 // rename them for another PHI node in this block
Owen Anderson42f9e962007-11-13 20:13:24 +0000511 ProcessedNames.insert(PHIUnion.begin(), PHIUnion.end());
Owen Andersondc4d6552008-01-10 00:47:01 +0000512
Owen Anderson60a877d2007-11-07 05:17:15 +0000513 ++P;
514 }
Owen Andersonee49b532007-11-06 05:22:43 +0000515}
516
Gabor Greif2cf36e02008-03-06 10:51:21 +0000517/// processPHIUnion - Take a set of candidate registers to be coalesced when
Owen Anderson965b4672007-12-16 04:07:23 +0000518/// decomposing the PHI instruction. Use the DominanceForest to remove the ones
519/// that are known to interfere, and flag others that need to be checked for
520/// local interferences.
Owen Andersond525f662007-12-11 20:12:11 +0000521void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
522 std::set<unsigned>& PHIUnion,
Owen Anderson62d67dd2007-12-13 05:53:03 +0000523 std::vector<StrongPHIElimination::DomForestNode*>& DF,
524 std::vector<std::pair<unsigned, unsigned> >& locals) {
Owen Andersond525f662007-12-11 20:12:11 +0000525
526 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
527 SmallPtrSet<DomForestNode*, 4> visited;
528
Owen Andersonddd060f2008-01-10 01:36:43 +0000529 // Code is still in SSA form, so we can use MRI::getVRegDef()
530 MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
531
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000532 LiveIntervals& LI = getAnalysis<LiveIntervals>();
Owen Andersond525f662007-12-11 20:12:11 +0000533 unsigned DestReg = Inst->getOperand(0).getReg();
534
Owen Anderson965b4672007-12-16 04:07:23 +0000535 // DF walk on the DomForest
Owen Andersond525f662007-12-11 20:12:11 +0000536 while (!worklist.empty()) {
537 DomForestNode* DFNode = worklist.back();
538
Owen Andersond525f662007-12-11 20:12:11 +0000539 visited.insert(DFNode);
540
541 bool inserted = false;
Owen Andersond525f662007-12-11 20:12:11 +0000542 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
543 CI != CE; ++CI) {
544 DomForestNode* child = *CI;
Owen Anderson3b489522008-01-21 22:01:01 +0000545
546 // If the current node is live-out of the defining block of one of its
Owen Andersona6b19262008-01-21 22:03:00 +0000547 // children, insert a copy for it. NOTE: The paper actually calls for
548 // a more elaborate heuristic for determining whether to insert copies
549 // for the child or the parent. In the interest of simplicity, we're
550 // just always choosing the parent.
Owen Andersonddd060f2008-01-10 01:36:43 +0000551 if (isLiveOut(DFNode->getReg(),
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000552 MRI.getVRegDef(child->getReg())->getParent(), LI)) {
Owen Andersond525f662007-12-11 20:12:11 +0000553 // Insert copies for parent
554 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
555 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
Owen Andersoned2ffa22007-12-12 01:25:08 +0000556 unsigned SrcReg = DFNode->getReg();
Owen Andersond525f662007-12-11 20:12:11 +0000557 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
558
Owen Andersonefbcebc2007-12-23 15:37:26 +0000559 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
560 UsedByAnother.insert(SrcReg);
561
Owen Andersoned2ffa22007-12-12 01:25:08 +0000562 PHIUnion.erase(SrcReg);
Owen Andersond525f662007-12-11 20:12:11 +0000563 }
564 }
Owen Anderson3b489522008-01-21 22:01:01 +0000565
566 // If a node is live-in to the defining block of one of its children, but
567 // not live-out, then we need to scan that block for local interferences.
Owen Andersonddd060f2008-01-10 01:36:43 +0000568 } else if (isLiveIn(DFNode->getReg(),
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000569 MRI.getVRegDef(child->getReg())->getParent(), LI) ||
Owen Andersonddd060f2008-01-10 01:36:43 +0000570 MRI.getVRegDef(DFNode->getReg())->getParent() ==
571 MRI.getVRegDef(child->getReg())->getParent()) {
Owen Anderson62d67dd2007-12-13 05:53:03 +0000572 // Add (p, c) to possible local interferences
573 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
Owen Andersond525f662007-12-11 20:12:11 +0000574 }
Owen Anderson965b4672007-12-16 04:07:23 +0000575
Owen Anderson4ba08ec2007-12-13 05:43:37 +0000576 if (!visited.count(child)) {
577 worklist.push_back(child);
578 inserted = true;
Owen Andersond525f662007-12-11 20:12:11 +0000579 }
580 }
581
582 if (!inserted) worklist.pop_back();
583 }
584}
585
Owen Andersonefbcebc2007-12-23 15:37:26 +0000586/// ScheduleCopies - Insert copies into predecessor blocks, scheduling
587/// them properly so as to avoid the 'lost copy' and the 'virtual swap'
588/// problems.
589///
590/// Based on "Practical Improvements to the Construction and Destruction
591/// of Static Single Assignment Form" by Briggs, et al.
Owen Andersonf1519e82007-12-24 22:12:23 +0000592void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
593 std::set<unsigned>& pushed) {
Owen Anderson0d893b42008-01-08 05:16:15 +0000594 // FIXME: This function needs to update LiveVariables
Owen Andersonefbcebc2007-12-23 15:37:26 +0000595 std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
596
597 std::map<unsigned, unsigned> worklist;
598 std::map<unsigned, unsigned> map;
599
600 // Setup worklist of initial copies
601 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
602 E = copy_set.end(); I != E; ) {
603 map.insert(std::make_pair(I->first, I->first));
604 map.insert(std::make_pair(I->second, I->second));
605
606 if (!UsedByAnother.count(I->first)) {
607 worklist.insert(*I);
608
609 // Avoid iterator invalidation
610 unsigned first = I->first;
611 ++I;
612 copy_set.erase(first);
613 } else {
614 ++I;
615 }
616 }
617
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000618 LiveIntervals& LI = getAnalysis<LiveIntervals>();
Owen Anderson0d893b42008-01-08 05:16:15 +0000619 MachineFunction* MF = MBB->getParent();
Owen Andersonddd060f2008-01-10 01:36:43 +0000620 MachineRegisterInfo& MRI = MF->getRegInfo();
Owen Anderson0d893b42008-01-08 05:16:15 +0000621 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Owen Andersonefbcebc2007-12-23 15:37:26 +0000622
623 // Iterate over the worklist, inserting copies
624 while (!worklist.empty() || !copy_set.empty()) {
625 while (!worklist.empty()) {
626 std::pair<unsigned, unsigned> curr = *worklist.begin();
627 worklist.erase(curr.first);
628
Owen Anderson0d893b42008-01-08 05:16:15 +0000629 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
630
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000631 if (isLiveOut(curr.second, MBB, LI)) {
Owen Anderson0d893b42008-01-08 05:16:15 +0000632 // Create a temporary
633 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
634
635 // Insert copy from curr.second to a temporary at
636 // the Phi defining curr.second
Owen Andersonddd060f2008-01-10 01:36:43 +0000637 MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
638 TII->copyRegToReg(*PI->getParent(), PI, t,
Owen Anderson0d893b42008-01-08 05:16:15 +0000639 curr.second, RC, RC);
640
Owen Andersonefbcebc2007-12-23 15:37:26 +0000641 // Push temporary on Stacks
Owen Anderson0d893b42008-01-08 05:16:15 +0000642 Stacks[curr.second].push_back(t);
643
644 // Insert curr.second in pushed
645 pushed.insert(curr.second);
Owen Andersonefbcebc2007-12-23 15:37:26 +0000646 }
647
648 // Insert copy from map[curr.first] to curr.second
Owen Anderson9c2efa82008-01-10 00:01:41 +0000649 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
Owen Anderson0d893b42008-01-08 05:16:15 +0000650 map[curr.first], RC, RC);
Owen Andersonefbcebc2007-12-23 15:37:26 +0000651 map[curr.first] = curr.second;
652
653 // If curr.first is a destination in copy_set...
654 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
655 E = copy_set.end(); I != E; )
656 if (curr.first == I->second) {
657 std::pair<unsigned, unsigned> temp = *I;
658
659 // Avoid iterator invalidation
660 ++I;
661 copy_set.erase(temp.first);
662 worklist.insert(temp);
663
664 break;
665 } else {
666 ++I;
667 }
668 }
669
670 if (!copy_set.empty()) {
671 std::pair<unsigned, unsigned> curr = *copy_set.begin();
672 copy_set.erase(curr.first);
673
Owen Anderson0d893b42008-01-08 05:16:15 +0000674 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
675
Owen Andersonefbcebc2007-12-23 15:37:26 +0000676 // Insert a copy from dest to a new temporary t at the end of b
Owen Anderson0d893b42008-01-08 05:16:15 +0000677 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
Owen Anderson9c2efa82008-01-10 00:01:41 +0000678 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
Owen Anderson0d893b42008-01-08 05:16:15 +0000679 curr.second, RC, RC);
680 map[curr.second] = t;
Owen Andersonefbcebc2007-12-23 15:37:26 +0000681
682 worklist.insert(curr);
683 }
684 }
685}
686
Owen Andersonf1519e82007-12-24 22:12:23 +0000687/// InsertCopies - insert copies into MBB and all of its successors
Owen Anderson719fef62008-01-09 10:32:30 +0000688void StrongPHIElimination::InsertCopies(MachineBasicBlock* MBB,
689 std::set<MachineBasicBlock*>& visited) {
690 visited.insert(MBB);
691
Owen Andersonf1519e82007-12-24 22:12:23 +0000692 std::set<unsigned> pushed;
693
694 // Rewrite register uses from Stacks
695 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
696 I != E; ++I)
697 for (unsigned i = 0; i < I->getNumOperands(); ++i)
698 if (I->getOperand(i).isRegister() &&
699 Stacks[I->getOperand(i).getReg()].size()) {
700 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
701 }
702
703 // Schedule the copies for this block
704 ScheduleCopies(MBB, pushed);
705
706 // Recur to our successors
707 for (GraphTraits<MachineBasicBlock*>::ChildIteratorType I =
708 GraphTraits<MachineBasicBlock*>::child_begin(MBB), E =
709 GraphTraits<MachineBasicBlock*>::child_end(MBB); I != E; ++I)
Owen Anderson719fef62008-01-09 10:32:30 +0000710 if (!visited.count(*I))
711 InsertCopies(*I, visited);
Owen Andersonf1519e82007-12-24 22:12:23 +0000712
713 // As we exit this block, pop the names we pushed while processing it
714 for (std::set<unsigned>::iterator I = pushed.begin(),
715 E = pushed.end(); I != E; ++I)
716 Stacks[*I].pop_back();
717}
718
Owen Andersona4ad2e72007-11-06 04:49:43 +0000719bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
Owen Andersonefbcebc2007-12-23 15:37:26 +0000720 // Compute DFS numbers of each block
Owen Andersona4ad2e72007-11-06 04:49:43 +0000721 computeDFS(Fn);
722
Owen Andersonefbcebc2007-12-23 15:37:26 +0000723 // Determine which phi node operands need copies
Owen Anderson60a877d2007-11-07 05:17:15 +0000724 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
725 if (!I->empty() &&
726 I->begin()->getOpcode() == TargetInstrInfo::PHI)
727 processBlock(I);
Owen Andersona4ad2e72007-11-06 04:49:43 +0000728
Owen Andersonefbcebc2007-12-23 15:37:26 +0000729 // Insert copies
Owen Andersonf1519e82007-12-24 22:12:23 +0000730 // FIXME: This process should probably preserve LiveVariables
Owen Anderson719fef62008-01-09 10:32:30 +0000731 std::set<MachineBasicBlock*> visited;
732 InsertCopies(Fn.begin(), visited);
Owen Andersonefbcebc2007-12-23 15:37:26 +0000733
Owen Anderson0c5714b2008-01-08 21:54:52 +0000734 // Perform renaming
735 typedef std::map<unsigned, std::set<unsigned> > RenameSetType;
736 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
737 I != E; ++I)
738 for (std::set<unsigned>::iterator SI = I->second.begin(),
739 SE = I->second.end(); SI != SE; ++SI)
740 Fn.getRegInfo().replaceRegWith(*SI, I->first);
741
742 // FIXME: Insert last-minute copies
743
744 // Remove PHIs
Owen Anderson97ca75e2008-01-22 23:58:54 +0000745 std::vector<MachineInstr*> phis;
746 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
Owen Anderson0c5714b2008-01-08 21:54:52 +0000747 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
748 BI != BE; ++BI)
749 if (BI->getOpcode() == TargetInstrInfo::PHI)
Owen Anderson97ca75e2008-01-22 23:58:54 +0000750 phis.push_back(BI);
751 }
752
753 for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
754 I != E; ++I)
755 (*I)->eraseFromParent();
Owen Andersoncae8d8d2007-12-22 04:59:10 +0000756
Owen Andersona4ad2e72007-11-06 04:49:43 +0000757 return false;
758}