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