Fix MachineSink to be able to sink instructions that use physical registers
[oota-llvm.git] / lib / CodeGen / MachineSink.cpp
1 //===-- MachineSink.cpp - Sinking for machine instructions ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass moves instructions into successor blocks, when possible, so that
11 // they aren't executed on paths where their results aren't needed.
12 //
13 // This pass is not intended to be a replacement or a complete alternative
14 // for an LLVM-IR-level sinking pass. It is only designed to sink simple
15 // constructs that are not exposed before lowering and instruction selection.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "machine-sink"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/MachineDominators.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm;
31
32 STATISTIC(NumSunk, "Number of machine instructions sunk");
33
34 namespace {
35   class VISIBILITY_HIDDEN MachineSinking : public MachineFunctionPass {
36     const TargetMachine   *TM;
37     const TargetInstrInfo *TII;
38     const TargetRegisterInfo *TRI;
39     MachineFunction       *CurMF; // Current MachineFunction
40     MachineRegisterInfo  *RegInfo; // Machine register information
41     MachineDominatorTree *DT;   // Machine dominator tree
42
43   public:
44     static char ID; // Pass identification
45     MachineSinking() : MachineFunctionPass(&ID) {}
46     
47     virtual bool runOnMachineFunction(MachineFunction &MF);
48     
49     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
50       AU.setPreservesCFG();
51       MachineFunctionPass::getAnalysisUsage(AU);
52       AU.addRequired<MachineDominatorTree>();
53       AU.addPreserved<MachineDominatorTree>();
54     }
55   private:
56     bool ProcessBlock(MachineBasicBlock &MBB);
57     bool SinkInstruction(MachineInstr *MI, bool &SawStore);
58     bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB) const;
59   };
60 } // end anonymous namespace
61   
62 char MachineSinking::ID = 0;
63 static RegisterPass<MachineSinking>
64 X("machine-sink", "Machine code sinking");
65
66 FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
67
68 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
69 /// occur in blocks dominated by the specified block.
70 bool MachineSinking::AllUsesDominatedByBlock(unsigned Reg, 
71                                              MachineBasicBlock *MBB) const {
72   assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
73          "Only makes sense for vregs");
74   for (MachineRegisterInfo::use_iterator I = RegInfo->use_begin(Reg),
75        E = RegInfo->use_end(); I != E; ++I) {
76     // Determine the block of the use.
77     MachineInstr *UseInst = &*I;
78     MachineBasicBlock *UseBlock = UseInst->getParent();
79     if (UseInst->getOpcode() == TargetInstrInfo::PHI) {
80       // PHI nodes use the operand in the predecessor block, not the block with
81       // the PHI.
82       UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
83     }
84     // Check that it dominates.
85     if (!DT->dominates(MBB, UseBlock))
86       return false;
87   }
88   return true;
89 }
90
91
92
93 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
94   DEBUG(errs() << "******** Machine Sinking ********\n");
95   
96   CurMF = &MF;
97   TM = &CurMF->getTarget();
98   TII = TM->getInstrInfo();
99   TRI = TM->getRegisterInfo();
100   RegInfo = &CurMF->getRegInfo();
101   DT = &getAnalysis<MachineDominatorTree>();
102
103   bool EverMadeChange = false;
104   
105   while (1) {
106     bool MadeChange = false;
107
108     // Process all basic blocks.
109     for (MachineFunction::iterator I = CurMF->begin(), E = CurMF->end(); 
110          I != E; ++I)
111       MadeChange |= ProcessBlock(*I);
112     
113     // If this iteration over the code changed anything, keep iterating.
114     if (!MadeChange) break;
115     EverMadeChange = true;
116   } 
117   return EverMadeChange;
118 }
119
120 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
121   // Can't sink anything out of a block that has less than two successors.
122   if (MBB.succ_size() <= 1 || MBB.empty()) return false;
123
124   bool MadeChange = false;
125
126   // Walk the basic block bottom-up.  Remember if we saw a store.
127   MachineBasicBlock::iterator I = MBB.end();
128   --I;
129   bool ProcessedBegin, SawStore = false;
130   do {
131     MachineInstr *MI = I;  // The instruction to sink.
132     
133     // Predecrement I (if it's not begin) so that it isn't invalidated by
134     // sinking.
135     ProcessedBegin = I == MBB.begin();
136     if (!ProcessedBegin)
137       --I;
138     
139     if (SinkInstruction(MI, SawStore))
140       ++NumSunk, MadeChange = true;
141     
142     // If we just processed the first instruction in the block, we're done.
143   } while (!ProcessedBegin);
144   
145   return MadeChange;
146 }
147
148 /// SinkInstruction - Determine whether it is safe to sink the specified machine
149 /// instruction out of its current block into a successor.
150 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
151   // Check if it's safe to move the instruction.
152   if (!MI->isSafeToMove(TII, SawStore))
153     return false;
154   
155   // FIXME: This should include support for sinking instructions within the
156   // block they are currently in to shorten the live ranges.  We often get
157   // instructions sunk into the top of a large block, but it would be better to
158   // also sink them down before their first use in the block.  This xform has to
159   // be careful not to *increase* register pressure though, e.g. sinking
160   // "x = y + z" down if it kills y and z would increase the live ranges of y
161   // and z and only shrink the live range of x.
162   
163   // Loop over all the operands of the specified instruction.  If there is
164   // anything we can't handle, bail out.
165   MachineBasicBlock *ParentBlock = MI->getParent();
166   
167   // SuccToSinkTo - This is the successor to sink this instruction to, once we
168   // decide.
169   MachineBasicBlock *SuccToSinkTo = 0;
170   
171   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
172     const MachineOperand &MO = MI->getOperand(i);
173     if (!MO.isReg()) continue;  // Ignore non-register operands.
174     
175     unsigned Reg = MO.getReg();
176     if (Reg == 0) continue;
177     
178     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
179       // If this is a physical register use, we can't move it.  If it is a def,
180       // we can move it, but only if the def is dead.
181       if (MO.isUse()) {
182         // If the physreg has no defs anywhere, it's just an ambient register
183         // and we can freely move its uses.
184         if (!RegInfo->def_empty(Reg))
185           return false;
186         // Check for a def among the register's aliases too.
187         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias)
188           if (!RegInfo->def_empty(*Alias))
189             return false;
190       } else if (!MO.isDead()) {
191         // A def that isn't dead. We can't move it.
192         return false;
193       }
194     } else {
195       // Virtual register uses are always safe to sink.
196       if (MO.isUse()) continue;
197
198       // If it's not safe to move defs of the register class, then abort.
199       if (!TII->isSafeToMoveRegClassDefs(RegInfo->getRegClass(Reg)))
200         return false;
201       
202       // FIXME: This picks a successor to sink into based on having one
203       // successor that dominates all the uses.  However, there are cases where
204       // sinking can happen but where the sink point isn't a successor.  For
205       // example:
206       //   x = computation
207       //   if () {} else {}
208       //   use x
209       // the instruction could be sunk over the whole diamond for the 
210       // if/then/else (or loop, etc), allowing it to be sunk into other blocks
211       // after that.
212       
213       // Virtual register defs can only be sunk if all their uses are in blocks
214       // dominated by one of the successors.
215       if (SuccToSinkTo) {
216         // If a previous operand picked a block to sink to, then this operand
217         // must be sinkable to the same block.
218         if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo)) 
219           return false;
220         continue;
221       }
222       
223       // Otherwise, we should look at all the successors and decide which one
224       // we should sink to.
225       for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
226            E = ParentBlock->succ_end(); SI != E; ++SI) {
227         if (AllUsesDominatedByBlock(Reg, *SI)) {
228           SuccToSinkTo = *SI;
229           break;
230         }
231       }
232       
233       // If we couldn't find a block to sink to, ignore this instruction.
234       if (SuccToSinkTo == 0)
235         return false;
236     }
237   }
238   
239   // If there are no outputs, it must have side-effects.
240   if (SuccToSinkTo == 0)
241     return false;
242
243   // It's not safe to sink instructions to EH landing pad. Control flow into
244   // landing pad is implicitly defined.
245   if (SuccToSinkTo->isLandingPad())
246     return false;
247   
248   // If is not possible to sink an instruction into its own block.  This can
249   // happen with loops.
250   if (MI->getParent() == SuccToSinkTo)
251     return false;
252   
253   DEBUG(errs() << "Sink instr " << *MI);
254   DEBUG(errs() << "to block " << *SuccToSinkTo);
255   
256   // If the block has multiple predecessors, this would introduce computation on
257   // a path that it doesn't already exist.  We could split the critical edge,
258   // but for now we just punt.
259   // FIXME: Split critical edges if not backedges.
260   if (SuccToSinkTo->pred_size() > 1) {
261     DEBUG(errs() << " *** PUNTING: Critical edge found\n");
262     return false;
263   }
264   
265   // Determine where to insert into.  Skip phi nodes.
266   MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
267   while (InsertPos != SuccToSinkTo->end() && 
268          InsertPos->getOpcode() == TargetInstrInfo::PHI)
269     ++InsertPos;
270   
271   // Move the instruction.
272   SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
273                        ++MachineBasicBlock::iterator(MI));
274   return true;
275 }