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/MRegisterInfo.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"
32 // Hidden options to help debugging
34 PerformLICM("machine-licm",
35 cl::init(false), cl::Hidden,
36 cl::desc("Perform loop-invariant code motion on machine code"));
39 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
42 class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
43 const TargetMachine *TM;
44 const TargetInstrInfo *TII;
45 MachineFunction *CurMF; // Current MachineFunction
47 // Various analyses that we use...
48 MachineLoopInfo *LI; // Current MachineLoopInfo
49 MachineDominatorTree *DT; // Machine dominator tree for the current Loop
50 MachineRegisterInfo *RegInfo; // Machine register information
52 // State that is updated as we process loops
53 bool Changed; // True if a loop is changed.
54 MachineLoop *CurLoop; // The current loop we are working on.
56 static char ID; // Pass identification, replacement for typeid
57 MachineLICM() : MachineFunctionPass((intptr_t)&ID) {}
59 virtual bool runOnMachineFunction(MachineFunction &MF);
61 /// FIXME: Loop preheaders?
63 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64 MachineFunctionPass::getAnalysisUsage(AU);
66 AU.addRequired<MachineLoopInfo>();
67 AU.addRequired<MachineDominatorTree>();
70 /// VisitAllLoops - Visit all of the loops in depth first order and try to
71 /// hoist invariant instructions from them.
73 void VisitAllLoops(MachineLoop *L) {
74 const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
76 for (MachineLoop::iterator
77 I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
80 // Traverse the body of the loop in depth first order on the dominator
81 // tree so that we are guaranteed to see definitions before we see uses.
83 HoistRegion(DT->getNode(ML->getHeader()));
86 HoistRegion(DT->getNode(L->getHeader()));
89 /// IsInSubLoop - A little predicate that returns true if the specified
90 /// basic block is in a subloop of the current one, not the current one
93 bool IsInSubLoop(MachineBasicBlock *BB) {
94 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
95 return LI->getLoopFor(BB) != CurLoop;
98 /// IsLoopInvariantInst - Returns true if the instruction is loop
99 /// invariant. I.e., all virtual register operands are defined outside of
100 /// the loop, physical registers aren't accessed (explicitly or implicitly),
101 /// and the instruction is hoistable.
103 bool IsLoopInvariantInst(MachineInstr &I);
105 /// FindPredecessors - Get all of the predecessors of the loop that are not
108 void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
109 const MachineBasicBlock *Header = CurLoop->getHeader();
111 for (MachineBasicBlock::const_pred_iterator
112 I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
113 if (!CurLoop->contains(*I))
117 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
118 /// the predecessor basic block (but before the terminator instructions).
120 void MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
121 MachineBasicBlock *FromMBB,
124 DOUT << "Hoisting " << *MI;
125 if (ToMBB->getBasicBlock())
126 DOUT << " to MachineBasicBlock "
127 << ToMBB->getBasicBlock()->getName();
131 MachineBasicBlock::iterator WhereIter = ToMBB->getFirstTerminator();
132 MachineBasicBlock::iterator To, From = FromMBB->begin();
137 assert(From != FromMBB->end() && "Didn't find instr in BB!");
140 ToMBB->splice(WhereIter, FromMBB, From, ++To);
144 /// HoistRegion - Walk the specified region of the CFG (defined by all
145 /// blocks dominated by the specified block, and that are in the current
146 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
147 /// visit definitions before uses, allowing us to hoist a loop body in one
148 /// pass without iteration.
150 void HoistRegion(MachineDomTreeNode *N);
152 /// Hoist - When an instruction is found to only use loop invariant operands
153 /// that is safe to hoist, this instruction is called to do the dirty work.
155 void Hoist(MachineInstr &MI);
158 char MachineLICM::ID = 0;
159 RegisterPass<MachineLICM> X("machine-licm",
160 "Machine Loop Invariant Code Motion");
161 } // end anonymous namespace
163 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
165 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
166 /// is not preserved so it is not a good idea to run LICM multiple times on one
169 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
170 if (!PerformLICM) return false; // For debugging.
172 DOUT << "******** Machine LICM ********\n";
176 TM = &CurMF->getTarget();
177 TII = TM->getInstrInfo();
178 RegInfo = &CurMF->getRegInfo();
180 // Get our Loop information...
181 LI = &getAnalysis<MachineLoopInfo>();
182 DT = &getAnalysis<MachineDominatorTree>();
184 for (MachineLoopInfo::iterator
185 I = LI->begin(), E = LI->end(); I != E; ++I) {
188 // Visit all of the instructions of the loop. We want to visit the subloops
189 // first, though, so that we can hoist their invariants first into their
190 // containing loop before we process that loop.
191 VisitAllLoops(CurLoop);
197 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
198 /// dominated by the specified block, and that are in the current loop) in depth
199 /// first order w.r.t the DominatorTree. This allows us to visit definitions
200 /// before uses, allowing us to hoist a loop body in one pass without iteration.
202 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
203 assert(N != 0 && "Null dominator tree node?");
204 MachineBasicBlock *BB = N->getBlock();
206 // If this subregion is not in the top level loop at all, exit.
207 if (!CurLoop->contains(BB)) return;
209 // Only need to process the contents of this block if it is not part of a
210 // subloop (which would already have been processed).
211 if (!IsInSubLoop(BB))
212 for (MachineBasicBlock::iterator
213 I = BB->begin(), E = BB->end(); I != E; ) {
214 MachineInstr &MI = *I++;
216 // Try hoisting the instruction out of the loop. We can only do this if
217 // all of the operands of the instruction are loop invariant and if it is
218 // safe to hoist the instruction.
222 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
224 for (unsigned I = 0, E = Children.size(); I != E; ++I)
225 HoistRegion(Children[I]);
228 /// IsLoopInvariantInst - Returns true if the instruction is loop
229 /// invariant. I.e., all virtual register operands are defined outside of the
230 /// loop, physical registers aren't accessed explicitly, and there are no side
231 /// effects that aren't captured by the operands or other flags.
233 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
235 DOUT << "--- Checking if we can hoist " << I;
236 if (I.getInstrDescriptor()->ImplicitUses) {
237 DOUT << " * Instruction has implicit uses:\n";
239 const MRegisterInfo *MRI = TM->getRegisterInfo();
240 const unsigned *ImpUses = I.getInstrDescriptor()->ImplicitUses;
242 for (; *ImpUses; ++ImpUses)
243 DOUT << " -> " << MRI->getName(*ImpUses) << "\n";
246 if (I.getInstrDescriptor()->ImplicitDefs) {
247 DOUT << " * Instruction has implicit defines:\n";
249 const MRegisterInfo *MRI = TM->getRegisterInfo();
250 const unsigned *ImpDefs = I.getInstrDescriptor()->ImplicitDefs;
252 for (; *ImpDefs; ++ImpDefs)
253 DOUT << " -> " << MRI->getName(*ImpDefs) << "\n";
256 if (TII->hasUnmodelledSideEffects(&I))
257 DOUT << " * Instruction has side effects.\n";
260 // The instruction is loop invariant if all of its operands are loop-invariant
261 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
262 const MachineOperand &MO = I.getOperand(i);
264 if (!(MO.isRegister() && MO.getReg() && MO.isUse()))
267 unsigned Reg = MO.getReg();
269 // Don't hoist instructions that access physical registers.
270 if (!MRegisterInfo::isVirtualRegister(Reg))
273 assert(RegInfo->getVRegDef(Reg)&&"Machine instr not mapped for this vreg?");
275 // If the loop contains the definition of an operand, then the instruction
276 // isn't loop invariant.
277 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
281 // Don't hoist something that has unmodelled side effects.
282 if (TII->hasUnmodelledSideEffects(&I)) return false;
284 // If we got this far, the instruction is loop invariant!
288 /// Hoist - When an instruction is found to only use loop invariant operands
289 /// that is safe to hoist, this instruction is called to do the dirty work.
291 void MachineLICM::Hoist(MachineInstr &MI) {
292 if (!IsLoopInvariantInst(MI)) return;
294 std::vector<MachineBasicBlock*> Preds;
296 // Non-back-edge predecessors.
297 FindPredecessors(Preds);
299 // Either we don't have any predecessors(?!) or we have more than one, which
301 if (Preds.empty() || Preds.size() != 1) return;
303 // Check that the predecessor is qualified to take the hoisted
304 // instruction. I.e., there is only one edge from the predecessor, and it's to
306 MachineBasicBlock *MBB = Preds.front();
308 // FIXME: We are assuming at first that the basic block coming into this loop
309 // has only one successor. This isn't the case in general because we haven't
310 // broken critical edges or added preheaders.
311 if (MBB->succ_size() != 1) return;
312 assert(*MBB->succ_begin() == CurLoop->getHeader() &&
313 "The predecessor doesn't feed directly into the loop header!");
315 // Now move the instructions to the predecessor.
316 MoveInstToEndOfBlock(MBB, MI.getParent(), &MI);