blob: 8ae166b29475a58e0b2d4e273dc2c2d4713ca916 [file] [log] [blame]
Bill Wendlingb958b0d2007-12-07 21:42:31 +00001//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Bill Wendling and is distributed under the
6// University of Illinois Open Source 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"
Bill Wendling7c7888b2007-12-08 01:47:01 +000016#include "llvm/ADT/IndexedMap.h"
Bill Wendlingb958b0d2007-12-07 21:42:31 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/CodeGen/MachineBasicBlock.h"
20#include "llvm/CodeGen/MachineDominators.h"
21#include "llvm/CodeGen/MachineInstr.h"
22#include "llvm/CodeGen/MachineLoopInfo.h"
23#include "llvm/CodeGen/Passes.h"
Bill Wendlingb958b0d2007-12-07 21:42:31 +000024#include "llvm/Support/CFG.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Compiler.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Target/MRegisterInfo.h"
Bill Wendling3caa4702007-12-11 23:27:51 +000029#include "llvm/Target/TargetInstrInfo.h"
Bill Wendlingb958b0d2007-12-07 21:42:31 +000030#include "llvm/Target/TargetMachine.h"
Bill Wendlingb958b0d2007-12-07 21:42:31 +000031
32using namespace llvm;
33
34namespace {
35 // Hidden options to help debugging
36 cl::opt<bool>
37 PerformLICM("machine-licm",
Bill Wendling7c7888b2007-12-08 01:47:01 +000038 cl::init(false), cl::Hidden,
39 cl::desc("Perform loop-invariant code motion on machine code"));
Bill Wendlingb958b0d2007-12-07 21:42:31 +000040}
41
Bill Wendling0fe34c22007-12-08 23:58:46 +000042STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Bill Wendling7c7888b2007-12-08 01:47:01 +000043
Bill Wendlingb958b0d2007-12-07 21:42:31 +000044namespace {
45 class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
Bill Wendling3caa4702007-12-11 23:27:51 +000046 const TargetInstrInfo *TII;
47 MachineFunction *CurMF; // Current MachineFunction
Bill Wendlingd9b9be62007-12-11 19:40:06 +000048
Bill Wendlingb958b0d2007-12-07 21:42:31 +000049 // Various analyses that we use...
50 MachineLoopInfo *LI; // Current MachineLoopInfo
51 MachineDominatorTree *DT; // Machine dominator tree for the current Loop
52
Bill Wendlingb958b0d2007-12-07 21:42:31 +000053 // State that is updated as we process loops
54 bool Changed; // True if a loop is changed.
55 MachineLoop *CurLoop; // The current loop we are working on.
56
57 // Map the def of a virtual register to the machine instruction.
Bill Wendling7c7888b2007-12-08 01:47:01 +000058 IndexedMap<const MachineInstr*, VirtReg2IndexFunctor> VRegDefs;
Bill Wendlingb958b0d2007-12-07 21:42:31 +000059 public:
60 static char ID; // Pass identification, replacement for typeid
61 MachineLICM() : MachineFunctionPass((intptr_t)&ID) {}
62
63 virtual bool runOnMachineFunction(MachineFunction &MF);
64
65 /// FIXME: Loop preheaders?
66 ///
67 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68 AU.setPreservesCFG();
69 AU.addRequired<MachineLoopInfo>();
70 AU.addRequired<MachineDominatorTree>();
71 }
72 private:
Bill Wendling7c7888b2007-12-08 01:47:01 +000073 /// VisitAllLoops - Visit all of the loops in depth first order and try to
74 /// hoist invariant instructions from them.
Bill Wendlingb958b0d2007-12-07 21:42:31 +000075 ///
Bill Wendling7c7888b2007-12-08 01:47:01 +000076 void VisitAllLoops(MachineLoop *L) {
Bill Wendlingb958b0d2007-12-07 21:42:31 +000077 const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
78
79 for (MachineLoop::iterator
Bill Wendling7c7888b2007-12-08 01:47:01 +000080 I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
81 MachineLoop *ML = *I;
Bill Wendlingb958b0d2007-12-07 21:42:31 +000082
Bill Wendling7c7888b2007-12-08 01:47:01 +000083 // Traverse the body of the loop in depth first order on the dominator
84 // tree so that we are guaranteed to see definitions before we see uses.
85 VisitAllLoops(ML);
86 HoistRegion(DT->getNode(ML->getHeader()));
87 }
88
89 HoistRegion(DT->getNode(L->getHeader()));
Bill Wendlingb958b0d2007-12-07 21:42:31 +000090 }
91
92 /// MapVirtualRegisterDefs - Create a map of which machine instruction
93 /// defines a virtual register.
94 ///
Bill Wendlingd9b9be62007-12-11 19:40:06 +000095 void MapVirtualRegisterDefs();
Bill Wendlingb958b0d2007-12-07 21:42:31 +000096
Bill Wendling0fe34c22007-12-08 23:58:46 +000097 /// IsInSubLoop - A little predicate that returns true if the specified
Bill Wendlingb958b0d2007-12-07 21:42:31 +000098 /// basic block is in a subloop of the current one, not the current one
99 /// itself.
100 ///
Bill Wendling0fe34c22007-12-08 23:58:46 +0000101 bool IsInSubLoop(MachineBasicBlock *BB) {
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000102 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Bill Wendling2dfc9eb2007-12-11 18:45:11 +0000103 return LI->getLoopFor(BB) != CurLoop;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000104 }
105
106 /// CanHoistInst - Checks that this instructions is one that can be hoisted
107 /// out of the loop. I.e., it has no side effects, isn't a control flow
108 /// instr, etc.
109 ///
110 bool CanHoistInst(MachineInstr &I) const {
Bill Wendling3caa4702007-12-11 23:27:51 +0000111#ifndef NDEBUG
112 DEBUG({
113 DOUT << "--- Checking if we can hoist " << I << "\n";
114 if (I.getInstrDescriptor()->ImplicitUses)
115 DOUT << " * Instruction has implicit uses.\n";
116 else if (!TII->isTriviallyReMaterializable(&I))
117 DOUT << " * Instruction has side effects.\n";
118 });
119#endif
Bill Wendling2dfc9eb2007-12-11 18:45:11 +0000120 // Don't hoist if this instruction implicitly reads physical registers.
Bill Wendling3caa4702007-12-11 23:27:51 +0000121 if (I.getInstrDescriptor()->ImplicitUses) return false;
122 return TII->isTriviallyReMaterializable(&I);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000123 }
124
Bill Wendling0fe34c22007-12-08 23:58:46 +0000125 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000126 /// invariant. I.e., all virtual register operands are defined outside of
127 /// the loop, physical registers aren't accessed (explicitly or implicitly),
128 /// and the instruction is hoistable.
129 ///
Bill Wendling0fe34c22007-12-08 23:58:46 +0000130 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000131
132 /// FindPredecessors - Get all of the predecessors of the loop that are not
133 /// back-edges.
134 ///
Bill Wendling2dfc9eb2007-12-11 18:45:11 +0000135 void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000136 const MachineBasicBlock *Header = CurLoop->getHeader();
137
138 for (MachineBasicBlock::const_pred_iterator
139 I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
140 if (!CurLoop->contains(*I))
141 Preds.push_back(*I);
142 }
143
Bill Wendling7c7888b2007-12-08 01:47:01 +0000144 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
145 /// the predecessor basic block (but before the terminator instructions).
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000146 ///
Bill Wendling7c7888b2007-12-08 01:47:01 +0000147 void MoveInstToEndOfBlock(MachineBasicBlock *MBB, MachineInstr *MI) {
Bill Wendling3caa4702007-12-11 23:27:51 +0000148 DEBUG({
149 DOUT << "Hoisting " << *MI;
150 if (MBB->getBasicBlock())
151 DOUT << " to MachineBasicBlock "
152 << MBB->getBasicBlock()->getName();
153 DOUT << "\n";
154 });
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000155 MachineBasicBlock::iterator Iter = MBB->getFirstTerminator();
156 MBB->insert(Iter, MI);
Bill Wendling7c7888b2007-12-08 01:47:01 +0000157 ++NumHoisted;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000158 }
159
160 /// HoistRegion - Walk the specified region of the CFG (defined by all
161 /// blocks dominated by the specified block, and that are in the current
162 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
163 /// visit definitions before uses, allowing us to hoist a loop body in one
164 /// pass without iteration.
165 ///
166 void HoistRegion(MachineDomTreeNode *N);
167
168 /// Hoist - When an instruction is found to only use loop invariant operands
169 /// that is safe to hoist, this instruction is called to do the dirty work.
170 ///
Bill Wendling7c7888b2007-12-08 01:47:01 +0000171 void Hoist(MachineInstr &MI);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000172 };
173
174 char MachineLICM::ID = 0;
175 RegisterPass<MachineLICM> X("machine-licm",
176 "Machine Loop Invariant Code Motion");
177} // end anonymous namespace
178
179FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
180
181/// Hoist expressions out of the specified loop. Note, alias info for inner loop
182/// is not preserved so it is not a good idea to run LICM multiple times on one
183/// loop.
184///
185bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
186 if (!PerformLICM) return false; // For debugging.
187
Bill Wendling14ba7ae2007-12-11 22:22:22 +0000188 DOUT << "******** Machine LICM ********\n";
189
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000190 Changed = false;
Bill Wendlingd9b9be62007-12-11 19:40:06 +0000191 CurMF = &MF;
192 TII = CurMF->getTarget().getInstrInfo();
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000193
194 // Get our Loop information...
195 LI = &getAnalysis<MachineLoopInfo>();
196 DT = &getAnalysis<MachineDominatorTree>();
197
Bill Wendlingd9b9be62007-12-11 19:40:06 +0000198 MapVirtualRegisterDefs();
199
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000200 for (MachineLoopInfo::iterator
201 I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendling14ba7ae2007-12-11 22:22:22 +0000202 CurLoop = *I;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000203
204 // Visit all of the instructions of the loop. We want to visit the subloops
205 // first, though, so that we can hoist their invariants first into their
206 // containing loop before we process that loop.
Bill Wendling14ba7ae2007-12-11 22:22:22 +0000207 VisitAllLoops(CurLoop);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000208 }
209
210 return Changed;
211}
212
213/// MapVirtualRegisterDefs - Create a map of which machine instruction defines a
214/// virtual register.
215///
Bill Wendlingd9b9be62007-12-11 19:40:06 +0000216void MachineLICM::MapVirtualRegisterDefs() {
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000217 for (MachineFunction::const_iterator
Bill Wendlingd9b9be62007-12-11 19:40:06 +0000218 I = CurMF->begin(), E = CurMF->end(); I != E; ++I) {
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000219 const MachineBasicBlock &MBB = *I;
220
221 for (MachineBasicBlock::const_iterator
222 II = MBB.begin(), IE = MBB.end(); II != IE; ++II) {
223 const MachineInstr &MI = *II;
224
Bill Wendling7c7888b2007-12-08 01:47:01 +0000225 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
Bill Wendlinge91b2ef2007-12-11 19:17:04 +0000226 const MachineOperand &MO = MI.getOperand(i);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000227
228 if (MO.isRegister() && MO.isDef() &&
Bill Wendling3caa4702007-12-11 23:27:51 +0000229 MRegisterInfo::isVirtualRegister(MO.getReg())) {
230 VRegDefs.grow(MO.getReg());
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000231 VRegDefs[MO.getReg()] = &MI;
Bill Wendling3caa4702007-12-11 23:27:51 +0000232 }
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000233 }
234 }
235 }
236}
237
238/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
239/// dominated by the specified block, and that are in the current loop) in depth
240/// first order w.r.t the DominatorTree. This allows us to visit definitions
241/// before uses, allowing us to hoist a loop body in one pass without iteration.
242///
243void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
244 assert(N != 0 && "Null dominator tree node?");
245 MachineBasicBlock *BB = N->getBlock();
246
247 // If this subregion is not in the top level loop at all, exit.
248 if (!CurLoop->contains(BB)) return;
249
250 // Only need to process the contents of this block if it is not part of a
251 // subloop (which would already have been processed).
Bill Wendling0fe34c22007-12-08 23:58:46 +0000252 if (!IsInSubLoop(BB))
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000253 for (MachineBasicBlock::iterator
254 I = BB->begin(), E = BB->end(); I != E; ) {
255 MachineInstr &MI = *I++;
256
257 // Try hoisting the instruction out of the loop. We can only do this if
258 // all of the operands of the instruction are loop invariant and if it is
259 // safe to hoist the instruction.
Bill Wendling7c7888b2007-12-08 01:47:01 +0000260 Hoist(MI);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000261 }
262
263 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
264
265 for (unsigned I = 0, E = Children.size(); I != E; ++I)
266 HoistRegion(Children[I]);
267}
268
Bill Wendling0fe34c22007-12-08 23:58:46 +0000269/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000270/// invariant. I.e., all virtual register operands are defined outside of the
271/// loop, physical registers aren't accessed (explicitly or implicitly), and the
272/// instruction is hoistable.
273///
Bill Wendling0fe34c22007-12-08 23:58:46 +0000274bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000275 if (!CanHoistInst(I)) return false;
276
277 // The instruction is loop invariant if all of its operands are loop-invariant
278 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
279 const MachineOperand &MO = I.getOperand(i);
280
281 if (!MO.isRegister() || !MO.isUse())
282 continue;
283
284 unsigned Reg = MO.getReg();
285
286 // Don't hoist instructions that access physical registers.
287 if (!MRegisterInfo::isVirtualRegister(Reg))
288 return false;
289
Bill Wendling7c7888b2007-12-08 01:47:01 +0000290 assert(VRegDefs[Reg] && "Machine instr not mapped for this vreg?");
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000291
292 // If the loop contains the definition of an operand, then the instruction
293 // isn't loop invariant.
294 if (CurLoop->contains(VRegDefs[Reg]->getParent()))
295 return false;
296 }
297
298 // If we got this far, the instruction is loop invariant!
299 return true;
300}
301
302/// Hoist - When an instruction is found to only use loop invariant operands
303/// that is safe to hoist, this instruction is called to do the dirty work.
304///
Bill Wendling7c7888b2007-12-08 01:47:01 +0000305void MachineLICM::Hoist(MachineInstr &MI) {
Bill Wendling0fe34c22007-12-08 23:58:46 +0000306 if (!IsLoopInvariantInst(MI)) return;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000307
308 std::vector<MachineBasicBlock*> Preds;
309
310 // Non-back-edge predecessors.
311 FindPredecessors(Preds);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000312
Bill Wendling7c7888b2007-12-08 01:47:01 +0000313 // Either we don't have any predecessors(?!) or we have more than one, which
314 // is forbidden.
315 if (Preds.empty() || Preds.size() != 1) return;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000316
Bill Wendling7c7888b2007-12-08 01:47:01 +0000317 // Check that the predecessor is qualified to take the hoisted
318 // instruction. I.e., there is only one edge from the predecessor, and it's to
319 // the loop header.
320 MachineBasicBlock *MBB = Preds.front();
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000321
Bill Wendling0fe34c22007-12-08 23:58:46 +0000322 // FIXME: We are assuming at first that the basic block coming into this loop
323 // has only one successor. This isn't the case in general because we haven't
324 // broken critical edges or added preheaders.
Bill Wendling7c7888b2007-12-08 01:47:01 +0000325 if (MBB->succ_size() != 1) return;
326 assert(*MBB->succ_begin() == CurLoop->getHeader() &&
327 "The predecessor doesn't feed directly into the loop header!");
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000328
Bill Wendling7c7888b2007-12-08 01:47:01 +0000329 // Now move the instructions to the predecessor.
Bill Wendlinge91b2ef2007-12-11 19:17:04 +0000330 MachineInstr *NewMI = MI.clone();
331 MoveInstToEndOfBlock(MBB, NewMI);
332
333 // Update VRegDefs.
334 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
335 const MachineOperand &MO = NewMI->getOperand(i);
336
337 if (MO.isRegister() && MO.isDef() &&
Bill Wendling3caa4702007-12-11 23:27:51 +0000338 MRegisterInfo::isVirtualRegister(MO.getReg())) {
339 VRegDefs.grow(MO.getReg());
Bill Wendlinge91b2ef2007-12-11 19:17:04 +0000340 VRegDefs[MO.getReg()] = NewMI;
Bill Wendling3caa4702007-12-11 23:27:51 +0000341 }
Bill Wendlinge91b2ef2007-12-11 19:17:04 +0000342 }
Bill Wendling7c7888b2007-12-08 01:47:01 +0000343
344 // Hoisting was successful! Remove bothersome instruction now.
345 MI.getParent()->remove(&MI);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000346 Changed = true;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000347}