Switch the MachineOperand accessors back to the short names like
[oota-llvm.git] / lib / CodeGen / MachineLICM.cpp
1 //===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
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 performs loop invariant code motion on machine instructions. We
11 // attempt to remove as much code from the body of a loop as possible.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "machine-licm"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/CodeGen/MachineDominators.h"
18 #include "llvm/CodeGen/MachineLoopInfo.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/Debug.h"
28
29 using namespace llvm;
30
31 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
32
33 namespace {
34   class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
35     const TargetMachine   *TM;
36     const TargetInstrInfo *TII;
37
38     // Various analyses that we use...
39     MachineLoopInfo      *LI;      // Current MachineLoopInfo
40     MachineDominatorTree *DT;      // Machine dominator tree for the cur loop
41     MachineRegisterInfo  *RegInfo; // Machine register information
42
43     // State that is updated as we process loops
44     bool         Changed;          // True if a loop is changed.
45     MachineLoop *CurLoop;          // The current loop we are working on.
46   public:
47     static char ID; // Pass identification, replacement for typeid
48     MachineLICM() : MachineFunctionPass(&ID) {}
49
50     virtual bool runOnMachineFunction(MachineFunction &MF);
51
52     // FIXME: Loop preheaders?
53     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54       AU.setPreservesCFG();
55       AU.addRequired<MachineLoopInfo>();
56       AU.addRequired<MachineDominatorTree>();
57       AU.addPreserved<MachineLoopInfo>();
58       AU.addPreserved<MachineDominatorTree>();
59       MachineFunctionPass::getAnalysisUsage(AU);
60     }
61   private:
62     /// VisitAllLoops - Visit all of the loops in depth first order and try to
63     /// hoist invariant instructions from them.
64     /// 
65     void VisitAllLoops(MachineLoop *L) {
66       const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
67
68       for (MachineLoop::iterator
69              I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
70         MachineLoop *ML = *I;
71
72         // Traverse the body of the loop in depth first order on the dominator
73         // tree so that we are guaranteed to see definitions before we see uses.
74         VisitAllLoops(ML);
75         HoistRegion(DT->getNode(ML->getHeader()));
76       }
77
78       HoistRegion(DT->getNode(L->getHeader()));
79     }
80
81     /// IsInSubLoop - A little predicate that returns true if the specified
82     /// basic block is in a subloop of the current one, not the current one
83     /// itself.
84     ///
85     bool IsInSubLoop(MachineBasicBlock *BB) {
86       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
87       return LI->getLoopFor(BB) != CurLoop;
88     }
89
90     /// IsLoopInvariantInst - Returns true if the instruction is loop
91     /// invariant. I.e., all virtual register operands are defined outside of
92     /// the loop, physical registers aren't accessed (explicitly or implicitly),
93     /// and the instruction is hoistable.
94     /// 
95     bool IsLoopInvariantInst(MachineInstr &I);
96
97     /// FindPredecessors - Get all of the predecessors of the loop that are not
98     /// back-edges.
99     /// 
100     void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
101       const MachineBasicBlock *Header = CurLoop->getHeader();
102
103       for (MachineBasicBlock::const_pred_iterator
104              I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
105         if (!CurLoop->contains(*I))
106           Preds.push_back(*I);
107     }
108
109     /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
110     /// the predecessor basic block (but before the terminator instructions).
111     /// 
112     void MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
113                               MachineBasicBlock *FromMBB,
114                               MachineInstr *MI);
115
116     /// HoistRegion - Walk the specified region of the CFG (defined by all
117     /// blocks dominated by the specified block, and that are in the current
118     /// loop) in depth first order w.r.t the DominatorTree. This allows us to
119     /// visit definitions before uses, allowing us to hoist a loop body in one
120     /// pass without iteration.
121     ///
122     void HoistRegion(MachineDomTreeNode *N);
123
124     /// Hoist - When an instruction is found to only use loop invariant operands
125     /// that is safe to hoist, this instruction is called to do the dirty work.
126     ///
127     void Hoist(MachineInstr &MI);
128   };
129 } // end anonymous namespace
130
131 char MachineLICM::ID = 0;
132 static RegisterPass<MachineLICM>
133 X("machinelicm", "Machine Loop Invariant Code Motion");
134
135 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
136
137 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
138 /// is not preserved so it is not a good idea to run LICM multiple times on one
139 /// loop.
140 ///
141 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
142   DOUT << "******** Machine LICM ********\n";
143
144   Changed = false;
145   TM = &MF.getTarget();
146   TII = TM->getInstrInfo();
147   RegInfo = &MF.getRegInfo();
148
149   // Get our Loop information...
150   LI = &getAnalysis<MachineLoopInfo>();
151   DT = &getAnalysis<MachineDominatorTree>();
152
153   for (MachineLoopInfo::iterator
154          I = LI->begin(), E = LI->end(); I != E; ++I) {
155     CurLoop = *I;
156
157     // Visit all of the instructions of the loop. We want to visit the subloops
158     // first, though, so that we can hoist their invariants first into their
159     // containing loop before we process that loop.
160     VisitAllLoops(CurLoop);
161   }
162
163   return Changed;
164 }
165
166 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
167 /// dominated by the specified block, and that are in the current loop) in depth
168 /// first order w.r.t the DominatorTree. This allows us to visit definitions
169 /// before uses, allowing us to hoist a loop body in one pass without iteration.
170 ///
171 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
172   assert(N != 0 && "Null dominator tree node?");
173   MachineBasicBlock *BB = N->getBlock();
174
175   // If this subregion is not in the top level loop at all, exit.
176   if (!CurLoop->contains(BB)) return;
177
178   // Only need to process the contents of this block if it is not part of a
179   // subloop (which would already have been processed).
180   if (!IsInSubLoop(BB))
181     for (MachineBasicBlock::iterator
182            I = BB->begin(), E = BB->end(); I != E; ) {
183       MachineInstr &MI = *I++;
184
185       // Try hoisting the instruction out of the loop. We can only do this if
186       // all of the operands of the instruction are loop invariant and if it is
187       // safe to hoist the instruction.
188       Hoist(MI);
189     }
190
191   const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
192
193   for (unsigned I = 0, E = Children.size(); I != E; ++I)
194     HoistRegion(Children[I]);
195 }
196
197 /// IsLoopInvariantInst - Returns true if the instruction is loop
198 /// invariant. I.e., all virtual register operands are defined outside of the
199 /// loop, physical registers aren't accessed explicitly, and there are no side
200 /// effects that aren't captured by the operands or other flags.
201 /// 
202 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
203   const TargetInstrDesc &TID = I.getDesc();
204   
205   // Ignore stuff that we obviously can't hoist.
206   if (TID.mayStore() || TID.isCall() || TID.isReturn() || TID.isBranch() ||
207       TID.hasUnmodeledSideEffects())
208     return false;
209   
210   if (TID.mayLoad()) {
211     // Okay, this instruction does a load. As a refinement, we allow the target
212     // to decide whether the loaded value is actually a constant. If so, we can
213     // actually use it as a load.
214     if (!TII->isInvariantLoad(&I))
215       // FIXME: we should be able to sink loads with no other side effects if
216       // there is nothing that can change memory from here until the end of
217       // block. This is a trivial form of alias analysis.
218       return false;
219   }
220
221   DEBUG({
222       DOUT << "--- Checking if we can hoist " << I;
223       if (I.getDesc().getImplicitUses()) {
224         DOUT << "  * Instruction has implicit uses:\n";
225
226         const TargetRegisterInfo *TRI = TM->getRegisterInfo();
227         for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
228              *ImpUses; ++ImpUses)
229           DOUT << "      -> " << TRI->getName(*ImpUses) << "\n";
230       }
231
232       if (I.getDesc().getImplicitDefs()) {
233         DOUT << "  * Instruction has implicit defines:\n";
234
235         const TargetRegisterInfo *TRI = TM->getRegisterInfo();
236         for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
237              *ImpDefs; ++ImpDefs)
238           DOUT << "      -> " << TRI->getName(*ImpDefs) << "\n";
239       }
240     });
241
242   if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
243     DOUT << "Cannot hoist with implicit defines or uses\n";
244     return false;
245   }
246
247   // The instruction is loop invariant if all of its operands are.
248   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
249     const MachineOperand &MO = I.getOperand(i);
250
251     if (!MO.isReg())
252       continue;
253
254     if (MO.isDef() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
255       // Don't hoist an instruction that defines a physical register.
256       return false;
257
258     if (!MO.isUse())
259       continue;
260
261     unsigned Reg = MO.getReg();
262     if (Reg == 0) continue;
263
264     // Don't hoist instructions that access physical registers.
265     if (TargetRegisterInfo::isPhysicalRegister(Reg))
266       return false;
267
268     assert(RegInfo->getVRegDef(Reg) &&
269            "Machine instr not mapped for this vreg?!");
270
271     // If the loop contains the definition of an operand, then the instruction
272     // isn't loop invariant.
273     if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
274       return false;
275   }
276
277   // If we got this far, the instruction is loop invariant!
278   return true;
279 }
280
281 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of the
282 /// predecessor basic block (but before the terminator instructions).
283 /// 
284 void MachineLICM::MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
285                                        MachineBasicBlock *FromMBB,
286                                        MachineInstr *MI) {
287   DEBUG({
288       DOUT << "Hoisting " << *MI;
289       if (ToMBB->getBasicBlock())
290         DOUT << " to MachineBasicBlock "
291              << ToMBB->getBasicBlock()->getName();
292       if (FromMBB->getBasicBlock())
293         DOUT << " from MachineBasicBlock "
294              << FromMBB->getBasicBlock()->getName();
295       DOUT << "\n";
296     });
297
298   MachineBasicBlock::iterator WhereIter = ToMBB->getFirstTerminator();
299   MachineBasicBlock::iterator To, From = FromMBB->begin();
300
301   while (&*From != MI)
302     ++From;
303
304   assert(From != FromMBB->end() && "Didn't find instr in BB!");
305
306   To = From;
307   ToMBB->splice(WhereIter, FromMBB, From, ++To);
308   ++NumHoisted;
309 }
310
311 /// Hoist - When an instruction is found to use only loop invariant operands
312 /// that are safe to hoist, this instruction is called to do the dirty work.
313 ///
314 void MachineLICM::Hoist(MachineInstr &MI) {
315   if (!IsLoopInvariantInst(MI)) return;
316
317   std::vector<MachineBasicBlock*> Preds;
318
319   // Non-back-edge predecessors.
320   FindPredecessors(Preds);
321
322   // Either we don't have any predecessors(?!) or we have more than one, which
323   // is forbidden.
324   if (Preds.empty() || Preds.size() != 1) return;
325
326   // Check that the predecessor is qualified to take the hoisted instruction.
327   // I.e., there is only one edge from the predecessor, and it's to the loop
328   // header.
329   MachineBasicBlock *MBB = Preds.front();
330
331   // FIXME: We are assuming at first that the basic block coming into this loop
332   // has only one successor. This isn't the case in general because we haven't
333   // broken critical edges or added preheaders.
334   if (MBB->succ_size() != 1) return;
335   assert(*MBB->succ_begin() == CurLoop->getHeader() &&
336          "The predecessor doesn't feed directly into the loop header!");
337
338   // Now move the instructions to the predecessor.
339   MoveInstToEndOfBlock(MBB, MI.getParent(), &MI);
340   Changed = true;
341 }