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