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