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/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"
31 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
34 class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
35 const TargetMachine *TM;
36 const TargetInstrInfo *TII;
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
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.
47 static char ID; // Pass identification, replacement for typeid
48 MachineLICM() : MachineFunctionPass(&ID) {}
50 virtual bool runOnMachineFunction(MachineFunction &MF);
52 // FIXME: Loop preheaders?
53 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55 AU.addRequired<MachineLoopInfo>();
56 AU.addRequired<MachineDominatorTree>();
57 AU.addPreserved<MachineLoopInfo>();
58 AU.addPreserved<MachineDominatorTree>();
59 MachineFunctionPass::getAnalysisUsage(AU);
62 /// VisitAllLoops - Visit all of the loops in depth first order and try to
63 /// hoist invariant instructions from them.
65 void VisitAllLoops(MachineLoop *L) {
66 const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
68 for (MachineLoop::iterator
69 I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
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.
75 HoistRegion(DT->getNode(ML->getHeader()));
78 HoistRegion(DT->getNode(L->getHeader()));
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
85 bool IsInSubLoop(MachineBasicBlock *BB) {
86 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
87 return LI->getLoopFor(BB) != CurLoop;
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.
95 bool IsLoopInvariantInst(MachineInstr &I);
97 /// FindPredecessors - Get all of the predecessors of the loop that are not
100 void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
101 const MachineBasicBlock *Header = CurLoop->getHeader();
103 for (MachineBasicBlock::const_pred_iterator
104 I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
105 if (!CurLoop->contains(*I))
109 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
110 /// the predecessor basic block (but before the terminator instructions).
112 void MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
113 MachineBasicBlock *FromMBB,
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.
122 void HoistRegion(MachineDomTreeNode *N);
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.
127 void Hoist(MachineInstr &MI);
129 } // end anonymous namespace
131 char MachineLICM::ID = 0;
132 static RegisterPass<MachineLICM>
133 X("machinelicm", "Machine Loop Invariant Code Motion");
135 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
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
141 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
142 DOUT << "******** Machine LICM ********\n";
145 TM = &MF.getTarget();
146 TII = TM->getInstrInfo();
147 RegInfo = &MF.getRegInfo();
149 // Get our Loop information...
150 LI = &getAnalysis<MachineLoopInfo>();
151 DT = &getAnalysis<MachineDominatorTree>();
153 for (MachineLoopInfo::iterator
154 I = LI->begin(), E = LI->end(); I != E; ++I) {
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);
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.
171 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
172 assert(N != 0 && "Null dominator tree node?");
173 MachineBasicBlock *BB = N->getBlock();
175 // If this subregion is not in the top level loop at all, exit.
176 if (!CurLoop->contains(BB)) return;
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++;
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.
191 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
193 for (unsigned I = 0, E = Children.size(); I != E; ++I)
194 HoistRegion(Children[I]);
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.
202 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
203 const TargetInstrDesc &TID = I.getDesc();
205 // Ignore stuff that we obviously can't hoist.
206 if (TID.mayStore() || TID.isCall() || TID.isReturn() || TID.isBranch() ||
207 TID.hasUnmodeledSideEffects())
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.
222 DOUT << "--- Checking if we can hoist " << I;
223 if (I.getDesc().getImplicitUses()) {
224 DOUT << " * Instruction has implicit uses:\n";
226 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
227 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
229 DOUT << " -> " << TRI->getName(*ImpUses) << "\n";
232 if (I.getDesc().getImplicitDefs()) {
233 DOUT << " * Instruction has implicit defines:\n";
235 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
236 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
238 DOUT << " -> " << TRI->getName(*ImpDefs) << "\n";
242 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
243 DOUT << "Cannot hoist with implicit defines or uses\n";
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);
251 if (!MO.isRegister())
254 if (MO.isDef() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
255 // Don't hoist an instruction that defines a physical register.
261 unsigned Reg = MO.getReg();
262 if (Reg == 0) continue;
264 // Don't hoist instructions that access physical registers.
265 if (TargetRegisterInfo::isPhysicalRegister(Reg))
268 assert(RegInfo->getVRegDef(Reg) &&
269 "Machine instr not mapped for this vreg?!");
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()))
277 // If we got this far, the instruction is loop invariant!
281 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of the
282 /// predecessor basic block (but before the terminator instructions).
284 void MachineLICM::MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
285 MachineBasicBlock *FromMBB,
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();
298 MachineBasicBlock::iterator WhereIter = ToMBB->getFirstTerminator();
299 MachineBasicBlock::iterator To, From = FromMBB->begin();
304 assert(From != FromMBB->end() && "Didn't find instr in BB!");
307 ToMBB->splice(WhereIter, FromMBB, From, ++To);
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.
314 void MachineLICM::Hoist(MachineInstr &MI) {
315 if (!IsLoopInvariantInst(MI)) return;
317 std::vector<MachineBasicBlock*> Preds;
319 // Non-back-edge predecessors.
320 FindPredecessors(Preds);
322 // Either we don't have any predecessors(?!) or we have more than one, which
324 if (Preds.empty() || Preds.size() != 1) return;
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
329 MachineBasicBlock *MBB = Preds.front();
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!");
338 // Now move the instructions to the predecessor.
339 MoveInstToEndOfBlock(MBB, MI.getParent(), &MI);