blob: 1df453c6fe51d584b4349f2fbb070ad954c6c78a [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 Anderson755ebab2008-03-17 06:08:26 +000028#include "llvm/CodeGen/MachineLoopInfo.h"
Owen Anderson0d893b42008-01-08 05:16:15 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Owen Anderson3947e4d2008-05-30 18:38:26 +000030#include "llvm/CodeGen/RegisterCoalescer.h"
Owen Anderson0bda0e82007-10-31 03:37:57 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetMachine.h"
Owen Andersonefbcebc2007-12-23 15:37:26 +000033#include "llvm/ADT/DepthFirstIterator.h"
Owen Anderson0bda0e82007-10-31 03:37:57 +000034#include "llvm/ADT/Statistic.h"
35#include "llvm/Support/Compiler.h"
36using namespace llvm;
37
Owen Anderson0bda0e82007-10-31 03:37:57 +000038namespace {
39 struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
40 static char ID; // Pass identification, replacement for typeid
41 StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
42
Owen Andersonec1213f2008-01-09 22:40:54 +000043 // Waiting stores, for each MBB, the set of copies that need to
44 // be inserted into that MBB
Owen Andersonafc6de02007-12-10 08:07:09 +000045 DenseMap<MachineBasicBlock*,
Owen Andersonefbcebc2007-12-23 15:37:26 +000046 std::map<unsigned, unsigned> > Waiting;
47
Owen Andersonec1213f2008-01-09 22:40:54 +000048 // Stacks holds the renaming stack for each register
Owen Andersonefbcebc2007-12-23 15:37:26 +000049 std::map<unsigned, std::vector<unsigned> > Stacks;
Owen Andersonec1213f2008-01-09 22:40:54 +000050
51 // Registers in UsedByAnother are PHI nodes that are themselves
52 // used as operands to another another PHI node
Owen Andersonefbcebc2007-12-23 15:37:26 +000053 std::set<unsigned> UsedByAnother;
Owen Andersonec1213f2008-01-09 22:40:54 +000054
Owen Andersona9efb262008-06-05 17:22:53 +000055 // RenameSets are the is a map from a PHI-defined register
Owen Andersonc12417e2008-07-24 17:12:16 +000056 // 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;
Owen Andersondfd07ea2008-03-12 04:22:57 +000059
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;
Owen Andersonafc6de02007-12-10 08:07:09 +000063
Owen Andersonec1213f2008-01-09 22:40:54 +000064 // Store the DFS-in number of each block
65 DenseMap<MachineBasicBlock*, unsigned> preorder;
66
67 // Store the DFS-out number of each block
68 DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
69
Owen Andersona4ad2e72007-11-06 04:49:43 +000070 bool runOnMachineFunction(MachineFunction &Fn);
71
Owen Anderson0bda0e82007-10-31 03:37:57 +000072 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.addRequired<MachineDominatorTree>();
Owen Andersoneb37ecc2008-03-10 07:22:36 +000074 AU.addRequired<LiveIntervals>();
75
76 // TODO: Actually make this true.
77 AU.addPreserved<LiveIntervals>();
Owen Anderson3947e4d2008-05-30 18:38:26 +000078 AU.addPreserved<RegisterCoalescer>();
Owen Anderson0bda0e82007-10-31 03:37:57 +000079 MachineFunctionPass::getAnalysisUsage(AU);
80 }
81
82 virtual void releaseMemory() {
83 preorder.clear();
84 maxpreorder.clear();
Owen Andersona4ad2e72007-11-06 04:49:43 +000085
Owen Andersonefbcebc2007-12-23 15:37:26 +000086 Waiting.clear();
Owen Andersonec1213f2008-01-09 22:40:54 +000087 Stacks.clear();
88 UsedByAnother.clear();
89 RenameSets.clear();
Owen Anderson0bda0e82007-10-31 03:37:57 +000090 }
91
92 private:
Owen Andersonec1213f2008-01-09 22:40:54 +000093
94 /// DomForestNode - Represents a node in the "dominator forest". This is
95 /// a forest in which the nodes represent registers and the edges
96 /// represent a dominance relation in the block defining those registers.
Owen Anderson83430bc2007-11-04 22:33:26 +000097 struct DomForestNode {
98 private:
Owen Andersonec1213f2008-01-09 22:40:54 +000099 // Store references to our children
Owen Anderson83430bc2007-11-04 22:33:26 +0000100 std::vector<DomForestNode*> children;
Owen Andersonec1213f2008-01-09 22:40:54 +0000101 // The register we represent
Owen Andersonee49b532007-11-06 05:22:43 +0000102 unsigned reg;
Owen Anderson83430bc2007-11-04 22:33:26 +0000103
Owen Andersonec1213f2008-01-09 22:40:54 +0000104 // Add another node as our child
Owen Anderson83430bc2007-11-04 22:33:26 +0000105 void addChild(DomForestNode* DFN) { children.push_back(DFN); }
106
107 public:
108 typedef std::vector<DomForestNode*>::iterator iterator;
109
Owen Andersonec1213f2008-01-09 22:40:54 +0000110 // Create a DomForestNode by providing the register it represents, and
111 // the node to be its parent. The virtual root node has register 0
112 // and a null parent.
Owen Andersonee49b532007-11-06 05:22:43 +0000113 DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
Owen Anderson83430bc2007-11-04 22:33:26 +0000114 if (parent)
115 parent->addChild(this);
116 }
117
Owen Andersona4ad2e72007-11-06 04:49:43 +0000118 ~DomForestNode() {
119 for (iterator I = begin(), E = end(); I != E; ++I)
120 delete *I;
121 }
Owen Anderson83430bc2007-11-04 22:33:26 +0000122
Owen Andersonec1213f2008-01-09 22:40:54 +0000123 /// getReg - Return the regiser that this node represents
Owen Andersonee49b532007-11-06 05:22:43 +0000124 inline unsigned getReg() { return reg; }
Owen Andersona4ad2e72007-11-06 04:49:43 +0000125
Owen Andersonec1213f2008-01-09 22:40:54 +0000126 // Provide iterator access to our children
Owen Andersona4ad2e72007-11-06 04:49:43 +0000127 inline DomForestNode::iterator begin() { return children.begin(); }
128 inline DomForestNode::iterator end() { return children.end(); }
Owen Anderson83430bc2007-11-04 22:33:26 +0000129 };
130
Owen Anderson0bda0e82007-10-31 03:37:57 +0000131 void computeDFS(MachineFunction& MF);
Owen Anderson60a877d2007-11-07 05:17:15 +0000132 void processBlock(MachineBasicBlock* MBB);
Owen Anderson83430bc2007-11-04 22:33:26 +0000133
Owen Andersonc12417e2008-07-24 17:12:16 +0000134 std::vector<DomForestNode*> computeDomForest(
135 std::map<unsigned, MachineBasicBlock*>& instrs,
Owen Andersonddd060f2008-01-10 01:36:43 +0000136 MachineRegisterInfo& MRI);
Owen Andersond525f662007-12-11 20:12:11 +0000137 void processPHIUnion(MachineInstr* Inst,
Owen Andersonc12417e2008-07-24 17:12:16 +0000138 std::map<unsigned, MachineBasicBlock*>& PHIUnion,
Owen Anderson62d67dd2007-12-13 05:53:03 +0000139 std::vector<StrongPHIElimination::DomForestNode*>& DF,
140 std::vector<std::pair<unsigned, unsigned> >& locals);
Owen Andersonf1519e82007-12-24 22:12:23 +0000141 void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
Owen Andersone46611e2008-03-24 04:11:27 +0000142 void InsertCopies(MachineBasicBlock* MBB,
143 SmallPtrSet<MachineBasicBlock*, 16>& v);
Owen Andersonc12417e2008-07-24 17:12:16 +0000144 void mergeLiveIntervals(unsigned primary, unsigned secondary,
145 MachineBasicBlock* pred);
Owen Anderson0bda0e82007-10-31 03:37:57 +0000146 };
Owen Anderson0bda0e82007-10-31 03:37:57 +0000147}
148
Dan Gohman844731a2008-05-13 00:00:25 +0000149char StrongPHIElimination::ID = 0;
150static RegisterPass<StrongPHIElimination>
151X("strong-phi-node-elimination",
152 "Eliminate PHI nodes for register allocation, intelligently");
153
Dan Gohman6ddba2b2008-05-13 02:05:11 +0000154const PassInfo *const llvm::StrongPHIEliminationID = &X;
Owen Anderson0bda0e82007-10-31 03:37:57 +0000155
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.
159void StrongPHIElimination::computeDFS(MachineFunction& MF) {
160 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
161 SmallPtrSet<MachineDomTreeNode*, 8> visited;
162
163 unsigned time = 0;
164
165 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
166
167 MachineDomTreeNode* node = DT.getRootNode();
168
169 std::vector<MachineDomTreeNode*> worklist;
170 worklist.push_back(node);
171
172 while (!worklist.empty()) {
173 MachineDomTreeNode* currNode = worklist.back();
174
175 if (!frontier.count(currNode)) {
176 frontier.insert(currNode);
177 ++time;
178 preorder.insert(std::make_pair(currNode->getBlock(), time));
179 }
180
181 bool inserted = false;
Owen Andersonbc91bd32008-03-31 01:39:20 +0000182 for (MachineDomTreeNode::iterator I = currNode->begin(), E = currNode->end();
Owen Anderson0bda0e82007-10-31 03:37:57 +0000183 I != E; ++I)
184 if (!frontier.count(*I) && !visited.count(*I)) {
185 worklist.push_back(*I);
186 inserted = true;
187 break;
188 }
189
190 if (!inserted) {
191 frontier.erase(currNode);
192 visited.insert(currNode);
193 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
194
195 worklist.pop_back();
196 }
197 }
Duncan Sands1bd32712007-10-31 08:49:24 +0000198}
Owen Anderson83430bc2007-11-04 22:33:26 +0000199
Dan Gohman844731a2008-05-13 00:00:25 +0000200namespace {
201
Owen Anderson8b96b9f2007-11-06 05:26:02 +0000202/// PreorderSorter - a helper class that is used to sort registers
203/// according to the preorder number of their defining blocks
Owen Anderson83430bc2007-11-04 22:33:26 +0000204class PreorderSorter {
205private:
206 DenseMap<MachineBasicBlock*, unsigned>& preorder;
Owen Andersonddd060f2008-01-10 01:36:43 +0000207 MachineRegisterInfo& MRI;
Owen Anderson83430bc2007-11-04 22:33:26 +0000208
209public:
Owen Andersonee49b532007-11-06 05:22:43 +0000210 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
Owen Andersonddd060f2008-01-10 01:36:43 +0000211 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
Owen Anderson83430bc2007-11-04 22:33:26 +0000212
Owen Andersonee49b532007-11-06 05:22:43 +0000213 bool operator()(unsigned A, unsigned B) {
Owen Anderson83430bc2007-11-04 22:33:26 +0000214 if (A == B)
215 return false;
216
Owen Andersonddd060f2008-01-10 01:36:43 +0000217 MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
218 MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
Owen Andersonee49b532007-11-06 05:22:43 +0000219
220 if (preorder[ABlock] < preorder[BBlock])
Owen Anderson83430bc2007-11-04 22:33:26 +0000221 return true;
Owen Andersonee49b532007-11-06 05:22:43 +0000222 else if (preorder[ABlock] > preorder[BBlock])
Owen Anderson83430bc2007-11-04 22:33:26 +0000223 return false;
224
Owen Andersonee49b532007-11-06 05:22:43 +0000225 return false;
Owen Anderson83430bc2007-11-04 22:33:26 +0000226 }
227};
228
Dan Gohman844731a2008-05-13 00:00:25 +0000229}
230
Owen Anderson8b96b9f2007-11-06 05:26:02 +0000231/// computeDomForest - compute the subforest of the DomTree corresponding
232/// to the defining blocks of the registers in question
Owen Anderson83430bc2007-11-04 22:33:26 +0000233std::vector<StrongPHIElimination::DomForestNode*>
Owen Andersonc12417e2008-07-24 17:12:16 +0000234StrongPHIElimination::computeDomForest(
235 std::map<unsigned, MachineBasicBlock*>& regs,
Owen Andersonddd060f2008-01-10 01:36:43 +0000236 MachineRegisterInfo& MRI) {
Owen Andersonec1213f2008-01-09 22:40:54 +0000237 // 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.
Owen Anderson83430bc2007-11-04 22:33:26 +0000239 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
240 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
241
Owen Andersonec1213f2008-01-09 22:40:54 +0000242 // Populate a worklist with the registers
Owen Andersonee49b532007-11-06 05:22:43 +0000243 std::vector<unsigned> worklist;
244 worklist.reserve(regs.size());
Owen Andersonc12417e2008-07-24 17:12:16 +0000245 for (std::map<unsigned, MachineBasicBlock*>::iterator I = regs.begin(),
246 E = regs.end(); I != E; ++I)
Owen Anderson00316712008-03-12 03:13:29 +0000247 worklist.push_back(I->first);
Owen Andersonee49b532007-11-06 05:22:43 +0000248
Owen Andersonec1213f2008-01-09 22:40:54 +0000249 // Sort the registers by the DFS-in number of their defining block
Owen Andersonddd060f2008-01-10 01:36:43 +0000250 PreorderSorter PS(preorder, MRI);
Owen Anderson83430bc2007-11-04 22:33:26 +0000251 std::sort(worklist.begin(), worklist.end(), PS);
252
Owen Andersonec1213f2008-01-09 22:40:54 +0000253 // Create a "current parent" stack, and put the virtual root on top of it
Owen Anderson83430bc2007-11-04 22:33:26 +0000254 DomForestNode* CurrentParent = VirtualRoot;
255 std::vector<DomForestNode*> stack;
256 stack.push_back(VirtualRoot);
257
Owen Andersonec1213f2008-01-09 22:40:54 +0000258 // Iterate over all the registers in the previously computed order
Owen Andersonee49b532007-11-06 05:22:43 +0000259 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
260 I != E; ++I) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000261 unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
Owen Andersoncb7d9492008-01-09 06:19:05 +0000262 MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
Owen Andersonddd060f2008-01-10 01:36:43 +0000263 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
Owen Andersoncb7d9492008-01-09 06:19:05 +0000264 0;
Owen Andersonee49b532007-11-06 05:22:43 +0000265
Owen Andersonec1213f2008-01-09 22:40:54 +0000266 // 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.
Owen Andersonee49b532007-11-06 05:22:43 +0000268 while (pre > maxpreorder[parentBlock]) {
Owen Anderson83430bc2007-11-04 22:33:26 +0000269 stack.pop_back();
270 CurrentParent = stack.back();
Owen Andersonee49b532007-11-06 05:22:43 +0000271
Owen Anderson864e3a32008-01-09 10:41:39 +0000272 parentBlock = CurrentParent->getReg() ?
Owen Andersonddd060f2008-01-10 01:36:43 +0000273 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
Owen Anderson864e3a32008-01-09 10:41:39 +0000274 0;
Owen Anderson83430bc2007-11-04 22:33:26 +0000275 }
276
Owen Andersonec1213f2008-01-09 22:40:54 +0000277 // Now that we've found the appropriate parent, create a DomForestNode for
278 // this register and attach it to the forest
Owen Anderson83430bc2007-11-04 22:33:26 +0000279 DomForestNode* child = new DomForestNode(*I, CurrentParent);
Owen Andersonec1213f2008-01-09 22:40:54 +0000280
281 // Push this new node on the "current parent" stack
Owen Anderson83430bc2007-11-04 22:33:26 +0000282 stack.push_back(child);
283 CurrentParent = child;
284 }
285
Owen Andersonec1213f2008-01-09 22:40:54 +0000286 // Return a vector containing the children of the virtual root node
Owen Anderson83430bc2007-11-04 22:33:26 +0000287 std::vector<DomForestNode*> ret;
288 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
289 return ret;
290}
Owen Andersona4ad2e72007-11-06 04:49:43 +0000291
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000292/// isLiveIn - helper method that determines, from a regno, if a register
Owen Anderson60a877d2007-11-07 05:17:15 +0000293/// is live into a block
Owen Andersonddd060f2008-01-10 01:36:43 +0000294static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000295 LiveIntervals& LI) {
296 LiveInterval& I = LI.getOrCreateInterval(r);
297 unsigned idx = LI.getMBBStartIdx(MBB);
298 return I.liveBeforeAndAt(idx);
Owen Anderson60a877d2007-11-07 05:17:15 +0000299}
300
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000301/// isLiveOut - help method that determines, from a regno, if a register is
Owen Anderson60a877d2007-11-07 05:17:15 +0000302/// live out of a block.
Owen Andersonddd060f2008-01-10 01:36:43 +0000303static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000304 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;
Owen Anderson14b3fb72007-11-08 01:32:45 +0000309 }
Owen Anderson60a877d2007-11-07 05:17:15 +0000310
311 return false;
312}
313
Owen Anderson87a702b2007-12-16 05:44:27 +0000314/// 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
Owen Andersonb199cbe2008-01-10 00:33:11 +0000318static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000319 LiveIntervals& LV, unsigned mode) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000320 MachineInstr* def = 0;
321 MachineInstr* kill = 0;
322
Owen Andersonddd060f2008-01-10 01:36:43 +0000323 // 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();
Owen Andersonb199cbe2008-01-10 00:33:11 +0000326
Owen Anderson87a702b2007-12-16 05:44:27 +0000327 bool interference = false;
328
329 // Wallk the block, checking for interferences
330 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
331 MBI != MBE; ++MBI) {
332 MachineInstr* curr = MBI;
333
334 // Same defining block...
335 if (mode == 0) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000336 if (curr == MRI->getVRegDef(a)) {
337 // If we find our first definition, save it
Owen Anderson87a702b2007-12-16 05:44:27 +0000338 if (!def) {
339 def = curr;
Owen Andersonddd060f2008-01-10 01:36:43 +0000340 // If there's already an unkilled definition, then
Owen Anderson87a702b2007-12-16 05:44:27 +0000341 // this is an interference
342 } else if (!kill) {
343 interference = true;
344 break;
Owen Andersonddd060f2008-01-10 01:36:43 +0000345 // If there's a definition followed by a KillInst, then
Owen Anderson87a702b2007-12-16 05:44:27 +0000346 // they can't interfere
347 } else {
348 interference = false;
349 break;
350 }
351 // Symmetric with the above
Owen Andersonddd060f2008-01-10 01:36:43 +0000352 } else if (curr == MRI->getVRegDef(b)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000353 if (!def) {
354 def = curr;
355 } else if (!kill) {
356 interference = true;
357 break;
358 } else {
359 interference = false;
360 break;
361 }
Owen Andersonddd060f2008-01-10 01:36:43 +0000362 // Store KillInsts if they match up with the definition
Evan Cheng6130f662008-03-05 00:59:57 +0000363 } else if (curr->killsRegister(a)) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000364 if (def == MRI->getVRegDef(a)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000365 kill = curr;
Evan Cheng6130f662008-03-05 00:59:57 +0000366 } else if (curr->killsRegister(b)) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000367 if (def == MRI->getVRegDef(b)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000368 kill = curr;
369 }
370 }
371 }
372 // First properly dominates second...
373 } else if (mode == 1) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000374 if (curr == MRI->getVRegDef(b)) {
375 // Definition of second without kill of first is an interference
Owen Anderson87a702b2007-12-16 05:44:27 +0000376 if (!kill) {
377 interference = true;
378 break;
Owen Andersonddd060f2008-01-10 01:36:43 +0000379 // Definition after a kill is a non-interference
Owen Anderson87a702b2007-12-16 05:44:27 +0000380 } else {
381 interference = false;
382 break;
383 }
384 // Save KillInsts of First
Evan Cheng6130f662008-03-05 00:59:57 +0000385 } else if (curr->killsRegister(a)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000386 kill = curr;
387 }
388 // Symmetric with the above
389 } else if (mode == 2) {
Owen Andersonddd060f2008-01-10 01:36:43 +0000390 if (curr == MRI->getVRegDef(a)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000391 if (!kill) {
392 interference = true;
393 break;
394 } else {
395 interference = false;
396 break;
397 }
Evan Cheng6130f662008-03-05 00:59:57 +0000398 } else if (curr->killsRegister(b)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000399 kill = curr;
400 }
401 }
402 }
403
404 return interference;
405}
406
Owen Andersondc4d6552008-01-10 00:47:01 +0000407/// 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
410/// which treatment.
Owen Anderson60a877d2007-11-07 05:17:15 +0000411void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000412 LiveIntervals& LI = getAnalysis<LiveIntervals>();
Owen Andersonddd060f2008-01-10 01:36:43 +0000413 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
Owen Anderson60a877d2007-11-07 05:17:15 +0000414
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;
418
Owen Andersondc4d6552008-01-10 00:47:01 +0000419 // Iterate over all the PHI nodes in this block
Owen Anderson60a877d2007-11-07 05:17:15 +0000420 MachineBasicBlock::iterator P = MBB->begin();
Owen Anderson78216bc2008-04-01 18:05:08 +0000421 while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
Owen Andersonafc6de02007-12-10 08:07:09 +0000422 unsigned DestReg = P->getOperand(0).getReg();
423
Owen Anderson9860b712008-08-06 20:29:20 +0000424
Owen Andersond382f8a2008-03-26 03:03:23 +0000425 // Don't both doing PHI elimination for dead PHI's.
426 if (P->registerDefIsDead(DestReg)) {
427 ++P;
428 continue;
429 }
430
Owen Andersondfd07ea2008-03-12 04:22:57 +0000431 LiveInterval& PI = LI.getOrCreateInterval(DestReg);
Owen Andersonc7c00362008-03-29 01:58:47 +0000432 unsigned pIdx = LI.getDefIndex(LI.getInstructionIndex(P));
Owen Andersondfd07ea2008-03-12 04:22:57 +0000433 VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
434 PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
435
Owen Andersondc4d6552008-01-10 00:47:01 +0000436 // PHIUnion is the set of incoming registers to the PHI node that
437 // are going to be renames rather than having copies inserted. This set
438 // is refinded over the course of this function. UnionedBlocks is the set
439 // of corresponding MBBs.
Owen Andersonc12417e2008-07-24 17:12:16 +0000440 std::map<unsigned, MachineBasicBlock*> PHIUnion;
Owen Andersone46611e2008-03-24 04:11:27 +0000441 SmallPtrSet<MachineBasicBlock*, 8> UnionedBlocks;
Owen Anderson60a877d2007-11-07 05:17:15 +0000442
Owen Andersondc4d6552008-01-10 00:47:01 +0000443 // Iterate over the operands of the PHI node
Owen Anderson60a877d2007-11-07 05:17:15 +0000444 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
445 unsigned SrcReg = P->getOperand(i-1).getReg();
Owen Anderson9860b712008-08-06 20:29:20 +0000446
447 // Don't need to try to coalesce a register with itself.
448 if (SrcReg == DestReg) {
449 ProcessedNames.insert(SrcReg);
450 continue;
451 }
Owen Anderson60a877d2007-11-07 05:17:15 +0000452
Owen Andersondc4d6552008-01-10 00:47:01 +0000453 // Check for trivial interferences via liveness information, allowing us
454 // to avoid extra work later. Any registers that interfere cannot both
455 // be in the renaming set, so choose one and add copies for it instead.
456 // The conditions are:
457 // 1) if the operand is live into the PHI node's block OR
458 // 2) if the PHI node is live out of the operand's defining block OR
459 // 3) if the operand is itself a PHI node and the original PHI is
460 // live into the operand's defining block OR
461 // 4) if the operand is already being renamed for another PHI node
462 // in this block OR
463 // 5) if any two operands are defined in the same block, insert copies
464 // for one of them
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000465 if (isLiveIn(SrcReg, P->getParent(), LI) ||
Owen Andersonddd060f2008-01-10 01:36:43 +0000466 isLiveOut(P->getOperand(0).getReg(),
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000467 MRI.getVRegDef(SrcReg)->getParent(), LI) ||
Owen Andersonddd060f2008-01-10 01:36:43 +0000468 ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
469 isLiveIn(P->getOperand(0).getReg(),
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000470 MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
Owen Andersonafc6de02007-12-10 08:07:09 +0000471 ProcessedNames.count(SrcReg) ||
Owen Andersonddd060f2008-01-10 01:36:43 +0000472 UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
Owen Andersonafc6de02007-12-10 08:07:09 +0000473
Owen Andersondc4d6552008-01-10 00:47:01 +0000474 // Add a copy for the selected register
Chris Lattner8aa797a2007-12-30 23:10:15 +0000475 MachineBasicBlock* From = P->getOperand(i).getMBB();
Owen Andersonefbcebc2007-12-23 15:37:26 +0000476 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
477 UsedByAnother.insert(SrcReg);
Owen Anderson60a877d2007-11-07 05:17:15 +0000478 } else {
Owen Andersondc4d6552008-01-10 00:47:01 +0000479 // Otherwise, add it to the renaming set
Owen Andersonc12417e2008-07-24 17:12:16 +0000480 PHIUnion.insert(std::make_pair(SrcReg,P->getOperand(i).getMBB()));
Owen Andersonddd060f2008-01-10 01:36:43 +0000481 UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
Owen Anderson60a877d2007-11-07 05:17:15 +0000482 }
Owen Anderson60a877d2007-11-07 05:17:15 +0000483 }
484
Owen Andersondc4d6552008-01-10 00:47:01 +0000485 // Compute the dominator forest for the renaming set. This is a forest
486 // where the nodes are the registers and the edges represent dominance
487 // relations between the defining blocks of the registers
Owen Anderson42f9e962007-11-13 20:13:24 +0000488 std::vector<StrongPHIElimination::DomForestNode*> DF =
Owen Andersonddd060f2008-01-10 01:36:43 +0000489 computeDomForest(PHIUnion, MRI);
Owen Anderson42f9e962007-11-13 20:13:24 +0000490
Owen Andersondc4d6552008-01-10 00:47:01 +0000491 // Walk DomForest to resolve interferences at an inter-block level. This
492 // will remove registers from the renaming set (and insert copies for them)
493 // if interferences are found.
Owen Anderson62d67dd2007-12-13 05:53:03 +0000494 std::vector<std::pair<unsigned, unsigned> > localInterferences;
495 processPHIUnion(P, PHIUnion, DF, localInterferences);
496
Owen Anderson52b17332008-04-02 03:00:13 +0000497 // If one of the inputs is defined in the same block as the current PHI
498 // then we need to check for a local interference between that input and
499 // the PHI.
Owen Andersonc12417e2008-07-24 17:12:16 +0000500 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
Owen Anderson52b17332008-04-02 03:00:13 +0000501 E = PHIUnion.end(); I != E; ++I)
502 if (MRI.getVRegDef(I->first)->getParent() == P->getParent())
503 localInterferences.push_back(std::make_pair(I->first,
504 P->getOperand(0).getReg()));
505
Owen Andersondc4d6552008-01-10 00:47:01 +0000506 // The dominator forest walk may have returned some register pairs whose
Owen Anderson52b17332008-04-02 03:00:13 +0000507 // interference cannot be determined from dominator analysis. We now
Owen Andersondc4d6552008-01-10 00:47:01 +0000508 // examine these pairs for local interferences.
Owen Anderson87a702b2007-12-16 05:44:27 +0000509 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
510 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
511 std::pair<unsigned, unsigned> p = *I;
512
Owen Anderson87a702b2007-12-16 05:44:27 +0000513 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
514
515 // Determine the block we need to scan and the relationship between
516 // the two registers
517 MachineBasicBlock* scan = 0;
518 unsigned mode = 0;
Owen Andersonddd060f2008-01-10 01:36:43 +0000519 if (MRI.getVRegDef(p.first)->getParent() ==
520 MRI.getVRegDef(p.second)->getParent()) {
521 scan = MRI.getVRegDef(p.first)->getParent();
Owen Anderson87a702b2007-12-16 05:44:27 +0000522 mode = 0; // Same block
Owen Andersonddd060f2008-01-10 01:36:43 +0000523 } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
524 MRI.getVRegDef(p.second)->getParent())) {
525 scan = MRI.getVRegDef(p.second)->getParent();
Owen Anderson87a702b2007-12-16 05:44:27 +0000526 mode = 1; // First dominates second
527 } else {
Owen Andersonddd060f2008-01-10 01:36:43 +0000528 scan = MRI.getVRegDef(p.first)->getParent();
Owen Anderson87a702b2007-12-16 05:44:27 +0000529 mode = 2; // Second dominates first
530 }
531
532 // If there's an interference, we need to insert copies
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000533 if (interferes(p.first, p.second, scan, LI, mode)) {
Owen Anderson87a702b2007-12-16 05:44:27 +0000534 // Insert copies for First
535 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
536 if (P->getOperand(i-1).getReg() == p.first) {
537 unsigned SrcReg = p.first;
538 MachineBasicBlock* From = P->getOperand(i).getMBB();
539
Owen Andersonefbcebc2007-12-23 15:37:26 +0000540 Waiting[From].insert(std::make_pair(SrcReg,
541 P->getOperand(0).getReg()));
542 UsedByAnother.insert(SrcReg);
543
Owen Anderson87a702b2007-12-16 05:44:27 +0000544 PHIUnion.erase(SrcReg);
545 }
546 }
547 }
548 }
Owen Anderson42f9e962007-11-13 20:13:24 +0000549
Owen Anderson52b17332008-04-02 03:00:13 +0000550 // Add the renaming set for this PHI node to our overall renaming information
Owen Anderson0c5714b2008-01-08 21:54:52 +0000551 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
Owen Andersoncae8d8d2007-12-22 04:59:10 +0000552
Owen Andersondc4d6552008-01-10 00:47:01 +0000553 // Remember which registers are already renamed, so that we don't try to
554 // rename them for another PHI node in this block
Owen Andersonc12417e2008-07-24 17:12:16 +0000555 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
Owen Anderson00316712008-03-12 03:13:29 +0000556 E = PHIUnion.end(); I != E; ++I)
557 ProcessedNames.insert(I->first);
Owen Andersondc4d6552008-01-10 00:47:01 +0000558
Owen Anderson60a877d2007-11-07 05:17:15 +0000559 ++P;
560 }
Owen Andersonee49b532007-11-06 05:22:43 +0000561}
562
Gabor Greif2cf36e02008-03-06 10:51:21 +0000563/// processPHIUnion - Take a set of candidate registers to be coalesced when
Owen Anderson965b4672007-12-16 04:07:23 +0000564/// decomposing the PHI instruction. Use the DominanceForest to remove the ones
565/// that are known to interfere, and flag others that need to be checked for
566/// local interferences.
Owen Andersond525f662007-12-11 20:12:11 +0000567void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
Owen Andersonc12417e2008-07-24 17:12:16 +0000568 std::map<unsigned, MachineBasicBlock*>& PHIUnion,
Owen Anderson62d67dd2007-12-13 05:53:03 +0000569 std::vector<StrongPHIElimination::DomForestNode*>& DF,
570 std::vector<std::pair<unsigned, unsigned> >& locals) {
Owen Andersond525f662007-12-11 20:12:11 +0000571
572 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
573 SmallPtrSet<DomForestNode*, 4> visited;
574
Owen Andersonddd060f2008-01-10 01:36:43 +0000575 // Code is still in SSA form, so we can use MRI::getVRegDef()
576 MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
577
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000578 LiveIntervals& LI = getAnalysis<LiveIntervals>();
Owen Andersond525f662007-12-11 20:12:11 +0000579 unsigned DestReg = Inst->getOperand(0).getReg();
580
Owen Anderson965b4672007-12-16 04:07:23 +0000581 // DF walk on the DomForest
Owen Andersond525f662007-12-11 20:12:11 +0000582 while (!worklist.empty()) {
583 DomForestNode* DFNode = worklist.back();
584
Owen Andersond525f662007-12-11 20:12:11 +0000585 visited.insert(DFNode);
586
587 bool inserted = false;
Owen Andersond525f662007-12-11 20:12:11 +0000588 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
589 CI != CE; ++CI) {
590 DomForestNode* child = *CI;
Owen Anderson3b489522008-01-21 22:01:01 +0000591
592 // If the current node is live-out of the defining block of one of its
Owen Andersona6b19262008-01-21 22:03:00 +0000593 // children, insert a copy for it. NOTE: The paper actually calls for
594 // a more elaborate heuristic for determining whether to insert copies
595 // for the child or the parent. In the interest of simplicity, we're
596 // just always choosing the parent.
Owen Andersonddd060f2008-01-10 01:36:43 +0000597 if (isLiveOut(DFNode->getReg(),
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000598 MRI.getVRegDef(child->getReg())->getParent(), LI)) {
Owen Andersond525f662007-12-11 20:12:11 +0000599 // Insert copies for parent
600 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
601 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
Owen Andersoned2ffa22007-12-12 01:25:08 +0000602 unsigned SrcReg = DFNode->getReg();
Owen Andersond525f662007-12-11 20:12:11 +0000603 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
604
Owen Andersonefbcebc2007-12-23 15:37:26 +0000605 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
606 UsedByAnother.insert(SrcReg);
607
Owen Andersoned2ffa22007-12-12 01:25:08 +0000608 PHIUnion.erase(SrcReg);
Owen Andersond525f662007-12-11 20:12:11 +0000609 }
610 }
Owen Anderson3b489522008-01-21 22:01:01 +0000611
612 // If a node is live-in to the defining block of one of its children, but
613 // not live-out, then we need to scan that block for local interferences.
Owen Andersonddd060f2008-01-10 01:36:43 +0000614 } else if (isLiveIn(DFNode->getReg(),
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000615 MRI.getVRegDef(child->getReg())->getParent(), LI) ||
Owen Andersonddd060f2008-01-10 01:36:43 +0000616 MRI.getVRegDef(DFNode->getReg())->getParent() ==
617 MRI.getVRegDef(child->getReg())->getParent()) {
Owen Anderson62d67dd2007-12-13 05:53:03 +0000618 // Add (p, c) to possible local interferences
619 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
Owen Andersond525f662007-12-11 20:12:11 +0000620 }
Owen Anderson965b4672007-12-16 04:07:23 +0000621
Owen Anderson4ba08ec2007-12-13 05:43:37 +0000622 if (!visited.count(child)) {
623 worklist.push_back(child);
624 inserted = true;
Owen Andersond525f662007-12-11 20:12:11 +0000625 }
626 }
627
628 if (!inserted) worklist.pop_back();
629 }
630}
631
Owen Andersonefbcebc2007-12-23 15:37:26 +0000632/// ScheduleCopies - Insert copies into predecessor blocks, scheduling
633/// them properly so as to avoid the 'lost copy' and the 'virtual swap'
634/// problems.
635///
636/// Based on "Practical Improvements to the Construction and Destruction
637/// of Static Single Assignment Form" by Briggs, et al.
Owen Andersonf1519e82007-12-24 22:12:23 +0000638void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
639 std::set<unsigned>& pushed) {
Owen Anderson38b42502008-06-04 17:55:58 +0000640 // FIXME: This function needs to update LiveIntervals
Owen Andersonefbcebc2007-12-23 15:37:26 +0000641 std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
642
643 std::map<unsigned, unsigned> worklist;
644 std::map<unsigned, unsigned> map;
645
646 // Setup worklist of initial copies
647 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
648 E = copy_set.end(); I != E; ) {
649 map.insert(std::make_pair(I->first, I->first));
650 map.insert(std::make_pair(I->second, I->second));
651
Owen Andersonc7c00362008-03-29 01:58:47 +0000652 if (!UsedByAnother.count(I->second)) {
Owen Andersonefbcebc2007-12-23 15:37:26 +0000653 worklist.insert(*I);
654
655 // Avoid iterator invalidation
656 unsigned first = I->first;
657 ++I;
658 copy_set.erase(first);
659 } else {
660 ++I;
661 }
662 }
663
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000664 LiveIntervals& LI = getAnalysis<LiveIntervals>();
Owen Anderson0d893b42008-01-08 05:16:15 +0000665 MachineFunction* MF = MBB->getParent();
Owen Andersonddd060f2008-01-10 01:36:43 +0000666 MachineRegisterInfo& MRI = MF->getRegInfo();
Owen Anderson0d893b42008-01-08 05:16:15 +0000667 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Owen Andersonefbcebc2007-12-23 15:37:26 +0000668
Owen Anderson38b42502008-06-04 17:55:58 +0000669 SmallVector<std::pair<unsigned, MachineInstr*>, 4> InsertedPHIDests;
670
Owen Andersonefbcebc2007-12-23 15:37:26 +0000671 // Iterate over the worklist, inserting copies
672 while (!worklist.empty() || !copy_set.empty()) {
673 while (!worklist.empty()) {
674 std::pair<unsigned, unsigned> curr = *worklist.begin();
675 worklist.erase(curr.first);
676
Owen Anderson0d893b42008-01-08 05:16:15 +0000677 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
678
Owen Andersoneb37ecc2008-03-10 07:22:36 +0000679 if (isLiveOut(curr.second, MBB, LI)) {
Owen Anderson0d893b42008-01-08 05:16:15 +0000680 // Create a temporary
681 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
682
683 // Insert copy from curr.second to a temporary at
684 // the Phi defining curr.second
Owen Andersonddd060f2008-01-10 01:36:43 +0000685 MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
686 TII->copyRegToReg(*PI->getParent(), PI, t,
Owen Anderson0d893b42008-01-08 05:16:15 +0000687 curr.second, RC, RC);
688
Owen Andersonefbcebc2007-12-23 15:37:26 +0000689 // Push temporary on Stacks
Owen Anderson0d893b42008-01-08 05:16:15 +0000690 Stacks[curr.second].push_back(t);
691
692 // Insert curr.second in pushed
693 pushed.insert(curr.second);
Owen Andersonefbcebc2007-12-23 15:37:26 +0000694 }
695
696 // Insert copy from map[curr.first] to curr.second
Owen Anderson9c2efa82008-01-10 00:01:41 +0000697 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
Owen Anderson0d893b42008-01-08 05:16:15 +0000698 map[curr.first], RC, RC);
Owen Andersonefbcebc2007-12-23 15:37:26 +0000699 map[curr.first] = curr.second;
700
Owen Anderson38b42502008-06-04 17:55:58 +0000701 // Push this copy onto InsertedPHICopies so we can
702 // update LiveIntervals with it.
703 MachineBasicBlock::iterator MI = MBB->getFirstTerminator();
704 InsertedPHIDests.push_back(std::make_pair(curr.second, --MI));
705
Owen Andersonefbcebc2007-12-23 15:37:26 +0000706 // If curr.first is a destination in copy_set...
707 for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
708 E = copy_set.end(); I != E; )
709 if (curr.first == I->second) {
710 std::pair<unsigned, unsigned> temp = *I;
711
712 // Avoid iterator invalidation
713 ++I;
714 copy_set.erase(temp.first);
715 worklist.insert(temp);
716
717 break;
718 } else {
719 ++I;
720 }
721 }
722
723 if (!copy_set.empty()) {
724 std::pair<unsigned, unsigned> curr = *copy_set.begin();
725 copy_set.erase(curr.first);
726
Owen Anderson0d893b42008-01-08 05:16:15 +0000727 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
728
Owen Andersonefbcebc2007-12-23 15:37:26 +0000729 // Insert a copy from dest to a new temporary t at the end of b
Owen Anderson0d893b42008-01-08 05:16:15 +0000730 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
Owen Anderson9c2efa82008-01-10 00:01:41 +0000731 TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
Owen Anderson0d893b42008-01-08 05:16:15 +0000732 curr.second, RC, RC);
733 map[curr.second] = t;
Owen Andersonefbcebc2007-12-23 15:37:26 +0000734
735 worklist.insert(curr);
736 }
737 }
Owen Anderson38b42502008-06-04 17:55:58 +0000738
739 // Renumber the instructions so that we can perform the index computations
740 // needed to create new live intervals.
741 LI.computeNumbering();
742
743 // For copies that we inserted at the ends of predecessors, we construct
744 // live intervals. This is pretty easy, since we know that the destination
745 // register cannot have be in live at that point previously. We just have
746 // to make sure that, for registers that serve as inputs to more than one
747 // PHI, we don't create multiple overlapping live intervals.
748 std::set<unsigned> RegHandled;
749 for (SmallVector<std::pair<unsigned, MachineInstr*>, 4>::iterator I =
Owen Andersona9efb262008-06-05 17:22:53 +0000750 InsertedPHIDests.begin(), E = InsertedPHIDests.end(); I != E; ++I)
Owen Andersona279a892008-07-25 23:38:08 +0000751 if (RegHandled.insert(I->first).second)
Owen Andersona9efb262008-06-05 17:22:53 +0000752 LI.addLiveRangeToEndOfBlock(I->first, I->second);
Owen Andersonefbcebc2007-12-23 15:37:26 +0000753}
754
Owen Andersonf1519e82007-12-24 22:12:23 +0000755/// InsertCopies - insert copies into MBB and all of its successors
Owen Anderson719fef62008-01-09 10:32:30 +0000756void StrongPHIElimination::InsertCopies(MachineBasicBlock* MBB,
Owen Andersone46611e2008-03-24 04:11:27 +0000757 SmallPtrSet<MachineBasicBlock*, 16>& visited) {
Owen Anderson719fef62008-01-09 10:32:30 +0000758 visited.insert(MBB);
759
Owen Andersonf1519e82007-12-24 22:12:23 +0000760 std::set<unsigned> pushed;
761
762 // Rewrite register uses from Stacks
763 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
764 I != E; ++I)
765 for (unsigned i = 0; i < I->getNumOperands(); ++i)
766 if (I->getOperand(i).isRegister() &&
767 Stacks[I->getOperand(i).getReg()].size()) {
768 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
769 }
770
771 // Schedule the copies for this block
772 ScheduleCopies(MBB, pushed);
773
774 // Recur to our successors
775 for (GraphTraits<MachineBasicBlock*>::ChildIteratorType I =
776 GraphTraits<MachineBasicBlock*>::child_begin(MBB), E =
777 GraphTraits<MachineBasicBlock*>::child_end(MBB); I != E; ++I)
Owen Anderson719fef62008-01-09 10:32:30 +0000778 if (!visited.count(*I))
779 InsertCopies(*I, visited);
Owen Andersonf1519e82007-12-24 22:12:23 +0000780
781 // As we exit this block, pop the names we pushed while processing it
782 for (std::set<unsigned>::iterator I = pushed.begin(),
783 E = pushed.end(); I != E; ++I)
784 Stacks[*I].pop_back();
785}
786
Owen Anderson00316712008-03-12 03:13:29 +0000787void StrongPHIElimination::mergeLiveIntervals(unsigned primary,
Owen Andersone46611e2008-03-24 04:11:27 +0000788 unsigned secondary,
Owen Andersonc12417e2008-07-24 17:12:16 +0000789 MachineBasicBlock* pred) {
Owen Anderson755ebab2008-03-17 06:08:26 +0000790
791 LiveIntervals& LI = getAnalysis<LiveIntervals>();
792 LiveInterval& LHS = LI.getOrCreateInterval(primary);
793 LiveInterval& RHS = LI.getOrCreateInterval(secondary);
794
Owen Andersona9efb262008-06-05 17:22:53 +0000795 LI.computeNumbering();
Owen Andersonc12417e2008-07-24 17:12:16 +0000796 const LiveRange* RangeMergingIn =
797 RHS.getLiveRangeContaining(LI.getMBBEndIdx(pred));
Owen Anderson83ea1f82008-07-29 21:17:08 +0000798 VNInfo* RHSVN = RangeMergingIn->valno;
Owen Andersonc12417e2008-07-24 17:12:16 +0000799 VNInfo* NewVN = LHS.getNextValue(RangeMergingIn->valno->def,
800 RangeMergingIn->valno->copy,
801 LI.getVNInfoAllocator());
Owen Andersonb9fb8d12008-07-30 00:21:16 +0000802
803 // If we discover that a live range was defined by a two-addr
804 // instruction, we need to merge over the input as well, even if
805 // it has a different VNInfo.
806 SmallPtrSet<VNInfo*, 4> MergedVNs;
807 MergedVNs.insert(RHSVN);
808
809 DenseMap<VNInfo*, VNInfo*> VNMap;
810 VNMap.insert(std::make_pair(RangeMergingIn->valno, NewVN));
811
Owen Andersond723f722008-07-30 18:27:35 +0000812 // Find all VNs that are the inputs to two-address instructiosn
813 // chaining upwards from the VN we're trying to merge.
814 bool addedVN = true;
815 while (addedVN) {
816 addedVN = false;
817 unsigned defIndex = RHSVN->def;
818
819 if (defIndex != ~0U) {
820 MachineInstr* instr = LI.getInstructionFromIndex(defIndex);
Owen Anderson83ea1f82008-07-29 21:17:08 +0000821
Owen Andersond723f722008-07-30 18:27:35 +0000822 for (unsigned i = 0; i < instr->getNumOperands(); ++i) {
823 if (instr->getOperand(i).isReg() &&
824 instr->getOperand(i).getReg() == secondary)
825 if (instr->isRegReDefinedByTwoAddr(secondary, i)) {
826 RHSVN = RHS.getLiveRangeContaining(defIndex-1)->valno;
827 addedVN = true;
828
829 VNInfo* NextVN = LHS.getNextValue(RHSVN->def,
830 RHSVN->copy,
831 LI.getVNInfoAllocator());
832 VNMap.insert(std::make_pair(RHSVN, NextVN));
833
834 break;
835 }
836 }
837 }
838 }
839
840 // Merge VNs from RHS into LHS using the mapping we computed above.
841 for (DenseMap<VNInfo*, VNInfo*>::iterator VI = VNMap.begin(),
842 VE = VNMap.end(); VI != VE; ++VI) {
843 LHS.MergeValueInAsValue(RHS, VI->first, VI->second);
844 RHS.removeValNo(VI->first);
Owen Andersonb9fb8d12008-07-30 00:21:16 +0000845 }
Owen Anderson55c64352008-07-25 21:08:41 +0000846
Owen Anderson83ea1f82008-07-29 21:17:08 +0000847 if (RHS.begin() == RHS.end())
Owen Anderson55c64352008-07-25 21:08:41 +0000848 LI.removeInterval(RHS.reg);
Owen Anderson00316712008-03-12 03:13:29 +0000849}
850
Owen Andersona4ad2e72007-11-06 04:49:43 +0000851bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
Owen Andersonc7c00362008-03-29 01:58:47 +0000852 LiveIntervals& LI = getAnalysis<LiveIntervals>();
853
Owen Andersonefbcebc2007-12-23 15:37:26 +0000854 // Compute DFS numbers of each block
Owen Andersona4ad2e72007-11-06 04:49:43 +0000855 computeDFS(Fn);
856
Owen Andersonefbcebc2007-12-23 15:37:26 +0000857 // Determine which phi node operands need copies
Owen Anderson60a877d2007-11-07 05:17:15 +0000858 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
859 if (!I->empty() &&
860 I->begin()->getOpcode() == TargetInstrInfo::PHI)
861 processBlock(I);
Owen Andersona4ad2e72007-11-06 04:49:43 +0000862
Owen Anderson883771f2008-08-06 22:08:58 +0000863 // Break interferences where two different phis want to coalesce
864 // in the same register.
865 std::set<unsigned> seen;
866 typedef std::map<unsigned, std::map<unsigned, MachineBasicBlock*> >
867 RenameSetType;
868 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
869 I != E; ++I) {
870 for (std::map<unsigned, MachineBasicBlock*>::iterator
871 OI = I->second.begin(), OE = I->second.end(); OI != OE; ) {
872 if (!seen.count(OI->first)) {
873 seen.insert(OI->first);
874 ++OI;
875 } else {
876 Waiting[OI->second].insert(std::make_pair(OI->first, I->first));
877 unsigned reg = OI->first;
878 ++OI;
879 I->second.erase(reg);
880 }
881 }
882 }
883
Owen Andersonefbcebc2007-12-23 15:37:26 +0000884 // Insert copies
Owen Andersona9efb262008-06-05 17:22:53 +0000885 // FIXME: This process should probably preserve LiveIntervals
Owen Andersone46611e2008-03-24 04:11:27 +0000886 SmallPtrSet<MachineBasicBlock*, 16> visited;
Owen Anderson719fef62008-01-09 10:32:30 +0000887 InsertCopies(Fn.begin(), visited);
Owen Andersonefbcebc2007-12-23 15:37:26 +0000888
Owen Anderson0c5714b2008-01-08 21:54:52 +0000889 // Perform renaming
Owen Anderson0c5714b2008-01-08 21:54:52 +0000890 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
891 I != E; ++I)
Owen Anderson883771f2008-08-06 22:08:58 +0000892 while (I->second.size()) {
893 std::map<unsigned, MachineBasicBlock*>::iterator SI = I->second.begin();
894
895 if (SI->first != I->first) {
896 mergeLiveIntervals(I->first, SI->first, SI->second);
897 Fn.getRegInfo().replaceRegWith(SI->first, I->first);
898
899 if (RenameSets.count(SI->first)) {
900 I->second.insert(RenameSets[SI->first].begin(),
901 RenameSets[SI->first].end());
902 RenameSets.erase(SI->first);
903 }
904
905
906 }
907
908 I->second.erase(SI->first);
Owen Anderson00316712008-03-12 03:13:29 +0000909 }
Owen Anderson0c5714b2008-01-08 21:54:52 +0000910
911 // FIXME: Insert last-minute copies
912
913 // Remove PHIs
Owen Anderson97ca75e2008-01-22 23:58:54 +0000914 std::vector<MachineInstr*> phis;
915 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
Owen Anderson0c5714b2008-01-08 21:54:52 +0000916 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
917 BI != BE; ++BI)
918 if (BI->getOpcode() == TargetInstrInfo::PHI)
Owen Anderson97ca75e2008-01-22 23:58:54 +0000919 phis.push_back(BI);
920 }
921
922 for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
Owen Andersonc7c00362008-03-29 01:58:47 +0000923 I != E; ) {
924 MachineInstr* PInstr = *(I++);
925
Owen Anderson71ac0be2008-08-05 21:18:51 +0000926 // If this is a dead PHI node, then remove it from LiveIntervals.
927 unsigned DestReg = PInstr->getOperand(0).getReg();
928 LiveInterval& PI = LI.getInterval(DestReg);
929 if (PInstr->registerDefIsDead(DestReg)) {
930 if (PI.containsOneValue()) {
931 LI.removeInterval(DestReg);
932 } else {
933 unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
934 PI.removeRange(*PI.getLiveRangeContaining(idx), true);
935 }
936 } else {
Owen Andersone7b82052008-08-05 20:51:26 +0000937 // Trim live intervals of input registers. They are no longer live into
Owen Anderson9b491202008-08-06 18:36:17 +0000938 // this block if they died after the PHI. If they lived after it, don't
939 // trim them because they might have other legitimate uses.
Owen Andersone7b82052008-08-05 20:51:26 +0000940 for (unsigned i = 1; i < PInstr->getNumOperands(); i += 2) {
941 unsigned reg = PInstr->getOperand(i).getReg();
Owen Anderson883771f2008-08-06 22:08:58 +0000942
Owen Andersone7b82052008-08-05 20:51:26 +0000943 MachineBasicBlock* MBB = PInstr->getOperand(i+1).getMBB();
944 LiveInterval& InputI = LI.getInterval(reg);
945 if (MBB != PInstr->getParent() &&
Owen Anderson9b491202008-08-06 18:36:17 +0000946 InputI.liveAt(LI.getMBBStartIdx(PInstr->getParent())) &&
947 InputI.expiredAt(LI.getInstructionIndex(PInstr) +
948 LiveIntervals::InstrSlots::NUM))
Owen Andersone7b82052008-08-05 20:51:26 +0000949 InputI.removeRange(LI.getMBBStartIdx(PInstr->getParent()),
950 LI.getInstructionIndex(PInstr),
951 true);
Owen Andersond382f8a2008-03-26 03:03:23 +0000952 }
Owen Andersone7b82052008-08-05 20:51:26 +0000953
Owen Anderson71ac0be2008-08-05 21:18:51 +0000954 // If the PHI is not dead, then the valno defined by the PHI
955 // now has an unknown def.
956 unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
957 const LiveRange* PLR = PI.getLiveRangeContaining(idx);
958 PLR->valno->def = ~0U;
959 LiveRange R (LI.getMBBStartIdx(PInstr->getParent()),
960 PLR->start, PLR->valno);
961 PI.addRange(R);
Owen Andersond382f8a2008-03-26 03:03:23 +0000962 }
Owen Anderson59df8782008-04-02 02:12:45 +0000963
Owen Andersonc7c00362008-03-29 01:58:47 +0000964 LI.RemoveMachineInstrFromMaps(PInstr);
965 PInstr->eraseFromParent();
Owen Andersone46611e2008-03-24 04:11:27 +0000966 }
Owen Andersoncae8d8d2007-12-22 04:59:10 +0000967
Owen Anderson3947e4d2008-05-30 18:38:26 +0000968 LI.computeNumbering();
969
Owen Andersonc7c00362008-03-29 01:58:47 +0000970 return true;
Owen Andersona4ad2e72007-11-06 04:49:43 +0000971}