1 //===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
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/Statistic.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
30 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
33 class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
34 const TargetMachine *TM;
35 const TargetInstrInfo *TII;
37 // Various analyses that we use...
38 MachineLoopInfo *LI; // Current MachineLoopInfo
39 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
40 MachineRegisterInfo *RegInfo; // Machine register information
42 // State that is updated as we process loops
43 bool Changed; // True if a loop is changed.
44 MachineLoop *CurLoop; // The current loop we are working on.
46 static char ID; // Pass identification, replacement for typeid
47 MachineLICM() : MachineFunctionPass(&ID) {}
49 virtual bool runOnMachineFunction(MachineFunction &MF);
51 const char *getPassName() const { return "Machine Instruction LICM"; }
53 // FIXME: Loop preheaders?
54 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequired<MachineLoopInfo>();
57 AU.addRequired<MachineDominatorTree>();
58 AU.addPreserved<MachineLoopInfo>();
59 AU.addPreserved<MachineDominatorTree>();
60 MachineFunctionPass::getAnalysisUsage(AU);
63 /// VisitAllLoops - Visit all of the loops in depth first order and try to
64 /// hoist invariant instructions from them.
66 void VisitAllLoops(MachineLoop *L) {
67 const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
69 for (MachineLoop::iterator
70 I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
73 // Traverse the body of the loop in depth first order on the dominator
74 // tree so that we are guaranteed to see definitions before we see uses.
76 HoistRegion(DT->getNode(ML->getHeader()));
79 HoistRegion(DT->getNode(L->getHeader()));
82 /// IsInSubLoop - A little predicate that returns true if the specified
83 /// basic block is in a subloop of the current one, not the current one
86 bool IsInSubLoop(MachineBasicBlock *BB) {
87 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
88 return LI->getLoopFor(BB) != CurLoop;
91 /// IsLoopInvariantInst - Returns true if the instruction is loop
92 /// invariant. I.e., all virtual register operands are defined outside of
93 /// the loop, physical registers aren't accessed (explicitly or implicitly),
94 /// and the instruction is hoistable.
96 bool IsLoopInvariantInst(MachineInstr &I);
98 /// FindPredecessors - Get all of the predecessors of the loop that are not
101 void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
102 const MachineBasicBlock *Header = CurLoop->getHeader();
104 for (MachineBasicBlock::const_pred_iterator
105 I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
106 if (!CurLoop->contains(*I))
110 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
111 /// the predecessor basic block (but before the terminator instructions).
113 void MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
114 MachineBasicBlock *FromMBB,
117 /// HoistRegion - Walk the specified region of the CFG (defined by all
118 /// blocks dominated by the specified block, and that are in the current
119 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
120 /// visit definitions before uses, allowing us to hoist a loop body in one
121 /// pass without iteration.
123 void HoistRegion(MachineDomTreeNode *N);
125 /// Hoist - When an instruction is found to only use loop invariant operands
126 /// that is safe to hoist, this instruction is called to do the dirty work.
128 void Hoist(MachineInstr &MI);
130 } // end anonymous namespace
132 char MachineLICM::ID = 0;
133 static RegisterPass<MachineLICM>
134 X("machinelicm", "Machine Loop Invariant Code Motion");
136 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
138 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
139 /// is not preserved so it is not a good idea to run LICM multiple times on one
142 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
143 DOUT << "******** Machine LICM ********\n";
146 TM = &MF.getTarget();
147 TII = TM->getInstrInfo();
148 RegInfo = &MF.getRegInfo();
150 // Get our Loop information...
151 LI = &getAnalysis<MachineLoopInfo>();
152 DT = &getAnalysis<MachineDominatorTree>();
154 for (MachineLoopInfo::iterator
155 I = LI->begin(), E = LI->end(); I != E; ++I) {
158 // Visit all of the instructions of the loop. We want to visit the subloops
159 // first, though, so that we can hoist their invariants first into their
160 // containing loop before we process that loop.
161 VisitAllLoops(CurLoop);
167 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
168 /// dominated by the specified block, and that are in the current loop) in depth
169 /// first order w.r.t the DominatorTree. This allows us to visit definitions
170 /// before uses, allowing us to hoist a loop body in one pass without iteration.
172 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
173 assert(N != 0 && "Null dominator tree node?");
174 MachineBasicBlock *BB = N->getBlock();
176 // If this subregion is not in the top level loop at all, exit.
177 if (!CurLoop->contains(BB)) return;
179 // Only need to process the contents of this block if it is not part of a
180 // subloop (which would already have been processed).
181 if (!IsInSubLoop(BB))
182 for (MachineBasicBlock::iterator
183 I = BB->begin(), E = BB->end(); I != E; ) {
184 MachineInstr &MI = *I++;
186 // Try hoisting the instruction out of the loop. We can only do this if
187 // all of the operands of the instruction are loop invariant and if it is
188 // safe to hoist the instruction.
192 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
194 for (unsigned I = 0, E = Children.size(); I != E; ++I)
195 HoistRegion(Children[I]);
198 /// IsLoopInvariantInst - Returns true if the instruction is loop
199 /// invariant. I.e., all virtual register operands are defined outside of the
200 /// loop, physical registers aren't accessed explicitly, and there are no side
201 /// effects that aren't captured by the operands or other flags.
203 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
204 const TargetInstrDesc &TID = I.getDesc();
206 // Ignore stuff that we obviously can't hoist.
207 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
208 TID.hasUnmodeledSideEffects())
212 // Okay, this instruction does a load. As a refinement, we allow the target
213 // to decide whether the loaded value is actually a constant. If so, we can
214 // actually use it as a load.
215 if (!TII->isInvariantLoad(&I))
216 // FIXME: we should be able to sink loads with no other side effects if
217 // there is nothing that can change memory from here until the end of
218 // block. This is a trivial form of alias analysis.
223 DOUT << "--- Checking if we can hoist " << I;
224 if (I.getDesc().getImplicitUses()) {
225 DOUT << " * Instruction has implicit uses:\n";
227 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
228 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
230 DOUT << " -> " << TRI->getName(*ImpUses) << "\n";
233 if (I.getDesc().getImplicitDefs()) {
234 DOUT << " * Instruction has implicit defines:\n";
236 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
237 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
239 DOUT << " -> " << TRI->getName(*ImpDefs) << "\n";
243 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
244 DOUT << "Cannot hoist with implicit defines or uses\n";
248 // The instruction is loop invariant if all of its operands are.
249 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
250 const MachineOperand &MO = I.getOperand(i);
255 if (MO.isDef() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
256 // Don't hoist an instruction that defines a physical register.
262 unsigned Reg = MO.getReg();
263 if (Reg == 0) continue;
265 // Don't hoist instructions that access physical registers.
266 if (TargetRegisterInfo::isPhysicalRegister(Reg))
269 assert(RegInfo->getVRegDef(Reg) &&
270 "Machine instr not mapped for this vreg?!");
272 // If the loop contains the definition of an operand, then the instruction
273 // isn't loop invariant.
274 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
278 // If we got this far, the instruction is loop invariant!
282 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of the
283 /// predecessor basic block (but before the terminator instructions).
285 void MachineLICM::MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
286 MachineBasicBlock *FromMBB,
289 DOUT << "Hoisting " << *MI;
290 if (ToMBB->getBasicBlock())
291 DOUT << " to MachineBasicBlock "
292 << ToMBB->getBasicBlock()->getName();
293 if (FromMBB->getBasicBlock())
294 DOUT << " from MachineBasicBlock "
295 << FromMBB->getBasicBlock()->getName();
299 MachineBasicBlock::iterator WhereIter = ToMBB->getFirstTerminator();
300 MachineBasicBlock::iterator To, From = FromMBB->begin();
305 assert(From != FromMBB->end() && "Didn't find instr in BB!");
308 ToMBB->splice(WhereIter, FromMBB, From, ++To);
312 /// Hoist - When an instruction is found to use only loop invariant operands
313 /// that are safe to hoist, this instruction is called to do the dirty work.
315 void MachineLICM::Hoist(MachineInstr &MI) {
316 if (!IsLoopInvariantInst(MI)) return;
318 std::vector<MachineBasicBlock*> Preds;
320 // Non-back-edge predecessors.
321 FindPredecessors(Preds);
323 // Either we don't have any predecessors(?!) or we have more than one, which
325 if (Preds.empty() || Preds.size() != 1) return;
327 // Check that the predecessor is qualified to take the hoisted instruction.
328 // I.e., there is only one edge from the predecessor, and it's to the loop
330 MachineBasicBlock *MBB = Preds.front();
332 // FIXME: We are assuming at first that the basic block coming into this loop
333 // has only one successor. This isn't the case in general because we haven't
334 // broken critical edges or added preheaders.
335 if (MBB->succ_size() != 1) return;
336 assert(*MBB->succ_begin() == CurLoop->getHeader() &&
337 "The predecessor doesn't feed directly into the loop header!");
339 // Now move the instructions to the predecessor.
340 MoveInstToEndOfBlock(MBB, MI.getParent(), &MI);