This is to fix the bug in IntrinsicLowering.cpp,
[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 // This pass does not attempt to throttle itself to limit register pressure.
14 // The register allocation phases are expected to perform rematerialization
15 // to recover when register pressure is high.
16 //
17 // This pass is not intended to be a replacement or a complete alternative
18 // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
19 // constructs that are not exposed before lowering and instruction selection.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #define DEBUG_TYPE "machine-licm"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
35
36 using namespace llvm;
37
38 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
39
40 namespace {
41   class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
42     const TargetMachine   *TM;
43     const TargetInstrInfo *TII;
44
45     // Various analyses that we use...
46     MachineLoopInfo      *LI;      // Current MachineLoopInfo
47     MachineDominatorTree *DT;      // Machine dominator tree for the cur loop
48     MachineRegisterInfo  *RegInfo; // Machine register information
49
50     // State that is updated as we process loops
51     bool         Changed;          // True if a loop is changed.
52     MachineLoop *CurLoop;          // The current loop we are working on.
53     MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
54   public:
55     static char ID; // Pass identification, replacement for typeid
56     MachineLICM() : MachineFunctionPass(&ID) {}
57
58     virtual bool runOnMachineFunction(MachineFunction &MF);
59
60     const char *getPassName() const { return "Machine Instruction LICM"; }
61
62     // FIXME: Loop preheaders?
63     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64       AU.setPreservesCFG();
65       AU.addRequired<MachineLoopInfo>();
66       AU.addRequired<MachineDominatorTree>();
67       AU.addPreserved<MachineLoopInfo>();
68       AU.addPreserved<MachineDominatorTree>();
69       MachineFunctionPass::getAnalysisUsage(AU);
70     }
71   private:
72     /// IsLoopInvariantInst - Returns true if the instruction is loop
73     /// invariant. I.e., all virtual register operands are defined outside of
74     /// the loop, physical registers aren't accessed (explicitly or implicitly),
75     /// and the instruction is hoistable.
76     /// 
77     bool IsLoopInvariantInst(MachineInstr &I);
78
79     /// HoistRegion - Walk the specified region of the CFG (defined by all
80     /// blocks dominated by the specified block, and that are in the current
81     /// loop) in depth first order w.r.t the DominatorTree. This allows us to
82     /// visit definitions before uses, allowing us to hoist a loop body in one
83     /// pass without iteration.
84     ///
85     void HoistRegion(MachineDomTreeNode *N);
86
87     /// Hoist - When an instruction is found to only use loop invariant operands
88     /// that is safe to hoist, this instruction is called to do the dirty work.
89     ///
90     void Hoist(MachineInstr &MI);
91   };
92 } // end anonymous namespace
93
94 char MachineLICM::ID = 0;
95 static RegisterPass<MachineLICM>
96 X("machinelicm", "Machine Loop Invariant Code Motion");
97
98 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
99
100 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
101 /// loop that has a preheader.
102 static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
103   for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
104     if (L->getLoopPreheader())
105       return false;
106   return true;
107 }
108
109 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
110 /// is not preserved so it is not a good idea to run LICM multiple times on one
111 /// loop.
112 ///
113 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
114   DOUT << "******** Machine LICM ********\n";
115
116   Changed = false;
117   TM = &MF.getTarget();
118   TII = TM->getInstrInfo();
119   RegInfo = &MF.getRegInfo();
120
121   // Get our Loop information...
122   LI = &getAnalysis<MachineLoopInfo>();
123   DT = &getAnalysis<MachineDominatorTree>();
124
125   for (MachineLoopInfo::iterator
126          I = LI->begin(), E = LI->end(); I != E; ++I) {
127     CurLoop = *I;
128
129     // Only visit outer-most preheader-sporting loops.
130     if (!LoopIsOuterMostWithPreheader(CurLoop))
131       continue;
132
133     // Determine the block to which to hoist instructions. If we can't find a
134     // suitable loop preheader, we can't do any hoisting.
135     //
136     // FIXME: We are only hoisting if the basic block coming into this loop
137     // has only one successor. This isn't the case in general because we haven't
138     // broken critical edges or added preheaders.
139     CurPreheader = CurLoop->getLoopPreheader();
140     if (!CurPreheader)
141       continue;
142
143     HoistRegion(DT->getNode(CurLoop->getHeader()));
144   }
145
146   return Changed;
147 }
148
149 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
150 /// dominated by the specified block, and that are in the current loop) in depth
151 /// first order w.r.t the DominatorTree. This allows us to visit definitions
152 /// before uses, allowing us to hoist a loop body in one pass without iteration.
153 ///
154 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
155   assert(N != 0 && "Null dominator tree node?");
156   MachineBasicBlock *BB = N->getBlock();
157
158   // If this subregion is not in the top level loop at all, exit.
159   if (!CurLoop->contains(BB)) return;
160
161   for (MachineBasicBlock::iterator
162          I = BB->begin(), E = BB->end(); I != E; ) {
163     MachineInstr &MI = *I++;
164
165     // Try hoisting the instruction out of the loop. We can only do this if
166     // all of the operands of the instruction are loop invariant and if it is
167     // safe to hoist the instruction.
168     Hoist(MI);
169   }
170
171   const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
172
173   for (unsigned I = 0, E = Children.size(); I != E; ++I)
174     HoistRegion(Children[I]);
175 }
176
177 /// IsLoopInvariantInst - Returns true if the instruction is loop
178 /// invariant. I.e., all virtual register operands are defined outside of the
179 /// loop, physical registers aren't accessed explicitly, and there are no side
180 /// effects that aren't captured by the operands or other flags.
181 /// 
182 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
183   const TargetInstrDesc &TID = I.getDesc();
184   
185   // Ignore stuff that we obviously can't hoist.
186   if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
187       TID.hasUnmodeledSideEffects())
188     return false;
189   
190   if (TID.mayLoad()) {
191     // Okay, this instruction does a load. As a refinement, we allow the target
192     // to decide whether the loaded value is actually a constant. If so, we can
193     // actually use it as a load.
194     if (!TII->isInvariantLoad(&I))
195       // FIXME: we should be able to sink loads with no other side effects if
196       // there is nothing that can change memory from here until the end of
197       // block. This is a trivial form of alias analysis.
198       return false;
199   }
200
201   DEBUG({
202       DOUT << "--- Checking if we can hoist " << I;
203       if (I.getDesc().getImplicitUses()) {
204         DOUT << "  * Instruction has implicit uses:\n";
205
206         const TargetRegisterInfo *TRI = TM->getRegisterInfo();
207         for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
208              *ImpUses; ++ImpUses)
209           DOUT << "      -> " << TRI->getName(*ImpUses) << "\n";
210       }
211
212       if (I.getDesc().getImplicitDefs()) {
213         DOUT << "  * Instruction has implicit defines:\n";
214
215         const TargetRegisterInfo *TRI = TM->getRegisterInfo();
216         for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
217              *ImpDefs; ++ImpDefs)
218           DOUT << "      -> " << TRI->getName(*ImpDefs) << "\n";
219       }
220     });
221
222   if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
223     DOUT << "Cannot hoist with implicit defines or uses\n";
224     return false;
225   }
226
227   // The instruction is loop invariant if all of its operands are.
228   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
229     const MachineOperand &MO = I.getOperand(i);
230
231     if (!MO.isReg())
232       continue;
233
234     unsigned Reg = MO.getReg();
235     if (Reg == 0) continue;
236
237     // Don't hoist an instruction that uses or defines a physical register.
238     if (TargetRegisterInfo::isPhysicalRegister(Reg))
239       return false;
240
241     if (!MO.isUse())
242       continue;
243
244     assert(RegInfo->getVRegDef(Reg) &&
245            "Machine instr not mapped for this vreg?!");
246
247     // If the loop contains the definition of an operand, then the instruction
248     // isn't loop invariant.
249     if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
250       return false;
251   }
252
253   // If we got this far, the instruction is loop invariant!
254   return true;
255 }
256
257 /// Hoist - When an instruction is found to use only loop invariant operands
258 /// that are safe to hoist, this instruction is called to do the dirty work.
259 ///
260 void MachineLICM::Hoist(MachineInstr &MI) {
261   if (!IsLoopInvariantInst(MI)) return;
262
263   // Now move the instructions to the predecessor, inserting it before any
264   // terminator instructions.
265   DEBUG({
266       DOUT << "Hoisting " << MI;
267       if (CurPreheader->getBasicBlock())
268         DOUT << " to MachineBasicBlock "
269              << CurPreheader->getBasicBlock()->getName();
270       if (MI.getParent()->getBasicBlock())
271         DOUT << " from MachineBasicBlock "
272              << MI.getParent()->getBasicBlock()->getName();
273       DOUT << "\n";
274     });
275
276   CurPreheader->splice(CurPreheader->getFirstTerminator(), MI.getParent(), &MI);
277
278   ++NumHoisted;
279   Changed = true;
280 }