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